coze-bridge 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +108 -103
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var Kg=Object.create;var La=Object.defineProperty;var $g=Object.getOwnPropertyDescriptor;var Vg=Object.getOwnPropertyNames;var Jg=Object.getPrototypeOf,Zg=Object.prototype.hasOwnProperty;var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var rt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Na=(t,e)=>{for(var r in e)La(t,r,{get:e[r],enumerable:!0})},Yg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vg(e))!Zg.call(t,s)&&s!==r&&La(t,s,{get:()=>e[s],enumerable:!(i=$g(e,s))||i.enumerable});return t};var Gt=(t,e,r)=>(r=t!=null?Kg(Jg(t)):{},Yg(e||!t||!t.__esModule?La(r,"default",{value:t,enumerable:!0}):r,t));function Ye(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var lr=rt(()=>{"use strict"});import{createWriteStream as Xg,mkdirSync as Qg,readdirSync as em,unlinkSync as tm}from"node:fs";import{join as Ll}from"node:path";function Nn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function ur(t,e){return`${t}-${e}.log`}function Ma(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function nm(t,e,r){let i=c=>{let[l,u,x]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,x??1)};return Math.floor((i(e)-i(t))/864e5)>r}function ps(t,e,r,i){let s;try{s=em(t)}catch{return}for(let c of s){let l=Ma(c,e);if(l&&nm(l,r,i))try{tm(Ll(t,c))}catch{}}}var ai,Ba=rt(()=>{"use strict";ai=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Nn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{Qg(this.dir,{recursive:!0});let r=Xg(Ll(this.dir,ur(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
- `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&ps(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 rm,mkdirSync as im}from"node:fs";import{join as sm}from"node:path";function Ml(t){let e=t.retentionDays??cm,r=t.clock??(()=>Nn(new Date));ms={bridgeSink:new ai(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:s=>new ai(t.agentLogsDir(s),"agent",{retentionDays:e,clock:r})};let i=r();ps(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])ps(t.agentLogsDir(s),"agent",i,e)}function dm(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Bl(t){Fa=t}function Fl(t){return fr[Fa]<=fr[t]}function zl(t,e){let r=fr[t];return r===void 0?!0:r>=fr[e]}function ws(t){Nl={...t}}function Ul(t){let e=(u,x=2)=>String(u).padStart(x,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",s=Math.abs(r),c=e(Math.floor(s/60)),l=e(s%60);return`${Nn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function it(t,e,r,i,s){try{let c=`${JSON.stringify({ts:Ul(new Date),level:e,module:r,msg:i,...s})}
11
- `;im(t,{recursive:!0}),rm(sm(t,ur("bridge",Nn(new Date))),c)}catch{}}function lm(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function gs(t,e,r,i,s){if(fr[t]<fr[Fa])return;let c=`${JSON.stringify({ts:Ul(new Date),level:t,module:e,msg:r,...Nl,...i})}
12
- `;if(ms){let l=lm(s,i),u=l?dm(ms,l):ms.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?am.write(c):om.write(c)}function j(t,e){return{debug:(r,i)=>gs("debug",t,r,i,e),info:(r,i)=>gs("info",t,r,i,e),warn:(r,i)=>gs("warn",t,r,i,e),error:(r,i)=>gs("error",t,r,i,e),child:r=>j(`${t}.${r}`,e),forAgent:r=>j(t,r)}}var fr,Fa,om,am,Nl,cm,ms,ie=rt(()=>{"use strict";lr();Ba();fr={debug:10,info:20,warn:30,error:40},Fa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),om=process.stdout,am=process.stderr,Nl={},cm=Ye("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ms=null});var k,Ve=rt(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var jl={};Na(jl,{ACP_WRAPPER_NPM_PACKAGES:()=>ys,_resetAcpInstallerForTests:()=>gm,_setBinaryPathCacheForTests:()=>mm,buildAcpSpawn:()=>ci,ensureAcpInstalled:()=>hr,getAcpBinaryPath:()=>bs,pickWhichLine:()=>Ha,probeAcpVersion:()=>pm,resolveAcpCommand:()=>Gl});import{readFileSync as Hl}from"node:fs";import{createRequire as um}from"node:module";import{dirname as fm,resolve as xm}from"node:path";function Ua(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Ha(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(s=>s.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function hm(t){let e=ql.resolve(`${t.npmPackage}/package.json`),r=fm(e),i=JSON.parse(Hl(e,"utf8")),s=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!s)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return xm(r,s)}async function hr(t,e){let r=za[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=xr.get(t);if(i)return i;let s=Ua(t);if(s)return xr.set(t,s),_s.info("acp wrapper overridden by env",{framework:t,path:s}),s;try{let c=hm(r);return xr.set(t,c),_s.info("acp wrapper resolved",{framework:t,binary:r.binary,path:c}),c}catch(c){throw _s.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(c)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
- `),{cause:c})}}async function pm(t){let e=za[t];if(e)try{let r=ql.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Hl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){_s.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function bs(t){return xr.get(t)}function Gl(t,e){if(e)return e;let r=Ua(t);if(r)return r;let i=bs(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 ci(t,e,r){if(e)return{command:e,args:[...r]};let i=Ua(t);if(i)return{command:i,args:[...r]};let s=Gl(t);return{command:process.execPath,args:[s,...r]}}function gm(){xr.clear()}function mm(t,e){xr.set(t,e)}var _s,za,ys,ql,xr,dn=rt(()=>{"use strict";Ve();ie();_s=j("agents.acp-installer"),za={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ys=Object.values(za).filter(t=>t!==void 0).map(t=>t.npmPackage),ql=um(import.meta.url),xr=new Map});import{chmod as _m,mkdir as ym,readFile as bm,rename as Em,rm as vm,writeFile as Sm}from"node:fs/promises";import{dirname as Im}from"node:path";async function ln(t){try{let e=await bm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function un(t,e,r){await ym(Im(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Sm(i,e,{encoding:"utf8",mode:r?.mode}),await Em(i,t),r?.mode!==void 0&&await _m(t,r.mode)}catch(s){throw await vm(i,{force:!0}).catch(()=>{}),s}}async function fn(t,e,r){await un(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var xn=rt(()=>{"use strict"});import{promises as $l,readdirSync as Am}from"node:fs";import{homedir as km}from"node:os";import{sep as Tm,join as Te,resolve as Vl}from"node:path";function Z(t){let e=t??km(),r=Te(e,".coze"),i=Te(r,"bridge"),s=Te(i,"lib"),c=Te(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:s,libEntry:Te(s,"index.js"),binDir:Te(i,"bin"),pidFile:Te(i,"bridge.pid"),portFile:Te(i,"bridge.port"),tokenFile:Te(i,"bridge.token"),patTokenFile:Te(i,"pat-token"),agentEnvFile:Te(i,"agent-env.json"),logFile:Te(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Te(c,"daemon-stdio.log"),installLock:Te(i,"install.lock"),configFile:Te(i,"config.json"),agentsRoot:Te(r,"agents")}}function ze(t,e=Z()){let r=Te(e.agentsRoot,t);return{root:r,config:Te(r,"config.json"),workspace:Te(r,"workspace"),logs:Te(r,"logs")}}function Es(t=Z()){try{return Am(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function di(t,e){let r=await $l.realpath(Vl(t)).catch(()=>null);if(!r)return!1;let i=await $l.realpath(Vl(e)).catch(()=>null);if(!i)return!1;let s=process.platform==="win32"?r.toLowerCase():r,c=process.platform==="win32"?i.toLowerCase():i;return s===c||s.startsWith(c+Tm)}var Ce=rt(()=>{"use strict"});var Ss={};Na(Ss,{AGENT_CONFIG_FILE_MODE:()=>vs,enforceAgentConfigMode:()=>Pm,loadAgentConfig:()=>Re,persistAgentSessions:()=>li,persistAgentSkills:()=>ui,saveAgentConfig:()=>Ue});import{chmod as Cm,stat as Rm}from"node:fs/promises";function Re(t,e){return ln(ze(t,e).config)}function Ue(t,e){return fn(ze(t.agentId,e).config,t,{mode:vs})}async function Pm(t,e){if(process.platform==="win32")return;let r=ze(t,e).config;try{let i=await Rm(r);if(!i.isFile())return;let s=i.mode&511;s!==vs&&(await Cm(r,vs),Jl.warn("agent config mode auto-corrected to 0600",{path:r,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Jl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function li(t,e,r){let i=await Re(t,r);i&&(i.sessions=Object.fromEntries(e),await Ue(i,r))}async function ui(t,e,r){let i=await Re(t,r);i&&(i.skills=e,await Ue(i,r))}var Jl,vs,hn=rt(()=>{"use strict";xn();ie();Ce();Jl=j("agent-config"),vs=384});var ja=ce((tA,Xl)=>{Xl.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 As=ce(eu=>{var Ql={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 Bm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Ql))eu[t]=Bm(Ql[t])});var su=ce((rA,iu)=>{var Fm=xe("fs"),Ne=xe("path"),tu=ja(),zm=As(),Um=typeof process=="object"&&process.platform==="win32",nu=t=>typeof t=="object"&&t!==null,ru=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ve(t){this.sep=Ne.sep,this.fs=Fm,nu(t)&&nu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}iu.exports=ve;ve.prototype.makeDir=function(t){let e=this;function r(i){let s=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){s+=e.sep+c;var l;try{l=e.fs.statSync(s)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw u}if(l&&l.isFile())throw zm.FILE_IN_THE_WAY(`"${s}"`)}})}r(t)};ve.prototype.writeFileTo=function(t,e,r,i){let s=this;if(s.fs.existsSync(t)){if(!r)return!1;var c=s.fs.statSync(t);if(c.isDirectory())return!1}var l=Ne.dirname(t);s.fs.existsSync(l)||s.makeDir(l);var u;try{u=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),u=s.fs.openSync(t,"w",438)}if(u)try{s.fs.writeSync(u,e,0,e.length,0)}finally{s.fs.closeSync(u)}return s.fs.chmodSync(t,i||438),!0};ve.prototype.writeFileToAsync=function(t,e,r,i,s){typeof i=="function"&&(s=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!r)return s(!1);c.fs.stat(t,function(u,x){if(l&&x.isDirectory())return s(!1);var h=Ne.dirname(t);c.fs.exists(h,function(m){m||c.makeDir(h),c.fs.open(t,"w",438,function(w,S){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){s(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){s(!0)})})}):c.fs.chmod(t,i||438,function(){s(!0)})})})})})};ve.prototype.findFiles=function(t){let e=this;function r(i,s,c){typeof s=="boolean"&&(c=s,s=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let x=Ne.join(i,u),h=e.fs.statSync(x);(!s||s.test(x))&&l.push(Ne.normalize(x)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&c&&(l=l.concat(r(x,s,c)))}),l}return r(t,void 0,!0)};ve.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(s,c){if(s)return e(s);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=Ne.join(t,u),r.fs.stat(u,function(x,h){if(x)return e(x);h&&(i.push(Ne.normalize(u)+(h.isDirectory()?r.sep:"")),h.isDirectory()?r.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--l||e(null,i)}):--l||e(null,i))})})})};ve.prototype.getAttributes=function(){};ve.prototype.setAttributes=function(){};ve.crc32update=function(t,e){return ru[(t^e)&255]^t>>>8};ve.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=ve.crc32update(r,t[i++]);return~r>>>0};ve.methodToString=function(t){switch(t){case tu.STORED:return"STORED ("+t+")";case tu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ve.canonical=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.join(".",e)};ve.zipnamefix=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.posix.join(".",e)};ve.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};ve.sanitize=function(t,e){t=Ne.resolve(Ne.normalize(t));for(var r=e.split("/"),i=0,s=r.length;i<s;i++){var c=Ne.normalize(Ne.join(t,r.slice(i,s).join(Ne.sep)));if(c.indexOf(t)===0)return c}return Ne.normalize(Ne.join(t,Ne.basename(e)))};ve.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};ve.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ve.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ve.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};ve.isWin=Um;ve.crcTable=ru});var au=ce((iA,ou)=>{var Hm=xe("path");ou.exports=function(t,{fs:e}){var r=t||"",i=c(),s=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(s=e.statSync(r),i.directory=s.isDirectory(),i.mtime=s.mtime,i.atime=s.atime,i.executable=(73&s.mode)!==0,i.readonly=(128&s.mode)===0,i.hidden=Hm.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var du=ce((sA,cu)=>{cu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var mr=ce((oA,gr)=>{gr.exports=su();gr.exports.Constants=ja();gr.exports.Errors=As();gr.exports.FileAttr=au();gr.exports.decoder=du()});var uu=ce((aA,lu)=>{var pn=mr(),U=pn.Constants;lu.exports=function(){var t=20,e=10,r=0,i=0,s=0,c=0,l=0,u=0,x=0,h=0,m=0,w=0,S=0,y=0,E=0;t|=pn.isWin?2560:768,r|=U.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,T=b=>Math.max(0,b)&65535,C=b=>Math.max(0,b)&255;return s=pn.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return r},set flags(b){r=b},get flags_efs(){return(r&U.FLG_EFS)>0},set flags_efs(b){b?r|=U.FLG_EFS:r&=~U.FLG_EFS},get flags_desc(){return(r&U.FLG_DESC)>0},set flags_desc(b){b?r|=U.FLG_DESC:r&=~U.FLG_DESC},get method(){return i},set method(b){switch(b){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=b},get time(){return pn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=pn.fromDate2DOS(b)},get timeval(){return s},set timeval(b){s=A(b)},get timeHighByte(){return C(s>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return l},set compressedSize(b){l=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return x},set fileNameLength(b){x=b},get extraLength(){return h},set extraLength(b){h=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return w},set diskNumStart(b){w=A(b)},get inAttr(){return S},set inAttr(b){S=A(b)},get attr(){return y},set attr(b){y=A(b)},get fileAttr(){return(y||0)>>16&4095},get offset(){return E},set offset(b){E=A(b)},get encrypted(){return(r&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+x+h+m},get realDataOffset(){return E+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var R=b.slice(E,E+U.LOCHDR);if(R.readUInt32LE(0)!==U.LOCSIG)throw pn.Errors.INVALID_LOC();I.version=R.readUInt16LE(U.LOCVER),I.flags=R.readUInt16LE(U.LOCFLG),I.flags_desc=(I.flags&U.FLG_DESC)>0,I.method=R.readUInt16LE(U.LOCHOW),I.time=R.readUInt32LE(U.LOCTIM),I.crc=R.readUInt32LE(U.LOCCRC),I.compressedSize=R.readUInt32LE(U.LOCSIZ),I.size=R.readUInt32LE(U.LOCLEN),I.fnameLen=R.readUInt16LE(U.LOCNAM),I.extraLen=R.readUInt16LE(U.LOCEXT);let D=E+U.LOCHDR+I.fnameLen,F=D+I.extraLen;return b.slice(D,F)},loadFromBinary:function(b){if(b.length!==U.CENHDR||b.readUInt32LE(0)!==U.CENSIG)throw pn.Errors.INVALID_CEN();t=b.readUInt16LE(U.CENVEM),e=b.readUInt16LE(U.CENVER),r=b.readUInt16LE(U.CENFLG),i=b.readUInt16LE(U.CENHOW),s=b.readUInt32LE(U.CENTIM),c=b.readUInt32LE(U.CENCRC),l=b.readUInt32LE(U.CENSIZ),u=b.readUInt32LE(U.CENLEN),x=b.readUInt16LE(U.CENNAM),h=b.readUInt16LE(U.CENEXT),m=b.readUInt16LE(U.CENCOM),w=b.readUInt16LE(U.CENDSK),S=b.readUInt16LE(U.CENATT),y=b.readUInt32LE(U.CENATX),E=b.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(U.LOCHDR);return b.writeUInt32LE(U.LOCSIG,0),b.writeUInt16LE(e,U.LOCVER),b.writeUInt16LE(r,U.LOCFLG),b.writeUInt16LE(i,U.LOCHOW),b.writeUInt32LE(s,U.LOCTIM),b.writeUInt32LE(c,U.LOCCRC),b.writeUInt32LE(l,U.LOCSIZ),b.writeUInt32LE(u,U.LOCLEN),b.writeUInt16LE(x,U.LOCNAM),b.writeUInt16LE(I.extraLen,U.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(U.CENHDR+x+h+m);return b.writeUInt32LE(U.CENSIG,0),b.writeUInt16LE(t,U.CENVEM),b.writeUInt16LE(e,U.CENVER),b.writeUInt16LE(r,U.CENFLG),b.writeUInt16LE(i,U.CENHOW),b.writeUInt32LE(s,U.CENTIM),b.writeUInt32LE(c,U.CENCRC),b.writeUInt32LE(l,U.CENSIZ),b.writeUInt32LE(u,U.CENLEN),b.writeUInt16LE(x,U.CENNAM),b.writeUInt16LE(h,U.CENEXT),b.writeUInt16LE(m,U.CENCOM),b.writeUInt16LE(w,U.CENDSK),b.writeUInt16LE(S,U.CENATT),b.writeUInt32LE(y,U.CENATX),b.writeUInt32LE(E,U.CENOFF),b},toJSON:function(){let b=function(R){return R+" bytes"};return{made:t,version:e,flags:r,method:pn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(l),size:b(u),fileNameLength:b(x),extraLength:b(h),commentLength:b(m),diskNumStart:w,inAttr:S,attr:y,offset:E,centralHeaderSize:b(U.CENHDR+x+h+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var xu=ce((cA,fu)=>{var wr=mr(),ye=wr.Constants;fu.exports=function(){var t=0,e=0,r=0,i=0,s=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return s},set commentLength(c){s=c},get mainHeaderSize(){return ye.ENDHDR+s},loadFromBinary:function(c){if((c.length!==ye.ENDHDR||c.readUInt32LE(0)!==ye.ENDSIG)&&(c.length<ye.ZIP64HDR||c.readUInt32LE(0)!==ye.ZIP64SIG))throw wr.Errors.INVALID_END();c.readUInt32LE(0)===ye.ENDSIG?(t=c.readUInt16LE(ye.ENDSUB),e=c.readUInt16LE(ye.ENDTOT),r=c.readUInt32LE(ye.ENDSIZ),i=c.readUInt32LE(ye.ENDOFF),s=c.readUInt16LE(ye.ENDCOM)):(t=wr.readBigUInt64LE(c,ye.ZIP64SUB),e=wr.readBigUInt64LE(c,ye.ZIP64TOT),r=wr.readBigUInt64LE(c,ye.ZIP64SIZE),i=wr.readBigUInt64LE(c,ye.ZIP64OFF),s=0)},toBinary:function(){var c=Buffer.alloc(ye.ENDHDR+s);return c.writeUInt32LE(ye.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ye.ENDSUB),c.writeUInt16LE(e,ye.ENDTOT),c.writeUInt32LE(r,ye.ENDSIZ),c.writeUInt32LE(i,ye.ENDOFF),c.writeUInt16LE(s,ye.ENDCOM),c.fill(" ",ye.ENDHDR),c},toJSON:function(){let c=function(l,u){let x=l.toString(16).toUpperCase();for(;x.length<u;)x="0"+x;return"0x"+x};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ka=ce(Wa=>{Wa.EntryHeader=uu();Wa.MainHeader=xu()});var pu=ce((lA,hu)=>{hu.exports=function(t){var e=xe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var s=e.createDeflateRaw(r),c=[],l=0;s.on("data",function(u){c.push(u),l+=u.length}),s.on("end",function(){var u=Buffer.alloc(l),x=0;u.fill(0);for(var h=0;h<c.length;h++){var m=c[h];m.copy(u,x),x+=m.length}i&&i(u)}),s.end(t)}}}});var mu=ce((uA,gu)=>{var qm=+(process.versions?process.versions.node:"").split(".")[0]||0;gu.exports=function(t,e){var r=xe("zlib");let i=qm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(s){var c=r.createInflateRaw(i),l=[],u=0;c.on("data",function(x){l.push(x),u+=x.length}),c.on("end",function(){var x=Buffer.alloc(u),h=0;x.fill(0);for(var m=0;m<l.length;m++){var w=l[m];w.copy(x,h),h+=w.length}s&&s(x)}),c.end(t)}}}});var Eu=ce((fA,bu)=>{"use strict";var{randomFillSync:wu}=xe("crypto"),Gm=As(),jm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),yu=(t,e)=>Math.imul(t,e)>>>0,_u=(t,e)=>jm[(t^e)&255]^t>>>8,fi=()=>typeof wu=="function"?wu(Buffer.alloc(12)):fi.node();fi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ks={genSalt:fi};function Ts(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}Ts.prototype.updateKeys=function(t){let e=this.keys;return e[0]=_u(e[0],t),e[1]+=e[0]&255,e[1]=yu(e[1],134775813)+1,e[2]=_u(e[2],e[1]>>>24),t};Ts.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return yu(t,t^1)>>8&255};function Wm(t){let e=new Ts(t);return function(r){let i=Buffer.alloc(r.length),s=0;for(let c of r)i[s++]=e.updateKeys(c^e.next());return i}}function Km(t){let e=new Ts(t);return function(r,i,s=0){i||(i=Buffer.alloc(r.length));for(let c of r){let l=e.next();i[s++]=c^l,e.updateKeys(c)}return i}}function $m(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Wm(r),s=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==c)throw Gm.WRONG_PASSWORD();return i(t.slice(12))}function Vm(t){Buffer.isBuffer(t)&&t.length>=12?ks.genSalt=function(){return t.slice(0,12)}:t==="node"?ks.genSalt=fi.node:ks.genSalt=fi}function Jm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=Km(r),c=ks.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return s(c,l),s(t,l,12)}bu.exports={decrypt:$m,encrypt:Jm,_salter:Vm}});var vu=ce(Cs=>{Cs.Deflater=pu();Cs.Inflater=mu();Cs.ZipCrypto=Eu()});var Va=ce((hA,Su)=>{var de=mr(),Zm=Ka(),Se=de.Constants,$a=vu();Su.exports=function(t,e){var r=new Zm.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),x=Buffer.alloc(0),h=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:de.decoder;h=w.hasOwnProperty("efs")?w.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(x=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function y(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(de.crc32(b)!==r.localHeader.crc)return!1}else{let R={},D=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(D)==Se.LOCSIG||e.readUInt32LE(D)==Se.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==Se.EXTSIG)R.crc=e.readUInt32LE(D+Se.EXTCRC),R.compressedSize=e.readUInt32LE(D+Se.EXTSIZ),R.size=e.readUInt32LE(D+Se.EXTLEN);else if(e.readUInt16LE(D+12)===19280)R.crc=e.readUInt32LE(D+Se.EXTCRC-4),R.compressedSize=e.readUInt32LE(D+Se.EXTSIZ-4),R.size=e.readUInt32LE(D+Se.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.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),c)return b&&R&&R(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return b&&R&&R(F),F;if(r.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw de.Errors.INVALID_PASS_PARAM();F=$a.ZipCrypto.decrypt(F,r,D)}var B=Buffer.alloc(r.size);switch(r.method){case de.Constants.STORED:if(F.copy(B),y(B))return b&&R&&R(B),B;throw b&&R&&R(B,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var J=new $a.Inflater(F,r.size);if(b)J.inflateAsync(function(V){V.copy(V,0),R&&(y(V)?R(V):R(V,de.Errors.BAD_CRC()))});else{if(J.inflate(B).copy(B,0),!y(B))throw de.Errors.BAD_CRC(`"${w.decode(i)}"`);return B}break;default:throw b&&R&&R(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.Errors.UNKNOWN_METHOD()}}function I(b,R){if((!l||!l.length)&&Buffer.isBuffer(e))return b&&R&&R(S()),S();if(l.length&&!c){var D;switch(r.method){case de.Constants.STORED:return r.compressedSize=r.size,D=Buffer.alloc(l.length),l.copy(D),b&&R&&R(D),D;default:case de.Constants.DEFLATED:var F=new $a.Deflater(l);if(b)F.deflateAsync(function(J){D=Buffer.alloc(J.length),r.compressedSize=J.length,J.copy(D),R&&R(D)});else{var B=F.deflate();return r.compressedSize=B.length,B}F=null;break}}else if(b&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,R){return de.readBigUInt64LE(b,R)}function T(b){try{for(var R=0,D,F,B;R+4<b.length;)D=b.readUInt16LE(R),R+=2,F=b.readUInt16LE(R),R+=2,B=b.slice(R,R+F),R+=F,Se.ID_ZIP64===D&&C(B)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function C(b){var R,D,F,B;b.length>=Se.EF_ZIP64_SCOMP&&(R=A(b,Se.EF_ZIP64_SUNCOMP),r.size===Se.EF_ZIP64_OR_32&&(r.size=R)),b.length>=Se.EF_ZIP64_RHO&&(D=A(b,Se.EF_ZIP64_SCOMP),r.compressedSize===Se.EF_ZIP64_OR_32&&(r.compressedSize=D)),b.length>=Se.EF_ZIP64_DSN&&(F=A(b,Se.EF_ZIP64_RHO),r.offset===Se.EF_ZIP64_OR_32&&(r.offset=F)),b.length>=Se.EF_ZIP64_DSN+4&&(B=b.readUInt32LE(Se.EF_ZIP64_DSN),r.diskNumStart===Se.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=de.toBuffer(b,w.encode);var R=i[i.length-1];c=R===47||R===92,r.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,T(b)},get comment(){return w.decode(s)},set comment(b){if(s=de.toBuffer(b,w.encode),r.commentLength=s.length,s.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var b=w.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){l=de.toBuffer(b,de.decoder.encode),!c&&l.length?(r.size=l.length,r.method=de.Constants.DEFLATED,r.crc=de.crc32(b),r.changed=!0):r.method=de.Constants.STORED},getData:function(b){return r.changed?l:E(!1,null,b)},getDataAsync:function(b,R){r.changed?b(l):E(!0,b,R)},set attr(b){r.attr=b},get attr(){return r.attr},set header(b){r.loadFromBinary(b)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var b=r.centralHeaderToBinary(),R=de.Constants.CENHDR;return i.copy(b,R),R+=i.length,u.copy(b,R),R+=r.extraLength,s.copy(b,R),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=x.length;let R=r.localHeaderToBinary(),D=Buffer.alloc(R.length+i.length+r.extraLocalLength);return R.copy(D,b),b+=R.length,i.copy(D,b),b+=i.length,x.copy(D,b),b+=x.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:r.toJSON(),compressedData:b(e),data:b(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ku=ce((pA,Au)=>{var Iu=Va(),Ym=Ka(),Je=mr();Au.exports=function(t,e){var r=[],i={},s=Buffer.alloc(0),c=new Ym.MainHeader,l=!1,u=null;let x=new Set,h=e,{noSort:m,decoder:w}=h;t?E(h.readEntries):l=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let C=T.split("/");if(C.pop(),!!C.length)for(let b=0;b<C.length;b++){let R=C.slice(0,b+1).join("/")+"/";A.add(R)}}for(let T of A)if(!(T in i)){let C=new Iu(h);C.entryName=T,C.attr=16,C.temporary=!0,r.push(C),i[C.entryName]=C,x.add(C)}}function y(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,T=0;T<r.length;T++){var C=A,b=new Iu(h,t);b.header=t.slice(C,C+=Je.Constants.CENHDR),b.entryName=t.slice(C,C+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(C,C+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(C,C+b.header.commentLength)),A+=b.header.centralHeaderSize,r[T]=b,i[b.entryName]=b}x.clear(),S()}function E(A){var T=t.length-Je.Constants.ENDHDR,C=Math.max(0,T-65535),b=C,R=t.length,D=-1,F=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(C=0),T;T>=b;T--)if(t[T]===80){if(t.readUInt32LE(T)===Je.Constants.ENDSIG){D=T,F=T,R=T+Je.Constants.ENDHDR,b=T-Je.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Je.Constants.END64SIG){b=C;continue}if(t.readUInt32LE(T)===Je.Constants.ZIP64SIG){D=T,R=T+Je.readBigUInt64LE(t,T+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(D==-1)throw Je.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(D,R)),c.commentLength&&(s=t.slice(F+Je.Constants.ENDHDR)),A&&y()}function I(){r.length>1&&!m&&r.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return l||y(),r.filter(A=>!x.has(A))},get comment(){return w.decode(s)},set comment(A){s=Je.toBuffer(A,w.encode),c.commentLength=s.length},getEntryCount:function(){return l?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||y(),i[A]||null},setEntry:function(A){l||y(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,T=!0){l||y();let C=i[A];this.getEntryChildren(C,T).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||y();let T=i[A],C=r.indexOf(T);C>=0&&(r.splice(C,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,T=!0){if(l||y(),typeof A=="object")if(A.isDirectory&&T){let C=[],b=A.entryName;for(let R of r)R.entryName.startsWith(b)&&C.push(R);return C}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){l||y(),I();let A=[],T=[],C=0,b=0;c.size=0,c.offset=0;let R=0;for(let B of this.entries){let J=B.getCompressedData();B.header.offset=b;let V=B.packLocalHeader(),se=V.length+J.length;b+=se,A.push(V),A.push(J);let X=B.packCentralHeader();T.push(X),c.size+=X.length,C+=se+X.length,R++}C+=c.mainHeaderSize,c.offset=b,c.totalEntries=R,b=0;let D=Buffer.alloc(C);for(let B of A)B.copy(D,b),b+=B.length;for(let B of T)B.copy(D,b),b+=B.length;let F=c.toBinary();return s&&s.copy(F,Je.Constants.ENDHDR),F.copy(D,b),t=D,l=!1,D},toAsyncBuffer:function(A,T,C,b){try{l||y(),I();let R=[],D=[],F=0,B=0,J=0;c.size=0,c.offset=0;let V=function(se){if(se.length>0){let X=se.shift(),te=X.entryName+X.extra.toString();C&&C(te),X.getCompressedDataAsync(function(ae){b&&b(te),X.header.offset=B;let P=X.packLocalHeader(),q=P.length+ae.length;B+=q,R.push(P),R.push(ae);let K=X.packCentralHeader();D.push(K),c.size+=K.length,F+=q+K.length,J++,V(se)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=J,B=0;let X=Buffer.alloc(F);R.forEach(function(ae){ae.copy(X,B),B+=ae.length}),D.forEach(function(ae){ae.copy(X,B),B+=ae.length});let te=c.toBinary();s&&s.copy(te,Je.Constants.ENDHDR),te.copy(X,B),t=X,l=!1,A(X)}};V(Array.from(this.entries))}catch(R){T(R)}}}}});var Ru=ce((gA,Cu)=>{var Ee=mr(),be=xe("path"),Xm=Va(),Qm=ku(),Mn=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),Tu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),ew=(...t)=>Ee.findLast(t,e=>typeof e=="function"),tw={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};Cu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),tw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Ee.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new Ee(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ee.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=Ee.Constants.FILE,i.filename=t,r=s.fs.readFileSync(t);else throw Ee.Errors.INVALID_FILENAME();let c=new Qm(r,i),{canonical:l,sanitize:u,zipnamefix:x}=Ee;function h(y){if(y&&c){var E;if(typeof y=="string"&&(E=c.getEntry(be.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(E=c.getEntry(y.entryName)),E)return E}return null}function m(y){let{join:E,normalize:I,sep:A}=be.posix;return E(be.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function w(y){return y instanceof RegExp?(function(E){return function(I){return E.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,E)=>{let I=E.slice(-1);return I=I===s.sep?s.sep:"",be.relative(y,E)+I};return{readFile:function(y,E){var I=h(y);return I&&I.getData(E)||null},childCount:function(y){let E=h(y);if(E)return c.getChildCount(E)},readFileAsync:function(y,E){var I=h(y);I?I.getDataAsync(E):E(null,"getEntry failed for:"+y)},readAsText:function(y,E){var I=h(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(y,E,I){var A=h(y);A?A.getDataAsync(function(T,C){if(C){E(T,C);return}T&&T.length?E(T.toString(I||"utf8")):E("")}):E("")},deleteFile:function(y,E=!0){var I=h(y);I&&c.deleteFile(I.entryName,E)},deleteEntry:function(y){var E=h(y);E&&c.deleteEntry(E.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,E){var I=h(y);I&&(I.comment=E)},getZipEntryComment:function(y){var E=h(y);return E&&E.comment||""},updateFile:function(y,E){var I=h(y);I&&I.setData(E)},addLocalFile:function(y,E,I,A){if(s.fs.existsSync(y)){E=E?m(E):"";let T=be.win32.basename(be.win32.normalize(y));E+=I||T;let C=s.fs.statSync(y),b=C.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);C.isDirectory()&&(E+=s.sep),this.addFile(E,b,A,C)}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,E){y=typeof y=="object"?y:{localPath:y};let I=be.resolve(y.localPath),{comment:A}=y,{zipPath:T,zipName:C}=y,b=this;s.fs.stat(I,function(R,D){if(R)return E(R,!1);T=T?m(T):"";let F=be.win32.basename(be.win32.normalize(I));if(T+=C||F,D.isFile())s.fs.readFile(I,function(B,J){return B?E(B,!1):(b.addFile(T,J,A,D),setImmediate(E,void 0,!0))});else if(D.isDirectory())return T+=s.sep,b.addFile(T,Buffer.alloc(0),A,D),setImmediate(E,void 0,!0)})},addLocalFolder:function(y,E,I){if(I=w(I),E=E?m(E):"",y=be.normalize(y),s.fs.existsSync(y)){let A=s.findFiles(y),T=this;if(A.length)for(let C of A){let b=be.join(E,S(y,C));I(b)&&T.addLocalFile(C,be.dirname(b))}}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,E,I,A){A=w(A),I=I?m(I):"",y=be.normalize(y);var T=this;s.fs.open(y,"r",function(C){if(C&&C.code==="ENOENT")E(void 0,Ee.Errors.FILE_NOT_FOUND(y));else if(C)E(void 0,C);else{var b=s.findFiles(y),R=-1,D=function(){if(R+=1,R<b.length){var F=b[R],B=S(y,F).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(B)?s.fs.stat(F,function(J,V){J&&E(void 0,J),V.isFile()?s.fs.readFile(F,function(se,X){se?E(void 0,se):(T.addFile(I+B,X,"",V),D())}):(T.addFile(I+B+"/",Buffer.alloc(0),"",V),D())}):process.nextTick(()=>{D()})}else E(!0,void 0)};D()}})},addLocalFolderAsync2:function(y,E){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=be.resolve(m(y.localPath));let{zipPath:A,filter:T,namefix:C}=y;T instanceof RegExp?T=(function(D){return function(F){return D.test(F)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?m(A):"",C=="latin1"&&(C=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof C!="function"&&(C=D=>D);let b=D=>be.join(A,C(S(localPath,D))),R=D=>be.win32.basename(be.win32.normalize(C(D)));s.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?E(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):D?E(void 0,D):s.findFilesAsync(localPath,function(F,B){if(F)return E(F);B=B.filter(J=>T(b(J))),B.length||E(void 0,!1),setImmediate(B.reverse().reduce(function(J,V){return function(se,X){if(se||X===!1)return setImmediate(J,se,!1);I.addLocalFileAsync({localPath:V,zipPath:be.dirname(b(V)),zipName:R(V)},J)}},E))})})},addLocalFolderPromise:function(y,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},E),(T,C)=>{T&&A(T),C&&I(this)})})},addFile:function(y,E,I,A){y=x(y);let T=h(y),C=T!=null;C||(T=new Xm(i),T.entryName=y),T.comment=I||"";let b=typeof A=="object"&&A instanceof s.fs.Stats;b&&(T.header.time=A.mtime);var R=T.isDirectory?16:0;let D=T.isDirectory?16384:32768;return b?D|=4095&A.mode:typeof A=="number"?D|=4095&A:D|=T.isDirectory?493:420,R=(R|D<<16)>>>0,T.attr=R,T.setData(E),C||c.setEntry(T),T},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return h(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,E,I,A,T,C){A=Mn(!1,A),T=Mn(!1,T),I=Mn(!0,I),C=Tu(T,C);var b=h(y);if(!b)throw Ee.Errors.NO_ENTRY();var R=l(b.entryName),D=u(E,C&&!b.isDirectory?C:I?R:be.basename(R));if(b.isDirectory){var F=c.getEntryChildren(b);return F.forEach(function(V){if(V.isDirectory)return;var se=V.getData();if(!se)throw Ee.Errors.CANT_EXTRACT_FILE();var X=l(V.entryName),te=u(E,I?X:be.basename(X));let ae=T?V.header.fileAttr:void 0;s.writeFileTo(te,se,A,ae)}),!0}var B=b.getData(c.password);if(!B)throw Ee.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(D)&&!A)throw Ee.Errors.CANT_OVERRIDE();let J=T?y.header.fileAttr:void 0;return s.writeFileTo(D,B,A,J),!0},test:function(y){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,E,I,A){if(I=Mn(!1,I),A=Tu(I,A),E=Mn(!1,E),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(T){var C=u(y,l(T.entryName));if(T.isDirectory){s.makeDir(C);return}var b=T.getData(A);if(!b)throw Ee.Errors.CANT_EXTRACT_FILE();let R=I?T.header.fileAttr:void 0;s.writeFileTo(C,b,E,R);try{s.fs.utimesSync(C,T.header.time,T.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,E,I,A){if(A=ew(E,I,A),I=Mn(!1,I),E=Mn(!1,E),!A)return new Promise((D,F)=>{this.extractAllToAsync(y,E,I,function(B){B?F(B):D(this)})});if(!c){A(Ee.Errors.NO_ZIP());return}y=be.resolve(y);let T=D=>u(y,be.normalize(l(D.entryName))),C=(D,F)=>new Error(D+': "'+F+'"'),b=[],R=[];c.entries.forEach(D=>{D.isDirectory?b.push(D):R.push(D)});for(let D of b){let F=T(D),B=I?D.header.fileAttr:void 0;try{s.makeDir(F),B&&s.fs.chmodSync(F,B),s.fs.utimesSync(F,D.header.time,D.header.time)}catch{A(C("Unable to create folder",F))}}R.reverse().reduce(function(D,F){return function(B){if(B)D(B);else{let J=be.normalize(l(F.entryName)),V=u(y,J);F.getDataAsync(function(se,X){if(X)D(X);else if(!se)D(Ee.Errors.CANT_EXTRACT_FILE());else{let te=I?F.header.fileAttr:void 0;s.writeFileToAsync(V,se,E,te,function(ae){ae||D(C("Unable to write file",V)),s.fs.utimes(V,F.header.time,F.header.time,function(P){P?D(C("Unable to set times",V)):D()})})}})}}},A)()},writeZip:function(y,E){if(arguments.length===1&&typeof y=="function"&&(E=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=s.writeFileTo(y,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((T,C)=>{!y&&i.filename&&(y=i.filename),y||C("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let R=D=>D?T(D):C("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(y,b,I,A,R)},C)})},toBufferPromise:function(){return new Promise((y,E)=>{c.toAsyncBuffer(y,E)})},toBuffer:function(y,E,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,E,I,A),null):c.compressToBuffer()}}}});import{execFile as dy,spawn as ly,spawnSync as Lk}from"node:child_process";import{promisify as uy}from"node:util";function xy(t){if(process.platform!=="win32")return!1;if(Xf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Xf,"").toLowerCase();return fy.has(r)}function Qf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return xy(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function ot(t,e=[],r={}){return ly(t,e,Qf(t,r))}function e0(t,e=[],r={}){return hy(t,e,Qf(t,r))}var fy,Xf,hy,Zt=rt(()=>{"use strict";fy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Xf=/\.(cmd|bat|ps1)$/i;hy=uy(dy)});var Qt=ce((SP,Wx)=>{"use strict";var Gx=["nodebuffer","arraybuffer","fragments"],jx=typeof Blob<"u";jx&&Gx.push("blob");Wx.exports={BINARY_TYPES:Gx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:jx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var es=ce((IP,Uo)=>{"use strict";var{EMPTY_BUFFER:vv}=Qt(),Cd=Buffer[Symbol.species];function Sv(t,e){if(t.length===0)return vv;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let s=0;s<t.length;s++){let c=t[s];r.set(c,i),i+=c.length}return i<e?new Cd(r.buffer,r.byteOffset,i):r}function Kx(t,e,r,i,s){for(let c=0;c<s;c++)r[i+c]=t[c]^e[c&3]}function $x(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Iv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Rd(t){if(Rd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Cd(t):ArrayBuffer.isView(t)?e=new Cd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Rd.readOnly=!1),e}Uo.exports={concat:Sv,mask:Kx,toArrayBuffer:Iv,toBuffer:Rd,unmask:$x};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Uo.exports.mask=function(e,r,i,s,c){c<48?Kx(e,r,i,s,c):t.mask(e,r,i,s,c)},Uo.exports.unmask=function(e,r){e.length<32?$x(e,r):t.unmask(e,r)}}catch{}});var Zx=ce((AP,Jx)=>{"use strict";var Vx=Symbol("kDone"),Pd=Symbol("kRun"),Dd=class{constructor(e){this[Vx]=()=>{this.pending--,this[Pd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Pd]()}[Pd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Vx])}}};Jx.exports=Dd});var $r=ce((kP,eh)=>{"use strict";var ts=xe("zlib"),Yx=es(),Av=Zx(),{kStatusCode:Xx}=Qt(),kv=Buffer[Symbol.species],Tv=Buffer.from([0,0,255,255]),qo=Symbol("permessage-deflate"),en=Symbol("total-length"),Wr=Symbol("callback"),Pn=Symbol("buffers"),Kr=Symbol("error"),Ho,Od=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,!Ho){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new Av(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Wr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(s=>!(r.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>s.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let s=r[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let c=+s;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let c=+s;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=s})}),e}decompress(e,r,i){Ho.add(s=>{this._decompress(e,r,(c,l)=>{s(),i(c,l)})})}compress(e,r,i){Ho.add(s=>{this._compress(e,r,(c,l)=>{s(),i(c,l)})})}_decompress(e,r,i){let s=this._isServer?"client":"server";if(!this._inflate){let c=`${s}_max_window_bits`,l=typeof this.params[c]!="number"?ts.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=ts.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[qo]=this,this._inflate[en]=0,this._inflate[Pn]=[],this._inflate.on("error",Rv),this._inflate.on("data",Qx)}this._inflate[Wr]=i,this._inflate.write(e),r&&this._inflate.write(Tv),this._inflate.flush(()=>{let c=this._inflate[Kr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Yx.concat(this._inflate[Pn],this._inflate[en]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[en]=0,this._inflate[Pn]=[],r&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,r,i){let s=this._isServer?"server":"client";if(!this._deflate){let c=`${s}_max_window_bits`,l=typeof this.params[c]!="number"?ts.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=ts.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[en]=0,this._deflate[Pn]=[],this._deflate.on("data",Cv)}this._deflate[Wr]=i,this._deflate.write(e),this._deflate.flush(ts.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Yx.concat(this._deflate[Pn],this._deflate[en]);r&&(c=new kv(c.buffer,c.byteOffset,c.length-4)),this._deflate[Wr]=null,this._deflate[en]=0,this._deflate[Pn]=[],r&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};eh.exports=Od;function Cv(t){this[Pn].push(t),this[en]+=t.length}function Qx(t){if(this[en]+=t.length,this[qo]._maxPayload<1||this[en]<=this[qo]._maxPayload){this[Pn].push(t);return}this[Kr]=new RangeError("Max payload size exceeded"),this[Kr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Kr][Xx]=1009,this.removeListener("data",Qx),this.reset()}function Rv(t){if(this[qo]._inflate=null,this[Kr]){this[Wr](this[Kr]);return}t[Xx]=1007,this[Wr](t)}});var Vr=ce((TP,Go)=>{"use strict";var{isUtf8:th}=xe("buffer"),{hasBlob:Pv}=Qt(),Dv=[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 Ov(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ld(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Lv(t){return Pv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Go.exports={isBlob:Lv,isValidStatusCode:Ov,isValidUTF8:Ld,tokenChars:Dv};if(th)Go.exports.isValidUTF8=function(t){return t.length<24?Ld(t):th(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Go.exports.isValidUTF8=function(e){return e.length<32?Ld(e):t(e)}}catch{}});var zd=ce((CP,ch)=>{"use strict";var{Writable:Nv}=xe("stream"),nh=$r(),{BINARY_TYPES:Mv,EMPTY_BUFFER:rh,kStatusCode:Bv,kWebSocket:Fv}=Qt(),{concat:Nd,toArrayBuffer:zv,unmask:Uv}=es(),{isValidStatusCode:Hv,isValidUTF8:ih}=Vr(),jo=Buffer[Symbol.species],pt=0,sh=1,oh=2,ah=3,Md=4,Bd=5,Wo=6,Fd=class extends Nv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Mv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=pt}_write(e,r,i){if(this._opcode===8&&this._state==pt)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 jo(i.buffer,i.byteOffset+e,i.length-e),new jo(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=r.length-e;e>=i.length?r.set(this._buffers.shift(),s):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new jo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case pt:this.getInfo(e);break;case sh:this.getPayloadLength16(e);break;case oh:this.getPayloadLength64(e);break;case ah:this.getMask();break;case Md:this.getData(e);break;case Bd:case Wo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let i=(r[0]&64)===64;if(i&&!this._extensions[nh.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=sh:this._payloadLength===127?this._state=oh:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=i*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=ah:this._state=Md}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Md}getData(e){let r=rh;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Uv(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Bd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[nh.extensionName].decompress(e,this._fin,(s,c)=>{if(s)return r(s);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(l);return}this._fragments.push(c)}this.dataMessage(r),this._state===pt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=pt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Nd(i,r):this._binaryType==="arraybuffer"?s=zv(Nd(i,r)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=pt):(this._state=Wo,setImmediate(()=>{this.emit("message",s,!0),this._state=pt,this.startLoop(e)}))}else{let s=Nd(i,r);if(!this._skipUTF8Validation&&!ih(s)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Bd||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=pt):(this._state=Wo,setImmediate(()=>{this.emit("message",s,!1),this._state=pt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,rh),this.end();else{let i=e.readUInt16BE(0);if(!Hv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let s=new jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ih(s)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=pt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=pt):(this._state=Wo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=pt,this.startLoop(r)}))}createError(e,r,i,s,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(l,this.createError),l.code=c,l[Bv]=s,l}};ch.exports=Fd});var qd=ce((PP,uh)=>{"use strict";var{Duplex:RP}=xe("stream"),{randomFillSync:qv}=xe("crypto"),dh=$r(),{EMPTY_BUFFER:Gv,kWebSocket:jv,NOOP:Wv}=Qt(),{isBlob:Jr,isValidStatusCode:Kv}=Vr(),{mask:lh,toBuffer:Qn}=es(),gt=Symbol("kByteLength"),$v=Buffer.alloc(4),Ko=8*1024,er,Zr=Ko,It=0,Vv=1,Jv=2,Ud=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=It,this.onerror=Wv,this[jv]=void 0}static frame(e,r){let i,s=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||$v,r.generateMask?r.generateMask(i):(Zr===Ko&&(er===void 0&&(er=Buffer.alloc(Ko)),qv(er,0,Ko),Zr=0),i[0]=er[Zr++],i[1]=er[Zr++],i[2]=er[Zr++],i[3]=er[Zr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||l)&&r[gt]!==void 0?u=r[gt]:(e=Buffer.from(e),u=e.length):(u=e.length,s=r.mask&&r.readOnly&&!l);let x=u;u>=65536?(c+=8,x=127):u>125&&(c+=2,x=126);let h=Buffer.allocUnsafe(s?u+c:c);return h[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(h[0]|=64),h[1]=x,x===126?h.writeUInt16BE(u,2):x===127&&(h[2]=h[3]=0,h.writeUIntBE(u,4,6)),r.mask?(h[1]|=128,h[c-4]=i[0],h[c-3]=i[1],h[c-2]=i[2],h[c-1]=i[3],l?[h,e]:s?(lh(e,i,h,c,u),[h]):(lh(e,i,e,0,u),[h,e])):[h,e]}close(e,r,i,s){let c;if(e===void 0)c=Gv;else{if(typeof e!="number"||!Kv(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(r);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string"?c.write(r,2):c.set(r,2)}}let l={[gt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,c,!1,l,s]):this.sendFrame(t.frame(c,l),s)}ping(e,r,i){let s,c;if(typeof e=="string"?(s=Buffer.byteLength(e),c=!1):Jr(e)?(s=e.size,c=!1):(e=Qn(e),s=e.length,c=Qn.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[gt]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==It?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,r,i){let s,c;if(typeof e=="string"?(s=Buffer.byteLength(e),c=!1):Jr(e)?(s=e.size,c=!1):(e=Qn(e),s=e.length,c=Qn.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[gt]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==It?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let s=this._extensions[dh.extensionName],c=r.binary?2:1,l=r.compress,u,x;typeof e=="string"?(u=Buffer.byteLength(e),x=!1):Jr(e)?(u=e.size,x=!1):(e=Qn(e),u=e.length,x=Qn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=s._threshold),this._compress=l):(l=!1,c=0),r.fin&&(this._firstFragment=!0);let h={[gt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:x,rsv1:l};Jr(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==It?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,r,i,s){this._bufferedBytes+=i[gt],this._state=Jv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Hd,this,u,s);return}this._bufferedBytes-=i[gt];let l=Qn(c);r?this.dispatch(l,r,i,s):(this._state=It,this.sendFrame(t.frame(l,i),s),this.dequeue())}).catch(c=>{process.nextTick(Zv,this,c,s)})}dispatch(e,r,i,s){if(!r){this.sendFrame(t.frame(e,i),s);return}let c=this._extensions[dh.extensionName];this._bufferedBytes+=i[gt],this._state=Vv,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let x=new Error("The socket was closed while data was being compressed");Hd(this,x,s);return}this._bufferedBytes-=i[gt],this._state=It,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};uh.exports=Ud;function Hd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let s=t._queue[i],c=s[s.length-1];typeof c=="function"&&c(e)}}function Zv(t,e,r){Hd(t,e,r),t.onerror(e)}});var yh=ce((DP,_h)=>{"use strict";var{kForOnEventAttribute:ns,kListener:Gd}=Qt(),fh=Symbol("kCode"),xh=Symbol("kData"),hh=Symbol("kError"),ph=Symbol("kMessage"),gh=Symbol("kReason"),Yr=Symbol("kTarget"),mh=Symbol("kType"),wh=Symbol("kWasClean"),tn=class{constructor(e){this[Yr]=null,this[mh]=e}get target(){return this[Yr]}get type(){return this[mh]}};Object.defineProperty(tn.prototype,"target",{enumerable:!0});Object.defineProperty(tn.prototype,"type",{enumerable:!0});var tr=class extends tn{constructor(e,r={}){super(e),this[fh]=r.code===void 0?0:r.code,this[gh]=r.reason===void 0?"":r.reason,this[wh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[fh]}get reason(){return this[gh]}get wasClean(){return this[wh]}};Object.defineProperty(tr.prototype,"code",{enumerable:!0});Object.defineProperty(tr.prototype,"reason",{enumerable:!0});Object.defineProperty(tr.prototype,"wasClean",{enumerable:!0});var Xr=class extends tn{constructor(e,r={}){super(e),this[hh]=r.error===void 0?null:r.error,this[ph]=r.message===void 0?"":r.message}get error(){return this[hh]}get message(){return this[ph]}};Object.defineProperty(Xr.prototype,"error",{enumerable:!0});Object.defineProperty(Xr.prototype,"message",{enumerable:!0});var rs=class extends tn{constructor(e,r={}){super(e),this[xh]=r.data===void 0?null:r.data}get data(){return this[xh]}};Object.defineProperty(rs.prototype,"data",{enumerable:!0});var Yv={addEventListener(t,e,r={}){for(let s of this.listeners(t))if(!r[ns]&&s[Gd]===e&&!s[ns])return;let i;if(t==="message")i=function(c,l){let u=new rs("message",{data:l?c:c.toString()});u[Yr]=this,$o(e,this,u)};else if(t==="close")i=function(c,l){let u=new tr("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Yr]=this,$o(e,this,u)};else if(t==="error")i=function(c){let l=new Xr("error",{error:c,message:c.message});l[Yr]=this,$o(e,this,l)};else if(t==="open")i=function(){let c=new tn("open");c[Yr]=this,$o(e,this,c)};else return;i[ns]=!!r[ns],i[Gd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Gd]===e&&!r[ns]){this.removeListener(t,r);break}}};_h.exports={CloseEvent:tr,ErrorEvent:Xr,Event:tn,EventTarget:Yv,MessageEvent:rs};function $o(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Vo=ce((OP,bh)=>{"use strict";var{tokenChars:is}=Vr();function zt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Xv(t){let e=Object.create(null),r=Object.create(null),i=!1,s=!1,c=!1,l,u,x=-1,h=-1,m=-1,w=0;for(;w<t.length;w++)if(h=t.charCodeAt(w),l===void 0)if(m===-1&&is[h]===1)x===-1&&(x=w);else if(w!==0&&(h===32||h===9))m===-1&&x!==-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let y=t.slice(x,m);h===44?(zt(e,y,r),r=Object.create(null)):l=y,x=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&is[h]===1)x===-1&&(x=w);else if(h===32||h===9)m===-1&&x!==-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w),zt(r,t.slice(x,m),!0),h===44&&(zt(e,l,r),r=Object.create(null),l=void 0),x=m=-1}else if(h===61&&x!==-1&&m===-1)u=t.slice(x,w),x=m=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(s){if(is[h]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);x===-1?x=w:i||(i=!0),s=!1}else if(c)if(is[h]===1)x===-1&&(x=w);else if(h===34&&x!==-1)c=!1,m=w;else if(h===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(h===34&&t.charCodeAt(w-1)===61)c=!0;else if(m===-1&&is[h]===1)x===-1&&(x=w);else if(x!==-1&&(h===32||h===9))m===-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let y=t.slice(x,m);i&&(y=y.replace(/\\/g,""),i=!1),zt(r,u,y),h===44&&(zt(e,l,r),r=Object.create(null),l=void 0),u=void 0,x=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(x===-1||c||h===32||h===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=w);let S=t.slice(x,m);return l===void 0?zt(e,S,r):(u===void 0?zt(r,S,!0):i?zt(r,u,S.replace(/\\/g,"")):zt(r,u,S),zt(e,l,r)),e}function Qv(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(s=>{let c=i[s];return Array.isArray(c)||(c=[c]),c.map(l=>l===!0?s:`${s}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bh.exports={format:Qv,parse:Xv}});var Xo=ce((MP,Oh)=>{"use strict";var eS=xe("events"),tS=xe("https"),nS=xe("http"),Sh=xe("net"),rS=xe("tls"),{randomBytes:iS,createHash:sS}=xe("crypto"),{Duplex:LP,Readable:NP}=xe("stream"),{URL:jd}=xe("url"),Dn=$r(),oS=zd(),aS=qd(),{isBlob:cS}=Vr(),{BINARY_TYPES:Eh,CLOSE_TIMEOUT:dS,EMPTY_BUFFER:Jo,GUID:lS,kForOnEventAttribute:Wd,kListener:uS,kStatusCode:fS,kWebSocket:We,NOOP:Ih}=Qt(),{EventTarget:{addEventListener:xS,removeEventListener:hS}}=yh(),{format:pS,parse:gS}=Vo(),{toBuffer:mS}=es(),Ah=Symbol("kAborted"),Kd=[8,13],nn=["CONNECTING","OPEN","CLOSING","CLOSED"],wS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends eS{constructor(e,r,i){super(),this._binaryType=Eh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Jo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),kh(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Eh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,i){let s=new oS({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new aS(e,this._extensions,i.generateMask);this._receiver=s,this._sender=c,this._socket=e,s[We]=this,c[We]=this,e[We]=this,s.on("conclude",bS),s.on("drain",ES),s.on("error",vS),s.on("message",SS),s.on("ping",IS),s.on("pong",AS),c.onerror=kS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Rh),e.on("data",Yo),e.on("end",Ph),e.on("error",Dh),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Dn.extensionName]&&this._extensions[Dn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){lt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ch(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Jo,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Jo,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Dn.extensionName]||(s.compress=!1),this._sender.send(e||Jo,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){lt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Wd])return e[uS];return null},set(e){for(let r of this.listeners(t))if(r[Wd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Wd]:!0})}})});we.prototype.addEventListener=xS;we.prototype.removeEventListener=hS;Oh.exports=we;function kh(t,e,r,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:dS,protocolVersion:Kd[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=s.autoPong,t._closeTimeout=s.closeTimeout,!Kd.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Kd.join(", ")})`);let c;if(e instanceof jd)c=e;else try{c=new jd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let l=c.protocol==="wss:",u=c.protocol==="ws+unix:",x;if(c.protocol!=="ws:"&&!l&&!u?x=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?x="The URL's pathname is empty":c.hash&&(x="The URL contains a fragment identifier"),x){let I=new SyntaxError(x);if(t._redirects===0)throw I;Zo(t,I);return}let h=l?443:80,m=iS(16).toString("base64"),w=l?tS.request:nS.request,S=new Set,y;if(s.createConnection=s.createConnection||(l?yS:_S),s.defaultPort=s.defaultPort||h,s.port=c.port||h,s.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},s.path=c.pathname+c.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(y=new Dn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=pS({[Dn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!wS.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(c.username||c.password)&&(s.auth=`${c.username}:${c.password}`),u){let I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let E;if(s.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?s.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),E=t._req=w(s),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(s);s.timeout&&E.on("timeout",()=>{lt(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Ah]||(E=t._req=null,Zo(t,I))}),E.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&s.followRedirects&&T>=300&&T<400){if(++t._redirects>s.maxRedirects){lt(t,E,"Maximum redirects exceeded");return}E.abort();let C;try{C=new jd(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);Zo(t,R);return}kh(t,C,r,i)}else t.emit("unexpected-response",E,I)||lt(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==we.CONNECTING)return;E=t._req=null;let C=I.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){lt(t,A,"Invalid Upgrade header");return}let b=sS("sha1").update(m+lS).digest("base64");if(I.headers["sec-websocket-accept"]!==b){lt(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],D;if(R!==void 0?S.size?S.has(R)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":S.size&&(D="Server sent no subprotocol"),D){lt(t,A,D);return}R&&(t._protocol=R);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!y){lt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=gS(F)}catch{lt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(B);if(J.length!==1||J[0]!==Dn.extensionName){lt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(B[Dn.extensionName])}catch{lt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=y}t.setSocket(A,T,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(E,t):E.end()}function Zo(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function _S(t){return t.path=t.socketPath,Sh.connect(t)}function yS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Sh.isIP(t.host)?"":t.host),rS.connect(t)}function lt(t,e,r){t._readyState=we.CLOSING;let i=new Error(r);Error.captureStackTrace(i,lt),e.setHeader?(e[Ah]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function $d(t,e,r){if(e){let i=cS(e)?e.size:mS(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${nn[t.readyState]})`);process.nextTick(r,i)}}function bS(t,e){let r=this[We];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[We]!==void 0&&(r._socket.removeListener("data",Yo),process.nextTick(Th,r._socket),t===1005?r.close():r.close(t,e))}function ES(){let t=this[We];t.isPaused||t._socket.resume()}function vS(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",Yo),process.nextTick(Th,e._socket),e.close(t[fS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vh(){this[We].emitClose()}function SS(t,e){this[We].emit("message",t,e)}function IS(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,Ih),e.emit("ping",t)}function AS(t){this[We].emit("pong",t)}function Th(t){t.resume()}function kS(t){let e=this[We];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,Ch(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ch(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Rh(){let t=this[We];if(this.removeListener("close",Rh),this.removeListener("data",Yo),this.removeListener("end",Ph),t._readyState=we.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vh),t._receiver.on("finish",vh))}function Yo(t){this[We]._receiver.write(t)||this.pause()}function Ph(){let t=this[We];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function Dh(){let t=this[We];this.removeListener("error",Dh),this.on("error",Ih),t&&(t._readyState=we.CLOSING,this.destroy())}});var Bh=ce((FP,Mh)=>{"use strict";var BP=Xo(),{Duplex:TS}=xe("stream");function Lh(t){t.emit("close")}function CS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nh(t){this.removeListener("error",Nh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function RS(t,e){let r=!0,i=new TS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,l){let u=!l&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,c){if(t.readyState===t.CLOSED){c(s),process.nextTick(Lh,i);return}let l=!1;t.once("error",function(x){l=!0,c(x)}),t.once("close",function(){l||c(s),process.nextTick(Lh,i)}),r&&t.terminate()},i._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(s,c,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(s,c,l)});return}t.send(s,l)},i.on("end",CS),i.on("error",Nh),i}Mh.exports=RS});var Vd=ce((zP,Fh)=>{"use strict";var{tokenChars:PS}=Vr();function DS(t){let e=new Set,r=-1,i=-1,s=0;for(s;s<t.length;s++){let l=t.charCodeAt(s);if(i===-1&&PS[l]===1)r===-1&&(r=s);else if(s!==0&&(l===32||l===9))i===-1&&r!==-1&&(i=s);else if(l===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,s);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Fh.exports={parse:DS}});var Wh=ce((HP,jh)=>{"use strict";var OS=xe("events"),Qo=xe("http"),{Duplex:UP}=xe("stream"),{createHash:LS}=xe("crypto"),zh=Vo(),nr=$r(),NS=Vd(),MS=Xo(),{CLOSE_TIMEOUT:BS,GUID:FS,kWebSocket:zS}=Qt(),US=/^[+/0-9A-Za-z]{22}==$/,Uh=0,Hh=1,Gh=2,Jd=class extends OS{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:BS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:MS,...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=Qo.createServer((i,s)=>{let c=Qo.STATUS_CODES[426];s.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),s.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=HS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,c,l)=>{this.handleUpgrade(s,c,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Uh}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===Gh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ss,this);return}if(e&&this.once("close",e),this._state!==Hh)if(this._state=Hh,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ss,this):process.nextTick(ss,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ss(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,s){r.on("error",qh);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){rr(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){rr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!US.test(c)){rr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){rr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){os(r,400);return}let x=e.headers["sec-websocket-protocol"],h=new Set;if(x!==void 0)try{h=NS.parse(x)}catch{rr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&m!==void 0){let S=new nr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=zh.parse(m);y[nr.extensionName]&&(S.accept(y[nr.extensionName]),w[nr.extensionName]=S)}catch{rr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(y,E,I,A)=>{if(!y)return os(r,E||401,I,A);this.completeUpgrade(w,c,h,e,r,i,s)});return}if(!this.options.verifyClient(S))return os(r,401)}this.completeUpgrade(w,c,h,e,r,i,s)}completeUpgrade(e,r,i,s,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[zS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Uh)return os(c,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${LS("sha1").update(r+FS).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;w&&(h.push(`Sec-WebSocket-Protocol: ${w}`),m._protocol=w)}if(e[nr.extensionName]){let w=e[nr.extensionName].params,S=zh.format({[nr.extensionName]:[w]});h.push(`Sec-WebSocket-Extensions: ${S}`),m._extensions=e}this.emit("headers",h,s),c.write(h.concat(`\r
8
+ var am=Object.create;var ja=Object.defineProperty;var cm=Object.getOwnPropertyDescriptor;var dm=Object.getOwnPropertyNames;var lm=Object.getPrototypeOf,um=Object.prototype.hasOwnProperty;var me=(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 st=(t,e)=>()=>(t&&(e=t(t=0)),e);var ue=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ka=(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 s of dm(e))!um.call(t,s)&&s!==n&&ja(t,s,{get:()=>e[s],enumerable:!(i=cm(e,s))||i.enumerable});return t};var Wt=(t,e,n)=>(n=t!=null?am(lm(t)):{},fm(e||!t||!t.__esModule?ja(n,"default",{value:t,enumerable:!0}):n,t));function Qe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var xr=st(()=>{"use strict"});import{createWriteStream as hm,mkdirSync as xm,readdirSync as pm,unlinkSync as gm}from"node:fs";import{join as ql}from"node:path";function Bn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function pr(t,e){return`${t}-${e}.log`}function Wa(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function mm(t,e,n){let i=a=>{let[d,u,h]=a.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>n}function Es(t,e,n,i){let s;try{s=pm(t)}catch{return}for(let a of s){let d=Wa(a,e);if(d&&mm(d,n,i))try{gm(ql(t,a))}catch{}}}var hi,$a=st(()=>{"use strict";hi=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Bn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let n=this.clock();n!==this.currentDate&&this.rotate(n),this.stream?.write(e)}rotate(e){this.stream?.end();try{xm(this.dir,{recursive:!0});let n=hm(ql(this.dir,pr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
+ `)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&Es(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as wm,mkdirSync as _m}from"node:fs";import{join as ym}from"node:path";function Kl(t){let e=t.retentionDays??vm,n=t.clock??(()=>Bn(new Date));Ss={bridgeSink:new hi(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:s=>new hi(t.agentLogsDir(s),"agent",{retentionDays:e,clock:n})};let i=n();Es(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])Es(t.agentLogsDir(s),"agent",i,e)}function Sm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Wl(t){Va=t}function $l(t){return gr[Va]<=gr[t]}function Vl(t,e){let n=gr[t];return n===void 0?!0:n>=gr[e]}function Is(t){jl={...t}}function Zl(t){let e=(u,h=2)=>String(u).padStart(h,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",s=Math.abs(n),a=e(Math.floor(s/60)),d=e(s%60);return`${Bn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function ot(t,e,n,i,s){try{let a=`${JSON.stringify({ts:Zl(new Date),level:e,module:n,msg:i,...s})}
11
+ `;_m(t,{recursive:!0}),wm(ym(t,pr("bridge",Bn(new Date))),a)}catch{}}function Im(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function vs(t,e,n,i,s){if(gr[t]<gr[Va])return;let a=`${JSON.stringify({ts:Zl(new Date),level:t,module:e,msg:n,...jl,...i})}
12
+ `;if(Ss){let d=Im(s,i),u=d?Sm(Ss,d):Ss.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?Em.write(a):bm.write(a)}function K(t,e){return{debug:(n,i)=>vs("debug",t,n,i,e),info:(n,i)=>vs("info",t,n,i,e),warn:(n,i)=>vs("warn",t,n,i,e),error:(n,i)=>vs("error",t,n,i,e),child:n=>K(`${t}.${n}`,e),forAgent:n=>K(t,n)}}var gr,Va,bm,Em,jl,vm,Ss,ne=st(()=>{"use strict";xr();$a();gr={debug:10,info:20,warn:30,error:40},Va=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),bm=process.stdout,Em=process.stderr,jl={},vm=Qe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Ss=null});var k,Ye=st(()=>{"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 Ql={};Ka(Ql,{ACP_WRAPPER_NPM_PACKAGES:()=>ks,_resetAcpInstallerForTests:()=>Cm,_setBinaryPathCacheForTests:()=>Rm,buildAcpSpawn:()=>xi,ensureAcpInstalled:()=>wr,getAcpBinaryPath:()=>Ts,pickWhichLine:()=>Ya,probeAcpVersion:()=>Dm,resolveAcpCommand:()=>Xl});import{readFileSync as Jl}from"node:fs";import{createRequire as Am}from"node:module";import{dirname as km,resolve as Tm}from"node:path";function Ja(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Ya(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(s=>s.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function Pm(t){let e=Yl.resolve(`${t.npmPackage}/package.json`),n=km(e),i=JSON.parse(Jl(e,"utf8")),s=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!s)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return Tm(n,s)}async function wr(t,e){let n=Za[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=mr.get(t);if(i)return i;let s=Ja(t);if(s)return mr.set(t,s),As.info("acp wrapper overridden by env",{framework:t,path:s}),s;try{let a=Pm(n);return mr.set(t,a),As.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw As.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 Dm(t){let e=Za[t];if(e)try{let n=Yl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Jl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){As.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Ts(t){return mr.get(t)}function Xl(t,e){if(e)return e;let n=Ja(t);if(n)return n;let i=Ts(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 xi(t,e,n){if(e)return{command:e,args:[...n]};let i=Ja(t);if(i)return{command:i,args:[...n]};let s=Xl(t);return{command:process.execPath,args:[s,...n]}}function Cm(){mr.clear()}function Rm(t,e){mr.set(t,e)}var As,Za,ks,Yl,mr,xn=st(()=>{"use strict";Ye();ne();As=K("agents.acp-installer"),Za={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ks=Object.values(Za).filter(t=>t!==void 0).map(t=>t.npmPackage),Yl=Am(import.meta.url),mr=new Map});import{chmod as Lm,mkdir as Nm,readFile as Mm,rename as Bm,rm as Fm,writeFile as zm}from"node:fs/promises";import{dirname as Um}from"node:path";async function pn(t){try{let e=await Mm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function xt(t,e,n){await Nm(Um(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await zm(i,e,{encoding:"utf8",mode:n?.mode}),await Bm(i,t),n?.mode!==void 0&&await Lm(t,n.mode)}catch(s){throw await Fm(i,{force:!0}).catch(()=>{}),s}}async function gn(t,e,n){await xt(t,`${JSON.stringify(e,null,2)}
14
+ `,n)}var $t=st(()=>{"use strict"});import{promises as nu,readdirSync as Hm}from"node:fs";import{homedir as Gm}from"node:os";import{sep as qm,join as Le,resolve as ru}from"node:path";function J(t){let e=t??Gm(),n=Le(e,".coze"),i=Le(n,"bridge"),s=Le(i,"lib"),a=Le(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:s,libEntry:Le(s,"index.js"),binDir:Le(i,"bin"),pidFile:Le(i,"bridge.pid"),portFile:Le(i,"bridge.port"),tokenFile:Le(i,"bridge.token"),patTokenFile:Le(i,"pat-token"),agentEnvFile:Le(i,"agent-env.json"),logFile:Le(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Le(a,"daemon-stdio.log"),installLock:Le(i,"install.lock"),configFile:Le(i,"config.json"),agentsRoot:Le(n,"agents")}}function Ne(t,e=J()){let n=Le(e.agentsRoot,t);return{root:n,config:Le(n,"config.json"),workspace:Le(n,"workspace"),logs:Le(n,"logs")}}function Ps(t=J()){try{return Hm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function pi(t,e){let n=await nu.realpath(ru(t)).catch(()=>null);if(!n)return!1;let i=await nu.realpath(ru(e)).catch(()=>null);if(!i)return!1;let s=process.platform==="win32"?n.toLowerCase():n,a=process.platform==="win32"?i.toLowerCase():i;return s===a||s.startsWith(a+qm)}var Ce=st(()=>{"use strict"});var Cs={};Ka(Cs,{AGENT_CONFIG_FILE_MODE:()=>Ds,enforceAgentConfigMode:()=>Wm,loadAgentConfig:()=>ke,persistAgentSessions:()=>gi,persistAgentSkills:()=>mi,saveAgentConfig:()=>je});import{chmod as jm,stat as Km}from"node:fs/promises";function ke(t,e){return pn(Ne(t,e).config)}function je(t,e){return gn(Ne(t.agentId,e).config,t,{mode:Ds})}async function Wm(t,e){if(process.platform==="win32")return;let n=Ne(t,e).config;try{let i=await Km(n);if(!i.isFile())return;let s=i.mode&511;s!==Ds&&(await jm(n,Ds),iu.warn("agent config mode auto-corrected to 0600",{path:n,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;iu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function gi(t,e,n){let i=await ke(t,n);i&&(i.sessions=Object.fromEntries(e),await je(i,n))}async function mi(t,e,n){let i=await ke(t,n);i&&(i.skills=e,await je(i,n))}var iu,Ds,Vt=st(()=>{"use strict";$t();ne();Ce();iu=K("agent-config"),Ds=384});var ec=ue((v2,au)=>{au.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 Os=ue(du=>{var cu={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Xm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(cu))du[t]=Xm(cu[t])});var xu=ue((I2,hu)=>{var Qm=me("fs"),Ue=me("path"),lu=ec(),ew=Os(),tw=typeof process=="object"&&process.platform==="win32",uu=t=>typeof t=="object"&&t!==null,fu=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 Te(t){this.sep=Ue.sep,this.fs=Qm,uu(t)&&uu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}hu.exports=Te;Te.prototype.makeDir=function(t){let e=this;function n(i){let s=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){s+=e.sep+a;var d;try{d=e.fs.statSync(s)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw u}if(d&&d.isFile())throw ew.FILE_IN_THE_WAY(`"${s}"`)}})}n(t)};Te.prototype.writeFileTo=function(t,e,n,i){let s=this;if(s.fs.existsSync(t)){if(!n)return!1;var a=s.fs.statSync(t);if(a.isDirectory())return!1}var d=Ue.dirname(t);s.fs.existsSync(d)||s.makeDir(d);var u;try{u=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),u=s.fs.openSync(t,"w",438)}if(u)try{s.fs.writeSync(u,e,0,e.length,0)}finally{s.fs.closeSync(u)}return s.fs.chmodSync(t,i||438),!0};Te.prototype.writeFileToAsync=function(t,e,n,i,s){typeof i=="function"&&(s=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!n)return s(!1);a.fs.stat(t,function(u,h){if(d&&h.isDirectory())return s(!1);var x=Ue.dirname(t);a.fs.exists(x,function(g){g||a.makeDir(x),a.fs.open(t,"w",438,function(w,v){w?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(){s(!0)})})})})}):v?a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){s(!0)})})}):a.fs.chmod(t,i||438,function(){s(!0)})})})})})};Te.prototype.findFiles=function(t){let e=this;function n(i,s,a){typeof s=="boolean"&&(a=s,s=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Ue.join(i,u),x=e.fs.statSync(h);(!s||s.test(h))&&d.push(Ue.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(h,s,a)))}),d}return n(t,void 0,!0)};Te.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(s,a){if(s)return e(s);let d=a.length;if(!d)return e(null,i);a.forEach(function(u){u=Ue.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Ue.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(g,w){if(g)return e(g);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};Te.prototype.getAttributes=function(){};Te.prototype.setAttributes=function(){};Te.crc32update=function(t,e){return fu[(t^e)&255]^t>>>8};Te.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Te.crc32update(n,t[i++]);return~n>>>0};Te.methodToString=function(t){switch(t){case lu.STORED:return"STORED ("+t+")";case lu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Te.canonical=function(t){if(!t)return"";let e=Ue.posix.normalize("/"+t.split("\\").join("/"));return Ue.join(".",e)};Te.zipnamefix=function(t){if(!t)return"";let e=Ue.posix.normalize("/"+t.split("\\").join("/"));return Ue.posix.join(".",e)};Te.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]};Te.sanitize=function(t,e){t=Ue.resolve(Ue.normalize(t));for(var n=e.split("/"),i=0,s=n.length;i<s;i++){var a=Ue.normalize(Ue.join(t,n.slice(i,s).join(Ue.sep)));if(a.indexOf(t)===0)return a}return Ue.normalize(Ue.join(t,Ue.basename(e)))};Te.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Te.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Te.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)};Te.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};Te.isWin=tw;Te.crcTable=fu});var gu=ue((A2,pu)=>{var nw=me("path");pu.exports=function(t,{fs:e}){var n=t||"",i=a(),s=null;function a(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(s=e.statSync(n),i.directory=s.isDirectory(),i.mtime=s.mtime,i.atime=s.atime,i.executable=(73&s.mode)!==0,i.readonly=(128&s.mode)===0,i.hidden=nw.basename(n)[0]==="."):console.warn("Invalid path: "+n),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:n,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var wu=ue((k2,mu)=>{mu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var br=ue((T2,yr)=>{yr.exports=xu();yr.exports.Constants=ec();yr.exports.Errors=Os();yr.exports.FileAttr=gu();yr.exports.decoder=wu()});var yu=ue((P2,_u)=>{var mn=br(),j=mn.Constants;_u.exports=function(){var t=20,e=10,n=0,i=0,s=0,a=0,d=0,u=0,h=0,x=0,g=0,w=0,v=0,_=0,E=0;t|=mn.isWin?2560:768,n|=j.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,T=b=>Math.max(0,b)&65535,O=b=>Math.max(0,b)&255;return s=mn.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&j.FLG_EFS)>0},set flags_efs(b){b?n|=j.FLG_EFS:n&=~j.FLG_EFS},get flags_desc(){return(n&j.FLG_DESC)>0},set flags_desc(b){b?n|=j.FLG_DESC:n&=~j.FLG_DESC},get method(){return i},set method(b){switch(b){case j.STORED:this.version=10;case j.DEFLATED:default:this.version=20}i=b},get time(){return mn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=mn.fromDate2DOS(b)},get timeval(){return s},set timeval(b){s=A(b)},get timeHighByte(){return O(s>>>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 h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return g},set commentLength(b){g=b},get diskNumStart(){return w},set diskNumStart(b){w=A(b)},get inAttr(){return v},set inAttr(b){v=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&j.FLG_ENC)===j.FLG_ENC},get centralHeaderSize(){return j.CENHDR+h+x+g},get realDataOffset(){return E+j.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var L=b.slice(E,E+j.LOCHDR);if(L.readUInt32LE(0)!==j.LOCSIG)throw mn.Errors.INVALID_LOC();I.version=L.readUInt16LE(j.LOCVER),I.flags=L.readUInt16LE(j.LOCFLG),I.flags_desc=(I.flags&j.FLG_DESC)>0,I.method=L.readUInt16LE(j.LOCHOW),I.time=L.readUInt32LE(j.LOCTIM),I.crc=L.readUInt32LE(j.LOCCRC),I.compressedSize=L.readUInt32LE(j.LOCSIZ),I.size=L.readUInt32LE(j.LOCLEN),I.fnameLen=L.readUInt16LE(j.LOCNAM),I.extraLen=L.readUInt16LE(j.LOCEXT);let N=E+j.LOCHDR+I.fnameLen,H=N+I.extraLen;return b.slice(N,H)},loadFromBinary:function(b){if(b.length!==j.CENHDR||b.readUInt32LE(0)!==j.CENSIG)throw mn.Errors.INVALID_CEN();t=b.readUInt16LE(j.CENVEM),e=b.readUInt16LE(j.CENVER),n=b.readUInt16LE(j.CENFLG),i=b.readUInt16LE(j.CENHOW),s=b.readUInt32LE(j.CENTIM),a=b.readUInt32LE(j.CENCRC),d=b.readUInt32LE(j.CENSIZ),u=b.readUInt32LE(j.CENLEN),h=b.readUInt16LE(j.CENNAM),x=b.readUInt16LE(j.CENEXT),g=b.readUInt16LE(j.CENCOM),w=b.readUInt16LE(j.CENDSK),v=b.readUInt16LE(j.CENATT),_=b.readUInt32LE(j.CENATX),E=b.readUInt32LE(j.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(j.LOCHDR);return b.writeUInt32LE(j.LOCSIG,0),b.writeUInt16LE(e,j.LOCVER),b.writeUInt16LE(n,j.LOCFLG),b.writeUInt16LE(i,j.LOCHOW),b.writeUInt32LE(s,j.LOCTIM),b.writeUInt32LE(a,j.LOCCRC),b.writeUInt32LE(d,j.LOCSIZ),b.writeUInt32LE(u,j.LOCLEN),b.writeUInt16LE(h,j.LOCNAM),b.writeUInt16LE(I.extraLen,j.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(j.CENHDR+h+x+g);return b.writeUInt32LE(j.CENSIG,0),b.writeUInt16LE(t,j.CENVEM),b.writeUInt16LE(e,j.CENVER),b.writeUInt16LE(n,j.CENFLG),b.writeUInt16LE(i,j.CENHOW),b.writeUInt32LE(s,j.CENTIM),b.writeUInt32LE(a,j.CENCRC),b.writeUInt32LE(d,j.CENSIZ),b.writeUInt32LE(u,j.CENLEN),b.writeUInt16LE(h,j.CENNAM),b.writeUInt16LE(x,j.CENEXT),b.writeUInt16LE(g,j.CENCOM),b.writeUInt16LE(w,j.CENDSK),b.writeUInt16LE(v,j.CENATT),b.writeUInt32LE(_,j.CENATX),b.writeUInt32LE(E,j.CENOFF),b},toJSON:function(){let b=function(L){return L+" bytes"};return{made:t,version:e,flags:n,method:mn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(g),diskNumStart:w,inAttr:v,attr:_,offset:E,centralHeaderSize:b(j.CENHDR+h+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Eu=ue((D2,bu)=>{var Er=br(),Se=Er.Constants;bu.exports=function(){var t=0,e=0,n=0,i=0,s=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 s},set commentLength(a){s=a},get mainHeaderSize(){return Se.ENDHDR+s},loadFromBinary:function(a){if((a.length!==Se.ENDHDR||a.readUInt32LE(0)!==Se.ENDSIG)&&(a.length<Se.ZIP64HDR||a.readUInt32LE(0)!==Se.ZIP64SIG))throw Er.Errors.INVALID_END();a.readUInt32LE(0)===Se.ENDSIG?(t=a.readUInt16LE(Se.ENDSUB),e=a.readUInt16LE(Se.ENDTOT),n=a.readUInt32LE(Se.ENDSIZ),i=a.readUInt32LE(Se.ENDOFF),s=a.readUInt16LE(Se.ENDCOM)):(t=Er.readBigUInt64LE(a,Se.ZIP64SUB),e=Er.readBigUInt64LE(a,Se.ZIP64TOT),n=Er.readBigUInt64LE(a,Se.ZIP64SIZE),i=Er.readBigUInt64LE(a,Se.ZIP64OFF),s=0)},toBinary:function(){var a=Buffer.alloc(Se.ENDHDR+s);return a.writeUInt32LE(Se.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,Se.ENDSUB),a.writeUInt16LE(e,Se.ENDTOT),a.writeUInt32LE(n,Se.ENDSIZ),a.writeUInt32LE(i,Se.ENDOFF),a.writeUInt16LE(s,Se.ENDCOM),a.fill(" ",Se.ENDHDR),a},toJSON:function(){let a=function(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:a(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var nc=ue(tc=>{tc.EntryHeader=yu();tc.MainHeader=Eu()});var Su=ue((R2,vu)=>{vu.exports=function(t){var e=me("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var s=e.createDeflateRaw(n),a=[],d=0;s.on("data",function(u){a.push(u),d+=u.length}),s.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<a.length;x++){var g=a[x];g.copy(u,h),h+=g.length}i&&i(u)}),s.end(t)}}}});var Au=ue((O2,Iu)=>{var rw=+(process.versions?process.versions.node:"").split(".")[0]||0;Iu.exports=function(t,e){var n=me("zlib");let i=rw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(s){var a=n.createInflateRaw(i),d=[],u=0;a.on("data",function(h){d.push(h),u+=h.length}),a.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var g=0;g<d.length;g++){var w=d[g];w.copy(h,x),x+=w.length}s&&s(h)}),a.end(t)}}}});var Cu=ue((L2,Du)=>{"use strict";var{randomFillSync:ku}=me("crypto"),iw=Os(),sw=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Pu=(t,e)=>Math.imul(t,e)>>>0,Tu=(t,e)=>sw[(t^e)&255]^t>>>8,wi=()=>typeof ku=="function"?ku(Buffer.alloc(12)):wi.node();wi.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 Ls={genSalt:wi};function Ns(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])}Ns.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Tu(e[0],t),e[1]+=e[0]&255,e[1]=Pu(e[1],134775813)+1,e[2]=Tu(e[2],e[1]>>>24),t};Ns.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Pu(t,t^1)>>8&255};function ow(t){let e=new Ns(t);return function(n){let i=Buffer.alloc(n.length),s=0;for(let a of n)i[s++]=e.updateKeys(a^e.next());return i}}function aw(t){let e=new Ns(t);return function(n,i,s=0){i||(i=Buffer.alloc(n.length));for(let a of n){let d=e.next();i[s++]=a^d,e.updateKeys(a)}return i}}function cw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=ow(n),s=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==a)throw iw.WRONG_PASSWORD();return i(t.slice(12))}function dw(t){Buffer.isBuffer(t)&&t.length>=12?Ls.genSalt=function(){return t.slice(0,12)}:t==="node"?Ls.genSalt=wi.node:Ls.genSalt=wi}function lw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=aw(n),a=Ls.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return s(a,d),s(t,d,12)}Du.exports={decrypt:cw,encrypt:lw,_salter:dw}});var Ru=ue(Ms=>{Ms.Deflater=Su();Ms.Inflater=Au();Ms.ZipCrypto=Cu()});var ic=ue((M2,Ou)=>{var fe=br(),uw=nc(),Pe=fe.Constants,rc=Ru();Ou.exports=function(t,e){var n=new uw.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let g=t,w=typeof g.decoder=="object"?g.decoder:fe.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=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 L={},N=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(N)==Pe.LOCSIG||e.readUInt32LE(N)==Pe.CENSIG)throw fe.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(N)==Pe.EXTSIG)L.crc=e.readUInt32LE(N+Pe.EXTCRC),L.compressedSize=e.readUInt32LE(N+Pe.EXTSIZ),L.size=e.readUInt32LE(N+Pe.EXTLEN);else if(e.readUInt16LE(N+12)===19280)L.crc=e.readUInt32LE(N+Pe.EXTCRC-4),L.compressedSize=e.readUInt32LE(N+Pe.EXTSIZ-4),L.size=e.readUInt32LE(N+Pe.EXTLEN-4);else throw fe.Errors.DESCRIPTOR_UNKNOWN();if(L.compressedSize!==n.compressedSize||L.size!==n.size||L.crc!==n.crc)throw fe.Errors.DESCRIPTOR_FAULTY();if(fe.crc32(b)!==L.crc)return!1}return!0}function E(b,L,N){if(typeof L>"u"&&typeof b=="string"&&(N=b,b=void 0),a)return b&&L&&L(Buffer.alloc(0),fe.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var H=v();if(H.length===0)return b&&L&&L(H),H;if(n.encrypted){if(typeof N!="string"&&!Buffer.isBuffer(N))throw fe.Errors.INVALID_PASS_PARAM();H=rc.ZipCrypto.decrypt(H,n,N)}var z=Buffer.alloc(n.size);switch(n.method){case fe.Constants.STORED:if(H.copy(z),_(z))return b&&L&&L(z),z;throw b&&L&&L(z,fe.Errors.BAD_CRC()),fe.Errors.BAD_CRC();case fe.Constants.DEFLATED:var Y=new rc.Inflater(H,n.size);if(b)Y.inflateAsync(function(Z){Z.copy(Z,0),L&&(_(Z)?L(Z):L(Z,fe.Errors.BAD_CRC()))});else{if(Y.inflate(z).copy(z,0),!_(z))throw fe.Errors.BAD_CRC(`"${w.decode(i)}"`);return z}break;default:throw b&&L&&L(Buffer.alloc(0),fe.Errors.UNKNOWN_METHOD()),fe.Errors.UNKNOWN_METHOD()}}function I(b,L){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&L&&L(v()),v();if(d.length&&!a){var N;switch(n.method){case fe.Constants.STORED:return n.compressedSize=n.size,N=Buffer.alloc(d.length),d.copy(N),b&&L&&L(N),N;default:case fe.Constants.DEFLATED:var H=new rc.Deflater(d);if(b)H.deflateAsync(function(Y){N=Buffer.alloc(Y.length),n.compressedSize=Y.length,Y.copy(N),L&&L(N)});else{var z=H.deflate();return n.compressedSize=z.length,z}H=null;break}}else if(b&&L)L(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,L){return fe.readBigUInt64LE(b,L)}function T(b){try{for(var L=0,N,H,z;L+4<b.length;)N=b.readUInt16LE(L),L+=2,H=b.readUInt16LE(L),L+=2,z=b.slice(L,L+H),L+=H,Pe.ID_ZIP64===N&&O(z)}catch{throw fe.Errors.EXTRA_FIELD_PARSE_ERROR()}}function O(b){var L,N,H,z;b.length>=Pe.EF_ZIP64_SCOMP&&(L=A(b,Pe.EF_ZIP64_SUNCOMP),n.size===Pe.EF_ZIP64_OR_32&&(n.size=L)),b.length>=Pe.EF_ZIP64_RHO&&(N=A(b,Pe.EF_ZIP64_SCOMP),n.compressedSize===Pe.EF_ZIP64_OR_32&&(n.compressedSize=N)),b.length>=Pe.EF_ZIP64_DSN&&(H=A(b,Pe.EF_ZIP64_RHO),n.offset===Pe.EF_ZIP64_OR_32&&(n.offset=H)),b.length>=Pe.EF_ZIP64_DSN+4&&(z=b.readUInt32LE(Pe.EF_ZIP64_DSN),n.diskNumStart===Pe.EF_ZIP64_OR_16&&(n.diskNumStart=z))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=fe.toBuffer(b,w.encode);var L=i[i.length-1];a=L===47||L===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,T(b)},get comment(){return w.decode(s)},set comment(b){if(s=fe.toBuffer(b,w.encode),n.commentLength=s.length,s.length>65535)throw fe.Errors.COMMENT_TOO_LONG()},get name(){var b=w.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,L){n.changed?b(d):E(!0,b,L)},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(),L=fe.Constants.CENHDR;return i.copy(b,L),L+=i.length,u.copy(b,L),L+=n.extraLength,s.copy(b,L),b},packLocalHeader:function(){let b=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let L=n.localHeaderToBinary(),N=Buffer.alloc(L.length+i.length+n.extraLocalLength);return L.copy(N,b),b+=L.length,i.copy(N,b),b+=i.length,h.copy(N,b),b+=h.length,N},toJSON:function(){let b=function(L){return"<"+(L&&L.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 Mu=ue((B2,Nu)=>{var Lu=ic(),fw=nc(),Xe=br();Nu.exports=function(t,e){var n=[],i={},s=Buffer.alloc(0),a=new fw.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:g,decoder:w}=x;t?E(x.readEntries):d=!0;function v(){let A=new Set;for(let T of Object.keys(i)){let O=T.split("/");if(O.pop(),!!O.length)for(let b=0;b<O.length;b++){let L=O.slice(0,b+1).join("/")+"/";A.add(L)}}for(let T of A)if(!(T in i)){let O=new Lu(x);O.entryName=T,O.attr=16,O.temporary=!0,n.push(O),i[O.entryName]=O,h.add(O)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Xe.Constants.CENHDR)throw Xe.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,T=0;T<n.length;T++){var O=A,b=new Lu(x,t);b.header=t.slice(O,O+=Xe.Constants.CENHDR),b.entryName=t.slice(O,O+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(O,O+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(O,O+b.header.commentLength)),A+=b.header.centralHeaderSize,n[T]=b,i[b.entryName]=b}h.clear(),v()}function E(A){var T=t.length-Xe.Constants.ENDHDR,O=Math.max(0,T-65535),b=O,L=t.length,N=-1,H=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(O=0),T;T>=b;T--)if(t[T]===80){if(t.readUInt32LE(T)===Xe.Constants.ENDSIG){N=T,H=T,L=T+Xe.Constants.ENDHDR,b=T-Xe.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Xe.Constants.END64SIG){b=O;continue}if(t.readUInt32LE(T)===Xe.Constants.ZIP64SIG){N=T,L=T+Xe.readBigUInt64LE(t,T+Xe.Constants.ZIP64SIZE)+Xe.Constants.ZIP64LEAD;break}}if(N==-1)throw Xe.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(N,L)),a.commentLength&&(s=t.slice(H+Xe.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!g&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(A=>!h.has(A))},get comment(){return w.decode(s)},set comment(A){s=Xe.toBuffer(A,w.encode),a.commentLength=s.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||_(),i[A]||null},setEntry:function(A){d||_(),n.push(A),i[A.entryName]=A,a.totalEntries=n.length},deleteFile:function(A,T=!0){d||_();let O=i[A];this.getEntryChildren(O,T).map(L=>L.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||_();let T=i[A],O=n.indexOf(T);O>=0&&(n.splice(O,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(d||_(),typeof A=="object")if(A.isDirectory&&T){let O=[],b=A.entryName;for(let L of n)L.entryName.startsWith(b)&&O.push(L);return O}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),I();let A=[],T=[],O=0,b=0;a.size=0,a.offset=0;let L=0;for(let z of this.entries){let Y=z.getCompressedData();z.header.offset=b;let Z=z.packLocalHeader(),ae=Z.length+Y.length;b+=ae,A.push(Z),A.push(Y);let Q=z.packCentralHeader();T.push(Q),a.size+=Q.length,O+=ae+Q.length,L++}O+=a.mainHeaderSize,a.offset=b,a.totalEntries=L,b=0;let N=Buffer.alloc(O);for(let z of A)z.copy(N,b),b+=z.length;for(let z of T)z.copy(N,b),b+=z.length;let H=a.toBinary();return s&&s.copy(H,Xe.Constants.ENDHDR),H.copy(N,b),t=N,d=!1,N},toAsyncBuffer:function(A,T,O,b){try{d||_(),I();let L=[],N=[],H=0,z=0,Y=0;a.size=0,a.offset=0;let Z=function(ae){if(ae.length>0){let Q=ae.shift(),se=Q.entryName+Q.extra.toString();O&&O(se),Q.getCompressedDataAsync(function(de){b&&b(se),Q.header.offset=z;let C=Q.packLocalHeader(),q=C.length+de.length;z+=q,L.push(C),L.push(de);let W=Q.packCentralHeader();N.push(W),a.size+=W.length,H+=q+W.length,Y++,Z(ae)})}else{H+=a.mainHeaderSize,a.offset=z,a.totalEntries=Y,z=0;let Q=Buffer.alloc(H);L.forEach(function(de){de.copy(Q,z),z+=de.length}),N.forEach(function(de){de.copy(Q,z),z+=de.length});let se=a.toBinary();s&&s.copy(se,Xe.Constants.ENDHDR),se.copy(Q,z),t=Q,d=!1,A(Q)}};Z(Array.from(this.entries))}catch(L){T(L)}}}}});var zu=ue((F2,Fu)=>{var Ae=br(),Ie=me("path"),hw=ic(),xw=Mu(),Fn=(...t)=>Ae.findLast(t,e=>typeof e=="boolean"),Bu=(...t)=>Ae.findLast(t,e=>typeof e=="string"),pw=(...t)=>Ae.findLast(t,e=>typeof e=="function"),gw={noSort:!1,readEntries:!1,method:Ae.Constants.NONE,fs:null};Fu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),gw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=Ae.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new Ae(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ae.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=Ae.Constants.FILE,i.filename=t,n=s.fs.readFileSync(t);else throw Ae.Errors.INVALID_FILENAME();let a=new xw(n,i),{canonical:d,sanitize:u,zipnamefix:h}=Ae;function x(_){if(_&&a){var E;if(typeof _=="string"&&(E=a.getEntry(Ie.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=a.getEntry(_.entryName)),E)return E}return null}function g(_){let{join:E,normalize:I,sep:A}=Ie.posix;return E(Ie.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function w(_){return _ instanceof RegExp?(function(E){return function(I){return E.test(I)}})(_):typeof _!="function"?()=>!0:_}let v=(_,E)=>{let I=E.slice(-1);return I=I===s.sep?s.sep:"",Ie.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(T,O){if(O){E(T,O);return}T&&T.length?E(T.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(s.fs.existsSync(_)){E=E?g(E):"";let T=Ie.win32.basename(Ie.win32.normalize(_));E+=I||T;let O=s.fs.statSync(_),b=O.isFile()?s.fs.readFileSync(_):Buffer.alloc(0);O.isDirectory()&&(E+=s.sep),this.addFile(E,b,A,O)}else throw Ae.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let I=Ie.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:O}=_,b=this;s.fs.stat(I,function(L,N){if(L)return E(L,!1);T=T?g(T):"";let H=Ie.win32.basename(Ie.win32.normalize(I));if(T+=O||H,N.isFile())s.fs.readFile(I,function(z,Y){return z?E(z,!1):(b.addFile(T,Y,A,N),setImmediate(E,void 0,!0))});else if(N.isDirectory())return T+=s.sep,b.addFile(T,Buffer.alloc(0),A,N),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,I){if(I=w(I),E=E?g(E):"",_=Ie.normalize(_),s.fs.existsSync(_)){let A=s.findFiles(_),T=this;if(A.length)for(let O of A){let b=Ie.join(E,v(_,O));I(b)&&T.addLocalFile(O,Ie.dirname(b))}}else throw Ae.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,I,A){A=w(A),I=I?g(I):"",_=Ie.normalize(_);var T=this;s.fs.open(_,"r",function(O){if(O&&O.code==="ENOENT")E(void 0,Ae.Errors.FILE_NOT_FOUND(_));else if(O)E(void 0,O);else{var b=s.findFiles(_),L=-1,N=function(){if(L+=1,L<b.length){var H=b[L],z=v(_,H).split("\\").join("/");z=z.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(z)?s.fs.stat(H,function(Y,Z){Y&&E(void 0,Y),Z.isFile()?s.fs.readFile(H,function(ae,Q){ae?E(void 0,ae):(T.addFile(I+z,Q,"",Z),N())}):(T.addFile(I+z+"/",Buffer.alloc(0),"",Z),N())}):process.nextTick(()=>{N()})}else E(!0,void 0)};N()}})},addLocalFolderAsync2:function(_,E){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Ie.resolve(g(_.localPath));let{zipPath:A,filter:T,namefix:O}=_;T instanceof RegExp?T=(function(N){return function(H){return N.test(H)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?g(A):"",O=="latin1"&&(O=N=>N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof O!="function"&&(O=N=>N);let b=N=>Ie.join(A,O(v(localPath,N))),L=N=>Ie.win32.basename(Ie.win32.normalize(O(N)));s.fs.open(localPath,"r",function(N){N&&N.code==="ENOENT"?E(void 0,Ae.Errors.FILE_NOT_FOUND(localPath)):N?E(void 0,N):s.findFilesAsync(localPath,function(H,z){if(H)return E(H);z=z.filter(Y=>T(b(Y))),z.length||E(void 0,!1),setImmediate(z.reverse().reduce(function(Y,Z){return function(ae,Q){if(ae||Q===!1)return setImmediate(Y,ae,!1);I.addLocalFileAsync({localPath:Z,zipPath:Ie.dirname(b(Z)),zipName:L(Z)},Y)}},E))})})},addLocalFolderPromise:function(_,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},E),(T,O)=>{T&&A(T),O&&I(this)})})},addFile:function(_,E,I,A){_=h(_);let T=x(_),O=T!=null;O||(T=new hw(i),T.entryName=_),T.comment=I||"";let b=typeof A=="object"&&A instanceof s.fs.Stats;b&&(T.header.time=A.mtime);var L=T.isDirectory?16:0;let N=T.isDirectory?16384:32768;return b?N|=4095&A.mode:typeof A=="number"?N|=4095&A:N|=T.isDirectory?493:420,L=(L|N<<16)>>>0,T.attr=L,T.setData(E),O||a.setEntry(T),T},getEntries:function(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,E,I,A,T,O){A=Fn(!1,A),T=Fn(!1,T),I=Fn(!0,I),O=Bu(T,O);var b=x(_);if(!b)throw Ae.Errors.NO_ENTRY();var L=d(b.entryName),N=u(E,O&&!b.isDirectory?O:I?L:Ie.basename(L));if(b.isDirectory){var H=a.getEntryChildren(b);return H.forEach(function(Z){if(Z.isDirectory)return;var ae=Z.getData();if(!ae)throw Ae.Errors.CANT_EXTRACT_FILE();var Q=d(Z.entryName),se=u(E,I?Q:Ie.basename(Q));let de=T?Z.header.fileAttr:void 0;s.writeFileTo(se,ae,A,de)}),!0}var z=b.getData(a.password);if(!z)throw Ae.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(N)&&!A)throw Ae.Errors.CANT_OVERRIDE();let Y=T?_.header.fileAttr:void 0;return s.writeFileTo(N,z,A,Y),!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=Fn(!1,I),A=Bu(I,A),E=Fn(!1,E),!a)throw Ae.Errors.NO_ZIP();a.entries.forEach(function(T){var O=u(_,d(T.entryName));if(T.isDirectory){s.makeDir(O);return}var b=T.getData(A);if(!b)throw Ae.Errors.CANT_EXTRACT_FILE();let L=I?T.header.fileAttr:void 0;s.writeFileTo(O,b,E,L);try{s.fs.utimesSync(O,T.header.time,T.header.time)}catch{throw Ae.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,I,A){if(A=pw(E,I,A),I=Fn(!1,I),E=Fn(!1,E),!A)return new Promise((N,H)=>{this.extractAllToAsync(_,E,I,function(z){z?H(z):N(this)})});if(!a){A(Ae.Errors.NO_ZIP());return}_=Ie.resolve(_);let T=N=>u(_,Ie.normalize(d(N.entryName))),O=(N,H)=>new Error(N+': "'+H+'"'),b=[],L=[];a.entries.forEach(N=>{N.isDirectory?b.push(N):L.push(N)});for(let N of b){let H=T(N),z=I?N.header.fileAttr:void 0;try{s.makeDir(H),z&&s.fs.chmodSync(H,z),s.fs.utimesSync(H,N.header.time,N.header.time)}catch{A(O("Unable to create folder",H))}}L.reverse().reduce(function(N,H){return function(z){if(z)N(z);else{let Y=Ie.normalize(d(H.entryName)),Z=u(_,Y);H.getDataAsync(function(ae,Q){if(Q)N(Q);else if(!ae)N(Ae.Errors.CANT_EXTRACT_FILE());else{let se=I?H.header.fileAttr:void 0;s.writeFileToAsync(Z,ae,E,se,function(de){de||N(O("Unable to write file",Z)),s.fs.utimes(Z,H.header.time,H.header.time,function(C){C?N(O("Unable to set times",Z)):N()})})}})}}},A)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=a.compressToBuffer();if(I){var A=s.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((T,O)=>{!_&&i.filename&&(_=i.filename),_||O("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let L=N=>N?T(N):O("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(_,b,I,A,L)},O)})},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 Sy,spawn as Iy,spawnSync as nT}from"node:child_process";import{promisify as Ay}from"node:util";function Ty(t){if(process.platform!=="win32")return!1;if(a0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(a0,"").toLowerCase();return ky.has(n)}function c0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return Ty(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function ct(t,e=[],n={}){return Iy(t,e,c0(t,n))}function d0(t,e=[],n={}){return Py(t,e,c0(t,n))}var ky,a0,Py,tn=st(()=>{"use strict";ky=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),a0=/\.(cmd|bat|ps1)$/i;Py=Ay(Sy)});var sn=ue((hR,ox)=>{"use strict";var ix=["nodebuffer","arraybuffer","fragments"],sx=typeof Blob<"u";sx&&ix.push("blob");ox.exports={BINARY_TYPES:ix,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:sx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var as=ue((xR,Jo)=>{"use strict";var{EMPTY_BUFFER:Kv}=sn(),zd=Buffer[Symbol.species];function Wv(t,e){if(t.length===0)return Kv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let s=0;s<t.length;s++){let a=t[s];n.set(a,i),i+=a.length}return i<e?new zd(n.buffer,n.byteOffset,i):n}function ax(t,e,n,i,s){for(let a=0;a<s;a++)n[i+a]=t[a]^e[a&3]}function cx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function $v(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ud(t){if(Ud.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new zd(t):ArrayBuffer.isView(t)?e=new zd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ud.readOnly=!1),e}Jo.exports={concat:Wv,mask:ax,toArrayBuffer:$v,toBuffer:Ud,unmask:cx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=me("bufferutil");Jo.exports.mask=function(e,n,i,s,a){a<48?ax(e,n,i,s,a):t.mask(e,n,i,s,a)},Jo.exports.unmask=function(e,n){e.length<32?cx(e,n):t.unmask(e,n)}}catch{}});var ux=ue((pR,lx)=>{"use strict";var dx=Symbol("kDone"),Hd=Symbol("kRun"),Gd=class{constructor(e){this[dx]=()=>{this.pending--,this[Hd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hd]()}[Hd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[dx])}}};lx.exports=Gd});var Xr=ue((gR,px)=>{"use strict";var cs=me("zlib"),fx=as(),Vv=ux(),{kStatusCode:hx}=sn(),Zv=Buffer[Symbol.species],Jv=Buffer.from([0,0,255,255]),Xo=Symbol("permessage-deflate"),on=Symbol("total-length"),Jr=Symbol("callback"),On=Symbol("buffers"),Yr=Symbol("error"),Yo,qd=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,!Yo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Yo=new Vv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Jr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let s=n[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=s})}),e}decompress(e,n,i){Yo.add(s=>{this._decompress(e,n,(a,d)=>{s(),i(a,d)})})}compress(e,n,i){Yo.add(s=>{this._compress(e,n,(a,d)=>{s(),i(a,d)})})}_decompress(e,n,i){let s=this._isServer?"client":"server";if(!this._inflate){let a=`${s}_max_window_bits`,d=typeof this.params[a]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=cs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Xo]=this,this._inflate[on]=0,this._inflate[On]=[],this._inflate.on("error",Xv),this._inflate.on("data",xx)}this._inflate[Jr]=i,this._inflate.write(e),n&&this._inflate.write(Jv),this._inflate.flush(()=>{let a=this._inflate[Yr];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=fx.concat(this._inflate[On],this._inflate[on]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[on]=0,this._inflate[On]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let s=this._isServer?"server":"client";if(!this._deflate){let a=`${s}_max_window_bits`,d=typeof this.params[a]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=cs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[on]=0,this._deflate[On]=[],this._deflate.on("data",Yv)}this._deflate[Jr]=i,this._deflate.write(e),this._deflate.flush(cs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=fx.concat(this._deflate[On],this._deflate[on]);n&&(a=new Zv(a.buffer,a.byteOffset,a.length-4)),this._deflate[Jr]=null,this._deflate[on]=0,this._deflate[On]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};px.exports=qd;function Yv(t){this[On].push(t),this[on]+=t.length}function xx(t){if(this[on]+=t.length,this[Xo]._maxPayload<1||this[on]<=this[Xo]._maxPayload){this[On].push(t);return}this[Yr]=new RangeError("Max payload size exceeded"),this[Yr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Yr][hx]=1009,this.removeListener("data",xx),this.reset()}function Xv(t){if(this[Xo]._inflate=null,this[Yr]){this[Jr](this[Yr]);return}t[hx]=1007,this[Jr](t)}});var Qr=ue((mR,Qo)=>{"use strict";var{isUtf8:gx}=me("buffer"),{hasBlob:Qv}=sn(),eS=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function tS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function jd(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function nS(t){return Qv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Qo.exports={isBlob:nS,isValidStatusCode:tS,isValidUTF8:jd,tokenChars:eS};if(gx)Qo.exports.isValidUTF8=function(t){return t.length<24?jd(t):gx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=me("utf-8-validate");Qo.exports.isValidUTF8=function(e){return e.length<32?jd(e):t(e)}}catch{}});var Zd=ue((wR,Sx)=>{"use strict";var{Writable:rS}=me("stream"),mx=Xr(),{BINARY_TYPES:iS,EMPTY_BUFFER:_x,kStatusCode:sS,kWebSocket:oS}=sn(),{concat:Kd,toArrayBuffer:aS,unmask:cS}=as(),{isValidStatusCode:dS,isValidUTF8:yx}=Qr(),ea=Buffer[Symbol.species],_t=0,bx=1,Ex=2,vx=3,Wd=4,$d=5,ta=6,Vd=class extends rS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||iS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[oS]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=_t}_write(e,n,i){if(this._opcode===8&&this._state==_t)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 ea(i.buffer,i.byteOffset+e,i.length-e),new ea(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=n.length-e;e>=i.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new ea(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 _t:this.getInfo(e);break;case bx:this.getPayloadLength16(e);break;case Ex:this.getPayloadLength64(e);break;case vx:this.getMask();break;case Wd:this.getData(e);break;case $d:case ta:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let i=(n[0]&64)===64;if(i&&!this._extensions[mx.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=bx:this._payloadLength===127?this._state=Ex:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=vx:this._state=Wd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Wd}getData(e){let n=_x;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&cS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=$d,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[mx.extensionName].decompress(e,this._fin,(s,a)=>{if(s)return n(s);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===_t&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=_t;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Kd(i,n):this._binaryType==="arraybuffer"?s=aS(Kd(i,n)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=_t):(this._state=ta,setImmediate(()=>{this.emit("message",s,!0),this._state=_t,this.startLoop(e)}))}else{let s=Kd(i,n);if(!this._skipUTF8Validation&&!yx(s)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===$d||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=_t):(this._state=ta,setImmediate(()=>{this.emit("message",s,!1),this._state=_t,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,_x),this.end();else{let i=e.readUInt16BE(0);if(!dS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let s=new ea(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!yx(s)){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,s),this.end()}this._state=_t;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=_t):(this._state=ta,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=_t,this.startLoop(n)}))}createError(e,n,i,s,a){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=a,d[sS]=s,d}};Sx.exports=Vd});var Xd=ue((yR,kx)=>{"use strict";var{Duplex:_R}=me("stream"),{randomFillSync:lS}=me("crypto"),Ix=Xr(),{EMPTY_BUFFER:uS,kWebSocket:fS,NOOP:hS}=sn(),{isBlob:ei,isValidStatusCode:xS}=Qr(),{mask:Ax,toBuffer:ir}=as(),yt=Symbol("kByteLength"),pS=Buffer.alloc(4),na=8*1024,sr,ti=na,Dt=0,gS=1,mS=2,Jd=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=hS,this[fS]=void 0}static frame(e,n){let i,s=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||pS,n.generateMask?n.generateMask(i):(ti===na&&(sr===void 0&&(sr=Buffer.alloc(na)),lS(sr,0,na),ti=0),i[0]=sr[ti++],i[1]=sr[ti++],i[2]=sr[ti++],i[3]=sr[ti++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[yt]!==void 0?u=n[yt]:(e=Buffer.from(e),u=e.length):(u=e.length,s=n.mask&&n.readOnly&&!d);let h=u;u>=65536?(a+=8,h=127):u>125&&(a+=2,h=126);let x=Buffer.allocUnsafe(s?u+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:s?(Ax(e,i,x,a,u),[x]):(Ax(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,s){let a;if(e===void 0)a=uS;else{if(typeof e!="number"||!xS(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+u),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let d={[yt]: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,s]):this.sendFrame(t.frame(a,d),s)}ping(e,n,i){let s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):ei(e)?(s=e.size,a=!1):(e=ir(e),s=e.length,a=ir.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[yt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};ei(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 s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):ei(e)?(s=e.size,a=!1):(e=ir(e),s=e.length,a=ir.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[yt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};ei(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 s=this._extensions[Ix.extensionName],a=n.binary?2:1,d=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):ei(e)?(u=e.size,h=!1):(e=ir(e),u=e.length,h=ir.readOnly),this._firstFragment?(this._firstFragment=!1,d&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=s._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[yt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:h,rsv1:d};ei(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,s){this._bufferedBytes+=i[yt],this._state=mS,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Yd,this,u,s);return}this._bufferedBytes-=i[yt];let d=ir(a);n?this.dispatch(d,n,i,s):(this._state=Dt,this.sendFrame(t.frame(d,i),s),this.dequeue())}).catch(a=>{process.nextTick(wS,this,a,s)})}dispatch(e,n,i,s){if(!n){this.sendFrame(t.frame(e,i),s);return}let a=this._extensions[Ix.extensionName];this._bufferedBytes+=i[yt],this._state=gS,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");Yd(this,h,s);return}this._bufferedBytes-=i[yt],this._state=Dt,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===Dt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][yt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][yt],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)}};kx.exports=Jd;function Yd(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let s=t._queue[i],a=s[s.length-1];typeof a=="function"&&a(e)}}function wS(t,e,n){Yd(t,e,n),t.onerror(e)}});var Mx=ue((bR,Nx)=>{"use strict";var{kForOnEventAttribute:ds,kListener:Qd}=sn(),Tx=Symbol("kCode"),Px=Symbol("kData"),Dx=Symbol("kError"),Cx=Symbol("kMessage"),Rx=Symbol("kReason"),ni=Symbol("kTarget"),Ox=Symbol("kType"),Lx=Symbol("kWasClean"),an=class{constructor(e){this[ni]=null,this[Ox]=e}get target(){return this[ni]}get type(){return this[Ox]}};Object.defineProperty(an.prototype,"target",{enumerable:!0});Object.defineProperty(an.prototype,"type",{enumerable:!0});var or=class extends an{constructor(e,n={}){super(e),this[Tx]=n.code===void 0?0:n.code,this[Rx]=n.reason===void 0?"":n.reason,this[Lx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Tx]}get reason(){return this[Rx]}get wasClean(){return this[Lx]}};Object.defineProperty(or.prototype,"code",{enumerable:!0});Object.defineProperty(or.prototype,"reason",{enumerable:!0});Object.defineProperty(or.prototype,"wasClean",{enumerable:!0});var ri=class extends an{constructor(e,n={}){super(e),this[Dx]=n.error===void 0?null:n.error,this[Cx]=n.message===void 0?"":n.message}get error(){return this[Dx]}get message(){return this[Cx]}};Object.defineProperty(ri.prototype,"error",{enumerable:!0});Object.defineProperty(ri.prototype,"message",{enumerable:!0});var ls=class extends an{constructor(e,n={}){super(e),this[Px]=n.data===void 0?null:n.data}get data(){return this[Px]}};Object.defineProperty(ls.prototype,"data",{enumerable:!0});var _S={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[ds]&&s[Qd]===e&&!s[ds])return;let i;if(t==="message")i=function(a,d){let u=new ls("message",{data:d?a:a.toString()});u[ni]=this,ra(e,this,u)};else if(t==="close")i=function(a,d){let u=new or("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[ni]=this,ra(e,this,u)};else if(t==="error")i=function(a){let d=new ri("error",{error:a,message:a.message});d[ni]=this,ra(e,this,d)};else if(t==="open")i=function(){let a=new an("open");a[ni]=this,ra(e,this,a)};else return;i[ds]=!!n[ds],i[Qd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Qd]===e&&!n[ds]){this.removeListener(t,n);break}}};Nx.exports={CloseEvent:or,ErrorEvent:ri,Event:an,EventTarget:_S,MessageEvent:ls};function ra(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ia=ue((ER,Bx)=>{"use strict";var{tokenChars:us}=Qr();function Gt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function yS(t){let e=Object.create(null),n=Object.create(null),i=!1,s=!1,a=!1,d,u,h=-1,x=-1,g=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(g===-1&&us[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let _=t.slice(h,g);x===44?(Gt(e,_,n),n=Object.create(null)):d=_,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(g===-1&&us[x]===1)h===-1&&(h=w);else if(x===32||x===9)g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w),Gt(n,t.slice(h,g),!0),x===44&&(Gt(e,d,n),n=Object.create(null),d=void 0),h=g=-1}else if(x===61&&h!==-1&&g===-1)u=t.slice(h,w),h=g=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(s){if(us[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),s=!1}else if(a)if(us[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)a=!1,g=w;else if(x===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)a=!0;else if(g===-1&&us[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))g===-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let _=t.slice(h,g);i&&(_=_.replace(/\\/g,""),i=!1),Gt(n,u,_),x===44&&(Gt(e,d,n),n=Object.create(null),d=void 0),u=void 0,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=w);let v=t.slice(h,g);return d===void 0?Gt(e,v,n):(u===void 0?Gt(n,v,!0):i?Gt(n,u,v.replace(/\\/g,"")):Gt(n,u,v),Gt(e,d,n)),e}function bS(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(s=>{let a=i[s];return Array.isArray(a)||(a=[a]),a.map(d=>d===!0?s:`${s}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Bx.exports={format:bS,parse:yS}});var ca=ue((IR,Zx)=>{"use strict";var ES=me("events"),vS=me("https"),SS=me("http"),Ux=me("net"),IS=me("tls"),{randomBytes:AS,createHash:kS}=me("crypto"),{Duplex:vR,Readable:SR}=me("stream"),{URL:el}=me("url"),Ln=Xr(),TS=Zd(),PS=Xd(),{isBlob:DS}=Qr(),{BINARY_TYPES:Fx,CLOSE_TIMEOUT:CS,EMPTY_BUFFER:sa,GUID:RS,kForOnEventAttribute:tl,kListener:OS,kStatusCode:LS,kWebSocket:Ze,NOOP:Hx}=sn(),{EventTarget:{addEventListener:NS,removeEventListener:MS}}=Mx(),{format:BS,parse:FS}=ia(),{toBuffer:zS}=as(),Gx=Symbol("kAborted"),nl=[8,13],cn=["CONNECTING","OPEN","CLOSING","CLOSED"],US=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ee=class t extends ES{constructor(e,n,i){super(),this._binaryType=Fx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=sa,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]),qx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Fx.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let s=new TS({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new PS(e,this._extensions,i.generateMask);this._receiver=s,this._sender=a,this._socket=e,s[Ze]=this,a[Ze]=this,e[Ze]=this,s.on("conclude",qS),s.on("drain",jS),s.on("error",KS),s.on("message",WS),s.on("ping",$S),s.on("pong",VS),a.onerror=ZS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Wx),e.on("data",aa),e.on("end",$x),e.on("error",Vx),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[Ln.extensionName]&&this._extensions[Ln.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ft(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Kx(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){rl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||sa,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){rl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||sa,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){rl(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ln.extensionName]||(s.compress=!1),this._sender.send(e||sa,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ft(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ee,"CONNECTING",{enumerable:!0,value:cn.indexOf("CONNECTING")});Object.defineProperty(Ee.prototype,"CONNECTING",{enumerable:!0,value:cn.indexOf("CONNECTING")});Object.defineProperty(Ee,"OPEN",{enumerable:!0,value:cn.indexOf("OPEN")});Object.defineProperty(Ee.prototype,"OPEN",{enumerable:!0,value:cn.indexOf("OPEN")});Object.defineProperty(Ee,"CLOSING",{enumerable:!0,value:cn.indexOf("CLOSING")});Object.defineProperty(Ee.prototype,"CLOSING",{enumerable:!0,value:cn.indexOf("CLOSING")});Object.defineProperty(Ee,"CLOSED",{enumerable:!0,value:cn.indexOf("CLOSED")});Object.defineProperty(Ee.prototype,"CLOSED",{enumerable:!0,value:cn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ee.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ee.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[tl])return e[OS];return null},set(e){for(let n of this.listeners(t))if(n[tl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[tl]:!0})}})});Ee.prototype.addEventListener=NS;Ee.prototype.removeEventListener=MS;Zx.exports=Ee;function qx(t,e,n,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CS,protocolVersion:nl[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=s.autoPong,t._closeTimeout=s.closeTimeout,!nl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${nl.join(", ")})`);let a;if(e instanceof el)a=e;else try{a=new el(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),t._url=a.href;let d=a.protocol==="wss:",u=a.protocol==="ws+unix:",h;if(a.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?h="The URL's pathname is empty":a.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;oa(t,I);return}let x=d?443:80,g=AS(16).toString("base64"),w=d?vS.request:SS.request,v=new Set,_;if(s.createConnection=s.createConnection||(d?GS:HS),s.defaultPort=s.defaultPort||x,s.port=a.port||x,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(_=new Ln({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=BS({[Ln.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!US.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),u){let I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let E;if(s.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?s.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),E=t._req=w(s),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(s);s.timeout&&E.on("timeout",()=>{ft(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Gx]||(E=t._req=null,oa(t,I))}),E.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&s.followRedirects&&T>=300&&T<400){if(++t._redirects>s.maxRedirects){ft(t,E,"Maximum redirects exceeded");return}E.abort();let O;try{O=new el(A,e)}catch{let L=new SyntaxError(`Invalid URL: ${A}`);oa(t,L);return}qx(t,O,n,i)}else t.emit("unexpected-response",E,I)||ft(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==Ee.CONNECTING)return;E=t._req=null;let O=I.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){ft(t,A,"Invalid Upgrade header");return}let b=kS("sha1").update(g+RS).digest("base64");if(I.headers["sec-websocket-accept"]!==b){ft(t,A,"Invalid Sec-WebSocket-Accept header");return}let L=I.headers["sec-websocket-protocol"],N;if(L!==void 0?v.size?v.has(L)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":v.size&&(N="Server sent no subprotocol"),N){ft(t,A,N);return}L&&(t._protocol=L);let H=I.headers["sec-websocket-extensions"];if(H!==void 0){if(!_){ft(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let z;try{z=FS(H)}catch{ft(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(z);if(Y.length!==1||Y[0]!==Ln.extensionName){ft(t,A,"Server indicated an extension that was not requested");return}try{_.accept(z[Ln.extensionName])}catch{ft(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ln.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(E,t):E.end()}function oa(t,e){t._readyState=Ee.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function HS(t){return t.path=t.socketPath,Ux.connect(t)}function GS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ux.isIP(t.host)?"":t.host),IS.connect(t)}function ft(t,e,n){t._readyState=Ee.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ft),e.setHeader?(e[Gx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(oa,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function rl(t,e,n){if(e){let i=DS(e)?e.size:zS(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${cn[t.readyState]})`);process.nextTick(n,i)}}function qS(t,e){let n=this[Ze];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ze]!==void 0&&(n._socket.removeListener("data",aa),process.nextTick(jx,n._socket),t===1005?n.close():n.close(t,e))}function jS(){let t=this[Ze];t.isPaused||t._socket.resume()}function KS(t){let e=this[Ze];e._socket[Ze]!==void 0&&(e._socket.removeListener("data",aa),process.nextTick(jx,e._socket),e.close(t[LS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function zx(){this[Ze].emitClose()}function WS(t,e){this[Ze].emit("message",t,e)}function $S(t){let e=this[Ze];e._autoPong&&e.pong(t,!this._isServer,Hx),e.emit("ping",t)}function VS(t){this[Ze].emit("pong",t)}function jx(t){t.resume()}function ZS(t){let e=this[Ze];e.readyState!==Ee.CLOSED&&(e.readyState===Ee.OPEN&&(e._readyState=Ee.CLOSING,Kx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Kx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Wx(){let t=this[Ze];if(this.removeListener("close",Wx),this.removeListener("data",aa),this.removeListener("end",$x),t._readyState=Ee.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[Ze]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",zx),t._receiver.on("finish",zx))}function aa(t){this[Ze]._receiver.write(t)||this.pause()}function $x(){let t=this[Ze];t._readyState=Ee.CLOSING,t._receiver.end(),this.end()}function Vx(){let t=this[Ze];this.removeListener("error",Vx),this.on("error",Hx),t&&(t._readyState=Ee.CLOSING,this.destroy())}});var Qx=ue((kR,Xx)=>{"use strict";var AR=ca(),{Duplex:JS}=me("stream");function Jx(t){t.emit("close")}function YS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Yx(t){this.removeListener("error",Yx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function XS(t,e){let n=!0,i=new JS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let u=!d&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(n=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,a){if(t.readyState===t.CLOSED){a(s),process.nextTick(Jx,i);return}let d=!1;t.once("error",function(h){d=!0,a(h)}),t.once("close",function(){d||a(s),process.nextTick(Jx,i)}),n&&t.terminate()},i._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(s,a,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(s,a,d)});return}t.send(s,d)},i.on("end",YS),i.on("error",Yx),i}Xx.exports=XS});var il=ue((TR,ep)=>{"use strict";var{tokenChars:QS}=Qr();function e1(t){let e=new Set,n=-1,i=-1,s=0;for(s;s<t.length;s++){let d=t.charCodeAt(s);if(i===-1&&QS[d]===1)n===-1&&(n=s);else if(s!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=s);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}ep.exports={parse:e1}});var ap=ue((DR,op)=>{"use strict";var t1=me("events"),da=me("http"),{Duplex:PR}=me("stream"),{createHash:n1}=me("crypto"),tp=ia(),ar=Xr(),r1=il(),i1=ca(),{CLOSE_TIMEOUT:s1,GUID:o1,kWebSocket:a1}=sn(),c1=/^[+/0-9A-Za-z]{22}==$/,np=0,rp=1,sp=2,sl=class extends t1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:s1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:i1,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=da.createServer((i,s)=>{let a=da.STATUS_CODES[426];s.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),s.end(a)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=d1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,a,d)=>{this.handleUpgrade(s,a,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=np}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===sp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(fs,this);return}if(e&&this.once("close",e),this._state!==rp)if(this._state=rp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(fs,this):process.nextTick(fs,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{fs(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,s){n.on("error",ip);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){cr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){cr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!c1.test(a)){cr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){cr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){hs(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=r1.parse(h)}catch{cr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&g!==void 0){let v=new ar({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=tp.parse(g);_[ar.extensionName]&&(v.accept(_[ar.extensionName]),w[ar.extensionName]=v)}catch{cr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(_,E,I,A)=>{if(!_)return hs(n,E||401,I,A);this.completeUpgrade(w,a,x,e,n,i,s)});return}if(!this.options.verifyClient(v))return hs(n,401)}this.completeUpgrade(w,a,x,e,n,i,s)}completeUpgrade(e,n,i,s,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[a1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>np)return hs(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${n1("sha1").update(n+o1).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),g._protocol=w)}if(e[ar.extensionName]){let w=e[ar.extensionName].params,v=tp.format({[ar.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${v}`),g._extensions=e}this.emit("headers",x,s),a.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",qh),m.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ss,this)})),u(m,s)}};jh.exports=Jd;function HS(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function ss(t){t._state=Gh,t.emit("close")}function qh(){this.destroy()}function os(t,e,r,i){r=r||Qo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Qo.STATUS_CODES[e]}\r
16
+ `)),a.removeListener("error",ip),g.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(fs,this)})),u(g,s)}};op.exports=sl;function d1(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function fs(t){t._state=sp,t.emit("close")}function ip(){this.destroy()}function hs(t,e,n,i){n=n||da.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} ${da.STATUS_CODES[e]}\r
17
17
  `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+r)}function rr(t,e,r,i,s,c){if(t.listenerCount("wsClientError")){let l=new Error(s);Error.captureStackTrace(l,rr),t.emit("wsClientError",l,r,e)}else os(r,i,s,c)}});var ip=ce(Be=>{"use strict";var M=z;function ra(){let t=["tgP5ANC","BuHmB2G","uMX4rMq","tgnKvwe","uvfqzKu","A2DrsMG","ihzHBgLKigq","sgnpuuG","s2DPwLG","zxjFCw9Zx2e","vvnTr1C","uuLIA0C","BwXerNG","AKv3EKO","CMzhEM4","DMHArMi","EgHmBMq","CMvXDwLYzwq","B2HQAK0","quLMzK0","CgzOruO","B3bLBKrc","yvbuqva","zxjYtM8","A2LiswG","B2fK","y29UDgLUDwu","u0HLAMO","sg1gBxK","u1zdCuS","v0XNtey","q2LZr1i","Dgv4DfbHEwW","CejrCgm","rMDJt3C","zKPkAvG","yxrLq291BNq","DxLLCfy","zxbMDeG","Aw50zwDLCIa","zxmGCMvHy2G","uK1Orwu","D0LpsKq","CM9gqxK","uLjpuG","qMzSD0y","uwDRA2i","sKDeCfi","runmDMG","B3nLza","DuLWD3y","CgLUz09Uy2u","shDOwui","rvzwquq","ywXSB2nvBNm","De1HBMfNzxi","CuLQDNG","ihzHBgLKihm","x2jPBMfYEvq","yxKSihrYEsa","Ag1ruMG","wgryEhy","ELfSD2O","x2LZtwLUAvq","vLDLDha","r1vXDLq","z3r6tvq","tujYDvi","vLzdzem","C2vUza","yKTiww0","CMvQzwn0","z2vjBMzVu3K","DLPXB1m","y3vYC29Y","x2nSzwfYugK","y29SBM8","ExbL","uu1ive0","teTMAxq","B25mAw5L","B3jpBMXPBMu","z29JB08","zNzLs2O","BIWGAg9ZDg4","Aw9WDMq","terksg0","v2vPEgLUsLm","CKDNs1O","wxznvgW","twvLzxy","x3bHDgHlzxK","yNzTEhe","CxHzAue","BwvZ","t3bLBKv2zw4","yKzjzhC","mdaWmdaWmda","ywnOzwqSihC","s0LmC2C","tg9JAW","CwnJy3K","u0fqBhy","Cen5EuK","uhLLweS","BwfUDwfSihi","zMLSDgvY","seTACKe","sgjvB0y","CMvUDevUzha","BwLUzW","vKLyvhO","BLfIzKS","x3vYBa","u290q1m","zev6vMO","t2vkAxm","y3vYC29Yx24","AeHUqwG","Bvvvv28","zxzlD2e","thzmD2e","CMvZB2X2zq","uK9ivhi","x29Uq2XVC2u","CMvKDwnL","CNnLr1y","y3j4ufC","r2roDfa","vLP2vvK","y1riqve","CeLbC3K","z2jVvNO","tg1dEg0","wwHLDuC","t1fgBxu","DM5RuvO","z2v0qwXS","zNjVBNrPzxi","BgLZDgvUtMu","u2roB3G","CMLLC0nVDw4","ExHJz3e","u2vXsuq","Aw1pquO","zw1LBNq","DMLJzuLeig8","ywnR","B3nJA0i","AKjes20","t0PqCKq","zNjVBu51Bwi","rujTvfi","DKnqvMC","ihbYB3rVy28","z0Dfzxm","CLDVwgK","yMfSrxzLBNq","CYbHBhjLywq","rLLYBM8","uwHLtwq","rMnQsNi","D3fLv1O","q2Dyzgi","y2vZC0HHBMq","CfniEvi","revZr3i","otvqDMj1EwC","x2DLBMvYyxq","AwXLtMfTzq","zxHyAvO","AwXK","x2rYB3bhBg8","AwvVs3K","Ec11C2uT","t2TLz1m","Chv0","DgHHBIbSB2m","zMLN","ruXOrMK","vLzjvKi","yxbWBgLJyxq","ue9wvKK","CNzhz2u","Cw9jwKG","rMfeCwO","AgfUz2u","y2nVAhu","BNzsruq","CNDrBu0","x29Ut3bLBG","AevYCM9Yrxy","mxWZ","B3nLrxzLBNq","uLntA3a","A0DwCuu","EvzIv2S","rvLUz28","Cgu6ia","BgvUz3rO","x2nVBM5Ly3q","uMvMzxC","zw5HyMXLqxu","CxPTtfq","DMLivg0","ywDL","C2vYDMLJzq","BxLTzKW","EMvlsLe","Aw1orhq","pxv0zI04","u2fxvei","zM5cuuq","x2vUzhbVAw4","ENDOCuq","qMvsCg8","zLfpEMG","CMP4Cum","Aw1LCYbPBIa","zNjVBujPDhm","wxnUEMm","zw5XDwv1zq","uKTmte8","x2zVCM1HDeu","mNWWFdr8nxW","DxLgC1i","CgXLyxnLiha","tgLZDgvUzxi","B0LbD2S","shftBwu","D0XitKu","suTiEuC","zMzMzG","EhrYwMG","ELnWsfa","q29Kzq","txLsteq","uhHdwMK","qKncvfG","y2f0y2G","ywrKq291BNq","zfzRCMm","ihjLy29UBMu","uMvJB25Uzwm","DMTgwLu","nhWZFdb8mNW","sxbPz24","BKD6Buq","B2jQzwn0u3q","ENn6sKe","BKTSwxu","mNW1Fdz8m3W","z2HoqKm","C2vmq2y","vLDQCue","rff5yuK","AxjLza","tLnxsNa","ruvXAgG","oxWZFdr8mNW","AMHouMK","BLjwrfq","tLn3q2u","lcbTyxGGCMu","A1L4q0O","zgnNBgW","ywnRtxnNswq","zxjYtxnN","B3bLCNr5tMe","qKDXthi","yw51Ce1LC3m","zxjFywnRx20","x2DLDeLUDgu","C0nVDw50zxi","x29UtwvZC2e","tMTRq0m","sevqAfC","D1rWu1a","BwvZC2fNztO","zxHWB3j0CW","yMXVy2TLza","rNjVBNrPzxi","AursBwO","vMryA3m","B2LUDfjLywm","zxH0ugf5Bg8","vuLMAfO","rKLmrv9ot1q","vLjnr2q","BgLUzq","rvDez04","wgLkENe","DhjPzxm","BNvTyMvY","EK5Zyxy","ww1VsKq","ANrHD04","mxWZFdb8nhW","sfr6ruC","EvHjA1u","zMX1C2HfEha","y3vYCMvUDeu","uvb1qMG","CK5YA2G","AwfxCva","y2TtqKe","zMLSzw5HBwu","ANL3t1e","rLfTwgu","Ae9uAg0","CuncrxO","Dg9cExrLC0i","x19LC01Vzhu","quXm","shftrMS","tLflvLm","zMDAzxu","Cujhvfu","zv90Aw1LB3u","zNjHBwvuExa","mZeXotyZnejgwKvwsq","qNLjqLC","y2uGBM90igK","CKvPwha","Be5lwwe","ru9VuLq","vfrWtu8","yxnZAwDU","uw1LvhO","DgL4AKu","tg9Nsuq","AfrewMO","zNvUy3rPB24","sfbNvMG","s0HsB3m","EwX3Dfu","yMLqtwm","CYbWyxjHBxm","B25szwnLAxy","yvnvvxq","ELjPwu4","B3bLBG","DKzRCK4","r0vnDge","tuLoEge","BNrfBMrWB2K","DvboBgC","wNnWC1u","z2v0sxrLBq","mhWZ","x21PBMLoyxy","y2fSBa","tg9yEgi","BhbKBwu","x2n1CNnVCK0","B2nRzxrgywK","tLr4wxu","zw5JB2rLrNi","tK5Xugm","v3Lzuhm","C2neu28","ALnquvq","EKPlr1C","EMn1zgq","EhHyAxq","Bxbftwq","D1j3CKq","AgnYA0W","CuLMugC","vhP5zuu","Cgf5Bg9Hza","BMvJDa","yuDJAu8","CMvZzxrfBMq","CgLUz0XVC3m","Axnby2TdBgu","twvZC2fNzuu","rM5SCuq","z1nXANm","vezbsNy","x2rPC3bHDgm","ywXSq3vYC28","x2fKzfDZtgK","x2LZtwLUAvC","yxv0BW","DhjPzxmGCMu","EgrnDLC","yNL0zuXLBMC","BvDuEeC","wLz5sfy","qvnqzMK","A2Xyrxy","BwvMwxC","BMCGDxjSoIa","v1H3yKG","lcbOB3n0BMe","zwfQy3C","veXjsNq","u2DMuKS","y3r4","B25Uzwn0Aw4","rNLVrfm","uLf4DeW","C2XPy2u","D0zns3y","x2rItMfTzq","AMTTEuW","BxDjy1e","rgvAEhu","C3rYAw5NAwy","A2v5","tgXhy1K","CxnczNe","v25lweq","wwPgANi","y0nlCfC","wercrKe","zxj2AwnL","C2v0u3rVCMe","x1fVu01HBMe","q1L4zeO","EvrNyxy","CM92AwrLige","vxbKyxrLq28","zv9ZDwnJzxm","yK1hsey","DMfSDwvZ","rxjYB3jdB2q","svjStNu","x29UrxjYB3i","zwn0","t2HXtuy","qMT6ywu","zuz2Chq","BMLTveq","u0jjz1m","zgf0yq","y29UBMvJDeu","CgnABfG","AxnszwfKEq","CwrQwhm","BLziB1u","tKfIALK","Cfb6sMW","rgvKAwnHDgu","senHuMq","Dev2zw50","vxLYuum","A3noy20","yMLUyxj5vhK","sxrKAxa","EMntsxa","qujXAei","uhPrA2C","tLrgwgi","C3rVCcbPBw0","nxWYFdn8mq","rg5zAe4","yMDAANe","zw50tgLZDgu","z2v0qwXSs2u","uNzzDLO","se5oAfm","reiGzMfPBgu","Cwvlzgi","y2HnyxHuCMK","mtb8mtf8oxW","v3bezwO","qNn6q2S","C2fevum","sgXtBeq","D0rdvwO","ywrK","Aw5KzxHpzG","CfD4t0C","DhjHBNnHy3q","svv0yxG","AMLrrNe","zfHRu24","v09us2u","wxPRBue","r0fAu0i","tuvtu0fhrv8","z2v0","u2vYDMLJzvC","r3z2vKC","wfH1CwG","BxrguM8","vvPKy1a","CKnKzMS","zcWG","qMfvzuq","tKndwwq","s1DPr0O","sKrHA3K","q2XRq3G","qvvZqva","id4G","Cw9Z","ywnRDxbfBMq","zw5HyMXLvhi","CMvTB3zLq2G","DM9MtgS","A1zgt3C","CMvHzg9UBhK","wu1XrMC","yvbuAgW","B25tDgfYDfi","uxfiEhi","zxfgtw0","nxWYFdb8m3W","vu93y1e","uvLnC0e","zKTyDwO","sfvby2K","Bhzwv2S","zcWGDw5RBM8","q3DZvNa","rxzLBNq","EgjTCeS","su5tvefova","ALLssMi","EKTwEhK","BhbZzei","qwTMrNK","DNzYCgW","r2XNAgO","DxbKyxrLq3u","BMnVzgLUzW","x3jLBw92zvC","DuTzq28","zNL4thK","BML0AwfSAxO","y09KveS","yw5nEKq","CwXhyxO","lcbxzwjtB2m","t0n0zxi","ExnZvgy","zM9Yy2u","CNjVCK1LC3m","Aw9U","C2vYDMvYvgK","yKrur2O","yKPcB1i","DNDyBNe","z2u6ia","y29UC3rYDwm","x0vysvnu","C3vIyxjYyxK","BeHHBMrSzxi","CMvTB3zLrxy","y2HHCKnVzgu","zerVuMm","zM9YrwfJAa","BLjyCMO","yM9L","vgLTzw91Da","x3bPBMC","yKH2C0C","yNLL","zNDitKC","C0XPC3rLBMu","CLDPDNa","x3bYzwzPEa","txjbvLu","DgLTzw91DcW","ihrPBwvVDxq","y1zgBfO","vufxrvK","EsbJBg9Zzwq","zgPbwMu","A3zoEhi","DwrQtKS","D2vI","q0Xpu0ve","tvP3rvu","x2rLC3rYB3K","t3fUAfu","EgDLBKC","zw5NDgG","zcbLCNjVCI4","C2v0sxrLBq","DePJzfy","EeHdsKu","B3vUDa","zeHwAe8","qKLWsMi","rxLOEKC","Cg9PBNrbBMq","zhfNuwi","ChrVCG","CM1tsgG","twrTEwG","s09pwvG","twzkBgO","mJe2odrOqvrlruu","BMDuAw1LCG","zsbHihn0CMK","zwj4A3a","qLHetuG","Aw47y2HHCNm","yw5Hz2vY","Aw5L","veDhwNi","Aw1ku1u","x2rPC2nVBM4","sMvQzgO","rKrtyxy","zwnVBM5Ly3q","zMzLCG","B216B2G","Ae5Mvfa","ufbKy2e","x2nYzwf0zvm","sK9WAeO","zxj6wee","weHAu3G","v2vIu29JA2u","uw9pu1K","CMfTzq","Bg93","uwzutu4","Dgv4Dc9WBge","qwz4Cgi","y3vYDMfSDwu","qwnbAxu","B25nzxnZywC","B2zMC2v0","q1DUC1a","DKzVu1u","yMLUyxj5","BKz4rw0","y29Uy2f0","Egj2sMG","qu1fvMK","vvbqBeC","A3nIqxe","ru5Is0C","AwXSihvZzsa","uuvnsuK","AxnFywnR","rwLRv1y","Dhr3Awq","q2P1yMC","mtb8mxWZFdC","Cgf5Bg9Hzfq","y3jLyxrLt3a","qxjpB2C","Bwf4uMv0CMK","m3WXFdb8nhW","tMXRCKi","s2DtDLe","DeLUDgvYy2u","vLfcrhy","AMvJDfn0B3i","aaaaaaaaaaa","Bwj1Cxa","AvPPENq","ihrVihjLDhi","tNHAAeC","Eg5ouwe","mxWZFdj8mhW","AxmGDw5Kzwy","wufOqNK","whr2Dha","D29suuu","rw9tCeO","BeDPsw4","sNLmwue","CMzhCeW","igfYCMf5yNu","u3rYyxrLz3K","zNfKEfm","BwvY","zNjVBuHHC2G","q3vZDg9Trxi","y3jLyxrLrxi","BvzkBvi","r3HwrNy","yMLQq2q","x21LC3nHz2u","s29kDKK","sLnptLa","BNzzEei","DhjPBq","v1bmtNm","Aw5N","wKLICu4","vw5PBxbSzw0","CLfJzfy","v1bnsMO","v0XguM8","z0X4ANy","qKjqwxi","zxjFAxnFywm","rvnZthy","t2Htvxe","wMrmENy","vLblD3i","CuLlwKS","yw1L","zMryq08","FdL8ohW0","txfbsfy","yxjPrxm","z01QqNq","x2LUAxrqCM8","BwfW","AgvHzgvY","BNrbBMrvCgq","DM52suW","CMvHzfvjBNq","Dgv4Dc9Qyxy","AM9PvMO","DMvtwwW","x2nSzwfYvgK","y29Kzq","DxvZsg8","vgPNCey","qwHWExK","uvrXr1u","Ae1JD1i","Cwr0BKO","CMPMwvG","ChjVDg9JB2W","x2LUAxq","A0rYsey","serLDLu","z2v0u3rVCMe","C3rLBMvYCW","CeHVyNm","qLz1Cfa","AurZDuK","rgLMq2u","s2jZq0K","qxfit0K","Dujju2K","nxW0","BwvZC2fNzq","DMvY","y2Dgq1C","ywrKrxzLBNq","ExbdqMC","BgvY","uM51DMK","B25SAw5L","DfzjCe0","v016zfe","rNfWv3u","ihrPBwvZ","B3bLCNr5","Dxrjza","D3nZoI8V","DgLUzYbZzxi","zw50","yxv0B21HDgK","B2vutM4","qwjjsfu","BKXPBMu","vwfVz1G","ExHYz0S","qxjly1C","CNzHBa","DgfIyxnL","rMz1rhm","vMzysKG","B3jLtMfTzxm","zw5HyMXLuw8","z1v0Dfe","reTmww4","Cu5otvC","ueLVv1G","CgfYC2u","D3DKzK8","BwLevMm","t0zUDeO","Dw5ZAwDUzwq","rgzVt0C","D01Kv28","y2HnyxHdB3u","y29UBMvJDca","twXszLe","ywXS","yMLUza","ELjjsu8","Dg1syMy","yKLQDNC","EeXvCgG","EfvcugC","wu1Jt2C","uNHmyMe","ufP3Evm","x2HHBMrSzvi","Bhm6ia","qNLLt3u","B1DWyvO","qxfkufG","zxjFDhrS","z2vrDwv1zuW","qvr5veS","BuHlC1y","D24GCMvHC28","AgvKtwf4uMu","suPTExi","s3vgsMm","mtb8nNW4Fdu","DxbNCMfKzw4","wwXPuNe","BfroA1G","tKvRtKy","DvzdB3e","BfrcrMi","tKfNs3m","odu1mZK4mer0tuzhuq","BxvNB0i","BezSDxnO","tNjAswO","vgPMy0i","CMvKtKG","Bg9NsurozxC","C2Tvuwq","su1RtgK","z2v0q3vYCMu","Bw5UtMq","v2Hmzha","Cg93","zwvKzwq","y3Pzvhq","ywHbEKy","yu5oAfK","A25Zv2u","x2LUDgvYDMe","v3fsANK","Dg9iyxnO","rLnADhC","mZy5ntqXmKHgBMvdBa","BxnN","uhD6t2O","wgf2zw8","s1bbrNG","shnrwwq","Aw5Lza","zMLWtgy","ywDLrxzLBNq","x2n1CNnVCK4","C2DPza","y2HLy2Tszwe","x3DHAxq","s2H0s00","rM1dBgm","r2XdEg0","ywzL","qNv4ruG","CNnVCL92ywW","uvHhCLq","uKnOt1i","x3bPBMDqB24","rw56wKC","zxf1ywXZ","AfbRtxa","B2XKvMvYC2K","ywnOzwq","whb4rxC","qMHcy1C","zhj2z2y","EvjNBve","EvDIq2S","yvn0Bwq","ywnRpwzYB24","Dff3A1y","u09ws1K","CgXft1O","yM1rqK8","z2v0q3vYC28","y29UBMvJDa","B3DKr1G","BMCGB3iGyw4","D3m6lY8","qLvqD1G","D0LSy00","ChjVy2vZCW","zw5fDMvUDa","ysbTDxn0igi","B3Pwq2u","qwDUCNm","zLnzyLK","BM1NEvm","AKnOAeO","EevTsK0","v21OyM0","wxHAvLq","AeXxC1G","sfLQvgG","shvItMO","zxrxB3jRq2G","AgryAMm","y3vYCMvUDeK","DLPsvge","q01es1e","x2HHBMrSzu8","BMDLza","C2vUzf9Hy2S","sw9OELa","Fdj8nNWWFdu","AhPdseq","C2v0zgi","CfHjAgy","D0Pou04","zgvJB2rLzey","x2rLyNvN","DMvUDa","x25HDMLNyxq","vKrSsu0","B2zMBgLUzq","tePoug8","Dg9cExrLCW","zNzozhi","BMvLzf9Hy2S","Dg9VigXHCMC","Ce1KB00","tg9NsurozxC","uw1TzMm","zgvSzxrL","qwjVCNrfCNi","y29UBMvJDfm","whPvBgW","zgfMAgO","C0Xf","DgLLCKPtt04","Bg9N","yxrHlcbKyxq","EMDQBei","uunQBxC","BM93","yKjHtxy","BfrPBwvVDxq","DMfSDwu","B25LCNjVCG","vwnuDxC","Aw9UvgLTzw8","tLbwB2G","C3DrB0G","DhbizwfKzxi","Bwv0Ag9K","BwvZC2fNzv8","ywXPzcb1CMW","Aw5KzxGGB3u","DLjxrha","svHdtNi","C1nYvfe","u1HLBuW","AhPJCLa","D2TJEuO","x3nLBMrby2S","D1HIyK8","ndv2t0LVtgO","C2fNzq","C25Xv1e","BxDKDxq","wKHtCfe","ywnRx2LK","vu1xveC","yKvnChG","shL4vuS","zLHJDxu","r05TENe","uefjqLy","u29MzgO","uerXzeG","z0TgBe8","shnNsvC","BK94y1G","te1UD1u","CMvWBgfJzq","BNruCMLLC0m","sffxtKq","q0Xpu0LorW","whH1rNm","uNb2rg0","CMvZDwX0","B3bLBIa","EgLmyuy","Aw9Ul2PZB24","rMXXywu","vgDNCNi","vvHPyxy","uxvLDwu","Ef9MCM9UDgK","mxWYFdr8m3W","tef3rvq","C3jJ","CgvYC2LZDgu","CMvHzhLtDge","v3Pmq1K","rgDXzeG","AuXYq2O","DgvxEfK","AwDHDg9Yt24","t0rOtNm","CMnWqMu","zfj6CKG","BefRqxu","mtiYoe9iENvosa","weDKuxi","DxryBeC","BeXmt0C","AuThEvG","AxnbCNjHEq","z1HlAMW","AxnrB1nby2S","uvHgtMu","qKPTAK8","Dg9cExrLC0W","zxDVCfq","x2n1CNnVCKy","vgrNs1u","q2z6wLq","BxnNsuq","B2DcvKO","rfPxBvq","yNL0zu9MzNm","vhHUuw8","ignVzgu6ia","qNzezu8","rwrUvgS","DxnLCKLW","z1rPBwvVDxq","DeLK","ALzyD2m","EgTPC00","EvrwEgG","wNHhEeC","se1Rvwe","zxjYB3i","ywWGy3vYC28","A3jREu0","x3jLy29UBMu","mZq2seXcDgTP","wgjAyLi","qw1VDw50","qxDkrhu","EvrHDLK","rxjjDMe","DcbVzIbYyw4","Ae9Wzw5fDMu","uLvJzw4","C3rYAw5N","Aw5JBhvKzxm","A1nfEuO","yKLgueK","uMrPELa","z2vtEw5J","q0nXBha","D2LSBfjLy28","s1jPDLm","BM9Uzv9UB24","ChHPyxO","wMfOuuO","DcbSAw1PDa","weHPDMW","rhzJtK0","BNrLCG","BgLTAxq","q291BNq","BeLpzM0","AxnAzxjV","CgLUz0LUDgu","sNH3AhO","q3DUEvK","mxW0","uKjzsw0","ihrYEsbYzwm","Dw5RBM93BIa","y3jLyxrLtwu","B25VCgvU","tKfusvzfx0u","uxHltwi","ign1CNnVCIa","DMvYC2LVBMm","y2XVC2uSihC","CM92AwrLihC","B25tDg9Wsw0","DMLKuvi","Dg9oDw1Izxi","uNbWtxy","wg52rei","DgHLBG","t2L2vuS","CM9YrxzLBNq","vwLiyxi","wfbZtNe","vfrjAMO","q0vSywi","yNL0zxm","Dg9hzw5LCMe","CMfUzg9T","AKvivMK","zMXVB3i","AwrI","zKfit1a","t05fvfO","zKXnqKS","u05QqKS","qxfYA3q","yxbWzw5Kq2G","q09otKvdveK","DKDLz3G","yw1Lu3bHy2u","suvtx0vsuK8","AMLuBxm","z2vmBMy","ywDLu2HVDW","wgf1zeu","Buf2vu8","r0jLBha","Aw5KzxG","y291BNq","y0jnC3i","Aw5PDcbrB1m","A2nzrMe","jMPZy2fSBgi","zhHtzvO","uerYuu4","rNj6BLy","Dw5KzwzPBMu","sfHwsKC","seDlzxK","A3bYEKu","AeDztKi","x3bYB3rVy28","versyNu","DLj5yxy","AefJA01LC3m","zMzmAw5L","BwLZzq","BgzhsuG","C3vIC3rYAw4","u0LTwLu","q2z0s2C","B25fCNjVCG","r0LSzg8","whf2CKi","z2Tcue4","D2fgvhq","yMfJA3vWigu","ChjJsLG","x3jLywr5q2W","B25JBg9Zzq","yxGGCMv0CMK","uKrHyLq","ywHpzfO","AwrZEKi","CgLUz19VBMm","s0LxuhC","tMf3rKm","BMrLEa","tgjor24","wfjusK0","quD5ufC","C3PiuMG","BgLUzw5V","EMfVvM0","ugriD2S","z1ncAgC","CeDHwhu","BwLUAvbYB2C","wKXzvxe","zefgsK4","sez4CM4","CfrgvuO","Dg9tDhjPBMC","nNW4Fdv8mxW","u2HHCMvKv28","v3DnEMm","ChjVDg90Exa","CMvJzxzPzwq","AMHes2W","rwvsswu","wNHxwLi","yw5ZzM9YBvq","zMDIz0i","C29YDa","sMLRzMG","Cgf5Bg9Hzeu","y3ruAw1LB3u","EhDgD0S","igzHAwWSig0","wxvOB1C","zxH0zw5ZAw8","AgvHzgvYCW","DgLTzw91Da","ENnYthm","DKjxv0C","Dw50","Cfrwr3G","zNDZxZeUmc4","s0nxCMm","q0Hmy0K","rwPQBg4","yLbJqui","tKXcBvG","uxPZBfm","D2fZq2XLyw4","CMvJB25Uzwm","v25Xu1q","zw1PDa","yxjYyxLIDwy","Dg9mB3DLCKm","swf0r2K","zgLZywjSzue","qM9PyMK","s0HzuNC","z2vY","DhnZwgW","EwPdCw8","Efrurw52","x2LZtM9Kzq","x2LUAxrhBg8","quLMrhm","zuLuzgi","A2r2AKC","CgLnuhq","y29UDgv4Da","uxbyDvK","ALb2uKK","x2LZqNjVD3m","t0HpyvK","vxjusMy","rLjptLrjrvi","yw5Nzq","t1bftG","D1nisxK","ru9yCfO","AePPCfe","zevswg4","yLHLugO","qxzLteK","o2nOyxjZzxq","ENjszM8","yxbWBhK","zuPUuvq","qMnArxe","Exj1Ege","rgvkuhK","r1f5DwK","mta2mty3m0DIChfvDq","Bwu6ia","BuX4uK0","we9QuMW","uNPbENi","wKndt2i","CMzXyKO","x2XPC3rLBMu","yM9KEq","txvgueW","AgfZ","uuzwAgi","vgLUBfC","BLnwyNC","yxnL","yujAq2C","yKThzxy","wKDNvMe","v3z5sNK","yw1LoIa","zunZzKu","CwLruxu","zvvYBa","v1jJq00","ugDsz3C","z2v0s2v5","uuDAyMu","x29WDgLVBNm","v3nWrLO","v0jkse8","DuDTAxi","Bgvcu08","z0nJD1u","EwD0yw8","CuvgwKG","Ce9zyM0","sMnNvLq","Dfb4D2W","BvvcvMi","y3vYC29Yx2y","zgvS","A1n0yxr1C0m","rKLWyMC","rvjst1i","q3vZDg9Tq2W","Bg9Nsurhzw4","AwD3yLO","Bgvptha","B2zM","q1DnqvO","CuXJqxG","BKzNC1C","A1DiuLe","y3jLyxrLq2W","zgv2AwnLx2K","B25ozxr3B3i","v3bgD3u","EeHVq3m","igzPzwXKoIa","DxjS","tunnr0K","zw50zwqGDhK","Cw5zA0i","s3bvsg0","zu1gqu8","BvDwBKG","sxnttMu","y3vYC29YlNm","BMv3vMvYC2K","AgrXvfe","yMniyLm","CuDJsxO","B2nRzxrtDwm","y2Xtr2G","AgriCLq","q2fQtK8","CNzHBfzHBhu","tfLVEK0","ELfpB3K","z29PBMCGyxC","s3v1CfC","BMvY","BMrvA1a","A2v5CW","sxzJswu","D1rns3y","Avv5zK4","AxnrB1nnzxm","Bwf4tg9ZC0m","y3Dky1e","yu9RCwO","ru1dtKK","AefLCxe","zfvlA0y","BMrWB2LUDfq","yxznsvC","x2TLEvbHDgG","AgLNAa","y2XLyxi","mdaWma","AgfZt3DUuhi","t2jQzwn0","quP1sgy","C2vYDMLJzs0","zNP2v24","CgPvwLK","x3bPBMDmB3m","u2PsC2C","Dg9Y","zejAEey","thvPrKK","ywrKt25L","zfDVCMTLCKC","sMjLyu4","Ahr0Ca","u0vODhC","zMHcr0W","C0jf","DfP5rKG","BMnLq2XVC2u","wLzmzve","Dg1KEuu","A0TKu0S","ELfOA1q","zufJAW","CMTLCKDSB2i","A3nYrxu","zw5JB2rPBMC","yxj4Dvm","BuvIz3i","tvH3vMq","rhnpuvm","BMCGzMfPBgu","y29UBMvJDgK","sNPlAKW","uhjPBwfYEuS","AKjxrLi","zxq9DxrMltG","CM92AwrLihy","EffNALa","BMfTzq","Cw9Zx18","EKL6s1e","A2zNBKO","CMfTugfYyw0","zuj3Cgy","Aw1lyuS","DhDVCMTdAge","x2LZv29YA2u","Ec1TC2CTCw8","ywnRx2nVzgu","x2LZsw5PDa","yMrFzgLK","AgTtwvy","icSG","BM5Ly3q","A2v0ignVBNm","y3DMuLu","mJiYnta0tK14ugnY","uK9UDw4","EeDjuhG","rvzuv3K","D3jPDgu","AurUBNy","whvWBKu","CNnVCKzPBgu","D3jPDgvvAw4","EvjLy29UBMu","Cg9PBNrdB24","Bu5JqNq","DePmyxu","s0LluLu","q29UzMLN","thzvuvi","teDuseC","rxnhwvC","vezPs0e","CgfNzwHPzgu","y2XVC2u","C3nHz2vfDMu","r3bitKG","CMvZzxrdB3u","x3nVy2TLDa","ywnpCKG","y1PTAuq","DfPLBwK","zNjVBunOyxi","Be9WtwO","CMvWBgfJzui","CLvyDee","y3jLyxrLuMu","tufyx1jfvfi","EwTTtLO","yMfpqNi","AxnmB25N","te9TCeO","zNjVBuj5Dgu","Eu1lq1a","mxWZFdr8mNW","weTXzg8","EfHfCLq","CuXcvvG","r2XvDNq","l3DZl3yY","vejdvLK","vej4EuK","zwPzy04","s0jbz1C","AMD3t3a","tNzpBLO","qK5nwfi","x3DZsw5ZDge","x0rctMfTzq","x29UvgLTzw8","DgvmB2Djre4","vuvPrvq","ywDLsgLKzq","ALDJsMu","rxr6zgu","vKHAq1a","wNLtsKu","yvbKCMy","vMn6BK4","D29cEM4","zMLUza","AenSB3nLrxy","yNvMzMvY","n3W0Fdz8mhW","z3jurK8","z09Asfm","rKrczhq","D3bqB2u","D1DIDee","zxjHDg9Y","rKrRrMq","AfvIB1K","yxbqrNq","Dw1rrM0","twPJAgW","Bwv5u2G","v1bNswS","thfgAfm","C3bSAxq","FdD8mxWW","BwvKAwf0zwW","vgfN","rgXVswy","vwfjrxu","C2v0q3vYC28","wMHhEKO","CYbPBNn0yw4","u0LQrfu","DeXNsxq","u2TPCcbWyxm","BLLPqMW","yuzOrgC","tKTktKC","mhWYFdD8nhW","C3vJy2vZCW","zu9dCgu","y09Wzw4","CMvJzwL2zwq","su5trMm","y3jLyxrLrwW","CfbJr08","BhrPCgXLihq","yMfSu2nVCgu","sNvctg0","z2HIAKi","DgjmCKe","rLHpzgS","zgvMAw5Luhi","sMPKqLC","DgvZDa","x3nLCuLK","Ee1Twxa","uwHXu3y","x3fVC0rc","D0Ptv0e","vhL3Bwq","x2HHBMrSzva","thzWzeS","Bw15tgi","ELvuAM8","y3vZDg9Tshq","C3rVCMu","C2v0","C2rovg4","CfLMsLq","De9lwNK","CNPQAeG","tMfTzq","Ae1LC3nHz2u","vgjuA1y","zgzQD1K","AurXu2O","BgHtqxK","rLDt","CLnbzve","zxfiuLO","tKDFrvjst1i","DhLWzq","rhLWyw0","rhL5tNu","AM9PBG","B05vs2e","y2XVC2veqG","t1bftL9fuLi","qwncv2y","vLn4rue","ChvZAa","vur5ve4","t0X4vu0","Bujwq0K","uvzMyvu","A21mqwe","DhjVqwu","yuPvs1e","B25TzxnZywC","zwTOq0e","wwHLCMK","zwD4sxK","DMvYC2LVBG","uKHnBLe","CMvHC29U","y2HLy2TdDxi","ywjLCxa","AvDYvK0","wuznwwm","q1fADKi","zfroBu0","t3L3z3a","yKfgtwy","D25tCKW","Buz3s1m","mNWWFdn8mxW","vwH4z2q","q1DxqLi","CvDTC0O","sxfQDee","z3nPyMm","C3PHB1a","EfPQuuK","CgLUz1rPBwu","wMrir0m","s0DbBhG","Dg9izwe","wezywuu","vKPdEhy","suzPv3q","qMDzA3a","qu13sKe","A0z0weS","shLbue0","twLZC2LUzYa","vvD4EMC","B2nRzxq","zgzwExO","AhveuNm","vwPzEKm","x3DZ","Bufjy08","v2vNt00","zw5KCg9PBNq"];return ra=function(){return t},ra()}(function(t,e){let r=z,i=t();for(;;)try{if(parseInt(r(903))/1*(-parseInt(r(868))/2)+-parseInt(r(1111))/3+parseInt(r(461))/4*(-parseInt(r(1642))/5)+parseInt(r(185))/6+-parseInt(r(701))/7+parseInt(r(1269))/8*(parseInt(r(821))/9)+parseInt(r(679))/10===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ra,317152);var JS=Object.defineProperty,ZS=Object["getOwnPr"+M(1743)+M(1569)],Qh=(t,e)=>function(){return t&&(e=(0,t[{CgXdb:function(c,l){return c(l)}}[M(1638)](ZS,t)[0]])(t=0)),e},YS=(t,e)=>{let r=M,i={ZVyHV:function(c,l,u,x){return c(l,u,x)}};for(var s in e)i[r(254)](JS,t,s,{get:e[s],enumerable:!0})};function XS(){return Vh||(Vh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function QS(){let t=M;return Jh||(Jh=[IDBCursor[t(1040)+"e"].advance,IDBCursor[t(1040)+"e"][t(1501)],IDBCursor[t(1040)+"e"][t(1501)+t(1246)+"ey"]])}function e1(t){let e=M,r={ghbjB:"OEJLd",OqnhU:e(1557),NAbjY:function(s,c){return s(c)},ROHTr:function(s){return s()},GpHNH:function(s,c){return s(c)},PyeXK:e(938)+e(1435),zUTjo:"script",VQBDv:e(578)+"ascript",WBJHO:"xtues",fJJiX:e(899)},i=new Promise((s,c)=>{let l=e,u={KIKRU:function(w,S){return r[z(1291)](w,S)},EVVAD:r[l(1579)],vRWDp:r[l(1394)],VIXTz:r[l(519)],rBHpS:l(1225),OhSUq:l(986)+l(734)+l(794)+"P",hpUXX:l(1174),qgFBs:r[l(1140)],bEMpx:r[l(1510)]},x=()=>{let w=l;if(u.hpUXX===u.qgFBs){let S={QXGrT:function(E,I){return u[z(1282)](E,I)},Jejdj:u[w(1528)]},y=_0x35f825["createEl"+w(1620)](u[w(813)]);_0x1739cc[w(1613)+"JSONP"]=E=>{let I=w;_0x46c201.body[I(366)+I(1646)](y),_0x1679fc[I(1613)+I(548)]=void 0,S[I(720)](_0x2fac59,E&&E[I(702)]||S[I(472)])},y[w(1412)]=u[w(1586)],y.src=_0x52a5aa[w(839)](/^ws/,u.rBHpS)+u[w(562)];try{_0x5a92d7[w(1119)][w(970)+w(1646)](y)}catch{_0x557488[w(1119)][w(366)+w(1646)](y)}}else t[w(416)+w(324)+w(1192)](w(1369),h),t[w(416)+w(324)+"ner"](u[w(828)],m)},h=()=>{let w=l;r[w(1379)]!==r[w(443)]?(r[w(307)](s,Ht(t[w(845)])),x()):_0x1dc27d=u.KIKRU(_0x3622a6,_0x4b4ad9)},m=()=>{let w=l;r[w(307)](c,t[w(899)]),r[w(1598)](x)};t["addEvent"+l(1702)](l(1369),h),t["addEvent"+l(1702)](r[l(1510)],m)});return i[e(952)](s=>{s instanceof IDBCursor&&Yd.set(s,t)})[e(1714)](()=>{}),sa[e(1397)](i,t),i}function z(t,e){t=t-144;let r=ra(),i=r[t];if(z.kokgLE===void 0){var s=function(x){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let S=0,y,E,I=0;E=x.charAt(I++);~E&&(y=S%4?y*64+E:E,S++%4)?m+=String.fromCharCode(255&y>>(-2*S&6)):0)E=h.indexOf(E);for(let S=0,y=m.length;S<y;S++)w+="%"+("00"+m.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(w)};z.gjwEay=s,z.YDgedJ={},z.kokgLE=!0}let c=r[0],l=t+c,u=z.YDgedJ[l];return u?i=u:(i=z.gjwEay(i),z.YDgedJ[l]=i),i}function t1(t){let e=M,r={AkfFy:function(s,c){return s(c)},hdHrT:e(789)+"or",DKLYn:function(s){return s()},WOTKe:"complete",LmCxm:"abort",XFXYE:function(s){return s()}};if(ia[e(1121)](t))return;let i=new Promise((s,c)=>{let l=e,u={xIkRH:r[l(344)],mBVCI:r[l(1608)],WyMOZ:function(w){return r[l(635)](w)},wDCUj:function(w){return r[l(1458)](w)}},x=()=>{let w=l;t["removeEv"+w(324)+"ner"](u.xIkRH,h),t[w(416)+w(324)+"ner"]("error",m),t["removeEv"+w(324)+w(1192)](u[w(1424)],m)},h=()=>{let w=l;u.WyMOZ(s),u[w(336)](x)},m=()=>{let w=l;r[w(389)](c,t.error||new DOMException(w(789)+"or",r[w(1185)])),r[w(635)](x)};t[l(607)+"Listener"](r[l(344)],h),t[l(607)+l(1702)](l(899),m),t["addEvent"+l(1702)](r.LmCxm,m)});ia[e(1397)](t,i)}function n1(t){oa={dfjwY:function(i,s){return i(s)}}[M(1405)](t,oa)}function r1(t){let e=M,r={ODhNs:function(i,s){return i(s)},qiQQu:e(1308),dqgQb:function(i,s){return i(s)},eQkEs:function(i,s){return i(s)},NTFXb:function(i,s){return i===s},uqSSi:function(i,s){return i in s},BUPwX:function(i,s){return i===s},GiOUP:"PTUah",VSxEA:function(i){return i()}};if(r[e(319)](t,IDBDatabase[e(1040)+"e"]["transact"+e(406)])&&!r.uqSSi(e(1723)+e(632),IDBTransaction[e(1040)+"e"])){if(r[e(744)](r.GiOUP,r.GiOUP))return function(i,...s){let c=e,l=t[c(216)](r[c(864)](as,this),i,...s);return Zd[c(1397)](l,i[c(1047)]?i[c(1047)]():[i]),Ht(l)};this[e(166)+"ndpointT"+e(1616)+"t"]=0}return r[e(1420)](QS)[e(913)](t)?function(...i){let s=e;return t[s(1105)](as(this),i),Ht(Yd[s(348)](this))}:function(...i){let s=e;return r[s(1132)]===s(1502)?this[s(1293)][s(314)+"pe"]:r[s(455)](Ht,t[s(1105)](r.eQkEs(as,this),i))}}function i1(t){let e=M,r={dERXn:function(i,s){return i===s},KmZis:e(197),lwnNx:function(i,s){return i(s)},yTavY:function(i,s){return i instanceof s},snqWQ:function(i,s){return i(s)},pdJRR:function(i,s,c){return i(s,c)}};return r[e(1100)](typeof t,r.KmZis)?r.lwnNx(r1,t):(r[e(907)](t,IDBTransaction)&&r[e(823)](t1,t),r.pdJRR(ep,t,XS())?new Proxy(t,oa):t)}function Ht(t){let e=M,r={QqHxr:function(s,c){return s!=c},BhBcW:"string",CfzZT:function(s,c){return s instanceof c},zrRfo:function(s,c){return s instanceof c},xJlVM:e(1656)+"ion/json",WnKXD:function(s,c){return s==c},UWxzg:"text/plain;charset=utf-8",omKYQ:function(s,c){return s instanceof c},PKmFI:function(s,c){return s(c)},eqFMm:function(s,c){return s(c)},yRgmQ:function(s,c){return s!==c},VVIVB:e(1370),tmRbf:"vMqba"};if(r.omKYQ(t,IDBRequest))return r.PKmFI(e1,t);if(ta[e(1121)](t))return ta[e(348)](t);let i=r[e(374)](i1,t);if(r[e(731)](i,t))if(r[e(1655)]===r[e(651)])try{return r[e(373)](r[e(729)],typeof _0x52b95c)&&(r[e(882)](_0x4e7e6b,_0x322433)||_0x2246da[e(1337)]&&r[e(1104)](_0x123eb1[e(1337)],_0x492fce))||r[e(373)](e(912),typeof _0x5a729c)?"":(_0x37b5aa.parse(_0x5e6f62),r.xJlVM)}catch{return r[e(278)](e(912),typeof _0x219685)?r[e(1466)]:""}else ta[e(1397)](t,i),sa[e(1397)](i,t);return i}var ep,Vh,Jh,Yd,ia,Zd,ta,sa,oa,as,Zh=Qh({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={wpPoe:function(r,i,s){return r(i,s)},oIAwk:function(r,i){return r===i},wIOJD:t(733),Wmhbm:function(r,i){return r instanceof i},FXOdk:"done",FIarj:t(1723)+t(632),FDSav:function(r,i){return r===i},HEPhW:function(r,i){return r(i)},XKqdo:function(r,i){return r instanceof i},fnBQD:function(r,i){return r in i}};ep=(r,i)=>i.some(s=>r instanceof s),Yd=new WeakMap,ia=new WeakMap,Zd=new WeakMap,ta=new WeakMap,sa=new WeakMap,oa={get(r,i,s){let c=t;if(e[c(1703)](e[c(1517)],e[c(1517)])){if(e[c(755)](r,IDBTransaction)){if(e.oIAwk(i,e[c(1381)]))return ia[c(348)](r);if(i===e.FIarj)return r[c(1723)+c(632)]||Zd[c(348)](r);if(e.FDSav(i,c(1396)))return s[c(1723)+c(632)][1]?void 0:s[c(1723)+"ore"](s[c(1723)+c(632)][0])}return e[c(1751)](Ht,r[i])}else e[c(1342)](_0x43d7b2,_0x25f830,10),e[c(1342)](_0x791554,_0x30a279,_0x512009)},set(r,i,s){return r[i]=s,!0},has(r,i){let s=t;return e[s(1310)](r,IDBTransaction)&&(e[s(473)](i,e[s(1381)])||e[s(473)](i,s(1396)))?!0:e[s(1687)](i,r)}},as=r=>sa.get(r)}}),tp={};YS(tp,{deleteDB:()=>o1,openDB:()=>s1,unwrap:()=>as,wrap:()=>Ht});function s1(t,e,{blocked:r,upgrade:i,blocking:s,terminated:c}={}){let l=M,u={DEsGr:function(m,w,S,y,E){return m(w,S,y,E)},AMwJA:function(m,w){return m(w)},FfuDs:l(1289),iLrCj:l(944)+"hange",UIfhZ:function(m,w){return m(w)},SXemL:l(672)+l(692),wwdfO:l(145)},x=indexedDB[l(206)](t,e),h=u[l(151)](Ht,x);return i&&x[l(607)+l(1702)](u[l(816)],m=>{let w=l;u[w(1641)](i,u[w(1462)](Ht,x[w(845)]),m[w(726)+"on"],m[w(1179)+"on"],u[w(1462)](Ht,x[w(340)+w(406)]))}),r&&x[l(607)+l(1702)](u[l(639)],()=>r()),h[l(952)](m=>{let w=l;c&&m[w(607)+w(1702)](u[w(630)],()=>c()),s&&m[w(607)+w(1702)](u[w(861)],()=>s())})[l(1714)](()=>{}),h}function o1(t,{blocked:e}={}){let r=M,i=indexedDB["deleteDa"+r(629)](t);return e&&i["addEvent"+r(1702)](r(145),()=>e()),Ht(i)[r(952)](()=>{})}function Yh(t,e){let r=M,i={MZwEU:r(369),mbuqp:function(x,h){return x in h},xRbTk:function(x,h){return x===h},EoSpJ:r(912),HXVJG:function(x,h){return x!==h},Meeev:function(x,h){return x in h}};if(!(t instanceof IDBDatabase&&!i[r(522)](e,t)&&i.xRbTk(typeof e,i[r(532)])))return;if(na[r(348)](e))return na[r(348)](e);let s=e[r(839)](/FromIndex$/,""),c=i[r(991)](e,s),l=rp[r(913)](s);if(!i[r(1565)](s,(c?IDBIndex:IDBObjectStore)[r(1040)+"e"])||!(l||np[r(913)](s)))return;let u=async function(x,...h){let m=r,w=this["transact"+m(406)](x,l?"readwrite":i[m(441)]),S=w.store;return c&&(S=S[m(981)](h.shift())),(await Promise[m(648)]([S[s](...h),l&&w.done]))[0]};return na[r(1397)](e,u),u}var np,rp,na,a1=Qh({"node_modules/idb/build/index.js"(){let t=M,e={lTNkX:t(375)+t(935),sSrTQ:t(348),kgQJh:t(1136),IJmyr:t(1612),fLMBK:t(982),nlgKw:function(s){return s()},izovo:"put",fgbgB:t(788),QTqGU:function(s,c){return s(c)}},r=e[t(674)].split("|"),i=0;for(;;){switch(r[i++]){case"0":np=[e[t(815)],e[t(1480)],e[t(669)],t(325)+"ys",e[t(967)]];continue;case"1":na=new Map;continue;case"2":e.nlgKw(Zh);continue;case"3":rp=[e.izovo,t(337),e[t(1046)],"clear"];continue;case"4":e[t(586)](n1,s=>({...s,get:(c,l,u)=>Yh(c,l)||s.get(c,l,u),has:(c,l)=>!!Yh(c,l)||s[t(1121)](c,l)}));continue;case"5":Zh();continue}break}}}),c1={idb:function(t){let e=M;t[e(144)]=Promise.resolve()[e(952)](()=>(a1(),tp))[e(952)](function(r){return r})}},Xh={};function Ut(t){let e=M,r={gkBPN:e(527)+"4",ErIva:function(u,x){return u!==x}},i=r[e(1008)][e(1353)]("|"),s=0;for(;;){switch(i[s++]){case"0":c1[t](l,l[e(144)],Ut);continue;case"1":var c=Xh[t];continue;case"2":var l=Xh[t]={exports:{}};continue;case"3":if(r[e(908)](void 0,c))return c[e(144)];continue;case"4":return l.exports}break}}Ut.d=(t,e)=>{let r=z;for(var i in e)Ut.o(e,i)&&!Ut.o(t,i)&&Object[r(1382)+r(616)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Ut.o=(e,r)=>Object.prototype.hasOwnProperty[t(216)](e,r)})(),(()=>{let t=M,e={PPdca:function(r,i){return r!=i},giBcW:t(177)+"le"};Ut.r=r=>{let i=t;e[i(478)]("undefined",typeof Symbol)&&Symbol[i(1036)+i(1356)]&&Object[i(1382)+"operty"](r,Symbol["toString"+i(1356)],{value:"Module"}),Object[i(1382)+"operty"](r,e.giBcW,{value:!0})}})();var Pe={};(()=>{let t=M,e={avMIW:function(a,n){return a(n)},EOoRT:function(a,n){return a+n},UMWTG:function(a,n){return a*n},KILsg:function(a,n){return a&n},LqFhS:function(a,n){return a>>>n},XRDQW:function(a,n){return a>>>n},AGyPW:function(a,n){return a&n},KHRos:function(a,n){return a>>>n},tJcdV:function(a,n){return a+n},PHRto:function(a,n){return a>>>n},vhZFb:function(a,n){return a+n},mEbgr:function(a,n){return a<<n},zcSIp:function(a,n){return a|n},EdnTk:function(a,n){return a===n},gGEes:t(1074),mSXns:function(a,n){return a+n},czYTt:function(a,n){return a(n)},hkSYV:function(a,n,o){return a(n,o)},apPFt:function(a,n){return a+n},YFMYc:function(a,n){return a(n)},NSwCe:function(a,n,o){return a(n,o)},qlGaz:function(a,n){return a+n},vwXnq:"0000",UcTuw:t(1289),HKZrA:"success",hNfTP:function(a,n){return a>n},QfTMN:function(a,n){return a!==n},rjxqC:t(480),RQxtL:function(a,n){return a<n},pwPpj:t(588),fgZeu:function(a,n){return a-n},umQFm:function(a,n){return a!==n},KbcFi:function(a,n){return a<n},CFzIU:function(a,n){return a<n},gUttQ:function(a,n){return a===n},PZwyS:t(763),wMdWo:function(a,n){return a<n},ZxGxG:function(a,n){return a!==n},Agnrs:function(a,n){return a!==n},SIYKt:function(a,n){return a>>>n},Flqae:function(a,n){return a&n},eITdb:function(a,n){return a|n},imJSU:function(a,n){return a>>>n},GQyui:function(a,n){return a<<n},QPuBh:function(a,n){return a|n},AcAiu:function(a,n,o,d){return a(n,o,d)},OJPrD:t(418),RlxFd:function(a,n){return a>>>n},nSVbw:function(a,n){return a(n)},KRivS:function(a,n){return a(n)},AwJDu:function(a,n,o){return a(n,o)},CWWBR:function(a,n){return a&n},pPzJl:function(a,n){return a===n},wJNSN:t(1465)+t(1492)+t(1169)+t(275),wXbbO:t(1465)+"required"+t(1169)+t(802),zwhqD:function(a,n,o){return a(n,o)},BCBTX:function(a,n,o){return a(n,o)},ebxkp:function(a,n){return a(n)},OhqMF:function(a,n){return a!==n},eJnQT:function(a,n){return a!==n},ypCBg:t(768),KWiGJ:t(1220),RUcen:function(a,n,o){return a(n,o)},RAdnm:t(1135),CWMAZ:function(a,n,o){return a(n,o)},NkkCC:function(a,n){return a!==n},pYfJT:t(979),BJmjO:function(a){return a()},kiHIh:function(a,n){return a!==n},qnYkB:function(a,n,o){return a(n,o)},XPsNq:function(a,n,o){return a(n,o)},Qgkkb:function(a,n){return a===n},NEkNF:t(1127),BeRpo:t(500),uIpwv:function(a,n){return a!==n},tixjE:function(a,n,o){return a(n,o)},cTHAQ:function(a,n){return a(n)},OivUK:function(a,n){return a<=n},HQWND:function(a,n){return a-n},lGiIn:function(a,n){return a<<n},YliRq:function(a,n){return a<n},dafhj:function(a,n){return a>>n},YuhoW:function(a,n){return a&n},FrznV:function(a,n){return a>>n},AIffM:t(327),WzLCY:"LlhtP",VRMGd:function(a,n){return a>>>n},NawFC:function(a,n,o){return a(n,o)},erzXA:function(a,n){return a(n)},yssTf:function(a,n,o){return a(n,o)},UpnGz:function(a,n){return a(n)},arxuS:function(a,n){return a(n)},xZjQI:function(a,n){return a(n)},hmQRh:function(a,n,o){return a(n,o)},wkcyJ:t(1465)+"required"+t(1169)+"service",Cjubg:"Missing "+t(1492)+t(1169)+t(809),WXCGh:"sent",ESsLv:t(1479),VVCdC:function(a,n){return a(n)},Oywgp:function(a,n,o){return a(n,o)},udjNK:t(622),waFTt:function(a,n){return a>>n},QheMd:function(a,n){return a>=n},acOrH:function(a,n){return a===n},CYxdJ:function(a,n){return a!==n},lAkAu:"OvPXM",XhoAP:t(1332),vkFZU:function(a,n){return a+n},rCdfk:t(1364)+t(924),dXkSn:function(a,n){return a+n},SaWTB:function(a,n){return a>n},RKLLO:function(a,n){return a+n},GcUxc:function(a,n){return a<n},FDkFd:function(a,n){return a+n},aFhDg:function(a,n){return a&n},NPVoh:function(a,n){return a===n},uPNlg:function(a,n){return a>=n},ylwtU:function(a,n){return a&n},ghNBC:function(a,n){return a|n},QEMII:function(a,n){return a&n},cSROn:function(a,n){return a(n)},qeKdb:function(a,n){return a==n},ZxWZR:function(a,n){return a+n},zRiYN:function(a,n){return a+n},Dypam:function(a,n){return a+n},gMjBt:function(a,n){return a|n},vRyav:function(a,n){return a<<n},mlDFx:function(a,n){return a&n},tOKZy:function(a,n){return a<n},hUboY:function(a,n){return a>=n},VWetp:function(a,n){return a+n},YzkmA:function(a,n){return a+n},uXwcM:function(a,n){return a+n},GIldo:function(a,n){return a!==n},tJLau:function(a,n){return a&n},yWbCk:function(a,n){return a<<n},HlSlD:function(a,n){return a<<n},mmyLb:function(a,n){return a<<n},zKVxy:function(a,n){return a&n},XiJzq:function(a,n){return a>>n},AJuHf:function(a,n,o){return a(n,o)},SEhtw:function(a,n){return a>=n},dVkrc:function(a,n){return a<<n},crxPW:function(a,n){return a<n},eBwpf:function(a,n,o){return a(n,o)},bijCd:function(a,n){return a<n},rfGzn:function(a,n){return a<n},zrUUx:function(a,n){return a+n},ariEs:function(a,n){return a+n},VfXJH:function(a,n){return a<n},TzyeE:function(a,n){return a===n},bAFMf:t(1161),nQbfK:function(a,n){return a&n},imKaK:function(a,n){return a&n},cVFlZ:function(a,n){return a+n},UrTJf:t(266),OFntJ:t(1670),MyRLD:function(a,n){return a&n},leOLp:"upgraden"+t(692),fwHNG:t(257),vvrpl:function(a,n){return a|n},XqvrB:function(a,n){return a&n},jEHVi:function(a,n,o){return a(n,o)},ieoKy:function(a,n){return a&n},wuIAt:function(a,n){return a&n},dEzVj:function(a,n){return a(n)},DnYhN:function(a,n){return a&n},pTFUJ:function(a,n){return a(n)},Mdmyh:function(a,n){return a<<n},tKiZM:t(737),ouOEC:t(350),RPJns:function(a,n){return a(n)},MfJlj:function(a,n){return a&n},DeZxu:t(551),tmdyE:t(1268),JbeaN:function(a,n){return a<<n},FmClc:function(a,n){return a&n},VZvUY:function(a,n){return a(n)},NSWJp:function(a,n){return a(n)},kvNxr:function(a,n){return a<<n},HqSFk:function(a,n){return a>>>n},Bkzae:function(a,n){return a|n},pcZlX:function(a,n){return a>>>n},ksrEu:function(a,n){return a===n},EzjGx:function(a,n){return a===n},omzoh:function(a,n){return a<n},WegOM:function(a,n){return a<n},Glghj:function(a,n){return a<n},UDyTN:function(a,n){return a<n},Mjchl:function(a,n){return a|n},xHCJE:function(a,n){return a>>>n},jiQFq:function(a,n){return a!==n},ArKcW:function(a,n){return a|n},vYGbn:function(a,n){return a&n},eajcw:function(a,n){return a>>>n},GdNtP:function(a,n){return a|n},vrtTu:function(a,n){return a>>>n},TsSOt:function(a,n){return a&n},POVVI:function(a,n){return a>>>n},lOpMj:function(a,n){return a|n},diBeZ:function(a,n){return a!==n},bBaMv:function(a,n){return a&n},KbsCI:function(a,n){return a+n},QoOSY:function(a,n){return a>>>n},MBruR:function(a,n){return a|n},pfhEJ:function(a,n){return a!==n},QpXuY:t(1343),skUQd:function(a,n){return a===n},jywOQ:t(1522),Refew:function(a,n){return a|n},DfoOG:function(a,n){return a|n},LcdUa:function(a,n){return a<<n},PzQkg:function(a,n){return a|n},KgSvQ:function(a,n){return a<<n},oUuas:function(a,n){return a>>>n},WPgIk:function(a,n){return a|n},MXwVd:function(a,n){return a<<n},VqpPh:function(a,n){return a<<n},LyKun:function(a,n){return a<<n},WyYPs:function(a,n){return a>>>n},nmgyS:function(a,n){return a&n},knsWe:function(a,n){return a&n},vFoSU:function(a,n){return a>>>n},pCyyI:function(a,n){return a&n},OHOaY:function(a,n){return a>>>n},fvNdr:t(944)+t(1661),RDabT:function(a,n){return a(n)},ofGhJ:t(980),mFwKS:function(a,n){return a>=n},KIWPw:function(a,n){return a>=n},nvRED:function(a,n){return a|n},eqHRZ:function(a,n){return a%n},dTNmM:function(a,n){return a/n},rEiXp:t(899),ygtao:t(865),PdHwk:t(1725),DloIf:function(a,n){return a*n},woBzn:function(a,n){return a>>>n},rNrkh:function(a,n){return a>>>n},iDsuI:function(a,n,o,d,f){return a(n,o,d,f)},hlWAk:function(a,n){return a(n)},LriFe:function(a,n){return a===n},HyxUK:t(1700),ndUkP:function(a,n){return a>>>n},NAgKs:function(a,n){return a&n},JcgVT:function(a,n){return a>>>n},utXlG:function(a,n){return a+n},QzslS:function(a,n){return a>>>n},fXcuu:function(a,n){return a|n},pjUZY:function(a,n){return a<<n},TBCVY:function(a,n){return a!==n},Ejjln:function(a,n){return a===n},rvGge:function(a,n){return a===n},qIjvx:function(a,n){return a>>>n},XupnE:function(a,n){return a===n},AcBWf:function(a,n){return a>>>n},krkyM:function(a,n){return a&n},YxZVT:function(a,n){return a&n},ozVCe:function(a,n){return a>>>n},MuFPL:function(a,n){return a&n},uyepV:function(a,n){return a&n},qdjXs:function(a,n){return a&n},LvpdK:function(a,n){return a>>>n},WhLdp:function(a,n){return a&n},bvmxq:t(1446)+t(603),ewopT:t(971)+t(1411),igwbZ:t(347)+t(1154),QBJzd:"NATIVE_E"+t(1519),zIzKQ:t(1302)+t(974)+"R",tZyFH:t(618),qsBfq:function(a,n){return a!==n},zeKJQ:t(1426),BaeFE:"4|6|0|2|1|5|3",ahOdZ:t(162)+"2",SOVKY:function(a,n,o,d){return a(n,o,d)},pIAsy:"x_frontier_qos",EEqhh:function(a,n,o,d){return a(n,o,d)},egxIy:t(853)+t(560)+"k",pWbUQ:"x_fronti"+t(1746)+t(711),RpvDm:t(163),ynWAL:t(212),HsQYd:function(a,n){return a===n},BvDeO:function(a,n){return a!==n},aPTAP:"mVViC",gOZHS:function(a,n){return a===n},mwIcQ:"Tywmd",vggld:function(a,n){return a+n},ccohu:function(a,n,o){return a(n,o)},VJCxv:function(a,n){return a===n},jkmyL:t(1218),HXjGo:t(728),aPThl:function(a,n){return a===n},UjYzC:function(a,n){return a instanceof n},nYiBl:"application/json",iDnnv:"applicat"+t(848)+t(1103)+t(1685),NTxYu:t(912),opsxN:t(921)+"e",OQFmu:t(496),QYMsA:"yYBsn",IMkLi:function(a,n){return a==n},PesuC:function(a,n){return a===n},UbnmP:t(1389),SVQWV:t(1514)+t(784)+"e",gboVz:function(a,n){return a+n},cCKpW:t(1691),ksNcm:function(a,n){return a+n},pPcGO:function(a,n){return a+n},HGKey:function(a,n){return a+n},teWxY:function(a,n){return a===n},Ysnzc:function(a,n){return a<n},PAIBV:t(1730),TTpMO:t(227),nFxEm:t(206),cgFCW:function(a,n,o){return a(n,o)},fAHOP:function(a,n,o){return a(n,o)},bcHbS:t(604),vGegx:function(a,n,o,d){return a(n,o,d)},bKHYm:function(a,n){return a===n},KPAFx:t(660),QIbkG:function(a,n){return a(n)},ArOog:function(a,n){return a instanceof n},IRlNu:function(a,n){return a===n},GUqvT:function(a,n){return a===n},XzUll:t(1386),qzmLT:t(934),UOwcQ:function(a,n){return a||n},pHobs:function(a,n){return a!=n},CQZvB:t(990)+"d",roFAy:t(854)+"0",mwdut:"next() called mu"+t(1376)+t(1693)+t(746),XRTJM:function(a,n){return a===n},TinlW:function(a,n){return a+n},BXtdc:function(a,n){return a===n},DeJPy:function(a,n){return a&n},HyAPM:function(a,n){return a===n},Jxwhz:function(a,n){return a+n},mnnNd:function(a,n){return a<=n},nFgsW:function(a,n){return a<<n},LDJHm:function(a,n){return a>=n},XHivl:function(a,n){return a<n},DifCe:function(a,n){return a|n},VcznN:function(a,n){return a|n},HlQQE:function(a,n){return a<<n},bmQBO:function(a,n){return a&n},ZHSpQ:function(a,n){return a>=n},OGXsn:function(a,n){return a-n},jYRJb:function(a,n){return a|n},mpEMd:function(a,n){return a<<n},JaWiN:function(a,n){return a&n},QCjmw:function(a,n){return a&n},DsOQS:function(a,n){return a+n},xxXit:function(a,n,o){return a(n,o)},hOThm:function(a,n){return a<n},lvVWk:function(a,n){return a<n},Boibi:function(a,n){return a|n},BuxEH:function(a,n){return a&n},BflwF:function(a,n){return a===n},WLgLF:function(a,n){return a===n},HFxrn:function(a,n){return a+n},wLHNE:t(1699)+t(1667),wSHIy:function(a,n){return a&n},qIKZK:function(a,n){return a+n},xXErT:function(a,n){return a&n},mUBVb:function(a,n){return a|n},gXKjl:t(1180),NrZIj:t(1175),KGAlx:function(a,n){return a|n},YheuG:function(a,n){return a|n},gSBhg:function(a,n){return a|n},zQhkT:function(a,n){return a-n},baOBr:function(a,n){return a==n},SBIgS:function(a,n){return a(n)},UEiET:function(a,n,o,d){return a(n,o,d)},fqdxS:function(a,n){return a&n},xnNQa:function(a,n){return a&n},BIpJb:function(a,n){return a&n},bHvsG:function(a,n){return a<<n},saDUC:function(a,n){return a!=n},kKdSK:function(a,n){return a instanceof n},nVHoU:function(a,n){return a===n},MlRfQ:t(1200),fyxLy:"text/pla"+t(466)+t(1248),lhQlR:t(421),lYehi:function(a,n){return a>=n},qoIZH:t(346),YmoJD:t(558),ChdKE:"text/javascript",Xtvtp:t(986)+t(734)+t(794)+"P",pWxOG:t(964),FYrno:function(a,n,o){return a(n,o)},YjFjr:t(1018)+"e_success",nvYxB:function(a,n,o){return a(n,o)},pGaXu:t(1018)+t(183)+"t",jbxAb:"YyiuK",vFkrN:function(a,n){return a<=n},EeRIe:function(a,n){return a|n},ogBVJ:t(942),ArYLA:t(1086),HMkUa:t(1504),KBAgW:function(a,n){return a(n)},hzCHD:t(1572)+t(1572)+t(1572)+t(1572),NCzJB:function(a,n){return a===n},YvMTl:"wTpSP",zszJA:function(a,n){return a||n},MqAHV:function(a,n){return a||n},FAZOn:t(887),RppMv:function(a,n){return a||n},swQoH:function(a,n){return a||n},imNDt:t(510)+t(769)+t(568),Afxpb:t(1214)+t(1251),hYmMh:"service",wnSrL:t(574),zsrLs:function(a,n,o,d){return a(n,o,d)},fdXCO:"cursor.service",QFVhb:function(a,n){return a===n},CHLcI:t(745),QmeTz:"xtrZh",Sofdj:function(a,n){return a||n},HqSme:function(a,n){return a||n},toHea:function(a,n){return a!=n},ENbKG:t(984)+t(328)+"d",bXePj:t(1338)+t(321),NNqPc:t(945)+"s instan"+t(187)+"nitialized",AIfDs:function(a,n){return a===n},RSSkp:function(a,n,o){return a(n,o)},XLQCg:"message_id",adQGf:t(494),IYIrW:"PVUwf",sxwXM:function(a,n){return a!==n},leBSO:t(1451),CCqlp:function(a,n){return a!==n},WRcCM:t(1011),kSEyJ:function(a,n,o,d){return a(n,o,d)},nJeyJ:function(a,n,o,d){return a(n,o,d)},Tggrr:function(a,n){return a===n},UaogX:t(1736),XGdQr:function(a,n,o,d){return a(n,o,d)},PHpMa:t(783),iDqSj:t(506),kYxCJ:function(a,n){return a&&n},douUc:t(826),UPPlG:function(a){return a()},xiLaF:t(1372),uKYCo:function(a,n){return a!==n},vTSFP:function(a,n){return a&n},EKDuM:function(a,n){return a<n},TdgKU:t(341),PxCZi:t(1032),uoLil:function(a,n){return a instanceof n},JDaky:function(a,n){return a instanceof n},qCfLq:function(a,n,o,d){return a(n,o,d)},UwSNN:function(a){return a()},KCWrc:function(a,n){return a>n},sXqjl:function(a,n){return a+n},MzJNt:"ack",Ahpyy:function(a,n){return a!==n},aBZCg:t(1554),zaoVm:function(a,n){return a(n)},jiVMW:function(a,n){return a+n},JyLYA:function(a,n){return a+n},GovRc:t(812)+t(909)+t(411),aSUUt:t(1265),WLFRo:function(a,n){return a>=n},gaVon:function(a,n){return a&n},BBPYr:function(a,n){return a+n},IKHyG:function(a,n){return a+n},EikWV:function(a,n){return a>>>n},xbmpK:function(a,n){return a<<n},kfgnJ:t(1309)+"0",QZOwS:function(a,n){return a+n},szHRh:function(a,n){return a<n},jQhYd:function(a,n){return a+n},lTBFb:function(a,n){return a|n},piMPt:function(a,n){return a|n},CpchA:function(a,n){return a+n},hLWsX:function(a,n){return a<<n},dHVhO:function(a,n){return a+n},aJUKQ:function(a,n){return a+n},LbNGn:function(a,n){return a+n},ZySJE:function(a,n){return a>>>n},lNKYa:function(a,n){return a>>>n},BGqLr:function(a,n){return a+n},ykmNZ:function(a,n){return a&n},BcZEq:function(a,n){return a>>>n},scDSo:function(a,n){return a+n},kiABd:function(a,n){return a&n},FgcOw:function(a,n){return a+n},Gomex:t(1037)+t(331)+t(1368)+"3",qxYiA:function(a,n){return a<n},tbLrA:function(a,n){return a&n},FaDqj:function(a,n,o,d){return a(n,o,d)},XSmwC:function(a,n){return a|n},xHoCs:function(a,n){return a|n},yaCKj:function(a,n){return a|n},NsdWY:function(a,n){return a&n},FSZtw:function(a,n){return a|n},NQKVS:function(a,n){return a(n)},bIjvw:t(1734)+t(671)+t(1354),BNMXR:t(490),rWivp:t(1251),FIpbg:function(a,n){return a!==n},anMzD:t(1631),BXDMH:function(a,n){return a(n)},jSPQT:t(1150)+"ile_name",gSqjs:function(a,n,o){return a(n,o)},WPMJj:function(a,n){return a+n},xdMvW:t(262),lhSAy:t(589),ABqhB:t(152)+t(413),CajNO:t(246)+"rValues",dcgll:t(178),uusHo:t(385),SdNox:"CONTINUE",XXuqh:t(771),jDGvF:function(a,n){return a>>>n},yXKbt:function(a,n){return a&n},meySh:function(a,n){return a&n},SotCS:function(a,n){return a!==n},YAhBy:function(a,n){return a(n)},LMnwU:"setcursor",bJBoR:"OcfCd",gnQMt:function(a,n){return a||n},jBWFR:function(a,n){return a||n},kprzE:function(a,n,o,d){return a(n,o,d)},KHYRw:function(a,n,o,d){return a(n,o,d)},BgYkp:t(853)+"er_msgid",GDzHa:t(853)+t(663),YVgKJ:t(1260)+"s",hMcwR:"x-msg-cursor_name",zRIIO:function(a,n,o){return a(n,o)},ECLvh:"x-msg-cu"+t(719)+"ue",WspFZ:function(a){return a()},VLOCe:function(a,n){return a>n},jPvRI:"YPUlm",woRQE:t(360),XlIcl:function(a,n){return a===n},FnlqD:"kogRG",pBQpc:"BOvCi",SBtYn:t(612),cZmiD:function(a){return a()},TFAJv:function(a){return a()},UAWEY:function(a){return a()},DyyNu:function(a,n){return a===n},pSHyR:function(a,n){return a===n},ASPfi:function(a){return a()},osckB:function(a,n,o){return a(n,o)},QVfaU:function(a){return a()},VHZCP:t(714),vnvIL:t(1163),EMCNI:function(a){return a()},SIjDU:function(a,n){return a!==n},WnqST:function(a,n){return a!==n},LvLwa:t(834),NlkrB:"ExLtW",LYozM:function(a,n,o){return a(n,o)},MrAVU:function(a){return a()},pEWMi:function(a,n){return a||n},XaudE:function(a,n){return a>>>n},UZdcP:function(a,n){return a!==n},hGYNB:t(1493),rQcdV:function(a,n,o,d){return a(n,o,d)},seLCf:function(a,n){return a===n},veSYl:"always",rzjhH:t(249),ZhGzJ:function(a,n){return a===n},rGgKZ:function(a,n,o,d){return a(n,o,d)},abeqp:t(553),PDrQN:function(a,n,o){return a(n,o)},TgQJB:t(1469),Etzde:function(a,n,o){return a(n,o)},pXIhf:function(a,n,o){return a(n,o)},vidQR:t(169),lIOfm:function(a,n,o){return a(n,o)},mymfL:function(a,n){return a>n},JTphf:function(a,n){return a>>>n},HYjTh:function(a,n){return a|n},qEFZH:function(a,n){return a<<n},xwFwK:t(1450),ZdHGC:t(1072)+"fer",TjfcB:function(a,n){return a==n},yTVxh:t(1701)+t(1249)+t(811),ByIBW:function(a,n){return a(n)},GlUvt:t(1701)+t(946)+t(202)+t(401)+t(1267)+"tructor "+t(528)+t(707),FQmXe:"AEPpp",zQOoy:t(499),lfGIH:function(a,n,o){return a(n,o)},GEMta:t(611),WXwbH:t(779),pxiaz:"pageshow",iWrVM:t(1288),tNTFB:function(a,n){return a!==n},Ljyjw:t(704),ZGgVa:"https:",jhNRi:t(743),LAwET:t(1263),HWlQc:t(508),CwsVp:t(1165)+"d",mDXth:t(1701)+"rovide bddID, de"+t(1621)+"r ttwID",KoJvI:function(a,n){return a==n},WqRjy:t(197),xLUph:function(a,n,o){return a(n,o)},xkisM:t(1061)+"0",zgjlB:function(a,n,o){return a(n,o)},QwWzJ:function(a,n){return a(n)},dfVyz:function(a,n){return a===n},Qmmfc:t(1197),beNGx:function(a,n,o){return a(n,o)},HwhYB:function(a,n){return a===n},dxSeZ:t(662),rfqbJ:function(a,n){return a||n},eCsfE:t(1115),Uhxgd:function(a,n,o){return a(n,o)},RcTpg:"start",HsgIW:function(a,n){return a-n},bCvpu:function(a,n,o){return a(n,o)},vBWWG:function(a,n){return a(n)},ZahQJ:t(1094)+">",Itdip:"1|2|5|4|"+t(214),KgiZX:function(a,n){return a&n},qNNMW:function(a,n){return a+n},VdXks:function(a,n){return a&n},UXiav:function(a,n){return a&n},IsSNe:function(a,n){return a>>n},ELhFi:t(1317),mugoB:t(161),RxLba:function(a,n){return a-n},yXIkU:function(a,n){return a||n},Ipign:t(876),tQwkV:function(a,n,o){return a(n,o)},ahAzF:t(352),sIMlc:"oOlCe",DgqdH:t(1190)+t(1534)+t(1069)+t(619)+t(605),SAPlv:function(a,n){return a<n},WIwEL:function(a,n){return a|n},epftH:"qIfPg",WvyJy:function(a,n){return a<=n},vRTMm:function(a,n){return a!==n},zQlwj:"LrpSq",mUUWo:t(431)+t(937)+t(265)+"g",YXRoK:t(767),rSAeQ:"WLTxe",ATyTK:t(281),jhDKl:t(515)+"2",kcYFa:function(a,n){return a===n},AKvWD:function(a,n){return a===n},mWTxG:function(a,n){return a!==n},HmFmy:t(1601),TZVxn:t(155),iDRmj:function(a,n){return a|n},rUXtA:function(a,n){return a|n},DvcNM:function(a,n){return a+n},CMDKQ:function(a,n){return a<<n},VPKwr:function(a,n){return a+n},dAFJN:function(a,n){return a|n},WpDej:function(a,n){return a<<n},pOYbm:function(a,n){return a<<n},oWpaZ:function(a,n){return a+n},WMzdQ:function(a,n){return a+n},CisGR:t(1476),gCcwU:function(a,n,o){return a(n,o)},eFvpt:t(425),KiAHv:t(1190)+"ay, network offl"+t(468),sdNTn:function(a,n){return a+n},SvCuJ:function(a,n){return a===n},tssXl:t(1137),hdXjc:function(a,n){return a|n},USmGW:function(a,n){return a<<n},RHMnQ:function(a,n){return a|n},aNNhY:"UQyuv",BszCk:t(232),uGmir:function(a,n,o){return a(n,o)},AqHOI:t(1383),szaoP:t(1116),lIkfm:t(1080),TjgpF:t(1726)+"0|7|4|1",OLjuL:t(945)+"s alread"+t(435),nOxcX:function(a,n){return a-n},nGzmD:function(a,n){return a|n},pTVGx:function(a,n){return a|n},vZqoS:function(a,n){return a<<n},bPoay:function(a,n){return a&n},MCMGI:function(a,n){return a&n},thPix:function(a,n){return a<<n},fSYbY:function(a,n){return a&n},LJNPo:function(a,n){return a&n},TvPYR:t(904),xgenG:t(916),xEmJM:t(1701)+t(287)+t(1481)+t(796)+t(748)+t(463)+t(742)+t(536)+t(475),qGcIz:function(a,n){return a instanceof n},kVFOw:t(1701)+t(287)+t(1532)+t(282),pMdoM:function(a,n){return a instanceof n},omkhn:function(a,n){return a(n)},exXiZ:function(a,n){return a===n},mAIcO:t(1696),GxVFv:function(a,n){return a||n},yruxa:t(1580)+t(474)+t(552),mVJmR:t(1720)+"1",GlCxm:function(a,n){return a!==n},ybCgx:t(894),hAeqq:t(402),eVeCB:t(1056),gKFlO:function(a,n){return a/n},bFIdw:function(a,n){return a!=n},HPgVh:"Window",HWfSc:function(a,n){return a!=n},Aqrkt:function(a,n){return a!=n},IXCNr:function(a,n){return a!=n},fveKj:function(a,n){return a===n},OLxUM:"Dedicate"+t(1223)+"lobalScope",iopvd:t(1038)+t(1236)+"alScope",BaUeD:function(a,n){return a===n},kZXHL:function(a,n){return a!=n},yxcgq:function(a,n){return a!=n},JuBLm:"Object",fhBGL:function(a,n,o){return a(n,o)},fzvWn:"__x_msg_"+t(1252)};Ut.r(Pe),Ut.d(Pe,{FWS:()=>Gg,CustomErrorEvent:()=>ml,createCloseEvent:()=>wt,ReconnectEvent:()=>gl,createErrorEvent:()=>ut,decodedFrame:()=>sn,createOpenEvent:()=>vl,CustomCloseEvent:()=>wl,createReconnectEvent:()=>va,FrontierMessageEvent:()=>yl,encodeFrame:()=>qt,createMessageEvent:()=>El,OpenEvent:()=>bl,ErrorCode:()=>an,Event:()=>or,MessageEvent:()=>_l});let r="";function i(a=""){let n=t,o="02",d=""+Date.now(),f=r||(r=e[n(1206)](x,a)),p=Math.random().toString(16)[n(268)](-6);return e[n(190)](e[n(190)](o,d),f)+p}function s(){let a=t;return e[a(190)](e[a(827)](1e4,Date[a(799)]()),Math[a(963)](e[a(827)](1e4,Math[a(961)]())))}function c(a){let n=t;if(e[n(890)](e[n(1630)],n(1636))){_0x33ceb4[n(1305)](_0x18a2a4)||(_0x261f3f=_0x223ae7[n(1626)+"er"](_0x5d49fa));let o=this[n(1208)]>>>16,d=65535&this[n(1208)],f=this[n(486)]>>>16,p=e[n(1574)](65535,this[n(486)]),_=e[n(1352)](_0x502b5b[n(1208)],16),v=65535&_0x4266bd[n(1208)],g=e.XRDQW(_0x4d8ca9[n(486)],16),L=e[n(1024)](65535,_0x3bf453[n(486)]),O=0,N=0,G=0,H=0;return H+=e[n(190)](p,L),G+=e[n(1352)](H,16),H&=65535,G+=e[n(190)](f,g),N+=e[n(199)](G,16),G&=65535,N+=e[n(448)](d,v),O+=e.PHRto(N,16),N&=65535,O+=e.vhZFb(o,_),O&=65535,_0x2a5c86[n(1694)](e[n(1240)](G,16)|H,e[n(316)](O<<16,N),this[n(642)])}else return e.mSXns(e[n(693)](Array,8).join("0"),e[n(1264)](parseInt,a,10)[n(1036)](2)).slice(-8)}function l(a){let n=t;return e[n(1347)](e.YFMYc(Array,4)[n(1415)]("0"),e.NSwCe(parseInt,a,2)[n(1036)](16))[n(268)](-4)}function u(a){let n=t,o=a[n(1353)](/\./)[n(573)](p=>c(p)),d=[];return d[0]=e[n(1439)](l,e[n(400)](o[0],o[1])),d[1]=l(e.vhZFb(o[2],o[3])),[n(1210),e[n(410)],n(1210),e.vwXnq,e.vwXnq,n(1707),d[0],d[1]][n(1415)]("")}function x(a){let n=t,o=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1384)](a),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(a);return o?e[n(693)](u,a):d?e.czYTt(h,a):n(1572)+n(1572)+"00000000"+n(1572)}function h(a){let n=t,o={ONETZ:function(L,O,N){return L(O,N)},EnzZG:e[n(804)],TGGZr:e[n(1582)]},d="",f=[],p=0,_=0,v=!0,g=e.vwXnq;if(e[n(477)](a[n(338)]("::"),-1)){let L=a[n(1353)]("::");for(let N=0;N<L[n(1674)];N++)if(e[n(487)](e[n(1692)],e[n(1692)])){let G=this[n(1138)]["reconnec"+n(518)+"ptor"](_0x16c6ae,_0x555933);this["_dispatc"+n(1336)+n(620)](o[n(966)](_0x13a8ea,o[n(723)],{code:_0x3b0c6d,reason:_0x1e3b62,wasClean:!0,willReconnect:G})),G&&this[n(1675)]()}else{let G=L[N];if(e.hNfTP(G[n(338)](":"),0)){let H=G[n(1353)](":");v&&(p=H[n(1674)]),_+=H.length;for(let re=0;e[n(267)](re,H[n(1674)]);re++)if(e[n(487)](4,H[re][n(1674)]))if(e[n(487)](e.pwPpj,"rjLfE")){let Fe=g[n(1002)+"g"](0,e[n(181)](4,H[re][n(1674)])),$e=Fe.concat(H[re]);f[n(1421)]($e)}else _0x2b0e1c[n(416)+n(324)+"ner"](eiPqJS[n(469)],_0x2a8663),_0x3300bd[n(416)+n(324)+"ner"](n(899),_0x463dd6);else f[n(1421)](H[re]);v=!1}else{if(e.umQFm(4,G[n(1674)])){let H=g[n(1002)+"g"](0,4-G[n(1674)]),re=H[n(498)](G);f.push(re)}else f[n(1421)](G);v&&(p+=1),_+=1,v=!1}}let O="";for(let N=0;e.KbcFi(N,e.fgZeu(8,_));N++)O=O.concat(g);for(let N=0;e.CFzIU(N,f[n(1674)]);N++)e[n(634)](N,p)?e[n(890)](e[n(657)],e[n(657)])?(d=d[n(498)](O),d=d[n(498)](f[N])):(this[n(1262)]=!0,this[n(1675)]()):d=d[n(498)](f[N]);return d}{let L=a[n(1353)](":");for(let O=0;e[n(644)](O,L[n(1674)]);O++){let N=L[O];if(e[n(897)](4,L[O][n(1674)])){let G=g[n(1002)+"g"](0,4-L[O].length),H=G[n(498)](N);d=d[n(498)](H)}else d=d.concat(N)}return d}}function m(a,n){let o=t,d=a[o(275)];e[o(897)](void 0,d)&&(e[o(1737)](ge,n,10),e[o(1737)](q,n,d));let f=a[o(802)];e[o(750)](void 0,f)&&(ge(n,18),e[o(1737)](q,n,f))}function w(a){let n=t,o={AimmA:function(d,f){return e.SIYKt(d,f)},QhqSv:function(d,f){return e[z(849)](d,f)},XOjRl:function(d,f){return d|f},wqeWZ:function(d,f){return d&f},SgfRK:function(d,f){return e.eITdb(d,f)},bIFPI:function(d,f){return e[z(470)](d,f)},rwQmM:function(d,f){return e[z(1110)](d,f)},VWjqA:function(d,f){return d>>>f},dGejL:function(d,f){return e[z(644)](d,f)},tyeoD:function(d,f){return e[z(167)](d,f)},redNH:function(d,f,p,_){return e[z(491)](d,f,p,_)}};if(e[n(890)](e[n(1625)],"dDoRc")){let d={};e:for(;!e.avMIW(V,a);){let f=ue(a);switch(e[n(1477)](f,3)){case 0:break e;case 1:d[n(275)]=e.hkSYV(P,a,e[n(1124)](ue,a));break;case 2:d[n(802)]=e[n(1737)](P,a,e[n(920)](ue,a));break;default:e.AwJDu(T,a,e[n(1448)](7,f))}}if(e[n(308)](void 0,d[n(275)]))throw new Error(e[n(773)]);if(e[n(634)](void 0,d[n(802)]))throw new Error(e[n(820)]);return d}else{let d={EsGYW:function(p,_){return o.AimmA(p,_)},rmSHh:function(p,_){return o[n(1387)](p,_)},jWcJe:function(p,_){return o[n(1114)](p,_)},aGciO:function(p,_){return p>>>_},INSFc:function(p,_){return p<<_},qLBUX:function(p,_){return o[n(1637)](p,_)},bPcAB:function(p,_){return o[n(263)](p,_)},TTIjj:function(p,_){return o[n(915)](p,_)},TDRbu:function(p,_){return o[n(1664)](p,_)},unJsr:function(p,_){return p<_},gtzMT:function(p,_){return o[n(1729)](p,_)},BuWDN:function(p,_){return o.dGejL(p,_)},XdXxv:function(p,_){return p|_},XxuFs:function(p,_){return o.tyeoD(p,_)},kFtXK:function(p,_){return p>_},fntxL:function(p,_,v,g){return o[n(684)](p,_,v,g)}},f=4294967295;return function(p,_,v=!0){let g=n;if(f=d[g(1286)](d.rmSHh(127,p[_]),0),p[_++]<128)return{value:v?f:d[g(1328)](0,f),offset:_};if(f=d[g(237)](d[g(1328)](f,d[g(1373)](d[g(1312)](127,p[_]),7)),0),p[_++]<128)return{value:v?f:d.bPcAB(0,f),offset:_};if(f=d[g(957)](f|d[g(996)](127&p[_],14),0),d.unJsr(p[_++],128))return{value:v?f:d[g(1065)](0,f),offset:_};if(f=d[g(1541)](d[g(1328)](f,d[g(1373)](d.qLBUX(127,p[_]),21)),0),d.BuWDN(p[_++],128))return{value:v?f:d[g(1536)](0,f),offset:_};if(f=d.XdXxv(f,d[g(457)](15,p[_])<<28)>>>0,d.BuWDN(p[_++],128))return{value:v?f:d[g(843)](0,f),offset:_};if(d[g(1463)](_+=5,p[g(1674)]))throw _=p[g(1674)],d.fntxL(_0x5075b3,_,10,p.length);return{value:v?f:0|f,offset:_}}}}function S(a){let n=R();return e.AwJDu(y,a,n),e.czYTt(B,n)}function y(a,n){let o=t,d={UiHar:function($e,nt,dr){return e[z(1689)]($e,nt,dr)},klXEv:function($e,nt,dr){return e.BCBTX($e,nt,dr)},lpdme:function($e,nt){return e.ebxkp($e,nt)}},f=a[o(1618)];f!==void 0&&(e[o(906)](ge,n,8),e.BCBTX(mt,n,f));let p=a[o(195)];e[o(296)](void 0,p)&&(ge(n,16),mt(n,p));let _=a[o(1681)];if(e[o(1106)](void 0,_))if(e[o(890)](e[o(608)],e[o(358)])){let $e=_0x22413b(_0x16794a,1);_0xa994ff[o(959)][$e]=_0x3622c4}else e[o(911)](ge,n,24),mt(n,e.avMIW(C,_));let v=a[o(809)];v!==void 0&&(e.RAdnm!=="MecvB"?(ge(n,32),e[o(1160)](mt,n,e.czYTt(C,v))):(++_0x5314a2,_0x1bdf61+=4));let g=a[o(1055)];if(e[o(1750)](void 0,g))for(let $e of g)if(e.pYfJT!==e[o(1399)])d[o(955)](_0x2f29f0,_0xebb485,96),d[o(256)](_0x505d92,_0x519c1b,d[o(218)](_0x57f004,_0x600686));else{ge(n,42);let nt=e.BJmjO(R);e.zwhqD(m,$e,nt),ge(n,nt.limit),e.RUcen(K,n,nt),D(nt)}let L=a.payloadEncoding;L!==void 0&&(ge(n,50),e.CWMAZ(q,n,L));let O=a["payloadT"+o(1552)];O!==void 0&&(e[o(1160)](ge,n,58),e.NSwCe(q,n,O));let N=a[o(235)];e[o(1499)](void 0,N)&&(e.BCBTX(ge,n,66),e[o(1173)](ge,n,N[o(1674)]),e[o(1737)](ae,n,N));let G=a.LogIDNew;G!==void 0&&(e.XPsNq(ge,n,74),e[o(1160)](q,n,G));let H=a[o(407)+o(1585)];if(H!==void 0){if(e[o(1521)](e[o(675)],e[o(1690)]))return this[o(1293)].url;e[o(1737)](ge,n,82),q(n,H)}let re=a.msgID;e[o(1525)](void 0,re)&&(e[o(194)](ge,n,90),e.BCBTX(q,n,re));let Fe=a[o(184)+"e"];Fe!==void 0&&(e[o(1737)](ge,n,96),mt(n,e[o(920)](C,Fe)))}function E(a){return I(e.cTHAQ(F,a))}function I(a){let n=t,o={NCCYd:function(d,f){return e[z(953)](d,f)},CElab:function(d,f){return d<f},ekhCA:function(d,f){return d+f},PIoWX:function(d,f){return e[z(841)](d,f)},hTDZj:function(d,f){return e[z(533)](d,f)},QwYWg:function(d,f){return e[z(673)](d,f)},QMHTM:function(d,f){return d&f},TgspQ:function(d,f){return e.dafhj(d,f)},aOkqj:function(d,f){return d<f},HUAci:function(d,f){return e[z(167)](d,f)},rqWQd:function(d,f){return e[z(1053)](d,f)},XnvDB:function(d,f){return e[z(792)](d,f)},mHKsV:function(d,f){return d|f},fipLf:function(d,f){return e[z(989)](d,f)}};if(e[n(1106)](e[n(1494)],e[n(859)])){let d={};e:for(;!V(a);){let f=e[n(1439)](ue,a);switch(e.VRMGd(f,3)){case 0:break e;case 1:d[n(1618)]=e[n(1689)](At,a,!0);break;case 2:d[n(195)]=e.CWMAZ(At,a,!0);break;case 3:d[n(1681)]=e[n(1124)](ue,a);break;case 4:d[n(809)]=ue(a);break;case 5:{let p=A(a);(d.headers||(d[n(1055)]=[]))[n(1421)](e[n(1206)](w,a)),a.limit=p;break}case 6:d[n(1049)+n(393)]=e[n(1020)](P,a,e[n(481)](ue,a));break;case 7:d[n(511)+n(1552)]=P(a,ue(a));break;case 8:d[n(235)]=e.yssTf(te,a,e.UpnGz(ue,a));break;case 9:d[n(786)]=e[n(1713)](P,a,e[n(1239)](ue,a));break;case 10:d[n(407)+"ming"]=e[n(956)](P,a,e[n(1453)](ue,a));break;case 11:d[n(883)]=e.hmQRh(P,a,ue(a));break;case 12:d[n(184)+"e"]=e.nSVbw(ue,a);break;default:T(a,e[n(1574)](7,f))}}if(e.pPzJl(void 0,d[n(1618)]))throw new Error("Missing required"+n(1169)+n(1618));if(d[n(195)]===void 0)throw new Error(n(1465)+n(1492)+" field: "+n(195));if(d[n(1681)]===void 0)throw new Error(e[n(818)]);if(e[n(1521)](void 0,d[n(809)]))throw new Error(e[n(509)]);return d}else{let d=_0x90111d[n(417)+"At"](_0x222950);d>=55296&&o[n(357)](d,56319)&&o[n(958)](o[n(1430)](_0x360b5f,1),_0x75e4b7)&&(d=o[n(637)](o[n(1430)](o[n(196)](d,10),_0x31021c[n(417)+"At"](++_0x300962)),56613888)),o.QwYWg(d,128)?_0x5294ca[_0x1559c9++]=d:(d<2048?_0x4edf3e[_0x5ab93c++]=o[n(1553)](o.TgspQ(d,6),31)|192:(o[n(1201)](d,65536)?_0x1d3dda[_0x53bafa++]=d>>12&15|224:(_0x32a2ef[_0x25283d++]=o[n(379)](o.rqWQd(o[n(951)](d,18),7),240),_0x21bad8[_0xe384cc++]=o[n(666)](o.fipLf(d,12)&63,128)),_0x452704[_0x38e3ea++]=o.HUAci(o[n(708)](d,6)&63,128)),_0x524ff7[_0x23eb04++]=o.HUAci(63&d,128))}}function A(a){let n=e.YFMYc(ue,a),o=a.limit;return a.limit=a.offset+n,o}function T(a,n){let o=t;if(o(1479)!==e[o(561)])this[o(1471)]&&this._ws[o(1544)](_0x54d2d3),this[o(775)](e.WXCGh,_0x545b23);else switch(n){case 0:for(;e[o(1448)](128,e[o(1543)](ne,a)););break;case 2:e[o(911)](J,a,e[o(481)](ue,a));break;case 5:e[o(1535)](J,a,4);break;case 1:e[o(1442)](J,a,8);break;default:throw new Error(e[o(400)](o(554)+o(1172)+o(1673),n))}}function C(a){let n=t;if(e.Agnrs(e[n(438)],e.udjNK))_0x1649ee(_0x3dc8f7,58),_0xc10c1(_0x31bcd1,_0x289643);else return a|=0,{low:a,high:e[n(1009)](a,31),unsigned:e[n(1635)](a,0)}}let b=[];function R(){let a=t,n={LuiFI:function(o,d){return e.acOrH(o,d)}};if(e.CYxdJ(e[a(867)],e.XhoAP)){let o=b.pop();return o?(o[a(493)]=o.limit=0,o):{bytes:new Uint8Array(64),offset:0,limit:0}}else return n[a(1221)](0,this.high)&&this[a(486)]===0}function D(a){b[t(1421)](a)}function F(a){return{bytes:a,offset:0,limit:a[t(1674)]}}function B(a){let n=t,o=a.bytes,d=a[n(928)];return e[n(634)](o[n(1674)],d)?o:o[n(414)](0,d)}function J(a,n){let o=t;if(e[o(477)](e.vkFZU(a[o(493)],n),a[o(928)]))throw new Error(e[o(354)]);a[o(493)]+=n}function V(a){let n=t;return e[n(1635)](a.offset,a[n(928)])}function se(a,n){let o=t,d=a[o(959)],f=a.offset,p=a.limit,_=e[o(343)](f,n);if(e[o(477)](_,d.length)){let v=new Uint8Array(2*_);v[o(1397)](d),a[o(959)]=v}return a[o(493)]=_,e.hNfTP(_,p)&&(a.limit=_),f}function X(a,n){let o=t,d=a[o(493)];if(e.SaWTB(e[o(190)](d,n),a.limit))throw new Error("Read pas"+o(924));return a[o(493)]+=n,d}function te(a,n){let o=t,d=e[o(1020)](X,a,n);return a[o(959)][o(414)](d,e[o(1697)](d,n))}function ae(a,n){let o=t,d=se(a,n[o(1674)]);a[o(959)][o(1397)](n,d)}function P(a,n){let o=t,d=e.yssTf(X,a,n),f=String["fromChar"+o(1710)],p=a[o(959)],_="\uFFFD",v="";for(let g=0;e.GcUxc(g,n);g++){let L=p[e[o(1345)](g,d)],O,N,G,H;e[o(1366)](128,L)===0?v+=e[o(1439)](f,L):e.NPVoh(e[o(1024)](224,L),192)?e[o(211)](g+1,n)?v+=_:(O=p[e[o(448)](g+d,1)],e[o(1525)](e.ylwtU(192,O),128)?v+=_:(H=e.ghNBC(e[o(505)](31,L)<<6,e[o(1448)](63,O)),e.RQxtL(H,128)?v+=_:(v+=e.cSROn(f,H),g++))):e[o(329)](e[o(1448)](240,L),224)?e[o(1044)](g,2)>=n?v+=_:(O=p[e[o(205)](e[o(1697)](g,d),1)],N=p[e[o(1413)](g+d,2)],e[o(1750)](e[o(1024)](e[o(571)](O,e[o(997)](N,8)),49344),32896)?v+=_:(H=e[o(1727)](e[o(571)](e[o(1487)](15,L)<<12,(63&O)<<6),e[o(505)](63,N)),e.tOKZy(H,2048)||H>=55296&&e[o(953)](H,57343)?v+=_:(v+=e[o(1543)](f,H),g+=2))):e[o(329)](e[o(1053)](248,L),240)?e[o(1346)](g+3,n)?v+=_:(O=p[e[o(1539)](e[o(345)](g,d),1)],N=p[e[o(448)](e.uXwcM(g,d),2)],G=p[g+d+3],e[o(1006)](e.tJLau(e[o(316)](e[o(167)](O,e[o(732)](N,8)),e[o(335)](G,16)),12632256),8421504)?v+=_:(H=e.QPuBh(e[o(167)](e.ghNBC(e[o(200)](7,L)<<18,e[o(997)](e[o(200)](63,O),12)),e[o(1393)](63&N,6)),e[o(387)](63,G)),e.RQxtL(H,65536)||H>1114111?v+=_:(H-=65536,v+=e[o(1713)](f,e[o(156)](H,10)+55296,e[o(1024)](1023,H)+56320),g+=3))):v+=_}return v}function q(a,n){let o=t,d=n[o(1674)],f=0;for(let v=0;e[o(267)](v,d);v++){let g=n[o(417)+"At"](v);e[o(1226)](g,55296)&&g<=56319&&e.KbcFi(v+1,d)&&(g=e[o(1716)](g,10)+n[o(417)+"At"](++v)-56613888),f+=g<128?1:e.crxPW(g,2048)?2:e[o(673)](g,65536)?3:4}e[o(1535)](ge,a,f);let p=e[o(1256)](se,a,f),_=a[o(959)];for(let v=0;e[o(545)](v,d);v++){let g=n[o(417)+"At"](v);if(g>=55296&&e[o(953)](g,56319)&&e.rfGzn(e.zrUUx(v,1),d)&&(g=e.fgZeu(e[o(570)](g<<10,n.charCodeAt(++v)),56613888)),e[o(631)](g,128))_[p++]=g;else{if(e[o(1400)](g,2048))_[p++]=e[o(571)](e[o(1281)](e.XiJzq(g,6),31),192);else{if(e.KbcFi(g,65536))_[p++]=e[o(571)](e[o(1448)](g>>12,15),224);else{if(e[o(234)](o(170),e[o(1443)]))return _0xc7a7d1[o(959)][e[o(1213)](_0x357f38,_0x54b8a8,1)];_[p++]=e[o(1727)](e[o(1587)](g>>18,7),240),_[p++]=e[o(387)](e.FrznV(g,12),63)|128}_[p++]=e.eITdb(e[o(1574)](g>>6,63),128)}_[p++]=e.imKaK(63,g)|128}}}function K(a,n){let o=t,d=se(a,n.limit),f=a[o(959)],p=n[o(959)];for(let _=0,v=n[o(928)];e[o(267)](_,v);_++)f[e[o(433)](_,d)]=p[_]}function ne(a){return a[t(959)][X(a,1)]}function Ze(a,n){let o=t,d=e.hmQRh(se,a,1);a[o(959)][d]=n}function ue(a){let n=t,o=0,d=0,f;do{if(e[n(1294)](e[n(1093)],e[n(641)]))return _0x8c0ea2[_0x316d9b]=_0x2d0b40,!0;f=ne(a),e[n(1400)](o,32)&&(d|=e[n(1240)](e[n(1711)](127,f),o)),o+=7}while(e[n(1053)](128,f));return d}function ge(a,n){let o=t;for(n>>>=0;e.hUboY(n,128);)if(e[o(1106)](e[o(426)],o(326)))e[o(1713)](Ze,a,e[o(390)](e[o(1007)](127,n),128)),n>>>=7;else{let d={SImZU:function(f,p){let _=o;return ZHFfXD[_(1239)](f,p)}};_0x4c5556.addEventListener(ZHFfXD[o(1158)],f=>{let p=o;_0x440118(d.SImZU(_0x9800e0,_0x3ee6ae[p(845)]),f[p(726)+"on"],f[p(1179)+"on"],d[p(1003)](_0x1991eb,_0x3d5318[p(340)+p(406)]))})}e[o(962)](Ze,a,n)}function At(a,n){let o=t,d={nimTD:function(g,L){return e[z(841)](g,L)}},f=0,p=0,_=0,v;if(v=e[o(481)](ne,a),f=e[o(1648)](127,v),128&v&&(v=ne(a),f|=e[o(200)](127,v)<<7,e.wuIAt(128,v)&&(v=e[o(1590)](ne,a),f|=e[o(387)](127,v)<<14,e[o(322)](128,v)&&(v=e[o(1035)](ne,a),f|=e[o(458)](e[o(1007)](127,v),21),e[o(505)](128,v)))))if(e[o(1348)](e.tKiZM,e.ouOEC)){if(v=ne(a),p=e[o(1257)](127,v),e[o(1366)](128,v)&&(v=e.RPJns(ne,a),p|=e[o(460)](127,v)<<7,e.YuhoW(128,v)))if(e[o(273)]!==e[o(1232)])v=ne(a),p|=e[o(1224)](e[o(1587)](127,v),14),e[o(715)](128,v)&&(v=e[o(1604)](ne,a),p|=e[o(1224)](127&v,21),128&v&&(v=e[o(1035)](ne,a),_=127&v,e[o(387)](128,v)&&(v=e[o(1732)](ne,a),_|=e[o(533)](e.MyRLD(127,v),7))));else{let g=_0x8eda1e.message[o(235)];g&&_0x3274cc.setCursors(g)}}else{let g=_0x566cb9[o(1002)+"g"](0,xllAWi[o(299)](4,_0x3ca5e6[_0x487522][o(1674)])),L=g[o(498)](_0xd3c13b);_0x2c3fe2=_0xf76485.concat(L)}return{low:e[o(571)](f,p<<28),high:e[o(1085)](p>>>4,e[o(437)](_,24)),unsigned:n}}function mt(a,n){let o=t,d=e[o(179)](n[o(486)],0),f=e[o(297)](e[o(179)](n[o(486)],28),e.lGiIn(n.high,4))>>>0,p=e[o(303)](n.high,24),_=e[o(1237)](0,p)?e.EzjGx(0,f)?e[o(476)](d,16384)?e.wMdWo(d,128)?1:2:e[o(1473)](d,2097152)?3:4:e[o(673)](f,16384)?e[o(391)](f,128)?5:6:e[o(1422)](f,2097152)?7:8:p<128?9:10,v=se(a,_),g=a[o(959)];switch(_){case 10:g[e[o(205)](v,9)]=e[o(1352)](p,7)&1;case 9:g[e[o(1719)](v,8)]=_!==9?e[o(297)](128,p):127&p;case 8:g[e[o(1490)](v,7)]=e[o(487)](8,_)?e.Mjchl(e[o(449)](f,21),128):e[o(1477)](f,21)&127;case 7:g[v+6]=e[o(342)](7,_)?e[o(627)](f>>>14,128):e.vYGbn(e[o(261)](f,14),127);case 6:g[v+5]=e[o(285)](6,_)?e[o(1603)](e.vrtTu(f,7),128):e.TsSOt(e[o(1657)](f,7),127);case 5:g[v+4]=_!==5?e[o(1298)](128,f):127&f;case 4:g[v+3]=e.diBeZ(4,_)?e.vvrpl(d>>>21,128):e[o(800)](e[o(199)](d,21),127);case 3:g[v+2]=e.ZxGxG(3,_)?e[o(167)](d>>>14,128):d>>>14&127;case 2:g[e[o(600)](v,1)]=_!==2?d>>>7|128:e.QoOSY(d,7)&127;case 1:g[v]=e[o(1499)](1,_)?e[o(1542)](128,d):e[o(505)](127,d)}}function sn(a){return e.avMIW(E,a)}function qt(a){return e[t(693)](S,a)}let on=65536,ii=t(521),_e=on*on,ke=e.UMWTG(_e,_e),sr=e[t(835)](ke,2),Le=String[t(1040)+"e"][t(417)+"At"];class fe{constructor(n,o,d){let f=t;this.isLong=!0,this[f(486)]=e[f(1542)](0,n),this[f(1208)]=e.Mjchl(0,o),this[f(642)]=!!d}static isLong(n){return n&&e[t(1521)](!0,n.isLong)}static[t(1694)](n,o,d){let f=t,p={uVCoq:f(431)+f(937)+f(265)+"g"};if(e[f(1495)](e[f(1089)],e[f(1089)])){let _=this[f(1688)+f(1530)]?.[f(688)+f(210)+"nt"]();this._debug(f(646)+_+" timeout"),this["_disconn"+f(295)](1001,p[f(676)],!0)}else return new fe(n,o,d)}static[t(1307)+"s"](n,o,d){let f=t;return d?fe[f(1307)+f(793)](n,o):fe[f(1307)+f(1228)](n,o)}static[t(1307)+t(793)](n,o){let d=t;if(e.skUQd(e[d(172)],e[d(172)]))return new fe(e[d(1349)](e[d(1676)](e[d(643)](n[0],e.JbeaN(n[1],8)),e[d(997)](n[2],16)),e[d(997)](n[3],24)),e[d(627)](n[4]|e[d(533)](n[5],8),e[d(1478)](n[6],16))|e[d(1716)](n[7],24),o);_0x24a73c.o=(f,p)=>_0x5cdb6b.prototype[d(1211)+d(616)][d(216)](f,p)}static[t(1307)+t(1228)](n,o){let d=t;return new fe(e[d(1298)](e[d(318)](n[4]<<24,e[d(1110)](n[5],16)),n[6]<<8)|n[7],e.PzQkg(e[d(167)](e[d(1298)](e[d(335)](n[0],24),e[d(517)](n[1],16)),e[d(997)](n[2],8)),n[3]),o)}static[t(540)](n){let o=t;return n===ii?pl:new fe(e.oUuas(e[o(1349)](e[o(1351)](Le[o(216)](n,0),e[o(1224)](Le.call(n,1),8))|e[o(1241)](Le[o(216)](n,2),16),e.LcdUa(Le[o(216)](n,3),24)),0),e[o(179)](e.eITdb(e.vvrpl(e[o(1603)](Le[o(216)](n,4),e.VqpPh(Le[o(216)](n,5),8)),e.LyKun(Le[o(216)](n,6),16)),e[o(1241)](Le[o(216)](n,7),24)),0),!0)}[t(699)](){let n=t;return String[n(1297)+n(1710)](e[n(322)](255,this[n(486)]),e[n(224)](this[n(486)],8)&255,e[n(752)](e[n(470)](this[n(486)],16),255),this[n(486)]>>>24,255&this[n(1208)],e[n(696)](e[n(495)](this[n(1208)],8),255),e[n(1578)](this[n(1208)]>>>16,255),e[n(1092)](this.high,24))}static[t(1626)+"er"](n,o=!0){let d=t;if(e.RDabT(isNaN,n))return o?tg:pl;if(o)if(e.ofGhJ===e.ofGhJ){if(e[d(1445)](n,ke))return rg}else _0x5be349&&_0x459a00[d(607)+d(1702)]("close",()=>_0xe209e1()),_0x975dc2&&_0x445a71[d(607)+"Listener"](ZHFfXD[d(782)],()=>_0xb261aa());else{if(e.OivUK(n,-sr))return ig;if(e[d(1019)](e[d(343)](n,1),sr))return ng}return fe[d(1694)](e[d(1663)](e[d(1410)](n,_e),0),e[d(1441)](n,_e)|0,o)}toNumber(){let n=t,o={AbIHU:function(d,f,p){return e[z(956)](d,f,p)},zHJRk:e.rEiXp};if(e[n(1144)]!==e[n(1028)])return this[n(642)]?e.YzkmA(e[n(1357)](e[n(1334)](this.high,0),_e),e[n(1477)](this[n(486)],0)):e[n(1357)](this[n(1208)],_e)+e[n(168)](this[n(486)],0);{let d=o[n(623)](_0xd47fbe,o.zHJRk,{message:_0x5280f0.message,code:_0x339ce4[n(347)+n(1154)],error:_0x59d05c});this[n(245)+n(1666)+n(620)](d)}}[t(931)](){let n=t,o={EyhzG:function(d,f,p,_,v){return e[z(598)](d,f,p,_,v)},HDevU:function(d,f){return e.hlWAk(d,f)}};if(e.LriFe(e[n(829)],e[n(829)]))return this.high===0&&this.low===0;eWPyXo[n(453)](_0x540554,eWPyXo[n(593)](_0x3d6fb1,_0x3336a1[n(845)]),_0x1dd2f0[n(726)+"on"],_0x4cf720[n(1179)+"on"],_0x2106ee(_0x2031c5[n(340)+n(406)]))}[t(337)](n){let o=t;fe[o(1305)](n)||(n=fe.fromNumber(n));let d=e[o(1193)](this[o(1208)],16),f=65535&this.high,p=e.HqSFk(this[o(486)],16),_=e[o(678)](65535,this[o(486)]),v=e[o(484)](n.high,16),g=e[o(1574)](65535,n.high),L=e[o(1147)](n[o(486)],16),O=65535&n[o(486)],N=0,G=0,H=0,re=0;return re+=e[o(870)](_,O),H+=e[o(1193)](re,16),re&=65535,H+=p+L,G+=e[o(1067)](H,16),H&=65535,G+=e[o(1413)](f,g),N+=G>>>16,G&=65535,N+=e[o(400)](d,v),N&=65535,fe[o(1694)](e[o(830)](e.pjUZY(H,16),re),e[o(1603)](N<<16,G),this.unsigned)}[t(724)](n){let o=t;return fe[o(1305)](n)||(n=fe[o(1626)+"er"](n)),e[o(1315)](this[o(642)],n[o(642)])&&e[o(1064)](e[o(303)](this[o(1208)],31),1)&&e[o(1658)](e[o(1531)](n[o(1208)],31),1)?!1:this[o(1208)]===n[o(1208)]&&e[o(1275)](this[o(486)],n.low)}[t(1222)](){let n=t;return e[n(686)](-1,this.low)&&this.high===-1?fe[n(1694)](0,0,this[n(642)]):e[n(1237)](-1,this[n(486)])?fe[n(1694)](0,e[n(600)](this[n(1208)],1),this.unsigned):fe[n(1694)](e[n(1719)](this[n(486)],1),this[n(1208)],this.unsigned)}[t(781)](n){let o=t;return n?this[o(878)+"E"]():this[o(176)+"E"]()}[t(878)+"E"](){let n=t,o=this[n(1208)],d=this[n(486)];return[255&d,e[n(1007)](e[n(1419)](d,8),255),e[n(1352)](d,16)&255,e[n(153)](d,24),e[n(901)](255,o),e.YxZVT(e[n(199)](o,8),255),e.YxZVT(e[n(1334)](o,16),255),o>>>24]}[t(176)+"E"](){let n=t,o=this[n(1208)],d=this[n(486)];return[e.JcgVT(o,24),e[n(749)](o,16)&255,e[n(1120)](o>>>8,255),e[n(1366)](255,o),e[n(1419)](d,24),e[n(1512)](e[n(153)](d,16),255),e[n(305)](e.LvpdK(d,8),255),e[n(690)](255,d)]}}let pl=new fe(0,0,!1),tg=new fe(0,0,!0),ng=fe.fromBits(-1,2147483647,!1),rg=fe.fromBits(-1,-1,!0),ig=fe[t(1694)](0,-2147483648,!1);var an=(function(a){let n=t,o=e[n(1567)][n(1353)]("|"),d=0;for(;;){switch(o[d++]){case"0":a[a[e[n(879)]]=5002]=n(971)+n(1411);continue;case"1":a[a[e[n(1157)]]=5004]=e[n(1157)];continue;case"2":a[a[e.QBJzd]=5001]=e.QBJzd;continue;case"3":a[a[e[n(1253)]]=5003]=n(1302)+"IES_ERROR";continue;case"4":return a;case"5":a[a.OPEN_ERROR=5005]=n(1418)+"OR";continue}break}})({});class or{constructor(n){let o=t;this[o(1412)]=n,this.target=null}}class gl extends or{constructor(n,o){let d=t;super(n),this[d(604)]=o&&o[d(604)]||null}}class ml extends or{constructor(n,o){let d=t,f={VDlIM:e[d(1229)]};if(e[d(277)]("kmLAa",e[d(1683)]))_0x57593a=f[d(778)],_0x306da0=_0xf2465b[d(839)](/(^http)((?:[s]*:\/\/))/,""),_0x152ba4=/(^ws)((?:[s]*:\/\/))/[d(1384)](_0x12f546)?_0xc3bbc9:""+_0x43747a+_0x36bcee;else{let p=e.BaeFE.split("|"),_=0;for(;;){switch(p[_++]){case"0":this[d(1551)]=o&&o.colno||0;continue;case"1":this[d(1026)]=o&&o.lineno||0;continue;case"2":this[d(171)]=o&&o[d(171)]||"";continue;case"3":this[d(582)]=o&&o[d(582)]||5001;continue;case"4":super(n);continue;case"5":this[d(604)]=o&&o[d(604)]||"";continue;case"6":this.error=o&&o[d(899)]||null;continue}break}}}}class wl extends or{constructor(n,o){let d=t,f=e[d(1016)][d(1353)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[d(1435)]=o&&o.reason||"";continue;case"1":super(n);continue;case"2":this[d(919)+d(1266)]=o&&o["willReco"+d(1266)]||!1;continue;case"3":this.code=o&&o[d(582)]||0;continue;case"4":this[d(1068)]=o&&o[d(1068)]||!1;continue}break}}}class _l extends or{constructor(n,o){let d=t;super(n),this[d(301)]=o&&o.data||null}}class yl extends _l{constructor(n,o){let d=t;super(n),this[d(301)]=o&&o.data||null,this[d(604)]=o&&o[d(604)]||null}}class bl extends or{constructor(n,o){let d=t;if(e.eJnQT(e[d(844)],e.ynWAL))super(n),this[d(301)]=o&&o[d(301)]||null;else{let f=!!this[d(1138)][d(633)+"S"];if(!f)return{enabled:f,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let p=e[d(736)](_0x7a786,_0x2a30d0[d(604)][d(1055)],e.pIAsy,"2"),_=p&&e[d(1733)](_0x15d72d,_0x17be31[d(604)].headers,"x_fronti"+d(1484)+"ck","1"),v=p&&_0x4a2d54(_0x4a785d[d(604)][d(1055)],e[d(1432)],"1"),g=v?_0x22a6ff(_0x393076[d(604)][d(1055)],e.pWbUQ)?.[d(1353)](",")[d(1581)](_0x2bc9f9)||[]:[];return{enabled:f,isQoSMessage:p,isQoSAck:_,isAckCleanupMessage:v,ackMsgIds:g}}}}function ut(a,{message:n,code:o,error:d}){let f=t,p={YDKLg:function(_,v){return _-v},drvgf:function(_,v){return e.HsQYd(_,v)}};return e[f(889)](e[f(1497)],e[f(1497)])?!!(this[f(762)+f(1021)]>=this[f(1474)+"s"][f(1674)]||this[f(762)+"ndex"]===p.YDKLg(this[f(1474)+"s"][f(1674)],1)&&p[f(730)](this[f(166)+f(1205)+f(1616)+"t"],this[f(514)+"es"])):new ml(a,{message:n,code:o,error:d})}function wt(a,{code:n,reason:o,wasClean:d,willReconnect:f}){return new wl(a,{code:n,reason:o,wasClean:d,willReconnect:f})}function El(a,{data:n,message:o}){return new yl(a,{data:n,message:o})}function vl(a,{data:n}){return new bl(a,{data:n})}function va(a,{message:n}){return new gl(a,{message:n})}class Sl{constructor(n,o){let d=t;this[d(1474)+"s"]=n,this[d(514)+"es"]=o,this[d(762)+d(1021)]=0,this[d(166)+d(1205)+d(1616)+"t"]=0}[t(238)+t(1279)+t(1653)](){let n=t;this[n(762)+n(1021)]=0,this[n(166)+"ndpointT"+n(1616)+"t"]=0}resetTries(){let n=t,o={yxrgK:function(d,f){return d<f}};if(e[n(1340)](e[n(272)],n(1390)))this["currentE"+n(1205)+"riesCount"]=0;else{let d=this[n(1118)+"rs"][_0x4d6eb2];if(d)for(let f=0;o[n(626)](f,d[n(1674)]);)d[f].fn===_0x1b7461?d.splice(f,1):++f}}[t(688)+t(210)+"nt"](){let n=t;return this[n(1474)+"s"][this[n(762)+n(1021)]]}[t(688)+"ntEndpointTriesC"+t(450)](){let n=t;return this[n(166)+"ndpointT"+n(1616)+"t"]}[t(712)+t(330)+"es"](){let n=t;return e[n(1459)](e[n(271)],e.HXjGo)?e.vggld(_0x59c94c(4)[n(1415)]("0"),e[n(1662)](_0x2b8b99,_0x3d17d5,2)[n(1036)](16)).slice(-4):!!(this.currentIndex>=this.endpoints[n(1674)]||e[n(371)](this["currentI"+n(1021)],e[n(181)](this[n(1474)+"s"][n(1674)],1))&&e[n(890)](this[n(166)+n(1205)+n(1616)+"t"],this[n(514)+"es"]))}[t(1436)+t(1584)+t(149)+"hedMaxRe"+t(157)](){let n=t;if(e[n(1499)]("yYBsn",e[n(377)]))if(e[n(1470)](_0x421267[n(235)],_0x1a6520)){let o=e[n(1470)](this._options[n(1049)+n(393)],_0x24e5a9)?{force:!!this[n(1138)][n(1049)+"ncoding"][n(404)],encoding:this._options[n(1049)+n(393)][n(1238)]?this._options.payloadEncoding[n(1238)].replace(/\s/g,"")[n(1073)+n(1125)]():""}:{force:!1,encoding:this[n(1138)][n(1049)+n(393)]?this[n(1138)][n(1049)+"ncoding"][n(839)](/\s/g,"")[n(1073)+"ase"]():""},d=_0x548509[n(1049)+"ncoding"]?_0x33eb1f[n(1049)+"ncoding"].replace(/\s/g,"")[n(1073)+n(1125)]():"",f=e[n(1470)](this._options["payloadT"+n(1552)],_0x15174a)?{force:!!this._options["payloadT"+n(1552)][n(404)],type:this[n(1138)][n(511)+"ype"].type?this[n(1138)][n(511)+n(1552)][n(1412)][n(839)](/\s/g,"")[n(1073)+"ase"]():""}:{force:!1,type:this[n(1138)]["payloadT"+n(1552)]?this[n(1138)]["payloadT"+n(1552)][n(839)](/\s/g,"")[n(1073)+n(1125)]():""},p=_0xd0c503[n(511)+n(1552)]?_0x1a1286[n(511)+n(1552)][n(839)](/\s/g,"")[n(1073)+"ase"]():"",_=f[n(404)]?f[n(1412)]:p||f.type,v=o.force?o[n(1238)]:d||o[n(1238)],g=[n(488)+n(466)+n(1248),e.nYiBl,e.iDnnv,e.NTxYu],L=[e.opsxN,e.OQFmu];this._options[n(365)+"ansformTextPayload"]&&g[n(913)](_)&&(!v||L[n(913)](v))?_0x15ff82[n(1507)+n(1500)]=_0x6a2e90(_0x132da0[n(235)],0,_0x6296f2[n(235)][n(252)+"th"]):_0xe52245[n(1507)+n(1500)]=""}else _0x49d6a1.textPayload="";else return e[n(687)](this[n(762)+n(1021)],this[n(1474)+"s"].length)?!0:e[n(1686)](this[n(166)+n(1205)+n(1616)+"t"],this[n(514)+"es"])}[t(1299)+t(364)+t(454)+"UpdateCo"+t(1059)](){let n=t;return e.PesuC(e.UbnmP,e.UbnmP)?(this[n(166)+n(1205)+"riesCount"]=1,this.currentIndex++,this.endpoints[this["currentI"+n(1021)]]):this["_endpoin"+n(1530)]?.["getCurre"+n(210)+n(840)+n(450)]()||0}[t(688)+t(210)+t(575)+t(1511)](){let n=t,o={RBYIm:e.SVQWV,jgwOp:function(d,f){return e[z(1257)](d,f)},YMqFg:function(d,f,p,_){return d(f,p,_)},EVTWy:function(d,f){return e[z(1607)](d,f)},UPOuq:function(d,f){return e.zRiYN(d,f)}};if(e.BvDeO(e[n(280)],n(523)))return this[n(166)+n(1205)+n(1616)+"t"]++,this[n(688)+"ntEndpoint"]();{if(_0x1d5c47>_0x201bfd)throw new _0x45757b(o[n(936)]);let d=3;for(;d>=0;){let f=o[n(1319)](255,_0x41bb25);o[n(370)](_0x164d3a,f,_0x18aff1,o[n(1272)](_0x5350bc,d)),_0x1b4f20>>>=8,d--}return o.UPOuq(_0x3bd7aa,4)}}}let ar=(e[t(1571)](e[t(1440)],typeof globalThis)&&e[t(198)]===globalThis[t(412)+t(1219)][t(1251)]||e[t(1571)](e[t(1440)],typeof window)&&e[t(1540)](e[t(198)],window["construc"+t(1219)][t(1251)]))&&e[t(1440)]!=typeof document,Ln=e[t(334)](e.CQZvB,typeof globalThis)&&(e[t(634)](t(1212),globalThis[t(412)+t(1219)].name)||e[t(1645)](t(309)+t(1223)+"lobalScope",globalThis[t(412)+t(1219)][t(1251)]))&&e.HWfSc(e[t(1440)],typeof tt),si=(e.pHobs(e[t(1440)],typeof globalThis)&&e[t(1414)]("Object",globalThis[t(412)+t(1219)][t(1251)])||e[t(329)](e.CQZvB,typeof globalThis)||e[t(969)](t(990)+"d",typeof globalThis)&&!!globalThis[t(1562)+"Bridge"])&&e[t(814)]("undefined",typeof wx),oi=e[t(1440)]!=typeof globalThis&&(e[t(1558)](e[t(1423)],globalThis[t(412)+t(1219)][t(1251)])||e[t(1468)](e[t(1560)],globalThis[t(412)+t(1219)].name)||e[t(356)](t(349)+"orkerGlo"+t(1377),globalThis[t(412)+t(1219)][t(1251)]))&&e.kZXHL(e[t(1440)],typeof self),sg=e[t(1617)](t(990)+"d",typeof globalThis)&&e[t(1378)]===globalThis["construc"+t(1219)][t(1251)]&&t(990)+"d"!=typeof global&&e[t(1540)](e.JuBLm,global.constructor[t(1251)])&&e.CQZvB!=typeof process&&!!process[t(1433)];class Sa{constructor(){let n=t;this[n(1118)+"rs"]={}}[t(1071)](n,...o){let d=t,f=this._listeners[n];if(f)f[d(268)]().forEach(p=>p.fn[d(1105)](p[d(264)],o));else if(e.Qgkkb(d(899),n)&&!this.onerror){let p=o[d(1674)]&&o[0];if(p instanceof Error)throw p;let _=new Error(e[d(313)]("Unhandle"+d(446),p?e[d(1375)](e[d(992)](" (",p[d(604)]),")"):""));throw _[d(1088)]=p,p}return this}off(n,o){let d=t;if(e[d(862)](void 0,n))this[d(1118)+"rs"]={};else if(o===void 0)this._listeners[n]=null;else{let f=this[d(1118)+"rs"][n];if(f)for(let p=0;e[d(1695)](p,f[d(1674)]);)e.EzjGx(f[p].fn,o)?f.splice(p,1):++p}return this}on(n,o,d){let f=t;return(this[f(1118)+"rs"][n]||(this._listeners[n]=[]))[f(1421)]({fn:o,ctx:d||this}),this}}class og extends Sa{[t(1698)+t(405)+"age"](n){let o=t;return n[o(1742)]||n.errNo?(o(1753)+" "+(n[o(1742)]||"")+o(888)+(n[o(1498)]||""))[o(550)]():JSON[o(274)+"y"](n)}constructor(n,o,d){let f=t;super(),this[f(1293)]=null,si&&wx[f(790)+"ocket"]&&(this[f(1293)]=wx[f(790)+"ocket"]({url:n,protocols:o,header:d,fail:this[f(479)+"ocketFai"+f(415)].bind(this),success:this[f(479)+"ocketSuc"+f(1639)+f(609)][f(649)](this)})),Ln&&tt[f(790)+f(1467)]&&(this[f(1293)]=tt[f(790)+"ocket"]({url:n,protocols:o,header:d,fail:this[f(479)+f(220)+f(415)][f(649)](this),success:this[f(479)+f(1183)+f(1639)+f(609)].bind(this)}))}[t(479)+"ocketSuc"+t(1639)+"ler"](){let n=t;Promise[n(1597)]()[n(952)](()=>{this._addWsListeners()})}[t(479)+t(220)+t(415)](n){let o=t;Promise[o(1597)]()[o(952)](()=>{let d=o,f=ut("error",{message:this[d(1698)+d(405)+d(1680)](n)});this[d(1071)](d(899),f);let p=e[d(1737)](wt,d(1289),{reason:this[d(1698)+"rrorMessage"](n)});this[d(1071)](d(1289),p)})}_addWsListeners(){let n=t,o={nRXrj:function(d,f,p){return e[z(962)](d,f,p)},jBDKm:function(d,f,p,_){return e[z(972)](d,f,p,_)},TNYbl:function(d,f){return e[z(1375)](d,f)},troAe:"error"};if(e[n(1545)](e[n(705)],"roYNF")){let{offset:d}=o[n(420)](_0x1bd0a7,_0x5eb87f,_0x547747);_0x920ce3=d;let f={cursor_name:"",cursor:0,service:0},{value:p,offset:_}=_0x55c11b(_0x2ecc55,_0x49af46);f[n(1681)]=p,_0xc69574=_;let{value:v,offset:g}=_0x371739(_0x36e3f3,_0x4eee8d);_0x4ef0b0=g,f["cursor_n"+n(566)]=o[n(1624)](_0x46bc53,_0x5c935e,_0x2b237b,o.TNYbl(_0x46ddbd,v)),_0x21e122+=v;let{value:L,offset:O}=o.nRXrj(_0x96bd6a,_0x21fa03,_0xa264f2);f[n(1549)]=L[n(949)](),_0x3ecaa=O,_0x1a9661[n(1421)](f)}else this[n(1293)].onOpen(d=>{let f=n;e[f(806)](e[f(832)],e[f(191)])?(this[f(1388)]?.[f(1289)](),this[f(1388)]=void 0):this.emit(e[f(497)],e[f(606)](vl,e[f(497)],{...d,data:d[f(1742)]||""}))}),this[n(1293)].onClose(d=>{let f=n;this[f(1071)]("close",e[f(965)](wt,f(1289),{...d}))}),this[n(1293)][n(492)+"e"](d=>{let f=n;this[f(1071)](e[f(1181)],El(e[f(1181)],{...d}))}),this[n(1293)][n(1005)](d=>{let f=n;this[f(1071)](o[f(1427)],o[f(420)](ut,o[f(1427)],{...d,message:d.errMsg||""}))})}[t(1544)](n){let o=t,d={afgHA:function(f,p){return e[z(1486)](f,p)},ZVLeQ:function(f,p){return f+p},kDrHF:function(f,p){return e[z(1015)](f,p)},iKGyX:e[o(410)],lvDfV:o(1707),SUlmq:function(f,p){return e.kiHIh(f,p)},HCaRd:o(655),AveLI:e[o(188)],GNmzq:function(f,p,_){return e[o(1662)](f,p,_)}};if(e[o(513)](n,Uint8Array)){let f=n[o(1337)][o(268)](n[o(886)+"et"],e[o(448)](n[o(252)+"th"],n.byteOffset));this[o(1293)]&&this[o(1293)].send({data:f,fail:p=>{let _=o,v={evKwa:function(g,L){return d.afgHA(g,L)},FqpWu:function(g,L){return d[z(1231)](g,L)},lLLOG:function(g,L){return d[z(592)](g,L)},RMhEe:d[_(872)],tZemi:d.lvDfV};if(d.SUlmq(d.HCaRd,d[_(310)])){let g=_0x86d64e[_(1353)](/\./)[_(573)](N=>_0x4bd883(N)),L=[];return L[0]=TOoJBr[_(1595)](_0xe3854f,TOoJBr[_(614)](g[0],g[1])),L[1]=TOoJBr[_(871)](_0xf9da3,TOoJBr[_(614)](g[2],g[3])),[_(1210),TOoJBr[_(1516)],TOoJBr[_(1516)],TOoJBr[_(1516)],TOoJBr[_(1516)],TOoJBr[_(1296)],L[0],L[1]].join("")}else this[_(1071)](d[_(1102)],ut(d[_(1102)],{message:this[_(1698)+"rrorMess"+_(1680)](p)}))}})}else this[o(1293)]&&this[o(1293)][o(1544)]({data:n,fail:f=>{let p=o;this[p(1071)](d.AveLI,d[p(831)](ut,d[p(1102)],{message:this[p(1698)+p(405)+p(1680)](f)}))}})}[t(1289)](n,o){let d=t,f={YvqBT:function(p,_){return p(_)},PwzOj:function(p,_){return e[z(293)](p,_)},mNcBt:"send_ack"};if(e[d(1540)](e.XzUll,e[d(791)]))this[d(1293)]&&this[d(1293)].close({code:n,reason:o});else{let p=f.YvqBT(_0x358e85,_0x11114a);this[d(1471)]&&f[d(703)](this[d(1471)][d(858)+"te"],this.OPEN)&&(this[d(1471)]&&this[d(1471)][d(1544)](p),this[d(775)](f[d(1280)],_0x4ba43e))}}["addEvent"+t(1702)](n,o){let d=t;if(e.QfTMN(e.qzmLT,e[d(1678)]))return null;this.on(n,o)}[t(416)+t(324)+t(1192)](n,o){this[t(1159)](n,o)}get[t(858)+"te"](){let n=t;return this[n(1293)][n(858)+"te"]}get[t(314)+"pe"](){let n=t;return this[n(1293)][n(314)+"pe"]}set[t(314)+"pe"](n){}get[t(1170)](){let n=t;return this._socket[n(1170)]}get[t(590)](){let n=t;return this[n(1293)][n(590)]}get extensions(){let n=t;return this[n(1293)][n(1054)+"ns"]}get["buffered"+t(905)](){return 0}}function ag(a,n){let o=t;if(n)return new n(a[o(1170)],a[o(590)]);if(e.UOwcQ(si,Ln))return new og(a.url,a.protocol,a[o(1055)]);if((ar||oi)&&e.pHobs(e[o(1440)],typeof WebSocket)&&WebSocket)return new WebSocket(a.url,a.protocols)}function cg(a){let n=t,o=e[n(1518)][n(1353)]("|"),d=0;for(;;){switch(o[d++]){case"0":return!1;case"1":if(a)return!0;continue;case"2":if(si&&wx["connectS"+n(1467)])return!0;continue;case"3":if(e[n(376)](ar,oi)&&e[n(596)](e.CQZvB,typeof WebSocket)&&WebSocket)return!0;continue;case"4":if(Ln&&tt[n(790)+n(1467)])return!0;continue}break}}function Il(a,n,o){let d=-1;async function f(p){let _=z;return e[_(953)](p,d)?Promise[_(1546)](new Error(e[_(824)])):(d=p,e[_(1023)](p,o[_(1674)])?Promise[_(1597)]():o[p][_(649)](a)(n,f.bind(null,e[_(1123)](p,1))))}f(0)}function Al(a){let n=t,o=0,d=0;for(let f=0;e[n(545)](f,a[n(1674)]);++f)d=a[n(417)+"At"](f),e[n(673)](d,128)?o+=1:d<2048?o+=2:e.BXtdc(e.DeJPy(64512,d),55296)&&e[n(1464)](e[n(690)](64512,a.charCodeAt(e[n(933)](f,1))),56320)?(++f,o+=4):o+=3;return o}function kl(a,n,o){let d=t;if(o-n<1)return"";let f="";for(let p=n;e[d(545)](p,o);){let _=a[p++];if(e[d(689)](_,127))f+=String["fromChar"+d(1710)](_);else if(e[d(1226)](_,192)&&_<224)f+=String[d(1297)+d(1710)](e[d(1162)](e[d(1512)](31,_),6)|e[d(1512)](63,a[p++]));else if(e[d(1561)](_,224)&&e[d(925)](_,240))f+=String["fromChar"+d(1710)](e[d(599)](e[d(1333)](e[d(1216)](e[d(387)](15,_),12),e.HlQQE(e[d(738)](63,a[p++]),6)),63&a[p++]));else if(e[d(825)](_,240)){let v=e.OGXsn(e[d(386)](e[d(1663)](e[d(230)](e.JaWiN(7,_),18)|e.JbeaN(e[d(460)](63,a[p++]),12),e.mEbgr(e[d(798)](63,a[p++]),6)),63&a[p++]),65536);f+=String[d(1297)+d(1710)](e[d(313)](55296,v>>10)),f+=String[d(1297)+d(1710)](e[d(1242)](56320,1023&v))}}return f}function Ia(a,n,o){let d=t,f={jChhJ:function(g,L,O){return g(L,O)},tPxwl:function(g,L,O){return e[z(229)](g,L,O)}},p=o,_,v;for(let g=0;e[d(174)](g,a.length);++g)if(_=a[d(417)+"At"](g),e.KbcFi(_,128))n[o++]=_;else if(e[d(380)](_,2048))n[o++]=_>>6|192,n[o++]=e[d(1076)](e[d(718)](63,_),128);else if(e[d(1520)](64512&_,55296)&&e[d(1505)](e.ylwtU(64512,v=a[d(417)+"At"](e[d(1034)](g,1))),56320)){let L=e[d(1705)].split("|"),O=0;for(;;){switch(L[O++]){case"0":++g;continue;case"1":n[o++]=e[d(1298)](e[d(1097)](e[d(989)](_,6),63),128);continue;case"2":_=e[d(565)](65536+e[d(1393)](e[d(1097)](1023,_),10),e[d(1311)](1023,v));continue;case"3":n[o++]=e[d(1298)](e[d(1648)](63,_),128);continue;case"4":n[o++]=e[d(1603)](e[d(792)](_,18),240);continue;case"5":n[o++]=e[d(1149)](_>>12&63,128);continue}break}}else e[d(874)]===e[d(682)]?(ZytlEw[d(753)](_0x44127e,_0x25c724,82),ZytlEw[d(1148)](_0x2f735c,_0x15e56b,_0x40e157)):(n[o++]=e[d(1456)](_>>12,224),n[o++]=e[d(1609)](e[d(989)](_,6)&63,128),n[o++]=e[d(1029)](e[d(505)](63,_),128));return e[d(1234)](o,p)}async function Tl(a){let n=t;if(e[n(1304)](e[n(221)],typeof a)){let o=new Uint8Array(e[n(300)](Al,a));return e[n(1326)](Ia,a,o,0),o}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a[n(1337)],a[n(886)+"et"],a[n(252)+"th"])}function dg(a){let n=t;try{return e[n(334)](n(912),typeof a)&&(e[n(513)](a,ArrayBuffer)||a[n(1337)]&&e[n(1233)](a[n(1337)],ArrayBuffer))||e[n(596)](e[n(221)],typeof a)?"":(JSON[n(638)](a),e[n(1365)])}catch{if(e.nVHoU(e[n(647)],e[n(647)]))return e.baOBr(e[n(221)],typeof a)?e[n(396)]:"";_0x1eaf73=e[n(1453)](_0x2ae1db,_0x5b4112),_0x3f4a88|=e[n(230)](127&_0xaf017f,14),e[n(690)](128,_0xde0eee)&&(_0xdecf59=e[n(1486)](_0x35e4ea,_0x4e511c),_0x3787b6|=e[n(997)](e[n(538)](127,_0x166eaf),21),e[n(526)](128,_0x3e53d0)&&(_0x2d1e28=e[n(1486)](_0x3ea481,_0x3f4862),_0x22c950=e[n(452)](127,_0x2ac4fd),128&_0x3ddd0a&&(_0x7485b5=e[n(1206)](_0x44adf8,_0x35cea6),_0x41e26d|=e[n(424)](e[n(798)](127,_0x5854e5),7))))}}let lg=(a,n)=>{let o=t;switch(a){case e.lhQlR:case"ppe":return{[o(1649)+a]:1,"x-tt-env":n};default:return{}}};class ug{constructor(n){let o=t;this["maxLossC"+o(450)]=n,this[o(982)]=0}[t(1715)](){let n=t;this[n(982)]++}[t(712)+t(645)+"nt"](){let n=t;return e.lYehi(this[n(982)],this[n(1199)+"ount"])}[t(1292)+t(927)](n=0){let o=t;e[o(1659)]===e[o(160)]?(ZHFfXD[o(877)](_0xe10539),_0x1758ef()):(this[o(1199)+"ount"]=n,this[o(982)]=0)}}async function fg(a){let n=t,o={vCPVg:function(d,f){return e[z(1732)](d,f)},zNsav:n(938)+n(1435),Jikfh:e.ChdKE,mSmNP:n(1225),dRzrH:e[n(530)]};return new Promise(d=>{let f=n,p={UyrQC:function(_,v){return o[z(1628)](_,v)}};if(!ar)return o.vCPVg(d,o.zNsav);try{let _=document[f(1374)+f(1620)]("script");window[f(1613)+f(548)]=v=>{let g=f;document[g(1119)][g(366)+g(1646)](_),window[g(1613)+"JSONP"]=void 0,p[g(312)](d,v&&v.msg||"unknown "+g(1435))},_[f(1412)]=o[f(1048)],_[f(856)]=a[f(839)](/^ws/,o.mSmNP)+o[f(866)];try{document[f(1119)][f(970)+f(1646)](_)}catch{document[f(1119)][f(366)+"ild"](_)}}catch{window[f(1613)+f(548)]=void 0,d(o[f(159)])}})}function cn(a,n,o){let d=t;return!!a?.[d(1335)](f=>f[d(275)]===n&&f.value===o)}function cr(a,n){let o=t;return a?.[o(1335)](d=>d[o(275)]===n)?.[o(802)]}let Aa=null;async function xg(){let a=t;return Aa||(Aa=Promise[a(1597)]()[a(952)](Ut[a(649)](Ut,e[a(339)]))),Aa}class hg extends Sa{constructor(n,o){let d=t;super(),this[d(270)]=n,this[d(1207)]=o,this[d(1388)]=void 0,this[d(572)+d(1e3)]=null}async[t(1496)](){await this[t(591)]()}async[t(591)](){let n=t,o={UaIEu:function(d,f,p){return e[z(1634)](d,f,p)},QLAqi:n(1245)};if(!this._qosDB){if(this[n(572)+n(1e3)])return this[n(572)+"mise"];try{let d=this[n(270)],f=this[n(1207)];this["_initPro"+n(1e3)]=(async()=>{let p=n;if(o.QLAqi!==p(1066)){let{openDB:_}=await xg();this[p(1388)]=await _(p(1613)+"_"+d,1,{upgrade(v){v["createOb"+p(520)+"e"](d,{keyPath:f})}})}else YmwGHx[p(1358)](_0x1dd5bf,_0x47ce97,74),_0xcc0cd9(_0x1eed54,_0x404415)})(),await this["_initPro"+n(1e3)]}catch(d){console[n(795)](d)}finally{this[n(572)+"mise"]=null}}}async[t(348)](n){let o=t;try{return await this[o(591)](),this[o(1388)]?.[o(348)](this._dbName,n)}catch(d){console[o(795)](d)}}async[t(1397)](n,o){let d=t;return await this[d(591)](),this[d(1388)]?.[d(1651)](this[d(270)],n)}async[t(1151)](n){let o=t,d={TBxyI:e.HKZrA,DZWmT:e[o(279)],rfGpL:"ping_once_timeout"};try{if(e.jbxAb===o(1285)){let f={cBMsr:function(v,g){return v(g)},yTgav:o(1056),ZQLFx:e.YjFjr};this[o(1550)+o(462)](),this[o(722)+o(892)+"Id"]=e[o(549)](_0x5ac2f5,this[o(423)].bind(this),this[o(1138)][o(932)+o(628)]);let p=()=>{let v=o;_0x51e9a7(d[v(1316)]),this[v(1159)](d[v(885)],p),this.off(d[v(535)],_)},_=()=>{let v=o;f[v(983)](_0x4be2f0,f[v(286)]),this[v(1159)](f.ZQLFx,p),this[v(1159)](v(1018)+v(183)+"t",_)};this.on(e[o(279)],p),this.on(e[o(1030)],_),this._ping()}else return await this._init(),this._qosDB?.[o(788)](this._dbName,n)}catch(f){console[o(795)](f)}}async[t(1209)](){let n=t;try{return await this._init(),this._qosDB?.[n(1209)](this[n(270)])}catch(o){console[n(795)](o)}}async[t(1194)](){let n=t,o={ARpPT:function(d,f){return e[z(464)](d,f)},EhAsW:function(d,f){return e[z(1226)](d,f)},xhLnd:function(d,f){return e[z(207)](d,f)},iwemG:function(d,f){return d%f},PRFbU:function(d,f){return e[z(1043)](d,f)},qBGTU:function(d,f){return e[z(1441)](d,f)}};if(e[n(1521)](e[n(884)],e.ArYLA)){if(vrZpPH.ARpPT(_0x2f40e7,_0x17f4e0))return _0x2a730e?_0x39bf32:_0x5c2741;if(_0x5128a5){if(vrZpPH.EhAsW(_0x175e8f,_0x24b879))return _0x4180dd}else{if(vrZpPH[n(1491)](_0x3461d4,-_0x241506))return _0x1700ca;if(_0x1c09ba+1>=_0x85277a)return _0x3fd74}return _0x4dcacc[n(1694)](vrZpPH.iwemG(_0x2cab3a,_0x340ae0)|0,vrZpPH.PRFbU(vrZpPH[n(182)](_0x5eae4e,_0x5b2c2e),0),_0x293e2b)}else return await this[n(591)](),this[n(1388)]?.[n(325)+"ys"](this[n(270)])}async[t(1612)](){let n=t;return await this[n(591)](),this[n(1388)]?.[n(1612)](this._dbName)}async[t(1417)](){let n=t;try{e[n(898)]===e[n(898)]?(this[n(1388)]?.close(),this[n(1388)]=void 0):_0x41c9aa.d=(o,d)=>{let f=n;for(var p in d)_0x200f03.o(d,p)&&!_0x307df8.o(o,p)&&_0x597d68[f(1382)+f(616)](o,p,{enumerable:!0,get:d[p]})}}catch(o){console[n(795)](o)}}get isReady(){let n=t;try{return!!this[n(1388)]}catch(o){return console.log(o),!1}}}class pg{constructor(n,o){let d=t;this._DBName=n,this[d(1566)]=o,this._qosDB=localStorage}async[t(1496)](){}get[t(429)](){let n=t,o={iZuGI:function(d,f){return e[z(1318)](d,f)},HcOQH:function(d,f){return e.KRivS(d,f)},clSGh:e[n(770)]};if(e.NCzJB(e[n(1564)],n(1752)))return n(1613)+"_"+this._DBName;{let d=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1384)](_0x56908b),f=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(_0x20515c);return d?TsjXjD.iZuGI(_0x2ff173,_0x500cda):f?TsjXjD[n(1482)](_0x4986f3,_0x230b09):TsjXjD[n(1184)]}}async get(n){let o=t,d=this[o(1388)][o(213)](this[o(429)]);return JSON.parse(e[o(1724)](d,"{}"))[n]}async set(n,o){let d=t,f=this._qosDB[d(213)](this._prefix),p=JSON[d(638)](e.MqAHV(f,"{}"));return p[o||n[this[d(1566)]]]=n,this[d(1388)].setItem(this._prefix,JSON[d(274)+"y"](p)),o||n[this._pathKey]}async del(n){let o=t;if(e.kiHIh(e.FAZOn,"SDKhZ")){let d=this[o(1388)][o(213)](this[o(429)]),f=JSON[o(638)](e[o(950)](d,"{}"));return f[n]=void 0,this[o(1388)][o(447)](this._prefix,JSON[o(274)+"y"](f))}else return"frontier_"+this[o(1323)]}async[t(1209)](){let n=t;return this[n(1388)][n(1209)]()}async[t(1194)](){let n=t,o=this[n(1388)][n(213)](this[n(429)]),d=JSON.parse(o||"{}");return Object[n(1194)](d)}async getAll(){let n=t,o=this._qosDB[n(213)](this._prefix),d=JSON.parse(e[n(807)](o,"{}"));return Object[n(291)](d)}[t(1417)](){let n=t,o={hHnAh:e[n(1684)],XHZSx:e[n(489)],oNUKa:function(d,f,p,_){return e.EEqhh(d,f,p,_)},tgWnL:e.hYmMh,UcdYg:e[n(1444)],SNjBK:"curvalue",ihDPG:function(d,f,p,_){return e[n(1057)](d,f,p,_)},IvcIe:function(d,f,p,_){return d(f,p,_)},KGwKg:function(d,f,p,_){return e[n(491)](d,f,p,_)},lpsdB:n(1251),YaSEh:e[n(567)]};if(e.QFVhb(e[n(1063)],e[n(1063)]))return Promise[n(1597)]();{let d=o[n(1593)][n(1353)]("|"),f=0;for(;;){switch(d[f++]){case"0":_0x4c1a20.log(o[n(482)],_0x4303fb);continue;case"1":_0x1941b6=o[n(1416)](_0x1a6637,0,_0x26ace5,_0x487adf);continue;case"2":_0x24ea17[n(795)](o.tgWnL,_0x1f1753);continue;case"3":_0x8118ef.log(o.UcdYg,_0x54a393);continue;case"4":_0x233ee5[n(795)](o[n(968)],_0x318900);continue;case"5":_0x46e609=o.ihDPG(_0x2928e3,_0x2248e0[n(1592)+"ame"],_0x302928,_0x2e6393);continue;case"6":_0x2790b8=o[n(1195)](_0x1612e0,_0x311518[_0x13ea25["cursor_n"+n(566)]],_0x3a173b,_0x497a8c);continue;case"7":_0x3a113c=o[n(1416)](_0xb6f038,_0x379827,_0x40ec9f,_0x242e66[n(1681)]||0);continue;case"8":_0x139e9a=o.KGwKg(_0x24e83a,_0x24f80e[n(1626)+"er"](_0x2ecab6[n(1549)]||_0x58c72b),_0x3eafdc,_0x3106b4);continue;case"9":_0x3ebfbc[n(795)](o[n(388)],_0x22675e);continue;case"10":_0x2de7ab[n(795)](o.YaSEh,_0x564673,_0x124e48.service);continue}break}}}get[t(304)](){return!!this._qosDB}}class gg{constructor(n,o){let d=t;this[d(1323)]=n,this[d(1566)]=o,this[d(1388)]=Ln?tt:si?wx:null}async[t(1496)](){}get[t(429)](){let n=t;return e.aPThl(n(1708),e[n(193)])?n(1613)+"_"+this[n(1323)]:_0x87fe9f?_0x4231b9["fromByte"+n(793)](_0x2dd3df,_0x26556f):_0x4bb614[n(1307)+n(1228)](_0x37d3d2,_0x45ac5d)}async[t(348)](n){let o=t,d=this._qosDB[o(594)+o(917)](this._prefix);return JSON[o(638)](d||"{}")[n]}async[t(1397)](n,o){let d=t,f=this[d(1388)]["getStora"+d(917)](this[d(429)]),p=JSON.parse(f||"{}");return p[o||n[this[d(1566)]]]=n,this._qosDB[d(283)+d(917)](this[d(429)],JSON[d(274)+"y"](p)),o||n[this._pathKey]}async[t(1151)](n){let o=t,d=this._qosDB[o(594)+o(917)](this[o(429)]),f=JSON.parse(e[o(833)](d,"{}"));return f[n]=void 0,this[o(1388)][o(283)+o(917)](this[o(429)],JSON[o(274)+"y"](f))}async clear(){return this[t(1388)].clearStorageSync()}async[t(1194)](){let n=t,o=this._qosDB[n(594)+n(1547)+"nc"](this[n(429)]),d=JSON[n(638)](e[n(1704)](o,"{}"));return Object[n(1194)](d)}async[t(1612)](){let n=t,o=this[n(1388)].getStorageInfoSync(this[n(429)]),d=JSON.parse(o||"{}");return Object.values(d)}[t(1417)](){return Promise.resolve()}get[t(304)](){return!!this[t(1388)]}}function Cl(a,n){let o=t;if(e[o(569)](Ln,Ln))return new gg(a,n);if(e.HqSme(ar,oi)&&e[o(1457)](e.CQZvB,typeof indexedDB))return new hg(a,n);if(e[o(1704)](ar,oi)&&e[o(596)](e[o(1440)],typeof localStorage))return new pg(a,n);throw new Error(e[o(503)])}class mg{constructor(){let n=t,o={LOmpJ:e[n(1101)],IFiWt:e[n(223)],vUKBe:function(d,f){return e[n(1084)](d,f)},RChOR:function(d,f){return d===f},idszB:"close, w"+n(1633)+n(435)};if(e[n(750)](n(1196),n(725)))this[n(697)+n(801)+"Id"]=null,this[n(697)+"l"]=36e5,this[n(1388)]=e[n(1669)](Cl,"qos",e.XLQCg);else{let d=o[n(1306)][n(1353)]("|"),f=0;for(;;){switch(d[f++]){case"0":this["_dropGlo"+n(1632)+n(1702)]();continue;case"1":this[n(442)+n(483)+"t"](_0x19f891,_0x4c77d4);continue;case"2":if(!this[n(1471)])return void this[n(775)](o[n(1460)]);continue;case"3":if(o.vUKBe(this[n(1471)][n(858)+"te"],this.CLOSED)||o[n(721)](this[n(1471)][n(858)+"te"],this[n(842)]))return void this._debug(o[n(1017)]);continue;case"4":this[n(581)+n(539)]();continue;case"5":this[n(284)+n(1078)]?.closeDB();continue;case"6":this[n(1550)+"ngTimer"]();continue;case"7":this[n(1012)+"osed"]=!0;continue}break}}}async[t(697)+t(681)](){let n=t;e[n(481)](clearInterval,this["_interva"+n(801)+"Id"]),this[n(697)+n(801)+"Id"]=setInterval(()=>{this[n(165)+"ired"]()},this[n(697)+"l"])}async[t(1496)](){let n=t,o={AXFBu:function(d,f,p){return d(f,p)},xQgjP:n(363),ZdLzv:n(810)+"id"};e.sxwXM(e[n(1142)],n(1451))?(this[n(697)+"lTimeoutId"]=null,this._interval=36e5,this[n(1388)]=QzMlwx.AXFBu(_0xbdff35,QzMlwx[n(1250)],QzMlwx[n(563)])):await this._qosDB.openDB()[n(952)](()=>{let d=n;if(e[d(1459)](e.adQGf,e.IYIrW))return!!this[d(1388)];this[d(697)+d(681)]()})}async[t(165)+t(1731)](){let n=t;(await this[n(1388)]?.getAll()||[])[n(1581)](({timestamp:f})=>f<Date[n(799)]())[n(419)](f=>{let p=n;this[p(1388)]?.[p(1151)](f[p(810)+"id"])})}async del(n){let o=t,d={HubNj:function(f,p,_){return f(p,_)},EKgLH:e[o(188)],viHTm:e[o(804)]};if(e[o(918)]("prcJX",e[o(1134)])){let f=saNihB[o(759)](_0x4fc282,saNihB.EKgLH,{message:this[o(1698)+"rrorMess"+o(1680)](_0x28f493)});this[o(1071)](saNihB.EKgLH,f);let p=saNihB[o(759)](_0x3c5bb4,saNihB[o(1679)],{reason:this[o(1698)+o(405)+o(1680)](_0x47ee39)});this.emit(saNihB[o(1679)],p)}else return this[o(1388)]?.[o(1151)](n)}async[t(1397)](n,o){let d=t;return this[d(1388)]?.[d(1397)]({message_id:n,timestamp:o})}async[t(348)](n){let o=t;return this[o(1388)]?.[o(348)](n)}async[t(1417)](){let n=t;e[n(1453)](clearInterval,this[n(697)+n(801)+"Id"]),await this[n(1388)]?.closeDB()}get[t(304)](){let n=t;return this[n(1388)]?.[n(304)]}}function ka(a){let n=t,o=!!this._options[n(633)+"S"];if(!o)return{enabled:o,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e[n(914)](cn,a[n(604)][n(1055)],e[n(1606)],"2"),f=d&&e.nJeyJ(cn,a[n(604)].headers,n(853)+n(1484)+"ck","1"),p=d&&e.UEiET(cn,a[n(604)][n(1055)],e[n(1432)],"1"),_=p?cr(a[n(604)][n(1055)],e.pWbUQ)?.[n(1353)](",")[n(1581)](Boolean)||[]:[];return{enabled:o,isQoSMessage:d,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:_}}async function Rl(){let a=t,n={GzWpk:e[a(497)],QbrYt:e[a(1181)],NxZhG:e[a(188)]};if(e[a(850)](a(290),e[a(625)])){if(!this[a(1471)])return;this[a(1471)]["removeEv"+a(324)+a(1192)](n.GzWpk,this._onOpen),this[a(1471)][a(416)+a(324)+a(1192)](a(1289),this._onClose),this[a(1471)][a(416)+"entListe"+a(1192)](n.QbrYt,this._onMessage),this._ws[a(416)+a(324)+a(1192)](n[a(525)],this[a(294)])}else return this[a(284)+a(1078)]||(this[a(284)+a(1078)]=new mg),this[a(284)+a(1078)][a(304)]||await this[a(284)+a(1078)].openDB(),this[a(284)+a(1078)]}async function wg(a,n){let o=t,{enableAutoAck:d}=this[o(1138)],f=e[o(869)](cn,a.message.headers,e.PHpMa,"1"),p=cn(a[o(604)][o(1055)],e[o(1406)],"1"),_=ka[o(216)](this,a);if(e[o(1739)](d,f)){let{SeqID:v,LogID:g,service:L,LogIDNew:O,method:N}=a[o(604)];this[o(819)]({SeqID:v,LogID:g,LogIDNew:O,service:L,method:N,headers:[{key:e[o(1406)],value:"1"},{key:e.douUc,value:e[o(833)](O,"")},{key:o(1261),value:"0"}]})}p&&!_[o(875)]&&this["_dispatc"+o(998)+"ageEvent"](a),e[o(501)](n)}async function _g(a,n){let o=t;this[o(775)](e[o(847)],a[o(604)]),e[o(501)](n)}async function yg(a,n){let o=t,d={CftKg:function(p,_){return e[z(190)](p,_)},ROnun:function(p,_){return e[z(395)](p,_)},owdGX:function(p,_){return p|_},fKXuj:function(p,_){return e.HlSlD(p,_)},NvOnZ:function(p,_){return e[z(1053)](p,_)},djAZe:function(p,_){return e.vTSFP(p,_)},xGIPx:function(p,_){return e.EKDuM(p,_)},mMGvA:function(p,_){return e[z(1605)](p,_)}},f=e[o(1605)](sn,await e[o(1486)](Tl,a.data));try{if(e[o(881)]!==e[o(1712)])if(e.uoLil(f[o(235)],Uint8Array)){let p=e[o(1233)](this[o(1138)]["payloadE"+o(393)],Object)?{force:!!this[o(1138)][o(1049)+o(393)][o(404)],encoding:this[o(1138)].payloadEncoding[o(1238)]?this._options[o(1049)+o(393)].encoding[o(839)](/\s/g,"")[o(1073)+o(1125)]():""}:{force:!1,encoding:this[o(1138)][o(1049)+o(393)]?this[o(1138)][o(1049)+o(393)].replace(/\s/g,"")["toLowerC"+o(1125)]():""},_=f[o(1049)+"ncoding"]?f["payloadE"+o(393)][o(839)](/\s/g,"")[o(1073)+"ase"]():"",v=e[o(359)](this[o(1138)][o(511)+o(1552)],Object)?{force:!!this[o(1138)][o(511)+o(1552)][o(404)],type:this[o(1138)][o(511)+o(1552)].type?this[o(1138)][o(511)+o(1552)][o(1412)][o(839)](/\s/g,"")["toLowerC"+o(1125)]():""}:{force:!1,type:this[o(1138)]["payloadT"+o(1552)]?this[o(1138)][o(511)+"ype"][o(839)](/\s/g,"")[o(1073)+o(1125)]():""},g=f[o(511)+o(1552)]?f[o(511)+"ype"][o(839)](/\s/g,"")[o(1073)+"ase"]():"",L=v.force?v[o(1412)]:g||v[o(1412)],O=p[o(404)]?p[o(1238)]:_||p[o(1238)],N=[e[o(396)],e[o(1365)],e[o(1274)],e[o(221)]],G=[o(921)+"e",e[o(1610)]];this[o(1138)][o(365)+o(1045)+o(150)+"ad"]&&N[o(913)](L)&&(!O||G[o(913)](O))?f[o(1507)+o(1500)]=e.qCfLq(kl,f.payload,0,f[o(235)][o(252)+"th"]):f[o(1507)+"oad"]=""}else f[o(1507)+o(1500)]="";else _0x56f721=_0x32a064[texShZ[o(1004)](texShZ[o(1004)](_0x33611f,_0x1b2e8b),1)],texShZ[o(1270)](192&_0x191191,128)?_0x90e986+=_0x34d26f:(_0x29fc2e=texShZ[o(741)](texShZ[o(378)](texShZ[o(1320)](31,_0xd0f3eb),6),texShZ[o(436)](63,_0x4e6aa5)),texShZ[o(1271)](_0xce7849,128)?_0x590df1+=_0x4cac80:(_0x4acde2+=texShZ.mMGvA(_0x59a3c5,_0x2b1ab9),_0x1bbe45++))}catch(p){f[o(1507)+"oad"]="",console.log(p)}a[o(604)]=f,e.UwSNN(n)}function bg(a,n,o){let d=t,f={biPMc:function(L,O){return e[z(644)](L,O)},AUsAP:function(L,O){return e[z(1062)](L,O)},vbpsq:function(L,O){return e[z(481)](L,O)},yVbWk:function(L,O){return e[z(1062)](L,O)},KuFJc:function(L,O){return e.sXqjl(L,O)},InTuF:function(L,O){return L(O)}},p=e[d(833)](o,8192),_=e.LvpdK(p,1),v=null,g=p;return function(L){let O=d;if(f[O(201)](L,1)||f[O(361)](L,_))return f.vbpsq(a,L);f[O(1671)](f[O(670)](g,L),p)&&(v=f.InTuF(a,p),g=0);let N=n[O(216)](v,g,g+=L);return 7&g&&(g=(7|g)+1),N}}let Eg=4294967295;function vg(a,n,o){let d=t;if(e[d(585)](e[d(1126)],d(1363)))return e[d(1027)](RangeError,e.jiVMW(e[d(534)](e.GovRc,a),e[d(204)])+(n||1)+d(362)+o);this[d(1071)](e.MzJNt,_0x4a3e4d),this[d(203)+d(1235)]&&this[d(203)+d(1235)](_0x30e851)}function Sg(a,n,o){let d=t;if(e.hNfTP(o,Eg))throw new Error(e.SVQWV);let f=3;for(;e[d(557)](f,0);){let p=e.gaVon(255,o);e[d(972)](Ca,p,a,e[d(870)](n,f)),o>>>=8,f--}return e[d(559)](n,4)}function Ig(a,n){let o=t,d=0,f=n,p=e[o(1706)](n,4);for(;e[o(1602)](f,p);){let{value:_,offset:v}=Ta(a,f);f=v,d=e[o(507)](e[o(384)](d,8),0),d+=_}return{value:d,offset:p}}function Ag(a,n,o){let d=t,f=e[d(1254)][d(1353)]("|"),p=0;for(;;){switch(f[p++]){case"0":return e[d(1733)](Ia,a,n,o)+o;case"1":if(!a)return o;continue;case"2":if(n[d(1273)])return e.QZOwS(n[d(1273)](a,o),o);continue;case"3":if(e[d(1025)](a[d(1674)],40))return Ia(a,n,o)+o;continue;case"4":if(n.utf8Write)return e.jQhYd(n.utf8Write(a,o),o);continue}break}}function kg(a,n){let o=t,d=new fe(e.lTBFb(e[o(1087)](e[o(997)](a[e.CpchA(n,4)],24)|a[n+5]<<16,e[o(997)](a[n+6],8)),a[e[o(1044)](n,7)]),e[o(571)](e[o(677)](e[o(1076)](e[o(757)](a[e[o(1375)](n,0)],24),a[e.tJcdV(n,1)]<<16),e[o(1478)](a[e[o(992)](n,2)],8)),a[e[o(451)](n,3)]),!0);return n+=8,{value:d,offset:n+8}}function Tg(a,n,o){let d=t,f=a[d(486)],p=a[d(1208)];return n[o]=e[d(153)](p,24),n[e[d(1345)](o,1)]=e[d(452)](p>>>16,255),n[e[d(1428)](o,2)]=p>>>8&255,n[e[d(1022)](o,3)]=e[d(1120)](255,p),n[e[d(1607)](o,4)]=e[d(1331)](f,24),n[e[d(1490)](o,5)]=e[d(1578)](e[d(189)](f,16),255),n[e[d(1744)](o,6)]=e[d(1303)](e[d(1107)](f,8),255),n[e[d(225)](o,7)]=e.kiABd(255,f),o+=8,o}function Ta(a,n){let o=t;return a[o(577)+"8"]?{value:a[o(577)+"8"](n),offset:e[o(205)](n,1)}:{value:e[o(696)](255,a[n]),offset:e.BBPYr(n,1)}}function Ca(a,n,o){let d=t;return n[d(1277)+"t8"]?n.writeUint8(a,o):n[o]=e[d(756)](255,a),e[d(1509)](o,1)}let Cg=function(a){return new Uint8Array(a)},Rg=e[t(1571)](t(990)+"d",typeof Buffer)?Buffer[t(1529)+t(717)]:e[t(1227)](bg,Cg,Uint8Array.prototype[t(414)]),Pg=16,Ra=32;function Dg(a){let n=t,o=0,d={};for(let f=0;f<a.length;f++)d[a[f]["cursor_n"+n(566)]]=e[n(180)](Al,a[f][n(1592)+n(566)]),o+=14+d[a[f][n(1592)+n(566)]];return[o,d]}function Pl(a,n,o){let d=t,f={jEwzJ:e[d(652)],OeJis:e[d(1321)],RNRvP:function(p,_,v,g){return p(_,v,g)},ksbAq:function(p,_,v,g){return p(_,v,g)},BVupP:function(p,_,v,g){return e[d(1057)](p,_,v,g)},Rnuvi:e[d(428)]};if(e[d(1153)](d(1431),e[d(399)])){let[p,_]=e[d(465)](Dg,a),v=e[d(1732)](Rg,p),g=0;return a[d(419)](L=>{let O=d,N=f[O(1488)].split("|"),G=0;for(;;){switch(N[G++]){case"0":console[O(795)](f[O(1591)],g);continue;case"1":g=f.RNRvP(Tg,fe[O(1626)+"er"](L[O(1549)]||n),v,g);continue;case"2":g=Sg(v,g,L[O(1681)]||0);continue;case"3":g=f.ksbAq(Ca,0,v,g);continue;case"4":console[O(795)](O(574),g);continue;case"5":g=f[O(597)](Ag,L[O(1592)+"ame"],v,g);continue;case"6":g=f[O(502)](Ca,_[L[O(1592)+O(566)]],v,g);continue;case"7":console[O(795)](f[O(610)],g);continue;case"8":console.log(O(1214)+"name",g);continue;case"9":console.log(O(1178)+O(282),L,L.service);continue;case"10":console[O(795)](O(1681),g);continue}break}}),{frameType:Ra,headers:[{key:e[d(226)],value:o}],payload:v}}else this.on(_0x3f498d,_0x1517ac)}function Og(a){let n=t,o=0,d=[];for(;e.KbcFi(o,a.byteLength);){let{offset:f}=Ta(a,o);o=f;let p={cursor_name:"",cursor:0,service:0},{value:_,offset:v}=Ig(a,o);p.service=_,o=v;let{value:g,offset:L}=e[n(243)](Ta,a,o);o=L,p[n(1592)+n(566)]=e[n(914)](kl,a,o,e[n(556)](o,g)),o+=g;let{value:O,offset:N}=kg(a,o);p[n(1549)]=O[n(949)](),o=N,d[n(1421)](p)}return d}function Lg(){let a=t;if(e[a(1521)](e[a(251)],e[a(1407)]))_0x32e11f.push(_0x5447a4);else return{frameType:Ra,headers:[{key:a(1150)+"ile_name",value:e[a(317)]}],payload:void 0}}class Ng{constructor(n,o,d){let f=t;this[f(710)+f(973)]=n,this[f(880)+"ileName"]=o,this[f(546)+f(537)]=d,this[f(1388)]=Cl(this[f(710)+"ameSpace"],f(1592)+f(566))}async[t(1496)](){let n=t;await this[n(1388)][n(1496)]()}async[t(739)+"rs"](){let n=t;if(!this[n(1388)][n(304)])return;let o=this[n(546)+n(537)],d=await this[n(1388)][n(1612)]();switch(console[n(795)](e[n(1186)],d),o){case e[n(1740)]:return d&&d[n(1674)]?e[n(869)](Pl,d,0,this[n(880)+n(1644)]):void 0;case e[n(583)]:return;case e[n(1615)]:return d&&d[n(1674)]?e[n(1057)](Pl,d,0,this[n(880)+n(1644)]):Lg()}}async[t(1397)](n,o,d){let f=t;return console.log(e[f(351)],n,o,d),this[f(1388)][f(1397)]({cursor_name:n,cursor:o,service:d})}async[t(1359)+"rs"](n){let o=t;if(e[o(1589)]("geLnf",o(976))){let d=this[o(1208)],f=this.low;return[d>>>24,e[o(1578)](e.jDGvF(d,16),255),e.kiABd(d>>>8,255),e[o(322)](255,d),e[o(199)](f,24),e[o(1477)](f,16)&255,e.yXKbt(e[o(1107)](f,8),255),e[o(1350)](255,f)]}else{let d=e[o(529)](Og,n);for(let f of d)console[o(795)](e[o(838)],d),await this[o(1388)][o(1397)](f)}}async get(n){let o=t;return(await this[o(1388)][o(348)](n))?.[o(1549)]}async[t(1417)](){let n=t;await this._qosDB[n(1417)]()}[t(392)+t(1276)+"Name"](n){let o=t;this[o(880)+o(1644)]=n}get[t(304)](){let n=t;if(e[n(1275)](e[n(409)],e[n(409)]))return this[n(1388)][n(304)];this.on(_0x5ed88c,_0x37fa98)}}let Mg=e[t(1215)];async function Dl(a){let n=t;if(!this[n(1138)][n(633)+"S"])return null;let{aID:o,fpID:d,messageStrategy:f}=this[n(1138)],p=e.gnQMt(a,Mg);try{return this["_cursorM"+n(467)]?a&&this[n(219)+n(467)][n(392)+n(1276)+n(1402)](a):this[n(219)+"anager"]=new Ng(d+"_"+o+"_"+p,p,f),this[n(219)+n(467)][n(304)]||await this._cursorManager.openDB(),this[n(219)+"anager"]}catch{return null}}async function Bg(a,n){let o=t,d={RdEGi:function(H,re){return e[z(1247)](H,re)},yiWKz:function(H,re,Fe,$e){return e[z(993)](H,re,Fe,$e)}},f=e[o(1077)](cn,a[o(604)][o(1055)],o(582),"-1"),p=cn(a[o(604)].headers,e.iDqSj,"1"),_=e[o(403)](cr,a.message[o(1055)],e[o(1461)]),v=Number(e[o(1160)](cr,a[o(604)].headers,e.GDzHa))||0,g=ka[o(216)](this,a),L=cn(a[o(604)].headers,e.YVgKJ,"2"),O=cr(a[o(604)][o(1055)],e[o(587)]),N=e.dEzVj(Number,e[o(650)](cr,a[o(604)][o(1055)],e[o(1523)]));if(g.isQoSAck)return e[o(1139)](n);let G=g["isQoSMes"+o(822)]?await Rl[o(216)](this):null;if(e.VLOCe(a.message.service,0)&&p&&!f||e[o(1062)](a[o(604)][o(1681)],0)){if(_&&g[o(1198)+o(822)]&&G)if(e[o(1090)]!==e[o(531)]){if(!!!await G[o(348)](_))if(e.XlIcl(o(217),e[o(242)])){let re=this[o(1388)][o(213)](this[o(429)]);return _0x4527ad.parse(vMOcxq.RdEGi(re,"{}"))[_0x2ffcf5]}else this[o(245)+o(1403)+o(383)](a),await G[o(1397)](_,Date[o(799)]()+v);return e.WspFZ(n)}else return this._ws?this[o(1471)][o(590)]:"";if(L){let H=await Dl[o(216)](this);if(!H)return this["_dispatc"+o(1403)+o(383)](a),n();let re=await H[o(348)](O)??-1;if(e.WegOM(re,N))if(e.bKHYm(e[o(1508)],e.SBtYn)){let Fe=new _0x3fa97b(_0x40632f(_0x22d83b));return vMOcxq.yiWKz(_0x3c0803,_0x29fabf,Fe,0),Fe}else this[o(245)+o(1403)+o(383)](a),H[o(1397)](O,N,a[o(604)][o(1681)]);else throw new Error(o(1041)+" message"+o(943)+N+(" larger "+o(1652)+o(900)+"r ")+re);return e[o(877)](n)}return this[o(245)+"hMessageEvent"](a),e[o(1295)](n)}}async function Fg(a,n){let o=t,d=ka[o(216)](this,a);if(!d[o(1198)+o(822)])return e[o(244)](n);let f=await Rl[o(216)](this);if(d[o(240)+o(1745)+"age"]&&d[o(1741)+"s"].length)for(let p of d.ackMsgIds)await f[o(1151)](p);e[o(434)](n)}async function zg(a,n){let o=t,d={mLxRM:e[o(847)],qWmsJ:function(g){return g()}},f=e[o(1414)](a.message[o(184)+"e"],Pg),p=e[o(1640)](a[o(604)].frameType,Ra);if(!f&&!p)return e[o(255)](n);let _=e[o(1623)](cr,a[o(604)][o(1055)],e[o(226)]);if(!_)return n();let v=await Dl[o(216)](this,_);if(!v)return e[o(1425)](n);if(f){let g=await v[o(739)+"rs"](),L={frameType:g?.[o(184)+"e"],SeqID:fe[o(1626)+"er"](this[o(1385)]++),LogID:fe.fromNumber(this[o(1138)][o(1156)+o(1344)]()),service:9e3,method:5,headers:g?.[o(1055)],payload:g?.[o(235)]},O=e.UpnGz(S,L);this[o(1471)]&&this._ws[o(858)+"te"]&&this._ws[o(1544)](O)}if(p)if(e[o(1330)]===e[o(576)])this._debug(ZVRkZG[o(1113)],_0x3d0c3b[o(604)]),ZVRkZG[o(1449)](_0x18b162);else{let g=a[o(604)].payload;g&&v[o(1359)+"rs"](g)}}let Ug=async function(a,n){let o=t;this[o(1262)]=!1,e[o(1239)](clearTimeout,this[o(1675)+o(805)+o(617)]),e[o(1202)](n)},Hg=async function(a,n){let o=t;if(!this._ws||e.SIjDU(this[o(1471)][o(858)+"te"],this[o(1096)]))return n();let{pingInterval:d}=this[o(1138)];this["_endpoin"+o(1530)]?.[o(238)+"pointConfig"]();for(let p=0;e[o(1473)](p,this["_message"+o(852)][o(1674)]);p++){let _=this[o(546)+o(852)][p];if(e[o(706)](this[o(1471)].readyState,this[o(1096)])&&e[o(1070)](null,_)){if(e[o(1596)]===e[o(516)])return(this._listeners[_0x8fbc95]||(this._listeners[_0x5952a6]=[]))[o(1421)]({fn:_0x4326f6,ctx:_0x5c196e||this}),this;this[o(1471)]&&this._ws[o(1544)](_),this["_message"+o(852)][p]=null}else break}this[o(546)+o(852)]=this[o(546)+"Queue"].filter(p=>!!p),this["_pingPon"+o(892)+"Id"]=e[o(1188)](setTimeout,()=>this[o(423)](),d),this[o(245)+"hOpenEvent"](a),this._isBrowser&&this[o(1471)]&&(this._ws[o(314)+"pe"]=this["_binaryT"+o(1552)]);let f=this[o(1688)+o(1530)]?.[o(688)+o(210)+"nt"]();this[o(775)](o(846)+f+" success"),e[o(255)](n)},qg=async function(a,n){let o=t,d=this[o(1688)+o(1530)]?.[o(688)+o(210)+"nt"]();this[o(775)](o(846)+d),e[o(430)](n)};class Gg extends Sa{constructor(n){let o=t,d={LlGcY:function(f,p){return e[z(1682)](f,p)},vofLk:function(f,p){return f+p},iPFoE:function(f,p){return f(p)},LwoUN:function(f,p){return e[z(600)](f,p)},bDTGj:function(f,p){return e.JTphf(f,p)},FDBdt:function(f,p){return e[z(571)](f,p)},TFiKA:function(f,p){return e[z(758)](f,p)},cOdTK:function(f,p){return e[z(1145)](f,p)}};if(e[o(1051)]==="zgoKc"){let f=e.pEWMi(_0x46ea8c,8192),p=e[o(978)](f,1),_=null,v=f;return function(g){let L=o;if(g<1||hbhuLR[L(276)](g,p))return _0x3359f2(g);hbhuLR[L(367)](v,g)>f&&(_=hbhuLR.iPFoE(_0x2feeee,f),v=0);let O=_0x301c42[L(216)](_,v,v+=g);return 7&v&&(v=hbhuLR.LwoUN(7|v,1)),O}}else{super(),this[o(215)+o(863)+o(154)]=!0,this[o(1091)+"er"]=ar,this[o(1082)]=sg,this[o(1538)+"T"]=Ln,this[o(248)+"X"]=si,this[o(1259)+"r"]=oi,this[o(546)+o(852)]=[],this[o(1688)+o(1530)]=null,this[o(1012)+o(1524)]=!1,this["_binaryT"+o(1552)]=e[o(1455)],this[o(1675)+o(1575)]=!1,this[o(1675)+"ionTimeo"+o(617)]=null,this["_reconne"+o(1050)+o(893)]=null,this._pingPongTimeoutId=null,this[o(1385)]=0,this[o(1262)]=!1,this._url="",this["_QoSMana"+o(1078)]=null,this["_cursorM"+o(467)]=null,this[o(1217)+o(1748)]=null,this[o(995)+"ls"]="pbbp2",this[o(440)]=3,this[o(971)+"NG"]=0,this[o(1096)]=1,this[o(842)]=2,this[o(1665)]=v=>{let g=o;if(e[g(353)](g(1493),e[g(994)]))return _0x322595===_0x29c86b?_0x930be0:new _0x15746c(hbhuLR[g(408)](hbhuLR[g(1341)](hbhuLR.TFiKA(hbhuLR[g(1287)](_0x360bca[g(216)](_0x45e31e,0),hbhuLR[g(398)](_0x1f49cd[g(216)](_0x38427a,1),8)),hbhuLR.cOdTK(_0x41b74f[g(216)](_0x2b9aa0,2),16)),_0x1f603c.call(_0xea0d51,3)<<24),0),hbhuLR[g(408)](_0x43842c[g(216)](_0xa219c5,4)|_0x208fb2[g(216)](_0x2702f0,5)<<8|hbhuLR[g(398)](_0x4b66f2.call(_0x3c9efa,6),16)|_0x290f61[g(216)](_0x1bb057,7)<<24,0),!0);try{e[g(555)](Il,this,v,[Ug,Hg,qg])}catch(L){let O=e.BCBTX(ut,e[g(188)],{message:L[g(604)],code:an[g(1418)+"OR"],error:L});this[g(245)+g(1666)+g(620)](O)}},this[o(1749)+"ge"]=async v=>{let g=o,L={grTFO:function(G,H){return G||H}},{pingInterval:O,pingFrequency:N}=this._options;if((e[g(1728)]("hi",v[g(301)])&&e[g(306)](e[g(580)],N)||e.nVHoU(e.rzjhH,N))&&(this[g(1550)+g(462)](),this.emit(e[g(279)],e[g(1582)]),this[g(722)+g(892)+"Id"]=setTimeout(this[g(423)][g(649)](this),O)),!e[g(1360)]("hi",v[g(301)]))try{e[g(1563)](Il,this,v,[yg,wg,Fg,zg,Bg,_g])}catch(G){if(g(553)!==e[g(1437)]){let H=this[g(1388)][g(594)+g(917)](this._prefix);return _0x225569.parse(FDWPwF[g(1339)](H,"{}"))[_0x460ac3]}else{let H=e[g(1213)](ut,g(899),{message:G.message,code:an[g(347)+g(1154)],error:G});this[g(245)+g(1666)+g(620)](H)}}},this[o(294)]=v=>{let g=o,L=this["_endpoin"+g(1530)]?.[g(712)+"chMaxTries"](),O=this[g(1688)+g(1530)]?.[g(688)+g(210)+"nt"]();if(L&&!v[g(604)]){let N=g(646)+O+(" fail, m"+g(1014)+g(1515)+"ed");this[g(245)+"hErrorEv"+g(620)](e.PDrQN(ut,e[g(188)],{message:N,code:an[g(1302)+"IES_ERROR"],error:v}));return}this[g(1471)]&&e[g(1640)](this[g(1471)].readyState,this[g(1096)])&&this["_disconn"+g(295)](),this[g(245)+"hErrorEv"+g(620)](e.FYrno(ut,e.rEiXp,{message:v[g(604)],code:an["NATIVE_E"+g(1519)],error:v}))},this[o(1599)]=async v=>{let g=o,L={wFMKv:function(O,N){return e[z(1489)](O,N)},hzcrP:function(O,N){return e[z(1568)](O,N)},KOOYX:function(O,N){return O===N},dUKkF:function(O,N){return e.ieoKy(O,N)},HbUoF:function(O,N){return O+N}};if(e.TgQJB!==g(1469))return _0xeddaea||(_0x17f181=[_0x36e569,_0x4c616c,_0x38f01b,_0x2799b6,_0x44e297]);{this["_clearTi"+g(539)](),this[g(1550)+g(462)](),this["_removeW"+g(427)+"rs"](),this[g(1471)]=null,this[g(1675)+"Lock"]=!1;let O=this[g(1688)+g(1530)]?.[g(712)+"chMaxTries"]();if(!O&&this["_navigat"+g(1556)]()&&!this[g(1012)+"osed"]){let N=this[g(1688)+g(1530)]?.[g(688)+g(210)+"nt"](),G=this[g(1138)]["reconnec"+g(518)+g(456)](v[g(582)],v[g(1435)]);this[g(245)+"hCloseEv"+g(620)](e[g(1329)](wt,e[g(804)],{code:1006,reason:v.reason||g(1244)+g(1243)+g(381)+g(667)+"n, hostn"+g(1130)+N,willReconnect:G})),G&&this[g(1675)]();return}if(v[g(582)]!==1e3&&this[g(1012)+g(1524)]){this[g(245)+g(1336)+"ent"](e[g(772)](wt,"close",{code:1e3,reason:g(425)})),this[g(1688)+g(1530)]?.[g(238)+g(1279)+g(1653)](),this[g(1217)+g(1748)]?.[g(1292)+"nter"]();return}if(e.pfhEJ(1e3,v[g(582)])&&O){let N=this[g(1688)+g(1530)]?.[g(688)+"ntEndpoint"](),G=v.reason;G||(G=await fg(this._url)),G="connecti"+g(1243)+g(355)+G+(g(260)+g(1112))+N+(g(1738)+"tries reached"),this[g(245)+g(1336)+g(620)](wt(e.UcTuw,{code:v.code,reason:G}));let H=g(646)+N+(g(1052)+"ax retri"+g(1515)+"ed");this[g(245)+"hErrorEv"+g(620)](ut(e.rEiXp,{message:H,code:an[g(1302)+g(974)+"R"]})),this[g(1688)+g(1530)]?.[g(238)+g(1279)+g(1653)](),this[g(1217)+"sCounter"]?.[g(1292)+"nter"]();return}if(e[g(918)](1e3,v[g(582)])&&!v[g(1435)])if(e[g(948)]!==e[g(948)]){let N=0,G=0;for(let H=0;qbPhNJ.wFMKv(H,_0x29661f.length);++H)G=_0x2ddd7f[g(417)+"At"](H),qbPhNJ[g(269)](G,128)?N+=1:qbPhNJ[g(817)](G,2048)?N+=2:qbPhNJ[g(459)](qbPhNJ.dUKkF(64512,G),55296)&&qbPhNJ[g(1204)](64512,_0x499822.charCodeAt(qbPhNJ[g(1583)](H,1)))===56320?(++H,N+=4):N+=3;return N}else{let N=this["_endpoin"+g(1530)]?.getCurrentEndpoint();this[g(245)+g(1336)+g(620)](e[g(930)](wt,g(1289),{code:v[g(582)],reason:g(1244)+g(1243)+g(381)+g(667)+g(1559)+"ame: "+N})),this[g(1688)+"tManager"]?.["resetEnd"+g(1279)+g(1653)](),this[g(1217)+"sCounter"]?.[g(1292)+"nter"]();return}this[g(245)+"hCloseEv"+g(620)](v),this[g(1688)+g(1530)]?.[g(238)+g(1279)+g(1653)](),this[g(1217)+g(1748)]?.["resetCou"+g(927)]()}},this[o(1013)]=null,this[o(803)]=null,this[o(1429)+"e"]=null,this[o(940)]=null,this[o(372)+o(474)]=null,this[o(203)+o(1235)]=null,this[o(947)+o(1355)+o(1278)+"ct"]=null,this[o(765)+"nLine"]=this[o(765)+o(624)][o(649)](this),this[o(765)+o(999)]=this[o(765)+o(999)][o(649)](this),this._handlePageHide=this[o(1391)+o(1327)].bind(this),this[o(1391)+o(977)]=this[o(1391)+o(977)][o(649)](this),this[o(1138)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:s,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[o(1401)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[o(1615)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:p}=n,_=Array[o(873)](f)?f:e[o(683)](e[o(221)],typeof f)?[f]:[];if(!_||e[o(306)](0,_.length))throw new Error(e[o(896)]);if(!e[o(186)](cg,p))throw new Error(e[o(1313)]);Object.assign(this[o(1138)],n),this["_endpoin"+o(1530)]=new Sl(_,this[o(1138)][o(514)+"es"]),this[o(1217)+o(1748)]=new ug(this[o(1138)][o(239)+o(929)]),this._options[o(621)+o(1371)]&&(this[o(1262)]=!0,this[o(1675)]()),this[o(1138)][o(1614)+o(1258)+o(766)]&&(this._isMiniTT||this[o(248)+"X"]?this["_onPageN"+o(760)+o(1095)]():this[o(1091)+"er"]&&this[o(1083)+"balEventListener"]())}}[t(765)+t(624)](){let n=t;this._options[n(1075)+"utoRecon"+n(236)]||this[n(1012)+n(1524)]||this["_handleR"+n(474)]()}[t(765)+t(999)](){let n=t;if(e[n(173)]===e[n(1189)])return _0x634bf4&&e[n(686)](!0,_0x5a0fbe.isLong);{this[n(442)+n(483)+"t"]();let o=e[n(1001)](va,n(1069)+"t",{message:n(320)+"ediately"+n(1717)+"ct"});this[n(947)+n(1355)+"yReconnect"]&&this[n(947)+n(1355)+n(1278)+"ct"](o)}}["_initGlo"+t(1632)+"Listener"](){let n=t;this[n(1091)+"er"]&&window[n(607)+n(1702)](e[n(208)],this["_handleO"+n(624)]),this[n(1091)+"er"]&&window[n(607)+"Listener"](e[n(259)],this["_handleO"+n(999)]),this[n(1091)+"er"]&&window.addEventListener(n(1288),this[n(1391)+n(1327)]),this[n(1091)+"er"]&&window[n(607)+n(1702)](e[n(922)],this._handlePageShow)}_dropGlobalEventListener(){let n=t;this[n(1091)+"er"]&&window[n(416)+"entListe"+n(1192)](e.GEMta,this["_handleO"+n(624)]),this[n(1091)+"er"]&&window["removeEventListe"+n(1192)](e[n(259)],this[n(765)+n(999)]),this._isBrowser&&window[n(416)+n(324)+n(1192)](e[n(1438)],this[n(1391)+n(1327)]),this[n(1091)+"er"]&&window[n(416)+n(324)+n(1192)](e[n(922)],this[n(1391)+"ageShow"])}[t(1391)+t(1327)](n){let o=t;!n[o(857)+"d"]&&(this[o(1091)+"er"]&&window[o(416)+o(324)+o(1192)](e[o(1438)],this["_handleP"+o(1327)]),this[o(1091)+"er"]&&window[o(416)+o(324)+o(1192)](e[o(922)],this[o(1391)+o(977)]),this[o(1289)]()),this[o(1091)+"er"]&&window[o(416)+"entListener"](o(611),this[o(765)+o(624)]),this[o(1091)+"er"]&&window[o(416)+o(324)+"ner"](e[o(259)],this[o(765)+o(999)])}[t(1391)+t(977)](n){let o=t;n[o(857)+"d"]&&(this["_navigat"+o(1556)]()&&(!this[o(1471)]||e[o(897)](this._ws[o(858)+"te"],this[o(1096)])||e.tNTFB(this[o(1471)][o(858)+"te"],this.CONNECTING))&&this[o(765)+o(624)](),this[o(1091)+"er"]&&window[o(607)+o(1702)]("online",this[o(765)+o(624)]),this[o(1091)+"er"]&&window[o(607)+o(1702)](e[o(259)],this[o(765)+o(999)]))}async[t(1643)+"eUrl"](n){let o=t;if(e[o(1122)](e[o(1475)],o(704))){let{fpID:d,deviceID:f,bddID:p,ttwID:_,accessKey:v,aID:g,customParams:L={},enableAutoAck:O,enableQoS:N,QoSLevel:G,env:H}=this._options,re,Fe,$e;this._isBrowser||this._isMiniWX||this[o(1538)+"T"]?(re=location&&e[o(1128)]==location[o(590)]?e[o(1229)]:e[o(1735)],Fe=n[o(839)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),$e=/^wss(.*:\/\/)/[o(1384)](n)?n:""+re+Fe):(re=e[o(1229)],Fe=n[o(839)](/(^http)((?:[s]*:\/\/))/,""),$e=/(^ws)((?:[s]*:\/\/))/[o(1384)](Fe)?Fe:""+re+Fe);let nt=p?e[o(855)]:_?e.HWlQc:e[o(382)],dr=p||_||f;if(!dr||!nt)throw new Error(e.mDXth);let Ol=e[o(547)](e[o(698)],typeof L)?await L():L,jg=H?e[o(653)](lg,H.xUseEnv,H[o(1081)]):{},Pa=Object[o(192)]({device_platform:o(439),version_code:e[o(895)],access_key:v,fpid:d,aid:g,[nt]:dr,xsack:O?1:0,xaack:O?1:0,xsqos:N?1:0,qos_level:N?G:void 0,qos_sdk_version:2,...jg},Ol),Wg=Object[o(1194)](Pa)[o(1600)]((Da,Oa)=>Pa[Oa]!==void 0?""+Da+(Da?"&":"?")+Oa+"="+Pa[Oa]:Da,"");return $e+o(1314)+Wg}else return 0}async _connect(){let n=t;if(!(this["_connect"+n(1575)]||this[n(1012)+n(1524)])){this["_connect"+n(1575)]=!0;try{if(e[n(1468)](n(1197),e[n(787)])){let o=this[n(1688)+n(1530)]?.["checkCur"+n(1584)+n(149)+n(668)+"tries"](),{timeoutInterval:d}=this[n(1138)];if(o){let p=this[n(1688)+"tManager"]?.[n(688)+n(210)+"nt"](),_=this[n(1688)+"tManager"]?.[n(1299)+n(364)+n(454)+n(288)+n(1059)](),v=this[n(1688)+n(1530)]?.[n(688)+n(210)+n(840)+n(450)]();if(_){let g="connect "+p+(n(432)+", max retries re"+n(1573)+n(504)+n(1010)+"ndpoint ")+_+(n(524)+"y"),L=e.beNGx(ut,n(899),{message:g,code:an[n(1302)+n(974)+"R"]});this[n(775)](g),this["_dispatc"+n(1666)+n(620)](L),this[n(1588)]=await this[n(1643)+"eUrl"](_),this._debug(n(646)+_+" "+v+n(615)),this._removeWsListeners()}else if(e[n(1527)](n(1167),e[n(987)]))this[n(1118)+"rs"]={};else{let g=n(646)+p+(n(432)+n(1738)+"tries re"+n(727));this[n(775)](g),this[n(245)+n(1666)+n(620)](ut(n(899),{message:g,code:an[n(1302)+n(974)+"R"]}));return}}else{let p=this[n(1688)+n(1530)]?.[n(688)+"ntEndpoi"+n(575)+n(1511)](),_=this[n(1688)+n(1530)]?.["getCurre"+n(210)+n(840)+n(450)]();this[n(1588)]=await this["_generat"+n(1133)](e[n(1117)](p,"")),this[n(775)](n(646)+p+" "+_+" times"),this._removeWsListeners()}if(this[n(1262)])this[n(1262)]=!1;else if(e[n(1464)](e[n(1131)],e.eCsfE)){let p=e[n(1447)](va,n(1069)+"t",{message:e.RcTpg});this[n(372)+n(474)]&&this["onStartR"+n(474)](p)}else _0x83a426(_0x4a14ef,24),e[n(797)](_0x5a89cf,_0x419ea0,e.QwWzJ(_0x2ff810,_0x1f593d));let f=this[n(1688)+n(1530)]?.[n(688)+n(210)+n(840)+"ount"]()||0;f>1&&await this[n(713)](e[n(836)](f,1)),this[n(775)]("connecti"+n(258)+this[n(1588)]+(n(1629)+n(659))+this._protocols),this[n(1471)]=ag({url:this._url,protocols:[this._protocols],headers:this[n(1138)][n(1031)+n(1255)+"s"][n(1395)+n(808)]},this[n(1138)].ws),(this._isBrowser||this._isWorker)&&this[n(1471)]&&(this[n(1471)][n(314)+"pe"]=this[n(1533)+n(1552)]),this[n(247)+n(595)](),this[n(1675)+n(805)+n(617)]=e.bCvpu(setTimeout,this[n(1324)+"ut"][n(649)](this),d)}else return this._qosDB[n(1209)]()}catch(o){throw this["_connect"+n(1575)]=!1,o}}}[t(581)+t(539)](){let n=t;e[n(1239)](clearTimeout,this[n(1675)+n(805)+n(617)]),this[n(1675)+n(805)+"utId"]=null}[t(1550)+"ngTimer"](){let n=t;e[n(464)](clearTimeout,this["_pingPon"+n(892)+"Id"]),e[n(1058)](clearTimeout,this[n(902)+n(1050)+n(893)]),this["_pingPon"+n(892)+"Id"]=null,this[n(902)+"ctTimeou"+n(893)]=null}[t(775)](...n){let o=t;this._options.debug&&console[o(795)][o(1105)](console,[e[o(923)],...n])}[t(1747)+t(1187)+"e"](n){let o=t;if(e[o(1362)](e[o(1654)],e[o(680)])){let{initReconnectInterval:d,maxReconnectInterval:f,reconnectIntervalGrowFactor:p}=this[o(1138)],_=e[o(1357)](d,Math[o(691)](p,e[o(656)](n,1)));return e[o(1682)](_,f)?f:_}else{let d=e[o(315)][o(1353)]("|"),f=0;for(;;){switch(d[f++]){case"0":_0x48cdf4[_0x19c073++]=e[o(1076)](e[o(1483)](e[o(1009)](_0x11d526,6),63),128);continue;case"1":_0x52889d=e.vggld(e[o(636)](65536,e[o(1483)](1023,_0x57fb79)<<10),1023&_0x301226);continue;case"2":++_0x91e7d1;continue;case"3":_0x481941[_0x154378++]=e[o(316)](e[o(148)](63,_0x38057d),128);continue;case"4":_0xbe5ae4[_0x180769++]=e[o(851)](e[o(1177)](_0x415bc4,12),63)|128;continue;case"5":_0x4479ed[_0x2f209b++]=e[o(758)](e.waFTt(_0x32e59f,18),240);continue}break}}}[t(423)](){let n=t,o={zSpHP:function(d,f){return e[z(164)](d,f)}};if(e.EdnTk(e[n(1721)],n(1367))){let d=this[n(1388)].getItem(this[n(429)]),f=_0x5e249f.parse(uKCrRP[n(1709)](d,"{}"));return _0x50487c[n(291)](f)}else{if(this[n(1471)]&&this[n(1471)][n(858)+"te"]===this[n(971)+"NG"]){this[n(1550)+n(462)](),this[n(722)+n(892)+"Id"]=e[n(735)](setTimeout,this[n(423)][n(649)](this),this._options[n(932)+"rval"]);return}if(!this._ws||e[n(1106)](this[n(1471)][n(858)+"te"],this[n(1096)]))return void this[n(658)+n(474)]();this._ws&&this[n(1471)][n(1544)]("hi"),this[n(902)+n(1050)+n(893)]=e[n(930)](setTimeout,this["_handleR"+n(474)+n(422)].bind(this),this._options[n(1454)+"outInterval"])}}[t(658)+t(474)+t(422)](){let n=t,o={jiTms:function(d,f){return e.QheMd(d,f)}};if(e[n(694)]===e.sIMlc)return _0x7f3540|=0,{low:_0x431cb8,high:_0x2e8d12>>31,unsigned:dmzoRO[n(975)](_0x2e40e5,0)};this[n(1217)+n(1748)]?.[n(1715)](),this[n(1071)](e[n(1030)],n(1056)),this["_pingLos"+n(1748)]?.[n(712)+n(645)+"nt"]()?this[n(658)+n(474)]():this[n(423)]()}[t(777)+t(1556)](){let n=t;return this._isMiniTT||this[n(248)+"X"]?this._miniNavigatorOnline:(this[n(1091)+"er"]||this._isWorker)&&this[n(1138)]["listenNe"+n(1258)+n(766)]?navigator[n(1555)]:!0}[t(658)+t(474)](){let n=t;!this[n(777)+"orOnline"]()||this[n(1012)+n(1524)]||(this["_endpoin"+n(1530)]?.["resetEnd"+n(1279)+n(1653)](),this[n(1217)+"sCounter"]?.[n(1292)+n(927)](),this[n(1471)]?this[n(471)+n(295)](1001,e[n(860)],!0):this[n(1675)]())}["_onPageN"+t(760)+t(1095)](){let n=t,o={LvUQR:function(d,f){return e[z(1577)](d,f)},wRwrD:function(d,f){return e[z(1303)](d,f)},uBISi:function(d,f){return d>>f},MINxa:function(d,f){return d&f},EBmTR:function(d,f){return e[z(1076)](d,f)},hJipQ:function(d,f){return e.WIwEL(d,f)}};e[n(1106)](e[n(1513)],n(233))?(tMJrVc[n(1284)](_0x3ef4a4,2048)?_0x7f5844[_0x49ead8++]=tMJrVc[n(231)](tMJrVc[n(602)](_0x20eefd,6),31)|192:(_0x486dc3<65536?_0x448677[_0x3aef39++]=tMJrVc[n(209)](tMJrVc[n(602)](_0x49ab66,12),15)|224:(_0x35055f[_0x32a890++]=tMJrVc[n(1627)](tMJrVc[n(602)](_0x727795,18)&7,240),_0x59b9c7[_0x5d0f4e++]=tMJrVc[n(1099)](tMJrVc[n(602)](_0x5f4e80,12)&63,128)),_0x15b82d[_0x1fbda9++]=tMJrVc[n(231)](tMJrVc[n(602)](_0x63b8b8,6),63)|128),_0xfbd027[_0xb41100++]=tMJrVc.EBmTR(tMJrVc[n(209)](63,_0x32a0d6),128)):this._isMiniTT?tt[n(1166)+n(1152)+n(1661)](({isConnected:d})=>{let f=n;this[f(215)+f(863)+f(154)]=d,d?this._handleOnLine():this[f(765)+f(999)]()}):this[n(248)+"X"]&&wx["onNetwor"+n(1152)+n(1661)](({isConnected:d})=>{let f=n;this[f(215)+f(863)+f(154)]=d,d?this[f(765)+f(624)]():this[f(765)+f(999)]()})}[t(713)](n){return new Promise(o=>{let d=z;e[d(243)](setTimeout,o,this[d(1747)+d(1187)+"e"](n))})}["_disconn"+t(295)](n=1e3,o="",d=!1){let f=t;this[f(1471)]&&this[f(442)+f(483)+"t"](n,o,d)}_onTimeout(){let n=t;if(e.vRTMm(e[n(1537)],e[n(1537)])){if(e[n(1129)](_0x49da49,-_0x4d2744))return _0x314642;if(e.SEhtw(_0x398517+1,_0x43a3e7))return _0x3f6877}else{let o=this["_endpoin"+n(1530)]?.[n(688)+"ntEndpoint"]();this[n(775)](n(646)+o+n(432)),this[n(471)+n(295)](1001,e[n(1594)],!0)}}_sendAck(n){let o=t,d=qt(n);this._ws&&this._ws.readyState===this.OPEN&&(this[o(1471)]&&this._ws[o(1544)](d),this[o(775)](e.YXRoK,n))}_removeWsListeners(){let n=t,o={AVdVk:function(d,f,p){return d(f,p)},OkegS:e[n(188)],WwMzc:function(d,f,p){return e[n(1020)](d,f,p)}};if(e[n(1409)]===e[n(665)]){let d=this[n(1688)+n(1530)]?.[n(712)+n(330)+"es"](),f=this[n(1688)+n(1530)]?.["getCurre"+n(210)+"nt"]();if(d&&!_0x58bb89[n(604)]){let p=n(646)+f+(n(1052)+n(1014)+n(1515)+"ed");this["_dispatc"+n(1666)+n(620)](NlaMZQ.AVdVk(_0x5e0c4c,NlaMZQ[n(1650)],{message:p,code:_0x9d5258[n(1302)+n(974)+"R"],error:_0x5896e5}));return}this._ws&&this[n(1471)][n(858)+"te"]===this[n(1096)]&&this[n(471)+n(295)](),this[n(245)+n(1666)+n(620)](NlaMZQ[n(1039)](_0x38b059,NlaMZQ[n(1650)],{message:_0x5a2f60[n(604)],code:_0xf79dcd[n(941)+"RROR"],error:_0x5af80c}))}else{if(!this[n(1471)])return;this._ws[n(416)+n(324)+n(1192)](e[n(497)],this[n(1665)]),this[n(1471)][n(416)+n(324)+n(1192)](e[n(804)],this[n(1599)]),this[n(1471)][n(416)+n(324)+n(1192)](e[n(1181)],this[n(1749)+"ge"]),this._ws[n(416)+n(324)+n(1192)](n(899),this[n(294)])}}_addWsListeners(){let n=t,o=e[n(1042)][n(1353)]("|"),d=0;for(;;){switch(o[d++]){case"0":this[n(1471)][n(607)+n(1702)](e[n(804)],this[n(1599)]);continue;case"1":this._ws[n(607)+"Listener"](e[n(497)],this[n(1665)]);continue;case"2":this[n(1471)][n(607)+"Listener"](n(899),this[n(294)]);continue;case"3":if(!this._ws)return;continue;case"4":this[n(1471)][n(607)+n(1702)](e.bcHbS,this[n(1749)+"ge"]);continue}break}}[t(1322)+t(1230)](n=1e3,o=""){let d=t,f={imOAJ:function(p,_){return e[z(985)](p,_)},zcudd:e[d(580)],twaOh:function(p,_){return e.AKvWD(p,_)},miDVc:d(249),bgZjq:e[d(279)],qcccy:function(p,_,v){return e[d(988)](p,_,v)},vnkQZ:e[d(188)]};try{if(e[d(253)](e[d(1503)],e.TZVxn))this._ws&&this[d(1471)][d(1289)](n,o);else{let{pingInterval:p,pingFrequency:_}=this[d(1138)];if((qJRqii[d(1619)]("hi",_0x8e7fa1.data)&&qJRqii[d(1619)](qJRqii[d(228)],_)||qJRqii.twaOh(qJRqii[d(640)],_))&&(this[d(1550)+d(462)](),this[d(1071)](qJRqii[d(323)],d(1369)),this[d(722)+d(892)+"Id"]=qJRqii[d(1576)](_0x149c09,this[d(423)][d(649)](this),p)),_0x174cb5[d(301)]==="hi")return;try{_0xceccd4(this,_0x2b577c,[_0x2db373,_0x2701e6,_0x3208a3,_0x468f42,_0x54c57e,_0x20bfa7])}catch(v){let g=qJRqii[d(1576)](_0x4e1c54,qJRqii[d(1611)],{message:v[d(604)],code:_0x3499d8[d(347)+d(1154)],error:v});this[d(245)+d(1666)+d(620)](g)}}}catch{}}[t(442)+t(483)+"t"](n=1e3,o="",d=!1){let f=t;if(e.sxwXM("mHLoh",e[f(1506)])){let p=new _0x3cab13(e[f(147)](e[f(1300)](e[f(533)](_0x3b8913[e[f(926)](_0x108051,4)],24),_0x599158[e[f(1022)](_0x272e61,5)]<<16)|e[f(764)](_0x35e3b9[_0x2a1c07+6],8),_0x495922[e[f(564)](_0x1582d9,7)]),e[f(758)](e[f(1033)](e[f(758)](e[f(332)](_0x105bea[_0x4074e0+0],24),e[f(424)](_0x223290[e[f(343)](_0x8340a6,1)],16)),e[f(1146)](_0xe3d029[e[f(661)](_0x7b750c,2)],8)),_0x4d40ea[e[f(613)](_0x310d60,3)]),!0);return _0xb58456+=8,{value:p,offset:_0x299308+8}}else{if(this[f(1550)+f(462)](),this[f(581)+f(539)](),this[f(394)+f(427)+"rs"](),this[f(1322)+f(1230)](1e3,o),this[f(1675)+f(1575)]=!1,d&&this[f(777)+f(1556)]()&&!this[f(1012)+f(1524)]){if(this[f(1688)+f(1530)]?.checkReachMaxTries()){let _=this[f(1688)+f(1530)]?.[f(688)+f(210)+"nt"]();this[f(245)+"hCloseEv"+f(620)](e[f(1143)](wt,e[f(804)],{code:1006,reason:f(646)+_+(" timeout"+f(1738)+"tries reached"),wasClean:!0}))}else{let _=this[f(1138)][f(1069)+f(518)+f(456)](n,o);this[f(245)+"hCloseEv"+f(620)](e[f(1634)](wt,f(1289),{code:n,reason:o,wasClean:!0,willReconnect:_})),_&&this[f(1675)]()}return}this[f(777)+f(1556)]()||this[f(1012)+f(1524)]?this[f(245)+f(1336)+"ent"](wt(f(1289),{code:n,reason:e[f(298)]})):this[f(245)+"hCloseEv"+f(620)](wt(e[f(804)],{code:1006,reason:e.KiAHv})),this._ws=null,this[f(1688)+f(1530)]?.["resetEnd"+f(1279)+f(1653)](),this._pingLossCounter?.[f(1292)+f(927)]()}}[t(245)+t(910)+"nt"](n){let o=t;if(e.SvCuJ(e[o(1079)],o(1137)))this[o(1071)]("open",n),this[o(940)]&&this[o(940)](n);else{let d=0,f={};for(let p=0;p<_0x1fa18e.length;p++)f[_0xe7cd1c[p]["cursor_n"+o(566)]]=_0x8edf2d(_0x43f99d[p].cursor_name),d+=e[o(1398)](14,f[_0x5b9e7c[p][o(1592)+o(566)]]);return[d,f]}}[t(245)+t(1403)+t(383)](n){let o=t;this[o(1071)](o(604),n),this[o(1429)+"e"]&&this.onmessage(n)}[t(245)+t(998)+t(709)](n){let o=t;this.emit(o(1622),n),this["onReceiv"+o(1235)]&&this[o(203)+o(1235)](n)}[t(245)+"hErrorEv"+t(620)](n){let o=t;this[o(1071)](o(899),n),this.onerror&&this[o(803)](n)}[t(245)+"hCloseEv"+t(620)](n){let o=t;this.emit(e[o(804)],n),this.onclose&&this[o(1013)](n)}get[t(314)+"pe"](){let n=t;return this[n(1471)]?this[n(1471)][n(314)+"pe"]:this._binaryType}set[t(314)+"pe"](n){let o=t;this["_binaryT"+o(1552)]=n,this._ws&&(this[o(1471)][o(314)+"pe"]=n)}get retryCount(){let n=t;return this[n(1688)+"tManager"]?.[n(688)+n(210)+n(840)+"ount"]()||0}get["buffered"+t(905)](){let n=t,o={TbTkV:function(d,f){return e.piMPt(d,f)},EYngo:function(d,f){return e[z(761)](d,f)},EOXpZ:function(d,f){return e[z(1485)](d,f)},DUtis:function(d,f){return e[z(1434)](d,f)}};return e[n(1006)](e[n(695)],e[n(333)])?this[n(546)+"Queue"].reduce((f,p)=>(f+=p&&p[n(252)+"th"]||0,f),0)+(this._ws?this[n(1471)]["buffered"+n(905)]:0):new _0x57e499(DHltCJ[n(1404)](DHltCJ[n(1672)](_0x1ea565[0],DHltCJ[n(1098)](_0x2e89f8[1],8))|DHltCJ.EOXpZ(_0x4fd45f[2],16),_0x170604[3]<<24),DHltCJ.DUtis(_0x44a5d6[4],DHltCJ.EOXpZ(_0x56df78[5],8))|DHltCJ[n(1098)](_0x2ef8e1[6],16)|_0x5ba22b[7]<<24,_0x2640d4)}get[t(1054)+"ns"](){let n=t;return this[n(1471)]?this._ws[n(1054)+"ns"]:""}get[t(590)](){let n=t;return this._ws?this[n(1471)].protocol:""}get[t(858)+"te"](){let n=t,o={qCBEz:function(d,f,p){return e[z(1141)](d,f,p)},QHzVw:e[n(188)]};if(e[n(890)](e[n(601)],e[n(1452)])){let d=n(646)+_0x304d98+(" timeout, max re"+n(250)+"ached");this[n(775)](d),this[n(245)+n(1666)+n(620)](mxATgc[n(175)](_0x33a1ca,mxATgc.QHzVw,{message:d,code:_0x5afa7b[n(1302)+"IES_ERROR"]}));return}else return this[n(1471)]?this[n(1471)].readyState:this[n(1138)].automaticOpen?this[n(971)+"NG"]:this[n(440)]}get[t(1170)](){let n=t;return this[n(1471)]?this._ws.url:this[n(1588)]}[t(1289)](n=1e3,o){let d=t;if(e.GIldo(e.lIkfm,d(579))){let f=e[d(584)][d(1353)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[d(284)+d(1078)]?.[d(1417)]();continue;case"1":this[d(442)+d(483)+"t"](n,o);continue;case"2":this["_readyCl"+d(1524)]=!0;continue;case"3":this[d(1647)+d(1632)+d(1702)]();continue;case"4":if(this._ws[d(858)+"te"]===this.CLOSED||this[d(1471)].readyState===this[d(842)])return void this._debug(e.OLjuL);continue;case"5":this[d(581)+d(539)]();continue;case"6":this[d(1550)+d(462)]();continue;case"7":if(!this._ws)return void this[d(775)](d(945)+d(1361)+d(187)+d(397)+"ed");continue}break}}else return _0x2bfb3e(_0x13ab21(_0x2e3808))}async[t(1544)](n,o){let d=t;if(e[d(296)](e.TvPYR,e[d(444)])){if(e.IMkLi(null,n))throw new Error(e[d(754)]);e.KoJvI(d(158),typeof n)&&(n=JSON[d(274)+"y"](n)),e[d(1457)](e[d(221)],typeof n)&&!e[d(1182)](n,ArrayBuffer)&&!(n[d(1337)]&&e[d(513)](n.buffer,ArrayBuffer))&&(n=JSON[d(274)+"y"](n));let f=await Tl(n),p=dg(n),{method:_=0,service:v=this[d(1138)][d(1681)],logID:g=this[d(1138)][d(1156)+d(1344)](),headers:L=this[d(1138)].headers,payloadEncoding:O=this._options[d(1049)+d(393)],payloadType:N=this[d(1138)]["payloadT"+d(1552)],logIDNew:G=this._options["logIDNew"+d(1283)][d(1677)+d(960)+d(1325)+"ew"]?i(this[d(1138)][d(685)+d(1283)][d(891)]):""}=o||{};if(!v)throw new Error(e[d(368)]);let H={SeqID:fe[d(1626)+"er"](this[d(1385)]++),LogID:fe[d(1626)+"er"](g),service:v,method:_,headers:L,payloadEncoding:e[d(785)](O,Object)?O[d(1238)]?O[d(1238)]:"":O,payloadType:N instanceof Object?N[d(1412)]?N[d(1412)]:p:N||p,payload:f,LogIDNew:G},re=e.omkhn(qt,H);return this[d(1471)]&&e[d(1645)](this._ws[d(858)+"te"],this[d(1096)])?(this[d(1471)]&&this[d(1471)][d(1544)](re),this._debug(e.WXCGh,H)):e.omzoh(this["_message"+d(852)][d(1674)],this._options["maxMessa"+d(664)+d(445)])?(this[d(546)+d(852)][d(1421)](re),this[d(775)](e[d(1472)],H)):(this[d(546)+d(852)].shift(),this["_message"+d(852)][d(1421)](re)),{seqID:this[d(1385)],logID:g,logIDNew:G}}else{let f=e[d(837)](e[d(1722)](e[d(1060)](e[d(1548)](e.bPoay(7,_0xfab211),18),e[d(1171)](63,_0x52d97e[_0x209f83++])<<12)|e.thPix(e[d(1109)](63,_0x102db1[_0x2b1eec++]),6),e[d(751)](63,_0x2e5f86[_0x8d1a07++])),65536);_0x172d82+=_0x80e2f8[d(1297)+d(1710)](55296+(f>>10)),_0x5a33b4+=_0x54201e[d(1297)+d(1710)](e[d(636)](56320,e[d(780)](1023,f)))}}async[t(1069)+"t"](n){let o=t,{url:d}=e[o(544)](n,{}),f=Array[o(873)](d)?d:e.qeKdb(e[o(221)],typeof d)?[d]:[];n&&Object[o(192)](this[o(1138)],n),f&&f[o(1674)]?this["_endpoin"+o(1530)]=new Sl(f,this[o(1138)][o(514)+"es"]):this[o(1688)+o(1530)]?.[o(238)+"pointCon"+o(1653)](),this[o(1217)+"sCounter"]?.[o(1292)+"nter"](this[o(1138)][o(239)+o(929)]),this["_readyCl"+o(1524)]=!1,this[o(1471)]&&e.OhqMF(this[o(1471)].readyState,this[o(440)])?this[o(471)+"ect"](1e3,e[o(1108)],!0):(this[o(1262)]=!0,this[o(1675)]())}async[t(740)](){let n=t;if(!this[n(1675)+n(1575)]){let o=e[n(543)][n(1353)]("|"),d=0;for(;;){switch(o[d++]){case"0":this[n(1012)+n(1524)]=!1;continue;case"1":this[n(1675)]();continue;case"2":this._isInit=!0;continue;case"3":this[n(1217)+"sCounter"]?.[n(1292)+n(927)]();continue;case"4":this[n(1688)+n(1530)]?.[n(238)+n(1279)+n(1653)]();continue}break}}}addEventListener(n,o){let d=t;if(e[d(716)](e.ybCgx,e[d(1203)]))this.on(n,o);else throw this[d(1675)+d(1575)]=!1,_0x25c453}["dispatch"+t(383)](n){let o=t,{type:d}=n;this[o(1071)](d,n)}[t(416)+t(324)+t(1192)](n,o){this[t(1159)](n,o)}[t(1526)](){let n=t,o={xUBPg:function(d,f){return e.UpnGz(d,f)},mWVnH:e.HKZrA,KuupW:e.eVeCB,nCfCB:e[n(1030)]};return new Promise((d,f)=>{let p=n;this["_clearPi"+p(462)](),this[p(722)+"gTimeoutId"]=setTimeout(this[p(423)][p(649)](this),this[p(1138)][p(932)+p(628)]);let _=()=>{let g=p;o[g(654)](d,o[g(1176)]),this[g(1159)]("ping_onc"+g(289)+"s",_),this[g(1159)](g(1018)+g(183)+"t",v)},v=()=>{let g=p;f(o[g(1191)]),this[g(1159)]("ping_onc"+g(289)+"s",_),this[g(1159)](o.nCfCB,v)};this.on(p(1018)+p(289)+"s",_),this.on(e.pGaXu,v),this[p(423)]()})}}})(),Be[M(1155)+M(1668)]=Pe["CustomCl"+M(1668)],Be[M(541)+M(954)]=Pe[M(541)+"rorEvent"],Be.ErrorCode=Pe[M(292)+"e"],Be[M(383)]=Pe[M(383)],Be.FWS=Pe[M(1408)],Be["Frontier"+M(241)+"vent"]=Pe.FrontierMessageEvent,Be["MessageE"+M(776)]=Pe["MessageE"+M(776)],Be[M(1570)+"t"]=Pe[M(1570)+"t"],Be[M(1718)+M(311)]=Pe[M(1718)+M(311)],Be["createCl"+M(1668)]=Pe["createCl"+M(1668)],Be[M(542)+M(954)]=Pe[M(542)+M(954)],Be[M(939)+"ssageEvent"]=Pe[M(939)+M(1290)+"nt"],Be["createOp"+M(747)]=Pe[M(512)+M(747)],Be[M(1301)+M(302)+M(776)]=Pe[M(1301)+M(302)+M(776)],Be.decodedFrame=Pe[M(774)+M(485)],Be[M(222)+"ame"]=Pe[M(222)+"ame"];for(ea in Pe)[M(1155)+"oseEvent",M(541)+M(954),M(292)+"e",M(383),M(1408),M(146)+M(241)+M(776),"MessageE"+M(776),M(1570)+"t",M(1718)+M(311),M(1164)+"oseEvent",M(542)+"rorEvent",M(939)+M(1290)+"nt",M(512)+M(747),M(1301)+M(302)+M(776),M(774)+M(485),"encodeFrame"][M(338)](ea)===-1&&(Be[ea]=Pe[ea]);var ea;Object[M(1382)+M(616)](Be,M(177)+"le",{value:!0})});import{existsSync as C1,openSync as R1}from"node:fs";import{mkdir as P1}from"node:fs/promises";import{dirname as D1}from"node:path";import{fileURLToPath as O1}from"node:url";function N1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function nl(t=Z()){return C1(t.libEntry)?t.libEntry:O1(new URL("../index.ts",import.meta.url))}async function gp(t={}){let e=t.paths??Z(),r=t.entryOverride??nl(e),i=N1(e,process.env.COZE_BRIDGE_LOG_MODE);await P1(D1(i),{recursive:!0});let s=R1(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=ot(process.execPath,l,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[ls]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return L1.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var L1,ls,ua=rt(()=>{"use strict";Zt();ie();Ce();L1=j("spawn-daemon"),ls="COZE_BRIDGE_DAEMON"});import{spawn as DI}from"node:child_process";import{mkdir as OI,unlink as LI,writeFile as NI}from"node:fs/promises";import{dirname as MI,join as BI}from"node:path";function ni(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function FI(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${ni(r)}</key>
21
- <string>${ni(i)}</string>`).join(`
20
+ `+n)}function cr(t,e,n,i,s,a){if(t.listenerCount("wsClientError")){let d=new Error(s);Error.captureStackTrace(d,cr),t.emit("wsClientError",d,n,e)}else hs(n,i,s,a)}});var yp=ue(Ge=>{"use strict";var U=G;function G(t,e){t=t-320;let n=ga(),i=n[t];if(G.YmdZtv===void 0){var s=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",w="";for(let v=0,_,E,I=0;E=h.charAt(I++);~E&&(_=v%4?_*64+E:E,v++%4)?g+=String.fromCharCode(255&_>>(-2*v&6)):0)E=x.indexOf(E);for(let v=0,_=g.length;v<_;v++)w+="%"+("00"+g.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(w)};G.baRQdD=s,G.JvvqoU={},G.YmdZtv=!0}let a=n[0],d=t+a,u=G.JvvqoU[d];return u?i=u:(i=G.baRQdD(i),G.JvvqoU[d]=i),i}(function(t,e){let n=G,i=t();for(;;)try{if(-parseInt(n(1336))/1+-parseInt(n(1812))/2*(parseInt(n(1564))/3)+parseInt(n(667))/4+parseInt(n(1055))/5+-parseInt(n(1167))/6+parseInt(n(1885))/7+-parseInt(n(1771))/8*(-parseInt(n(1530))/9)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ga,708739);var m1=Object[U(1652)+"operty"],w1=Object[U(517)+U(1182)+U(925)],pp=(t,e)=>function(){return t&&(e=(0,t[w1(t)[0]])(t=0)),e},_1=(t,e)=>{let n=U,i={sDCdm:function(a,d,u,h){return a(d,u,h)}};for(var s in e)i[n(827)](m1,t,s,{get:e[s],enumerable:!0})};function y1(){return lp||(lp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function b1(){let t=U;return up||(up=[IDBCursor.prototype[t(1635)],IDBCursor[t(1700)+"e"].continue,IDBCursor[t(1700)+"e"]["continue"+t(331)+"ey"]])}function E1(t){let e=U,n={JoRGj:e(484),JELvi:"error",HxcrN:function(s,a){return s(a)},iUkml:function(s,a){return s<a},xJlWc:function(s,a){return s|a},GbKRB:function(s,a){return s|a},vrojf:function(s,a){return s&a},EQSIa:function(s,a){return s>>>a},rSAAa:function(s,a){return s|a},xTaYg:function(s,a){return s&a},GjDOC:function(s,a){return s|a},JmyAb:function(s,a){return s<<a},fXFxk:function(s,a){return s|a},uAPGS:function(s,a){return s>a},saHTM:function(s,a){return s<a},THWST:function(s,a){return s|a},PuPJm:function(s,a){return s<a},bMpUA:function(s,a){return s instanceof a},tddGU:e(418)},i=new Promise((s,a)=>{let d=e,u={IWJxv:function(w,v){return w(v)},DNqpq:function(w){return w()},xwdBk:function(w,v){return n[G(388)](w,v)}},h=()=>{let w=G;t[w(1248)+w(943)+w(1390)](n[w(335)],x),t["removeEventListe"+w(1390)](n[w(1636)],g)},x=()=>{let w=G;s(u[w(1678)](jt,t.result)),u[w(891)](h)},g=()=>{let w=G;u.xwdBk(a,t[w(371)]),h()};t[d(1795)+d(1518)](n[d(335)],x),t[d(1795)+d(1518)](n[d(1636)],g)});return i[e(1327)](s=>{let a=e;if(n[a(1273)](s,IDBCursor))if(n[a(1571)]===n[a(1571)])al[a(651)](s,t);else{let d=(a(1224)+"|5|1|7|0"+a(1318)+"3").split("|"),u=0;for(;;){switch(d[u++]){case"0":if(n[a(1671)](_0x659935[_0x34bd90++],128))return{value:_0x49791e?_0x11c340:n[a(574)](0,_0x1e8484),offset:_0x9191a4};continue;case"1":if(n[a(1671)](_0x3f9f6e[_0x2e6ea6++],128))return{value:_0x9b1b74?_0x484904:n[a(574)](0,_0x85d27),offset:_0x4ce9fb};continue;case"2":if(_0x10f3de[_0x6fff5a++]<128)return{value:_0x5c50f2?_0x15b8a0:n[a(574)](0,_0x283fc8),offset:_0x4f7b9f};continue;case"3":return{value:_0x52d0e1?_0x978b43:n.xJlWc(0,_0x2cb24b),offset:_0x1ed53f};case"4":_0x1521cf=n[a(744)](_0x292982,n[a(835)](15,_0x21ddec[_0x56f2c7])<<28)>>>0;continue;case"5":_0x5a2053=n[a(801)](n[a(1420)](_0x4436a9,n[a(1706)](127,_0x485696[_0x2c111a])<<14),0);continue;case"6":_0x1e4dbc=n.EQSIa(n.GjDOC(_0x48cf2f,n[a(702)](127&_0x23eba6[_0x9a4b10],7)),0);continue;case"7":_0x5ad36e=n.fXFxk(_0x54841c,n[a(702)](127&_0x506633[_0x1849ef],21))>>>0;continue;case"8":if(n.uAPGS(_0x40e37b+=5,_0x134d6e[a(516)]))throw _0x400409=_0x5dca36.length,_0x13e5ae(_0xe29511,10,_0x4d9c17[a(516)]);continue;case"9":if(n.saHTM(_0x38a0d4[_0x481563++],128))return{value:_0x1ea6dd?_0x242c96:n[a(511)](0,_0x3e0255),offset:_0x5057c2};continue;case"10":_0x192d0f=n.EQSIa(n[a(1706)](127,_0x266c5d[_0x39c1ca]),0);continue;case"11":if(n[a(902)](_0x2c2500[_0x390c38++],128))return{value:_0x4210d8?_0x24f863:0|_0x5d5995,offset:_0x9b0345};continue}break}}}).catch(()=>{}),xa[e(651)](i,t),i}function v1(t){let e=U,n={ZWetk:e(1361),LgSoO:e(875),asahs:function(s,a){return s(a)},pLuJz:e(782)+"or",VRKof:function(s,a,d){return s(a,d)},JcPbY:e(760),BpoWD:e(894),QODYf:function(s){return s()},oeyYW:e(371)};if(ha.has(t))return;let i=new Promise((s,a)=>{let d=e,u={ULywD:function(w,v,_){return w(v,_)},Erxej:function(w,v,_){return n[G(480)](w,v,_)},LQEsh:n[d(1094)],mdnwa:function(w,v){return w===v},oxCqt:n[d(1673)],JThqu:function(w){return n[d(1391)](w)}},h=()=>{let w=d;t[w(1248)+w(943)+w(1390)](n[w(1688)],x),t[w(1248)+w(943)+"ner"]("error",g),t[w(1248)+"entListe"+w(1390)](n[w(683)],g)},x=()=>{let w=d,v={aSOhU:function(_,E,I){return u[G(1849)](_,E,I)},MmWFe:function(_,E,I){return u[G(1312)](_,E,I)},CTAvY:u[w(569)]};u[w(1230)](u.oxCqt,w(894))?(s(),u[w(1536)](h)):_0x335c45.resolve()[w(1327)](()=>{let _=w,E=v[_(833)](_0x5da0e3,_(371),{message:this["_formatE"+_(1316)+"age"](_0x3c6ebb)});this[_(1387)](_(371),E);let I=v[_(670)](_0x11fe79,v[_(1158)],{reason:this["_formatE"+_(1316)+"age"](_0x35b8f0)});this[_(1387)](v.CTAvY,I)})},g=()=>{let w=d;n[w(1866)](a,t.error||new DOMException(n[w(1138)],n[w(1138)])),h()};t[d(1795)+d(1518)]("complete",x),t[d(1795)+d(1518)](n[d(820)],g),t[d(1795)+d(1518)](n[d(683)],g)});ha[e(651)](t,i)}function S1(t){pa=t(pa)}function I1(t){let e=U,n={IUkqP:function(i,s){return i(s)},icHGF:function(i,s){return i(s)},rVhFt:function(i,s){return i in s},vQYZn:e(753)+e(724),EZXgz:function(i){return i()}};return t===IDBDatabase.prototype["transact"+e(1502)]&&!n[e(1377)](n[e(1517)],IDBTransaction.prototype)?function(i,...s){let a=e,d=t[a(768)](n.IUkqP(xs,this),i,...s);return ol[a(651)](d,i.sort?i[a(815)]():[i]),n[a(961)](jt,d)}:n[e(624)](b1)[e(1854)](t)?function(...i){let s=e;return t[s(1059)](n[s(961)](xs,this),i),n[s(961)](jt,al.get(this))}:function(...i){let s=e;return n[s(1403)](jt,t[s(1059)](n[s(1403)](xs,this),i))}}function A1(t){let e=U,n={GOsdU:function(i,s){return i(s)},sPTpw:function(i,s){return i instanceof s},jolCs:function(i,s){return i(s)},DejtI:function(i,s,a){return i(s,a)},Qibjr:function(i){return i()}};return typeof t===e(871)?n[e(1155)](I1,t):(n[e(1030)](t,IDBTransaction)&&n[e(726)](v1,t),n[e(1042)](gp,t,n.Qibjr(y1))?new Proxy(t,pa):t)}function jt(t){let e=U,n={zPnXx:function(s,a){return s instanceof a},MQbFZ:function(s,a){return s(a)}};if(n[e(390)](t,IDBRequest))return n[e(1313)](E1,t);if(ua[e(1813)](t))return ua[e(1478)](t);let i=n.MQbFZ(A1,t);return i!==t&&(ua.set(t,i),xa[e(651)](i,t)),i}var gp,lp,up,al,ha,ol,ua,xa,pa,xs,fp=pp({"node_modules/idb/build/wrap-idb-value.js"(){let t=U,e={APcef:function(n,i){return n instanceof i},KEEiV:function(n,i){return n===i},tqfti:t(415),nMLJP:t(753)+t(724),iVbbc:"store",oOypr:function(n,i){return n(i)},GKyHM:t(840),KFkqw:function(n,i){return n instanceof i},VGMKP:function(n,i){return n===i},vxdoO:function(n,i){return n in i}};gp=(n,i)=>i[t(368)](s=>n instanceof s),al=new WeakMap,ha=new WeakMap,ol=new WeakMap,ua=new WeakMap,xa=new WeakMap,pa={get(n,i,s){let a=t;if(e[a(1232)](n,IDBTransaction)){if(e[a(1341)](i,e.tqfti))return ha.get(n);if(e[a(1341)](i,e[a(658)]))return n[a(753)+"oreNames"]||ol[a(1478)](n);if(e[a(1341)](i,e[a(1344)]))return s[a(753)+a(724)][1]?void 0:s[a(753)+a(1697)](s[a(753)+a(724)][0])}return e[a(1552)](jt,n[i])},set(n,i,s){let a=t;return e.KEEiV(e[a(452)],e[a(452)])?(n[i]=s,!0):this[a(1298)]?this[a(1298)][a(1165)+"ns"]:""},has(n,i){let s=t;return e.KFkqw(n,IDBTransaction)&&(e[s(1341)](i,e[s(824)])||e.VGMKP(i,e[s(1344)]))?!0:e[s(596)](i,n)}},xs=n=>xa[t(1478)](n)}}),mp={};_1(mp,{deleteDB:()=>T1,openDB:()=>k1,unwrap:()=>xs,wrap:()=>jt});function k1(t,e,{blocked:n,upgrade:i,blocking:s,terminated:a}={}){let d=U,u={UREwN:function(g,w,v,_,E){return g(w,v,_,E)},Jnttv:function(g,w){return g(w)},RcPHJ:function(g,w){return g(w)},XYHik:d(913)+"hange"},h=indexedDB[d(499)](t,e),x=u[d(773)](jt,h);return i&&h[d(1795)+"Listener"]("upgraden"+d(1350),g=>{let w=d;u[w(346)](i,u[w(773)](jt,h.result),g[w(1873)+"on"],g.newVersion,u[w(1399)](jt,h[w(445)+w(1502)]))}),n&&h[d(1795)+d(1518)](d(715),()=>n()),x.then(g=>{let w=d;a&&g[w(1795)+w(1518)](w(760),()=>a()),s&&g[w(1795)+"Listener"](u[w(1244)],()=>s())})[d(1225)](()=>{}),x}function T1(t,{blocked:e}={}){let n=U,i={clFpt:n(715)},s=indexedDB["deleteDa"+n(1733)](t);return e&&s[n(1795)+n(1518)](i.clFpt,()=>e()),jt(s)[n(1327)](()=>{})}function hp(t,e){let n=U,i={jZxzd:"cursor_f"+n(1002),tcOdH:n(1178)+"e",DQvGA:n(1504),PlwHe:function(h,x){return h instanceof x},xnAmf:function(h,x){return h===x},iFeOK:n(439),jGkhP:function(h,x){return h!==x},RbRrf:function(h,x){return h in x},jjhid:function(h,x){return h===x},LlobD:n(1372),pRjyy:"pKKFT"};if(!(i[n(1574)](t,IDBDatabase)&&!(e in t)&&i[n(1593)](typeof e,i.iFeOK)))return;if(fa[n(1478)](e))return fa[n(1478)](e);let s=e[n(1650)](/FromIndex$/,""),a=i[n(1068)](e,s),d=_p[n(1854)](s);if(!i[n(1434)](s,(a?IDBIndex:IDBObjectStore)[n(1700)+"e"])||!(d||wp[n(1854)](s)))return i.jjhid(i[n(550)],i[n(1191)])?{frameType:_0x14ca50,headers:[{key:i.jZxzd,value:n(802)+n(457)}],payload:void 0}:void 0;let u=async function(h,...x){let g=n,w=this["transact"+g(1502)](h,d?i[g(675)]:i[g(1264)]),v=w[g(635)];return a&&(v=v[g(1268)](x[g(965)]())),(await Promise[g(1330)]([v[s](...x),d&&w[g(415)]]))[0]};return fa.set(e,u),u}var wp,_p,fa,P1=pp({"node_modules/idb/build/index.js"(){let t=U,e={VMgno:function(n){return n()},GroVV:t(1478),fAhuo:t(1600),OlQpD:t(1095),FBXcz:"getAllKeys",eybYs:t(601),izmFp:t(1662),LgVoD:t(1044),oaiDy:function(n,i){return n(i)}};e[t(1617)](fp),e[t(1617)](fp),wp=[e[t(488)],e[t(531)],e[t(417)],e[t(573)],t(1141)],_p=[t(930),e[t(396)],e[t(1200)],e[t(831)]],fa=new Map,e.oaiDy(S1,n=>({...n,get:(i,s,a)=>hp(i,s)||n[t(1478)](i,s,a),has:(i,s)=>!!hp(i,s)||n[t(1813)](i,s)}))}}),D1={idb:function(t){let e=U;t.exports=Promise[e(1599)]()[e(1327)](()=>(P1(),mp))[e(1327)](function(n){return n})}},xp={};function qt(t){let e=U;var n=xp[t];if(n!==void 0)return n[e(1823)];var i=xp[t]={exports:{}};return D1[t](i,i[e(1823)],qt),i[e(1823)]}qt.d=(t,e)=>{let n=G;for(var i in e)qt.o(e,i)&&!qt.o(t,i)&&Object[n(1652)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=U;qt.o=(e,n)=>Object[t(1700)+"e"][t(1443)+t(755)].call(e,n)})(),(()=>{let t=U,e={mgxGi:t(547)+"d",NnYoO:t(1796),pxBOY:t(525)+"le"};qt.r=n=>{let i=t;e[i(1046)]!=typeof Symbol&&Symbol["toString"+i(1474)]&&Object["definePr"+i(755)](n,Symbol[i(1489)+i(1474)],{value:e[i(1373)]}),Object[i(1652)+i(755)](n,e[i(428)],{value:!0})}})();var Me={};(()=>{let t=U,e={GiQpQ:function(c,r){return c(r)},iajSt:function(c,r){return c+r},kDvaX:function(c,r){return c+r},WmDGY:function(c,r){return c+r},eOpwV:function(c,r){return c*r},vuPUF:function(c,r,o){return c(r,o)},Ykeqv:t(929),uDrzj:t(922),tmnHR:function(c,r){return c+r},OHQLY:function(c,r){return c(r)},PISPQ:t(341),ECLnK:t(877),rFMEe:"00000000"+t(416)+t(416)+t(416),fgAxL:function(c,r){return c<r},yvTSZ:function(c,r){return c|r},DDLQj:function(c,r){return c&r},KzawE:function(c,r){return c>>r},ZInnU:function(c,r){return c|r},ZvZbH:function(c,r){return c&r},HVwaH:function(c,r){return c>>r},tJRMA:function(c,r){return c|r},BLwcG:function(c,r){return c>>r},hpIhn:function(c,r){return c|r},WWMPA:function(c,r){return c&r},ILbdq:function(c,r){return c>>r},YGftH:function(c,r){return c|r},eYUDH:function(c,r){return c&r},AOzEL:function(c,r){return c>r},XrgQx:function(c,r){return c<r},cNamg:function(c,r){return c===r},yAwbE:t(886),SazGe:function(c,r){return c!==r},KXaKg:function(c,r){return c-r},VJNxE:function(c,r){return c===r},kEfLO:function(c,r){return c!==r},kuNLD:"BAnRZ",HgFla:function(c,r){return c!==r},NXvjN:t(860),wKZnt:t(438),HCAfK:function(c,r,o){return c(r,o)},WVzti:function(c,r,o){return c(r,o)},tvPHj:function(c,r){return c(r)},XsvpZ:function(c,r){return c>>>r},KNXsu:function(c,r,o){return c(r,o)},qPIZz:t(442)+"required field: "+t(1205),vlGbz:function(c,r,o){return c(r,o)},UEGEf:function(c,r){return c(r)},ATIuU:function(c,r,o){return c(r,o)},WqxUT:function(c,r){return c!==r},YZWly:function(c,r){return c!==r},GVPmo:t(1006),tALez:function(c,r,o){return c(r,o)},MudIL:function(c,r){return c(r)},djvON:function(c,r){return c!==r},LoZZs:function(c,r,o){return c(r,o)},DNQts:function(c,r){return c(r)},AmZUA:function(c){return c()},HnzfH:function(c,r,o){return c(r,o)},ZIFcF:function(c,r,o){return c(r,o)},OIkxn:function(c,r){return c!==r},RDuda:function(c,r){return c===r},JbGZD:"IqVZA",OYnLw:t(1369),UdSvi:function(c,r,o){return c(r,o)},hRVxY:function(c,r){return c!==r},VZUTO:function(c,r,o){return c(r,o)},GWwmm:function(c,r,o){return c(r,o)},zSiXq:function(c,r){return c(r)},XsRnl:function(c,r){return c===r},UsECd:t(1562),Pzeqd:t(1833),hUphP:function(c,r){return c>>>r},YRmPw:function(c,r){return c(r)},EWcRJ:function(c,r,o){return c(r,o)},ajMye:function(c,r){return c(r)},hQCID:function(c,r){return c(r)},IMNVP:function(c,r){return c===r},LGSHx:t(442)+t(566)+t(351)+t(703),gMgiB:function(c,r){return c===r},MJctc:"Missing "+t(566)+t(351)+"service",CWOOK:function(c,r){return c(r)},ypEYa:function(c,r){return c(r)},pwnGU:function(c,r,o){return c(r,o)},ceGiN:t(1561)+t(1755)+t(372),KuAta:function(c,r){return c+r},hnucK:"hYwWW",QNjaC:function(c,r){return c>>r},LBYMi:function(c,r){return c>=r},rCJkj:t(782)+"or",kwZJk:function(c,r){return c===r},MsEBK:t(1335),epytU:t(988),eqoPx:function(c,r){return c===r},gfAVV:t(620),CAnIT:t(1762),PhfTk:function(c,r){return c===r},OHEPy:function(c,r){return c>r},ARiHr:"Skip pas"+t(1024),hOgKR:function(c,r,o,l){return c(r,o,l)},VAzwF:t(472),FxSKN:function(c,r){return c>r},FEQuS:function(c,r){return c>r},tLgSG:function(c,r){return c>r},fMSUx:function(c,r){return c+r},idDfC:"is_ack",NmGYz:"ack_id",CRHek:function(c,r){return c||r},GqYMG:function(c,r){return c===r},TrIXc:t(1642),GGQTF:function(c,r,o){return c(r,o)},rhKFB:t(1361),NfZlp:t(875),YCafD:function(c){return c()},bwuCI:function(c,r){return c+r},GmKHR:function(c,r){return c&r},MbzEJ:function(c,r){return c+r},HOQzr:function(c,r){return c+r},QHrhP:function(c,r){return c&r},AscvK:function(c,r){return c&r},dJNNM:function(c,r){return c(r)},HsyfN:function(c,r){return c==r},osFLS:function(c,r){return c+r},LfRSI:function(c,r){return c+r},FfAQU:function(c,r){return c!==r},afPhV:function(c,r){return c|r},byxaU:function(c,r){return c<<r},PWXxJ:t(1040),KpIrI:t(1611),QQvqo:function(c,r){return c|r},eFcFk:function(c,r){return c|r},SuPAc:function(c,r){return c<<r},ZxiNF:function(c,r){return c<<r},ABNPe:function(c,r){return c<r},GWvZM:function(c,r){return c<=r},LhcdL:function(c,r){return c==r},rafhK:function(c,r){return c&r},zHpJD:function(c,r){return c+r},zJwqX:function(c,r){return c+r},yBzpy:function(c,r){return c+r},uSqLy:function(c,r){return c&r},jQDCv:function(c,r){return c|r},uRMrk:function(c,r){return c|r},KBbbN:function(c,r){return c|r},zWUkh:function(c,r){return c|r},zwQdr:function(c,r){return c<<r},qXzvP:function(c,r){return c<<r},FBOxh:function(c,r){return c<r},DKMqA:t(1824),SYZvx:function(c,r,o,l,f){return c(r,o,l,f)},JSCvD:function(c,r){return c!==r},VLZUY:function(c,r,o){return c(r,o)},AwaGn:"tWDoh",SBZTO:t(375),QhPxc:function(c,r){return c+r},HTnKY:function(c,r){return c<r},YDuOP:function(c,r){return c<r},IQtgF:"evwoM",bUGAF:function(c,r){return c<=r},SqKuJ:function(c,r){return c<r},jSFxm:function(c,r){return c<r},VcUWQ:"IVBge",HjHii:function(c,r){return c|r},QOjSr:function(c,r){return c&r},WWUen:function(c,r){return c>>r},haaLa:"eExAp",LtAff:t(1490),XNoaD:function(c,r){return c<r},FYVLv:function(c,r){return c&r},MvWBD:function(c,r){return c!==r},OOAbn:t(1773),klNWC:function(c,r){return c&r},kJDTd:function(c,r){return c>>r},vwNPB:function(c,r){return c&r},CsfUe:function(c,r,o){return c(r,o)},MzrGF:function(c,r,o){return c(r,o)},BoSBM:function(c,r){return c(r)},kblWR:function(c,r){return c<r},FDjIO:function(c,r){return c<<r},CEVxg:function(c,r){return c&r},DSiEI:function(c,r){return c|r},sSquq:t(549)+t(1209),TSuVB:function(c,r){return c(r)},ZGptV:function(c,r){return c&r},NYKMy:t(1092),RvAHE:function(c,r){return c===r},OpItT:function(c,r){return c(r)},xLKEi:function(c,r){return c&r},OYEIT:function(c,r){return c(r)},Wlkgj:function(c,r){return c&r},Zodsb:function(c,r){return c<<r},RbVlV:function(c,r){return c<<r},IomCM:function(c,r){return c!==r},HQmTw:"QqwsK",kJPPK:function(c,r){return c<<r},mcgbd:function(c,r){return c&r},NKzfM:function(c,r){return c(r)},bXVEe:function(c,r){return c&r},uqoAQ:function(c,r){return c>>>r},mVgaY:function(c,r){return c<<r},ZdTvi:function(c,r){return c<<r},nIrWA:function(c,r){return c>>>r},QgttU:function(c,r){return c===r},GSrZk:function(c,r){return c<r},vxNcv:function(c,r){return c<r},ibfqb:function(c,r){return c<r},tgoxp:function(c,r){return c+r},LvGyN:function(c,r){return c|r},xSXtx:function(c,r){return c+r},YxMWe:function(c,r){return c|r},dRFEY:function(c,r){return c+r},xCNHR:function(c,r){return c>>>r},ztvCo:function(c,r){return c!==r},BIiSD:function(c,r){return c&r},XGQRk:function(c,r){return c>>>r},TwtRp:function(c,r){return c>>>r},mCmjU:function(c,r){return c&r},FHYZT:function(c,r){return c+r},VqXGs:function(c,r){return c&r},eNdid:function(c,r){return c|r},BqMzk:function(c,r){return c!==r},kTwMe:"nnMEt",qGMdm:function(c,r){return c|r},dtSTb:function(c,r){return c|r},gSFdj:function(c,r){return c<<r},rJmaR:function(c,r){return c<<r},CRuOQ:function(c,r){return c<<r},rvYaE:function(c,r){return c<<r},gHGJS:function(c,r){return c|r},Wiwkr:function(c,r){return c<<r},YVcPg:function(c,r){return c|r},uHVpo:function(c,r){return c|r},qPLQV:function(c,r){return c<<r},KpOMu:function(c,r){return c<<r},sGWdq:function(c,r){return c===r},HATHd:t(912),nqfVJ:function(c,r){return c===r},RKJPN:function(c,r){return c>>>r},RpvOn:function(c,r){return c|r},IgyWu:function(c,r){return c|r},iHdEP:function(c,r){return c>>>r},RDpaY:function(c,r){return c|r},VHqyK:t(1310)+t(542)+t(379)+t(1424)+"ver",WHkxf:t(1260),twDDt:function(c,r){return c&r},cjlKo:function(c,r){return c>>>r},Rapes:function(c,r){return c&r},xbmLN:function(c,r){return c>>>r},jukEK:"boe",hLasz:t(1666),GGrxm:t(1638),ZdBpe:function(c,r){return c(r)},MKySh:function(c,r){return c>=r},FShvB:function(c,r){return c<=r},yxUPN:function(c,r){return c+r},xrWSk:function(c,r){return c|r},obhAx:function(c,r){return c/r},rQRtc:t(1233),YruIp:function(c,r){return c*r},GskPH:function(c,r){return c>>>r},iJoEW:function(c,r){return c+r},wHonj:function(c,r){return c>>>r},EuGFA:function(c,r){return c===r},IZDzQ:function(c,r){return c===r},bsxQE:function(c,r){return c>>>r},DivZy:function(c,r){return c&r},XRuxn:function(c,r){return c&r},DlGqJ:function(c,r){return c>>>r},WScHv:function(c,r){return c&r},zHnns:function(c,r){return c+r},IKUNS:function(c,r){return c>>>r},PrMHh:function(c,r){return c+r},JIorg:function(c,r){return c>>>r},vjoRm:function(c,r){return c+r},ZIdnm:function(c,r){return c+r},ZcmEh:function(c,r){return c|r},Vgilk:function(c,r){return c==r},QsDQp:"string",TbWIh:function(c,r,o,l){return c(r,o,l)},UBFKz:t(1001),PMJxD:function(c,r){return c===r},VVgET:function(c,r){return c===r},TeCtV:function(c,r){return c===r},lQnbm:function(c,r){return c+r},pXcrs:function(c,r){return c+r},fqQij:function(c,r){return c&r},qULJh:function(c,r){return c&r},uwnpA:function(c,r){return c>>>r},KZOao:function(c,r){return c>>>r},BKrMh:function(c,r){return c&r},WDQDc:function(c,r){return c>>>r},NTbzi:function(c,r){return c>>>r},BlrWQ:function(c,r){return c>>>r},cUXhh:function(c,r){return c>>>r},SKaHP:function(c,r){return c>>>r},DihCN:function(c,r){return c>>>r},HaIGE:function(c,r){return c>>>r},MVYSb:t(1808)+t(812),bElZv:t(626)+t(387),KwLNw:t(1687)+"IES_ERROR",NBYli:t(1695)+t(1829),gpPvj:function(c,r){return c<=r},DxEus:function(c,r){return c|r},saiZZ:function(c,r){return c-r},tYWFZ:function(c,r){return c!==r},vRKKd:t(652),PXiyF:function(c,r){return c===r},tgBFC:function(c,r){return c<=r},MXOnV:"iGzxn",irVju:t(1121),eihKR:t(1325),oqhBp:"foboJ",MeTTY:t(1364),wOFjD:function(c,r){return c>=r},ZIwVR:function(c,r){return c-r},fxGCJ:function(c,r){return c==r},PWThc:function(c,r){return c>r},weYZz:t(1482),VDLvX:"error",scwAs:function(c,r){return c instanceof r},YRLwj:function(c,r){return c+r},VAnAe:t(715),SQtPv:function(c,r){return c(r)},dLXnv:"YUNtr",EDipc:"KVWgY",pARUE:"open",OGAmy:function(c,r,o){return c(r,o)},TRQNK:function(c,r,o){return c(r,o)},tlCKi:function(c,r){return c===r},JcNrf:t(1612),vmVBn:"close",rIPyc:function(c,r,o){return c(r,o)},myTww:t(1229),OppAF:t(447),iWNYp:function(c,r,o){return c(r,o)},otMKR:function(c,r){return c(r)},wnHMc:function(c,r){return c===r},PmhxK:"tOTSk",qBtOG:function(c,r){return c+r},Mhhyd:t(1314),jQRab:t(1086),dLFVz:function(c,r){return c||r},CKdKW:"undefined",fQYTa:function(c,r){return c!=r},cPLHY:function(c,r){return c+r},sssLx:function(c,r){return c>>>r},rmdEw:function(c,r){return c>>>r},wScdt:function(c,r){return c&r},qLwqw:function(c,r){return c===r},ZrVXa:"WUyMB",EoQkd:t(519),nmBpU:function(c,r){return c<r},WevOF:function(c,r){return c<r},NIJcs:function(c,r){return c===r},LHWvB:function(c,r){return c+r},SeOoc:function(c,r){return c(r)},SKRDa:t(1850)+t(809)+"s",oNXRg:t(1850)+t(1265)+"t",nWFhy:"NBcMZ",BAtUi:function(c,r){return c<=r},EWzeI:function(c,r){return c&r},oQhng:function(c,r){return c|r},sccHk:function(c,r){return c|r},nJYAY:function(c,r){return c|r},yqrMA:function(c,r){return c<<r},CKKkr:function(c,r){return c+r},CYgSO:function(c,r){return c+r},vnKIg:function(c,r){return c+r},uKxNW:function(c,r){return c!==r},hxQyw:"OTXTE",zylue:function(c,r){return c<r},vMoCI:function(c,r){return c<r},OQgPl:function(c,r){return c>>r},QhEdR:function(c,r){return c&r},pwkJX:"SKugO",kssTP:t(1234)+t(762),wtdFK:function(c,r){return c+r},qZqMH:function(c,r){return c&r},WbKIw:function(c,r){return c&r},orkZj:function(c,r){return c>>r},DVMHE:function(c,r){return c|r},PwHdL:function(c,r){return c|r},cxLZX:function(c,r){return c>>r},LyDJU:function(c,r){return c&r},IjymB:function(c,r){return c==r},KDZqH:t(816),XOmsm:function(c,r){return c instanceof r},cvwEM:function(c,r){return c!=r},VqEcp:t(678)+t(604),etvNL:function(c,r){return c>=r},cWQrN:function(c,r){return c(r)},fHrjJ:function(c,r){return c===r},ybaXt:t(917),fSCgq:t(1416)+t(1118),ZjZHb:function(c,r){return c+r},MJShp:t(1741),oRzgW:"WyMQI",JXMkK:t(1263),kJlfg:t(1539),KUlfb:function(c,r){return c||r},firFm:function(c,r){return c||r},BbZuz:function(c,r){return c||r},qAuOq:"gIlWJ",qQcHi:"AaJJw",eBDSL:function(c,r){return c||r},hSvre:function(c,r){return c||r},MJtPs:function(c,r){return c!==r},SdsFZ:t(1271),LLTSm:function(c,r){return c+r},IZEom:t(1340),tnhQv:function(c,r){return c!=r},wwZpd:function(c,r){return c!=r},OMcVv:t(1152)+t(1481)+"d",IsyTh:function(c,r,o){return c(r,o)},DSNSC:t(1246),hLXns:t(656)+"id",qjtbw:t(1320),eIFwm:t(1661)+t(1293),HLdfo:"x_fronti"+t(941)+"ck",pUobD:t(1661)+t(714)+"k",hSXfC:t(1661)+t(1135)+"sgid",QTALH:t(484),nEzjK:function(c,r){return c(r)},ESLAm:function(c){return c()},RCYTw:function(c,r){return c===r},nAFGq:t(1863),nXKaz:t(761),QsJio:t(1215),JmIfI:function(c,r,o,l){return c(r,o,l)},KSHFX:function(c,r){return c&&r},OEuTQ:function(c,r){return c||r},UHnAE:t(1710),bkygZ:function(c,r,o){return c(r,o)},JDyfZ:"tgNYk",yrpBx:t(741),AdlLp:function(c){return c()},ZBFbo:function(c,r){return c(r)},DUQgT:function(c,r){return c(r)},FWKti:function(c,r){return c instanceof r},ougik:t(900),ykrzd:function(c,r,o,l){return c(r,o,l)},IcEhk:function(c,r){return c!==r},lEbkL:t(1180),qUVAD:function(c,r){return c>r},BeQvr:function(c,r){return c+r},Hdcfd:function(c,r){return c+r},XVqgy:function(c,r){return c+r},cbjcu:"index out of ran"+t(1098),uLTUl:" + ",aBLqC:function(c,r){return c||r},DhtLh:function(c,r){return c>r},QjpIS:t(344)+t(911)+"e",hJTsD:function(c,r){return c>=r},CBBlO:function(c,r,o,l){return c(r,o,l)},Qvndw:function(c,r){return c+r},gXrqx:t(425)+"4",lXNVf:function(c,r){return c<r},rFFQS:function(c,r){return c+r},ZbRMG:function(c,r,o,l){return c(r,o,l)},phaZc:function(c,r){return c|r},cZuFU:function(c,r){return c<<r},EVDWZ:function(c,r){return c+r},dpqjR:function(c,r){return c<<r},MGiVG:function(c,r){return c|r},YQaKH:function(c,r){return c<<r},iDsLC:function(c,r){return c+r},fyAjB:function(c,r){return c<<r},nnxpu:function(c,r){return c+r},JxTgj:function(c,r){return c+r},jGASs:function(c,r){return c+r},ZLfbi:function(c,r){return c&r},mQlxO:function(c,r){return c+r},ivNzJ:function(c,r){return c&r},nUPWM:function(c,r){return c+r},LshwO:function(c,r){return c&r},CVDEX:function(c,r){return c+r},eMZzP:function(c,r){return c&r},AUsXB:function(c,r){return c>r},ebzHn:function(c,r,o,l){return c(r,o,l)},ZAtEQ:function(c,r){return c|r},EGCFp:function(c,r){return c|r},TGUJu:function(c,r){return c<r},UatrQ:function(c,r){return c<<r},WROzp:function(c,r){return c&r},KHaXD:function(c,r){return c&r},oRdDL:t(622),csjbO:t(742),iJdLK:function(c,r){return c(r)},EdRSq:function(c,r){return c+r},RVYFC:function(c,r,o,l){return c(r,o,l)},SgSCt:t(473),dbnFb:t(718),RNLty:function(c,r){return c(r)},MMnjV:t(1594)+"ile_name",CsEjz:function(c,r){return c<r},DAmhf:function(c,r,o){return c(r,o)},etIgP:function(c,r,o){return c(r,o)},xZjgQ:function(c,r){return c+r},fZECU:t(802)+t(457),pqfLg:"cursor_n"+t(1035),taidJ:t(1197)+t(451),fWzQj:t(1073),wqHKz:t(1573),QWtQk:function(c){return c()},DPpcw:t(1569),YfLtP:function(c,r){return c!==r},OydWX:function(c,r){return c(r)},sHlMr:t(907)+"r",LNkhe:function(c,r,o){return c(r,o)},YhcYF:function(c,r){return c<<r},RVnYP:t(640),JUkQS:t(415),HeKHa:t(1860),baYfm:t(1177),nCTBO:function(c,r,o,l){return c(r,o,l)},yejts:t(1661)+t(1427),sAlEn:t(908)+"s",xSODh:"x-msg-cu"+t(1292)+"e",sZFra:function(c){return c()},OXiku:function(c,r){return c+r},QasNm:"jXThC",FjyRb:t(1719),RUbcp:function(c){return c()},Avavx:function(c){return c()},CssLW:t(333),QsXQI:t(1491),uoZCJ:function(c){return c()},VkcNU:function(c,r){return c===r},izAMs:function(c,r){return c===r},hXfWU:function(c,r){return c&&r},gmSHn:function(c,r,o){return c(r,o)},xsAgo:function(c){return c()},hXUTn:t(627),kPzsl:function(c){return c()},dIvZZ:function(c){return c()},aXLUi:function(c,r){return c<r},iKQqT:function(c,r,o){return c(r,o)},VuhtP:function(c){return c()},lpckX:function(c,r,o){return c(r,o)},nKtXy:function(c,r){return c&r},ZPYEy:function(c,r){return c!==r},iUGwe:function(c,r){return c>>>r},geFYy:function(c,r){return c&r},yoMHd:function(c,r){return c!==r},pnosA:function(c,r){return c+r},DHaBD:function(c,r){return c!==r},imbsL:function(c,r){return c!==r},uXvNV:function(c,r){return c>>>r},QUmRY:function(c,r){return c===r},Frzyn:function(c,r){return c===r},CcMfq:t(1214),QljaW:t(838),WjZYu:function(c,r){return c===r},jNtva:t(779),jlibQ:t(1052),NSoGx:function(c,r){return c===r},vufcV:function(c,r,o){return c(r,o)},wOeBk:function(c,r,o){return c(r,o)},earyz:function(c,r){return c!==r},ZliYU:t(1295),bcknM:function(c,r){return c===r},XXhVE:"KZgKL",pgQWB:function(c,r,o){return c(r,o)},lGhFB:t(1800),ZjNYt:t(808),trrJP:t(548)+t(1241),rWlDg:t(1303),PYFNF:function(c,r){return c==r},svNrx:function(c,r){return c===r},Rdvoh:t(1132)+t(680)+t(884),dgJrY:t(1132)+t(852)+t(850)+", WebSoc"+t(1060)+t(560)+t(398)+t(1497),uBxjw:t(1452),AmSty:t(1079),LKbUG:t(379)+"t",YkbwD:t(1307)+t(772)+t(1668)+"ct",HalHo:"offline",fGyWs:t(564),Zrslb:t(444),bhMZt:t(1519),rduSb:"ttwid",TaqAe:t(825)+"d",WzcOE:t(1132)+t(1105)+"ddID, de"+t(837)+t(687),dHBMH:t(871),hTbiz:function(c){return c()},blIAB:function(c,r,o){return c(r,o)},fIOSX:t(383),hcCfq:t(1204)+"0",xZuJg:function(c,r,o){return c(r,o)},uIjkv:function(c,r){return c||r},zgvFv:t(1712),xuyLj:function(c,r){return c-r},Kuvpt:function(c,r,o){return c(r,o)},xNXZq:function(c,r,o){return c(r,o)},fGajZ:function(c,r){return c-r},IOMUB:function(c,r,o){return c(r,o)},JnHsD:function(c,r){return c!==r},nPiby:t(1758),NBVhE:"kAZgr",uqOGu:t(482),EoRKT:t(617),YTYUF:t(1879)+t(1460)+t(1534)+"g",fDZpW:function(c,r){return c!==r},yXYpp:t(1368),cehFM:t(1633),GBoXf:function(c,r){return c(r)},ljZOd:t(822),KQWzv:t(1747),ByzaB:t(1862)+"3",fLidV:function(c,r){return c>>r},XoAFo:function(c,r){return c===r},OANoJ:function(c,r){return c|r},KNWMQ:function(c,r){return c&r},DGznl:function(c,r){return c&r},nLgMx:function(c,r){return c+r},vyZbz:function(c,r){return c+r},iHmNE:function(c,r){return c>>r},zcqjw:function(c,r){return c|r},xZVGO:function(c,r){return c|r},lOXVY:function(c,r){return c&r},kcVoj:function(c,r){return c>>r},oYEQB:t(1160)+"RROR",aTyTZ:t(458)+"OR",MOudf:t(1048),DnBay:t(1189),WPOfE:function(c,r,o){return c(r,o)},pIMNj:function(c,r,o){return c(r,o)},iXLUE:function(c,r,o){return c(r,o)},cjIKR:t(1310)+t(869)+t(1028)+t(365),OKTyQ:function(c,r){return c!==r},TgpSJ:t(405),GzGmC:"BnSuV",EeyOM:"oPLel",ptyBc:t(1576),aFiuI:t(1176),abJLm:t(1190)+"s instan"+t(705)+t(1057)+"ed",nToMM:function(c,r){return c===r},LayBe:t(1190)+t(1367)+t(500),xgvdw:function(c,r){return c===r},FIDXg:t(1495),VnbGv:function(c,r){return c==r},BpJSP:t(1132)+t(966)+t(796)+t(1708)+t(1663)+t(1228)+t(1216)+t(1083)+t(964),DmjXr:function(c,r){return c==r},tsrXa:t(526),DqErN:function(c,r){return c instanceof r},ZBGhe:function(c,r){return c(r)},qDCds:function(c,r){return c(r)},DjUHx:function(c,r){return c instanceof r},owtne:function(c,r){return c instanceof r},ktdkr:function(c,r){return c===r},SmYcR:t(1087),moXha:t(1279),hVZSA:function(c,r){return c||r},aJJbc:function(c,r){return c==r},iHdjL:function(c,r){return c!==r},VeImp:t(544)+t(914)+t(1740),FLzSu:"timeout",sxdPV:function(c,r){return c+r},DMGKr:t(1548),pDeec:t(1867),DAEfR:function(c,r){return c*r},HZqiu:function(c,r){return c===r},PuqTC:t(668),iGlLV:function(c,r){return c!=r},yVyUg:function(c,r){return c===r},IIJyf:function(c,r){return c===r},hqgGc:"Object",JsEMd:function(c,r){return c===r},AwrhW:"Dedicate"+t(1250)+t(863)+"pe",xykSG:function(c,r){return c!=r},ahuQp:function(c,r){return c!=r},CHyYg:function(c,r){return c!=r},cOCIz:function(c,r){return c!=r},hEchk:function(c,r){return c!=r},BQlSs:function(c,r){return c===r},ciJsH:"SharedWo"+t(1133)+t(1049),GcMyO:function(c,r){return c===r},IixQw:"ServiceWorkerGlo"+t(392),iCGXm:function(c,r){return c===r},zlxXB:function(c,r){return c!=r}};qt.r(Me),qt.d(Me,{FWS:()=>sm,CustomErrorEvent:()=>kl,createCloseEvent:()=>Et,ReconnectEvent:()=>Al,createErrorEvent:()=>ht,decodedFrame:()=>ln,createOpenEvent:()=>Ol,CustomCloseEvent:()=>Tl,createReconnectEvent:()=>Oa,FrontierMessageEvent:()=>Dl,encodeFrame:()=>Kt,createMessageEvent:()=>Rl,OpenEvent:()=>Cl,ErrorCode:()=>fn,Event:()=>ur,MessageEvent:()=>Pl});let n="";function i(c=""){let r=t,o="02",l=""+Date[r(1015)](),f=n||(n=e[r(557)](h,c)),m=Math[r(1819)]()[r(1489)](16)[r(350)](-6);return e[r(1532)](e[r(1532)](e[r(581)](o,l),f),m)}function s(){let c=t;return e[c(1113)](e.eOpwV(1e4,Date[c(1015)]()),Math[c(719)](e[c(1736)](1e4,Math[c(1819)]())))}function a(c){let r=t;return(e.GiQpQ(Array,8).join("0")+e[r(359)](parseInt,c,10)[r(1489)](2))[r(350)](-8)}function d(c){let r=t;if(e[r(1299)]!==e[r(1645)])return e.iajSt(e[r(557)](Array,4)[r(1324)]("0"),e[r(359)](parseInt,c,2)[r(1489)](16))[r(350)](-4);{let o=_0xc9d52a[r(1747)][r(841)];o&&_0x542939[r(1116)+"rs"](o)}}function u(c){let r=t,o=c.split(/\./).map(m=>a(m)),l=[];return l[0]=d(e[r(778)](o[0],o[1])),l[1]=e[r(663)](d,e[r(581)](o[2],o[3])),[e[r(991)],e[r(991)],e.PISPQ,e.PISPQ,e.PISPQ,e.ECLnK,l[0],l[1]].join("")}function h(c){let r=t,o=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(1702)](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(1702)](c);return o?e[r(557)](u,c):l?e[r(557)](x,c):e.rFMEe}function x(c){let r=t,o={MKFfi:function(R,M){return e[G(663)](R,M)}},l="",f=[],m=0,y=0,S=!0,p=e[r(991)];if(e[r(429)](c[r(632)]("::"),-1)){let R=c[r(1604)]("::");for(let F=0;e[r(990)](F,R[r(516)]);F++){let P=R[F];if(e[r(429)](P[r(632)](":"),0))if(e.cNamg(e[r(1703)],e[r(1703)])){let D=P[r(1604)](":");S&&(m=D[r(516)]),y+=D[r(516)];for(let B=0;B<D[r(516)];B++)if(e[r(448)](4,D[B][r(516)])){let ie=p[r(1618)+"g"](0,4-D[B][r(516)]),le=ie[r(1760)](D[B]);f.push(le)}else f.push(D[B]);S=!1}else _0x590e6a(_0x3b2568(_0x47bbc4[r(427)]),_0xbb00c[r(1873)+"on"],_0x5b4c96[r(376)+"on"],ChPSEU[r(1553)](_0x14e299,_0xd3311e["transact"+r(1502)]));else{if(e[r(448)](4,P.length)){let D=p[r(1618)+"g"](0,e[r(1513)](4,P[r(516)])),B=D[r(1760)](P);f.push(B)}else f.push(P);S&&(m+=1),y+=1,S=!1}}let M="";for(let F=0;F<8-y;F++)M=M[r(1760)](p);for(let F=0;e[r(990)](F,f[r(516)]);F++)e[r(1371)](F,m)?(l=l[r(1760)](M),l=l[r(1760)](f[F])):l=l.concat(f[F]);return l}{let R=c[r(1604)](":");for(let M=0;e[r(990)](M,R[r(516)]);M++)if(e[r(630)](e[r(729)],r(1875)))e[r(470)](_0x351b9b,2048)?_0x3ead12[_0x297024++]=e[r(623)](e[r(1351)](e[r(1239)](_0x1d2876,6),31),192):(_0x9db3f0<65536?_0x5b69d0[_0x547dbd++]=e[r(937)](e[r(1401)](e[r(1149)](_0x5c440a,12),15),224):(_0xc0fb1f[_0x2c862e++]=_0x31f6a8>>18&7|240,_0x4b2a58[_0x672e50++]=e[r(1846)](e[r(1542)](_0x365467,12)&63,128)),_0x1c8a6e[_0x4209ad++]=e[r(1844)](e[r(1883)](e[r(1426)](_0x532022,6),63),128)),_0x163294[_0x30adb2++]=e[r(1348)](e[r(1181)](63,_0x42d466),128);else{let F=R[M];if(e[r(545)](4,R[M].length)){let P=p.substring(0,4-R[M].length),D=P[r(1760)](F);l=l[r(1760)](D)}else l=l[r(1760)](F)}return l}}function g(c,r){let o=t,l=c[o(1205)];if(l!==void 0)if(e[o(413)]!==e.wKZnt)e[o(1338)](_e,r,10),q(r,l);else return _0x35cb7e?.[o(710)](m=>m[o(1205)]===_0x57464f)?.[o(1339)];let f=c[o(1339)];f!==void 0&&(e[o(359)](_e,r,18),e[o(1782)](q,r,f))}function w(c){let r=t,o={};e:for(;!e[r(557)](Z,c);){let l=e[r(644)](pe,c);switch(e.XsvpZ(l,3)){case 0:break e;case 1:o.key=e[r(1782)](C,c,e[r(557)](pe,c));break;case 2:o.value=e[r(496)](C,c,e[r(557)](pe,c));break;default:e[r(496)](T,c,e.eYUDH(7,l))}}if(e[r(1371)](void 0,o.key))throw new Error(e.qPIZz);if(e[r(968)](void 0,o[r(1339)]))throw new Error(r(442)+r(566)+" field: "+r(1339));return o}function v(c){let r=t,o=L();return e[r(1818)](_,c,o),e[r(597)](z,o)}function _(c,r){let o=t,l={fpQPQ:function(le,ye,vt){return e[G(1338)](le,ye,vt)},wuQuu:function(le,ye,vt){return e.vlGbz(le,ye,vt)}},f=c[o(1309)];e[o(1745)](void 0,f)&&(e.vlGbz(_e,r,8),e[o(359)](bt,r,f));let m=c[o(703)];if(e[o(1588)](void 0,m))if(o(1006)===e[o(1472)])e.vuPUF(_e,r,16),bt(r,m);else{let le=e[o(1143)](_0x2052ef,_0x105e68,_0x10a2fe);return _0x406e78.bytes[o(1499)](le,le+_0x483897)}let y=c[o(394)];e.kEfLO(void 0,y)&&(e[o(359)](_e,r,24),e.tALez(bt,r,e[o(1137)](O,y)));let S=c[o(800)];e[o(1535)](void 0,S)&&(e[o(1400)](_e,r,32),e[o(1558)](bt,r,e[o(1162)](O,S)));let p=c[o(602)];if(e[o(1745)](void 0,p))for(let le of p){e[o(1400)](_e,r,42);let ye=e[o(1630)](L);e[o(1782)](g,le,ye),e.vuPUF(_e,r,ye.limit),e.HnzfH(W,r,ye),e.MudIL(N,ye)}let R=c[o(1526)+o(395)];R!==void 0&&(_e(r,50),e[o(1681)](q,r,R));let M=c.payloadType;e.OIkxn(void 0,M)&&(e[o(558)](e[o(1370)],e[o(1848)])?(this[o(1789)+o(1591)+o(1175)]=_0x5741b8,_0x1d7ef3?this["_handleO"+o(1153)]():this[o(999)+o(1322)]()):(_e(r,58),e[o(896)](q,r,M)));let F=c.payload;e[o(648)](void 0,F)&&(o(1476)===o(1476)?(_e(r,66),e[o(1832)](_e,r,F[o(516)]),e.GWwmm(de,r,F)):(l[o(880)](_0x1da27a,_0x590fd0,16),l[o(606)](_0x585b82,_0xe6752f,_0xb0fe30)));let P=c.LogIDNew;e[o(1026)](void 0,P)&&(e[o(1521)](_e,r,74),q(r,P));let D=c[o(1009)+"ming"];e[o(1026)](void 0,D)&&(_e(r,82),q(r,D));let B=c[o(477)];B!==void 0&&(e[o(1681)](_e,r,90),q(r,B));let ie=c[o(1173)+"e"];e[o(545)](void 0,ie)&&(_e(r,96),e[o(1782)](bt,r,O(ie)))}function E(c){return e[t(614)](I,H(c))}function I(c){let r=t,o={};e:for(;!Z(c);){if(e.XsRnl(e[r(411)],e.Pzeqd))throw this[r(643)+r(410)]=!1,_0x320214;{let l=pe(c);switch(e[r(970)](l,3)){case 0:break e;case 1:o[r(1309)]=e[r(1521)](Ct,c,!0);break;case 2:o.LogID=e.WVzti(Ct,c,!0);break;case 3:o[r(394)]=pe(c);break;case 4:o[r(800)]=pe(c);break;case 5:{let f=A(c);(o.headers||(o[r(602)]=[]))[r(1302)](e[r(562)](w,c)),c[r(780)]=f;break}case 6:o.payloadEncoding=C(c,e[r(1162)](pe,c));break;case 7:o[r(450)+"ype"]=e[r(1545)](C,c,e[r(1137)](pe,c));break;case 8:o[r(841)]=e[r(1558)](se,c,e[r(1730)](pe,c));break;case 9:o[r(700)]=e[r(896)](C,c,pe(c));break;case 10:o[r(1009)+"ming"]=C(c,pe(c));break;case 11:o[r(477)]=e.vlGbz(C,c,e[r(597)](pe,c));break;case 12:o.frameType=e[r(672)](pe,c);break;default:e[r(1681)](T,c,7&l)}}}if(e[r(1195)](void 0,o[r(1309)]))throw new Error(r(442)+r(566)+r(351)+r(1309));if(e.XsRnl(void 0,o.LogID))throw new Error(e.LGSHx);if(e.gMgiB(void 0,o[r(394)]))throw new Error(e[r(1749)]);if(e[r(443)](void 0,o.method))throw new Error(r(442)+r(566)+r(351)+r(800));return o}function A(c){let r=t,o=e.CWOOK(pe,c),l=c.limit;return c.limit=e.WmDGY(c[r(1575)],o),l}function T(c,r){let o=t;switch(r){case 0:for(;e[o(1401)](128,te(c)););break;case 2:e[o(1832)](Y,c,e[o(485)](pe,c));break;case 5:e[o(1159)](Y,c,4);break;case 1:e[o(1545)](Y,c,8);break;default:throw new Error(e.ceGiN+r)}}function O(c){let r=t,o={yKkEE:function(l,f){return l<f},uqzKi:function(l,f){return e.KuAta(l,f)},iIxtk:function(l,f,m,y){return l(f,m,y)}};return e[r(1804)]!==e.hnucK?_0x483745?o[r(1470)](_0x47147e[r(516)],40)?o.uqzKi(o[r(1383)](_0x18eddc,_0x45ed2c,_0x1cd99c,_0x4563da),_0x583142):_0x2ff002[r(819)+"e"]?_0x46e4b9[r(819)+"e"](_0x11fde2,_0x11fbae)+_0x2579ce:_0x5b2d77[r(1718)]?_0xac1f5a[r(1718)](_0x2249c9,_0x34232f)+_0x5455cb:o[r(1082)](o[r(1383)](_0x51c145,_0x935001,_0x3bf1a2,_0x16a0e8),_0x12c886):_0x5e03ca:(c|=0,{low:c,high:e[r(498)](c,31),unsigned:e[r(787)](c,0)})}let b=[];function L(){let c=t,r={ZACNg:function(o,l){return o(l)},QAsKl:e.rCJkj,ieQxH:function(o){return e[G(1630)](o)}};if(e[c(540)](e[c(1815)],e[c(1815)])){let o=b[c(892)]();return o?(o[c(1575)]=o[c(780)]=0,o):{bytes:new Uint8Array(64),offset:0,limit:0}}else RGamCA[c(1531)](_0x5c1094,_0x83871c[c(371)]||new _0x1db6b8(RGamCA[c(1717)],RGamCA.QAsKl)),RGamCA.ieQxH(_0x3f49c4)}function N(c){b.push(c)}function H(c){let r=t,o={BdCTH:e.epytU};if(e[r(919)](e[r(1281)],r(620)))return{bytes:c,offset:0,limit:c[r(516)]};this[r(347)+"er"]&&_0xdabaf1[r(1248)+"entListe"+r(1390)]("pagehide",this[r(934)+r(595)]),this[r(347)+"er"]&&_0x1f5f9f[r(1248)+r(943)+"ner"](o[r(570)],this[r(934)+r(618)]),this[r(760)]()}function z(c){let r=t;if(e[r(540)](e[r(1096)],e[r(1096)])){let o=c[r(1589)],l=c[r(780)];return e[r(1887)](o[r(516)],l)?o:o[r(1499)](0,l)}else this[r(1332)+r(1347)]=_0x3d17fd,this.count=0}function Y(c,r){let o=t;if(e[o(704)](e.kDvaX(c[o(1575)],r),c.limit))throw new Error(e[o(1810)]);c[o(1575)]+=r}function Z(c){let r=t;return c[r(1575)]>=c[r(780)]}function ae(c,r){let o=t,l={qvTOv:function(f,m){return f&m},cGlGC:function(f,m,y,S){return e.hOgKR(f,m,y,S)}};if(e[o(1745)](e[o(332)],o(1514))){let f=c[o(1589)],m=c[o(1575)],y=c[o(780)],S=e.iajSt(m,r);if(e.FxSKN(S,f[o(516)])){let p=new Uint8Array(2*S);p[o(651)](f),c[o(1589)]=p}return c[o(1575)]=S,e[o(1103)](S,y)&&(c[o(780)]=S),m}else{let f=l.qvTOv(255,_0x4756df);l.cGlGC(_0x33daed,f,_0x471d15,_0x1a1a6b+_0x4c7a10),_0x578c7f>>>=8,_0x354e4d--}}function Q(c,r){let o=t,l=c[o(1575)];if(e[o(1838)](e[o(1487)](l,r),c[o(780)]))throw new Error(o(1034)+o(1024));return c.offset+=r,l}function se(c,r){let o=t,l={OStLK:e[o(851)],DWfqi:e.NmGYz,PKQkF:function(f,m){return e[o(1669)](f,m)}};if(e[o(1270)](e[o(591)],e[o(591)])){let f=e.pwnGU(Q,c,r);return c[o(1589)][o(1499)](f,f+r)}else{let{SeqID:f,LogID:m,service:y,LogIDNew:S,method:p}=_0x5c5a1a.message;this._sendAck({SeqID:f,LogID:m,LogIDNew:S,service:y,method:p,headers:[{key:l.OStLK,value:"1"},{key:l[o(722)],value:l[o(1003)](S,"")},{key:o(1710),value:"0"}]})}}function de(c,r){let o=e.GGQTF(ae,c,r.length);c.bytes.set(r,o)}function C(c,r){let o=t,l={MJTWd:e[o(953)],rEFNV:e[o(758)],nzbUr:function(R){return e[o(879)](R)}},f=Q(c,r),m=String["fromChar"+o(1837)],y=c[o(1589)],S="\uFFFD",p="";for(let R=0;R<r;R++){let M=y[e[o(436)](R,f)],F,P,D,B;if(e.RDuda(e[o(1459)](128,M),0))p+=m(M);else if(e[o(443)](e[o(1401)](224,M),192))e[o(378)](R,1)>=r?p+=S:(F=y[e[o(748)](e[o(581)](R,f),1)],e[o(1745)](e.QHrhP(192,F),128)?p+=S:(B=e[o(1844)](e[o(932)](31,M)<<6,63&F),e[o(990)](B,128)?p+=S:(p+=e[o(471)](m,B),R++)));else if(e[o(843)](e.ZvZbH(240,M),224))if(e[o(787)](e[o(778)](R,2),r))p+=S;else if(F=y[e.HOQzr(e[o(1113)](R,f),1)],P=y[e[o(1684)](e[o(1750)](R,f),2)],e[o(1168)](e.eYUDH(e[o(1676)](F,e.byxaU(P,8)),49344),32896))p+=S;else if(e[o(1743)]===e[o(1699)]){let ie={QBWxm:function(we,fi){return we(fi)},QLIqH:"AbortError",vfSbO:function(we){let fi=o;return qIeLXP[fi(1630)](we)}},le=()=>{let we=o;_0x2ad503["removeEv"+we(943)+we(1390)](IXbWMp[we(1418)],ye),_0x3db36f[we(1248)+we(943)+we(1390)](we(371),vt),_0x2e4246[we(1248)+we(943)+we(1390)](IXbWMp[we(1651)],vt)},ye=()=>{let we=o;IXbWMp[we(676)](_0x30b553),IXbWMp[we(676)](le)},vt=()=>{let we=o;ie[we(1496)](_0x1f49ce,_0x315aac[we(371)]||new _0x407609(ie[we(682)],we(782)+"or")),ie.vfSbO(le)};_0x2b166d[o(1795)+"Listener"](qIeLXP.rhKFB,ye),_0x1404f2[o(1795)+o(1518)](o(371),vt),_0x3dd629[o(1795)+"Listener"]("abort",vt)}else B=e.QQvqo(e.eFcFk(e.SuPAc(e[o(1459)](15,M),12),e.ZxiNF(e[o(1828)](63,F),6)),63&P),e[o(426)](B,2048)||B>=55296&&e.GWvZM(B,57343)?p+=S:(p+=e[o(557)](m,B),R+=2);else e[o(1790)](e.rafhK(248,M),240)?e[o(787)](e[o(581)](R,3),r)?p+=S:(F=y[e.zHpJD(e.osFLS(R,f),1)],P=y[e.zJwqX(e[o(436)](R,f),2)],D=y[e[o(975)](e[o(1532)](R,f),3)],e[o(1745)](e[o(931)](e[o(541)](e[o(1404)](F,P<<8),e[o(592)](D,16)),12632256),8421504)?p+=S:(B=e[o(404)](e[o(972)](e[o(972)](e[o(823)](7&M,18),e[o(386)](63&F,12)),e[o(814)](63&P,6)),e.DDLQj(63,D)),e[o(1362)](B,65536)||B>1114111?p+=S:e.DKMqA!==o(612)?(B-=65536,p+=e.pwnGU(m,e[o(1679)](e[o(1239)](B,10),55296),(1023&B)+56320),R+=3):(this["_message"+o(1726)].shift(),this[o(1786)+o(1726)][o(1302)](_0x156ab7)))):p+=S}return p}function q(c,r){let o=t,l={pYRod:function(R,M){return e[G(990)](R,M)},HORDP:function(R,M){return e[G(1108)](R,M)},yiaON:function(R,M,F){return e[G(377)](R,M,F)},BIRYP:function(R,M){return e[G(970)](R,M)},zwwaV:function(R,M){return e[G(814)](R,M)}},f=r.length,m=0;for(let R=0;e[o(990)](R,f);R++)if(e[o(1315)]!==e.SBZTO){let M=r[o(708)+"At"](R);M>=55296&&e[o(662)](M,56319)&&R+1<f&&(M=e.QhPxc(M<<10,r[o(708)+"At"](++R))-56613888),m+=M<128?1:e[o(1280)](M,2048)?2:e[o(830)](M,65536)?3:4}else return(e.UEGEf(_0x4fd917,4).join("0")+e[o(1818)](_0x2f8e56,_0x2791a7,2)[o(1489)](16))[o(350)](-4);_e(c,m);let y=e[o(359)](ae,c,m),S=c.bytes;for(let R=0;R<f;R++)if(e.IMNVP(e[o(1412)],o(1825))){let M=r[o(708)+"At"](R);if(e[o(787)](M,55296)&&e[o(1114)](M,56319)&&e[o(836)](R+1,f)&&(M=e[o(1113)](M<<10,r[o(708)+"At"](++R))-56613888),e.jSFxm(M,128))S[y++]=M;else if(e.VcUWQ===e.VcUWQ){if(e[o(1362)](M,2048))S[y++]=e[o(1765)](e[o(1540)](e[o(1366)](M,6),31),192);else if(e[o(1371)](e[o(691)],e[o(1172)])){let F=_0x2dced5[o(1604)](":");for(let P=0;qglhnu[o(1053)](P,F[o(516)]);P++){let D=F[P];if(qglhnu.HORDP(4,F[P].length)){let B=_0x412aa7[o(1618)+"g"](0,4-F[P][o(516)]),ie=B[o(1760)](D);_0x65622f=_0x400464[o(1760)](ie)}else _0x25cb46=_0x297d4f.concat(D)}return _0x46354c}else{if(e.XNoaD(M,65536))S[y++]=e[o(1430)](e[o(1149)](M,12),15)|224;else if(e[o(924)](e[o(1157)],e[o(1157)]))for(var p in _0x5e68ec)_0x60ec02.o(_0x3bf7d6,p)&&!_0x12f0ee.o(_0x349653,p)&&_0x34abe0[o(1652)+o(755)](_0x2f4da7,p,{enumerable:!0,get:_0x3fa7bc[p]});else S[y++]=e.klNWC(e.kJDTd(M,18),7)|240,S[y++]=e[o(1404)](e[o(1426)](M,12)&63,128);S[y++]=e[o(747)](e[o(1207)](M>>6,63),128)}S[y++]=e.AscvK(63,M)|128}else{let{value:F,offset:P}=l[o(1019)](_0x610256,_0x492bd1,_0x6c7301);_0x279fea=P,_0x189abb=l.BIRYP(l[o(1291)](_0x4189e1,8),0),_0x28374d+=F}}else{let M={BMUkV:function(F,P,D,B,ie){let le=o;return qIeLXP[le(1677)](F,P,D,B,ie)},GpSxM:function(F,P){let D=o;return qIeLXP[D(485)](F,P)}};_0x519fe6[o(1795)+o(1518)]("upgraden"+o(1350),F=>{let P=o;M[P(1607)](_0x4a4b88,M.GpSxM(_0xee355a,_0x2a5098[P(427)]),F[P(1873)+"on"],F[P(376)+"on"],M.GpSxM(_0x593e46,_0x2c3724[P(445)+P(1502)]))})}}function W(c,r){let o=t,l=ae(c,r[o(780)]),f=c[o(1589)],m=r.bytes;for(let y=0,S=r[o(780)];y<S;y++)f[e[o(1532)](y,l)]=m[y]}function te(c){let r=t;return c[r(1589)][e[r(1090)](Q,c,1)]}function qe(c,r){let o=t,l=e[o(1122)](ae,c,1);c.bytes[l]=r}function pe(c){let r=t,o=0,l=0,f;do f=e.BoSBM(te,c),e[r(1259)](o,32)&&(l|=e[r(695)](e.WWMPA(127,f),o)),o+=7;while(e[r(1778)](128,f));return l}function _e(c,r){let o=t;if(e.PhfTk(o(367),o(367))){for(r>>>=0;e.LBYMi(r,128);)e.KNXsu(qe,c,e[o(1221)](e[o(1351)](127,r),128)),r>>>=7;e[o(790)](qe,c,r)}else _0x18df51[o(1599)]()[o(1327)](()=>{let l=o;this[l(455)+l(1653)]()})}function Ct(c,r){let o=t,l=0,f=0,m=0,y;if(y=e[o(414)](te,c),l=127&y,e[o(1557)](128,y)){if(e[o(540)](o(1510),e[o(1208)]))return new _0x2ba4d6(_0x4d5e29,_0x524e21,_0x1b4c93);y=e.dJNNM(te,c),l|=e.AscvK(127,y)<<7,e[o(1540)](128,y)&&(e[o(1331)]("OFpOp",o(1565))?(y=e.tvPHj(te,c),l|=(127&y)<<14,e.vwNPB(128,y)&&(y=e[o(1231)](te,c),l|=e[o(1559)](127,y)<<21,e.uSqLy(128,y)&&(y=e[o(666)](te,c),f=e[o(684)](127,y),e[o(1778)](128,y)&&(y=e[o(644)](te,c),f|=e[o(600)](e[o(1430)](127,y),7),128&y&&(y=te(c),f|=e.RbVlV(127&y,14),128&y&&(e[o(811)](e[o(1503)],e.HQmTw)?(_0x39429d[o(1199)]["removeCh"+o(1445)](_0x22b26d),_0x5d02e8[o(356)+o(422)]=void 0,_0x300102(_0x2b1bfe&&_0x32cec2.msg||e.sSquq)):(y=e.OHQLY(te,c),f|=e[o(949)](e[o(380)](127,y),21),e[o(1459)](128,y)&&(y=e[o(1242)](te,c),m=127&y,e[o(738)](128,y)&&(y=te(c),m|=(127&y)<<7))))))))):(_0x3f58e8[_0xba4ef5++]=e.KzawE(_0x15161a,12)|224,_0x48c17b[_0x4c2305++]=e.ZInnU(e[o(1520)](_0x239f8a,6)&63,128),_0x10ce28[_0x2cf466++]=e[o(1846)](63&_0x57f42c,128)))}return{low:e.DSiEI(l,e[o(600)](f,28)),high:e[o(937)](e[o(1528)](f,4),e[o(628)](m,24)),unsigned:r}}function bt(c,r){let o=t,l=r[o(1674)]>>>0,f=(e[o(576)](r[o(1674)],28)|e[o(1422)](r.high,4))>>>0,m=e[o(1639)](r[o(1783)],24),y=e[o(797)](0,m)?e.RvAHE(0,f)?l<16384?e[o(1705)](l,128)?1:2:e[o(867)](l,2097152)?3:4:e[o(867)](f,16384)?e[o(803)](f,128)?5:6:e[o(990)](f,2097152)?7:8:e[o(1129)](m,128)?9:10,S=e.GGQTF(ae,c,y),p=c[o(1589)];switch(y){case 10:p[S+9]=e.nIrWA(m,7)&1;case 9:p[e.tgoxp(S,8)]=e[o(1168)](9,y)?e[o(685)](128,m):e[o(1828)](127,m);case 8:p[e[o(954)](S,7)]=y!==8?e[o(1727)](e[o(970)](f,21),128):e[o(1639)](f,21)&127;case 7:p[S+6]=y!==7?f>>>14|128:e.Wlkgj(e[o(576)](f,14),127);case 6:p[e[o(403)](S,5)]=e[o(1535)](6,y)?e.xCNHR(f,7)|128:e[o(1639)](f,7)&127;case 5:p[e[o(1466)](S,4)]=e.ztvCo(5,y)?e.hpIhn(128,f):e[o(1257)](127,f);case 4:p[S+3]=e[o(1108)](4,y)?e[o(1727)](e.XGQRk(l,21),128):e[o(1181)](l>>>21,127);case 3:p[e[o(881)](S,2)]=y!==3?e[o(685)](e.TwtRp(l,14),128):e.mCmjU(e[o(1546)](l,14),127);case 2:p[e[o(1136)](S,1)]=e[o(648)](2,y)?e.xCNHR(l,7)|128:e.VqXGs(e[o(970)](l,7),127);case 1:p[S]=e[o(1026)](1,y)?e[o(889)](128,l):e[o(1459)](127,l)}}function ln(c){return e[t(1137)](E,c)}function Kt(c){return v(c)}let un=65536,di=e[t(490)],ve=e[t(1288)](un,un),Oe=e[t(766)](ve,ve),lr=Oe/2,ze=String[t(1700)+"e"][t(708)+"At"];class ge{constructor(r,o,l){let f=t;this[f(435)]=!0,this[f(1674)]=0|r,this.high=e[f(1846)](0,o),this.unsigned=!!l}static[t(435)](r){let o=t;return r&&e[o(1270)](!0,r[o(435)])}static[t(1509)](r,o,l){return new ge(r,o,l)}static fromBytes(r,o,l){let f=t;if(e.BqMzk(e[f(578)],f(959))){let m=_0x2e77b2[f(1618)+"g"](0,4-_0x3c3316[_0x48cb5f][f(516)]),y=m[f(1760)](_0x4be401[_0x21695d]);_0x5d1165.push(y)}else return l?ge[f(407)+f(810)](r,o):ge[f(407)+"sBE"](r,o)}static[t(407)+t(810)](r,o){let l=t;return new ge(e[l(1237)](e[l(481)](r[0],e[l(788)](r[1],8)),e[l(1723)](r[2],16))|r[3]<<24,e[l(404)](e[l(937)](r[4],e.rJmaR(r[5],8)),e[l(399)](r[6],16))|e.rvYaE(r[7],24),o)}static[t(407)+t(1774)](r,o){let l=t;return new ge(e[l(1846)](e.gHGJS(e[l(1748)](r[4],24),e[l(1723)](r[5],16)),e[l(1734)](r[6],8))|r[7],e.YVcPg(e[l(1348)](e[l(1365)](e[l(1311)](r[0],24),e[l(1723)](r[1],16)),e[l(1753)](r[2],8)),r[3]),o)}static fromHash(r){let o=t;if(e[o(1483)](e[o(565)],e[o(565)]))return e[o(1682)](r,di)?Il:new ge(e[o(1781)](e[o(1467)](e[o(885)](e.QQvqo(ze.call(r,0),e[o(386)](ze[o(768)](r,1),8)),ze[o(768)](r,2)<<16),ze[o(768)](r,3)<<24),0),e[o(1770)](e.qGMdm(e[o(1817)](e[o(1237)](ze[o(768)](r,4),ze[o(768)](r,5)<<8),e[o(399)](ze[o(768)](r,6),16)),e.RbVlV(ze[o(768)](r,7),24)),0),!0);{let l=0,f={};for(let m=0;m<_0x1cfd5e[o(516)];m++)f[_0x5d9fd0[m][o(1690)+"ame"]]=e[o(597)](_0x38fd86,_0x21c553[m][o(1690)+o(1035)]),l+=14+f[_0x47f17b[m][o(1690)+o(1035)]];return[l,f]}}[t(605)](){let r=t;if(r(1260)===e[r(842)])return String[r(1463)+r(1837)](e[r(1430)](255,this[r(1674)]),e[r(1828)](this.low>>>8,255),e[r(1540)](e.XGQRk(this[r(1674)],16),255),e.xCNHR(this[r(1674)],24),e[r(846)](255,this[r(1783)]),e[r(1223)](e[r(1643)](this.high,8),255),e[r(1258)](this[r(1783)]>>>16,255),e.xbmLN(this[r(1783)],24));if(!this[r(887)+r(1385)]()||this["_readyCl"+r(698)])return;this[r(625)+"tManager"]?.[r(1278)+"pointCon"+r(1721)](),this[r(878)+r(1319)]?.[r(1707)+r(1076)](),this[r(1298)]?this[r(688)+r(716)](1001,e[r(1468)],!0):this[r(643)]()}static fromNumber(r,o=!0){let l=t;if(e.BqMzk(e[l(1493)],l(1638)))switch(_0x33ea61){case e.jukEK:case e[l(989)]:return{[l(1007)+_0xedf0b6]:1,"x-tt-env":_0x3352e8};default:return{}}else{if(e[l(1266)](isNaN,r))return o?mg:Il;if(o){if(e[l(1578)](r,Oe))return _g}else{if(e.FShvB(r,-lr))return yg;if(e.MKySh(e[l(725)](r,1),lr))return wg}return ge[l(1509)](e[l(885)](r%ve,0),e[l(1130)](e.obhAx(r,ve),0),o)}}toNumber(){let r=t;return e.RvAHE(r(1233),e[r(489)])?this[r(948)]?e[r(1679)](e.YruIp(e[r(321)](this.high,0),ve),this[r(1674)]>>>0):e[r(1609)](this.high*ve,e[r(1799)](this.low,0)):_0x46ad91.readUInt8?{value:_0x1534b0[r(1170)+"8"](_0x1360c4),offset:e.KuAta(_0x4c5a7d,1)}:{value:255&_0xa28302[_0x365019],offset:_0x3aeb7b+1}}isZero(){let r=t;return e.EuGFA(0,this.high)&&e[r(1761)](0,this[r(1674)])}add(r){let o=t;ge[o(435)](r)||(r=ge[o(613)+"er"](r));let l=e[o(674)](this[o(1783)],16),f=e[o(713)](65535,this[o(1783)]),m=e[o(1781)](this[o(1674)],16),y=e.XRuxn(65535,this[o(1674)]),S=e[o(707)](r[o(1783)],16),p=65535&r[o(1783)],R=e[o(1770)](r.low,16),M=e[o(504)](65535,r.low),F=0,P=0,D=0,B=0;return B+=e[o(1595)](y,M),D+=e[o(776)](B,16),B&=65535,D+=e[o(826)](m,R),P+=e.JIorg(D,16),D&=65535,P+=e[o(1211)](f,p),F+=e[o(707)](P,16),P&=65535,F+=e[o(1511)](l,S),F&=65535,ge[o(1509)](e[o(1467)](e[o(592)](D,16),B),e[o(1337)](F<<16,P),this[o(948)])}[t(977)](r){let o=t;if(e[o(781)]===e[o(781)])return ge.isLong(r)||(r=ge[o(613)+"er"](r)),e[o(1168)](this.unsigned,r[o(948)])&&e[o(797)](e[o(1546)](this.high,31),1)&&e[o(1568)](r[o(1783)]>>>31,1)?!1:e[o(968)](this[o(1783)],r[o(1783)])&&e[o(463)](this[o(1674)],r[o(1674)]);if(e[o(1884)](e[o(910)],typeof _0x13ba62)){let l=new _0x2acf17(e.YRmPw(_0x16f7c8,_0x7ca415));return e[o(1664)](_0x2d3500,_0x4ad057,l,0),l}return _0x4899d8 instanceof _0x406bff?new _0x3c6dfb(_0x20152d):new _0x378690(_0xb57a65[o(1524)],_0x524515[o(1020)+"et"],_0x48875f[o(1185)+"th"])}[t(588)](){let r=t;return e[r(1691)](-1,this[r(1674)])&&this[r(1783)]===-1?ge[r(1509)](0,0,this[r(948)]):e[r(699)](-1,this[r(1674)])?ge[r(1509)](0,e[r(798)](this.high,1),this[r(948)]):ge[r(1509)](e.pXcrs(this[r(1674)],1),this.high,this[r(948)])}[t(888)](r){let o=t;return r?this[o(839)+"E"]():this[o(998)+"E"]()}[t(839)+"E"](){let r=t,o=this[r(1783)],l=this.low;return[e[r(1451)](255,l),e[r(1728)](e[r(433)](l,8),255),e[r(1386)](l,16)&255,e[r(459)](l,24),e[r(936)](255,o),e.twDDt(o>>>8,255),e[r(1527)](e[r(1388)](o,16),255),e[r(1579)](o,24)]}[t(998)+"E"](){let r=t,o=this[r(1783)],l=this[r(1674)];return[e[r(1051)](o,24),e[r(1488)](e[r(409)](o,16),255),e[r(1394)](o,8)&255,255&o,e[r(325)](l,24),e.WWMPA(e[r(1473)](l,16),255),e[r(1207)](e[r(979)](l,8),255),255&l]}}let Il=new ge(0,0,!1),mg=new ge(0,0,!0),wg=ge.fromBits(-1,2147483647,!1),_g=ge[t(1509)](-1,-1,!0),yg=ge[t(1509)](0,-2147483648,!1);var fn=(function(c){let r=t,o=e[r(1384)][r(1604)]("|"),l=0;for(;;){switch(o[l++]){case"0":c[c[e[r(1285)]]=5002]=e.bElZv;continue;case"1":c[c.NATIVE_ERROR=5001]=r(1160)+"RROR";continue;case"2":c[c[e.KwLNw]=5003]="MAX_RETRIES_ERROR";continue;case"3":return c;case"4":c[c[r(458)+"OR"]=5005]="OPEN_ERROR";continue;case"5":c[c[r(1695)+r(1829)]=5004]=e.NBYli;continue}break}})({});class ur{constructor(r){let o=t;this.type=r,this[o(746)]=null}}class Al extends ur{constructor(r,o){let l=t;super(r),this[l(1747)]=o&&o[l(1747)]||null}}class kl extends ur{constructor(r,o){let l=t,f={rKjAG:function(m,y){return e[G(1453)](m,y)},BtUaV:function(m,y){return e[G(1578)](m,y)},PJAND:function(m,y){return e[G(1259)](m,y)},vIAuG:function(m,y){return e.RbVlV(m,y)},XxfYn:function(m,y){return e.ZvZbH(m,y)},tMDLX:function(m,y){return e[G(787)](m,y)},kTJof:function(m,y){return e[G(1797)](m,y)},UGGqT:function(m,y){return m|y},FTTsv:function(m,y){return e[G(1401)](m,y)},mKMzG:function(m,y){return e[G(956)](m,y)},ywAeJ:function(m,y){return e[G(571)](m,y)},QoKVo:function(m,y){return e[G(1149)](m,y)}};if(e[l(717)](l(1151),e[l(1689)])){let m=("0|1|2|5|"+l(1294))[l(1604)]("|"),y=0;for(;;){switch(m[y++]){case"0":super(r);continue;case"1":this[l(371)]=o&&o[l(371)]||null;continue;case"2":this[l(1203)]=o&&o[l(1203)]||0;continue;case"3":this[l(406)]=o&&o[l(406)]||0;continue;case"4":this[l(1747)]=o&&o[l(1747)]||"";continue;case"5":this[l(1382)]=o&&o[l(1382)]||"";continue;case"6":this[l(1177)]=o&&o[l(1177)]||5001;continue}break}}else{let m=_0x9288ff[_0x5d4620++];if(f[l(806)](m,127))_0x5a3eaf+=_0x5cd70b[l(1463)+l(1837)](m);else if(f[l(1023)](m,192)&&f[l(732)](m,224))_0x287d9e+=_0x49085c[l(1463)+"Code"](f.vIAuG(f[l(1112)](31,m),6)|f[l(1112)](63,_0x3a7af3[_0x5bda16++]));else if(f[l(1e3)](m,224)&&f[l(732)](m,240))_0x127daf+=_0x32045c["fromChar"+l(1837)](f[l(1021)](f[l(1544)](f[l(464)](f[l(609)](15,m),12),f[l(1112)](63,_0x1ef218[_0x9aee16++])<<6),f[l(1112)](63,_0x2beaae[_0x39b1c0++])));else if(f[l(1e3)](m,240)){let y=f[l(915)](f.UGGqT(f[l(1544)](f[l(1544)](f[l(1112)](7,m)<<18,f.vIAuG(f[l(609)](63,_0xf1a380[_0xc148a7++]),12)),f.vIAuG(f[l(609)](63,_0x3f8c0b[_0x5df1fc++]),6)),f[l(609)](63,_0x434a69[_0x53a5de++])),65536);_0x24b7f2+=_0x4c859b[l(1463)+l(1837)](f[l(616)](55296,f[l(1655)](y,10))),_0x310807+=_0x29ae68[l(1463)+l(1837)](f.ywAeJ(56320,1023&y))}}}}class Tl extends ur{constructor(r,o){let l=t;super(r),this[l(1177)]=o&&o[l(1177)]||0,this[l(1209)]=o&&o[l(1209)]||"",this[l(737)]=o&&o[l(737)]||!1,this[l(1614)+l(575)]=o&&o[l(1614)+l(575)]||!1}}class Pl extends ur{constructor(r,o){let l=t;super(r),this[l(467)]=o&&o[l(467)]||null}}class Dl extends Pl{constructor(r,o){let l=t;super(r),this[l(467)]=o&&o[l(467)]||null,this[l(1747)]=o&&o.message||null}}class Cl extends ur{constructor(r,o){let l=t;super(r),this[l(467)]=o&&o.data||null}}function ht(c,{message:r,code:o,error:l}){return new kl(c,{message:r,code:o,error:l})}function Et(c,{code:r,reason:o,wasClean:l,willReconnect:f}){let m=t;if(e[m(1454)](m(992),"oThoS"))_0x1a92d7.body["appendCh"+m(1445)](_0x1ab768);else return new Tl(c,{code:r,reason:o,wasClean:l,willReconnect:f})}function Rl(c,{data:r,message:o}){let l=t;return l(1737)!==l(1737)?e[l(1171)](0,this[l(1783)])&&e.PXiyF(0,this[l(1674)]):new Dl(c,{data:r,message:o})}function Ol(c,{data:r}){let o=t;if(e.HgFla("GKdUM",o(1415))){if(e[o(1556)](_0x3912e4,-_0xf98eaf))return _0x1d2410;if(e[o(1578)](e[o(1609)](_0x1cb09f,1),_0x1ac2cf))return _0x101e13}else return new Cl(c,{data:r})}function Oa(c,{message:r}){return new Al(c,{message:r})}class Ll{constructor(r,o){let l=t;this[l(1598)+"s"]=r,this[l(1276)+"es"]=o,this[l(641)+l(363)]=0,this[l(1754)+l(1667)+"riesCount"]=0}[t(1278)+t(1590)+"fig"](){let r=t;if(e[r(1887)](e[r(1500)],e[r(391)]))for(var o in _0x45b963)_0x119365(_0x1fa5f0,o,{get:_0x38a905[o],enumerable:!0});else this["currentI"+r(363)]=0,this[r(1754)+r(1667)+r(1363)+"t"]=0}[t(1826)+"es"](){let r=t;if(e[r(699)](e[r(689)],e[r(1777)]))return new _0x5186d5(_0x440af0,{message:_0x3b1729});this[r(1754)+r(1667)+"riesCount"]=0}["getCurre"+t(334)+"nt"](){let r=t;return e.gMgiB(e.MeTTY,"lQUUj")?(_0x3b0915[r(828)](r(1569),_0x39587b,_0x3b2872,_0xeec4c0),this._qosDB[r(651)]({cursor_name:_0x432fa9,cursor:_0x1391c6,service:_0x11bd15})):this.endpoints[this[r(641)+r(363)]]}[t(1274)+t(334)+t(1724)+t(1347)](){let r=t;return this[r(1754)+r(1667)+r(1363)+"t"]}[t(1080)+t(791)+"es"](){let r=t;return!!(e.wOFjD(this[r(641)+r(363)],this[r(1598)+"s"][r(516)])||e[r(558)](this[r(641)+r(363)],e[r(520)](this[r(1598)+"s"][r(516)],1))&&e[r(1171)](this[r(1754)+"ndpointT"+r(1363)+"t"],this[r(1276)+"es"]))}["checkCur"+t(505)+t(1587)+t(1432)+t(1139)](){let r=t;return e[r(1889)](this[r(641)+"ndex"],this[r(1598)+"s"][r(516)])?!0:e[r(1306)](this[r(1754)+r(1667)+r(1363)+"t"],this.maxRetries)}[t(621)+t(958)+t(777)+t(1801)+t(1868)](){let r=t,o={CTVcv:function(l,f){return e[G(672)](l,f)}};if(e[r(1691)](e[r(446)],"RVPNz"))_0x2a6e62=o.CTVcv(_0x5a5799,_0x5dc165),_0x5bab02=0;else return this[r(1754)+r(1667)+r(1363)+"t"]=1,this[r(641)+r(363)]++,this[r(1598)+"s"][this[r(641)+r(363)]]}[t(1274)+t(334)+t(1486)+t(1550)](){let r=t;return this[r(1754)+r(1667)+r(1363)+"t"]++,this[r(1274)+r(334)+"nt"]()}}let fr=(e[t(1464)]!=typeof globalThis&&e[t(1538)](e.PuqTC,globalThis["construc"+t(330)][t(473)])||e[t(634)](e[t(1464)],typeof window)&&e[t(1210)](t(668),window["construc"+t(330)].name))&&e[t(1099)](e[t(1464)],typeof document),Mn=e[t(1605)](e[t(1464)],typeof globalThis)&&(e[t(969)](e[t(1744)],globalThis[t(1686)+t(330)][t(473)])||e.JsEMd(e[t(1647)],globalThis[t(1686)+t(330)].name))&&e.xykSG(e[t(1464)],typeof tt),li=(e[t(735)](e[t(1464)],typeof globalThis)&&e[t(1134)](e[t(1744)],globalThis["construc"+t(330)].name)||e.CKdKW==typeof globalThis||e[t(650)](e[t(1464)],typeof globalThis)&&!!globalThis["WeixinJS"+t(1115)])&&e[t(733)]("undefined",typeof wx),ui=e[t(1592)](e[t(1464)],typeof globalThis)&&(e[t(443)](e[t(1647)],globalThis[t(1686)+t(330)][t(473)])||e[t(646)](e.ciJsH,globalThis[t(1686)+t(330)][t(473)])||e.GcMyO(e[t(1219)],globalThis[t(1686)+t(330)].name))&&typeof self<"u",bg=e.cOCIz(e.CKdKW,typeof globalThis)&&e[t(412)](e.hqgGc,globalThis[t(1686)+"tor"].name)&&e[t(1464)]!=typeof global&&e.XoAFo(t(1871),global[t(1686)+"tor"][t(473)])&&e.cOCIz(e[t(1464)],typeof process)&&!!process[t(1794)];class La{constructor(){this._listeners={}}emit(r,...o){let l=t,f=this[l(1780)+"rs"][r];if(f)f[l(350)]()[l(638)](m=>m.fn[l(1059)](m[l(818)],o));else if(e.PhfTk(e[l(1567)],r)&&!this.onerror){let m=o[l(516)]&&o[0];if(e[l(1694)](m,Error))throw m;let y=new Error(e[l(975)](l(1010)+l(723),m?e.YRLwj(e.WmDGY(" (",m[l(1747)]),")"):""));throw y[l(906)]=m,m}return this}off(r,o){let l=t;if(e.EuGFA(void 0,r))this._listeners={};else if(e[l(558)](void 0,o))this[l(1780)+"rs"][r]=null;else{let f=this[l(1780)+"rs"][r];if(f)for(let m=0;e[l(1738)](m,f[l(516)]);)e[l(1483)](f[m].fn,o)?f.splice(m,1):++m}return this}on(r,o,l){let f=t;return(this._listeners[r]||(this[f(1780)+"rs"][r]=[]))[f(1302)]({fn:o,ctx:l||this}),this}}class Eg extends La{[t(1183)+t(1316)+t(567)](r){let o=t;return r.errMsg||r[o(337)]?(o(1516)+" "+(r[o(1156)]||"")+o(1014)+(r[o(337)]||""))[o(1417)]():JSON[o(981)+"y"](r)}constructor(r,o,l){let f=t;super(),this[f(727)]=null,li&&wx[f(918)+f(890)]&&(this._socket=wx[f(918)+f(890)]({url:r,protocols:o,header:l,fail:this["_createSocketFai"+f(1343)].bind(this),success:this[f(848)+f(1583)+f(1628)+f(1128)][f(1359)](this)})),Mn&&tt[f(918)+"ocket"]&&(this._socket=tt[f(918)+f(890)]({url:r,protocols:o,header:l,fail:this[f(848)+f(952)+f(1343)][f(1359)](this),success:this["_createS"+f(1583)+f(1628)+f(1128)][f(1359)](this)}))}["_createS"+t(1583)+t(1628)+"ler"](){let r=t;if(e.dLXnv!==e.EDipc)Promise[r(1599)]()[r(1327)](()=>{let o=r;this[o(455)+o(1653)]()});else{let o=_0xc3880d[r(539)+"tabase"](_0x426cda);return _0x12dc10&&o[r(1795)+r(1518)](qIeLXP[r(514)],()=>_0x3c887d()),qIeLXP[r(1563)](_0x12edb7,o)[r(1327)](()=>{})}}[t(848)+t(952)+"lHandler"](r){let o=t,l={cjrFC:function(f,m,y){return e[G(1859)](f,m,y)},aVIBR:e.VDLvX,vrYcR:"close"};e[o(385)](e[o(1441)],e.JcNrf)?Promise[o(1599)]()[o(1327)](()=>{let f=o,m=l[f(1142)](ht,l.aVIBR,{message:this[f(1183)+"rrorMessage"](r)});this[f(1387)](f(371),m);let y=Et(f(760),{reason:this[f(1183)+f(1316)+f(567)](r)});this[f(1387)](l[f(1089)],y)}):this[o(1387)](e[o(1029)],e[o(669)](_0x150f81,e[o(1029)],{..._0x2ae205,data:_0x42e9bc[o(1156)]||""}))}[t(455)+t(1653)](){let r=t,o={Ckbdv:"message",wFUab:function(l,f,m){return e.HCAfK(l,f,m)},rBMez:r(371),GbUiN:function(l,f,m){return e.rIPyc(l,f,m)}};this[r(727)][r(1756)](l=>{let f=r;this[f(1387)](e[f(1029)],e[f(1338)](Ol,e[f(1029)],{...l,data:l[f(1156)]||""}))}),this._socket[r(984)](l=>{let f=r;this[f(1387)](e[f(1284)],Et(e[f(1284)],{...l}))}),this._socket[r(1767)+"e"](l=>{let f=r;this[f(1387)](o[f(1067)],o[f(1235)](Rl,f(1747),{...l}))}),this[r(727)][r(854)](l=>{let f=r;this[f(1387)](o[f(893)],o[f(1680)](ht,o.rBMez,{...l,message:l[f(1156)]||""}))})}[t(764)](r){let o=t,l={jGAIr:e[o(1029)]};if(e[o(1134)](e[o(731)],e[o(731)]))if(r instanceof Uint8Array){let f=r[o(1524)][o(350)](r[o(1020)+"et"],e.qBtOG(r.byteLength,r[o(1020)+"et"]));this[o(727)]&&this[o(727)][o(764)]({data:f,fail:m=>{let y=o;this.emit(e[y(1567)],e[y(377)](ht,y(371),{message:this["_formatE"+y(1316)+y(567)](m)}))}})}else this[o(727)]&&this[o(727)][o(764)]({data:r,fail:f=>{let m=o;e.gMgiB(e[m(353)],e[m(728)])?(this[m(1387)](l[m(1222)],_0x25ebb9),this[m(1798)]&&this[m(1798)](_0x432847)):this.emit(e[m(1567)],e[m(1623)](ht,e.VDLvX,{message:this["_formatErrorMess"+m(567)](f)}))}});else{let f=_0x5e7864.split(/\./).map(S=>_0x557060(S)),m=[];return m[0]=_0x1287e5(e[o(1511)](f[0],f[1])),m[1]=e[o(1409)](_0x216bae,e[o(1136)](f[2],f[3])),[e[o(991)],o(341),e.PISPQ,e[o(991)],e[o(991)],e[o(1104)],m[0],m[1]][o(1324)]("")}}close(r,o){let l=t;this[l(727)]&&this[l(727)][l(760)]({code:r,reason:o})}["addEvent"+t(1518)](r,o){let l=t;if(e[l(1168)](e[l(982)],e.jQRab))this.on(r,o);else return this[l(727)][l(1165)+"ns"]}[t(1248)+t(943)+t(1390)](r,o){this.off(r,o)}get[t(449)+"te"](){return this[t(727)].readyState}get binaryType(){let r=t;return this[r(727)][r(1212)+"pe"]}set[t(1212)+"pe"](r){}get[t(1193)](){let r=t;return this._socket[r(1193)]}get[t(508)](){let r=t;return this[r(727)][r(508)]}get extensions(){let r=t;return this[r(727)][r(1165)+"ns"]}get["buffered"+t(1715)](){return 0}}function vg(c,r){let o=t;if(r)return new r(c[o(1193)],c[o(508)]);if(li||Mn)return new Eg(c[o(1193)],c.protocol,c[o(602)]);if(e.dLFVz(fr,ui)&&e[o(1464)]!=typeof WebSocket&&WebSocket)return new WebSocket(c.url,c[o(508)+"s"])}function Sg(c){let r=t;return!!(c||li&&wx[r(918)+"ocket"]||Mn&&tt[r(918)+r(890)]||e[r(1669)](fr,ui)&&e[r(1529)](e.CKdKW,typeof WebSocket)&&WebSocket)}function Nl(c,r,o){let l=t,f=-1;async function m(y){let S=G;return e[S(662)](y,f)?Promise[S(1858)](new Error("next() called mu"+S(832)+S(1069)+"process")):(f=y,y===o[S(516)]?Promise[S(1599)]():o[y][S(1359)](c)(r,m[S(1359)](null,e.cPLHY(y,1))))}e[l(485)](m,0)}function Ml(c){let r=t,o={KRHQT:function(l,f){return e[G(590)](l,f)},BLZqv:function(l,f){return e.uSqLy(l,f)},SABMC:function(l,f){return e[G(424)](l,f)},BSnoR:function(l,f){return l&f},IoHac:function(l,f){return e[G(321)](l,f)},DnmxP:function(l,f){return e[G(1597)](l,f)},VrkvC:function(l,f){return l&f}};if(e[r(1551)](e[r(1505)],e.EoQkd)){let l=this[r(1783)],f=this[r(1674)];return[wFVrdI[r(1856)](l,24),wFVrdI[r(1549)](wFVrdI[r(1428)](l,16),255),wFVrdI[r(1616)](wFVrdI[r(1856)](l,8),255),wFVrdI.BLZqv(255,l),wFVrdI[r(515)](f,24),wFVrdI.DnmxP(wFVrdI[r(1856)](f,16),255),wFVrdI[r(515)](f,8)&255,wFVrdI[r(1081)](255,f)]}else{let l=0,f=0;for(let m=0;e[r(997)](m,c.length);++m)f=c[r(708)+"At"](m),e[r(1032)](f,128)?l+=1:f<2048?l+=2:e[r(642)](e.mCmjU(64512,f),55296)&&e.TeCtV(e[r(1828)](64512,c[r(708)+"At"](e[r(1102)](m,1))),56320)?(++m,l+=4):l+=3;return l}}function Bl(c,r,o){let l=t,f={pZNgQ:function(m,y){return e[G(647)](m,y)},vSWph:e[l(1660)],WHoAy:e[l(757)]};if(e[l(385)](l(579),e.nWFhy))f[l(1864)](_0x1d0977,"success"),this.off(f.vSWph,_0x5aeaba),this.off(f[l(1406)],_0x3c187a);else{if(e[l(1280)](o-r,1))return"";let m="";for(let y=r;y<o;){let S=c[y++];if(e.BAtUi(S,127))m+=String[l(1463)+l(1837)](S);else if(e[l(787)](S,192)&&S<224)m+=String[l(1463)+"Code"](e.yvTSZ(e.ZxiNF(e[l(1606)](31,S),6),e[l(1828)](63,c[y++])));else if(S>=224&&S<240)m+=String[l(1463)+l(1837)](e[l(765)](e[l(788)](15&S,12),e.rafhK(63,c[y++])<<6)|e[l(1401)](63,c[y++]));else if(S>=240){let p=e.saiZZ(e.dtSTb(e[l(1106)](e[l(1675)](e[l(845)](e[l(931)](7,S),18),e[l(600)](e[l(713)](63,c[y++]),12)),e[l(600)](e[l(380)](63,c[y++]),6)),63&c[y++]),65536);m+=String["fromChar"+l(1837)](e[l(1725)](55296,e[l(1149)](p,10))),m+=String[l(1463)+l(1837)](e[l(1615)](56320,e[l(1459)](1023,p)))}}return m}}function Na(c,r,o){let l=t;if(e[l(1641)](e[l(1358)],l(397))){let f=this._messageQueue[l(693)]((m,y)=>(m+=y&&y.byteLength||0,m),0);return e[l(536)](f,this[l(1298)]?this[l(1298)][l(1437)+l(1715)]:0)}else{let f=o,m,y;for(let S=0;e.zylue(S,c[l(516)]);++S)if(m=c.charCodeAt(S),e.kblWR(m,128))r[o++]=m;else if(e[l(530)](m,2048))r[o++]=e[l(1675)](e.OQgPl(m,6),192),r[o++]=e[l(1018)](63,m)|128;else if(e[l(1828)](64512,m)===55296&&(64512&(y=c[l(708)+"At"](e[l(1511)](S,1))))===56320)if(e[l(968)](e[l(987)],e[l(987)])){let p=e[l(552)][l(1604)]("|"),R=0;for(;;){switch(p[R++]){case"0":m=e[l(1102)](e[l(920)](65536,e.RbVlV(1023&m,10)),e[l(1430)](1023,y));continue;case"1":r[o++]=e[l(404)](e[l(1075)](e.OQgPl(m,12),63),128);continue;case"2":++S;continue;case"3":r[o++]=e[l(1047)](e[l(1065)](m,6),63)|128;continue;case"4":r[o++]=e.DVMHE(e[l(923)](63,m),128);continue;case"5":r[o++]=e[l(1508)](e.HVwaH(m,18),240);continue}break}}else _0x5c506f.o=(p,R)=>_0x22f6d2[l(1700)+"e"][l(1443)+"operty"][l(768)](p,R);else r[o++]=e.xrWSk(m>>12,224),r[o++]=e[l(889)](e.FYVLv(e[l(607)](m,6),63),128),r[o++]=e[l(348)](63,m)|128;return o-f}}async function Fl(c){let r=t;if(e[r(976)](e[r(910)],typeof c)){let o=new Uint8Array(Ml(c));return Na(c,o,0),o}return e.scwAs(c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[r(1524)],c[r(1020)+"et"],c.byteLength)}function Ig(c){let r=t;try{return e[r(545)](r(366),e.KDZqH)?e[r(1529)](e[r(910)],typeof c)&&(e.scwAs(c,ArrayBuffer)||c.buffer&&e[r(1054)](c[r(1524)],ArrayBuffer))||e[r(1099)](e.QsDQp,typeof c)?"":(JSON[r(1192)](c),e[r(1547)]):this._qosDB?.del(_0x2a46dc)}catch{return e[r(843)](e[r(910)],typeof c)?r(631)+r(1870)+r(1245):""}}let Ag=(c,r)=>{let o=t;switch(c){case e[o(440)]:case e[o(989)]:return{[o(1007)+c]:1,"x-tt-env":r};default:return{}}};class kg{constructor(r){let o=t;this[o(1332)+o(1347)]=r,this[o(1141)]=0}[t(1763)](){this.count++}[t(1080)+t(1566)+"nt"](){let r=t;return e[r(1145)](this[r(1141)],this[r(1332)+r(1347)])}["resetCou"+t(1076)](r=0){let o=t;this[o(1332)+o(1347)]=r,this[o(1141)]=0}}async function Tg(c){let r=t,o={KWQTN:function(l,f){return e.cWQrN(l,f)},uyCey:function(l,f){return e[G(389)](l,f)},eOsPn:e[r(1425)],aTccL:function(l,f){return e[r(1842)](l,f)},DmCxq:e[r(756)],NDVes:e[r(1525)],uIQQS:function(l,f){return e[r(1704)](l,f)},WGQZJ:function(l,f){return e[r(672)](l,f)}};return new Promise(l=>{let f=r,m={ZLJfV:function(y,S){return o[G(1374)](y,S)},fkXGz:function(y,S,p,R){return y(S,p,R)}};if(o[f(939)](f(917),o.eOsPn)){if(!fr)return o[f(1447)](l,o[f(339)]);try{let y=document.createElement(f(1835));window[f(356)+"JSONP"]=S=>{let p=f;document[p(1199)][p(1484)+"ild"](y),window[p(356)+"JSONP"]=void 0,m.ZLJfV(l,S&&S[p(1154)]||"unknown "+p(1209))},y[f(1494)]=o[f(1709)],y.src=o[f(556)](c[f(1650)](/^ws/,f(1120)),f(461)+f(1475)+"tierJSONP");try{document[f(1199)][f(1036)+f(1445)](y)}catch{document[f(1199)][f(1484)+f(1445)](y)}}catch{window[f(356)+f(422)]=void 0,o.WGQZJ(l,f(549)+"reason")}}else m[f(1421)](_0x31fb64,this,_0x1b482e,[_0x1dde4e,_0x352f12,_0x4ea1a6,_0x523c2c,_0x508698,_0x86001a])})}function hn(c,r,o){let l=t;return!!c?.[l(710)](f=>f.key===r&&f[l(1339)]===o)}function hr(c,r){let o=t;return c?.[o(710)](l=>l[o(1205)]===r)?.[o(1339)]}let Ma=null;async function Pg(){let c=t;return Ma||(Ma=Promise.resolve()[c(1327)](qt[c(1359)](qt,e.MJShp))),Ma}class Dg extends La{constructor(r,o){let l=t;super(),this[l(1164)]=r,this[l(1429)]=o,this._qosDB=void 0,this._initPromise=null}async[t(1543)](){await this[t(655)]()}async[t(655)](){let r=t,o={sZrTw:function(l){return l()}};if(e[r(1026)](e[r(1423)],r(1411)))_0x16f433[r(1302)](_0xb0b185);else{if(this[r(921)])return;if(this[r(593)+r(1584)])return this[r(593)+r(1584)];try{let l=this[r(1164)],f=this[r(1429)];this[r(593)+"mise"]=(async()=>{let m=r,{openDB:y}=await o[m(1074)](Pg);this[m(921)]=await y(m(356)+"_"+l,1,{upgrade(S){S["createOb"+m(950)+"e"](l,{keyPath:f})}})})(),await this["_initPro"+r(1584)]}catch(l){console[r(828)](l)}finally{this["_initPro"+r(1584)]=null}}}async[t(1478)](r){let o=t,l={NljxL:e[o(1791)]};try{return await this[o(655)](),this[o(921)]?.[o(1478)](this._dbName,r)}catch(f){e[o(696)]===e[o(696)]?console[o(828)](f):(_0x1c0c41=l[o(1255)],_0x13fe08=_0x10e964[o(1650)](/(^http)((?:[s]*:\/\/))/,""),_0x1e9997=/(^ws)((?:[s]*:\/\/))/[o(1702)](_0x38a0ca)?_0x3a3384:""+_0x5325ac+_0x549903)}}async[t(651)](r,o){let l=t;return await this[l(655)](),this[l(921)]?.[l(930)](this[l(1164)],r)}async del(r){let o=t;try{return await this[o(655)](),this[o(921)]?.[o(1662)](this[o(1164)],r)}catch(l){console.log(l)}}async[t(1044)](){let r=t;try{return await this._init(),this[r(921)]?.[r(1044)](this._dbName)}catch(o){console[r(828)](o)}}async[t(945)](){let r=t;return await this[r(655)](),this._qosDB?.getAllKeys(this[r(1164)])}async[t(1095)](){let r=t;return await this[r(655)](),this[r(921)]?.[r(1095)](this[r(1164)])}async[t(1146)](){let r=t;try{this[r(921)]?.[r(760)](),this[r(921)]=void 0}catch(o){console.log(o)}}get[t(1888)](){let r=t;try{return!!this._qosDB}catch(o){return console[r(828)](o),!1}}}class Cg{constructor(r,o){let l=t;this._DBName=r,this[l(1457)]=o,this._qosDB=localStorage}async[t(1543)](){}get[t(1625)](){return"frontier_"+this[t(1410)]}async[t(1478)](r){let o=t,l=this._qosDB.getItem(this[o(1625)]);return JSON[o(1192)](e.dLFVz(l,"{}"))[r]}async[t(651)](r,o){let l=t,f=this[l(921)][l(533)](this[l(1625)]),m=JSON[l(1192)](e[l(789)](f,"{}"));return m[o||r[this[l(1457)]]]=r,this[l(921)][l(752)](this[l(1625)],JSON[l(981)+"y"](m)),o||r[this[l(1457)]]}async[t(1685)](r){let o=t,l=this._qosDB[o(533)](this[o(1625)]),f=JSON.parse(e[o(1669)](l,"{}"));return f[r]=void 0,this[o(921)][o(752)](this[o(1625)],JSON.stringify(f))}async[t(1044)](){let r=t;return this._qosDB[r(1044)]()}async[t(945)](){let r=t,o=this._qosDB[r(533)](this._prefix),l=JSON[r(1192)](e[r(462)](o,"{}"));return Object.keys(l)}async[t(1095)](){let r=t,o=this[r(921)].getItem(this[r(1625)]),l=JSON.parse(e[r(1659)](o,"{}"));return Object[r(1398)](l)}[t(1146)](){return Promise[t(1599)]()}get[t(1888)](){let r=t,o={VUURA:function(l,f){return l(f)},gYpDO:function(l,f){return e[G(644)](l,f)}};return e[r(1802)]===e[r(1802)]?!!this._qosDB:njuEBf[r(868)](_0x2d6e2c,_0x5abd15.apply(njuEBf[r(829)](_0x3e970c,this),_0x59267e))}}class Rg{constructor(r,o){let l=t;this._DBName=r,this[l(1457)]=o,this._qosDB=Mn?tt:li?wx:null}async[t(1543)](){}get[t(1625)](){return"frontier_"+this[t(1410)]}async[t(1478)](r){let o=t;if(e[o(734)]!==o(1056)){let l=this._qosDB["getStora"+o(1874)](this[o(1625)]);return JSON[o(1192)](l||"{}")[r]}else _0x1544ba[o(651)](_0x2aff15,_0x4a14d6),_0xf5c6e3[o(651)](_0x1f9b35,_0xc49df6)}async set(r,o){let l=t,f=this[l(921)][l(1820)+"geSync"](this._prefix),m=JSON[l(1192)](e[l(1407)](f,"{}"));return m[o||r[this._pathKey]]=r,this._qosDB[l(749)+"geSync"](this[l(1625)],JSON[l(981)+"y"](m)),o||r[this[l(1457)]]}async[t(1685)](r){let o=t,l=this._qosDB[o(1820)+"geSync"](this[o(1625)]),f=JSON[o(1192)](e[o(462)](l,"{}"));return f[r]=void 0,this[o(921)].setStorageSync(this[o(1625)],JSON[o(981)+"y"](f))}async[t(1044)](){let r=t;return this._qosDB[r(973)+"rageSync"]()}async keys(){let r=t,o=this._qosDB[r(1820)+"geInfoSync"](this[r(1625)]),l=JSON[r(1192)](e.hSvre(o,"{}"));return Object[r(945)](l)}async[t(1095)](){let r=t,o=this[r(921)][r(1820)+r(712)+"nc"](this._prefix),l=JSON[r(1192)](e[r(1692)](o,"{}"));return Object.values(l)}closeDB(){let r=t;if(e[r(594)](e[r(1238)],"nzJcd"))_0x417875&&this[r(1775)+r(1522)]["updateCursorFile"+r(1247)](_0x3ca62e);else return Promise[r(1599)]()}get[t(1888)](){let r=t,o={kiICg:function(l,f){return e.LLTSm(l,f)},ykpSJ:function(l,f){return e[G(748)](l,f)},zGAIK:function(l,f){return l!==f},cCQHa:function(l,f){return e[G(1018)](l,f)},GQvGu:function(l,f){return l|f},pqphw:function(l,f){return e[G(1734)](l,f)}};if(r(1340)!==e.IZEom)_0x1f88eb=_0x22d698[tKmPCK[r(963)](tKmPCK[r(793)](_0x273833,_0x3bb9e1),1)],tKmPCK[r(1008)](tKmPCK[r(1665)](192,_0x220d2d),128)?_0x238363+=_0x39d685:(_0x1ceb67=tKmPCK.GQvGu(tKmPCK[r(686)](tKmPCK[r(1665)](31,_0x4ad1c9),6),63&_0x458831),_0x4f7808<128?_0x36490c+=_0x5a2ad5:(_0x6a82f8+=_0x228698(_0xc1725),_0x3f396e++));else return!!this[r(921)]}}function zl(c,r){let o=t;if(e.CRHek(Mn,Mn))return new Rg(c,r);if(e[o(523)](fr,ui)&&e[o(1605)](o(547)+"d",typeof indexedDB))return new Dg(c,r);if((fr||ui)&&e[o(1811)](e[o(1464)],typeof localStorage))return new Cg(c,r);throw new Error(e[o(324)])}class Og{constructor(){let r=t;this[r(537)+r(584)+"Id"]=null,this[r(537)+"l"]=36e5,this[r(921)]=e[r(577)](zl,e[r(1506)],e.hLXns)}async _intervalFlush(){let r=t;clearInterval(this[r(537)+r(584)+"Id"]),this[r(537)+"lTimeoutId"]=setInterval(()=>{this[r(483)+"ired"]()},this[r(537)+"l"])}async[t(1543)](){await this._qosDB.openDB().then(()=>{let r=G;this[r(537)+r(1252)]()})}async[t(483)+t(1254)](){let r=t,o={SwLeY:function(m,y){return e[G(1641)](m,y)}};(await this[r(921)]?.[r(1095)]()||[]).filter(({timestamp:m})=>m<Date[r(1015)]())[r(638)](m=>{let y=r;if(e.qjtbw==="jOJzM"){let S=_0x58d68f[_0x220060];if(mnHAjq.SwLeY(4,_0x2774f2[_0x1bfc82][y(516)])){let p=_0x4c2a6a[y(1618)+"g"](0,4-_0x242290[_0x5ac9fe][y(516)]),R=p[y(1760)](S);_0x7fc0b0=_0x3bb010[y(1760)](R)}else _0x5e5bfc=_0x426c47.concat(S)}else this[y(921)]?.[y(1685)](m[y(656)+"id"])})}async[t(1685)](r){return this[t(921)]?.del(r)}async[t(651)](r,o){let l=t;return this[l(921)]?.[l(651)]({message_id:r,timestamp:o})}async get(r){let o=t;return this[o(921)]?.[o(1478)](r)}async[t(1146)](){let r=t;clearInterval(this["_interva"+r(584)+"Id"]),await this[r(921)]?.[r(1146)]()}get[t(1888)](){return this._qosDB?.isReady}}function Ba(c){let r=t,o=!!this._options[r(1634)+"S"];if(!o)return{enabled:o,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=hn(c.message[r(602)],e[r(1654)],"2"),f=l&&hn(c[r(1747)].headers,e[r(501)],"1"),m=l&&e.hOgKR(hn,c.message[r(602)],e[r(1342)],"1"),y=m?e[r(496)](hr,c[r(1747)][r(602)],e[r(402)])?.split(",")[r(1353)](Boolean)||[]:[];return{enabled:o,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:m,ackMsgIds:y}}async function Ul(){let c=t;return this[c(342)+"ger"]||(this[c(342)+c(996)]=new Og),this[c(342)+"ger"][c(1888)]||await this[c(342)+"ger"][c(1543)](),this[c(342)+"ger"]}async function Lg(c,r){let o=t,l={xGfDu:e[o(1809)],iRrQQ:e[o(1567)],dAJwd:function(f,m){return e[o(1842)](f,m)},VmgxB:function(f,m){return e[o(1512)](f,m)},OXzCq:function(f){return e[o(1066)](f)},HgGOa:function(f,m){return f(m)}};if(e[o(1836)](e[o(599)],e[o(1326)])){let f=()=>{let S=o;_0xd0344a[S(1248)+S(943)+S(1390)](vPgPGf[S(469)],m),_0x1a4bf8[S(1248)+S(943)+S(1390)](vPgPGf[S(1644)],y)},m=()=>{let S=o;vPgPGf[S(1376)](_0x5651ae,vPgPGf[S(692)](_0xa58874,_0x47a1b4[S(427)])),vPgPGf[S(1111)](f)},y=()=>{let S=o;vPgPGf[S(522)](_0x40ab45,_0x4066c7[S(371)]),vPgPGf[S(1111)](f)};_0x1cfba0[o(1795)+o(1518)]("success",m),_0x4e376f[o(1795)+"Listener"](vPgPGf[o(1644)],y)}else{let{enableAutoAck:f}=this[o(1037)],m=hn(c[o(1747)][o(602)],e[o(1088)],"1"),y=e.JmIfI(hn,c[o(1747)].headers,e.idDfC,"1"),S=Ba[o(768)](this,c);if(e[o(1732)](f,m)){let{SeqID:p,LogID:R,service:M,LogIDNew:F,method:P}=c[o(1747)];this[o(582)]({SeqID:p,LogID:R,LogIDNew:F,service:M,method:P,headers:[{key:e.idDfC,value:"1"},{key:e[o(1300)],value:e.OEuTQ(F,"")},{key:e[o(354)],value:"0"}]})}y&&!S[o(1253)]&&this[o(329)+o(817)+o(1187)](c),e[o(879)](r)}}async function Ng(c,r){let o=t,l={SlxHT:function(f,m,y){return e[G(795)](f,m,y)},FYZME:o(1690)+o(1035)};e.RvAHE(e[o(423)],o(1124))?(this._debug(e[o(1807)],c.message),e[o(1186)](r)):(this[o(1752)+o(759)]=_0xc318bf,this[o(1648)+o(1620)]=_0x26c8e5,this[o(1786)+"Strategy"]=_0x2834b1,this._qosDB=l[o(432)](_0x3a0f7b,this[o(1752)+o(759)],l[o(419)]))}async function Mg(c,r){let o=t,l=e[o(928)](ln,await e[o(960)](Fl,c[o(467)]));try{if(e[o(1694)](l.payload,Uint8Array)){let f=e.FWKti(this[o(1037)][o(1526)+o(395)],Object)?{force:!!this[o(1037)][o(1526)+o(395)][o(901)],encoding:this[o(1037)]["payloadE"+o(395)][o(660)]?this[o(1037)][o(1526)+o(395)][o(660)][o(1650)](/\s/g,"")[o(1714)+"ase"]():""}:{force:!1,encoding:this[o(1037)][o(1526)+"ncoding"]?this[o(1037)].payloadEncoding[o(1650)](/\s/g,"")[o(1714)+o(1523)]():""},m=l[o(1526)+o(395)]?l[o(1526)+"ncoding"].replace(/\s/g,"")[o(1714)+o(1523)]():"",y=this[o(1037)][o(450)+o(1448)]instanceof Object?{force:!!this[o(1037)]["payloadT"+o(1448)][o(901)],type:this[o(1037)][o(450)+o(1448)][o(1494)]?this[o(1037)][o(450)+o(1448)][o(1494)][o(1650)](/\s/g,"")[o(1714)+o(1523)]():""}:{force:!1,type:this[o(1037)][o(450)+o(1448)]?this[o(1037)]["payloadT"+o(1448)][o(1650)](/\s/g,"")["toLowerC"+o(1523)]():""},S=l[o(450)+o(1448)]?l["payloadT"+o(1448)][o(1650)](/\s/g,"")[o(1714)+o(1523)]():"",p=y.force?y.type:S||y[o(1494)],R=f[o(901)]?f[o(660)]:m||f[o(660)],M=["text/pla"+o(1870)+o(1245),e[o(1547)],"applicat"+o(604)+";charset"+o(518),e[o(910)]],F=["none_none",e.ougik];this._options[o(1147)+o(944)+o(1004)+"ad"]&&M[o(1854)](p)&&(!R||F[o(1854)](R))?l[o(971)+o(437)]=e[o(1063)](Bl,l[o(841)],0,l[o(841)][o(1185)+"th"]):l.textPayload=""}else l["textPayl"+o(437)]=""}catch(f){e[o(1334)](e[o(1093)],e.lEbkL)?(this[o(1387)](o(371),_0xa6e256),this[o(770)]&&this[o(770)](_0x31ea5c)):(l[o(971)+o(437)]="",console.log(f))}c[o(1747)]=l,r()}function Bg(c,r,o){let l=t,f=e[l(1669)](o,8192),m=f>>>1,y=null,S=f;return function(p){let R=l;if(p<1||e[R(1637)](p,m))return c(p);e[R(1333)](e[R(1788)](S,p),f)&&(y=c(f),S=0);let M=r[R(768)](y,S,S+=p);return e.WbKIw(7,S)&&(S=e.FHYZT(7|S,1)),M}}let Fg=4294967295;function zg(c,r,o){let l=t;return e[l(597)](RangeError,e[l(920)](e[l(940)](e.bwuCI(e[l(370)](e[l(1127)],c),e.uLTUl),e[l(1477)](r,1))+" > ",o))}function Ug(c,r,o){let l=t;if(e[l(503)](o,Fg))throw new Error(e[l(639)]);let f=3;for(;e.hJTsD(f,0);){let m=255&o;e.CBBlO(za,m,c,e.XVqgy(r,f)),o>>>=8,f--}return e[l(940)](r,4)}function Hg(c,r){let o=t,l=0,f=r,m=e.Qvndw(r,4);for(;f<m;){let{value:y,offset:S}=Fa(c,f);f=S,l=e[o(1386)](l<<8,0),l+=y}return{value:l,offset:m}}function Gg(c,r,o){let l=t,f=e[l(1256)][l(1604)]("|"),m=0;for(;;){switch(f[m++]){case"0":if(!c)return o;continue;case"1":if(e[l(1296)](c[l(516)],40))return e[l(1664)](Na,c,r,o)+o;continue;case"2":if(r[l(819)+"e"])return e[l(1466)](r[l(819)+"e"](c,o),o);continue;case"3":if(r[l(1718)])return e[l(798)](r[l(1718)](c,o),o);continue;case"4":return e[l(1731)](e[l(1814)](Na,c,r,o),o)}break}}function qg(c,r){let o=t,l=new ge(e.uRMrk(e[o(882)](e[o(328)](c[e[o(1595)](r,4)],24)|c[e.EVDWZ(r,5)]<<16,e[o(1586)](c[e[o(408)](r,6)],8)),c[e.pXcrs(r,7)]),e.YGftH(e[o(1110)](e[o(1348)](e[o(1805)](c[e[o(771)](r,0)],24),e[o(1485)](c[e[o(821)](r,1)],16)),e[o(957)](c[e[o(1784)](r,2)],8)),c[e.CYgSO(r,3)]),!0);return r+=8,{value:l,offset:r+8}}function jg(c,r,o){let l=t,f=c[l(1674)],m=c[l(1783)];return r[o]=e[l(1386)](m,24),r[e[l(1880)](o,1)]=e.ZLfbi(m>>>16,255),r[e.mQlxO(o,2)]=e[l(1401)](m>>>8,255),r[e[l(581)](o,3)]=255&m,r[e[l(1466)](o,4)]=f>>>24,r[o+5]=e.hUphP(f,16)&255,r[e[l(1788)](o,6)]=e[l(1272)](e[l(424)](f,8),255),r[e[l(401)](o,7)]=e[l(807)](255,f),o+=8,o}function Fa(c,r){let o=t;return c.readUInt8?{value:c[o(1170)+"8"](r),offset:r+1}:{value:e[o(846)](255,c[r]),offset:e.CVDEX(r,1)}}function za(c,r,o){let l=t;return r[l(543)+"t8"]?r.writeUint8(c,o):r[o]=e[l(554)](255,c),o+1}let Kg=function(c){return new Uint8Array(c)},Wg=e[t(1480)](e[t(1464)],typeof Buffer)?Buffer[t(1696)+t(1431)]:e[t(1859)](Bg,Kg,Uint8Array[t(1700)+"e"][t(1499)]);(()=>{let c=t,r={UcmzN:"10|5|11|"+c(1439)+"7|2|4|0|3",EIdAc:function(l,f){return e.AUsXB(l,f)},ZiQVE:function(l,f,m,y){return e.ebzHn(l,f,m,y)},bkYYP:function(l,f){return e[c(1528)](l,f)},YduRk:function(l,f){return e[c(369)](l,f)},DToJi:function(l,f){return l<<f},EuyOP:function(l,f){return l&f},jzmlO:function(l,f){return e[c(855)](l,f)},utfDg:function(l,f){return l<f},QBzWc:function(l,f){return e[c(1847)](l,f)},AnycH:function(l,f){return e[c(1727)](l,f)},sOQTw:function(l,f){return e[c(1528)](l,f)},wqHcp:function(l,f){return e.UatrQ(l,f)},QYtoB:function(l,f){return e.WROzp(l,f)},gOwcE:function(l,f){return e.YxMWe(l,f)},wpxTd:function(l,f){return e.rJmaR(l,f)},FvNVl:function(l,f){return e[c(1872)](l,f)}},o=4294967295;return function(l,f,m=!0){let y=c,S=r[y(1038)].split("|"),p=0;for(;;){switch(S[p++]){case"0":if(r[y(874)](f+=5,l[y(516)]))throw f=l[y(516)],r[y(1013)](zg,f,10,l[y(516)]);continue;case"1":if(l[f++]<128)return{value:m?o:0|o,offset:f};continue;case"2":o=r[y(546)](r[y(456)](o,r[y(1624)](r[y(767)](15,l[f]),28)),0);continue;case"3":return{value:m?o:0|o,offset:f};case"4":if(l[f++]<128)return{value:m?o:r[y(1161)](0,o),offset:f};continue;case"5":if(r[y(751)](l[f++],128))return{value:m?o:r[y(456)](0,o),offset:f};continue;case"6":if(r[y(1456)](l[f++],128))return{value:m?o:r[y(1161)](0,o),offset:f};continue;case"7":if(r[y(751)](l[f++],128))return{value:m?o:r[y(374)](0,o),offset:f};continue;case"8":o=r.sOQTw(r[y(456)](o,r[y(468)](127&l[f],21)),0);continue;case"9":o=r[y(1469)](r[y(374)](o,r[y(468)](r.EuyOP(127,l[f]),14)),0);continue;case"10":o=r[y(805)](127,l[f])>>>0;continue;case"11":o=r[y(1469)](r.gOwcE(o,r[y(1841)](r[y(1619)](127,l[f]),7)),0);continue}break}}})();let $g=16,Ua=32;function Vg(c){let r=t;if(e[r(1621)]===e[r(1119)])_0x5875a3(_0x58e517,10),_0x34c99b(_0x20cd94,_0x2eac23);else{let o=0,l={};for(let f=0;e.zylue(f,c[r(516)]);f++)l[c[f][r(1690)+r(1035)]]=e[r(559)](Ml,c[f][r(1690)+r(1035)]),o+=e[r(1853)](14,l[c[f][r(1690)+r(1035)]]);return[o,l]}}function Hl(c,r,o){let l=t,f={NeXJT:l(561)+l(861),ZwmHm:function(R,M,F,P){return e[l(1022)](R,M,F,P)},AeSlI:"header",KiJmK:e.SgSCt,NYMQg:e[l(775)]},[m,y]=e[l(1198)](Vg,c),S=Wg(m),p=0;return c.forEach(R=>{let M=l;console[M(828)](f.NeXJT,R,R[M(394)]),p=f[M(736)](za,0,S,p),console[M(828)](f[M(1381)],p),p=f[M(736)](Ug,S,p,R.service||0),console[M(828)](M(394),p),p=f.ZwmHm(za,y[R[M(1690)+M(1035)]],S,p),console[M(828)](M(1537)+M(473),p),p=f.ZwmHm(Gg,R["cursor_n"+M(1035)],S,p),console[M(828)](f[M(844)],p),p=f.ZwmHm(jg,ge[M(613)+"er"](R.cursor||r),S,p),console[M(828)](f[M(1236)],p)}),{frameType:Ua,headers:[{key:e[l(1881)],value:o}],payload:S}}function Zg(c){let r=t,o=0,l=[];for(;e[r(1670)](o,c[r(1185)+"th"]);){let{offset:f}=Fa(c,o);o=f;let m={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=e[r(876)](Hg,c,o);m[r(394)]=y,o=S;let{value:p,offset:R}=e[r(993)](Fa,c,o);o=R,m.cursor_name=Bl(c,o,e[r(608)](o,p)),o+=p;let{value:M,offset:F}=e.DAmhf(qg,c,o);m[r(358)]=M[r(754)](),o=F,l.push(m)}return l}function Jg(){let c=t;return{frameType:Ua,headers:[{key:c(1594)+c(1002),value:e[c(453)]}],payload:void 0}}class Yg{constructor(r,o,l){let f=t;this[f(1752)+f(759)]=r,this[f(1648)+f(1620)]=o,this._messageStrategy=l,this._qosDB=e.CsfUe(zl,this[f(1752)+f(759)],e[f(466)])}async openDB(){let r=t;await this._qosDB[r(1543)]()}async[t(1123)+"rs"](){let r=t;if(!this[r(921)][r(1888)])return;let o=this[r(1786)+r(1012)],l=await this[r(921)][r(1095)]();switch(console[r(828)](e[r(784)],l),o){case e.fWzQj:return l&&l[r(516)]?Hl(l,0,this[r(1648)+r(1620)]):void 0;case e[r(799)]:return;case r(1822):return l&&l[r(516)]?e[r(1664)](Hl,l,0,this[r(1648)+"ileName"]):e[r(1070)](Jg)}}async[t(651)](r,o,l){let f=t;return console[f(828)](e.DPpcw,r,o,l),this[f(921)].set({cursor_name:r,cursor:o,service:l})}async setCursors(r){let o=t;if(e.YfLtP("zZhgU",o(493)))return _0x3d5c31(_0x28300d);{let l=e[o(1163)](Zg,r);for(let f of l)console[o(828)](e.sHlMr,l),await this._qosDB[o(651)](f)}}async[t(1478)](r){let o=t;return(await this[o(921)][o(1478)](r))?.[o(358)]}async[t(1146)](){let r=t;await this[r(921)][r(1146)]()}[t(361)+t(1455)+t(1247)](r){this._cursorFileName=r}get[t(1888)](){let r=t;return this._qosDB[r(1888)]}}let Xg=t(1585)+"qos__";async function Gl(c){let r=t;if(!this[r(1037)][r(1634)+"S"])return null;let{aID:o,fpID:l,messageStrategy:f}=this._options,m=e.BbZuz(c,Xg);try{if(this["_cursorM"+r(1522)])if(e[r(540)](e[r(951)],"GuLDP")){let y=0,S=_0xa4f367,p=_0x24b3d1+4;for(;e.GSrZk(S,p);){let{value:R,offset:M}=e[r(645)](_0x4895af,_0x36ef14,S);S=M,y=e[r(1097)](y,8)>>>0,y+=R}return{value:y,offset:p}}else c&&this[r(1775)+r(1522)]["updateCu"+r(1455)+r(1247)](c);else this[r(1775)+r(1522)]=new Yg(l+"_"+o+"_"+m,m,f);return this[r(1775)+r(1522)].isReady||await this[r(1775)+r(1522)].openDB(),this._cursorManager}catch{return null}}async function Qg(c,r){let o=t,l={AIbMx:function(f,m){return e[G(463)](f,m)},twDPU:e[o(421)]};if(e[o(797)](e[o(431)],e[o(431)])){let f=e[o(1022)](hn,c[o(1747)][o(602)],e[o(1031)],"-1"),m=e[o(465)](hn,c[o(1747)].headers,e.idDfC,"1"),y=hr(c[o(1747)][o(602)],e.yejts),S=e.tvPHj(Number,e.tALez(hr,c[o(1747)][o(602)],"x_fronti"+o(1414)))||0,p=Ba.call(this,c),R=hn(c[o(1747)].headers,e[o(916)],"2"),M=hr(c[o(1747)].headers,e[o(1393)]),F=Number(hr(c.message.headers,o(1631)+o(532)+"ue"));if(p[o(1253)])return e[o(1602)](r);let P=p[o(475)+o(804)]?await Ul[o(768)](this):null;if(c[o(1747)][o(394)]>0&&m&&!f||c[o(1747)][o(394)]>0){if(y&&p[o(475)+o(804)]&&P)return!!!await P[o(1478)](y)&&(this[o(329)+o(955)+o(1283)](c),await P[o(651)](y,e[o(1413)](Date[o(1015)](),S))),e[o(1630)](r);if(R){let D=await Gl[o(768)](this);if(!D)return this[o(329)+o(955)+o(1283)](c),r();let B=await D[o(1478)](M)??-1;if(B<F)if(e[o(1168)](e.QasNm,e.FjyRb))this[o(329)+"hMessage"+o(1283)](c),D[o(651)](M,F,c[o(1747)][o(394)]);else return _0xd6f3c8 instanceof _0x7bc2bb&&(thPLqO[o(441)](_0x59a719,thPLqO[o(1772)])||thPLqO[o(441)](_0x19f9e0,o(635)))?!0:_0x2ccef8 in _0x393373;else throw new Error("recevied"+o(585)+o(1596)+F+(" larger "+o(1125)+o(487)+"r ")+B);return e[o(794)](r)}return this[o(329)+o(955)+o(1283)](c),e.Avavx(r)}}else return this[o(727)][o(449)+"te"]}async function em(c,r){let o=t,l={nRPPe:function(f,m){return f||m}};if(e[o(1454)](e[o(1005)],e[o(1816)])){let f=Ba.call(this,c);if(!f[o(475)+"sage"])return r();let m=await Ul[o(768)](this);if(f["isAckCleanupMess"+o(567)]&&f.ackMsgIds.length)for(let y of f[o(1869)+"s"])await m.del(y);e[o(897)](r)}else{let f=this[o(921)]["getStora"+o(1874)](this[o(1625)]),m=_0x141584[o(1192)](uWXtQO[o(1140)](f,"{}"));return m[_0x4126eb||_0x1a65b1[this[o(1457)]]]=_0x5b10d1,this[o(921)][o(749)+o(1874)](this._prefix,_0x2f4776.stringify(m)),_0x1065b9||_0x252bd0[this[o(1457)]]}}async function tm(c,r){let o=t,l={AfZiN:function(p,R,M){return e[G(1558)](p,R,M)}},f=e.VkcNU(c[o(1747)][o(1173)+"e"],$g),m=e[o(497)](c.message[o(1173)+"e"],Ua);if(e[o(974)](!f,!m))return e[o(879)](r);let y=e[o(792)](hr,c.message[o(602)],e[o(1881)]);if(!y)return e[o(897)](r);let S=await Gl[o(768)](this,y);if(!S)return e[o(349)](r);if(f)if(e.hXUTn==="nXhyY"){this[o(1461)+o(1262)](),this._pingPongTimeoutId=l[o(1657)](_0x12d7f7,this[o(1698)][o(1359)](this),this[o(1037)][o(1779)+o(1632)]);return}else{let p=await S[o(1123)+"rs"](),R={frameType:p?.[o(1173)+"e"],SeqID:ge[o(613)+"er"](this[o(1321)]++),LogID:ge[o(613)+"er"](this[o(1037)][o(1793)+o(1658)]()),service:9e3,method:5,headers:p?.[o(602)],payload:p?.[o(841)]},M=e[o(960)](v,R);this[o(1298)]&&this._ws[o(449)+"te"]&&this[o(1298)].send(M)}if(m){let p=c[o(1747)][o(841)];p&&S.setCursors(p)}}let nm=async function(c,r){let o=t;this[o(400)]=!1,e.dJNNM(clearTimeout,this[o(643)+"ionTimeo"+o(1184)]),e[o(1492)](r)},rm=async function(c,r){let o=t;if(!this[o(1298)]||e[o(1535)](this[o(1298)][o(449)+"te"],this[o(1613)]))return e[o(1174)](r);let{pingInterval:l}=this._options;this[o(625)+o(883)]?.[o(1278)+o(1590)+o(1721)]();for(let m=0;e[o(1078)](m,this[o(1786)+o(1726)][o(516)]);m++){let y=this[o(1786)+o(1726)][m];if(this._ws.readyState===this[o(1613)]&&e[o(811)](null,y))this._ws&&this[o(1298)][o(764)](y),this[o(1786)+o(1726)][m]=null;else break}this[o(1786)+o(1726)]=this[o(1786)+o(1726)][o(1353)](m=>!!m),this[o(506)+o(1286)+"Id"]=e.iKQqT(setTimeout,()=>this[o(1698)](),l),this[o(329)+"hOpenEvent"](c),this[o(347)+"er"]&&this._ws&&(this[o(1298)][o(1212)+"pe"]=this[o(864)+"ype"]);let f=this[o(625)+"tManager"]?.[o(1274)+o(334)+"nt"]();this[o(1101)](o(1396)+f+o(1433)),e[o(1186)](r)},im=async function(c,r){let o=t,l=this[o(625)+o(883)]?.[o(1274)+o(334)+"nt"]();this[o(1101)]("open "+l),e.VuhtP(r)};class sm extends La{constructor(r){let o=t,l={fniyL:function(S,p,R,M){return S(p,R,M)},HEgZn:function(S,p,R){return e[G(1201)](S,p,R)},XMcOz:e[o(1567)],QQnhA:function(S,p){return e.VkcNU(S,p)},rkcrP:function(S,p,R){return e[o(790)](S,p,R)},VxvpG:function(S,p){return e[o(509)](S,p)},DPikU:e[o(1693)],WfoGT:o(1465),fmqdq:function(S,p){return e.bcknM(S,p)},URQgz:e[o(1289)],IbepG:function(S,p,R){return e[o(486)](S,p,R)},WKpnr:e[o(1284)],Himqb:e.lGhFB,WfwwL:e[o(572)],HSpHl:function(S,p){return e[o(672)](S,p)}};super(),this[o(1789)+"igatorOn"+o(1175)]=!0,this[o(347)+"er"]=fr,this[o(995)]=bg,this._isMiniTT=Mn,this[o(870)+"X"]=li,this._isWorker=ui,this[o(1786)+o(1726)]=[],this[o(625)+o(883)]=null,this[o(1580)+o(698)]=!1,this[o(864)+o(1448)]=e[o(898)],this[o(643)+"Lock"]=!1,this["_connect"+o(730)+o(1184)]=null,this[o(343)+o(1769)+o(946)]=null,this[o(506)+o(1286)+"Id"]=null,this[o(1321)]=0,this._isInit=!1,this._url="",this[o(342)+o(996)]=null,this["_cursorM"+o(1522)]=null,this[o(878)+o(1319)]=null,this[o(1570)+"ls"]=e[o(649)],this[o(935)]=3,this[o(626)+"NG"]=0,this[o(1613)]=1,this[o(598)]=2,this[o(1405)]=S=>{let p=o;try{l[p(1380)](Nl,this,S,[nm,rm,im])}catch(R){let M=l[p(1806)](ht,l[p(657)],{message:R.message,code:fn.OPEN_ERROR,error:R});this[p(329)+"hErrorEv"+p(677)](M)}},this[o(553)+"ge"]=async S=>{let p=o,R={SvVYN:function(P,D){return e[G(1394)](P,D)},gYnBc:function(P,D){return e[G(937)](P,D)},XGoOd:function(P,D){return P>>>D},sgboK:function(P,D){return e.Wiwkr(P,D)},fDmPh:function(P,D){return e[G(1171)](P,D)},xqUyR:function(P,D){return e[G(1436)](P,D)},FSDdR:function(P,D){return P<D},IVCTp:function(P,D,B){return e[G(352)](P,D,B)},LKIgh:function(P,D){return e[G(1317)](P,D)},FJram:function(P,D){return P+D},jyprC:function(P,D){return e[G(1261)](P,D)},cSOVr:function(P,D){return P&D},oJiHU:function(P,D){return e[G(1731)](P,D)},oaLZL:function(P,D){return P!==D},uKRRo:function(P,D){return e.bsxQE(P,D)},IEyvq:function(P,D){return P+D},KcptZ:function(P,D){return e[G(1676)](P,D)},RbaGQ:function(P,D){return e[G(1839)](P,D)},pvqvo:function(P,D){return e[G(665)](P,D)},muskG:function(P,D){return e[G(576)](P,D)},TtGFA:function(P,D){return e[G(502)](P,D)},IwavX:function(P,D){return e[G(1711)](P,D)},vyYLE:function(P,D){return e.DHaBD(P,D)},kvNNI:function(P,D){return P+D},aYeUa:function(P,D){return e[G(1840)](P,D)},jcBKw:function(P,D){return e[G(536)](P,D)},CGiOP:function(P,D){return e[G(481)](P,D)},VlHzH:function(P,D){return e[G(325)](P,D)},wKTGO:function(P,D){return e[G(978)](P,D)},TcXPB:function(P,D){return P|D}},{pingInterval:M,pingFrequency:F}=this._options;if(e.QUmRY("hi",S.data)&&e[p(434)](e.CcMfq,F)||e[p(1270)](e[p(872)],F))if(e[p(1716)](e[p(420)],e[p(460)])){let P=zxOfMj[p(1352)](_0x4eda42[p(1674)],0),D=zxOfMj[p(1352)](zxOfMj.gYnBc(zxOfMj[p(1117)](_0x48e8e1[p(1674)],28),zxOfMj[p(1683)](_0x1dc54[p(1783)],4)),0),B=_0x14c9a0[p(1783)]>>>24,ie=zxOfMj.fDmPh(0,B)?zxOfMj.xqUyR(0,D)?zxOfMj[p(697)](P,16384)?zxOfMj[p(697)](P,128)?1:2:P<2097152?3:4:zxOfMj[p(697)](D,16384)?D<128?5:6:D<2097152?7:8:zxOfMj.FSDdR(B,128)?9:10,le=zxOfMj.IVCTp(_0x31ead0,_0x449478,ie),ye=_0x2aa771[p(1589)];switch(ie){case 10:ye[le+9]=zxOfMj[p(589)](B>>>7,1);case 9:ye[zxOfMj[p(1827)](le,8)]=zxOfMj[p(1027)](9,ie)?128|B:zxOfMj[p(903)](127,B);case 8:ye[zxOfMj[p(1329)](le,7)]=zxOfMj[p(1397)](8,ie)?zxOfMj[p(1450)](zxOfMj[p(1117)](D,21),128):zxOfMj[p(589)](zxOfMj[p(1876)](D,21),127);case 7:ye[zxOfMj[p(568)](le,6)]=ie!==7?zxOfMj.KcptZ(zxOfMj[p(1608)](D,14),128):zxOfMj[p(1746)](zxOfMj[p(534)](D,14),127);case 6:ye[zxOfMj[p(1329)](le,5)]=zxOfMj[p(709)](6,ie)?zxOfMj[p(1450)](D>>>7,128):zxOfMj.LKIgh(zxOfMj[p(1608)](D,7),127);case 5:ye[zxOfMj.IwavX(le,4)]=ie!==5?zxOfMj[p(1450)](128,D):127&D;case 4:ye[zxOfMj[p(873)](le,3)]=zxOfMj[p(899)](4,ie)?P>>>21|128:zxOfMj.LKIgh(P>>>21,127);case 3:ye[zxOfMj[p(834)](le,2)]=zxOfMj[p(1408)](3,ie)?zxOfMj[p(1876)](P,14)|128:zxOfMj[p(1746)](zxOfMj[p(1876)](P,14),127);case 2:ye[zxOfMj[p(1061)](le,1)]=zxOfMj.TtGFA(2,ie)?zxOfMj.CGiOP(zxOfMj[p(1126)](P,7),128):zxOfMj.wKTGO(P,7)&127;case 1:ye[le]=zxOfMj[p(1408)](1,ie)?zxOfMj.TcXPB(128,P):127&P}}else this["_clearPi"+p(1262)](),this.emit(e[p(1660)],e[p(1809)]),this[p(506)+p(1286)+"Id"]=setTimeout(this[p(1698)][p(1359)](this),M);if(!e[p(1308)]("hi",S[p(467)]))try{e.nCTBO(Nl,this,S,[Mg,Lg,em,tm,Qg,Ng])}catch(P){let D=e[p(1672)](ht,p(371),{message:P.message,code:fn[p(1695)+p(1829)],error:P});this[p(329)+p(360)+p(677)](D)}},this[o(847)]=S=>{let p=o,R=this[p(625)+p(883)]?.[p(1080)+p(791)+"es"](),M=this[p(625)+"tManager"]?.["getCurre"+p(334)+"nt"]();if(R&&!S[p(1747)]){let F=p(495)+M+(" fail, m"+p(1582)+p(1392)+"ed");this[p(329)+p(360)+"ent"](l.HEgZn(ht,l[p(657)],{message:F,code:fn[p(1687)+p(1091)+"R"],error:S}));return}this[p(1298)]&&l[p(580)](this[p(1298)].readyState,this[p(1613)])&&this["_disconn"+p(716)](),this["_dispatc"+p(360)+"ent"](l[p(1107)](ht,l[p(657)],{message:S[p(1747)],code:fn[p(1160)+p(474)],error:S}))},this[o(507)]=async S=>{let p=o,R={csOLZ:p(478)+"1",QHvHb:function(P,D,B){return l.rkcrP(P,D,B)},HxWSA:l[p(657)],Zltxp:function(P,D){return l[p(580)](P,D)}};if(l.VxvpG(l[p(1188)],l[p(1830)])){this[p(1572)+p(1861)](),this[p(1461)+p(1262)](),this[p(1249)+p(1058)+"rs"](),this[p(1298)]=null,this._connectLock=!1;let P=this[p(625)+p(883)]?.["checkRea"+p(791)+"es"]();if(!P&&this[p(887)+p(1385)]()&&!this[p(1580)+p(698)]){let D=this[p(625)+p(883)]?.[p(1274)+"ntEndpoint"](),B=this[p(1037)][p(379)+"tInterce"+p(1269)](S[p(1177)],S[p(1209)]);this[p(329)+p(1722)+p(677)](Et("close",{code:1006,reason:S.reason||p(694)+p(866)+p(326)+p(1109)+p(1768)+p(555)+D,willReconnect:B})),B&&this[p(643)]();return}if(l.VxvpG(1e3,S[p(1177)])&&this[p(1580)+"osed"])if(l[p(521)](l[p(1305)],p(1395))){let D=R[p(1148)][p(1604)]("|"),B=0;for(;;){switch(D[B++]){case"0":if(F!==void 0)return F[p(1823)];continue;case"1":return M.exports;case"2":_0x47ad3e[_0x1c8a45](M,M.exports,_0x334ad6);continue;case"3":var M=_0x229fdb[_0xa1994f]={exports:{}};continue;case"4":var F=_0x1d78a4[_0x25b23e];continue}break}}else{this[p(329)+p(1722)+p(677)](l.IbepG(Et,l[p(510)],{code:1e3,reason:l[p(654)]})),this["_endpoin"+p(883)]?.["resetEndpointCon"+p(1721)](),this[p(878)+p(1319)]?.[p(1707)+"nter"]();return}if(l[p(909)](1e3,S[p(1177)])&&P)if(l[p(1017)]===l[p(1017)]){let D=this[p(625)+"tManager"]?.[p(1274)+"ntEndpoint"](),B=S[p(1209)];B||(B=await l[p(611)](Tg,this._url)),B=p(694)+p(866)+p(1349)+B+(p(1275)+p(1855))+D+(", max re"+p(491)+p(1287)),this[p(329)+"hCloseEv"+p(677)](l.rkcrP(Et,l[p(510)],{code:S.code,reason:B}));let ie=p(495)+D+(p(355)+p(1582)+p(1392)+"ed");this[p(329)+p(360)+p(677)](l[p(1806)](ht,l[p(657)],{message:ie,code:fn[p(1687)+p(1091)+"R"]})),this[p(625)+p(883)]?.["resetEnd"+p(1590)+"fig"](),this[p(878)+p(1319)]?.["resetCou"+p(1076)]();return}else{let D=this["_endpoin"+p(883)]?.[p(1080)+p(791)+"es"](),B=this[p(625)+p(883)]?.[p(1274)+p(334)+"nt"]();if(D&&!_0x3f49f3[p(1747)]){let ie="connect "+B+(p(355)+p(1582)+p(1392)+"ed");this[p(329)+p(360)+p(677)](IvLOwL[p(528)](_0x5f97d9,IvLOwL.HxWSA,{message:ie,code:_0x11b271[p(1687)+p(1091)+"R"],error:_0x5cc86a}));return}this[p(1298)]&&IvLOwL[p(527)](this[p(1298)].readyState,this.OPEN)&&this["_disconn"+p(716)](),this["_dispatc"+p(360)+p(677)](_0x5994ea(IvLOwL[p(535)],{message:_0x376023[p(1747)],code:_0x2ba7f2[p(1160)+p(474)],error:_0x306b84}))}if(l.VxvpG(1e3,S[p(1177)])&&!S[p(1209)]){let D=this[p(625)+p(883)]?.["getCurre"+p(334)+"nt"]();this[p(329)+p(1722)+p(677)](l[p(1739)](Et,p(760),{code:S.code,reason:p(694)+p(866)+p(326)+p(1109)+p(1768)+p(555)+D})),this._endpointManager?.[p(1278)+p(1590)+"fig"](),this[p(878)+p(1319)]?.[p(1707)+p(1076)]();return}this[p(329)+p(1722)+p(677)](S),this[p(625)+p(883)]?.[p(1278)+p(1590)+p(1721)](),this[p(878)+p(1319)]?.["resetCou"+p(1076)]()}else return this[p(393)+"T"]||this[p(870)+"X"]?this[p(1789)+p(1591)+p(1175)]:(this[p(347)+"er"]||this._isWorker)&&this[p(1037)]["listenNetworkCha"+p(1438)]?_0x44064f[p(494)]:!0},this.onclose=null,this[o(770)]=null,this[o(1603)+"e"]=null,this[o(1798)]=null,this["onStartR"+o(914)]=null,this[o(985)+o(1169)]=null,this[o(1865)+o(1379)+"yReconnect"]=null,this[o(999)+o(1153)]=this[o(999)+o(1153)][o(1359)](this),this[o(999)+o(1322)]=this[o(999)+o(1322)][o(1359)](this),this[o(934)+o(595)]=this["_handleP"+o(595)].bind(this),this[o(934)+o(618)]=this[o(934)+o(618)].bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:s,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:o(1822),env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:m}=r,y=Array[o(1085)](f)?f:e[o(636)](o(439),typeof f)?[f]:[];if(!y||e.svNrx(0,y[o(516)]))throw new Error(e[o(1462)]);if(!e.DNQts(Sg,m))throw new Error(e[o(362)]);Object[o(980)](this._options,r),this["_endpoin"+o(883)]=new Ll(y,this[o(1037)][o(1276)+"es"]),this[o(878)+o(1319)]=new kg(this[o(1037)][o(1831)+o(336)]),this[o(1037)][o(1323)+o(769)]&&(this._isInit=!0,this[o(643)]()),this._options["listenNe"+o(512)+o(1438)]&&(this[o(393)+"T"]||this[o(870)+"X"]?this[o(1050)+"etWorkChange"]():this[o(347)+"er"]&&this["_initGlo"+o(1072)+o(1518)]())}[t(999)+t(1153)](){let r=t;this[r(1037)][r(1713)+r(933)+r(1345)]||this[r(1580)+r(698)]||this["_handleR"+r(914)]()}["_handleO"+t(1322)](){let r=t,o={SMINK:function(l,f){return e[G(1889)](l,f)},vACTN:function(l,f){return l>f}};if(e[r(862)]!==e[r(629)]){this[r(1166)+r(345)+"t"]();let l=Oa(e[r(905)],{message:e.YkbwD});this[r(1865)+"mediatel"+r(1440)+"ct"]&&this[r(1865)+"mediatel"+r(1440)+"ct"](l)}else return iwkzJl[r(785)](this[r(641)+r(363)],this[r(1598)+"s"][r(516)])?!0:iwkzJl[r(1243)](this[r(1754)+r(1667)+r(1363)+"t"],this[r(1276)+"es"])}[t(1084)+t(1072)+t(1518)](){let r=t;this[r(347)+"er"]&&window[r(1795)+r(1518)](r(444),this[r(999)+r(1153)]),this[r(347)+"er"]&&window[r(1795)+r(1518)](e[r(1444)],this._handleOffLine),this[r(347)+"er"]&&window["addEvent"+r(1518)](e[r(1886)],this[r(934)+r(595)]),this[r(347)+"er"]&&window[r(1795)+r(1518)](e[r(1240)],this[r(934)+r(618)])}[t(1357)+t(1072)+t(1518)](){let r=t;this[r(347)+"er"]&&window[r(1248)+"entListe"+r(1390)](e[r(551)],this[r(999)+r(1153)]),this[r(347)+"er"]&&window[r(1248)+r(943)+r(1390)](e[r(1444)],this["_handleO"+r(1322)]),this[r(347)+"er"]&&window[r(1248)+"entListe"+r(1390)](r(564),this[r(934)+r(595)]),this[r(347)+"er"]&&window[r(1248)+r(943)+"ner"](r(988),this[r(934)+r(618)])}[t(934)+"ageHide"](r){let o=t;!r[o(1064)+"d"]&&(this[o(347)+"er"]&&window[o(1248)+o(943)+"ner"](o(564),this[o(934)+"ageHide"]),this[o(347)+"er"]&&window[o(1248)+o(943)+o(1390)](e[o(1240)],this[o(934)+o(618)]),this[o(760)]()),this[o(347)+"er"]&&window[o(1248)+o(943)+"ner"](e[o(551)],this._handleOnLine),this[o(347)+"er"]&&window[o(1248)+o(943)+o(1390)](o(1025),this["_handleO"+o(1322)])}["_handleP"+t(618)](r){let o=t;r[o(1064)+"d"]&&(this[o(887)+o(1385)]()&&(!this[o(1298)]||e[o(648)](this[o(1298)].readyState,this[o(1613)])||e.OIkxn(this[o(1298)][o(449)+"te"],this[o(626)+"NG"]))&&this[o(999)+o(1153)](),this[o(347)+"er"]&&window[o(1795)+o(1518)](e[o(551)],this[o(999)+o(1153)]),this[o(347)+"er"]&&window[o(1795)+"Listener"](e[o(1444)],this[o(999)+o(1322)]))}async["_generat"+t(1213)](r){let o=t,{fpID:l,deviceID:f,bddID:m,ttwID:y,accessKey:S,aID:p,customParams:R={},enableAutoAck:M,enableQoS:F,QoSLevel:P,env:D}=this._options,B,ie,le;this[o(347)+"er"]||this[o(870)+"X"]||this[o(393)+"T"]?(B=location&&location[o(508)]=="https:"?e[o(1791)]:"ws://",ie=r[o(1650)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),le=/^wss(.*:\/\/)/[o(1702)](r)?r:""+B+ie):(B=e.JXMkK,ie=r[o(1650)](/(^http)((?:[s]*:\/\/))/,""),le=/(^ws)((?:[s]*:\/\/))/[o(1702)](ie)?ie:""+B+ie);let ye=m?e[o(962)]:y?e[o(745)]:e[o(853)],vt=m||y||f;if(!vt||!ye)throw new Error(e.WzcOE);let we=e[o(976)](e[o(671)],typeof R)?await e[o(1011)](R):R,fi=D?e[o(1498)](Ag,D.xUseEnv,D[o(1282)]):{},Ha=Object[o(980)]({device_platform:e[o(1629)],version_code:e[o(1555)],access_key:S,fpid:l,aid:p,[ye]:vt,xsack:M?1:0,xaack:M?1:0,xsqos:F?1:0,qos_level:F?P:void 0,qos_sdk_version:2,...fi},we),om=Object[o(945)](Ha)[o(693)]((Ga,qa)=>Ha[qa]!==void 0?""+Ga+(Ga?"&":"?")+qa+"="+Ha[qa]:Ga,"");return le+o(476)+om}async[t(643)](){let r=t;if(!(this[r(643)+r(410)]||this[r(1580)+r(698)])){this[r(643)+r(410)]=!0;try{let o=this[r(625)+r(883)]?.[r(720)+r(505)+r(1587)+r(1432)+"tries"](),{timeoutInterval:l}=this[r(1037)];if(o){let m=this[r(625)+r(883)]?.["getCurre"+r(334)+"nt"](),y=this[r(625)+r(883)]?.[r(621)+r(958)+r(777)+r(1801)+r(1868)](),S=this._endpointManager?.[r(1274)+r(334)+r(1724)+r(1347)]();if(y){let p=r(495)+m+(r(895)+r(1471)+r(491)+"ached, w"+r(783)+r(1720)+r(701))+y+(r(637)+"y"),R=e[r(1851)](ht,e[r(1567)],{message:p,code:fn[r(1687)+r(1091)+"R"]});this[r(1101)](p),this[r(329)+r(360)+r(677)](R),this[r(1479)]=await this[r(1541)+r(1213)](y),this[r(1101)](r(495)+y+" "+S+r(938)),this[r(1249)+r(1058)+"rs"]()}else{let p=r(495)+m+(" timeout"+r(1471)+"tries re"+r(1287));this[r(1101)](p),this[r(329)+r(360)+r(677)](e[r(896)](ht,e[r(1567)],{message:p,code:fn[r(1687)+r(1091)+"R"]}));return}}else{let m=this[r(625)+r(883)]?.["getCurre"+r(334)+r(1486)+r(1550)](),y=this["_endpoin"+r(883)]?.[r(1274)+"ntEndpointTriesC"+r(1347)]();this[r(1479)]=await this[r(1541)+r(1213)](e[r(323)](m,"")),this[r(1101)](r(495)+m+" "+y+r(938)),this[r(1249)+"sListeners"]()}if(this[r(400)])this[r(400)]=!1;else{let m=e[r(795)](Oa,e.LKbUG,{message:e[r(1554)]});this["onStartR"+r(914)]&&this[r(859)+"econnect"](m)}let f=this[r(625)+r(883)]?.[r(1274)+"ntEndpoi"+r(1724)+r(1347)]()||0;f>1&&await this[r(384)](e.xuyLj(f,1)),this[r(1101)](r(694)+r(1100)+this[r(1479)]+(" protoco"+r(1759))+this[r(1570)+"ls"]),this[r(1298)]=e[r(1419)](vg,{url:this[r(1479)],protocols:[this[r(1570)+"ls"]],headers:this[r(1037)].miniProgramParams[r(942)+"tpHeader"]},this._options.ws),(this[r(347)+"er"]||this._isWorker)&&this._ws&&(this[r(1298)].binaryType=this[r(864)+"ype"]),this[r(455)+"steners"](),this[r(643)+r(730)+r(1184)]=e[r(1217)](setTimeout,this[r(1507)+"ut"][r(1359)](this),l)}catch(o){throw this["_connect"+r(410)]=!1,o}}}[t(1572)+t(1861)](){let r=t;clearTimeout(this["_connect"+r(730)+r(1184)]),this[r(643)+"ionTimeo"+r(1184)]=null}[t(1461)+t(1262)](){let r=t;clearTimeout(this["_pingPon"+r(1286)+"Id"]),e[r(562)](clearTimeout,this[r(343)+"ctTimeou"+r(946)]),this[r(506)+r(1286)+"Id"]=null,this[r(343)+r(1769)+r(946)]=null}[t(1101)](...r){let o=t;this[o(1037)][o(1226)]&&console[o(828)][o(1059)](console,["FRONTIER>",...r])}["_getInte"+t(1785)+"e"](r){let o=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:m}=this[o(1037)],y=e[o(1288)](l,Math[o(1389)](m,e[o(1446)](r,1)));return y>f?f:y}[t(1698)](){let r=t;if(this[r(1298)]&&e.QgttU(this._ws.readyState,this[r(626)+"NG"])){this[r(1461)+"ngTimer"](),this[r(506)+r(1286)+"Id"]=e.IOMUB(setTimeout,this[r(1698)][r(1359)](this),this[r(1037)][r(1779)+r(1632)]);return}if(!this._ws||e[r(648)](this[r(1298)][r(449)+"te"],this.OPEN))return void this["_handleR"+r(914)]();this[r(1298)]&&this[r(1298)][r(764)]("hi"),this["_reconne"+r(1769)+r(946)]=setTimeout(this["_handleReconnect"+r(750)][r(1359)](this),this[r(1037)][r(1878)+r(690)+r(986)])}["_handleR"+t(914)+t(750)](){let r=t,o={CAvAI:function(l,f){return e.hJTsD(l,f)}};if(e.JnHsD(e[r(1297)],e[r(338)]))this["_pingLos"+r(1319)]?.[r(1763)](),this[r(1387)](e[r(757)],r(381)),this._pingLossCounter?.[r(1080)+r(1566)+"nt"]()?this[r(983)+r(914)]():this._ping();else return keAQYB[r(538)](this[r(1141)],this[r(1332)+r(1347)])}[t(887)+t(1385)](){let r=t;return this._isMiniTT||this[r(870)+"X"]?this[r(1789)+r(1591)+"line"]:(this[r(347)+"er"]||this[r(1776)+"r"])&&this[r(1037)][r(774)+r(512)+r(1438)]?navigator[r(494)]:!0}_handleReconnect(){let r=t;!this[r(887)+"orOnline"]()||this[r(1580)+"osed"]||(this[r(625)+r(883)]?.[r(1278)+r(1590)+r(1721)](),this[r(878)+r(1319)]?.[r(1707)+r(1076)](),this[r(1298)]?this[r(688)+r(716)](1001,e[r(1468)],!0):this[r(643)]())}["_onPageN"+t(382)+t(1501)](){let r=t,o={RIRTq:function(l,f){return e[G(960)](l,f)},SoicI:function(l,f){return e[G(1458)](l,f)},NxZTK:function(l,f){return e[G(1113)](l,f)},fvqEW:e[r(1355)]};this[r(393)+"T"]?tt[r(492)+"kStatusC"+r(364)](({isConnected:l})=>{let f=r;this["_miniNav"+f(1591)+"line"]=l,l?this[f(999)+"nLine"]():this[f(999)+f(1322)]()}):this._isMiniWX&&wx[r(492)+"kStatusChange"](({isConnected:l})=>{let f=r;if(e[f(1168)](e[f(1346)],f(482)))return mZuXXb.RIRTq(_0x3f029f,mZuXXb[f(340)](mZuXXb[f(1515)]("index out of ran"+f(1098),_0x52b91b)+f(1845)+(_0x310cd9||1),mZuXXb[f(1378)])+_0x471810);this[f(1789)+f(1591)+f(1175)]=l,l?this["_handleO"+f(1153)]():this["_handleO"+f(1322)]()})}[t(384)](r){let o={MIfhl:function(l,f,m){return e[G(1419)](l,f,m)}};return new Promise(l=>{let f=G;o[f(813)](setTimeout,l,this[f(743)+f(1785)+"e"](r))})}[t(688)+t(716)](r=1e3,o="",l=!1){let f=t;this[f(1298)]&&this[f(1166)+f(345)+"t"](r,o,l)}[t(1507)+"ut"](){let r=t,o=this[r(625)+r(883)]?.["getCurre"+r(334)+"nt"]();this[r(1101)]("connect "+o+r(895)),this[r(688)+"ect"](1001,e[r(513)],!0)}[t(582)](r){let o=t;if(e.fDZpW(e[o(1277)],e[o(1649)])){let l=e[o(586)](Kt,r);this[o(1298)]&&e[o(434)](this[o(1298)][o(449)+"te"],this.OPEN)&&(this[o(1298)]&&this[o(1298)].send(l),this[o(1101)](e[o(1360)],r))}else return null}["_removeW"+t(1058)+"rs"](){let r=t;this[r(1298)]&&(this[r(1298)][r(1248)+"entListe"+r(1390)](e[r(1029)],this[r(1405)]),this._ws[r(1248)+r(943)+"ner"](e.vmVBn,this[r(507)]),this[r(1298)]["removeEv"+r(943)+"ner"](e[r(563)],this[r(553)+"ge"]),this[r(1298)][r(1248)+r(943)+r(1390)](e.VDLvX,this[r(847)]))}[t(455)+t(1653)](){let r=t,o=e[r(619)][r(1604)]("|"),l=0;for(;;){switch(o[l++]){case"0":this[r(1298)][r(1795)+r(1518)](e.vmVBn,this[r(507)]);continue;case"1":if(!this[r(1298)])return;continue;case"2":this[r(1298)][r(1795)+"Listener"](r(1747),this[r(553)+"ge"]);continue;case"3":this._ws[r(1795)+r(1518)](r(371),this[r(847)]);continue;case"4":this[r(1298)][r(1795)+r(1518)](r(499),this[r(1405)]);continue}break}}["_wsInsta"+t(711)](r=1e3,o=""){let l=t,f={JtYhj:e[l(1356)],Ljrga:e.bElZv,gjHpB:"MAX_RETR"+l(1091)+"R",WMuzT:e[l(1449)],UWXKZ:e[l(659)]};if(e[l(648)](l(1354),e[l(583)]))try{if(e[l(463)](e.DnBay,e[l(849)]))this[l(1298)]&&this[l(1298)][l(760)](r,o);else return _0x92ce0a[_0xad4126[pUHucB[l(1857)]]=5001]=l(1160)+l(474),_0x38ad41[_0x1cc646[l(626)+l(387)]=5002]=pUHucB[l(926)],_0x4bcaf1[_0x4c4544[l(1687)+"IES_ERROR"]=5003]=pUHucB[l(763)],_0xe4454e[_0x305e1a[pUHucB[l(1041)]]=5004]=l(1695)+l(1829),_0x23e23c[_0x348b91[pUHucB.UWXKZ]=5005]=l(458)+"OR",_0x326451}catch{}else if(_0x162829=_0x47ba2f[l(708)+"At"](_0x5d3a5c),e[l(1729)](_0x5d2c7d,128))_0x3e17e6[_0x1f55a2++]=_0x95dfa6;else if(_0x4de57e<2048)_0x52ff83[_0x1a6bfd++]=e.sccHk(e[l(1071)](_0x21ae81,6),192),_0x3e8d14[_0x373997++]=e[l(1150)](63&_0x4a11d1,128);else if(e[l(357)](64512&_0x8fff1e,55296)&&e.tlCKi(e.qZqMH(64512,_0x4819dd=_0x596a9c[l(708)+"At"](e.pnosA(_0x56cfd8,1))),56320)){let m=("2|5|4|3|"+l(1016)).split("|"),y=0;for(;;){switch(m[y++]){case"0":_0x19d684[_0x4999c6++]=e[l(529)](e[l(1646)](63,_0x24baea),128);continue;case"1":_0x1be3cd[_0x6d92fc++]=e.EGCFp(e[l(740)](_0x2c0346>>6,63),128);continue;case"2":_0x1c56c9=e[l(858)](e[l(967)](65536,e.cZuFU(e.Wlkgj(1023,_0x467345),10)),1023&_0x30d0b3);continue;case"3":_0x498792[_0x1a2ebe++]=e[l(1272)](e[l(1577)](_0x5988cd,12),63)|128;continue;case"4":_0x4fdba7[_0x12e802++]=e[l(1764)](_0x38372f>>18,240);continue;case"5":++_0xf156f8;continue}break}}else _0x10e12e[_0x43f225++]=e[l(1149)](_0x1a4a3a,12)|224,_0xc5360e[_0xedd078++]=e[l(1131)](e.lOXVY(e[l(1751)](_0x1c1091,6),63),128),_0xa04292[_0x5ec885++]=e[l(1237)](e.WbKIw(63,_0x30dad9),128)}[t(1166)+"WebSocket"](r=1e3,o="",l=!1){let f=t;if(this._clearPingTimer(),this[f(1572)+f(1861)](),this[f(1249)+f(1058)+"rs"](),this[f(1435)+f(711)](1e3,o),this[f(643)+f(410)]=!1,l&&this[f(887)+f(1385)]()&&!this[f(1580)+f(698)]){if(this[f(625)+f(883)]?.[f(1080)+f(791)+"es"]()){let y=this[f(625)+f(883)]?.["getCurre"+f(334)+"nt"]();this[f(329)+f(1722)+f(677)](e[f(739)](Et,f(760),{code:1006,reason:f(495)+y+(f(895)+f(1471)+"tries re"+f(1287)),wasClean:!0}))}else{let y=this[f(1037)][f(379)+f(1196)+f(1269)](r,o);this[f(329)+f(1722)+"ent"](e.pIMNj(Et,e[f(1284)],{code:r,reason:o,wasClean:!0,willReconnect:y})),y&&this[f(643)]()}return}this["_navigat"+f(1385)]()||this["_readyCl"+f(698)]?this[f(329)+f(1722)+f(677)](Et(e.vmVBn,{code:r,reason:f(1800)})):this["_dispatc"+f(1722)+f(677)](e.iXLUE(Et,e[f(1284)],{code:1006,reason:e.cjIKR})),this[f(1298)]=null,this[f(625)+f(883)]?.[f(1278)+f(1590)+"fig"](),this[f(878)+f(1319)]?.["resetCou"+f(1076)]()}[t(329)+t(664)+"nt"](r){let o=t;this.emit("open",r),this[o(1798)]&&this[o(1798)](r)}[t(329)+t(955)+t(1283)](r){let o=t;e[o(1627)](e.TgpSJ,e[o(615)])?(this.emit(e[o(563)],r),this[o(1603)+"e"]&&this[o(1603)+"e"](r)):(++_0x48c502,_0x5a33a1+=4)}[t(329)+"hAckMess"+t(1187)](r){let o=t;this[o(1387)](o(1290),r),this[o(985)+o(1169)]&&this[o(985)+o(1169)](r)}["_dispatc"+t(360)+t(677)](r){let o=t;this[o(1387)](e[o(1567)],r),this[o(770)]&&this.onerror(r)}["_dispatc"+t(1722)+t(677)](r){let o=t;this.emit(e[o(1284)],r),this[o(1033)]&&this[o(1033)](r)}get[t(1212)+"pe"](){let r=t;return this._ws?this[r(1298)][r(1212)+"pe"]:this[r(864)+r(1448)]}set[t(1212)+"pe"](r){let o=t;this[o(864)+o(1448)]=r,this._ws&&(this[o(1298)][o(1212)+"pe"]=r)}get[t(1251)+"nt"](){let r=t;return this[r(625)+r(883)]?.[r(1274)+r(334)+r(1724)+r(1347)]()||0}get["buffered"+t(1715)](){let r=t,o=this[r(1786)+r(1726)][r(693)]((l,f)=>{let m=r,y={GYHsp:e[m(1360)]};if(e[m(1834)]!==e[m(1834)])this._ws&&this[m(1298)][m(764)](_0x30b4d3),this[m(1101)](xgbbkz[m(1601)],_0x45a7b4);else return l+=f&&f[m(1185)+"th"]||0,l},0);return e[r(1711)](o,this[r(1298)]?this._ws["buffered"+r(1715)]:0)}get extensions(){let r=t;return this[r(1298)]?this[r(1298)][r(1165)+"ns"]:""}get[t(508)](){let r=t;return this[r(1298)]?this[r(1298)].protocol:""}get[t(449)+"te"](){let r=t;if(e[r(509)](e[r(865)],e[r(681)]))return this[r(1298)]?this[r(1298)][r(449)+"te"]:this[r(1037)][r(1323)+r(769)]?this[r(626)+"NG"]:this.CLOSED;this[r(593)+r(1584)]=null}get url(){let r=t;return this[r(1298)]?this[r(1298)][r(1193)]:this[r(1479)]}[t(760)](r=1e3,o){let l=t,f=(l(1843)+"3|0|1|2")[l(1604)]("|"),m=0;for(;;){switch(f[m++]){case"0":if(!this[l(1298)])return void this._debug(e[l(373)]);continue;case"1":if(e.nToMM(this[l(1298)][l(449)+"te"],this[l(935)])||this[l(1298)][l(449)+"te"]===this[l(598)])return void this[l(1101)](e[l(679)]);continue;case"2":this[l(1166)+l(345)+"t"](r,o);continue;case"3":this._QoSManager?.closeDB();continue;case"4":this[l(1357)+l(1072)+l(1518)]();continue;case"5":this[l(1572)+l(1861)]();continue;case"6":this[l(1461)+l(1262)]();continue;case"7":this[l(1580)+"osed"]=!0;continue}break}}async[t(764)](r,o){let l=t;if(e.xgvdw(e[l(587)],l(610)))return _0x4db105?_0x251441[l(407)+l(810)](_0x201e0d,_0x28b5f2):_0x2c6467[l(407)+"sBE"](_0x18510a,_0x1fbafa);{if(e.VnbGv(null,r))throw new Error(e[l(1194)]);e.DmjXr(e[l(1610)],typeof r)&&(r=JSON[l(981)+"y"](r)),e[l(910)]!=typeof r&&!e[l(904)](r,ArrayBuffer)&&!(r.buffer&&r[l(1524)]instanceof ArrayBuffer)&&(r=JSON[l(981)+"y"](r));let f=await e.ZBFbo(Fl,r),m=e.ZBGhe(Ig,r),{method:y=0,service:S=this[l(1037)][l(394)],logID:p=this[l(1037)]["logIDGen"+l(1658)](),headers:R=this[l(1037)][l(602)],payloadEncoding:M=this[l(1037)][l(1526)+l(395)],payloadType:F=this[l(1037)][l(450)+l(1448)],logIDNew:P=this._options[l(1560)+"Config"][l(1301)+"toGenera"+l(1757)+"ew"]?e.qDCds(i,this[l(1037)][l(1560)+l(1852)][l(1742)]):""}=e[l(462)](o,{});if(!S)throw new Error(l(1132)+l(966)+" valid s"+l(861));let D={SeqID:ge[l(613)+"er"](this[l(1321)]++),LogID:ge[l(613)+"er"](p),service:S,method:y,headers:R,payloadEncoding:e[l(857)](M,Object)?M[l(660)]?M[l(660)]:"":M,payloadType:e.owtne(F,Object)?F[l(1494)]?F[l(1494)]:m:F||m,payload:f,LogIDNew:P},B=e.OpItT(Kt,D);return this[l(1298)]&&e[l(1202)](this[l(1298)].readyState,this[l(1613)])?(this[l(1298)]&&this[l(1298)][l(764)](B),this._debug(e[l(430)],D)):this[l(1786)+"Queue"][l(516)]<this[l(1037)]["maxMessa"+l(653)+l(1267)]?(this[l(1786)+"Queue"][l(1302)](B),this[l(1101)](e[l(706)],D)):(this[l(1786)+l(1726)][l(965)](),this["_message"+l(1726)][l(1302)](B)),{seqID:this._seqId,logID:p,logIDNew:P}}}async reconnect(r){let o=t,{url:l}=e[o(633)](r,{}),f=Array[o(1085)](l)?l:e[o(1640)](o(439),typeof l)?[l]:[];r&&Object[o(980)](this._options,r),f&&f[o(516)]?this[o(625)+o(883)]=new Ll(f,this[o(1037)][o(1276)+"es"]):this[o(625)+o(883)]?.["resetEnd"+o(1590)+o(1721)](),this[o(878)+"sCounter"]?.[o(1707)+"nter"](this._options["pingLoss"+o(336)]),this[o(1580)+"osed"]=!1,this[o(1298)]&&e[o(1220)](this[o(1298)][o(449)+"te"],this[o(935)])?this["_disconn"+o(716)](1e3,e.VeImp,!0):(this[o(400)]=!0,this[o(643)]())}async[t(1144)](){let r=t;!this[r(643)+"Lock"]&&(this["_endpoin"+r(883)]?.[r(1278)+r(1590)+r(1721)](),this[r(878)+r(1319)]?.[r(1707)+r(1076)](),this[r(1580)+r(698)]=!1,this[r(400)]=!0,this[r(643)]())}addEventListener(r,o){this.on(r,o)}[t(1227)+t(1283)](r){let o=t,{type:l}=r;this[o(1387)](l,r)}[t(1248)+t(943)+"ner"](r,o){this[t(1039)](r,o)}[t(454)](){let r=t,o={sJYfg:e.VDLvX,UuocM:function(l,f,m){return l(f,m)},rTwGA:function(l,f){return e[G(857)](l,f)},YSsRD:function(l,f){return e[G(1766)](l,f)},GJWIk:e[r(856)],cpRBn:function(l,f){return l(f)},YxfoO:r(1850)+r(809)+"s",efPEr:e[r(757)]};return new Promise((l,f)=>{let m=r,y={Vjjsu:e[m(1701)],iSzPR:e[m(1660)],kRPWc:e[m(757)]};this[m(1461)+m(1262)](),this._pingPongTimeoutId=setTimeout(this[m(1698)].bind(this),this[m(1037)]["pingInte"+m(1632)]);let S=()=>{let R=m,M={OxtBj:o[R(1622)],SBdui:function(F,P,D){return o.UuocM(F,P,D)},AtdZk:function(F,P){return o[R(524)](F,P)},bsJGN:function(F,P){return o[R(1043)](F,P)}};if(o[R(1803)]!==o[R(1803)]){let F={qRwQU:kMqPUX[R(1877)],aKiZr:function(P,D,B){return P(D,B)}};if(kMqPUX[R(721)](_0x2016a5,_0x2e23ea)){let P=_0x4b4591[R(1524)].slice(_0x1be702[R(1020)+"et"],kMqPUX.bsJGN(_0x1f4238[R(1185)+"th"],_0x3dcf20[R(1020)+"et"]));this._socket&&this._socket.send({data:P,fail:D=>{let B=R;this[B(1387)](kMqPUX[B(1877)],kMqPUX[B(1304)](_0x2b0b56,kMqPUX[B(1877)],{message:this[B(1183)+B(1316)+B(567)](D)}))}})}else this[R(727)]&&this[R(727)][R(764)]({data:_0x2c3b78,fail:P=>{let D=R;this[D(1387)](F[D(1533)],F[D(1787)](_0x28beef,F[D(1533)],{message:this._formatErrorMessage(P)}))}})}else o[R(322)](l,R(484)),this[R(1039)](o[R(1792)],S),this[R(1039)](o[R(661)],p)},p=()=>{let R=m;f(y[R(1045)]),this.off(y[R(1735)],S),this.off(y[R(994)],p)};this.on(e.SKRDa,S),this.on(e[m(757)],p),this[m(1698)]()})}}})(),Ge["CustomCl"+U(1077)]=Me[U(1821)+U(1077)],Ge[U(673)+U(327)]=Me[U(673)+U(327)],Ge[U(1206)+"e"]=Me[U(1206)+"e"],Ge[U(1283)]=Me[U(1283)],Ge[U(1375)]=Me[U(1375)],Ge[U(320)+U(1328)+"vent"]=Me[U(320)+U(1328)+U(947)],Ge[U(1328)+U(947)]=Me[U(1328)+"vent"],Ge[U(1626)+"t"]=Me[U(1626)+"t"],Ge[U(479)+U(1882)]=Me[U(479)+U(1882)],Ge["createCl"+U(1077)]=Me[U(786)+U(1077)],Ge[U(1656)+U(327)]=Me[U(1656)+"rorEvent"],Ge[U(1218)+"ssageEvent"]=Me[U(1218)+"ssageEvent"],Ge[U(1581)+U(1062)]=Me[U(1581)+"enEvent"],Ge[U(1402)+U(1179)+"vent"]=Me.createReconnectEvent,Ge[U(927)+U(1442)]=Me["decodedF"+U(1442)],Ge.encodeFrame=Me[U(603)+"ame"];function ga(){let t=["BunTALu","DxfVqve","zLfzvge","ntC2mZzhzfLXyMW","wKfdtMC","AwfQu3q","Cvj3uvu","B25Uzwn0Aw4","zgP2t04","sLrOCxu","C2vYDMLJzs0","sfPXAxu","Ee5qAhu","uu9Qu3i","x2DLBMvYyxq","qKX3y0C","B3bLBKrc","vuDhCvq","rvDJuKO","vhD0uNa","vNffy3a","zwTfzvG","qKXACxy","yxrLq291BNq","CuX3CxC","B095Chi","tuTgzMK","EMD2rNy","AgndzNe","DgDcrKm","wKDWDfy","tg9AwNm","EeXlrwK","Bg9NsurozxC","vw5PBxbSzw0","zvfpA1e","u1f0uhy","mZe5mJi4mMLhCezLAq","t0zWt3a","y2HnyxHdB3u","vKrmDLG","ue1kEeq","C2v0zgi","x3bYB3rVy28","DgrKr1u","x2nSzwfYvgK","su5tvefova","ugX3sgu","B2zMC2v0","thfRyKy","AuHTtKu","tuT5u2G","tLrIEMK","x3jLywr5q2W","y3jLyxrLt3a","yxGGCMv0CMK","B2nRzxrtDwm","BwLZzq","x194x21Zz18","zhbXALi","B2LUDfjLywm","wvPxBhK","yNL0zxm","Cg9PBNrdB24","AwDHDg9Yt24","AevJAgS","Eg5bBwy","y3vYC29Yx2y","EKHUBNm","ign1CNnVCIa","D1nJzhq","zw5KCg9PBNq","CMvZB2X2zq","z2v0s2v5","r1LiC3a","C1PgCMe","B25TzxnZywC","C3bSAxq","Dg5Ouxy","rvD6zuK","qK1vA1y","uMjHr1e","AuPVrvC","DhnYwge","B3vmtwe","uxnltxC","t1bftG","D2LSBfjLy28","q1LNu08","qLnUB1i","vK1NBM8","C3vIC3rYAw4","rNzovMW","AwXLtMfTzq","B1jKreW","C0PzzMC","AvDowxa","rfrVsMK","x3bYzwzPEa","t3bLBKv2zw4","t0TuEve","y2vZC0HHBMq","zKLpu1G","qw1Avue","Ec1TC2CTy3u","CNzHBa","A0rwBvu","zw5HyMXLuw8","ywr2yw5Jzq","sKvmDMK","rNHts04","rKLotfG","BKLYv0e","yuPkyMm","DuT4tLC","CKDwvLi","y2PSs28","AvjYuve","DurYEMO","s05xtve","qxDYAfC","x2n1CNnVCKy","y2vOrK0","CMvWBgfJzq","CKvgtLy","zgvMAw5Luhi","C3rLBMvYCW","zuLgD20","uw9lvM8","y3jLyxrLrxi","qwzAAu4","zxjHDg9Y","qMjADxO","u0Tsrge","Ef9MCM9UDgK","zgvSzxrL","ysbTDxn0igi","vgjxswG","y0nrsge","ChbL","BMrWB2LUDfq","ihjLy29UBMu","q1jizwS","q3nfANO","AvvRBwW","DNvMy1y","qNbVv0q","Bg93","BKPzqvK","ywzqAfy","u1LADNG","svDkEhy","EKP3CvG","r2jvAu4","wKLgy0y","BNfMvKO","C2DIB0S","B3ngtfm","zgvS","y29UC3rYDwm","tufyx1jfvfi","wLDLDgS","DLjls2q","y3vYC29Yx24","rxvhrKe","Afn2CMu","wMXPwvu","C2n3qxm","tuvtu0fhrv8","ywXSB2nvBNm","B3jL","x3bPBMC","s3bjCKK","ChjVDg90Exa","rKX6u3u","DgvZDa","Euf3yKu","wMPAsgi","r1nYwMS","EfrHwwC","CMvZzxrdB3u","yxrHlcbKyxq","tKrwzxm","ywnRx2nVzgu","Cg5VC0e","C3rHCNq","zgLZywjSzue","Dg9mB3DLCKm","qw1VDw50","v2PAwxu","uufZs2W","D3jPDgu","tenvq3a","yMfJA3vWigu","zMLN","AenSB3nLrxy","CKPTyvi","BNruCMLLC0m","q0TlA3i","uxvLDwu","wxHnv2u","CvvmsMG","ENLSDwu","ywPnEwu","CKzguvm","s1nirLG","DgfIyxnL","v2L3A3i","Avn6ufi","zu9WD1y","y3jHwvy","we5Vyuq","swjLCeC","Aw5N","AwrI","DxnLCKLW","ufDyEeO","AhfNr2m","v3f4vvq","ChzXDM8","BwvZC2fNzq","uMjwBfy","tuPJDgm","tgzsu0K","A2nwB2O","x2n1CNnVCK4","s3bptxu","y3vYCMvUDeu","zw50zwqGDhK","B25pCgvU","DgvmB2Djre4","Cwv0qwK","Bhm6ia","y29Uy2f0","svPeELe","AwrRAwW","ywrKq291BNq","EMnXANC","sgPiAwK","C3HKufy","B25nzxnZywC","BIWGAg9ZDg4","y3ruAw1LB3u","AuHKrva","mJu5mLbOAfjSsW","DhDeufu","r2H0r0S","C0jf","x2n1CNnVCK0","x2LZv29YA2u","B3fOqNa","q0vwEgC","CgLUz0LUDgu","x2XPC3rLBMu","uKTkue4","v1z6DgK","AgLNAa","sNHuz2O","CNzHBfzHBhu","x21LC3nHz2u","yuTPwNi","qMvrDNi","x21PBMLoyxy","tgHJzeW","sLHnA0S","wxHMB08","Bg9Nsurhzw4","DMvYC2LVBG","ywrKrxzLBNq","tw9KDwXL","rhHfDxm","B25VCgvU","D0HVBMO","yNLL","vxbKyxrLq28","Cuf1t3e","r0PxswS","Ag51y0S","wvfHs0G","sevNwM4","ExjWqNG","mxWWFdj8nxW","uvrbteG","qvjPshi","D3DACgq","mMnvEvrvwG","AgfZ","wMjstuC","txnfqKS","uxnyuuK","uKrWyvK","DMXhyNO","CMfUzg9T","z2v0u3rVCMe","q3vZDg9Tq2W","q09oveLovuu","zxHWB3j0CW","q25syMW","zxz3B00","CMvZzxruCMK","rKPYyw0","uuHYAfa","rvjst1i","v2zVr1q","CgLUz0XVC3m","vLPvve8","DMngCva","rwv5t00","C2nYAxb0","uKnzvhC","q29Kzq","DeXNu0C","AvvhD2u","Aw1IC0W","D3b4vgq","y1DrCK4","n3W1Fdz8nhW","AhbjAg4","icSG","DePstue","veDvsNu","t1LUthC","vuX5D0q","CgLUz19VBMm","EfP1sMC","q29UzMLN","rwrsu3e","Aw5JBhvKzxm","Bwu6ia","s1jiuvq","sNrzAgO","CMvQzwn0","vfjrtKS","ugLHuNm","BwvY","mxW0Fdb8mNW","we9vqNe","CfPoz1e","B25tDg9Wsw0","yxnHAhm","aaaaaaaaaaa","Dw50","ywnRtxnNswq","Aw47y2HHCNm","t2jQzwn0","s0HHweq","B2XKvMvYC2K","z2vtEw5J","qKfUuLO","DuTsuM8","t3H0qMO","CgLUz1rPBwu","DgLTzw91DcW","AKDbu3m","tu1UALy","Dev2zw50","v1Dnuee","vMDPBgS","ndCXnJmXm3fcCuf2Ca","zKD5v3m","ugHMvgS","AxnszwfKEq","zNHhq0O","rNjVBNrPzxi","r3nRueG","y3bsqM4","DuLQA3y","t01JvNy","u0THsfa","zcWGDw5RBM8","CM9YrxzLBNq","y1P1rLu","x2rPC3bHDgm","Dg9Y","uhjPBwfYEuS","vKf6D0y","v29wueO","BNrfBMrWB2K","sM9sr2O","q291BNq","zxjYtM8","tKjwAeu","rg1dEhe","u29Py0K","mdaWma","x1fVu01HBMe","x3jLy29UBMu","Aw50zwDLCIa","v2vIu29JA2u","vvjfD04","x2LZqNjVD3m","thLesLu","Ehnbz28","C2XPy2u","igzPzwXKoIa","BhbJA1G","BxLuD3C","vuHUquu","igzHAwWSig0","zNjVBNrPzxi","wg9brM8","y3vYC29Y","DNvqvuy","AevYCM9Yrxy","DxbKyxrLq3u","zgDkCLK","BMrLEa","AgfUz2u","Aw5L","txPTA24","tgrZEKm","C29Tzq","wKf0rve","wfzXz3K","zxjYB3i","Cgu6ia","ywjktg0","qw55y0G","rMfHruu","BMv3vMvYC2K","vKXAvvK","twj6ruO","CMvJB25Uzwm","BwnNyMq","DgLTzw91Da","zxrxB3jRq2G","D2vI","x3DHAxq","DgXds2K","CvH6DLa","tKDFrvjst1i","shHJCK4","zKHYAKO","ELbUwhG","AxjwANu","yMfSu2nVCgu","x2LZtwLUAvq","C2vYDMLJzq","BMnVzgLUzW","zxLIwxm","t1ryveu","AxmGDw5Kzwy","q1j1t1e","x2LZsw5PDa","BLvqv00","AfnyzKm","zfjgrvK","s0jIyK4","rg5htfe","BgLUzw5V","zNjVBuj5Dgu","y1bmsfK","y1vyAgG","tg9JAW","vxnfq2q","Aunhwg0","tLH2AK4","vfn1vKi","zg9Uzq","mdaWmdaWmda","t2XrCeq","ALzPyKC","rLLAtuu","AK50DMe","sLvRuvm","sLnptLa","sKr5zLO","CM1KrxC","mhWXFdj8m3W","qujougu","CMvZDwX0","ChHct1K","qu96ruW","u21zy1i","sgvlsge","u2X4sfq","DxDUCee","rNj6Ew4","AxnmB25N","yND1q0K","B2fK","s1HHA2O","C3rYAw5N","ANvRruS","quLItxG","twLZC2LUzYa","whnsBMW","B25SAw5L","DhjHBNnHy3q","D2vzwNO","BKnnrvm","u2f6r2u","CMvHzhLtDge","Cgf5Bg9Hzfq","CLzHBhvLCW","r0T5se0","zLPfq1u","CgLUz09Uy2u","x2fKzfDZtgK","wwr1uMS","x0vysvnu","t1bftL9fuLi","s1Ppyw8","AMXPyLe","jMPZy2fSBgi","zMLYrM0","vLzNrvq","DKLbDuC","BKnuqK8","ChfMtgC","zgf0yq","D3fiy3a","EeDMrhu","zMDbEeW","zePotK0","EgnmqKq","BMfTzq","uLjpuG","AxnrB1nnzxm","l3DZl3yY","BxnNsuq","nhWWFdn8mNW","uMvJB25Uzwm","vLjlB2y","zhrtvgi","DfLvyKK","zMX1C2HfEha","C3vJy2vZCW","Exbfwwe","CgDrv0i","ywWGy3vYC28","r3jVvLy","CLfsDgm","CerLzwm","DhjPzxmGCMu","B25ozxr3B3i","ELPOz1u","B25mAw5L","y29UBMvJDca","s05yC3u","AxPbtxm","uu5Qyum","B3bLBG","EsbJBg9Zzwq","seXKzM8","Ew9nsgq","rgH0tgG","v1nJshy","CMvUDevUzha","x3bPBMDqB24","x29Uq2XVC2u","ChjVDg9JB2W","zwfYExO","v0TWBNi","veHxu1q","DhDVCMTdAge","wvrzvuy","vKfUqwu","sw9iywm","BgvUz3rO","z2v0t3DUuhi","pxv0zI04","y3nJDw4","wKL3vLi","zM1Xzhe","sgDht2e","zeXgvNO","CLr3r0e","x19LC01Vzhu","BNvTyMvY","wMX0Eha","uuH2sgi","t0foB0O","DK1Vq0K","zKfODw8","CNnVCL92ywW","z2v0sxrLBq","BxvZA0C","shHxu0e","DM5lswC","x2LUDgvYDMe","q0f2quK","zgvSzxrLrge","A3DAsMS","ALfeq3y","yxKSihrYEsa","D3jPDgvvAw4","BwfUDwfSihi","sgDgBge","yMTzwva","Dw5KzwzPBMu","yxjYyxLIDwy","Dw5RBM93BIa","tgXVyKq","wNjZBgi","A3nZvfa","x29UtwvZC2e","zu1AELa","yw1LoIa","DuLruvm","r2LrCfe","uKr1zge","AuPKteS","Dhj1y3rVCIa","y3vYC29YlNm","wvjTuhC","s1fxENy","CgfNzwHPzgu","sefusgq","CMvXDwLYzwq","ywDL","suv5DNe","tfffC2G","qMrdveG","uwHqEgm","wMPowxq","rKjyy3O","EePSv2m","BM5Ly3q","whn2CfO","sxn5vgG","A1r3twu","CwH6yuS","uvfUAee","A0r2yvG","x3nLBMrby2S","tu91zgy","BfrPBwvVDxq","ig1LC3nHz2u","r0jVwgy","rKLewgC","ywrKt25L","teTjz2G","C3nZthG","vhjjwgm","wNHPtKy","x2LUAxrqCM8","tuP0uhm","ywDLsgLKzq","DNHKB08","vuvhrwy","q0Xpu0LorW","BKfgr3e","wM9KC2i","ywrK","AgvHzgvYCW","zw5JB2rLrNi","Aw9Ul2PZB24","Dg9iyxnO","D3vrDxu","y3HmwLG","EfPQz1e","rLruC3y","qLDRC0K","sfnWsgW","ueDjq1y","zNjVBu51Bwi","ELnPwhe","r3PhBum","ExDbzuO","id4G","ywDLu2HVDW","qNL6yui","v0TVshK","CMvWBgfJzui","y29ICvi","Exzuu1O","rvPyz3O","x2vUzhbVAw4","q09otKvdveK","qwXTyNq","BvzNyvK","qw1tDhK","A0vMte8","Dgv4Dc9WBge","Aw5KzxHpzG","AfzAu0e","AuDStfy","C3rVCMu","ufLgtKy","ihrVihjLDhi","zM9YrwfJAa","uwPWsvm","u0n5sMW","y3vYCMvUDeK","tKLky3m","x2nVBM5Ly3q","DhzqsgO","te5RAgu","qLfSu3m","u2vpB2m","AfjwEfK","CLDSrgC","q0H5wwC","C2v0","t0zjuK4","z2vrDwv1zuW","sgLTCwi","x2LUAxq","BwvZC2fNzv8","we1Jt3O","BK1msLa","yvr5vfO","zw5JB2rPBMC","zwzqrxi","r1D2wK0","t0HrtfK","Ae9Wzw5fDMu","z2vgwxK","t1Lfsvq","mtC1mJy0ohPeBxvHuG","v2LUzg93","t0DbBxK","tw1xrMu","zeHctuG","Affdsuq","q3vZDg9Trxi","yNn4uuu","DgnpzeG","BNPIvxi","zw50","yxbWBgLJyxq","tgf5qMu","CM92AwrLihy","yuzPDuK","uuXjCuG","tgDtB08","v2XRz2O","thzhEu4","ChfWAhC","CIb0DhDjra","x2rPC2nVBM4","zwLOs1i","B3v0sw50zxi","AgfHtge","vM1NEei","CMvKDwnL","y29UBMvJDgK","rKrQsu8","A0PSzMC","rLnezfi","B3nLza","vgvdDfy","tg9NsurozxC","BMrWB2LUDca","sM15qwi","tg9Nsuq","t0HfuhK","y2uGBM90igK","Bw9yAge","rgXhCuO","y2HHCKnVzgu","vhrhrKe","zMLUza","BMnLq2XVC2u","z2vjBMzVu3K","rgL2wNK","zxjFAxnFywm","yMXVy2TLza","zwn0","DfLxrLO","y3vYDMfSDwu","zMXVB3i","y2HLy2TdDxi","qxrKwMS","rfDMCwK","zcbLCNjVCI4","B3jLtMfTzxm","ExHvue4","AM9Sq3m","x3nVy2TLDa","t3bWquy","A3voteq","Aw9UvgLTzw8","ug1OEeS","uePbtKq","y09dsxO","CvfJsgK","ywH1uxa","wNDTsg0","D2fZq2XLyw4","yLHwrwu","v1bpzKu","reD6BMW","CMvJzwL2zwq","wfDlt3q","x2DLDeLUDgu","r2jluKi","CMr1u2i","DgfYz2v0","uvf2Cw8","se9rENi","C2v0u3rVCMe","vgLTzw91Da","DxrMrgC","C2v0sxrLBq","B2jQzwn0u3q","Dg9oDw1Izxi","B3bLCNr5","C1nXDxe","B05yuMC","tMzABha","yw1Lu3bHy2u","y2XVC2u","zwfZvxy","m3W0","z2PiCei","C2vUza","B1fOBMC","reffzLi","rxv5t1a","y2fSBa","y09Wzw4","B25LCNjVCG","AurZtem","zwrPyxrLBhK","sM50Dhy","BgLZDgvUtMu","zgjUrMi","suTvtLm","Cg9PBNrbBMq","Dg1Usfi","EeDYCeq","BgLTAxq","vujgs3O","qwjVCNrfCNi","AwXSihvZzsa","DgfPzeO","u01jtKS","y3jLyxrLq2W","tejztwK","z1ngzgO","s1vSzMi","r0Drvey","y2HnyxHuCMK","z21tsg4","EwTWu0O","uLvIy3a","yMT5z1O","ihzHBgLKigq","uwD0Dfu","BffUyM0","D3fis3O","Bwv0Ag9K","rvftswe","rKLmrv9ot1q","AwjMCwi","C2fNzq","uvL0B0i","CKTQquC","thnOD08","CvjIwgC","zv9ZDwnJzxm","C0Xf","sw9Tq00","nhWZ","tuLMAgW","yNL4yvu","C29YDa","zxHIwMC","AefJA01LC3m","y3r4","DxrMofDYAxq","B2v5wvC","BM54Chu","C2vUzf9Hy2S","ENDrzhi","DhfMDgK","zgv2AwnLx2K","uhjnsgG","C0rdzg0","Bg9N","z1LWre8","wur1t1a","tgDwB0q","BhrPCgXLihq","yvnpAfu","A3zotKK","DNjVAMy","u3flDuO","DMLJzuLeig8","yxv0BW","Dg9cExrLC0W","yurftuO","Cgf5Bg9Hza","v0HREgy","shn5zK4","s2LkBuS","ExfYtue","A2Xov0m","x29UrxjYB3i","x2nYzwf0zvm","rg5cyxK","CYbWyxjHBxm","AwrezKm","CM92AwrLihC","vgfXqwu","B25fCNjVCG","ruDdrNa","re1hs3i","rgPvshG","BKXNtxG","B25tDgfYDfi","u2LUswi","zxj2AwnL","Duj4ANC","Bg9IywXty28","x2jPBMfYEvq","Chr5qMm","BMCGzMfPBgu","DNHoy3y","vLvvuKe","yxKSig5LDhC","x2LZtwLUAvC","zNvUy3rPB24","uwXQyvC","sxDHDLG","ruLKqwm","ywjVCNq","refTAgy","zMzMzG","x3bPBMDmB3m","wunHzKq","zNbrufe","EKHWsKq","CgHHwMm","De1HBMfNzxi","ywXPzcb1CMW","swD5v3u","BNfTEgW","x25HDMLNyxq","Dg9cExrLCW","zu5KAwq","B2nRzxq","re5XChe","Cg9W","CKjnzxO","rLLiEgC","ihrPBwvVDxq","vwrtDMK","Dw9Aq0O","DhjYsLa","DNLzteu","yMLUyxj5","zM9Yy2u","uhvqsM0","y1npvNi","rhffCK4","teTIvuC","y29UDgv4Da","C2v0y3vYC28","Ec1TC2CTCw8","vNH2CeC","uxneuxa","Dg9VigXHCMC","EKDnqLi","DMvYC2LVBMm","zwnVBM5Ly3q","BuTnEKC","C0fSrw4","svzrs1a","y29UBMvJDfm","zxfVuhG","D3rKrKS","x3fVC0rc","rKnytxa","CMfMAeS","txzxqKq","BwvZ","tgPYz2e","zgvJB2rLzey","wKjgyM8","tfH0uve","Chv0","DvnXthK","qxnJDKS","DxrVuMvJB24","x2HHBMrSzva","q0Xpu0ve","qKTYtwG","wKLUBLu","ihrPBwvZ","DxLdzxK","sgrJzMq","zxjFCw9Zx2e","y3vZDg9Tshq","zw50tgLZDgu","yw5ZzM9YBvq","A2v5CW","DeLK","DMvUDa","Dw5ZAwDUzwq","A0PqueS","AMvJDfn0B3i","uLzUwva","B2nRzxrgywK","CMHlrKi","EfnyDhG","Ae1LC3nHz2u","C2fPwLO","CNzzyuu","ywnRDxbfBMq","BM5nrxq","rfvrz1q","svvRCva","yMHnwNq","A2Ljq2C","zMzLCG","C2HPzNq","CM92AwrLige","DNLAyNO","y05HBwC","suLkEwy","AfvWAfa","Dgv4DfbHEwW","ELDvA2G","y2XLyxjtDg8","AfHMv1u","Euj6ChK","swP5Bui","zxf1ywXZ","DvH2tLy","sgfjr0u","yxnZAwDU","C3rYAw5NAwy","twHOEwq","x2HHBMrSzvi","B25dBg9Zzq","B25szwnLAxy","DMfS","ChDRsLG","CgfNzxnOB3C","AeXHC3O","whjNuxG","ueLtufe","B1rOB1m","zxrjz1a","A1jqv2m","x2LZtM9Kzq","z2vY","BM1cCfu","Dg9cExrLC0i","x2HHBMrSzu8","De1etfG","sfz3tuG","AwXLx25HBwu","ueTrA0y","zxH0ugf5Bg8","q3nZtfC","t1bjuxG","Ec11C2uT","EKDbsuS","C2vYDMvYvgK","vw5Oyw5KBgu","AfrIAxO","u3rYyxrLz3K","wMLrvKu","ignVzgu6ia","BM93","mxWW","v2z3D0W","uwHfzfi","EwLHt04","yNL0zu9MzNm","A1rkB2y","uLzzrKm","qNrvyvy","DcbSAw1PDa","B2zMBgLUzq","t0LREg4","ANLWCKm","B3jRig9MzMW","Cefsvuu","C1buChC","yMfzzM0","v2v2t0y","B25JBg9Zzq","uMvHzcbWyxm","yw1L","yxbWzw5Kq2G","x29WDgLVBNm","vwnTEK4","B2zM","qNLRB3m","v011ELq","rgvQDeK","wvnZuKq","y2XLyxi","vMPQC3u","BwD4r2K","v2jlsxC","C3neBg8","ywXty29Wzq","x29UugfNzu4","qMXYv1e","rvDHv0q","CfLsB2q","we9TC20","nJiWodCZnwreCNr5rq","qKz4AxO","BML0AwfSAxO","C0XPC3rLBMu","yxbWBhK","A2v0ignVBNm","AMncs3C","zw5fDMvUDa","EwTYEMq","CgvYC2LZDgu","B3jRwMO","rvnmqw0","q2TIzhy","AKDRAfa","Aw1LCYbPBIa","uvD0uwS","zKXPzfy","yMfSrxzLBNq","quXm","C1PYvhC","CvPXtuG","BNrLCG","B3nLrxzLBNq","yvHmvwK","EhrjCNi","y2HLy2Tszwe","vNjRDKm","Dxf6s2K","igfYCMf5yNu","x2LUAxrhBg8","AxnbCNjHEq","CKHkvhm","C2vUDa","uxnkAw8","DNjzy1i","q3nMvwu","suvtx0vsuK8","r2f1vue","BevIA0W","sMnqyLK","z2v0qwXS","q0fUsvq","wwHJwuy","z2u6ia","y3z3ru0","BMCGDxjSoIa","x2rLyNvN","teHxDKi","rKvrDvm","runmBKS","CM92AwrLigi","C2nJsgS","CMTJCLa","sLndDKq","D24GCMvHC28","tuDPvKC","t1H6q3e","whHMww4","v21er1K","yLvhquy","qNjPzgDL","C2v0q3vYC28","weDVt2q","yxnJCMLWDa","y3nQyK8","Ahr0Ca","EgXty1u","txPYr0y","z2v0q3vYC28","DgDowwS","DgHHBIbSB2m","vMXiEKG","y2jQy3u","BgvY","ALngEg0","Ehjxu2S","EfPwr08","CgXLyxnLiha","CMTLCKDSB2i","D25itwm","zxjFywnRx20","rKHzwLq","txvKsuW","CeX1sNO","DhjPzxm","BLjqugu","y291BNq","y2PYrKm","qvrjDvu","y29UBMvJDa","zxr2tKW","y2XVC2veqG","zw5HyMXLvhi","y3nptfO","sfz3yuG","z0HhsLm","B1zPvhi","Aw5PDcbrB1m","BKXPBMu","BxnN","r09Zzfu","zxjYtxnN","t09byM4","q1rbDLK","ChDUr1u","tKfusvzfx0u","ANPTBe8","re5rDhm","t3LKv1G","x2rItMfTzq","zxH0zw5ZAw8","x2rLC3rYB3K","nZuZntCZnKDNqu5XBa","rMzbuvu","zufJAW","CMvHzfvjBNq","ufHPEuy","thrbzMy","zNjHBwvuExa","zeL2wLO","BgLUzq","tNf4whe","y29Kzq","CMvHzhDYAxq","y29UBMvJDeu","tw1quKy","zvLvreG","B3bLCNr5tMe","x2zVCM1HDeu","Dxrjza","yNL0zuXLBMC","qwrStha","ywDLrxzLBNq","rfbPA1u","zu9stwe","y2XVC2uSihC","CfjQExK","CgfYC2u","DxjS","qNbku1a","su1ovLa","DeLUDgvYy2u","ywXSq3vYC28","uK5mDhK","yM9KEq","AxPTrNa","D09LqMS","A3rKA3i","y29SBM8","zNDZxZeUmc4","A2v5","rxjYB3jdB2q","DNDouei","tLLltxK","CMvHC29U","Evz5vwC","DMPVuM0","yMLUyxj5vhK","zvvYBa","ywX3yxLZ","BMvLzf9Hy2S","BMCGB3iGyw4","Ee5ywNe","y3jLyxrLtwu","swL4uxC","AuHKAKW","rfnPruK","AKDbsxi","DhDerhq","mtb8oxW2Fdi","y2f0y2G","zgvIDwC","zgLZCgf0y2G","zsbHihn0CMK","rxLtD3q","BwrUD2e","t3bjDfq","qvbJzwy","uK5VtNG","mhWYFdv8mxW","D0zvywi","tLLnuwC","CuDnzg0","u2rZrLO","s3PHD0u","zxb5Dfu","zMvY","tKT6zK0","DKfdve4","wfLiAwS","zxq9DxrMltG","Cw9Z","tMfTzq","CMvTB3zLrxy","x3jLBw92zvC","zfDVCMTLCKC","CMv0CNLdB3u","BezSDxnO","AxnrB1nby2S","AxjLza","tMXQEeW","z1HYCxG","qKLPu0q","uMfWzxm","A2jSv1i","revSDfq","wLbzrxK","BMDuAw1LCG","D3nZoI8V","rff2r0e","zv90Aw1LB3u","wMrcCgu","zw5NDgG","Aw5KzxG","ChrVCG","r3fztuC","BNPky2q","AxzoEKO","yK1Wvue","z2v0q3vYCMu","lcbOB3n0BMe","Bwf4uMv0CMK","EvHzCha","CMvZzxrfBMq","zw5XDwv1zq","sfrUs1K","z2zbvLy","Efrurw52","rxzLBNq","DM1wqM4","yKvSwNy","z1rPBwvVDxq","ywnOzwq","wxj1sxa","wfHOvKu","ywnR","END3yvy","CNnVCL9Uyw0","zxjFCw9Z","m3W0Fdy","v05bAMe","BfHovMy","BLbPyNK","x3DZ","wwTLCxy","tM1hwxO","zw5HyMXLqxu","ChvZAa","CgjICdi","u0jKDwK","vvjrz3O","ufDuAgm","C3rVCcbPBw0","tLnVr3G","u2vXsuq","z29PBMCGyxC","Cvbmuvy","rxj4zwO","tvfIrLO","shDbwuW","qxDHr24","CNjVCK1LC3m","BKT0whK","Fdr8mtf8ohW","C0nVDw50zxi","CfjwC3y","x3nLCuLK","zMzmAw5L","yxv0B21HDgK","AM9PBG","tLLUqMS","BLHlyxO","DgHLBG","twvZC2fNzuu","B0PPsfu","ywXS","uNzbseu","Bwf4tg9ZC0m","Cvvwquq","swnfAgS","uwnst0C","mtm5otC3nurXref2vG","wMnTrwG","senbzKS","DMfSDwu","Cfz1rvO","s0vfAvy","CfvVyKq","BeHHBMrSzxi","AvzIyMm","BMvJDa","Dxfpr3u","B3vUDa","wuDMDeG","zcWG","zwvKzwq","rermuwO","u3zwwu4","zMLSDgvY","uxzhEfO","rw9ss1q","B1Lfuui","x2rYB3bhBg8","AhHrExC","yMLUza","BgPAt2q","y29TCgXLDgu","rKjpEgG","CMLLC0nVDw4","zvrOr1q","DuHwCg8","v1Dvzw4","CYbHBhjLywq","t0D5ALq","qLHnBNK","sMjhwKq","vKPoEeu","zNzPC08","tM5zB08","s1Drve4","rLDt","zefkD2q","CLzOrNq","zNzXrvC","BwvKAwf0zwW","zM5PEuW","qwvtBeK","zMLSzw5HBwu","AuL4DgS","tvzzu2i","B3jpBMXPBMu","Eenosfi","zw1PDa","v0rrrgm","Cg93","BMvY","uu9ewwy","zxmGCMvHy2G","EfnprgG","weDruMS","uxnozxy","B3bLBIa","B2fmwKW","DMfSDwvZ","uMnqseO","DefmzxO","wNzAyKG","y3jLyxrLuMu","Awnir0y","DvjnCMS","x29Ut3bLBG","v0HVqxK","zujeu0W","yvLLvwe","B3rns1i","x0rctMfTzq","v3LnuuK","svf0z0y","t1HPA3u","zxjFDhrS","r0TKvu0","Dgv4Dc9Qyxy","DhjPBq","tuPuv2q","s3v2Chq","CLnbqwe","zMTyr3O","wMruDMK","B1j6z1C","DgLUzYbZzxi","EwjHwhq","suXIzhe","zxjFBxnNAwq","u0fctum","x2TLEvbHDgG","rLLwthy","ywzL","AgvKtwf4uMu","ihn1y2nLC3m","uMjsCMy","x3DZsw5ZDge","vMTJtLu","yNvMzMvYzwq","BMDLza","mxW5Fdz8ohW","EvjLy29UBMu","sMnoCMy","CMfTzq","AgfZt3DUuhi","sgfSsg8","AwXK","zKDHALO","yvrJy0W","ExbL","tKjzBgK","z1LUqMm","zNfrAwO","vhrrquC","z3bqDMO","ENr2q28","CNnVCKzPBgu","uuj6v2m","x3bHDgHlzxK","CfHJCNm","r21lsfi","ihrYEsbYzwm","x2nSzwfYugK","uMr2B2G","zNjVBunOyxi","q0TKs1C","CgDmDKe","s3vbDge","uNb2t24","vKHXEuS","C09rvhC","EuTRruu","lcbTyxGGCMu","r1zqBw8","rgLOq04","vgfN","ywnRpwzYB24","rKvmz1K","yujmCum","z2v0","x3vYBa","EMX4wei","reiGzMfPBgu","wwfYtLy","C0Dxzhe","CMvTB3zLq2G","zNLbAKi","BNrbBMrvCgq","zK1tvxG","wfj1Eg4","Dg9tDhjPBMC","BhfvvLm","wMLjzgW","A1b6C2W","r0DYEg0","DhLWzq","BeDXz0O","uujxEg0","Aw5Lza","yMXjqui","C3vIyxjYyxK","tvHpBLy","yw5Nzq","Aw9U","sffTvhC","CMvHzg9UBhK","wNjwwge","rfnou0m","x29UvgLTzw8","uhDizeW","zNjVBujPDhm","ugLZy3i","wKLKBM0","BKv6AKS","s1HHs2C","BNzjwwW","tNHAveS","BwvZC2fNztO","DLfzwM4","tgLZDgvUzxi","yMrFzgLK","A0Pevgq","r1D3Bw0","yw5Hz2vY","yxnL","yNvMzMvY","zLndz3e","Cgf5Bg9Hzeu"];return ga=function(){return t},ga()}for(la in Me)["CustomCl"+U(1077),U(673)+U(327),U(1206)+"e","Event",U(1375),U(320)+"MessageE"+U(947),U(1328)+U(947),"OpenEvent","Reconnec"+U(1882),"createCl"+U(1077),U(1656)+U(327),"createMessageEvent",U(1581)+U(1062),"createReconnectEvent",U(927)+"rame",U(603)+U(1035)][U(632)](la)===-1&&(Ge[la]=Me[la]);var la;Object[U(1652)+U(755)](Ge,U(525)+"le",{value:!0})});import{existsSync as Y1,openSync as X1}from"node:fs";import{mkdir as Q1}from"node:fs/promises";import{dirname as eI}from"node:path";import{fileURLToPath as tI}from"node:url";function rI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function fl(t=J()){return Y1(t.libEntry)?t.libEntry:tI(new URL("../index.ts",import.meta.url))}async function Rp(t={}){let e=t.paths??J(),n=t.entryOverride??fl(e),i=rI(e,process.env.COZE_BRIDGE_LOG_MODE);await Q1(eI(i),{recursive:!0});let s=X1(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=ct(process.execPath,d,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[ms]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return nI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var nI,ms,ba=st(()=>{"use strict";tn();ne();Ce();nI=K("spawn-daemon"),ms="COZE_BRIDGE_DAEMON"});import{spawn as eA}from"node:child_process";import{mkdir as tA,unlink as nA,writeFile as rA}from"node:fs/promises";import{dirname as iA,join as sA}from"node:path";function ai(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function oA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${ai(n)}</key>
21
+ <string>${ai(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function zI(t,e){return new Promise((r,i)=>{let s=DI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";s.stderr?.on("data",l=>{c+=l.toString("utf8")}),s.on("error",i),s.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ti,xs,ma,ul,zp=rt(()=>{"use strict";ie();ti=j("supervisor.launchd"),xs="ai.coze.bridge",ma=zI,ul={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function aA(t,e){return new Promise((n,i)=>{let s=eA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var oi,ys,ka,bl,tg=st(()=>{"use strict";ne();oi=K("supervisor.launchd"),ys="ai.coze.bridge",ka=aA,bl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
29
29
  <dict>
30
30
  <key>Label</key>
31
- <string>${xs}</string>
31
+ <string>${ys}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${ni(t.nodeBin)}</string>
35
- <string>${ni(t.entry)}</string>
34
+ <string>${ai(t.nodeBin)}</string>
35
+ <string>${ai(t.entry)}</string>
36
36
  <string>--daemon</string>
37
37
  </array>
38
38
  <key>RunAtLoad</key>
@@ -42,13 +42,13 @@ ${e}
42
42
  <key>ThrottleInterval</key>
43
43
  <integer>10</integer>
44
44
  <key>StandardOutPath</key>
45
- <string>${ni(t.logFile)}</string>
45
+ <string>${ai(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${ni(t.logFile)}</string>${FI(t.env)}
47
+ <string>${ai(t.logFile)}</string>${oA(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return BI(t.homeDir,"Library","LaunchAgents",`${xs}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await OI(MI(i),{recursive:!0}),await NI(i,this.renderConfig(t),"utf8"),ti.info("plist written",{plistPath:i,activate:r}),!r)return;await ma("launchctl",["unload","-w",i]).catch(c=>ti.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ma("launchctl",["load","-w",i]),ti.info("launchd job loaded",{label:xs});let s=process.getuid?.()??0;await ma("launchctl",["kickstart","-k",`gui/${s}/${xs}`]),ti.info("launchd job kickstarted",{label:xs,uid:s})},async uninstall(t){let e=this.configPath(t);await ma("launchctl",["unload","-w",e]).catch(r=>ti.warn("launchctl unload failed (ignored)",{err:String(r)})),await LI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),ti.info("launchd job removed",{plistPath:e})}}});import{spawn as UI}from"node:child_process";import{mkdir as HI,unlink as qI,writeFile as GI}from"node:fs/promises";import{dirname as jI,join as Up}from"node:path";function _a(t,e){return t.isRoot?e:["--user",...e]}function KI(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function ya(t,e){return new Promise((r,i)=>{let s=UI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";s.stderr?.on("data",l=>{c+=l.toString("utf8")}),s.on("error",i),s.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var wa,ri,WI,fl,Hp=rt(()=>{"use strict";ie();wa=j("supervisor.systemd"),ri="coze-bridge.service",WI="/etc/systemd/system";fl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return sA(t.homeDir,"Library","LaunchAgents",`${ys}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await tA(iA(i),{recursive:!0}),await rA(i,this.renderConfig(t),"utf8"),oi.info("plist written",{plistPath:i,activate:n}),!n)return;await ka("launchctl",["unload","-w",i]).catch(a=>oi.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await ka("launchctl",["load","-w",i]),oi.info("launchd job loaded",{label:ys});let s=process.getuid?.()??0;await ka("launchctl",["kickstart","-k",`gui/${s}/${ys}`]),oi.info("launchd job kickstarted",{label:ys,uid:s})},async uninstall(t){let e=this.configPath(t);await ka("launchctl",["unload","-w",e]).catch(n=>oi.warn("launchctl unload failed (ignored)",{err:String(n)})),await nA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),oi.info("launchd job removed",{plistPath:e})}}});import{spawn as cA}from"node:child_process";import{mkdir as dA,unlink as lA,writeFile as uA}from"node:fs/promises";import{dirname as fA,join as ng}from"node:path";function Pa(t,e){return t.isRoot?e:["--user",...e]}function xA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function Da(t,e){return new Promise((n,i)=>{let s=cA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Ta,ci,hA,El,rg=st(()=>{"use strict";ne();Ta=K("supervisor.systemd"),ci="coze-bridge.service",hA="/etc/systemd/system";El={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
52
52
  Description=Coze Bridge daemon
53
53
  After=network.target
54
54
 
@@ -59,10 +59,10 @@ Restart=always
59
59
  RestartSec=3
60
60
  StandardOutput=append:${t.logFile}
61
61
  StandardError=append:${t.logFile}
62
- ${KI(t.env)}
62
+ ${xA(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Up(WI,ri):Up(t.homeDir,".config","systemd","user",ri)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await HI(jI(i),{recursive:!0}),await GI(i,this.renderConfig(t),"utf8"),wa.info("systemd unit written",{unitPath:i,mode:s,activate:r}),await ya("systemctl",_a(t,["daemon-reload"])),await ya("systemctl",_a(t,r?["enable","--now",ri]:["enable",ri])),wa.info("systemd unit enabled",{unitName:ri,mode:s,activate:r})},async uninstall(t){let e=this.configPath(t);await ya("systemctl",_a(t,["disable","--now",ri])).catch(r=>wa.warn("systemctl disable failed (ignored)",{err:String(r)})),await qI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ya("systemctl",_a(t,["daemon-reload"])).catch(()=>{}),wa.info("systemd unit removed",{unitPath:e})}}});import{spawn as $I}from"node:child_process";import{join as VI}from"node:path";function qp(t,e){return new Promise((r,i)=>{let s=$I(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";s.stderr?.on("data",l=>{c+=l.toString("utf8")}),s.on("error",i),s.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var xl,ba,hl,Gp=rt(()=>{"use strict";ie();xl=j("supervisor.taskscheduler"),ba="CozeBridge",hl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?ng(hA,ci):ng(t.homeDir,".config","systemd","user",ci)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await dA(fA(i),{recursive:!0}),await uA(i,this.renderConfig(t),"utf8"),Ta.info("systemd unit written",{unitPath:i,mode:s,activate:n}),await Da("systemctl",Pa(t,["daemon-reload"])),await Da("systemctl",Pa(t,n?["enable","--now",ci]:["enable",ci])),Ta.info("systemd unit enabled",{unitName:ci,mode:s,activate:n})},async uninstall(t){let e=this.configPath(t);await Da("systemctl",Pa(t,["disable","--now",ci])).catch(n=>Ta.warn("systemctl disable failed (ignored)",{err:String(n)})),await lA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Da("systemctl",Pa(t,["daemon-reload"])).catch(()=>{}),Ta.info("systemd unit removed",{unitPath:e})}}});import{spawn as pA}from"node:child_process";import{join as gA}from"node:path";function ig(t,e){return new Promise((n,i)=>{let s=pA(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var vl,Ca,Sl,sg=st(()=>{"use strict";ne();vl=K("supervisor.taskscheduler"),Ca="CozeBridge",Sl={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,59 +86,64 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return VI(t.homeDir,".coze","bridge","task.xml")},async install(t){let r=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await qp("schtasks",["/Create","/SC","ONLOGON","/TN",ba,"/TR",r,"/RU",t.userName,"/F"]),xl.info("task scheduler entry created",{task:ba,logFile:t.logFile})},async uninstall(t){await qp("schtasks",["/Delete","/TN",ba,"/F"]).catch(e=>xl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),xl.info("task scheduler entry removed",{task:ba})}}});var jp={};Na(jp,{buildContext:()=>e2,getSupervisor:()=>YI,launchdSupervisor:()=>ul,systemdSupervisor:()=>fl,taskSchedulerSupervisor:()=>hl});import{homedir as JI,userInfo as ZI}from"node:os";function YI(t=process.platform){switch(t){case"darwin":return ul;case"linux":return fl;case"win32":return hl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function QI(){let t={};for(let e of XI){let r=process.env[e];r&&(t[e]=r)}return t}function e2(){let t=Z();return{nodeBin:process.execPath,entry:nl(t),logFile:t.logFile,homeDir:JI(),userName:ZI().username,isRoot:process.getuid?.()===0,env:QI()}}var XI,Wp=rt(()=>{"use strict";Ce();ua();zp();Hp();Gp();XI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ie();dn();var Wl=j("acp-installer-warmup"),wm=["claude-code","codex"];async function Kl(t={}){let e=t.ensure??hr,i=(await Promise.allSettled(wm.map(async s=>{let c=await e(s);Wl.info("acp wrapper warmup ok",{framework:s,path:c})}))).filter(s=>s.status==="rejected");i.length>0&&Wl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(s=>s.reason instanceof Error?s.reason.message:String(s.reason))})}hn();ie();import{readdir as Lm}from"node:fs/promises";import{mkdir as Zl,readFile as Dm,writeFile as Yl}from"node:fs/promises";import{join as qa}from"node:path";var Om={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function pr(t,e,r){await Zl(t,{recursive:!0});let i=Om[e],s=qa(t,i);return await Yl(s,r??"","utf8"),s}async function Ga(t,e,r){let i=qa(t,".claude");await Zl(i,{recursive:!0});let s=qa(i,"settings.local.json"),c={};try{let u=await Dm(s,"utf8"),x=JSON.parse(u);typeof x=="object"&&x!==null&&!Array.isArray(x)&&(c=x)}catch{}let l=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=r)}return c.permissions=l,await Yl(s,JSON.stringify(c,null,2),"utf8"),s}var Qe=j("agent-detail-sync"),Nm=6e4,Mm=5*6e4,Is=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Lm(r)}catch(s){Qe.info("agents dir not found, skip detail sync",{root:r,err:String(s)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let c=await Re(s,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,c)}catch(l){Qe.warn("detail sync failed for agent, skipping",{agentId:s,err:String(l)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,s]of this.retryQueue)e>=s.dueAt&&r.push(i);if(r.length!==0){Qe.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(s){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,r){let i=r??await Re(e,this.opts.paths);if(!i){Qe.info("detail sync: agent config missing, skip",{agentId:e});return}let s;try{s=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(x){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(x)});let h=this.retryQueue.get(e),m=h?Math.min(h.currentDelay*2,Mm):Nm;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(s.agentId&&s.agentId!==e){Qe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:s.agentId});return}let c=!1,l=!1;s.agentName&&s.agentName!==i.agentName&&(i.agentName=s.agentName,c=!0),s.description!==void 0&&s.description!==i.description&&(i.description=s.description,c=!0),s.cozeIdentity&&s.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=s.cozeIdentity,c=!0,l=!0);let u=!1;if(s.deployType==="cloud"&&i.deployType!=="cloud"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):s.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:s.deployType}),!c){Qe.debug("detail sync: no diff",{agentId:e});return}await Ue(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:l,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})):l&&(await pr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var hd=Gt(Ru(),1);import{createHash as wy}from"node:crypto";import{lstat as od,mkdir as ad,readFile as wo,readdir as w0,rm as cd,stat as fd,writeFile as dd}from"node:fs/promises";import{homedir as _y}from"node:os";import{basename as p0,dirname as yy,join as pe,normalize as by,relative as xd,resolve as ld,sep as _0}from"node:path";import{Readable as y0}from"node:stream";import{pipeline as b0}from"node:stream/promises";import iw from"events";import st from"fs";import{EventEmitter as Gc}from"node:events";import xf from"node:stream";import{StringDecoder as sw}from"node:string_decoder";import gf from"node:path";import kr from"node:fs";import{dirname as ww,parse as _w}from"path";import{EventEmitter as kw}from"events";import Sc from"assert";import{Buffer as Kn}from"buffer";import*as Nu from"zlib";import Tw from"zlib";import{posix as yr}from"node:path";import{basename as n_}from"node:path";import ro from"fs";import Pt from"fs";import Gu from"path";import{win32 as p_}from"node:path";import Zu from"path";import Pf from"node:fs";import D_ from"node:assert";import{randomBytes as Df}from"node:crypto";import oe from"node:fs";import Me from"node:path";import Of from"fs";import xo from"node:fs";import Pi from"node:path";import dt from"node:fs";import z_ from"node:fs/promises";import oo from"node:path";import{join as jf}from"node:path";import ct from"node:fs";import $f from"node:path";var nw=Object.defineProperty,rw=(t,e)=>{for(var r in e)nw(t,r,{get:e[r],enumerable:!0})},Pu=typeof process=="object"&&process?process:{stdout:null,stderr:null},ow=t=>!!t&&typeof t=="object"&&(t instanceof Jn||t instanceof xf||aw(t)||cw(t)),aw=t=>!!t&&typeof t=="object"&&t instanceof Gc&&typeof t.pipe=="function"&&t.pipe!==xf.Writable.prototype.pipe,cw=t=>!!t&&typeof t=="object"&&t instanceof Gc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),gn=Symbol("emittedEnd"),Rs=Symbol("emittingEnd"),xi=Symbol("emittedError"),Ps=Symbol("closed"),Du=Symbol("read"),Ds=Symbol("flush"),Ou=Symbol("flushChunk"),_t=Symbol("encoding"),_r=Symbol("decoder"),He=Symbol("flowing"),hi=Symbol("paused"),Sr=Symbol("resume"),qe=Symbol("buffer"),et=Symbol("pipes"),Ge=Symbol("bufferLength"),Ja=Symbol("bufferPush"),Os=Symbol("bufferShift"),Xe=Symbol("objectMode"),Ae=Symbol("destroyed"),Za=Symbol("error"),Ya=Symbol("emitData"),Lu=Symbol("emitEnd"),Xa=Symbol("emitEnd2"),kt=Symbol("async"),Qa=Symbol("abort"),Ls=Symbol("aborted"),pi=Symbol("signal"),Bn=Symbol("dataListeners"),at=Symbol("discarded"),gi=t=>Promise.resolve().then(t),dw=t=>t(),lw=t=>t==="end"||t==="finish"||t==="prefinish",uw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,fw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),hf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Sr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},xw=class extends hf{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},hw=t=>!!t.objectMode,pw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Jn=class extends Gc{[He]=!1;[hi]=!1;[et]=[];[qe]=[];[Xe];[_t];[kt];[_r];[jt]=!1;[gn]=!1;[Rs]=!1;[Ps]=!1;[xi]=null;[Ge]=0;[Ae]=!1;[pi];[Ls]=!1;[Bn]=0;[at]=!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");hw(e)?(this[Xe]=!0,this[_t]=null):pw(e)?(this[_t]=e.encoding,this[Xe]=!1):(this[Xe]=!1,this[_t]=null),this[kt]=!!e.async,this[_r]=this[_t]?new sw(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:r}=e;r&&(this[pi]=r,r.aborted?this[Qa]():r.addEventListener("abort",()=>this[Qa]()))}get bufferLength(){return this[Ge]}get encoding(){return this[_t]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Xe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[kt]}set async(t){this[kt]=this[kt]||!!t}[Qa](){this[Ls]=!0,this.emit("abort",this[pi]?.reason),this.destroy(this[pi]?.reason)}get aborted(){return this[Ls]}set aborted(t){}write(t,e,r){if(this[Ls])return!1;if(this[jt])throw new Error("write after end");if(this[Ae])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[kt]?gi:dw;if(!this[Xe]&&!Buffer.isBuffer(t)){if(fw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(uw(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[He]&&this[Ge]!==0&&this[Ds](!0),this[He]?this.emit("data",t):this[Ja](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[He]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[_r]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[_r].write(t)),this[He]&&this[Ge]!==0&&this[Ds](!0),this[He]?this.emit("data",t):this[Ja](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[He]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[He])}read(t){if(this[Ae])return null;if(this[at]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[Wt](),null;this[Xe]&&(t=null),this[qe].length>1&&!this[Xe]&&(this[qe]=[this[_t]?this[qe].join(""):Buffer.concat(this[qe],this[Ge])]);let e=this[Du](t||null,this[qe][0]);return this[Wt](),e}[Du](t,e){if(this[Xe])this[Os]();else{let r=e;t===r.length||t===null?this[Os]():typeof r=="string"?(this[qe][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[qe][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[qe].length&&!this[jt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[jt]=!0,this.writable=!1,(this[He]||!this[hi])&&this[Wt](),this}[Sr](){this[Ae]||(!this[Bn]&&!this[et].length&&(this[at]=!0),this[hi]=!1,this[He]=!0,this.emit("resume"),this[qe].length?this[Ds]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[Sr]()}pause(){this[He]=!1,this[hi]=!0,this[at]=!1}get destroyed(){return this[Ae]}get flowing(){return this[He]}get paused(){return this[hi]}[Ja](t){this[Xe]?this[Ge]+=1:this[Ge]+=t.length,this[qe].push(t)}[Os](){return this[Xe]?this[Ge]-=1:this[Ge]-=this[qe][0].length,this[qe].shift()}[Ds](t=!1){do;while(this[Ou](this[Os]())&&this[qe].length);!t&&!this[qe].length&&!this[jt]&&this.emit("drain")}[Ou](t){return this.emit("data",t),this[He]}pipe(t,e){if(this[Ae])return t;this[at]=!1;let r=this[gn];return e=e||{},t===Pu.stdout||t===Pu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[et].push(e.proxyErrors?new xw(this,t,e):new hf(this,t,e)),this[kt]?gi(()=>this[Sr]()):this[Sr]()),t}unpipe(t){let e=this[et].find(r=>r.dest===t);e&&(this[et].length===1?(this[He]&&this[Bn]===0&&(this[He]=!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 r=super.on(t,e);if(t==="data")this[at]=!1,this[Bn]++,!this[et].length&&!this[He]&&this[Sr]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(lw(t)&&this[gn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[xi]){let i=e;this[kt]?gi(()=>i.call(this,this[xi])):i.call(this,this[xi])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Bn]=this.listeners("data").length,this[Bn]===0&&!this[at]&&!this[et].length&&(this[He]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Bn]=0,!this[at]&&!this[et].length&&(this[He]=!1)),e}get emittedEnd(){return this[gn]}[Wt](){!this[Rs]&&!this[gn]&&!this[Ae]&&this[qe].length===0&&this[jt]&&(this[Rs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ps]&&this.emit("close"),this[Rs]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ae&&this[Ae])return!1;if(t==="data")return!this[Xe]&&!r?!1:this[kt]?(gi(()=>this[Ya](r)),!0):this[Ya](r);if(t==="end")return this[Lu]();if(t==="close"){if(this[Ps]=!0,!this[gn]&&!this[Ae])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[xi]=r,super.emit(Za,r);let s=!this[pi]||this.listeners("error").length?super.emit("error",r):!1;return this[Wt](),s}else if(t==="resume"){let s=super.emit("resume");return this[Wt](),s}else if(t==="finish"||t==="prefinish"){let s=super.emit(t);return this.removeAllListeners(t),s}let i=super.emit(t,...e);return this[Wt](),i}[Ya](t){for(let r of this[et])r.dest.write(t)===!1&&this.pause();let e=this[at]?!1:super.emit("data",t);return this[Wt](),e}[Lu](){return this[gn]?!1:(this[gn]=!0,this.readable=!1,this[kt]?(gi(()=>this[Xa]()),!0):this[Xa]())}[Xa](){if(this[_r]){let e=this[_r].end();if(e){for(let r of this[et])r.dest.write(e);this[at]||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",r=>{t.push(r),this[Xe]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Xe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ae,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[at]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[jt])return e();let i,s,c=h=>{this.off("data",l),this.off("end",u),this.off(Ae,x),e(),s(h)},l=h=>{this.off("error",c),this.off("end",u),this.off(Ae,x),this.pause(),i({value:h,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(Ae,x),e(),i({done:!0,value:void 0})},x=()=>c(new Error("stream destroyed"));return new Promise((h,m)=>{s=m,i=h,this.once(Ae,x),this.once("error",c),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[at]=!1;let t=!1,e=()=>(this.pause(),this.off(Za,e),this.off(Ae,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Za,e),this.once(Ae,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ae])return t?this.emit("error",t):this.emit(Ae),this;this[Ae]=!0,this[at]=!0,this[qe].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Ps]&&e.close(),t?this.emit("error",t):this.emit(Ae),this}static get isStream(){return ow}},gw=st.writev,In=Symbol("_autoClose"),vt=Symbol("_close"),mi=Symbol("_ended"),le=Symbol("_fd"),ec=Symbol("_finished"),Jt=Symbol("_flags"),tc=Symbol("_flush"),Ec=Symbol("_handleChunk"),vc=Symbol("_makeBuf"),Ci=Symbol("_mode"),Ns=Symbol("_needDrain"),Cr=Symbol("_onerror"),Rr=Symbol("_onopen"),nc=Symbol("_onread"),Ir=Symbol("_onwrite"),An=Symbol("_open"),Et=Symbol("_path"),yn=Symbol("_pos"),Tt=Symbol("_queue"),Ar=Symbol("_read"),rc=Symbol("_readSize"),Vt=Symbol("_reading"),wi=Symbol("_remain"),ic=Symbol("_size"),Ws=Symbol("_write"),Fn=Symbol("_writing"),Ks=Symbol("_defaultFlag"),Wn=Symbol("_errored"),jc=class extends Jn{[Wn]=!1;[le];[Et];[rc];[Vt]=!1;[ic];[wi];[In];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Wn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Et]=t,this[rc]=e.readSize||16*1024*1024,this[Vt]=!1,this[ic]=typeof e.size=="number"?e.size:1/0,this[wi]=this[ic],this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[Ar]():this[An]()}get fd(){return this[le]}get path(){return this[Et]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[An](){st.open(this[Et],"r",(t,e)=>this[Rr](t,e))}[Rr](t,e){t?this[Cr](t):(this[le]=e,this.emit("open",e),this[Ar]())}[vc](){return Buffer.allocUnsafe(Math.min(this[rc],this[wi]))}[Ar](){if(!this[Vt]){this[Vt]=!0;let t=this[vc]();if(t.length===0)return process.nextTick(()=>this[nc](null,0,t));st.read(this[le],t,0,t.length,null,(e,r,i)=>this[nc](e,r,i))}}[nc](t,e,r){this[Vt]=!1,t?this[Cr](t):this[Ec](e,r)&&this[Ar]()}[vt](){if(this[In]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Cr](t){this[Vt]=!0,this[vt](),this.emit("error",t)}[Ec](t,e){let r=!1;return this[wi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[wi]<=0)&&(r=!1,this[vt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[Ar](),!1;case"error":return this[Wn]?!1:(this[Wn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},mw=class extends jc{[An](){let t=!0;try{this[Rr](null,st.openSync(this[Et],"r")),t=!1}finally{t&&this[vt]()}}[Ar](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[vc](),r=e.length===0?0:st.readSync(this[le],e,0,e.length,null);if(!this[Ec](r,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[In]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.closeSync(t),this.emit("close")}}},ao=class extends iw{readable=!1;writable=!0;[Wn]=!1;[Fn]=!1;[mi]=!1;[Tt]=[];[Ns]=!1;[Et];[Ci];[In];[le];[Ks];[Jt];[ec]=!1;[yn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Ci]=e.mode===void 0?438:e.mode,this[yn]=typeof e.start=="number"?e.start:void 0,this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[yn]!==void 0?"r+":"w";this[Ks]=e.flags===void 0,this[Jt]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[An]()}emit(t,...e){if(t==="error"){if(this[Wn])return!1;this[Wn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[Et]}[Cr](t){this[vt](),this[Fn]=!0,this.emit("error",t)}[An](){st.open(this[Et],this[Jt],this[Ci],(t,e)=>this[Rr](t,e))}[Rr](t,e){this[Ks]&&this[Jt]==="r+"&&t&&t.code==="ENOENT"?(this[Jt]="w",this[An]()):t?this[Cr](t):(this[le]=e,this.emit("open",e),this[Fn]||this[tc]())}end(t,e){return t&&this.write(t,e),this[mi]=!0,!this[Fn]&&!this[Tt].length&&typeof this[le]=="number"&&this[Ir](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[mi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Fn]||this[Tt].length?(this[Tt].push(t),this[Ns]=!0,!1):(this[Fn]=!0,this[Ws](t),!0)}[Ws](t){st.write(this[le],t,0,t.length,this[yn],(e,r)=>this[Ir](e,r))}[Ir](t,e){t?this[Cr](t):(this[yn]!==void 0&&typeof e=="number"&&(this[yn]+=e),this[Tt].length?this[tc]():(this[Fn]=!1,this[mi]&&!this[ec]?(this[ec]=!0,this[vt](),this.emit("finish")):this[Ns]&&(this[Ns]=!1,this.emit("drain"))))}[tc](){if(this[Tt].length===0)this[mi]&&this[Ir](null,0);else if(this[Tt].length===1)this[Ws](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],gw(this[le],t,this[yn],(e,r)=>this[Ir](e,r))}}[vt](){if(this[In]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},pf=class extends ao{[An](){let t;if(this[Ks]&&this[Jt]==="r+")try{t=st.openSync(this[Et],this[Jt],this[Ci])}catch(e){if(e?.code==="ENOENT")return this[Jt]="w",this[An]();throw e}else t=st.openSync(this[Et],this[Jt],this[Ci]);this[Rr](null,t)}[vt](){if(this[In]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,st.closeSync(t),this.emit("close")}}[Ws](t){let e=!0;try{this[Ir](null,st.writeSync(this[le],t,0,t.length,this[yn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},yw=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"]]),bw=t=>!!t.sync&&!!t.file,Ew=t=>!t.sync&&!!t.file,vw=t=>!!t.sync&&!t.file,Sw=t=>!t.sync&&!t.file,Iw=t=>!!t.file,Aw=t=>yw.get(t)||t,Wc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let s=Aw(r);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Fi=(t,e,r,i,s)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let x=Wc(c);if(s?.(x,l),bw(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(x,l)}else if(Ew(x)){let h=e(x,l);return u?h.then(()=>u(),u):h}else if(vw(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(x,l)}else if(Sw(x)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(x,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:s}),Cw=Tw.constants||{ZLIB_VERNUM:4736},Ot=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Cw)),Rw=Kn.concat,Mu=Object.getOwnPropertyDescriptor(Kn,"concat"),Pw=t=>t,sc=Mu?.writable===!0||Mu?.set!==void 0?t=>{Kn.concat=t?Pw:Rw}:t=>{},$n=Symbol("_superWrite"),Ms=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"}},oc=Symbol("flushFlag"),Kc=class extends Jn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Nu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Nu[e](t)}catch(r){throw new Ms(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ms(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Sc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Kn.alloc(0),{[oc]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[$n](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Kn.from(t,e)),this.#e)return;Sc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},sc(!0);let l;try{let x=typeof t[oc]=="number"?t[oc]:this.#r;l=this.#t._processChunk(t,x),sc(!1)}catch(x){sc(!1),this.#o(new Ms(x,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=s,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",x=>this.#o(new Ms(x,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let x=l[0];u=this[$n](Kn.from(x));for(let h=1;h<l.length;h++)u=this[$n](l[h])}else u=this[$n](Kn.from(l));return r&&r(),u}},mf=class extends Kc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ot.Z_FINISH,t.fullFlushFlag=Ot.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Ot.Z_SYNC_FLUSH),Sc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,s)=>{typeof i=="function"&&(s=i,i=this.flushFlag),this.flush(i),s?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},Dw=class extends mf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[$n](t){return this.#e?(this.#e=!1,t[9]=255,super[$n](t)):super[$n](t)}},Ow=class extends mf{constructor(t){super(t,"Unzip")}},wf=class extends Kc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ot.BROTLI_OPERATION_FLUSH,super(t,e)}},Lw=class extends wf{constructor(t){super(t,"BrotliCompress")}},Nw=class extends wf{constructor(t){super(t,"BrotliDecompress")}},_f=class extends Kc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ot.ZSTD_e_end,t.fullFlushFlag=Ot.ZSTD_e_flush,super(t,e)}},Mw=class extends _f{constructor(t){super(t,"ZstdCompress")}},Bw=class extends _f{constructor(t){super(t,"ZstdDecompress")}},Fw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Uw(t,e):zw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},zw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Uw=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var i=e.length;i>1;i--){var s=t&255;t=Math.floor(t/256),r?e[i-1]=yf(s):s===0?e[i-1]=0:(r=!0,e[i-1]=bf(s))}},Hw=t=>{let e=t[0],r=e===128?Gw(t.subarray(1,t.length)):e===255?qw(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},qw=t=>{for(var e=t.length,r=0,i=!1,s=e-1;s>-1;s--){var c=Number(t[s]),l;i?l=yf(c):c===0?l=c:(i=!0,l=bf(c)),l!==0&&(r-=l*Math.pow(256,e-s-1))}return r},Gw=t=>{for(var e=t.length,r=0,i=e-1;i>-1;i--){var s=Number(t[i]);s!==0&&(r+=s*Math.pow(256,e-i-1))}return r},yf=t=>(255^t)&255,bf=t=>(255^t)+1&255,jw={};rw(jw,{code:()=>$c,isCode:()=>$s,isName:()=>Ww,name:()=>co,normalFsTypes:()=>Ef});var $s=t=>co.has(t),Ww=t=>$c.has(t),Ef=new Set(["0","","1","2","3","4","5","6","7","D"]),co=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),$c=new Map(Array.from(co).map(t=>[t[1],t[0]])),Kw=t=>t===void 0||t<0?void 0:t,Vn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,i){Buffer.isBuffer(t)?this.decode(t,e||0,r,i):t&&this.#n(t)}decode(t,e,r,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let s=zn(t,e+156,1),c=Ef.has(s),l=c?r:void 0,u=c?i:void 0;if(this.path=l?.path??zn(t,e,100),this.mode=l?.mode??u?.mode??bn(t,e+100,8),this.uid=l?.uid??u?.uid??bn(t,e+108,8),this.gid=l?.gid??u?.gid??bn(t,e+116,8),this.size=Kw(l?.size??u?.size??bn(t,e+124,12)),this.mtime=l?.mtime??u?.mtime??ac(t,e+136,12),this.cksum=bn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),$s(s)&&(this.#e=s||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=zn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=l?.uname??u?.uname??zn(t,e+265,32),this.gname=l?.gname??u?.gname??zn(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??bn(t,e+329,8)??0,this.devmin=l?.devmin??u?.devmin??bn(t,e+337,8)??0,t[e+475]!==0){let h=zn(t,e+345,155);this.path=h+"/"+this.path}else{let h=zn(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=r?.atime??i?.atime??ac(t,e+476,12),this.ctime=r?.ctime??i?.ctime??ac(t,e+488,12)}let x=256;for(let h=e;h<e+148;h++)x+=t[h];for(let h=e+156;h<e+512;h++)x+=t[h];this.cksumValid=x===this.cksum,this.cksum===void 0&&x===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="size"&&Number(i)<0||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=$w(this.path||"",r),s=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Un(t,e,100,s)||this.needPax,this.needPax=En(t,e+100,8,this.mode)||this.needPax,this.needPax=En(t,e+108,8,this.uid)||this.needPax,this.needPax=En(t,e+116,8,this.gid)||this.needPax,this.needPax=En(t,e+124,12,this.size)||this.needPax,this.needPax=cc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Un(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Un(t,e+265,32,this.uname)||this.needPax,this.needPax=Un(t,e+297,32,this.gname)||this.needPax,this.needPax=En(t,e+329,8,this.devmaj)||this.needPax,this.needPax=En(t,e+337,8,this.devmin)||this.needPax,this.needPax=Un(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Un(t,e+345,155,c)||this.needPax:(this.needPax=Un(t,e+345,130,c)||this.needPax,this.needPax=cc(t,e+476,12,this.atime)||this.needPax,this.needPax=cc(t,e+488,12,this.ctime)||this.needPax);let l=256;for(let u=e;u<e+148;u++)l+=t[u];for(let u=e+156;u<e+512;u++)l+=t[u];return this.cksum=l,En(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:co.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String($c.get(t));if($s(e)||e==="Unsupported")this.#e=e;else if($s(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},$w=(t,e)=>{let r=t,i="",s,c=yr.parse(t).root||".";if(Buffer.byteLength(r)<100)s=[r,i,!1];else{i=yr.dirname(r),r=yr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?s=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?s=[r.slice(0,99),i,!0]:(r=yr.join(yr.basename(i),r),i=yr.dirname(i));while(i!==c&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},zn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),ac=(t,e,r)=>Vw(bn(t,e,r)),Vw=t=>t===void 0?void 0:new Date(t*1e3),bn=(t,e,r)=>Number(t[e])&128?Hw(t.subarray(e,e+r)):Zw(t,e,r),Jw=t=>isNaN(t)?void 0:t,Zw=(t,e,r)=>Jw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Yw={12:8589934591,8:2097151},En=(t,e,r,i)=>i===void 0?!1:i>Yw[r]||i<0?(Fw(i,t.subarray(e,e+r)),!0):(Xw(t,e,r,i),!1),Xw=(t,e,r,i)=>t.write(Qw(i,r),e,r,"ascii"),Qw=(t,e)=>e_(Math.floor(t).toString(8),e),e_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",cc=(t,e,r,i)=>i===void 0?!1:En(t,e,r,i.getTime()/1e3),t_=new Array(156).join("\0"),Un=(t,e,r,i)=>i===void 0?!1:(t.write(i+t_,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),no=class vf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),i=512*Math.ceil(1+r/512),s=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)s[c]=0;new Vn({path:("PaxHeader/"+n_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(s),s.write(e,512,r,"utf8");for(let c=r+512;c<s.length;c++)s[c]=0;return s}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,s=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,c=Buffer.byteLength(s),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+s}static parse(e,r,i=!1){return new vf(r_(i_(e),r),i)}},r_=(t,e)=>e?Object.assign({},e,t):t,i_=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(s_,Object.create(null)),s_=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),s=i.shift();if(!s)return t;let c=s.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=").replace(/\0.*/,"");switch(c){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[c]=l;break;case"ctime":case"atime":case"mtime":t[c]=new Date(Number(l)*1e3);break;case"size":let u=+l;u>=0&&(t[c]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[c]=+l;break}return t},o_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=o_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),a_=class extends Jn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},lo=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},c_=1024*1024,Ic=Buffer.from([31,139]),Ac=Buffer.from([40,181,47,253]),d_=Math.max(Ic.length,Ac.length),ft=Symbol("state"),Hn=Symbol("writeEntry"),Kt=Symbol("readEntry"),dc=Symbol("nextEntry"),Bu=Symbol("processEntry"),Ct=Symbol("extendedHeader"),_i=Symbol("globalExtendedHeader"),mn=Symbol("meta"),Fu=Symbol("emitMeta"),me=Symbol("buffer"),$t=Symbol("queue"),wn=Symbol("ended"),lc=Symbol("emittedEnd"),qn=Symbol("emit"),Ie=Symbol("unzip"),Bs=Symbol("consumeChunk"),Fs=Symbol("consumeChunkSub"),uc=Symbol("consumeBody"),zu=Symbol("consumeMeta"),Uu=Symbol("consumeHeader"),yi=Symbol("consuming"),fc=Symbol("bufferConcat"),zs=Symbol("maybeEnd"),br=Symbol("writing"),Rt=Symbol("aborted"),Us=Symbol("onDone"),Gn=Symbol("sawValidEntry"),Hs=Symbol("sawNullBlock"),qs=Symbol("sawEOF"),Hu=Symbol("closeStream"),l_=1e3,bi=Symbol("compressedBytesRead"),xc=Symbol("decompressedBytesRead"),qu=Symbol("checkDecompressionRatio"),u_=()=>!0,Bi=class extends kw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[$t]=[];[me];[Kt];[Hn];[ft]="begin";[mn]="";[Ct];[_i];[wn]=!1;[Ie];[Rt]=!1;[Gn];[Hs]=!1;[qs]=!1;[br]=!1;[yi]=!1;[lc]=!1;[bi]=0;[xc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Us,()=>{(this[ft]==="begin"||this[Gn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Us,t.ondone):this.on(Us,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:l_,this.maxMetaEntrySize=t.maxMetaEntrySize||c_,this.filter=typeof t.filter=="function"?t.filter:u_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[Hu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){lo(this,t,e,r)}[Uu](t,e){this[Gn]===void 0&&(this[Gn]=!1);let r;try{r=new Vn(t,e,this[Ct],this[_i])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Hs]?(this[qs]=!0,this[ft]==="begin"&&(this[ft]="header"),this[qn]("eof")):(this[Hs]=!0,this[qn]("nullBlock"));else if(this[Hs]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let s=this[Hn]=new a_(r,this[Ct],this[_i]);if(!this[Gn])if(s.remain){let c=()=>{s.invalid||(this[Gn]=!0)};s.on("end",c)}else this[Gn]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[qn]("ignoredEntry",s),this[ft]="ignore",s.resume()):s.size>0&&(this[mn]="",s.on("data",c=>this[mn]+=c),this[ft]="meta"):(this[Ct]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[qn]("ignoredEntry",s),this[ft]=s.remain?"ignore":"header",s.resume()):(s.remain?this[ft]="body":(this[ft]="header",s.end()),this[Kt]?this[$t].push(s):(this[$t].push(s),this[dc]())))}}}[Hu](){queueMicrotask(()=>this.emit("close"))}[Bu](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[dc]()),e=!1);return e}[dc](){do;while(this[Bu](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[br]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[uc](t,e){let r=this[Hn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,s=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(s),r.blockRemain||(this[ft]="header",this[Hn]=void 0,r.end()),s.length}[zu](t,e){let r=this[Hn],i=this[uc](t,e);return!this[Hn]&&r&&this[Fu](r),i}[qn](t,e,r){this[$t].length===0&&!this[Kt]?this.emit(t,e,r):this[$t].push([t,e,r])}[Fu](t){switch(this[qn]("meta",this[mn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=no.parse(this[mn],this[Ct],!1);break;case"GlobalExtendedHeader":this[_i]=no.parse(this[mn],this[_i],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[mn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[mn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Rt]){if(this[Ie]){let e=this[Ie];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Rt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[qu](t){this[xc]+=t.length;let e=this[xc]/this[bi];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Rt])return r?.(),!1;if((this[Ie]===void 0||this.brotli===void 0&&this[Ie]===!1)&&t){if(this[me]&&(t=Buffer.concat([this[me],t]),this[me]=void 0),t.length<d_)return this[me]=t,r?.(),!0;for(let l=0;this[Ie]===void 0&&l<Ic.length;l++)t[l]!==Ic[l]&&(this[Ie]=!1);let s=!1;if(this[Ie]===!1&&this.zstd!==!1){s=!0;for(let l=0;l<Ac.length;l++)if(t[l]!==Ac[l]){s=!1;break}}let c=this.brotli===void 0&&!s;if(this[Ie]===!1&&c)if(t.length<512)if(this[wn])this.brotli=!0;else return this[me]=t,r?.(),!0;else try{new Vn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ie]===void 0||this[Ie]===!1&&(this.brotli||s)){let l=this[wn];this[wn]=!1,this[Ie]=this[Ie]===void 0?new Ow({}):s?new Bw({}):new Nw({}),this[Ie].on("data",x=>{this[qu](x)&&this[Bs](x)}),this[Ie].on("error",x=>{this[Rt]||this.abort(x)}),this[Ie].on("end",()=>{this[wn]=!0,this[Bs]()}),this[br]=!0,this[bi]+=t.length;let u=!!this[Ie][l?"end":"write"](t);return this[br]=!1,r?.(),u}}this[br]=!0,this[Ie]?(this[bi]+=t.length,this[Ie].write(t)):this[Bs](t),this[br]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),r?.(),i}[fc](t){t&&!this[Rt]&&(this[me]=this[me]?Buffer.concat([this[me],t]):t)}[zs](){if(this[wn]&&!this[lc]&&!this[Rt]&&!this[yi]){this[lc]=!0;let t=this[Hn];if(t?.blockRemain){let e=this[me]?this[me].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[me]&&t.write(this[me]),t.end()}this[qn](Us)}}[Bs](t){if(this[yi]&&t)this[fc](t);else if(!t&&!this[me])this[zs]();else if(t){if(this[yi]=!0,this[me]){this[fc](t);let e=this[me];this[me]=void 0,this[Fs](e)}else this[Fs](t);for(;this[me]&&this[me]?.length>=512&&!this[Rt]&&!this[qs];){let e=this[me];this[me]=void 0,this[Fs](e)}this[yi]=!1}(!this[me]||this[wn])&&this[zs]()}[Fs](t){let e=0,r=t.length;for(;e+512<=r&&!this[Rt]&&!this[qs];)switch(this[ft]){case"begin":case"header":this[Uu](t,e),e+=512;break;case"ignore":case"body":e+=this[uc](t,e);break;case"meta":e+=this[zu](t,e);break;default:throw new Error("invalid state: "+this[ft])}e<r&&(this[me]=this[me]?Buffer.concat([t.subarray(e),this[me]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[Rt]||(this[Ie]?(t&&(this[bi]+=t.length,this[Ie].write(t)),this[Ie].end()):(this[wn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[zs]())),this}},Ri=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},f_=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},Sf=(t,e)=>{let r=new Map(e.map(c=>[Ri(c),!0])),i=t.filter,s=(c,l="")=>{let u=l||_w(c).root||".",x;if(c===u)x=!1;else{let h=r.get(c);x=h!==void 0?h:s(ww(c),u)}return r.set(c,x),x};t.filter=i?(c,l)=>i(c,l)&&s(Ri(c)):c=>s(Ri(c))},x_=t=>{let e=new Bi(t),r=t.file,i;try{i=kr.openSync(r,"r");let s=kr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(s.size<c){let l=Buffer.allocUnsafe(s.size),u=kr.readSync(i,l,0,s.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<s.size;){let x=kr.readSync(i,u,0,c,l);if(x===0)break;l+=x,e.write(u.subarray(0,x))}e.end()}}finally{if(typeof i=="number")try{kr.closeSync(i)}catch{}}},h_=(t,e)=>{let r=new Bi(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),kr.stat(s,(u,x)=>{if(u)l(u);else{let h=new jc(s,{readSize:i,size:x.size});h.on("error",l),h.pipe(r)}})})},Pr=Fi(x_,h_,t=>new Bi(t),t=>new Bi(t),(t,e)=>{e?.length&&Sf(t,e),t.noResume||f_(t)}),If=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:g_,parse:ju}=p_,Vc=t=>{let e="",r=ju(t);for(;g_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=ju(t)}return[e,t]},uo=["|","<",">","?",":"],Jc=uo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),m_=new Map(uo.map((t,e)=>[t,Jc[e]])),w_=new Map(Jc.map((t,e)=>[t,uo[e]])),Wu=t=>uo.reduce((e,r)=>e.split(r).join(m_.get(r)),t),__=t=>Jc.reduce((e,r)=>e.split(r).join(w_.get(r)),t),Af=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ri(e)+"/"+t):Q(t),y_=16*1024*1024,Ku=Symbol("process"),$u=Symbol("file"),Vu=Symbol("directory"),kc=Symbol("symlink"),Ju=Symbol("hardlink"),Ei=Symbol("header"),Vs=Symbol("read"),Tc=Symbol("lstat"),Js=Symbol("onlstat"),Cc=Symbol("onread"),Rc=Symbol("onreadlink"),Pc=Symbol("openfile"),Dc=Symbol("onopenfile"),vn=Symbol("close"),io=Symbol("mode"),Oc=Symbol("awaitDrain"),hc=Symbol("ondrain"),Dt=Symbol("prefix"),kf=class extends Jn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Wc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||y_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Q(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Q(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,l]=Vc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=__(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Gu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let s=this.statCache.get(this.absolute);s?this[Js](s):this[Tc]()}warn(t,e,r={}){return lo(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Tc](){Pt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Js](e)})}[Js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=v_(t),this.emit("stat",t),this[Ku]()}[Ku](){switch(this.type){case"File":return this[$u]();case"Directory":return this[Vu]();case"SymbolicLink":return this[kc]();default:return this.end()}}[io](t){return If(t,this.type==="Directory",this.portable)}[Dt](t){return Af(t,this.prefix)}[Ei](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Vn({path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this[io](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 no({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[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](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)}[Vu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ei](),this.end()}[kc](){Pt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Rc](e)})}[Rc](t){this.linkpath=Q(t),this[Ei](),this.end()}[Ju](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Gu.relative(this.cwd,t)),this.stat.size=0,this[Ei](),this.end()}[$u](){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[Ju](e);this.linkCache.set(t,this.absolute)}if(this[Ei](),this.stat.size===0)return this.end();this[Pc]()}[Pc](){Pt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Dc](e)})}[Dc](t){if(this.fd=t,this.#e)return this[vn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Vs]()}[Vs](){let{fd:t,buf:e,offset:r,length:i,pos:s}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Pt.read(t,e,r,i,s,(c,l)=>{if(c)return this[vn](()=>this.emit("error",c));this[Cc](l)})}[vn](t=()=>{}){this.fd!==void 0&&Pt.close(this.fd,t)}[Cc](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[vn](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[vn](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[hc]():this[Oc](()=>this[hc]())}[Oc](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[hc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[vn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Vs]()}},b_=class extends kf{sync=!0;[Tc](){this[Js](Pt.lstatSync(this.absolute))}[kc](){this[Rc](Pt.readlinkSync(this.absolute))}[Pc](){this[Dc](Pt.openSync(this.absolute,"r"))}[Vs](){let t=!0;try{let{fd:e,buf:r,offset:i,length:s,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let l=Pt.readSync(e,r,i,s,c);this[Cc](l),t=!1}finally{if(t)try{this[vn](()=>{})}catch{}}}[Oc](t){t()}[vn](t=()=>{}){this.fd!==void 0&&Pt.closeSync(this.fd),t()}},E_=class extends Jn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return lo(this,t,e,r)}constructor(t,e={}){let r=Wc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[io](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let s=!1;if(!this.preservePaths){let[l,u]=Vc(this.path);l&&typeof u=="string"&&(this.path=u,s=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Vn({path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),s&&this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute path`,{entry:this,path:s+this.path}),this.header.encode()&&!this.noPax&&super.write(new no({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[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Dt](t){return Af(t,this.prefix)}[io](t){return If(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},v_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",S_=class Tr{tail;head;length=0;static create(e=[]){return new Tr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)A_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)k_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,s=0;i;s++)e.call(r,i.value,s,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,s=this.length-1;i;s--)e.call(r,i.value,s,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new Tr;for(let s=this.head;s;)i.push(e.call(r,s.value,this)),s=s.next;return i}mapReverse(e,r){r=r||this;var i=new Tr;for(let s=this.tail;s;)i.push(e.call(r,s.value,this)),s=s.prev;return i}reduce(e,r){let i,s=this.head;if(arguments.length>1)i=r;else if(this.head)s=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;s;c++)i=e(i,s.value,c),s=s.next;return i}reduceReverse(e,r){let i,s=this.tail;if(arguments.length>1)i=r;else if(this.tail)s=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;s;c--)i=e(i,s.value,c),s=s.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Tr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let s=this.head,c=0;for(c=0;s&&c<e;c++)s=s.next;for(;s&&c<r;c++,s=s.next)i.push(s.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Tr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let s=this.length,c=this.tail;for(;c&&s>r;s--)c=c.prev;for(;c&&s>e;s--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let s=this.head;for(let l=0;s&&l<e;l++)s=s.next;let c=[];for(let l=0;s&&l<r;l++)c.push(s.value),s=this.removeNode(s);s?s!==this.tail&&(s=s.prev):s=this.tail;for(let l of i)s=I_(this,s,l);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let s=i.prev;i.prev=i.next,i.next=s}return this.head=r,this.tail=e,this}};function I_(t,e,r){let i=e,s=e?e.next:t.head,c=new Zc(r,i,s,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function A_(t,e){t.tail=new Zc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function k_(t,e){t.head=new Zc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Zc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Yu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Xu=Buffer.alloc(1024),Zs=Symbol("onStat"),vi=Symbol("ended"),yt=Symbol("queue"),Si=Symbol("pendingLinks"),_n=Symbol("current"),jn=Symbol("process"),Ii=Symbol("processing"),Gs=Symbol("processJob"),bt=Symbol("jobs"),pc=Symbol("jobDone"),Ys=Symbol("addFSEntry"),Qu=Symbol("addTarEntry"),Lc=Symbol("stat"),Nc=Symbol("readdir"),Xs=Symbol("onreaddir"),Qs=Symbol("pipe"),ef=Symbol("entry"),gc=Symbol("entryOpt"),eo=Symbol("writeEntryClass"),Tf=Symbol("write"),mc=Symbol("ondrain"),fo=class extends Jn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[eo];onWriteEntry;[yt];[Si]=new Map;[bt]=0;[Ii]=!1;[vi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[eo]=kf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new Dw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Lw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Mw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[mc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[mc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[yt]=new S_,this[bt]=0,this.jobs=Number(t.jobs)||4,this[Ii]=!1,this[vi]=!1}[Tf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[vi]=!0,this[jn](),r&&r(),this}write(t){if(this[vi])throw new Error("write after end");return typeof t=="string"?this[Ys](t):this[Qu](t),this.flowing}[Qu](t){let e=Q(Zu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Yu(t.path,e);r.entry=new E_(t,this[gc](r)),r.entry.on("end",()=>this[pc](r)),this[bt]+=1,this[yt].push(r)}this[jn]()}[Ys](t){let e=Q(Zu.resolve(this.cwd,t));this[yt].push(new Yu(t,e)),this[jn]()}[Lc](t){t.pending=!0,this[bt]+=1;let e=this.follow?"stat":"lstat";ro[e](t.absolute,(r,i)=>{t.pending=!1,this[bt]-=1,r?this.emit("error",r):this[Zs](t,i)})}[Zs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[_n])this[Gs](t);else{let r=`${e.dev}:${e.ino}`,i=this[Si].get(r);i?i.push(t):this[Si].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[jn]()}[Nc](t){t.pending=!0,this[bt]+=1,ro.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[bt]-=1,e)return this.emit("error",e);this[Xs](t,r)})}[Xs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[jn]()}[jn](){if(!this[Ii]){this[Ii]=!0;for(let t=this[yt].head;t&&this[bt]<this.jobs;t=t.next)if(this[Gs](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[Ii]=!1,this[vi]&&this[yt].length===0&&this[bt]===0&&(this.zip?this.zip.end(Xu):(super.write(Xu),super.end()))}}get[_n](){return this[yt]&&this[yt].head&&this[yt].head.value}[pc](t){this[yt].shift(),this[bt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[Si].get(r);if(i){this[Si].delete(r);for(let s of i)s.pending=!1,this[Gs](s)}}this[jn]()}[Gs](t){if(t.pending&&t.pendingLink&&t===this[_n]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[_n]&&!t.piped&&this[Qs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Zs](t,e):this[Lc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Xs](t,e):this[Nc](t),!t.readdir)return}if(t.entry=this[ef](t),!t.entry){t.ignore=!0;return}t===this[_n]&&!t.piped&&this[Qs](t)}}}[gc](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[ef](t){this[bt]+=1;try{return new this[eo](t.path,this[gc](t)).on("end",()=>this[pc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[mc](){this[_n]&&this[_n].entry&&this[_n].entry.resume()}[Qs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Ys](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){lo(this,t,e,r)}},Yc=class extends fo{sync=!0;constructor(t){super(t),this[eo]=b_}pause(){}resume(){}[Lc](t){let e=this.follow?"statSync":"lstatSync";this[Zs](t,ro[e](t.absolute))}[Nc](t){this[Xs](t,ro.readdirSync(t.absolute))}[Qs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,c=s==="./"?"":s.replace(/\/*$/,"/");this[Ys](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[Tf](i)})}},T_=(t,e)=>{let r=new Yc(t),i=new pf(t.file,{mode:t.mode||438});r.pipe(i),Cf(r,e)},C_=(t,e)=>{let r=new fo(t),i=new ao(t.file,{mode:t.mode||438});r.pipe(i);let s=new Promise((c,l)=>{i.on("error",l),i.on("close",c),r.on("error",l)});return Rf(r,e).catch(c=>r.emit("error",c)),s},Cf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Pr({file:gf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},Rf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Pr({file:gf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},R_=(t,e)=>{let r=new Yc(t);return Cf(r,e),r},P_=(t,e)=>{let r=new fo(t);return Rf(r,e).catch(i=>r.emit("error",i)),r},MA=Fi(T_,C_,R_,P_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),O_=process.env.__FAKE_PLATFORM__||process.platform,Lf=O_==="win32",{O_CREAT:Nf,O_NOFOLLOW:tf,O_TRUNC:Mf,O_WRONLY:Bf}=Of.constants,Ff=Number(process.env.__FAKE_FS_O_FILENAME__)||Of.constants.UV_FS_O_FILEMAP||0,L_=Lf&&!!Ff,N_=512*1024,M_=Ff|Mf|Nf|Bf,nf=!Lf&&typeof tf=="number"?tf|Mf|Nf|Bf:null,zf=nf!==null?()=>nf:L_?t=>t<N_?M_:"w":()=>"w",Mc=(t,e,r)=>{try{return xo.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},so=(t,e,r,i)=>{xo.lchown(t,e,r,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},B_=(t,e,r,i,s)=>{if(e.isDirectory())Uf(Pi.resolve(t,e.name),r,i,c=>{if(c)return s(c);let l=Pi.resolve(t,e.name);so(l,r,i,s)});else{let c=Pi.resolve(t,e.name);so(c,r,i,s)}},Uf=(t,e,r,i)=>{xo.readdir(t,{withFileTypes:!0},(s,c)=>{if(s){if(s.code==="ENOENT")return i();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return i(s)}if(s||!c.length)return so(t,e,r,i);let l=c.length,u=null,x=h=>{if(!u){if(h)return i(u=h);if(--l===0)return so(t,e,r,i)}};for(let h of c)B_(t,h,e,r,x)})},F_=(t,e,r,i)=>{e.isDirectory()&&Hf(Pi.resolve(t,e.name),r,i),Mc(Pi.resolve(t,e.name),r,i)},Hf=(t,e,r)=>{let i;try{i=xo.readdirSync(t,{withFileTypes:!0})}catch(s){let c=s;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Mc(t,e,r);throw c}for(let s of i)F_(t,s,e,r);return Mc(t,e,r)},qf=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"}},ho=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"}},U_=(t,e)=>{dt.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new qf(t,r?.code||"ENOTDIR")),e(r)})},H_=(t,e,r)=>{t=Q(t);let i=e.umask??18,s=e.mode|448,c=(s&i)!==0,l=e.uid,u=e.gid,x=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),h=e.preserve,m=e.unlink,w=Q(e.cwd),S=(E,I)=>{E?r(E):I&&x?Uf(I,l,u,A=>S(A)):c?dt.chmod(t,s,r):r()};if(t===w)return U_(t,S);if(h)return z_.mkdir(t,{mode:s,recursive:!0}).then(E=>S(null,E??void 0),S);let y=Q(oo.relative(w,t)).split("/");Bc(w,y,s,m,w,void 0,S)},Bc=(t,e,r,i,s,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),x=Q(oo.resolve(t+"/"+u));dt.mkdir(x,r,Gf(x,e,r,i,s,c,l))},Gf=(t,e,r,i,s,c,l)=>u=>{u?dt.lstat(t,(x,h)=>{if(x)x.path=x.path&&Q(x.path),l(x);else if(h.isDirectory())Bc(t,e,r,i,s,c,l);else if(i)dt.unlink(t,m=>{if(m)return l(m);dt.mkdir(t,r,Gf(t,e,r,i,s,c,l))});else{if(h.isSymbolicLink())return l(new ho(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Bc(t,e,r,i,s,c,l))},q_=t=>{let e=!1,r;try{e=dt.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new qf(t,r??"ENOTDIR")}},G_=(t,e)=>{t=Q(t);let r=e.umask??18,i=e.mode|448,s=(i&r)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),x=e.preserve,h=e.unlink,m=Q(e.cwd),w=E=>{E&&u&&Hf(E,c,l),s&&dt.chmodSync(t,i)};if(t===m)return q_(m),w();if(x)return w(dt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(oo.relative(m,t)).split("/"),y;for(let E=S.shift(),I=m;E&&(I+="/"+E);E=S.shift()){I=Q(oo.resolve(I));try{dt.mkdirSync(I,i),y=y||I}catch{let A=dt.lstatSync(I);if(A.isDirectory())continue;if(h){dt.unlinkSync(I),dt.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new ho(I,I+"/"+S.join("/"))}}return w(y)},wc=Object.create(null),rf=1e4,Er=new Set,j_=t=>{Er.has(t)?Er.delete(t):wc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Er.add(t);let e=wc[t],r=Er.size-rf;if(r>rf/10){for(let i of Er)if(Er.delete(i),delete wc[i],--r<=0)break}return e},W_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,K_=W_==="win32",$_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=jf(i,r)),e.push(r||"/"),e},[]),V_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=K_?["win32 parallelization disabled"]:t.map(i=>Ri(jf(j_(i))));let r=new Set(t.map(i=>$_(i)).reduce((i,s)=>i.concat(s)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let s=this.#e.get(i);s?s.push(e):this.#e.set(i,[e])}for(let i of r){let s=this.#e.get(i);if(!s)this.#e.set(i,[new Set([e])]);else{let c=s.at(-1);c instanceof Set?c.add(e):s.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,s=new Set;for(let c of r){let l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")s.add(u);else for(let x of u)s.add(x)}for(let c of i){let l=this.#e.get(c),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(c);continue}else if(u.size===1){l.shift();let x=l[0];typeof x=="function"&&s.add(x)}else u.delete(t)}return this.#r.delete(t),s.forEach(c=>this.#i(c)),!0}},J_=()=>process.umask(),sf=Symbol("onEntry"),Fc=Symbol("checkFs"),of=Symbol("checkFs2"),zc=Symbol("isReusable"),xt=Symbol("makeFs"),Uc=Symbol("file"),Hc=Symbol("directory"),to=Symbol("link"),af=Symbol("symlink"),cf=Symbol("hardlink"),Ti=Symbol("ensureNoSymlink"),df=Symbol("unsupported"),lf=Symbol("checkPath"),_c=Symbol("stripAbsolutePath"),Sn=Symbol("mkdir"),je=Symbol("onError"),js=Symbol("pending"),uf=Symbol("pend"),vr=Symbol("unpend"),yc=Symbol("ended"),bc=Symbol("maybeClose"),qc=Symbol("skip"),Di=Symbol("doChown"),Oi=Symbol("uid"),Li=Symbol("gid"),Ni=Symbol("checkedCwd"),Z_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Mi=Z_==="win32",Y_=1024,X_=(t,e)=>{if(!Mi)return oe.unlink(t,e);let r=t+".DELETE."+Df(16).toString("hex");oe.rename(t,r,i=>{if(i)return e(i);oe.unlink(r,e)})},Q_=t=>{if(!Mi)return oe.unlinkSync(t);let e=t+".DELETE."+Df(16).toString("hex");oe.renameSync(t,e),oe.unlinkSync(e)},ff=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Xc=class extends Bi{[yc]=!1;[Ni]=!1;[js]=0;reservations=new V_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[yc]=!0,this[bc]()},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:Y_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Mi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Me.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:J_():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[sf](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[bc](){this[yc]&&this[js]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[_c](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[s,c]=Vc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Mi&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Me.posix.dirname(t.path),x=Me.posix.normalize(Me.posix.join(u,l.join("/")));if(x.startsWith("../")||x==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return s&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:r})),!0}[lf](t){let e=Q(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[_c](t,"path")||!this[_c](t,"linkpath"))return!1;if(t.absolute=Me.isAbsolute(t.path)?Q(Me.resolve(t.path)):Q(Me.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Me.win32.parse(String(t.absolute));t.absolute=i+Wu(String(t.absolute).slice(i.length));let{root:s}=Me.win32.parse(t.path);t.path=s+Wu(t.path.slice(s.length))}return!0}[sf](t){if(!this[lf](t))return t.resume();switch(D_.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[Fc](t);default:return this[df](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[vr](),e.resume())}[Sn](t,e,r){H_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Di](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}[Oi](t){return ff(this.uid,t.uid,this.processUid)}[Li](t){return ff(this.gid,t.gid,this.processGid)}[Uc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new ao(String(t.absolute),{flags:zf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&oe.close(i.fd,()=>{}),i.write=()=>!0,this[je](u,t),e()});let s=1,c=u=>{if(u){i.fd&&oe.close(i.fd,()=>{}),this[je](u,t),e();return}--s===0&&i.fd!==void 0&&oe.close(i.fd,x=>{x?this[je](x,t):this[vr](),e()})};i.on("finish",()=>{let u=String(t.absolute),x=i.fd;if(typeof x=="number"&&t.mtime&&!this.noMtime){s++;let h=t.atime||new Date,m=t.mtime;oe.futimes(x,h,m,w=>w?oe.utimes(u,h,m,S=>c(S&&w)):c())}if(typeof x=="number"&&this[Di](t)){s++;let h=this[Oi](t),m=this[Li](t);typeof h=="number"&&typeof m=="number"&&oe.fchown(x,h,m,w=>w?oe.chown(u,h,m,S=>c(S&&w)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[je](u,t),e()}),t.pipe(l)),l.pipe(i)}[Hc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Sn](String(t.absolute),r,i=>{if(i){this[je](i,t),e();return}let s=1,c=()=>{--s===0&&(e(),this[vr](),t.resume())};t.mtime&&!this.noMtime&&(s++,oe.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Di](t)&&(s++,oe.chown(String(t.absolute),Number(this[Oi](t)),Number(this[Li](t)),c)),c()})}[df](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[af](t,e){let r=Q(Me.relative(this.cwd,Me.resolve(Me.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ti](t,this.cwd,r,()=>this[to](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[cf](t,e){let r=Q(Me.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ti](t,this.cwd,i,()=>this[to](t,r,"link",e),s=>{this[je](s,t),e()})}[Ti](t,e,r,i,s){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Me.resolve(e,c);oe.lstat(l,(u,x)=>{if(u)return i();if(x?.isSymbolicLink())return s(new ho(l,Me.resolve(l,r.join("/"))));this[Ti](t,l,r,i,s)})}[uf](){this[js]++}[vr](){this[js]--,this[bc]()}[qc](t){this[vr](),t.resume()}[zc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Mi}[Fc](t){this[uf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[of](t,r))}[of](t,e){let r=l=>{e(l)},i=()=>{this[Sn](this.cwd,this.dmode,l=>{if(l){this[je](l,t),r();return}this[Ni]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let l=Q(Me.dirname(String(t.absolute)));if(l!==this.cwd)return this[Sn](l,this.dmode,u=>{if(u){this[je](u,t),r();return}c()})}c()},c=()=>{oe.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[qc](t),r();return}if(l||this[zc](t,u))return this[xt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let x=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=m=>this[xt](m??null,t,r);return x?oe.chmod(String(t.absolute),Number(t.mode),h):h()}if(t.absolute!==this.cwd)return oe.rmdir(String(t.absolute),x=>this[xt](x??null,t,r))}if(t.absolute===this.cwd)return this[xt](null,t,r);X_(String(t.absolute),x=>this[xt](x??null,t,r))})};this[Ni]?s():i()}[xt](t,e,r){if(t){this[je](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Uc](e,r);case"Link":return this[cf](e,r);case"SymbolicLink":return this[af](e,r);case"Directory":case"GNUDumpDir":return this[Hc](e,r)}}[to](t,e,r,i){oe[r](e,String(t.absolute),s=>{s?this[je](s,t):(this[vr](),t.resume()),i()})}},Ai=t=>{try{return[null,t()]}catch(e){return[e,null]}},Wf=class extends Xc{sync=!0;[xt](t,e){return super[xt](t,e,()=>{})}[Fc](t){if(!this[Ni]){let s=this[Sn](this.cwd,this.dmode);if(s)return this[je](s,t);this[Ni]=!0}if(t.absolute!==this.cwd){let s=Q(Me.dirname(String(t.absolute)));if(s!==this.cwd){let c=this[Sn](s,this.dmode);if(c)return this[je](c,t)}}let[e,r]=Ai(()=>oe.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[qc](t);if(e||this[zc](t,r))return this[xt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?Ai(()=>{oe.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[xt](l,t)}let[s]=Ai(()=>oe.rmdirSync(String(t.absolute)));this[xt](s,t)}let[i]=t.absolute===this.cwd?[]:Ai(()=>Q_(String(t.absolute)));this[xt](i,t)}[Uc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{oe.closeSync(s)}catch(x){u=x}(l||u)&&this[je](l||u,t),e()},s;try{s=oe.openSync(String(t.absolute),zf(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[je](l,t)),t.pipe(c)),c.on("data",l=>{try{oe.writeSync(s,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,x=t.mtime;try{oe.futimesSync(s,u,x)}catch(h){try{oe.utimesSync(String(t.absolute),u,x)}catch{l=h}}}if(this[Di](t)){let u=this[Oi](t),x=this[Li](t);try{oe.fchownSync(s,Number(u),Number(x))}catch(h){try{oe.chownSync(String(t.absolute),Number(u),Number(x))}catch{l=l||h}}}i(l)})}[Hc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Sn](String(t.absolute),r);if(i){this[je](i,t),e();return}if(t.mtime&&!this.noMtime)try{oe.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Di](t))try{oe.chownSync(String(t.absolute),Number(this[Oi](t)),Number(this[Li](t)))}catch{}e(),t.resume()}[Sn](t,e){try{return G_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Ti](t,e,r,i,s){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Me.resolve(c,l);let[u,x]=Ai(()=>oe.lstatSync(c));if(u)return i();if(x.isSymbolicLink())return s(new ho(c,Me.resolve(e,r.join("/"))))}i()}[to](t,e,r,i){let s=`${r}Sync`;try{oe[s](e,String(t.absolute)),i(),t.resume()}catch(c){return this[je](c,t)}}},ey=t=>{let e=new Wf(t),r=t.file,i=Pf.statSync(r),s=t.maxReadSize||16*1024*1024;new mw(r,{readSize:s,size:i.size}).pipe(e)},ty=(t,e)=>{let r=new Xc(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),Pf.stat(s,(u,x)=>{if(u)l(u);else{let h=new jc(s,{readSize:i,size:x.size});h.on("error",l),h.pipe(r)}})})},Kf=Fi(ey,ty,t=>new Wf(t),t=>new Xc(t),(t,e)=>{e?.length&&Sf(t,e)}),ny=(t,e)=>{let r=new Yc(t),i=!0,s,c;try{try{s=ct.openSync(t.file,"r+")}catch(x){if(x?.code==="ENOENT")s=ct.openSync(t.file,"w+");else throw x}let l=ct.fstatSync(s),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let m=0,w=0;m<512;m+=w){if(w=ct.readSync(s,u,m,u.length-m,c+m),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let x=new Vn(u);if(!x.cksumValid)break;let h=512*Math.ceil((x.size||0)/512);if(c+h+512>l.size)break;c+=h,t.mtimeCache&&x.mtime&&t.mtimeCache.set(String(x.path),x.mtime)}i=!1,ry(t,r,c,s,e)}finally{if(i)try{ct.closeSync(s)}catch{}}},ry=(t,e,r,i,s)=>{let c=new pf(t.file,{fd:i,start:r});e.pipe(c),sy(e,s)},iy=(t,e)=>{e=Array.from(e);let r=new fo(t),i=(s,c,l)=>{let u=(S,y)=>{S?ct.close(s,E=>l(S)):l(null,y)},x=0;if(c===0)return u(null,0);let h=0,m=Buffer.alloc(512),w=(S,y)=>{if(S||y===void 0)return u(S);if(h+=y,h<512&&y)return ct.read(s,m,h,m.length-h,x+h,w);if(x===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(h<512)return u(null,x);let E=new Vn(m);if(!E.cksumValid)return u(null,x);let I=512*Math.ceil((E.size??0)/512);if(x+I+512>c||(x+=I+512,x>=c))return u(null,x);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),h=0,ct.read(s,m,0,512,x,w)};ct.read(s,m,0,512,x,w)};return new Promise((s,c)=>{r.on("error",c);let l="r+",u=(x,h)=>{if(x&&x.code==="ENOENT"&&l==="r+")return l="w+",ct.open(t.file,l,u);if(x||!h)return c(x);ct.fstat(h,(m,w)=>{if(m)return ct.close(h,()=>c(m));i(h,w.size,(S,y)=>{if(S)return c(S);let E=new ao(t.file,{fd:h,start:y});r.pipe(E),E.on("error",c),E.on("close",s),oy(r,e)})})};ct.open(t.file,l,u)})},sy=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Pr({file:$f.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},oy=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Pr({file:$f.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},ki=Fi(ny,iy,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Iw(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")}),YA=Fi(ki.syncFile,ki.asyncFile,ki.syncNoFile,ki.asyncNoFile,(t,e=[])=>{ki.validate?.(t,e),ay(t)}),ay=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,i)=>e(r,i)&&!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};hn();var ht={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function po(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Vf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function go(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Jf(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function Zf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Yf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Zn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Zt();Ve();ie();Ce();Ve();function Dr(t,e){if(po(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function zi(t){return t.startsWith("http://")||t.startsWith("https://")}function Or(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as qk}from"node:fs";import{dirname as jk,join as Wk}from"node:path";import{fileURLToPath as $k}from"node:url";var Lt="0.2.7";Ve();ie();var mo="1008033",t0="1289";var n0="pbbp2",r0="https://www.coze.cn",i0="/api/coze_claw/resource/get_frontier_key",py="https://www.coze.cn",gy="wss://frontier.coze.cn";function Lr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??py}function s0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??gy}function kn(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Hi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Ui=j("handshake");async function Qc(t){let e=Lr(t.endpoint),r=t.timeoutMs??1e4,i=`${Or(e)}${i0}?aid=${encodeURIComponent(mo)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...kn(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),r);Ui.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:s,signal:c.signal}),x=u.headers.get("x-tt-logid")??"",h=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=${x}: ${E.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${x}`);let w=m.data??{},S=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,y=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!S||!y){let E=JSON.stringify(m).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${x}: ${E}`)}return Ui.info("handshake ok",{remoteDeviceId:y,logid:x,traceId:h}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof k)throw Ui.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Ui.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let x=u.cause;throw Ui.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:x?.code,syscall:x?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var td=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Nt="auto",ed=15e4,o0=32e3;function c0(t){return{model:nd(t.model)??Nt,...t.modelToken?{modelToken:t.modelToken}:{}}}function d0(t){return!t||t===Nt}var my=new Set(["auto","\u81EA\u52A8"]);function nd(t){let e=t?.trim();if(e)return my.has(e.toLowerCase())?Nt:e}function l0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=td,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Nt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else d0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function u0(t,e,r,i){let s={};if(t.modelToken?s.model=t.model||Nt:d0(t.model)||(s.model=t.model),t.modelToken){let c={name:"coze",base_url:`${td}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},l=rd(e,r,i);Object.keys(l).length>0&&(c.http_headers=l),s.model_providers={coze:c},s.model_context_window=t.modelInfo?.contextWindow??ed}return Object.keys(s).length===0?{}:{CODEX_CONFIG:JSON.stringify(s),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function f0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function rd(t,e,r){let{ttEnv:i,usePpe:s}=Hi(t),c={};return i&&(c["x-tt-env"]=i),s&&(c["x-use-ppe"]=s),e&&(c["x-mock-scenario"]=e),r&&(c["x-coze-request-scene"]=r),c}function x0(t,e,r,i){if(!t.modelToken)return{};let s=rd(e,r,i);return Object.keys(s).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(s).map(([l,u])=>`${l}:${u}`).join(`
92
- `)}}function id(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function sd(t){return t.model||Nt}function a0(t,e,r,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:r,maxTokens:i,api:"openai-completions"}}function h0(t,e,r,i,s){if(!t.modelToken)return null;let c=sd(t),l=rd(e,r,s),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let x=[a0(c,u,t.modelInfo?.contextWindow??ed,t.modelInfo?.maxOutput??o0)],h=new Set([c]);for(let w of i??[])!w||h.has(w)||(h.add(w),x.push(a0(w,["text"],ed,o0)));let m={baseUrl:`${td}/v1`,api:"openai-completions",apiKey:t.modelToken,models:x};return Object.keys(l).length>0&&(m.headers=l),m}var he=j("agent-handlers"),g0=5*1024*1024,Ey=1,vy=6,Sy=new Set(["node_modules",".git",".coze","dist","build",".next"]),Iy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ay=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,ky=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Ty(t){let e=t?.trim();return e?ky.test(e)||Ay.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Cy(t){return new Promise((e,r)=>{let i=ot("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),s=!1,c=l=>{s||(s=!0,l?r(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}var _o=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Zn(e._meta),i=await this.loadAgentCfg(r),s=i?.workspace??ze(r).workspace,c=i?.skills??[],l=[],u=new Set;for(let x of c){let h=pe(s,x.relPath,"SKILL.md");await fd(h).then(w=>w.isFile()).catch(()=>!1)&&(l.push(Ly(x)),u.add(x.relPath))}if(e.scanLocal){let x=i?.framework??"claude-code",h=await k0(r,s,x),m=await T0(r,x);for(let w of[...h,...m])u.has(w.relPath)||(u.add(w.relPath),l.push(w.skill))}return{skills:l}}async addSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),s=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((x,h)=>[x.skillId,h])),u=[];for(let x of s){let h=await yo({agentId:r,workspace:i.workspace,framework:i.framework,skill:x});bo(c,l,h),u.push(x)}return await ui(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),s=new Set(e.skillIds??[]),c=i.skills??[],l=[];for(let u of c){if(!s.has(u.skillId)){l.push(u);continue}let x=pe(i.workspace,u.relPath);await cd(x,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await ui(r,l),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Zn(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");he.info("_agent/publishSkill start",{agentId:r,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(r),s=i?.workspace??ze(r).workspace,c=i?.framework??"claude-code",l=e.isGlobal??!1,u=await Py(r,s,c,e.skillName,l);if(!u){let C=l?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${C}: ${e.skillName}`)}let{absDir:x,relPath:h,dirName:m}=u,w=pe(x,"SKILL.md"),S=new hd.default;S.addLocalFolder(x,m);let y=S.toBuffer();if(y.length>m0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${m0}`);let E=await wo(w,{encoding:"utf8"}).then(C=>I0(C).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):he.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??S0(r,h);if(i&&!l){let C=i.skills??[],b=C.find(R=>R.relPath===h);b?(b.version=A,b.skillId=T):C.push({skillId:T,skillName:e.skillName,relPath:h,version:A,installedAt:Date.now(),...E?{description:E}:{}}),await ui(r,C)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:h,zipBytes:y.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[s,c]of i.sessions){if(!c.downstream)continue;let l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:s,acpId:l});continue}let x=c.downstream;c.downstream=void 0,he.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:s,acpId:l}),x.stop(r).catch(h=>he.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:s,err:String(h)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return he.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Re(r);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return he.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await pr(i.workspace,i.framework,e.cozeIdentity)}catch(s){throw he.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(s)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(s)}`,{cause:s})}return i.cozeIdentity=e.cozeIdentity,await Ue(i),he.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Re(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let s=["-y"];e.registry&&zi(e.registry)&&s.push(`--registry=${e.registry}`);let c=Ty(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&Iy.test(l)&&s.push("--env",l);let u=await Cy(s);return he.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Re(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ue(i),he.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(he.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST",`${ht.DELETE}: missing agentId`);let i=await Re(r),s=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??s??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let l=ze(r);return c==="cloud"?await cd(l.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ue(i)),he.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Dr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=nd(e.model)??Nt,i=await Re(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ue(i),he.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return he.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=s.model;s.model=r,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s,c).catch(u=>he.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let l=[];for(let[u,x]of s.allSessionQueues())l.push(x.enqueue(async()=>{let h=s.sessions.get(u);h?.downstream&&(await h.downstream.stop(`switchModel: ${r}`).catch(()=>{}),h.downstream=void 0)}));return await Promise.all(l),he.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:l.length}),{ok:!0}}async resetAgent(e){if(Dr(e._meta,ht.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ht.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ht.RESET),await this.runDetailSync(e.agentId,ht.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),he.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let s=new Map;for(let[c,l]of i.sessions)s.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt});await li(e,s)}async clearPersistedAcpSessionIds(e){let r=await Re(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let s of Object.values(r.sessions))s.acpSessionId&&(s.acpSessionId=void 0,i=!0);i&&await Ue(r)}async repairAgent(e){if(Dr(e._meta,ht.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ht.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ht.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){he.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ht.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){he.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){he.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(s)})}}async getFileTree(e){Dr(e._meta,"_agent/getFileTree");let r=e._meta,i=Zn(r),s=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(s,c),u=await od(l).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await di(l,s))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let x=Ky(e.depth);return u.isDirectory()?{tree:await Wy(s,l,c,x)}:{tree:[{name:$y(c),path:P0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Dr(e._meta,"_agent/getFileContent");let r=Zn(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(i,e.filePath),c=await od(s).catch(()=>null);if(!c||!c.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await di(s,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>g0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${g0})`);let l=await wo(s);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await Re(e).catch(()=>null))?.workspace??ze(e).workspace}safeJoin(e,r){let i=ld(e,r||"."),s=xd(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${_0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Re(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function E0(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 pd(t){return t==="claude-code"?pe(".claude","skills"):pe(".agents","skills")}function v0(t){let e=_y();return t==="claude-code"?[pe(e,".claude","skills")]:t==="codex"?[pe(e,".agents","skills"),pe(e,".codex","skills")]:[pe(e,".agents","skills"),pe(e,".openclaw","skills")]}async function Ry(t,e,r,i){let s=async c=>fd(pe(c,"SKILL.md")).then(l=>l.isFile()).catch(()=>!1);if(!i){let c=pe(pd(e),r),l=pe(t,c);return await s(l)?{absDir:l,relPath:c}:null}for(let c of v0(e)){let l=pe(c,r);if(await s(l))return{absDir:l,relPath:l}}return null}async function Py(t,e,r,i,s){let c=E0(i),l=await Ry(e,r,c,s);if(l)return{...l,dirName:c};let x=(s?await T0(t,r):await k0(t,e,r)).filter(w=>w.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${s?"global":"workspace"}: ${x.map(w=>p0(w.relPath)).join(", ")} \u2014 rename or remove duplicates`);let h=x[0];return h?{absDir:s?h.relPath:pe(e,h.relPath),relPath:h.relPath,dirName:p0(h.relPath)}:null}function S0(t,e){return(wy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function I0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
- ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let s of r.split(`
94
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(s);if(!c||!c[2])continue;let l=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function A0(t,e,r,i){let s=await w0(e,{withFileTypes:!0}).catch(()=>null);if(!s)return[];let c=[];for(let l of s){let u=l.isDirectory();if(!u&&l.isSymbolicLink()&&(u=!!(await fd(pe(e,l.name)).catch(()=>null))?.isDirectory()),!u)continue;let x=l.name,h=pe(r,x),m=pe(e,x,"SKILL.md"),w=await wo(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let S=I0(w);c.push({relPath:h,skill:{skillId:S0(t,h),skillName:S.name||x,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function k0(t,e,r){let i=pd(r);return A0(t,pe(e,i),i,!1)}async function T0(t,e){let r=[],i=new Set;for(let s of v0(e)){let c=await A0(t,s,s,!0);for(let l of c)i.has(l.relPath)||(i.add(l.relPath),r.push(l))}return r}var Dy=3e4,Oy=50*1024*1024,m0=10*1024*1024,Nr=3e4;async function yo(t){let{agentId:e,workspace:r,framework:i,skill:s}=t;if(!s.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let c=typeof s.content=="string"&&s.content.length>0,l=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!c&&!l)throw new k("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let u=E0(s.skillName),x=pd(i),h=pe(x,u),m=pe(r,h);if(await ad(m,{recursive:!0}),c){let S=Buffer.from(s.content,"utf8");qi(S.length),await dd(pe(m,"SKILL.md"),S,"utf8")}else{let S=await My(s.downloadUrl);Fy(S)?await qy(S,m):zy(S)?await Uy(S,m):await dd(pe(m,"SKILL.md"),S.toString("utf8"),"utf8")}let w={skillId:s.skillId,skillName:s.skillName,relPath:h,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return he.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:h,source:c?"content":"downloadUrl"}),w}function bo(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function Ly(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}function Ny(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 C0(t,e){let r=await Re(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Lt,s=r.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return r.skillsRefreshedForVersion=i,await Ue(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],l=new Map(c.map((m,w)=>[m.skillId,w])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Ue(r,e),{status:"noop",count:0};let x=0,h=0;for(let m of u)try{await cd(pe(r.workspace,m.relPath),{recursive:!0,force:!0});let w=await yo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Ny(m)});bo(c,l,w),x+=1}catch(w){h+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(w)})}return r.skills=c,h===0&&(r.skillsRefreshedForVersion=i),await Ue(r,e),he.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:x,failed:h}),{status:"refreshed",count:x}}async function My(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 r=By(t);return qi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await wo(e);return qi(r.length),r}if(zi(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Dy);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let s=await i.arrayBuffer();return qi(s.byteLength),Buffer.from(s)}finally{clearTimeout(r)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function qi(t){if(t>Oy)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function By(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function Fy(t){return t.length>=2&&t[0]===31&&t[1]===139}function zy(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function ud(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Uy(t,e){let r,i;try{r=new hd.default(t),i=r.getEntries()}catch(l){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||ud(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(h=>h===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let x=l.header.attr>>>16&61440;if(x!==0&&x!==32768&&x!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${x.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let s=Hy(i),c=ld(e);for(let l of i){if(ud(l.entryName))continue;let u=l.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let x=ld(e,u),h=xd(c,x);if(h.startsWith("..")||h==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await ad(x,{recursive:!0});continue}await ad(yy(x),{recursive:!0});let m;try{m=l.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${w.message}`,{cause:w})}await dd(x,m)}}function Hy(t){let e;for(let r of t){let i=r.entryName;if(!i||ud(i))continue;let s=i.indexOf("/");if(s<=0)return;let c=i.slice(0,s+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function qy(t,e){await Gy(t);let r=Kf({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Nr}ms)`))},Nr);try{await b0(y0.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Nr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}}async function Gy(t){let e=[],r=Pr({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(h=>h==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,s=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Nr}ms)`))},Nr);try{await b0(y0.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Nr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(s)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var jy=5e3;async function Wy(t,e,r,i){return R0(t,e,r,i,{count:0})}async function R0(t,e,r,i,s){if(i<=0)return[];let c;try{c=await w0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(Sy.has(u.name)||u.isSymbolicLink())continue;if(s.count>=jy){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let x=pe(e,u.name),h=by(pe(r,u.name)),m=null;try{m=await od(x)}catch{continue}if(m.isSymbolicLink())continue;s.count++;let w={name:u.name,path:P0(xd(t,x)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await R0(t,x,h,i-1,s)),l.push(w)}return l.sort((u,x)=>u.isDir!==x.isDir?u.isDir?-1:1:u.name.localeCompare(x.name)),l}function Ky(t){return!t||t<=0?Ey:Math.min(t,vy)}function $y(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function P0(t){return t.split(_0).join("/")}ie();var Tn=j("agent-health-reporter"),Vy=1e4,Jy=3,Gi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Vy,this.livenessFailureThreshold=e.livenessFailureThreshold??Jy}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Tn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Tn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Tn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Tn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let l of this.opts.core.agents.values()){let u=Zy(l);if(!u)continue;let x={agentId:l.agentId,status:u};l.patToken&&(x.patToken=l.patToken),l.accountId&&(x.accountId=l.accountId),r.push(x)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Lt,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,Tn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=s?.authFailures;if(c&&c.length>0&&(Tn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(l=>l.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(l){Tn.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){Tn.warn("onTickEnd hook failed",{err:String(r)})}}};function Zy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}hn();import{copyFile as xE,cp as hE,mkdir as Oo,readFile as pE,rm as gE,stat as Sd,writeFile as mE}from"node:fs/promises";import{homedir as fx}from"node:os";import{basename as wE,join as Xt}from"node:path";dn();import{existsSync as db}from"node:fs";import{release as lb}from"node:os";import{basename as ub,isAbsolute as fb}from"node:path";function ji(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Mr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Br(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Cn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var Eo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function D0(t){return"method"in t&&"id"in t&&t.id!==void 0}function O0(t){return"method"in t&&!("id"in t)}function vo(t){return!("method"in t)&&"id"in t}var Yy={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function Xy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Wi(t.message)}:typeof t=="string"?Wi(t):typeof t=="object"?eb(t):t}var Qy=[[/\/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 Wi(t){let e=t;for(let[r,i]of Qy)e=e.replace(r,i);return e}function eb(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Wi(i):e[r]=i;return e}function Ki(t){if(t instanceof k){let e=Xy(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(r.reason=e.reason),{code:Yy[t.code]??Y.INTERNAL_ERROR,message:Wi(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:Wi(t instanceof Error?t.message:String(t))}}function L0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,s=i?e?.message:t.message,c=t.data;if(i&&e){let{message:l,...u}=e;c=u}return new k(r,s,{retriable:e?.retriable??!1,cause:c})}function M0(t){return`${JSON.stringify(t)}
95
- `}var N0=10*1024*1024,So=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>N0){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${N0} bytes`)}),[]}let r=this.buffer.split(`
96
- `);this.buffer=r.pop()??"";let i=[];for(let s of r){let c=s.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var F0={"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"},DT=Object.fromEntries(Object.entries(F0).map(([t,e])=>[e,t])),tb={"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:[]},Fr=class{seq=0;next(e,r){this.seq+=1;let i=F0[e]??nb(e),s=tb[i]??[],c=[i,String(this.seq)];if(s.length>0){let l=s.map(x=>B0(r?.[x]??"")),u=rb(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>B0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function nb(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function B0(t){return t.replace(/[:_\s]+/g,"-")}function rb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}xn();import{readFileSync as ib}from"node:fs";var sb=384;async function gd(t,e=process.env){let r={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(r[i]=s);await fn(t.agentEnvFile,r,{mode:sb})}function $i(t){try{let e=JSON.parse(ib(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Io(t,e,r={},i=s=>s){return{...i({...t,...$i(e)}),...r}}Zt();lr();Ve();ie();Ce();import{execFileSync as ob,spawnSync as ab}from"node:child_process";function Vi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Ji(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),ab("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var md=new Set;function z0(t){typeof t=="number"&&t>0&&md.add(t)}function U0(t){typeof t=="number"&&md.delete(t)}function H0(){for(let t of md)Ji(t,"SIGKILL")}var zr="coze-bridge-daemon";function q0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return ob("pgrep",["-U",String(s),"-f",zr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
- `).map(s=>Number.parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0&&s!==i)}async function G0(t,e){if(t.length===0)return;let r=e?.killFn??Ji,i=e?.isAliveFn??Vi,s=e?.sleepFn??(u=>new Promise(x=>setTimeout(x,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(x=>i(x));u+=l)await s(Math.min(l,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var cb=[{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:"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 j0(t,e){if(!e)return null;for(let r of cb)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function W0(t,e){return j0(t,e)}function K0(t,e){return j0(t,e)}function Ur(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function $0(t,e,r){let s=r-t.armedAt-t.expectedIntervalMs;if(s>e.suspendThresholdMs){let h=t.suspendedMs+s,m=r-t.startedAt-h;return{action:"suspend",suspendedDeltaMs:s,rearmMs:Ur(m,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Ur(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Ur(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Ur(c,!1,e)}}var V0=Ye("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),xb=200,hb=40,pb=Ye("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),gb=Ye("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),mb=Ye("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),wb=Ye("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),_b=Ye("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),yb=Ye("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),J0=500;function bb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=J0?t:`${e.slice(0,J0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Eb(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:r}=t;if(typeof r=="string")e.push(r);else if(r&&typeof r=="object")try{e.push(JSON.stringify(r))}catch{}return e.join(" ")}function Z0(t){try{return db(t)}catch{return}}function vb(t,e){return{platform:process.platform,osRelease:lb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:fb(e.command)?Z0(e.command):void 0,cwd:e.cwd,cwdExists:Z0(e.cwd),envKeys:e.envKeys}}function Sb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${ub(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Mt=class{constructor(e){this.opts=e;this.log=j(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new So({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Fr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=Io(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=ot(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,z0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",s=>{try{for(let c of this.decoder.push(s))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",s=>{let c=s.trimEnd();this.stderrRing.push(c),this.stderrRing.length>xb&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",s=>{this.log.warn("child stdin error",{err:String(s)})}),i.stdout?.on("error",s=>{this.log.warn("child stdout error",{err:String(s)})}),i.stderr?.on("error",s=>{this.log.warn("child stderr error",{err:String(s)})}),i.on("exit",(s,c)=>{this.stopped=!0,U0(i.pid),(s!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:s,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(s,c));for(let u of this.exitHandlers)u(s,c)}),i.on("error",s=>{let c=s,l=vb(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(s),diag:l}),this.failAllPending(new k("AGENT_SPAWN_FAILED",Sb(c,l),{cause:l}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Ji(r.pid,"SIGTERM");let s=setTimeout(()=>{r.killed||Ji(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:_b,phase2GateMs:pb,livenessWindowMs:gb,absoluteMaxMs:mb,approvalMaxMs:yb,suspendThresholdMs:wb,...r};return this.call("session/prompt",e,V0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Mr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Br(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Cn(e,r))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,i=V0,s){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=ji(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let x=r.sessionId;return typeof x=="string"?x:void 0})();return new Promise((x,h)=>{let m={resolve:x,reject:h,timer:null,method:e,promptTimeout:null};if(s){let w=this.now(),S={cfg:s,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Ur(0,!1,s),sessionId:u};m.promptTimeout=S;let y=()=>{let E={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=$0(E,S.cfg,I),T=C=>{S.armedAt=I,S.expectedIntervalMs=C,m.timer=setTimeout(y,C)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),h(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),h(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(y,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),h(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(l)}catch(w){m.timer&&clearTimeout(m.timer),this.pending.delete(c),h(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(M0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(vo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new k("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:bb(e.result)}),r.resolve(e.result));return}if(O0(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let s=i.promptTimeout;s&&(s.firstFrameSeen=!0,s.lastActivityAt=this.now(),this.trackToolCall(s,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(s=>this.log.warn("update handler failed (async)",{err:String(s)}))}catch(s){this.log.warn("update handler threw sync, swallowed",{err:String(s)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(D0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,s=i?.sessionUpdate;if(s!=="tool_call"&&s!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";s==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Cn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(Cn(e.id,Ki(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=L0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=K0(this.framework,Eb(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(hb).join(`
98
- `),s=W0(this.framework,i);return s?new k(s.bridgeCode,s.message,{cause:{reason:s.reason,code:e,signal:r,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Ib(t){let e={};for(let[r,i]of Object.entries(t))i!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=i));return e}var Ao=class extends Mt{framework="claude-code";constructor(e){let{command:r,args:i}=ci("claude-code",e.command,e.args??[]),s={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return Ib(e)}};dn();import{spawn as Ab}from"node:child_process";import{closeSync as kb,existsSync as yd,mkdirSync as Tb,mkdtempSync as Cb,openSync as Rb,readFileSync as nx,readSync as Pb,readdirSync as Db,rmSync as Ob,statSync as Lb}from"node:fs";import{homedir as Nb,tmpdir as Mb}from"node:os";import{join as Hr}from"node:path";var Y0=["default","acceptEdits","plan","auto","bypassPermissions"],X0=["read-only","auto","full-access"];function Bt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Y0.includes(e);case"codex":return X0.includes(e);case"openclaw":return!1}}function ko(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Q0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function wd(t){switch(t){case"claude-code":return Y0.join("/");case"codex":return X0.join("/");case"openclaw":return""}}Ce();var bd=9e4,Bb=64*1024,Fb=100;function zb(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?bd:Math.max(1,Math.floor(e*1e3))}function Ub(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?bd:Math.max(1,Math.floor(e))}function Hb(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[r,i]of Object.entries(t))typeof i=="string"&&(e[r]=i);return Object.keys(e).length>0?e:void 0}function ex(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:bd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let r=typeof e.command=="string"?e.command.trim():"";if(!r)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,s=Hb(e.env);return{command:r,timeoutMs:e.timeout_ms===void 0?zb(e.timeout):Ub(e.timeout_ms),...i?{cwd:i}:{},...s?{env:s}:{}}}function _d(t){if(Array.isArray(t))return t.flatMap(i=>_d(i));if(!t||typeof t!="object"){let i=ex(t);return i?[i]:[]}let e=t;if(e.hooks)return _d(e.hooks);let r=ex(e);return r?[r]:[]}function qb(t){let e=Hr(t,"hooks.json");if(!yd(e))return[];let r=JSON.parse(nx(e,"utf8")),s=r.hooks&&typeof r.hooks=="object"?r.hooks:r;return _d(s.Stop??s.stop)}function Gb(t,e){let r=Hr(t,"sessions");if(!yd(r))return;let i=[],s=c=>{let l;try{l=Db(c,{withFileTypes:!0})}catch{return}for(let u of l){let x=Hr(c,u.name);if(u.isDirectory())s(x);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:x,mtimeMs:Lb(x).mtimeMs})}catch{}}};s(r),i.sort((c,l)=>l.mtimeMs-c.mtimeMs);for(let c of i.slice(0,Fb))if(jb(c.path,e))return c.path}function jb(t,e){let r;try{r=Rb(t,"r");let i=Buffer.alloc(Bb),s=Pb(r,i,0,i.length,0),c=i.subarray(0,s).toString("utf8");return c.includes(JSON.stringify(e))||c.includes(e)}catch{return!1}finally{if(r!==void 0)try{kb(r)}catch{}}}function Wb(t){return $i(t??Z().agentEnvFile)}function Kb(t){let e=t.trim();if(e.length>=2){let r=e[0];if((r==='"'||r==="'")&&e.endsWith(r)){let i=e.slice(1,-1);return r==='"'?i.replace(/\\n/g,`
99
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function $b(t){let e={};for(let r of t.split(/\r?\n/)){let i=r.trim();if(!i||i.startsWith("#"))continue;let s=i.startsWith("export ")?i.slice(7).trimStart():i,c=s.indexOf("=");if(c<=0)continue;let l=s.slice(0,c).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(l)&&(e[l]=Kb(s.slice(c+1)))}return e}function Vb(t){let e=Hr(t,"cozeloop.env");return yd(e)?$b(nx(e,"utf8")):{}}function tx(t){let e=t?.trim();return e||void 0}function Jb(t){let e=Wb(t.agentEnvFile),r=tx(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(r)return r;let i=tx(t.env?.HOME??e.HOME??process.env.HOME)??Nb();return Hr(i,".codex")}var To=class extends Mt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:s,args:c}=ci("codex",e.command,i),l=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Cb(Hr(Mb(),"coze-bridge-codex-home-")):Jb(e),u=!!e.isolateCodexHome&&!!l&&!e.codexHomeDir&&e.env?.CODEX_HOME!==l;e.isolateCodexHome&&l&&!u&&Tb(l,{recursive:!0});let x=e.isolateCodexHome&&l?{...e.env??{},CODEX_HOME:l}:e.env,h={command:s,args:c,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...x?{env:x}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=l,this.cleanupCodexHomeDir=u}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async sessionPrompt(e){let r=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),r}setSessionMode(e){let r=Bt("codex",e.modeId)?ko(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(Zb(r)))}async runStopHooksBestEffort(e){let r=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!r)return;let i;try{i=qb(r)}catch(l){this.log.warn("codex stop hook load failed",{codexHomeDir:r,err:String(l)});return}if(i.length===0)return;let s=Gb(r,e),c=JSON.stringify({hook_event_name:"Stop",session_id:e,...s?{transcript_path:s}:{},trigger:"coze-bridge"});await Promise.all(i.map(async l=>{try{await this.runHookCommand(l,c)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:r,command:l.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,r){return new Promise((i,s)=>{let c=this.codexHomeDir??this.opts.env?.CODEX_HOME,l=c?Vb(c):{},u=Io(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...l,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let x=Ab(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),h="",m=setTimeout(()=>{x.kill("SIGTERM"),s(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);x.stderr?.setEncoding("utf8"),x.stderr?.on("data",w=>{h+=w,h.length>4e3&&(h=h.slice(-4e3))}),x.on("error",w=>{clearTimeout(m),s(w)}),x.on("close",(w,S)=>{if(clearTimeout(m),w===0){i();return}s(new Error(`hook exited code=${w} signal=${S} stderr=${h.slice(-1e3)}`))}),x.stdin.end(`${r}
100
- `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{Ob(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Zb(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=Q0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}Ve();var Yb=3e4,qr=class extends Mt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let s={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Yb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};xn();Ve();ie();Ce();function Ed(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}dn();var Rn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((r,i)=>{this.slots.push({task:e,resolve:r,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var Co=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new Rn,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,i]of this.sessions)Gr(i),i.downstream&&(r.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Gr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Yt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Zt();ie();import{constants as rx}from"node:fs";import{access as Xb}from"node:fs/promises";import{delimiter as Qb,join as eE}from"node:path";var St=j("framework-detector"),ix={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},tE=[".exe",".cmd",".bat",".ps1"],Yn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??ot,access:e.access??Xb}}async detect(e){let r=ix[e],i=await this.which(r);if(!i)return St.debug("framework binary not found",{framework:e,bin:r}),null;let s=e==="openclaw"?["--log-level","silent"]:[],[c,l]=await Promise.all([this.probeVersion(i,s),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(ix).map(async i=>[i,await this.detect(i)])),r={};for(let[i,s]of e)s&&(r[i]=s);return r}async which(e){let r=this.env.pathEnv.split(Qb).filter(Boolean),i=this.env.platform==="win32"?["",...tE]:[""];for(let s of r)for(let c of i){let l=eE(s,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?rx.F_OK:rx.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return St.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return St.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return St.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let s=JSON.parse(i[0]);if(!Array.isArray(s))return St.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=s.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(St.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(St.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return St.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(s),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return St.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||St.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let s={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let l=JSON.parse(c[0]);typeof l.gateway?.port=="number"&&(s.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(s.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(s.detail=l.rpc.error)}catch(l){St.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return s}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(rE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let s="",c=!1,l,u=x=>{c||(c=!0,l&&clearTimeout(l),i(x))};try{let x=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});l=setTimeout(()=>{x.kill("SIGKILL"),u(null)},15e3),x.stdout?.on("data",h=>{s+=h.toString("utf8")}),x.on("error",()=>u(null)),x.on("close",h=>u({code:h,stdout:s}))}catch{u(null)}})}},nE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function rE(t){return t.replace(nE,"")}import{homedir as ox}from"node:os";import{join as Po}from"node:path";xn();Zt();lr();Ve();ie();async function ax(){let t=Po(ox(),".openclaw/openclaw.json");return ln(t)}async function cx(){return(await ax())?.gateway?.auth?.token??""}var Xn=j("openclaw.config"),iE=[0,5e3,5e3],sE=Ye("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),sx="models.providers.",Ro="agents.defaults.models",oE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function jr(t,e){let r=Array.isArray(t)?[...t]:[],i=new Set(r);for(let s of e)i.has(s)||(i.add(s),r.push(s));return r}var Do=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Rn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??iE,this.cliTimeoutMs=e.cliTimeoutMs??sE,this.openclawDir=e.openclawDir??Po(ox(),".openclaw")}async withRetry(e,r){let i;for(let s=0;s<this.retryDelaysMs.length;s++){let c=this.retryDelaysMs[s]??0;c>0&&await new Promise(l=>setTimeout(l,c));try{return await r()}catch(l){i=l,Xn.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(l)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let s=ot(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=h=>{l||(l=!0,clearTimeout(x),h())};s.stderr?.on("data",h=>{c+=h.toString("utf8")});let x=setTimeout(()=>{u(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);x.unref(),s.on("error",h=>u(()=>i(h))),s.on("close",h=>u(()=>{h===0?r():i(new Error(`exit ${h}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let s=String(i);if(r.some(c=>s.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",r],["Config path not found","Nothing was changed"])))}catch(i){Xn.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${sx}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${sx}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ro}[${e}]`,()=>this.runCli(["config","set",Ro,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ro}[${e}]`,`${Ro}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await ax())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let s=`${e}/`,c=[];for(let l of Object.keys(i))l.startsWith(s)&&c.push(l.slice(s.length));return c}ensureAgent(e,r,i){let s=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&s.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["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=Po(this.openclawDir,"identity","device.json"),i=(await ln(e))?.deviceId?.trim();if(!i)return Xn.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let s=Po(this.openclawDir,"devices","paired.json"),c=await ln(s),l=c?.[i];if(!c||!l)return Xn.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=l.tokens?.operator,x=jr(jr(l.scopes,l.approvedScopes??[]),u?.scopes??[]).filter(E=>E.startsWith("operator.")),h=jr([...oE],x),m=jr(l.scopes,h),w=jr(l.approvedScopes,h),S=u?jr(u.scopes,h):void 0;return m.length!==(l.scopes?.length??0)||w.length!==(l.approvedScopes?.length??0)||u!==void 0&&S?.length!==(u.scopes?.length??0)?(l.scopes=m,l.approvedScopes=w,u&&S&&(u.scopes=S),await fn(s,c,{mode:384}),Xn.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:h}),!0):(Xn.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return Xn.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 aE,writeFile as cE}from"node:fs/promises";import{join as dE}from"node:path";var lE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
101
- `),uE=["# 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(`
102
- `);function fE(t){return t.length===0?t:`${(t.endsWith(`
89
+ `},configPath(t){return gA(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await ig("schtasks",["/Create","/SC","ONLOGON","/TN",Ca,"/TR",n,"/RU",t.userName,"/F"]),vl.info("task scheduler entry created",{task:Ca,logFile:t.logFile})},async uninstall(t){await ig("schtasks",["/Delete","/TN",Ca,"/F"]).catch(e=>vl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),vl.info("task scheduler entry removed",{task:Ca})}}});var og={};Ka(og,{buildContext:()=>EA,getSupervisor:()=>_A,launchdSupervisor:()=>bl,systemdSupervisor:()=>El,taskSchedulerSupervisor:()=>Sl});import{homedir as mA,userInfo as wA}from"node:os";function _A(t=process.platform){switch(t){case"darwin":return bl;case"linux":return El;case"win32":return Sl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function bA(){let t={};for(let e of yA){let n=process.env[e];n&&(t[e]=n)}return t}function EA(){let t=J();return{nodeBin:process.execPath,entry:fl(t),logFile:t.logFile,homeDir:mA(),userName:wA().username,isRoot:process.getuid?.()===0,env:bA()}}var yA,ag=st(()=>{"use strict";Ce();ba();tg();rg();sg();yA=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();xn();var eu=K("acp-installer-warmup"),Om=["claude-code","codex"];async function tu(t={}){let e=t.ensure??wr,i=(await Promise.allSettled(Om.map(async s=>{let a=await e(s);eu.info("acp wrapper warmup ok",{framework:s,path:a})}))).filter(s=>s.status==="rejected");i.length>0&&eu.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(s=>s.reason instanceof Error?s.reason.message:String(s.reason))})}Vt();ne();import{readdir as Zm}from"node:fs/promises";import{mkdir as su,readFile as $m,writeFile as ou}from"node:fs/promises";import{join as Xa}from"node:path";var Vm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function _r(t,e,n){await su(t,{recursive:!0});let i=Vm[e],s=Xa(t,i);return await ou(s,n??"","utf8"),s}async function Qa(t,e,n){let i=Xa(t,".claude");await su(i,{recursive:!0});let s=Xa(i,"settings.local.json"),a={};try{let u=await $m(s,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(a=h)}catch{}let d=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return a.permissions=d,await ou(s,JSON.stringify(a,null,2),"utf8"),s}var nt=K("agent-detail-sync"),Jm=6e4,Ym=5*6e4,Rs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Zm(n)}catch(s){nt.info("agents dir not found, skip detail sync",{root:n,err:String(s)});return}nt.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let a=await ke(s,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){nt.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,a)}catch(d){nt.warn("detail sync failed for agent, skipping",{agentId:s,err:String(d)})}}})),nt.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,s]of this.retryQueue)e>=s.dueAt&&n.push(i);if(n.length!==0){nt.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(s){nt.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,n){let i=n??await ke(e,this.opts.paths);if(!i){nt.info("detail sync: agent config missing, skip",{agentId:e});return}let s;try{s=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){nt.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,Ym):Jm;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(s.agentId&&s.agentId!==e){nt.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:s.agentId});return}let a=!1,d=!1;s.agentName&&s.agentName!==i.agentName&&(i.agentName=s.agentName,a=!0),s.description!==void 0&&s.description!==i.description&&(i.description=s.description,a=!0),s.cozeIdentity&&s.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=s.cozeIdentity,a=!0,d=!0);let u=!1;if(s.deployType==="cloud"&&i.deployType!=="cloud"?(nt.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):s.deployType&&nt.info("detail.deployType",{agentId:e,deployType:s.deployType}),!a){nt.debug("detail sync: no diff",{agentId:e});return}await je(i,this.opts.paths),nt.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}),nt.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await _r(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Ad=Wt(zu(),1);import{createHash as Hy}from"node:crypto";import{lstat as wd,mkdir as _d,readFile as To,readdir as R0,rm as yd,stat as Sd,writeFile as bd}from"node:fs/promises";import{homedir as Gy}from"node:os";import{basename as P0,dirname as qy,join as xe,normalize as jy,relative as Id,resolve as Ed,sep as O0}from"node:path";import{Readable as L0}from"node:stream";import{pipeline as N0}from"node:stream/promises";import _w from"events";import at from"fs";import{EventEmitter as Qc}from"node:events";import Ef from"node:stream";import{StringDecoder as yw}from"node:string_decoder";import If from"node:path";import Cr from"node:fs";import{dirname as Ow,parse as Lw}from"path";import{EventEmitter as Gw}from"events";import Lc from"assert";import{Buffer as Vn}from"buffer";import*as ju from"zlib";import qw from"zlib";import{posix as Sr}from"node:path";import{basename as m_}from"node:path";import uo from"fs";import Mt from"fs";import Xu from"path";import{win32 as D_}from"node:path";import of from"path";import Uf from"node:fs";import $_ from"node:assert";import{randomBytes as Hf}from"node:crypto";import ce from"node:fs";import He from"node:path";import Gf from"fs";import yo from"node:fs";import Bi from"node:path";import ut from"node:fs";import ey from"node:fs/promises";import xo from"node:path";import{join as Qf}from"node:path";import lt from"node:fs";import n0 from"node:path";var mw=Object.defineProperty,ww=(t,e)=>{for(var n in e)mw(t,n,{get:e[n],enumerable:!0})},Uu=typeof process=="object"&&process?process:{stdout:null,stderr:null},bw=t=>!!t&&typeof t=="object"&&(t instanceof Yn||t instanceof Ef||Ew(t)||vw(t)),Ew=t=>!!t&&typeof t=="object"&&t instanceof Qc&&typeof t.pipe=="function"&&t.pipe!==Ef.Writable.prototype.pipe,vw=t=>!!t&&typeof t=="object"&&t instanceof Qc&&typeof t.write=="function"&&typeof t.end=="function",Zt=Symbol("EOF"),Jt=Symbol("maybeEmitEnd"),wn=Symbol("emittedEnd"),Bs=Symbol("emittingEnd"),_i=Symbol("emittedError"),Fs=Symbol("closed"),Hu=Symbol("read"),zs=Symbol("flush"),Gu=Symbol("flushChunk"),St=Symbol("encoding"),vr=Symbol("decoder"),Ke=Symbol("flowing"),yi=Symbol("paused"),Tr=Symbol("resume"),We=Symbol("buffer"),rt=Symbol("pipes"),$e=Symbol("bufferLength"),sc=Symbol("bufferPush"),Us=Symbol("bufferShift"),et=Symbol("objectMode"),Re=Symbol("destroyed"),oc=Symbol("error"),ac=Symbol("emitData"),qu=Symbol("emitEnd"),cc=Symbol("emitEnd2"),Rt=Symbol("async"),dc=Symbol("abort"),Hs=Symbol("aborted"),bi=Symbol("signal"),zn=Symbol("dataListeners"),dt=Symbol("discarded"),Ei=t=>Promise.resolve().then(t),Sw=t=>t(),Iw=t=>t==="end"||t==="finish"||t==="prefinish",Aw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,kw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),vf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Tr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Tw=class extends vf{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)}},Pw=t=>!!t.objectMode,Dw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Yn=class extends Qc{[Ke]=!1;[yi]=!1;[rt]=[];[We]=[];[et];[St];[Rt];[vr];[Zt]=!1;[wn]=!1;[Bs]=!1;[Fs]=!1;[_i]=null;[$e]=0;[Re]=!1;[bi];[Hs]=!1;[zn]=0;[dt]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Pw(e)?(this[et]=!0,this[St]=null):Dw(e)?(this[St]=e.encoding,this[et]=!1):(this[et]=!1,this[St]=null),this[Rt]=!!e.async,this[vr]=this[St]?new yw(this[St]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[We]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[rt]});let{signal:n}=e;n&&(this[bi]=n,n.aborted?this[dc]():n.addEventListener("abort",()=>this[dc]()))}get bufferLength(){return this[$e]}get encoding(){return this[St]}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[et]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Rt]}set async(t){this[Rt]=this[Rt]||!!t}[dc](){this[Hs]=!0,this.emit("abort",this[bi]?.reason),this.destroy(this[bi]?.reason)}get aborted(){return this[Hs]}set aborted(t){}write(t,e,n){if(this[Hs])return!1;if(this[Zt])throw new Error("write after end");if(this[Re])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Rt]?Ei:Sw;if(!this[et]&&!Buffer.isBuffer(t)){if(kw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Aw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[et]?(this[Ke]&&this[$e]!==0&&this[zs](!0),this[Ke]?this.emit("data",t):this[sc](t),this[$e]!==0&&this.emit("readable"),n&&i(n),this[Ke]):t.length?(typeof t=="string"&&!(e===this[St]&&!this[vr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[St]&&(t=this[vr].write(t)),this[Ke]&&this[$e]!==0&&this[zs](!0),this[Ke]?this.emit("data",t):this[sc](t),this[$e]!==0&&this.emit("readable"),n&&i(n),this[Ke]):(this[$e]!==0&&this.emit("readable"),n&&i(n),this[Ke])}read(t){if(this[Re])return null;if(this[dt]=!1,this[$e]===0||t===0||t&&t>this[$e])return this[Jt](),null;this[et]&&(t=null),this[We].length>1&&!this[et]&&(this[We]=[this[St]?this[We].join(""):Buffer.concat(this[We],this[$e])]);let e=this[Hu](t||null,this[We][0]);return this[Jt](),e}[Hu](t,e){if(this[et])this[Us]();else{let n=e;t===n.length||t===null?this[Us]():typeof n=="string"?(this[We][0]=n.slice(t),e=n.slice(0,t),this[$e]-=t):(this[We][0]=n.subarray(t),e=n.subarray(0,t),this[$e]-=t)}return this.emit("data",e),!this[We].length&&!this[Zt]&&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[Zt]=!0,this.writable=!1,(this[Ke]||!this[yi])&&this[Jt](),this}[Tr](){this[Re]||(!this[zn]&&!this[rt].length&&(this[dt]=!0),this[yi]=!1,this[Ke]=!0,this.emit("resume"),this[We].length?this[zs]():this[Zt]?this[Jt]():this.emit("drain"))}resume(){return this[Tr]()}pause(){this[Ke]=!1,this[yi]=!0,this[dt]=!1}get destroyed(){return this[Re]}get flowing(){return this[Ke]}get paused(){return this[yi]}[sc](t){this[et]?this[$e]+=1:this[$e]+=t.length,this[We].push(t)}[Us](){return this[et]?this[$e]-=1:this[$e]-=this[We][0].length,this[We].shift()}[zs](t=!1){do;while(this[Gu](this[Us]())&&this[We].length);!t&&!this[We].length&&!this[Zt]&&this.emit("drain")}[Gu](t){return this.emit("data",t),this[Ke]}pipe(t,e){if(this[Re])return t;this[dt]=!1;let n=this[wn];return e=e||{},t===Uu.stdout||t===Uu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[rt].push(e.proxyErrors?new Tw(this,t,e):new vf(this,t,e)),this[Rt]?Ei(()=>this[Tr]()):this[Tr]()),t}unpipe(t){let e=this[rt].find(n=>n.dest===t);e&&(this[rt].length===1?(this[Ke]&&this[zn]===0&&(this[Ke]=!1),this[rt]=[]):this[rt].splice(this[rt].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[dt]=!1,this[zn]++,!this[rt].length&&!this[Ke]&&this[Tr]();else if(t==="readable"&&this[$e]!==0)super.emit("readable");else if(Iw(t)&&this[wn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[_i]){let i=e;this[Rt]?Ei(()=>i.call(this,this[_i])):i.call(this,this[_i])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[zn]=this.listeners("data").length,this[zn]===0&&!this[dt]&&!this[rt].length&&(this[Ke]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[zn]=0,!this[dt]&&!this[rt].length&&(this[Ke]=!1)),e}get emittedEnd(){return this[wn]}[Jt](){!this[Bs]&&!this[wn]&&!this[Re]&&this[We].length===0&&this[Zt]&&(this[Bs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Fs]&&this.emit("close"),this[Bs]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Re&&this[Re])return!1;if(t==="data")return!this[et]&&!n?!1:this[Rt]?(Ei(()=>this[ac](n)),!0):this[ac](n);if(t==="end")return this[qu]();if(t==="close"){if(this[Fs]=!0,!this[wn]&&!this[Re])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[_i]=n,super.emit(oc,n);let s=!this[bi]||this.listeners("error").length?super.emit("error",n):!1;return this[Jt](),s}else if(t==="resume"){let s=super.emit("resume");return this[Jt](),s}else if(t==="finish"||t==="prefinish"){let s=super.emit(t);return this.removeAllListeners(t),s}let i=super.emit(t,...e);return this[Jt](),i}[ac](t){for(let n of this[rt])n.dest.write(t)===!1&&this.pause();let e=this[dt]?!1:super.emit("data",t);return this[Jt](),e}[qu](){return this[wn]?!1:(this[wn]=!0,this.readable=!1,this[Rt]?(Ei(()=>this[cc]()),!0):this[cc]())}[cc](){if(this[vr]){let e=this[vr].end();if(e){for(let n of this[rt])n.dest.write(e);this[dt]||super.emit("data",e)}}for(let e of this[rt])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[et]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[et]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[et])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[St]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Re,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[dt]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[Zt])return e();let i,s,a=x=>{this.off("data",d),this.off("end",u),this.off(Re,h),e(),s(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(Re,h),this.pause(),i({value:x,done:!!this[Zt]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Re,h),e(),i({done:!0,value:void 0})},h=()=>a(new Error("stream destroyed"));return new Promise((x,g)=>{s=g,i=x,this.once(Re,h),this.once("error",a),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[dt]=!1;let t=!1,e=()=>(this.pause(),this.off(oc,e),this.off(Re,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(oc,e),this.once(Re,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Re])return t?this.emit("error",t):this.emit(Re),this;this[Re]=!0,this[dt]=!0,this[We].length=0,this[$e]=0;let e=this;return typeof e.close=="function"&&!this[Fs]&&e.close(),t?this.emit("error",t):this.emit(Re),this}static get isStream(){return bw}},Cw=at.writev,kn=Symbol("_autoClose"),Tt=Symbol("_close"),vi=Symbol("_ended"),he=Symbol("_fd"),lc=Symbol("_finished"),en=Symbol("_flags"),uc=Symbol("_flush"),Rc=Symbol("_handleChunk"),Oc=Symbol("_makeBuf"),Ni=Symbol("_mode"),Gs=Symbol("_needDrain"),Or=Symbol("_onerror"),Lr=Symbol("_onopen"),fc=Symbol("_onread"),Pr=Symbol("_onwrite"),Tn=Symbol("_open"),kt=Symbol("_path"),En=Symbol("_pos"),Ot=Symbol("_queue"),Dr=Symbol("_read"),hc=Symbol("_readSize"),Qt=Symbol("_reading"),Si=Symbol("_remain"),xc=Symbol("_size"),Xs=Symbol("_write"),Un=Symbol("_writing"),Qs=Symbol("_defaultFlag"),$n=Symbol("_errored"),ed=class extends Yn{[$n]=!1;[he];[kt];[hc];[Qt]=!1;[xc];[Si];[kn];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[$n]=!1,this[he]=typeof e.fd=="number"?e.fd:void 0,this[kt]=t,this[hc]=e.readSize||16*1024*1024,this[Qt]=!1,this[xc]=typeof e.size=="number"?e.size:1/0,this[Si]=this[xc],this[kn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[he]=="number"?this[Dr]():this[Tn]()}get fd(){return this[he]}get path(){return this[kt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Tn](){at.open(this[kt],"r",(t,e)=>this[Lr](t,e))}[Lr](t,e){t?this[Or](t):(this[he]=e,this.emit("open",e),this[Dr]())}[Oc](){return Buffer.allocUnsafe(Math.min(this[hc],this[Si]))}[Dr](){if(!this[Qt]){this[Qt]=!0;let t=this[Oc]();if(t.length===0)return process.nextTick(()=>this[fc](null,0,t));at.read(this[he],t,0,t.length,null,(e,n,i)=>this[fc](e,n,i))}}[fc](t,e,n){this[Qt]=!1,t?this[Or](t):this[Rc](e,n)&&this[Dr]()}[Tt](){if(this[kn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,at.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Or](t){this[Qt]=!0,this[Tt](),this.emit("error",t)}[Rc](t,e){let n=!1;return this[Si]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Si]<=0)&&(n=!1,this[Tt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[he]=="number"&&this[Dr](),!1;case"error":return this[$n]?!1:(this[$n]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Rw=class extends ed{[Tn](){let t=!0;try{this[Lr](null,at.openSync(this[kt],"r")),t=!1}finally{t&&this[Tt]()}}[Dr](){let t=!0;try{if(!this[Qt]){this[Qt]=!0;do{let e=this[Oc](),n=e.length===0?0:at.readSync(this[he],e,0,e.length,null);if(!this[Rc](n,e))break}while(!0);this[Qt]=!1}t=!1}finally{t&&this[Tt]()}}[Tt](){if(this[kn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,at.closeSync(t),this.emit("close")}}},po=class extends _w{readable=!1;writable=!0;[$n]=!1;[Un]=!1;[vi]=!1;[Ot]=[];[Gs]=!1;[kt];[Ni];[kn];[he];[Qs];[en];[lc]=!1;[En];constructor(t,e){e=e||{},super(e),this[kt]=t,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Ni]=e.mode===void 0?438:e.mode,this[En]=typeof e.start=="number"?e.start:void 0,this[kn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[En]!==void 0?"r+":"w";this[Qs]=e.flags===void 0,this[en]=e.flags===void 0?n:e.flags,this[he]===void 0&&this[Tn]()}emit(t,...e){if(t==="error"){if(this[$n])return!1;this[$n]=!0}return super.emit(t,...e)}get fd(){return this[he]}get path(){return this[kt]}[Or](t){this[Tt](),this[Un]=!0,this.emit("error",t)}[Tn](){at.open(this[kt],this[en],this[Ni],(t,e)=>this[Lr](t,e))}[Lr](t,e){this[Qs]&&this[en]==="r+"&&t&&t.code==="ENOENT"?(this[en]="w",this[Tn]()):t?this[Or](t):(this[he]=e,this.emit("open",e),this[Un]||this[uc]())}end(t,e){return t&&this.write(t,e),this[vi]=!0,!this[Un]&&!this[Ot].length&&typeof this[he]=="number"&&this[Pr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[vi]?(this.emit("error",new Error("write() after end()")),!1):this[he]===void 0||this[Un]||this[Ot].length?(this[Ot].push(t),this[Gs]=!0,!1):(this[Un]=!0,this[Xs](t),!0)}[Xs](t){at.write(this[he],t,0,t.length,this[En],(e,n)=>this[Pr](e,n))}[Pr](t,e){t?this[Or](t):(this[En]!==void 0&&typeof e=="number"&&(this[En]+=e),this[Ot].length?this[uc]():(this[Un]=!1,this[vi]&&!this[lc]?(this[lc]=!0,this[Tt](),this.emit("finish")):this[Gs]&&(this[Gs]=!1,this.emit("drain"))))}[uc](){if(this[Ot].length===0)this[vi]&&this[Pr](null,0);else if(this[Ot].length===1)this[Xs](this[Ot].pop());else{let t=this[Ot];this[Ot]=[],Cw(this[he],t,this[En],(e,n)=>this[Pr](e,n))}}[Tt](){if(this[kn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,at.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Sf=class extends po{[Tn](){let t;if(this[Qs]&&this[en]==="r+")try{t=at.openSync(this[kt],this[en],this[Ni])}catch(e){if(e?.code==="ENOENT")return this[en]="w",this[Tn]();throw e}else t=at.openSync(this[kt],this[en],this[Ni]);this[Lr](null,t)}[Tt](){if(this[kn]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,at.closeSync(t),this.emit("close")}}[Xs](t){let e=!0;try{this[Pr](null,at.writeSync(this[he],t,0,t.length,this[En])),e=!1}finally{if(e)try{this[Tt]()}catch{}}}},Nw=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),Mw=t=>!!t.sync&&!!t.file,Bw=t=>!t.sync&&!!t.file,Fw=t=>!!t.sync&&!t.file,zw=t=>!t.sync&&!t.file,Uw=t=>!!t.file,Hw=t=>Nw.get(t)||t,td=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let s=Hw(n);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},ji=(t,e,n,i,s)=>Object.assign((a=[],d,u)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=td(a);if(s?.(h,d),Mw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(Bw(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(Fw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,d)}else if(zw(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:s}),jw=qw.constants||{ZLIB_VERNUM:4736},Ft=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},jw)),Kw=Vn.concat,Ku=Object.getOwnPropertyDescriptor(Vn,"concat"),Ww=t=>t,pc=Ku?.writable===!0||Ku?.set!==void 0?t=>{Vn.concat=t?Ww:Kw}:t=>{},Zn=Symbol("_superWrite"),qs=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"}},gc=Symbol("flushFlag"),nd=class extends Yn{#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 ju[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new ju[e](t)}catch(n){throw new qs(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 qs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Lc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Vn.alloc(0),{[gc]: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}[Zn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Vn.from(t,e)),this.#e)return;Lc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},pc(!0);let d;try{let h=typeof t[gc]=="number"?t[gc]:this.#r;d=this.#t._processChunk(t,h),pc(!1)}catch(h){pc(!1),this.#o(new qs(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=s,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new qs(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[Zn](Vn.from(h));for(let x=1;x<d.length;x++)u=this[Zn](d[x])}else u=this[Zn](Vn.from(d));return n&&n(),u}},Af=class extends nd{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ft.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ft.Z_FINISH,t.fullFlushFlag=Ft.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(Ft.Z_SYNC_FLUSH),Lc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,s)=>{typeof i=="function"&&(s=i,i=this.flushFlag),this.flush(i),s?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},$w=class extends Af{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Zn](t){return this.#e?(this.#e=!1,t[9]=255,super[Zn](t)):super[Zn](t)}},Vw=class extends Af{constructor(t){super(t,"Unzip")}},kf=class extends nd{constructor(t,e){t=t||{},t.flush=t.flush||Ft.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ft.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ft.BROTLI_OPERATION_FLUSH,super(t,e)}},Zw=class extends kf{constructor(t){super(t,"BrotliCompress")}},Jw=class extends kf{constructor(t){super(t,"BrotliDecompress")}},Tf=class extends nd{constructor(t,e){t=t||{},t.flush=t.flush||Ft.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ft.ZSTD_e_end,t.fullFlushFlag=Ft.ZSTD_e_flush,super(t,e)}},Yw=class extends Tf{constructor(t){super(t,"ZstdCompress")}},Xw=class extends Tf{constructor(t){super(t,"ZstdDecompress")}},Qw=(t,e)=>{if(Number.isSafeInteger(t))t<0?t_(t,e):e_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},e_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},t_=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var s=t&255;t=Math.floor(t/256),n?e[i-1]=Pf(s):s===0?e[i-1]=0:(n=!0,e[i-1]=Df(s))}},n_=t=>{let e=t[0],n=e===128?i_(t.subarray(1,t.length)):e===255?r_(t):null;if(n===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(n))throw Error("parsed number outside of javascript safe integer range");return n},r_=t=>{for(var e=t.length,n=0,i=!1,s=e-1;s>-1;s--){var a=Number(t[s]),d;i?d=Pf(a):a===0?d=a:(i=!0,d=Df(a)),d!==0&&(n-=d*Math.pow(256,e-s-1))}return n},i_=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var s=Number(t[i]);s!==0&&(n+=s*Math.pow(256,e-i-1))}return n},Pf=t=>(255^t)&255,Df=t=>(255^t)+1&255,s_={};ww(s_,{code:()=>rd,isCode:()=>eo,isName:()=>o_,name:()=>go,normalFsTypes:()=>Cf});var eo=t=>go.has(t),o_=t=>rd.has(t),Cf=new Set(["0","","1","2","3","4","5","6","7","D"]),go=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"]]),rd=new Map(Array.from(go).map(t=>[t[1],t[0]])),a_=t=>t===void 0||t<0?void 0:t,Jn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let s=Hn(t,e+156,1),a=Cf.has(s),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??Hn(t,e,100),this.mode=d?.mode??u?.mode??vn(t,e+100,8),this.uid=d?.uid??u?.uid??vn(t,e+108,8),this.gid=d?.gid??u?.gid??vn(t,e+116,8),this.size=a_(d?.size??u?.size??vn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??mc(t,e+136,12),this.cksum=vn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),eo(s)&&(this.#e=s||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Hn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Hn(t,e+265,32),this.gname=d?.gname??u?.gname??Hn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??vn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??vn(t,e+337,8)??0,t[e+475]!==0){let x=Hn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Hn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??mc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??mc(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="size"&&Number(i)<0||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=c_(this.path||"",n),s=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Gn(t,e,100,s)||this.needPax,this.needPax=Sn(t,e+100,8,this.mode)||this.needPax,this.needPax=Sn(t,e+108,8,this.uid)||this.needPax,this.needPax=Sn(t,e+116,8,this.gid)||this.needPax,this.needPax=Sn(t,e+124,12,this.size)||this.needPax,this.needPax=wc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Gn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Gn(t,e+265,32,this.uname)||this.needPax,this.needPax=Gn(t,e+297,32,this.gname)||this.needPax,this.needPax=Sn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Sn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Gn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Gn(t,e+345,155,a)||this.needPax:(this.needPax=Gn(t,e+345,130,a)||this.needPax,this.needPax=wc(t,e+476,12,this.atime)||this.needPax,this.needPax=wc(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,Sn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:go.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(rd.get(t));if(eo(e)||e==="Unsupported")this.#e=e;else if(eo(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},c_=(t,e)=>{let n=t,i="",s,a=Sr.parse(t).root||".";if(Buffer.byteLength(n)<100)s=[n,i,!1];else{i=Sr.dirname(n),n=Sr.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?s=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?s=[n.slice(0,99),i,!0]:(n=Sr.join(Sr.basename(i),n),i=Sr.dirname(i));while(i!==a&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},Hn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),mc=(t,e,n)=>d_(vn(t,e,n)),d_=t=>t===void 0?void 0:new Date(t*1e3),vn=(t,e,n)=>Number(t[e])&128?n_(t.subarray(e,e+n)):u_(t,e,n),l_=t=>isNaN(t)?void 0:t,u_=(t,e,n)=>l_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),f_={12:8589934591,8:2097151},Sn=(t,e,n,i)=>i===void 0?!1:i>f_[n]||i<0?(Qw(i,t.subarray(e,e+n)),!0):(h_(t,e,n,i),!1),h_=(t,e,n,i)=>t.write(x_(i,n),e,n,"ascii"),x_=(t,e)=>p_(Math.floor(t).toString(8),e),p_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",wc=(t,e,n,i)=>i===void 0?!1:Sn(t,e,n,i.getTime()/1e3),g_=new Array(156).join("\0"),Gn=(t,e,n,i)=>i===void 0?!1:(t.write(i+g_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),lo=class Rf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),s=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)s[a]=0;new Jn({path:("PaxHeader/"+m_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(s),s.write(e,512,n,"utf8");for(let a=n+512;a<s.length;a++)s[a]=0;return s}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,s=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,a=Buffer.byteLength(s),d=Math.floor(Math.log(a)/Math.log(10))+1;return a+d>=Math.pow(10,d)&&(d+=1),d+a+s}static parse(e,n,i=!1){return new Rf(w_(__(e),n),i)}},w_=(t,e)=>e?Object.assign({},e,t):t,__=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(y_,Object.create(null)),y_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),s=i.shift();if(!s)return t;let a=s.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(a){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[a]=d;break;case"ctime":case"atime":case"mtime":t[a]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[a]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},b_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ee=b_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),E_=class extends Yn{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=ee(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?ee(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),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=ee(t.path)),t.linkpath&&(t.linkpath=ee(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},mo=(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,Nc=Buffer.from([31,139]),Mc=Buffer.from([40,181,47,253]),S_=Math.max(Nc.length,Mc.length),pt=Symbol("state"),qn=Symbol("writeEntry"),Yt=Symbol("readEntry"),_c=Symbol("nextEntry"),Wu=Symbol("processEntry"),Lt=Symbol("extendedHeader"),Ii=Symbol("globalExtendedHeader"),_n=Symbol("meta"),$u=Symbol("emitMeta"),be=Symbol("buffer"),Xt=Symbol("queue"),yn=Symbol("ended"),yc=Symbol("emittedEnd"),jn=Symbol("emit"),De=Symbol("unzip"),js=Symbol("consumeChunk"),Ks=Symbol("consumeChunkSub"),bc=Symbol("consumeBody"),Vu=Symbol("consumeMeta"),Zu=Symbol("consumeHeader"),Ai=Symbol("consuming"),Ec=Symbol("bufferConcat"),Ws=Symbol("maybeEnd"),Ir=Symbol("writing"),Nt=Symbol("aborted"),$s=Symbol("onDone"),Kn=Symbol("sawValidEntry"),Vs=Symbol("sawNullBlock"),Zs=Symbol("sawEOF"),Ju=Symbol("closeStream"),I_=1e3,ki=Symbol("compressedBytesRead"),vc=Symbol("decompressedBytesRead"),Yu=Symbol("checkDecompressionRatio"),A_=()=>!0,qi=class extends Gw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[Xt]=[];[be];[Yt];[qn];[pt]="begin";[_n]="";[Lt];[Ii];[yn]=!1;[De];[Nt]=!1;[Kn];[Vs]=!1;[Zs]=!1;[Ir]=!1;[Ai]=!1;[yc]=!1;[ki]=0;[vc]=0;constructor(t={}){super(),this.file=t.file||"",this.on($s,()=>{(this[pt]==="begin"||this[Kn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on($s,t.ondone):this.on($s,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:I_,this.maxMetaEntrySize=t.maxMetaEntrySize||v_,this.filter=typeof t.filter=="function"?t.filter:A_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[Ju]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){mo(this,t,e,n)}[Zu](t,e){this[Kn]===void 0&&(this[Kn]=!1);let n;try{n=new Jn(t,e,this[Lt],this[Ii])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Vs]?(this[Zs]=!0,this[pt]==="begin"&&(this[pt]="header"),this[jn]("eof")):(this[Vs]=!0,this[jn]("nullBlock"));else if(this[Vs]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let s=this[qn]=new E_(n,this[Lt],this[Ii]);if(!this[Kn])if(s.remain){let a=()=>{s.invalid||(this[Kn]=!0)};s.on("end",a)}else this[Kn]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[jn]("ignoredEntry",s),this[pt]="ignore",s.resume()):s.size>0&&(this[_n]="",s.on("data",a=>this[_n]+=a),this[pt]="meta"):(this[Lt]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[jn]("ignoredEntry",s),this[pt]=s.remain?"ignore":"header",s.resume()):(s.remain?this[pt]="body":(this[pt]="header",s.end()),this[Yt]?this[Xt].push(s):(this[Xt].push(s),this[_c]())))}}}[Ju](){queueMicrotask(()=>this.emit("close"))}[Wu](t){let e=!0;if(!t)this[Yt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Yt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[_c]()),e=!1);return e}[_c](){do;while(this[Wu](this[Xt].shift()));if(this[Xt].length===0){let t=this[Yt];!t||t.flowing||t.size===t.remain?this[Ir]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[bc](t,e){let n=this[qn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,s=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(s),n.blockRemain||(this[pt]="header",this[qn]=void 0,n.end()),s.length}[Vu](t,e){let n=this[qn],i=this[bc](t,e);return!this[qn]&&n&&this[$u](n),i}[jn](t,e,n){this[Xt].length===0&&!this[Yt]?this.emit(t,e,n):this[Xt].push([t,e,n])}[$u](t){switch(this[jn]("meta",this[_n]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Lt]=lo.parse(this[_n],this[Lt],!1);break;case"GlobalExtendedHeader":this[Ii]=lo.parse(this[_n],this[Ii],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Lt]??Object.create(null);this[Lt]=e,e.path=this[_n].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Lt]||Object.create(null);this[Lt]=e,e.linkpath=this[_n].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Nt]){if(this[De]){let e=this[De];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Nt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Yu](t){this[vc]+=t.length;let e=this[vc]/this[ki];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[Nt])return n?.(),!1;if((this[De]===void 0||this.brotli===void 0&&this[De]===!1)&&t){if(this[be]&&(t=Buffer.concat([this[be],t]),this[be]=void 0),t.length<S_)return this[be]=t,n?.(),!0;for(let d=0;this[De]===void 0&&d<Nc.length;d++)t[d]!==Nc[d]&&(this[De]=!1);let s=!1;if(this[De]===!1&&this.zstd!==!1){s=!0;for(let d=0;d<Mc.length;d++)if(t[d]!==Mc[d]){s=!1;break}}let a=this.brotli===void 0&&!s;if(this[De]===!1&&a)if(t.length<512)if(this[yn])this.brotli=!0;else return this[be]=t,n?.(),!0;else try{new Jn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[De]===void 0||this[De]===!1&&(this.brotli||s)){let d=this[yn];this[yn]=!1,this[De]=this[De]===void 0?new Vw({}):s?new Xw({}):new Jw({}),this[De].on("data",h=>{this[Yu](h)&&this[js](h)}),this[De].on("error",h=>{this[Nt]||this.abort(h)}),this[De].on("end",()=>{this[yn]=!0,this[js]()}),this[Ir]=!0,this[ki]+=t.length;let u=!!this[De][d?"end":"write"](t);return this[Ir]=!1,n?.(),u}}this[Ir]=!0,this[De]?(this[ki]+=t.length,this[De].write(t)):this[js](t),this[Ir]=!1;let i=this[Xt].length>0?!1:this[Yt]?this[Yt].flowing:!0;return!i&&this[Xt].length===0&&this[Yt]?.once("drain",()=>this.emit("drain")),n?.(),i}[Ec](t){t&&!this[Nt]&&(this[be]=this[be]?Buffer.concat([this[be],t]):t)}[Ws](){if(this[yn]&&!this[yc]&&!this[Nt]&&!this[Ai]){this[yc]=!0;let t=this[qn];if(t?.blockRemain){let e=this[be]?this[be].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[be]&&t.write(this[be]),t.end()}this[jn]($s)}}[js](t){if(this[Ai]&&t)this[Ec](t);else if(!t&&!this[be])this[Ws]();else if(t){if(this[Ai]=!0,this[be]){this[Ec](t);let e=this[be];this[be]=void 0,this[Ks](e)}else this[Ks](t);for(;this[be]&&this[be]?.length>=512&&!this[Nt]&&!this[Zs];){let e=this[be];this[be]=void 0,this[Ks](e)}this[Ai]=!1}(!this[be]||this[yn])&&this[Ws]()}[Ks](t){let e=0,n=t.length;for(;e+512<=n&&!this[Nt]&&!this[Zs];)switch(this[pt]){case"begin":case"header":this[Zu](t,e),e+=512;break;case"ignore":case"body":e+=this[bc](t,e);break;case"meta":e+=this[Vu](t,e);break;default:throw new Error("invalid state: "+this[pt])}e<n&&(this[be]=this[be]?Buffer.concat([t.subarray(e),this[be]]):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[Nt]||(this[De]?(t&&(this[ki]+=t.length,this[De].write(t)),this[De].end()):(this[yn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ws]())),this}},Mi=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},k_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Of=(t,e)=>{let n=new Map(e.map(a=>[Mi(a),!0])),i=t.filter,s=(a,d="")=>{let u=d||Lw(a).root||".",h;if(a===u)h=!1;else{let x=n.get(a);h=x!==void 0?x:s(Ow(a),u)}return n.set(a,h),h};t.filter=i?(a,d)=>i(a,d)&&s(Mi(a)):a=>s(Mi(a))},T_=t=>{let e=new qi(t),n=t.file,i;try{i=Cr.openSync(n,"r");let s=Cr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(s.size<a){let d=Buffer.allocUnsafe(s.size),u=Cr.readSync(i,d,0,s.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(a);for(;d<s.size;){let h=Cr.readSync(i,u,0,a,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Cr.closeSync(i)}catch{}}},P_=(t,e)=>{let n=new qi(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Cr.stat(s,(u,h)=>{if(u)d(u);else{let x=new ed(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Nr=ji(T_,P_,t=>new qi(t),t=>new qi(t),(t,e)=>{e?.length&&Of(t,e),t.noResume||k_(t)}),Lf=(t,e,n)=>(t&=4095,n&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:C_,parse:Qu}=D_,id=t=>{let e="",n=Qu(t);for(;C_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Qu(t)}return[e,t]},wo=["|","<",">","?",":"],sd=wo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),R_=new Map(wo.map((t,e)=>[t,sd[e]])),O_=new Map(sd.map((t,e)=>[t,wo[e]])),ef=t=>wo.reduce((e,n)=>e.split(n).join(R_.get(n)),t),L_=t=>sd.reduce((e,n)=>e.split(n).join(O_.get(n)),t),Nf=(t,e)=>e?(t=ee(t).replace(/^\.(\/|$)/,""),Mi(e)+"/"+t):ee(t),N_=16*1024*1024,tf=Symbol("process"),nf=Symbol("file"),rf=Symbol("directory"),Bc=Symbol("symlink"),sf=Symbol("hardlink"),Ti=Symbol("header"),to=Symbol("read"),Fc=Symbol("lstat"),no=Symbol("onlstat"),zc=Symbol("onread"),Uc=Symbol("onreadlink"),Hc=Symbol("openfile"),Gc=Symbol("onopenfile"),In=Symbol("close"),fo=Symbol("mode"),qc=Symbol("awaitDrain"),Sc=Symbol("ondrain"),Bt=Symbol("prefix"),Mf=class extends Yn{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=td(e);super(),this.path=ee(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||N_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=ee(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?ee(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]=id(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=L_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ee(n.absolute||Xu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let s=this.statCache.get(this.absolute);s?this[no](s):this[Fc]()}warn(t,e,n={}){return mo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Fc](){Mt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[no](e)})}[no](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=F_(t),this.emit("stat",t),this[tf]()}[tf](){switch(this.type){case"File":return this[nf]();case"Directory":return this[rf]();case"SymbolicLink":return this[Bc]();default:return this.end()}}[fo](t){return Lf(t,this.type==="Directory",this.portable)}[Bt](t){return Nf(t,this.prefix)}[Ti](){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 Jn({path:this[Bt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Bt](this.linkpath):this.linkpath,mode:this[fo](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 lo({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[Bt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Bt](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)}[rf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ti](),this.end()}[Bc](){Mt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Uc](e)})}[Uc](t){this.linkpath=ee(t),this[Ti](),this.end()}[sf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ee(Xu.relative(this.cwd,t)),this.stat.size=0,this[Ti](),this.end()}[nf](){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[sf](e);this.linkCache.set(t,this.absolute)}if(this[Ti](),this.stat.size===0)return this.end();this[Hc]()}[Hc](){Mt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Gc](e)})}[Gc](t){if(this.fd=t,this.#e)return this[In]();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[to]()}[to](){let{fd:t,buf:e,offset:n,length:i,pos:s}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Mt.read(t,e,n,i,s,(a,d)=>{if(a)return this[In](()=>this.emit("error",a));this[zc](d)})}[In](t=()=>{}){this.fd!==void 0&&Mt.close(this.fd,t)}[zc](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[In](()=>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[In](()=>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[Sc]():this[qc](()=>this[Sc]())}[qc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[Sc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[In](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[to]()}},M_=class extends Mf{sync=!0;[Fc](){this[no](Mt.lstatSync(this.absolute))}[Bc](){this[Uc](Mt.readlinkSync(this.absolute))}[Hc](){this[Gc](Mt.openSync(this.absolute,"r"))}[to](){let t=!0;try{let{fd:e,buf:n,offset:i,length:s,pos:a}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Mt.readSync(e,n,i,s,a);this[zc](d),t=!1}finally{if(t)try{this[In](()=>{})}catch{}}}[qc](t){t()}[In](t=()=>{}){this.fd!==void 0&&Mt.closeSync(this.fd),t()}},B_=class extends Yn{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 mo(this,t,e,n)}constructor(t,e={}){let n=td(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=ee(t.path),this.mode=t.mode!==void 0?this[fo](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?ee(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let s=!1;if(!this.preservePaths){let[d,u]=id(this.path);d&&typeof u=="string"&&(this.path=u,s=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Jn({path:this[Bt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Bt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),s&&this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute path`,{entry:this,path:s+this.path}),this.header.encode()&&!this.noPax&&super.write(new lo({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[Bt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Bt](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)}[Bt](t){return Nf(t,this.prefix)}[fo](t){return Lf(t,this.type==="Directory",this.portable)}write(t,e,n){typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,n)}end(t,e,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),n&&this.once("finish",n),t?super.end(t,n):super.end(n),this}},F_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",z_=class Rr{tail;head;length=0;static create(e=[]){return new Rr(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)H_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)G_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,s=0;i;s++)e.call(n,i.value,s,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,s=this.length-1;i;s--)e.call(n,i.value,s,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Rr;for(let s=this.head;s;)i.push(e.call(n,s.value,this)),s=s.next;return i}mapReverse(e,n){n=n||this;var i=new Rr;for(let s=this.tail;s;)i.push(e.call(n,s.value,this)),s=s.prev;return i}reduce(e,n){let i,s=this.head;if(arguments.length>1)i=n;else if(this.head)s=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;s;a++)i=e(i,s.value,a),s=s.next;return i}reduceReverse(e,n){let i,s=this.tail;if(arguments.length>1)i=n;else if(this.tail)s=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;s;a--)i=e(i,s.value,a),s=s.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Rr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.head,a=0;for(a=0;s&&a<e;a++)s=s.next;for(;s&&a<n;a++,s=s.next)i.push(s.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Rr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.length,a=this.tail;for(;a&&s>n;s--)a=a.prev;for(;a&&s>e;s--,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 s=this.head;for(let d=0;s&&d<e;d++)s=s.next;let a=[];for(let d=0;s&&d<n;d++)a.push(s.value),s=this.removeNode(s);s?s!==this.tail&&(s=s.prev):s=this.tail;for(let d of i)s=U_(this,s,d);return a}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let s=i.prev;i.prev=i.next,i.next=s}return this.head=n,this.tail=e,this}};function U_(t,e,n){let i=e,s=e?e.next:t.head,a=new od(n,i,s,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function H_(t,e){t.tail=new od(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function G_(t,e){t.head=new od(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var od=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}},af=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},cf=Buffer.alloc(1024),ro=Symbol("onStat"),Pi=Symbol("ended"),It=Symbol("queue"),Di=Symbol("pendingLinks"),bn=Symbol("current"),Wn=Symbol("process"),Ci=Symbol("processing"),Js=Symbol("processJob"),At=Symbol("jobs"),Ic=Symbol("jobDone"),io=Symbol("addFSEntry"),df=Symbol("addTarEntry"),jc=Symbol("stat"),Kc=Symbol("readdir"),so=Symbol("onreaddir"),oo=Symbol("pipe"),lf=Symbol("entry"),Ac=Symbol("entryOpt"),ao=Symbol("writeEntryClass"),Bf=Symbol("write"),kc=Symbol("ondrain"),_o=class extends Yn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ao];onWriteEntry;[It];[Di]=new Map;[At]=0;[Ci]=!1;[Pi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=ee(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[ao]=Mf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new $w(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Zw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Yw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[kc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[kc]);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[It]=new z_,this[At]=0,this.jobs=Number(t.jobs)||4,this[Ci]=!1,this[Pi]=!1}[Bf](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[Pi]=!0,this[Wn](),n&&n(),this}write(t){if(this[Pi])throw new Error("write after end");return typeof t=="string"?this[io](t):this[df](t),this.flowing}[df](t){let e=ee(of.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new af(t.path,e);n.entry=new B_(t,this[Ac](n)),n.entry.on("end",()=>this[Ic](n)),this[At]+=1,this[It].push(n)}this[Wn]()}[io](t){let e=ee(of.resolve(this.cwd,t));this[It].push(new af(t,e)),this[Wn]()}[jc](t){t.pending=!0,this[At]+=1;let e=this.follow?"stat":"lstat";uo[e](t.absolute,(n,i)=>{t.pending=!1,this[At]-=1,n?this.emit("error",n):this[ro](t,i)})}[ro](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[bn])this[Js](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[Wn]()}[Kc](t){t.pending=!0,this[At]+=1,uo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[At]-=1,e)return this.emit("error",e);this[so](t,n)})}[so](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Wn]()}[Wn](){if(!this[Ci]){this[Ci]=!0;for(let t=this[It].head;t&&this[At]<this.jobs;t=t.next)if(this[Js](t.value),t.value.ignore){let e=t.next;this[It].removeNode(t),t.next=e}this[Ci]=!1,this[Pi]&&this[It].length===0&&this[At]===0&&(this.zip?this.zip.end(cf):(super.write(cf),super.end()))}}get[bn](){return this[It]&&this[It].head&&this[It].head.value}[Ic](t){this[It].shift(),this[At]-=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 s of i)s.pending=!1,this[Js](s)}}this[Wn]()}[Js](t){if(t.pending&&t.pendingLink&&t===this[bn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[bn]&&!t.piped&&this[oo](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[ro](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[so](t,e):this[Kc](t),!t.readdir)return}if(t.entry=this[lf](t),!t.entry){t.ignore=!0;return}t===this[bn]&&!t.piped&&this[oo](t)}}}[Ac](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}}[lf](t){this[At]+=1;try{return new this[ao](t.path,this[Ac](t)).on("end",()=>this[Ic](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[kc](){this[bn]&&this[bn].entry&&this[bn].entry.resume()}[oo](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[io](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={}){mo(this,t,e,n)}},ad=class extends _o{sync=!0;constructor(t){super(t),this[ao]=M_}pause(){}resume(){}[jc](t){let e=this.follow?"statSync":"lstatSync";this[ro](t,uo[e](t.absolute))}[Kc](t){this[so](t,uo.readdirSync(t.absolute))}[oo](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[io](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Bf](i)})}},q_=(t,e)=>{let n=new ad(t),i=new Sf(t.file,{mode:t.mode||438});n.pipe(i),Ff(n,e)},j_=(t,e)=>{let n=new _o(t),i=new po(t.file,{mode:t.mode||438});n.pipe(i);let s=new Promise((a,d)=>{i.on("error",d),i.on("close",a),n.on("error",d)});return zf(n,e).catch(a=>n.emit("error",a)),s},Ff=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Nr({file:If.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},zf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Nr({file:If.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},K_=(t,e)=>{let n=new ad(t);return Ff(n,e),n},W_=(t,e)=>{let n=new _o(t);return zf(n,e).catch(i=>n.emit("error",i)),n},ik=ji(q_,j_,K_,W_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),V_=process.env.__FAKE_PLATFORM__||process.platform,qf=V_==="win32",{O_CREAT:jf,O_NOFOLLOW:uf,O_TRUNC:Kf,O_WRONLY:Wf}=Gf.constants,$f=Number(process.env.__FAKE_FS_O_FILENAME__)||Gf.constants.UV_FS_O_FILEMAP||0,Z_=qf&&!!$f,J_=512*1024,Y_=$f|Kf|jf|Wf,ff=!qf&&typeof uf=="number"?uf|Kf|jf|Wf:null,Vf=ff!==null?()=>ff:Z_?t=>t<J_?Y_:"w":()=>"w",Wc=(t,e,n)=>{try{return yo.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},ho=(t,e,n,i)=>{yo.lchown(t,e,n,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},X_=(t,e,n,i,s)=>{if(e.isDirectory())Zf(Bi.resolve(t,e.name),n,i,a=>{if(a)return s(a);let d=Bi.resolve(t,e.name);ho(d,n,i,s)});else{let a=Bi.resolve(t,e.name);ho(a,n,i,s)}},Zf=(t,e,n,i)=>{yo.readdir(t,{withFileTypes:!0},(s,a)=>{if(s){if(s.code==="ENOENT")return i();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return i(s)}if(s||!a.length)return ho(t,e,n,i);let d=a.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return ho(t,e,n,i)}};for(let x of a)X_(t,x,e,n,h)})},Q_=(t,e,n,i)=>{e.isDirectory()&&Jf(Bi.resolve(t,e.name),n,i),Wc(Bi.resolve(t,e.name),n,i)},Jf=(t,e,n)=>{let i;try{i=yo.readdirSync(t,{withFileTypes:!0})}catch(s){let a=s;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Wc(t,e,n);throw a}for(let s of i)Q_(t,s,e,n);return Wc(t,e,n)},Yf=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"}},bo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},ty=(t,e)=>{ut.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new Yf(t,n?.code||"ENOTDIR")),e(n)})},ny=(t,e,n)=>{t=ee(t);let i=e.umask??18,s=e.mode|448,a=(s&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,w=ee(e.cwd),v=(E,I)=>{E?n(E):I&&h?Zf(I,d,u,A=>v(A)):a?ut.chmod(t,s,n):n()};if(t===w)return ty(t,v);if(x)return ey.mkdir(t,{mode:s,recursive:!0}).then(E=>v(null,E??void 0),v);let _=ee(xo.relative(w,t)).split("/");$c(w,_,s,g,w,void 0,v)},$c=(t,e,n,i,s,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),h=ee(xo.resolve(t+"/"+u));ut.mkdir(h,n,Xf(h,e,n,i,s,a,d))},Xf=(t,e,n,i,s,a,d)=>u=>{u?ut.lstat(t,(h,x)=>{if(h)h.path=h.path&&ee(h.path),d(h);else if(x.isDirectory())$c(t,e,n,i,s,a,d);else if(i)ut.unlink(t,g=>{if(g)return d(g);ut.mkdir(t,n,Xf(t,e,n,i,s,a,d))});else{if(x.isSymbolicLink())return d(new bo(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,$c(t,e,n,i,s,a,d))},ry=t=>{let e=!1,n;try{e=ut.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new Yf(t,n??"ENOTDIR")}},iy=(t,e)=>{t=ee(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,g=ee(e.cwd),w=E=>{E&&u&&Jf(E,a,d),s&&ut.chmodSync(t,i)};if(t===g)return ry(g),w();if(h)return w(ut.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=ee(xo.relative(g,t)).split("/"),_;for(let E=v.shift(),I=g;E&&(I+="/"+E);E=v.shift()){I=ee(xo.resolve(I));try{ut.mkdirSync(I,i),_=_||I}catch{let A=ut.lstatSync(I);if(A.isDirectory())continue;if(x){ut.unlinkSync(I),ut.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new bo(I,I+"/"+v.join("/"))}}return w(_)},Tc=Object.create(null),hf=1e4,Ar=new Set,sy=t=>{Ar.has(t)?Ar.delete(t):Tc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Ar.add(t);let e=Tc[t],n=Ar.size-hf;if(n>hf/10){for(let i of Ar)if(Ar.delete(i),delete Tc[i],--n<=0)break}return e},oy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ay=oy==="win32",cy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Qf(i,n)),e.push(n||"/"),e},[]),dy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=ay?["win32 parallelization disabled"]:t.map(i=>Mi(Qf(sy(i))));let n=new Set(t.map(i=>cy(i)).reduce((i,s)=>i.concat(s)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let s=this.#e.get(i);s?s.push(e):this.#e.set(i,[e])}for(let i of n){let s=this.#e.get(i);if(!s)this.#e.set(i,[new Set([e])]);else{let a=s.at(-1);a instanceof Set?a.add(e):s.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,s=new Set;for(let 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")s.add(u);else for(let h of u)s.add(h)}for(let a of i){let d=this.#e.get(a),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(a);continue}else if(u.size===1){d.shift();let h=d[0];typeof h=="function"&&s.add(h)}else u.delete(t)}return this.#r.delete(t),s.forEach(a=>this.#i(a)),!0}},ly=()=>process.umask(),xf=Symbol("onEntry"),Vc=Symbol("checkFs"),pf=Symbol("checkFs2"),Zc=Symbol("isReusable"),gt=Symbol("makeFs"),Jc=Symbol("file"),Yc=Symbol("directory"),co=Symbol("link"),gf=Symbol("symlink"),mf=Symbol("hardlink"),Li=Symbol("ensureNoSymlink"),wf=Symbol("unsupported"),_f=Symbol("checkPath"),Pc=Symbol("stripAbsolutePath"),An=Symbol("mkdir"),Ve=Symbol("onError"),Ys=Symbol("pending"),yf=Symbol("pend"),kr=Symbol("unpend"),Dc=Symbol("ended"),Cc=Symbol("maybeClose"),Xc=Symbol("skip"),Fi=Symbol("doChown"),zi=Symbol("uid"),Ui=Symbol("gid"),Hi=Symbol("checkedCwd"),uy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Gi=uy==="win32",fy=1024,hy=(t,e)=>{if(!Gi)return ce.unlink(t,e);let n=t+".DELETE."+Hf(16).toString("hex");ce.rename(t,n,i=>{if(i)return e(i);ce.unlink(n,e)})},xy=t=>{if(!Gi)return ce.unlinkSync(t);let e=t+".DELETE."+Hf(16).toString("hex");ce.renameSync(t,e),ce.unlinkSync(e)},bf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,cd=class extends qi{[Dc]=!1;[Hi]=!1;[Ys]=0;reservations=new dy;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[Dc]=!0,this[Cc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:fy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Gi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ee(He.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:ly():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[xf](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Cc](){this[Dc]&&this[Ys]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Pc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[s,a]=id(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Gi&&/^[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=He.posix.dirname(t.path),h=He.posix.normalize(He.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return s&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:n})),!0}[_f](t){let e=ee(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=ee(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}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[Pc](t,"path")||!this[Pc](t,"linkpath"))return!1;if(t.absolute=He.isAbsolute(t.path)?ee(He.resolve(t.path)):ee(He.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:ee(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=He.win32.parse(String(t.absolute));t.absolute=i+ef(String(t.absolute).slice(i.length));let{root:s}=He.win32.parse(t.path);t.path=s+ef(t.path.slice(s.length))}return!0}[xf](t){if(!this[_f](t))return t.resume();switch($_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Vc](t);default:return this[wf](t)}}[Ve](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[kr](),e.resume())}[An](t,e,n){ny(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[Fi](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[zi](t){return bf(this.uid,t.uid,this.processUid)}[Ui](t){return bf(this.gid,t.gid,this.processGid)}[Jc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new po(String(t.absolute),{flags:Vf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&ce.close(i.fd,()=>{}),i.write=()=>!0,this[Ve](u,t),e()});let s=1,a=u=>{if(u){i.fd&&ce.close(i.fd,()=>{}),this[Ve](u,t),e();return}--s===0&&i.fd!==void 0&&ce.close(i.fd,h=>{h?this[Ve](h,t):this[kr](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){s++;let x=t.atime||new Date,g=t.mtime;ce.futimes(h,x,g,w=>w?ce.utimes(u,x,g,v=>a(v&&w)):a())}if(typeof h=="number"&&this[Fi](t)){s++;let x=this[zi](t),g=this[Ui](t);typeof x=="number"&&typeof g=="number"&&ce.fchown(h,x,g,w=>w?ce.chown(u,x,g,v=>a(v&&w)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[Ve](u,t),e()}),t.pipe(d)),d.pipe(i)}[Yc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[An](String(t.absolute),n,i=>{if(i){this[Ve](i,t),e();return}let s=1,a=()=>{--s===0&&(e(),this[kr](),t.resume())};t.mtime&&!this.noMtime&&(s++,ce.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Fi](t)&&(s++,ce.chown(String(t.absolute),Number(this[zi](t)),Number(this[Ui](t)),a)),a()})}[wf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[gf](t,e){let n=ee(He.relative(this.cwd,He.resolve(He.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Li](t,this.cwd,n,()=>this[co](t,String(t.linkpath),"symlink",e),i=>{this[Ve](i,t),e()})}[mf](t,e){let n=ee(He.resolve(this.cwd,String(t.linkpath))),i=ee(String(t.linkpath)).split("/");this[Li](t,this.cwd,i,()=>this[co](t,n,"link",e),s=>{this[Ve](s,t),e()})}[Li](t,e,n,i,s){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=He.resolve(e,a);ce.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return s(new bo(d,He.resolve(d,n.join("/"))));this[Li](t,d,n,i,s)})}[yf](){this[Ys]++}[kr](){this[Ys]--,this[Cc]()}[Xc](t){this[kr](),t.resume()}[Zc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Gi}[Vc](t){this[yf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[pf](t,n))}[pf](t,e){let n=d=>{e(d)},i=()=>{this[An](this.cwd,this.dmode,d=>{if(d){this[Ve](d,t),n();return}this[Hi]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let d=ee(He.dirname(String(t.absolute)));if(d!==this.cwd)return this[An](d,this.dmode,u=>{if(u){this[Ve](u,t),n();return}a()})}a()},a=()=>{ce.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Xc](t),n();return}if(d||this[Zc](t,u))return this[gt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[gt](g??null,t,n);return h?ce.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ce.rmdir(String(t.absolute),h=>this[gt](h??null,t,n))}if(t.absolute===this.cwd)return this[gt](null,t,n);hy(String(t.absolute),h=>this[gt](h??null,t,n))})};this[Hi]?s():i()}[gt](t,e,n){if(t){this[Ve](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Jc](e,n);case"Link":return this[mf](e,n);case"SymbolicLink":return this[gf](e,n);case"Directory":case"GNUDumpDir":return this[Yc](e,n)}}[co](t,e,n,i){ce[n](e,String(t.absolute),s=>{s?this[Ve](s,t):(this[kr](),t.resume()),i()})}},Ri=t=>{try{return[null,t()]}catch(e){return[e,null]}},e0=class extends cd{sync=!0;[gt](t,e){return super[gt](t,e,()=>{})}[Vc](t){if(!this[Hi]){let s=this[An](this.cwd,this.dmode);if(s)return this[Ve](s,t);this[Hi]=!0}if(t.absolute!==this.cwd){let s=ee(He.dirname(String(t.absolute)));if(s!==this.cwd){let a=this[An](s,this.dmode);if(a)return this[Ve](a,t)}}let[e,n]=Ri(()=>ce.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Xc](t);if(e||this[Zc](t,n))return this[gt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Ri(()=>{ce.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[gt](d,t)}let[s]=Ri(()=>ce.rmdirSync(String(t.absolute)));this[gt](s,t)}let[i]=t.absolute===this.cwd?[]:Ri(()=>xy(String(t.absolute)));this[gt](i,t)}[Jc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ce.closeSync(s)}catch(h){u=h}(d||u)&&this[Ve](d||u,t),e()},s;try{s=ce.openSync(String(t.absolute),Vf(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[Ve](d,t)),t.pipe(a)),a.on("data",d=>{try{ce.writeSync(s,d,0,d.length)}catch(u){i(u)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{ce.futimesSync(s,u,h)}catch(x){try{ce.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Fi](t)){let u=this[zi](t),h=this[Ui](t);try{ce.fchownSync(s,Number(u),Number(h))}catch(x){try{ce.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Yc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[An](String(t.absolute),n);if(i){this[Ve](i,t),e();return}if(t.mtime&&!this.noMtime)try{ce.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Fi](t))try{ce.chownSync(String(t.absolute),Number(this[zi](t)),Number(this[Ui](t)))}catch{}e(),t.resume()}[An](t,e){try{return iy(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[Li](t,e,n,i,s){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=He.resolve(a,d);let[u,h]=Ri(()=>ce.lstatSync(a));if(u)return i();if(h.isSymbolicLink())return s(new bo(a,He.resolve(e,n.join("/"))))}i()}[co](t,e,n,i){let s=`${n}Sync`;try{ce[s](e,String(t.absolute)),i(),t.resume()}catch(a){return this[Ve](a,t)}}},py=t=>{let e=new e0(t),n=t.file,i=Uf.statSync(n),s=t.maxReadSize||16*1024*1024;new Rw(n,{readSize:s,size:i.size}).pipe(e)},gy=(t,e)=>{let n=new cd(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Uf.stat(s,(u,h)=>{if(u)d(u);else{let x=new ed(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},t0=ji(py,gy,t=>new e0(t),t=>new cd(t),(t,e)=>{e?.length&&Of(t,e)}),my=(t,e)=>{let n=new ad(t),i=!0,s,a;try{try{s=lt.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")s=lt.openSync(t.file,"w+");else throw h}let d=lt.fstatSync(s),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let g=0,w=0;g<512;g+=w){if(w=lt.readSync(s,u,g,u.length-g,a+g),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let h=new Jn(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,wy(t,n,a,s,e)}finally{if(i)try{lt.closeSync(s)}catch{}}},wy=(t,e,n,i,s)=>{let a=new Sf(t.file,{fd:i,start:n});e.pipe(a),yy(e,s)},_y=(t,e)=>{e=Array.from(e);let n=new _o(t),i=(s,a,d)=>{let u=(v,_)=>{v?lt.close(s,E=>d(v)):d(null,_)},h=0;if(a===0)return u(null,0);let x=0,g=Buffer.alloc(512),w=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return lt.read(s,g,x,g.length-x,h+x,w);if(h===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let E=new Jn(g);if(!E.cksumValid)return u(null,h);let I=512*Math.ceil((E.size??0)/512);if(h+I+512>a||(h+=I+512,h>=a))return u(null,h);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,lt.read(s,g,0,512,h,w)};lt.read(s,g,0,512,h,w)};return new Promise((s,a)=>{n.on("error",a);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",lt.open(t.file,d,u);if(h||!x)return a(h);lt.fstat(x,(g,w)=>{if(g)return lt.close(x,()=>a(g));i(x,w.size,(v,_)=>{if(v)return a(v);let E=new po(t.file,{fd:x,start:_});n.pipe(E),E.on("error",a),E.on("close",s),by(n,e)})})};lt.open(t.file,d,u)})},yy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Nr({file:n0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},by=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Nr({file:n0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Oi=ji(my,_y,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Uw(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.zstd||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")}),_k=ji(Oi.syncFile,Oi.asyncFile,Oi.syncNoFile,Oi.asyncNoFile,(t,e=[])=>{Oi.validate?.(t,e),Ey(t)}),Ey=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(n,i)=>e(n,i)&&!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0)):(n,i)=>!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0))};Vt();var mt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function Eo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function r0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function vo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function i0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function s0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function o0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function Xn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}tn();Ye();ne();Ce();Ye();function Mr(t,e){if(Eo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ki(t){return t.startsWith("http://")||t.startsWith("https://")}function Br(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as lT}from"node:fs";import{dirname as fT,join as hT}from"node:path";import{fileURLToPath as pT}from"node:url";var zt="0.3.0";import{mkdir as zy,rm as S0}from"node:fs/promises";import{join as Zi}from"node:path";$t();import{readFileSync as Dy}from"node:fs";var Cy=384;async function dd(t,e=process.env){let n={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(n[i]=s);await gn(t.agentEnvFile,n,{mode:Cy})}function Qn(t){try{let e=JSON.parse(Dy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function So(t,e,n={},i=s=>s){return{...i({...t,...Qn(e)}),...n}}$t();function Wi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let s=t[i];s!==void 0&&(Ry(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
92
+ `)}
93
+ `}function Ry(t){if(t.includes(`
94
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ne();Ce();import{homedir as Ny}from"node:os";import{join as My}from"node:path";Ye();ne();var Io="1008033",l0="1289";var u0="pbbp2",f0="https://www.coze.cn",h0="/api/coze_claw/resource/get_frontier_key",Oy="https://www.coze.cn",Ly="wss://frontier.coze.cn";function Fr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Oy}function x0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Ly}function Pn(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 Vi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var $i=K("handshake");async function ld(t){let e=Fr(t.endpoint),n=t.timeoutMs??1e4,i=`${Br(e)}${h0}?aid=${encodeURIComponent(Io)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Pn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);$i.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:s,signal:a.signal}),h=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=${h}: ${E.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${h}`);let w=g.data??{},v=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!v||!_){let E=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${E}`)}return $i.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:v,deviceId:_}}catch(u){if(u instanceof k)throw $i.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw $i.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw $i.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Ao=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Pt="auto",ud=19e4,p0=32e3;function m0(t){return{model:fd(t.model)??Pt,...t.modelToken?{modelToken:t.modelToken}:{}}}function w0(t){return!t||t===Pt}var By=new Set(["auto","\u81EA\u52A8"]);function fd(t){let e=t?.trim();if(e)return By.has(e.toLowerCase())?Pt:e}function _0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Ao,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Pt;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 w0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function y0(t,e,n,i){let s={};if(t.modelToken?s.model=t.model||Pt:w0(t.model)||(s.model=t.model),t.modelToken){let a={name:"coze",base_url:`${Ao}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=ko(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),s.model_providers={coze:a},s.model_context_window=t.modelInfo?.contextWindow??ud}return Object.keys(s).length===0?{}:{CODEX_CONFIG:JSON.stringify(s),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function b0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function ko(t,e,n){let{ttEnv:i,usePpe:s}=Vi(t),a={};return i&&(a["x-tt-env"]=i),s&&(a["x-use-ppe"]=s),e&&(a["x-mock-scenario"]=e),n&&(a["x-coze-request-scene"]=n),a}function E0(t,e,n,i){if(!t.modelToken)return{};let s=ko(e,n,i);return Object.keys(s).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(s).map(([d,u])=>`${d}:${u}`).join(`
95
+ `)}}function hd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function xd(t){return t.model||Pt}function g0(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 v0(t,e,n,i,s){if(!t.modelToken)return null;let a=xd(t),d=ko(e,n,s),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let h=[g0(a,u,t.modelInfo?.contextWindow??ud,t.modelInfo?.maxOutput??p0)],x=new Set([a]);for(let w of i??[])!w||x.has(w)||(x.add(w),h.push(g0(w,["text"],ud,p0)));let g={baseUrl:`${Ao}/v1`,api:"openai-completions",apiKey:t.modelToken,models:h};return Object.keys(d).length>0&&(g.headers=d),g}function Fy(t){if(t!==void 0)return t?"auto":"text"}function pd(t,e,n){let i=ko(e,n),s=t.model||Pt,a=["model:"," provider: custom",` default: ${JSON.stringify(s)}`,` base_url: ${Ao}/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,h]of Object.entries(i))a.push(` ${u}: ${JSON.stringify(h)}`)}a.push("compression:"),a.push(" threshold: 0.8"),a.push("approvals:"),a.push(` mode: ${JSON.stringify("off")}`),a.push(` cron_mode: ${JSON.stringify("approve")}`);let d=Fy(t.modelInfo?.capabilities?.image);return d&&(a.push("agent:"),a.push(` image_input_mode: ${JSON.stringify(d)}`)),a.push("skills:"),a.push(" external_dirs:"),a.push(` - ${My(Ny(),".hermes","skills")}`),`${a.join(`
96
+ `)}
97
+ `}var er=K("hermes-config"),I0="dont_ask",A0="default";function tr(t,e){return Zi(Ne(t,e).root,"hermes-home")}async function Uy(t){let e=tr(t.agentId,t.paths);await zy(e,{recursive:!0,mode:448});let n=Wi({...process.env,...Qn(t.paths.agentEnvFile)});await xt(Zi(e,".env"),n,{mode:384});let i=pd(t.modelConfig,t.cozeEnv,t.mockScenario);await xt(Zi(e,"config.yaml"),i,{mode:384}),er.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function k0(t){let e=tr(t.agentId,t.paths),n=Zi(e,"state.db"),i=Zi(e,"config.yaml");er.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 S0(n,{force:!0}).catch(a=>er.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let s=pd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await xt(i,s,{mode:384}).catch(a=>er.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),er.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function md(t,e){let n=tr(t,e);er.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 S0(n,{recursive:!0,force:!0}).catch(i=>er.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var gd=new Map;function T0(t){let e=gd.get(t.agentId);if(e)return e;let n=Uy(t).finally(()=>gd.delete(t.agentId));return gd.set(t.agentId,n),n}var oe=K("agent-handlers"),D0=5*1024*1024,Ky=1,Wy=6,$y=new Set(["node_modules",".git",".coze","dist","build",".next"]),Vy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Zy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Jy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Yy(t){let e=t?.trim();return e?Jy.test(e)||Zy.test(e)?e:(oe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Xy(t){return new Promise((e,n)=>{let i=ct("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),s=!1,a=d=>{s||(s=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",d=>a(d))})}function Qy(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var Po=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??J()}async listSkills(e){e._meta;let n=Xn(e._meta),i=await this.loadAgentCfg(n),s=i?.workspace??Ne(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Ur(a,n,s,this.paths),h=[],x=new Set;for(let w of d){let v=xe(u,w.relPath,"SKILL.md");await Sd(v).then(E=>E.isFile()).catch(()=>!1)&&(h.push(ib(w)),x.add(w.relPath))}if(e.scanLocal){let w=await H0(n,s,a,this.paths),v=await G0(n,a);for(let _ of[...w,...v])x.has(_.relPath)||(x.add(_.relPath),h.push(_.skill))}return{skills:a==="hermes"?h.filter(w=>w.skillName!=="yuanbao"):h}}async addSkills(e){e._meta;let n=Xn(e._meta),i=await this.requireAgentCfg(n),s=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((h,x)=>[h.skillId,x])),u=[];for(let h of s){let x=await Do({agentId:n,workspace:i.workspace,framework:i.framework,skill:h,paths:this.paths});Co(a,d,x),u.push(h)}return await mi(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=Xn(e._meta),i=await this.requireAgentCfg(n),s=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Ur(i.framework,n,i.workspace,this.paths);for(let h of a){if(!s.has(h.skillId)){d.push(h);continue}let x=xe(u,h.relPath);oe.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:h.skillId,relPath:h.relPath,skillBase:u,absDir:x}),await yd(x,{recursive:!0,force:!0}),oe.info("skill removed",{agentId:n,skillId:h.skillId,relPath:h.relPath})}return await mi(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=Xn(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");oe.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),s=i?.workspace??Ne(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await tb(n,s,a,e.skillName,d,this.paths);if(!u){let O=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${O}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:g}=u,w=xe(h,"SKILL.md"),v=new Ad.default;v.addLocalFolder(h,g);let _=v.toBuffer();if(_.length>C0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${C0}`);let E=await To(w,{encoding:"utf8"}).then(O=>z0(O).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}:{}}):oe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??F0(n,x);if(i&&!d){let O=i.skills??[],b=O.find(L=>L.relPath===x);b?(b.version=A,b.skillId=T):O.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...E?{description:E}:{}}),await mi(n,O)}return oe.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[s,a]of i.sessions){if(!a.downstream)continue;let d=a.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,oe.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d});continue}let h=a.downstream;a.downstream=void 0,oe.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d}),h.stop(n).catch(x=>oe.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:s,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return oe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await ke(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return oe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await _r(i.workspace,i.framework,e.cozeIdentity)}catch(s){throw oe.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(s)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(s)}`,{cause:s})}return i.cozeIdentity=e.cozeIdentity,await je(i),oe.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 ke(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=["-y"];e.registry&&Ki(e.registry)&&s.push(`--registry=${e.registry}`);let a=Yy(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Vy.test(d)&&s.push("--env",d);let u=await Xy(s);return oe.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 ke(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await je(i),oe.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}):(oe.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",`${mt.DELETE}: missing agentId`);oe.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 ke(n),s=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??s??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=Ne(n);return a==="cloud"?(oe.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 yd(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await je(i)),oe.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(Mr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=fd(e.model)??Pt,i=await ke(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 je(i),oe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return oe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let a=s.model,d=s.modelInfo;s.model=n,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s,a).catch(x=>oe.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=s.framework==="hermes"&&Qy(d,s.modelInfo);if(s.framework==="hermes"&&!u){let x=[];for(let[g,w]of s.allSessionQueues())x.push(w.enqueue(async()=>{let v=s.sessions.get(g);if(!(!v?.downstream||!v.acpSessionId))try{await v.downstream.setSessionModel?.({sessionId:v.acpSessionId,modelId:n})}catch(_){oe.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:g,acpId:v.acpSessionId,err:String(_)})}}));return await Promise.all(x),oe.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let h=[];for(let[x,g]of s.allSessionQueues())h.push(g.enqueue(async()=>{let w=s.sessions.get(x);w?.downstream&&(await w.downstream.stop(`switchModel: ${n}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(h),oe.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:h.length}),{ok:!0}}async resetAgent(e){if(Mr(e._meta,mt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${mt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,mt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>oe.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,mt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),oe.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 s=new Map;for(let[a,d]of i.sessions)s.set(a,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await gi(e,s)}async clearPersistedAcpSessionIds(e){let n=await ke(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let s of Object.values(n.sessions))s.acpSessionId&&(s.acpSessionId=void 0,i=!0);i&&await je(n)}async repairAgent(e){if(Mr(e._meta,mt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${mt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${mt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){oe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,mt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){oe.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){oe.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(s)})}}async getFileTree(e){Mr(e._meta,"_agent/getFileTree");let n=e._meta,i=Xn(n),s=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(s,a),u=await wd(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 pi(d,s))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let h=gb(e.depth);return u.isDirectory()?{tree:await pb(s,d,a,h)}:{tree:[{name:mb(a),path:K0(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Mr(e._meta,"_agent/getFileContent");let n=Xn(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(i,e.filePath),a=await wd(s).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 pi(s,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>D0)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${D0})`);let d=await To(s);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 ke(e).catch(()=>null))?.workspace??Ne(e).workspace}safeJoin(e,n){let i=Ed(e,n||"."),s=Id(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${O0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return ke(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 M0(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 Ur(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:tr(e,i??J()),subdir:"skills"}}}function B0(t){let e=Gy();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 eb(t,e,n,i,s,a){let d=async u=>Sd(xe(u,"SKILL.md")).then(h=>h.isFile()).catch(()=>!1);if(!s){let{base:u,subdir:h}=Ur(n,t,e,a),x=xe(h,i),g=xe(u,x);return await d(g)?{absDir:g,relPath:x}:null}for(let u of B0(n)){let h=xe(u,i);if(await d(h))return{absDir:h,relPath:h}}return null}async function tb(t,e,n,i,s,a){let d=M0(i),u=await eb(t,e,n,d,s,a);if(u)return{...u,dirName:d};let x=(s?await G0(t,n):await H0(t,e,n,a)).filter(v=>v.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${s?"global":"workspace"}: ${x.map(v=>P0(v.relPath)).join(", ")} \u2014 rename or remove duplicates`);let g=x[0];return g?{absDir:s?g.relPath:xe(e,g.relPath),relPath:g.relPath,dirName:P0(g.relPath)}:null}function F0(t,e){return(Hy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function z0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
+ ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let s of n.split(`
102
+ `)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(s);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 U0(t,e,n,i){let s=await R0(e,{withFileTypes:!0}).catch(()=>null);if(!s)return[];let a=[];for(let d of s){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await Sd(xe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=xe(n,h),g=xe(e,h,"SKILL.md"),w=await To(g,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let v=z0(w);a.push({relPath:x,skill:{skillId:F0(t,x),skillName:v.name||h,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function H0(t,e,n,i){let{base:s,subdir:a}=Ur(n,t,e,i);return U0(t,xe(s,a),a,!1)}async function G0(t,e){let n=[],i=new Set;for(let s of B0(e)){let a=await U0(t,s,s,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var nb=3e4,rb=50*1024*1024,C0=10*1024*1024,zr=3e4;async function Do(t){let{agentId:e,workspace:n,framework:i,skill:s,paths:a}=t;if(!s.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let d=typeof s.content=="string"&&s.content.length>0,u=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!d&&!u)throw new k("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let h=M0(s.skillName),{base:x,subdir:g}=Ur(i,e,n,a),w=xe(g,h),v=xe(x,w);if(await _d(v,{recursive:!0}),d){let E=Buffer.from(s.content,"utf8");Ji(E.length),await bd(xe(v,"SKILL.md"),E,"utf8")}else{let E=await ob(s.downloadUrl);cb(E)?await fb(E,v):db(E)?await lb(E,v):await bd(xe(v,"SKILL.md"),E.toString("utf8"),"utf8")}let _={skillId:s.skillId,skillName:s.skillName,relPath:w,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return oe.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:w,source:d?"content":"downloadUrl"}),_}function Co(t,e,n){let i=e.get(n.skillId);if(i!==void 0){t[i]=n;return}e.set(n.skillId,t.length),t.push(n)}function ib(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}function sb(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function q0(t,e){let n=await ke(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=zt,s=n.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return n.skillsRefreshedForVersion=i,await je(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((w,v)=>[w.skillId,v])),u=a.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await je(n,e),{status:"noop",count:0};let h=0,x=0,{base:g}=Ur(n.framework,t,n.workspace,e);oe.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:s,current:i,skillBase:g,builtinCount:u.length,builtinRelPaths:u.map(w=>w.relPath)});for(let w of u)try{let v=xe(g,w.relPath);oe.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:v}),await yd(v,{recursive:!0,force:!0});let _=await Do({agentId:t,workspace:n.workspace,framework:n.framework,skill:sb(w),...e?{paths:e}:{}});Co(a,d,_),h+=1}catch(v){x+=1,oe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(v)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await je(n,e),oe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function ob(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ji(e);let n=ab(t);return Ji(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await To(e);return Ji(n.length),n}if(Ki(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),nb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let s=await i.arrayBuffer();return Ji(s.byteLength),Buffer.from(s)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ji(t){if(t>rb)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function ab(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 cb(t){return t.length>=2&&t[0]===31&&t[1]===139}function db(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],n=t[3];return e===3&&n===4||e===5&&n===6}function vd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function lb(t,e){let n,i;try{n=new Ad.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||vd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let s=ub(i),a=Ed(e);for(let d of i){if(vd(d.entryName))continue;let u=d.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let h=Ed(e,u),x=Id(a,h);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await _d(h,{recursive:!0});continue}await _d(qy(h),{recursive:!0});let g;try{g=d.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await bd(h,g)}}function ub(t){let e;for(let n of t){let i=n.entryName;if(!i||vd(i))continue;let s=i.indexOf("/");if(s<=0)return;let a=i.slice(0,s+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function fb(t,e){await hb(t);let n=t0({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${zr}ms)`))},zr);try{await N0(L0.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${zr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}}async function hb(t){let e=[],n=Nr({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,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${zr}ms)`))},zr);try{await N0(L0.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${zr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var xb=5e3;async function pb(t,e,n,i){return j0(t,e,n,i,{count:0})}async function j0(t,e,n,i,s){if(i<=0)return[];let a;try{a=await R0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if($y.has(u.name)||u.isSymbolicLink())continue;if(s.count>=xb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=xe(e,u.name),x=jy(xe(n,u.name)),g=null;try{g=await wd(h)}catch{continue}if(g.isSymbolicLink())continue;s.count++;let w={name:u.name,path:K0(Id(t,h)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(w.children=await j0(t,h,x,i-1,s)),d.push(w)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function gb(t){return!t||t<=0?Ky:Math.min(t,Wy)}function mb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function K0(t){return t.split(O0).join("/")}ne();var Dn=K("agent-health-reporter"),wb=1e4,_b=3,Yi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??wb,this.livenessFailureThreshold=e.livenessFailureThreshold??_b}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Dn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Dn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Dn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Dn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=yb(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),n.push(h)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:zt,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Dn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=s?.authFailures;if(a&&a.length>0&&(Dn.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){Dn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Dn.warn("onTickEnd hook failed",{err:String(n)})}}};function yb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Vt();import{copyFile as BE,cp as FE,mkdir as qo,readFile as zE,rm as UE,stat as Ld,writeFile as HE}from"node:fs/promises";import{homedir as Th}from"node:os";import{basename as GE,join as rn}from"node:path";xn();import{existsSync as Cb}from"node:fs";import{release as Rb}from"node:os";import{basename as Ob,isAbsolute as Lb}from"node:path";function Xi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Hr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Gr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Cn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ye();var Ro=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function W0(t){return"method"in t&&"id"in t&&t.id!==void 0}function $0(t){return"method"in t&&!("id"in t)}function Oo(t){return!("method"in t)&&"id"in t}var bb={AGENT_NOT_FOUND:X.AGENT_NOT_FOUND,AGENT_BUSY:X.AGENT_BUSY,AGENT_DISCONNECTED:X.AGENT_DISCONNECTED,AGENT_TIMEOUT:X.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:X.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:X.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:X.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:X.INTERNAL_ERROR,BRIDGE_INTERNAL:X.INTERNAL_ERROR,IPC_AUTH_FAILED:X.INTERNAL_ERROR,IPC_BAD_REQUEST:X.INVALID_REQUEST,METHOD_NOT_FOUND:X.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:X.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:X.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:X.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:X.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:X.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:X.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:X.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:X.FILE_TOO_LARGE,UNSUPPORTED_MIME:X.UNSUPPORTED_MIME,UPLOAD_FAILED:X.UPLOAD_FAILED,UPSTREAM_NOT_READY:X.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:X.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:X.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:X.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:X.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:X.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:X.SKILL_ZIP_TOO_LARGE};function Eb(t){if(t!=null)return t instanceof Error?{name:t.name,message:Qi(t.message)}:typeof t=="string"?Qi(t):typeof t=="object"?Sb(t):t}var vb=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Qi(t){let e=t;for(let[n,i]of vb)e=e.replace(n,i);return e}function Sb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Qi(i):e[n]=i;return e}function es(t){if(t instanceof k){let e=Eb(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(n.reason=e.reason),{code:bb[t.code]??X.INTERNAL_ERROR,message:Qi(t.message),data:n}}return{code:X.INTERNAL_ERROR,message:Qi(t instanceof Error?t.message:String(t))}}function V0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,s=i?e?.message:t.message,a=t.data;if(i&&e){let{message:d,...u}=e;a=u}return new k(n,s,{retriable:e?.retriable??!1,cause:a})}function J0(t){return`${JSON.stringify(t)}
103
+ `}var Z0=10*1024*1024,Lo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>Z0){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${Z0} bytes`)}),[]}let n=this.buffer.split(`
104
+ `);this.buffer=n.pop()??"";let i=[];for(let s of n){let a=s.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 X0={"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"},gP=Object.fromEntries(Object.entries(X0).map(([t,e])=>[e,t])),Ib={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},qr=class{seq=0;next(e,n){this.seq+=1;let i=X0[e]??Ab(e),s=Ib[i]??[],a=[i,String(this.seq)];if(s.length>0){let d=s.map(h=>Y0(n?.[h]??"")),u=kb(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>Y0(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function Ab(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Y0(t){return t.replace(/[:_\s]+/g,"-")}function kb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}tn();xr();Ye();ne();Ce();import{execFileSync as Tb,spawnSync as Pb}from"node:child_process";function ts(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ns(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),Pb("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var kd=new Set;function Q0(t){typeof t=="number"&&t>0&&kd.add(t)}function eh(t){typeof t=="number"&&kd.delete(t)}function th(){for(let t of kd)ns(t,"SIGKILL")}var jr="coze-bridge-daemon";function nh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return Tb("pgrep",["-U",String(s),"-f",jr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
105
+ `).map(s=>Number.parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0&&s!==i)}async function rh(t,e){if(t.length===0)return;let n=e?.killFn??ns,i=e?.isAliveFn??ts,s=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<a&&t.some(h=>i(h));u+=d)await s(Math.min(d,a-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var Db=[{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 Db)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function sh(t,e){return ih(t,e)}function oh(t,e){return ih(t,e)}function Kr(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 ah(t,e,n){let s=n-t.armedAt-t.expectedIntervalMs;if(s>e.suspendThresholdMs){let x=t.suspendedMs+s,g=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:s,rearmMs:Kr(g,t.firstFrameSeen,e)}}let a=n-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return a>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?a<e.phase2GateMs?{action:"continue",rearmMs:Kr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Kr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Kr(a,!1,e)}}var ch=Qe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Nb=200,Mb=40,Bb=Qe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fb=Qe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zb=Qe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Ub=Qe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hb=Qe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Gb=Qe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),dh=500;function qb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=dh?t:`${e.slice(0,dh)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function jb(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:n}=t;if(typeof n=="string")e.push(n);else if(n&&typeof n=="object")try{e.push(JSON.stringify(n))}catch{}return e.join(" ")}function lh(t){try{return Cb(t)}catch{return}}function Kb(t,e){return{platform:process.platform,osRelease:Rb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Lb(e.command)?lh(e.command):void 0,cwd:e.cwd,cwdExists:lh(e.cwd),envKeys:e.envKeys}}function Wb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ob(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var wt=class{constructor(e){this.opts=e;this.log=K(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Lo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new qr;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=So(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=ct(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Q0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",s=>{try{for(let a of this.decoder.push(s))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",s=>{let a=s.trimEnd();this.stderrRing.push(a),this.stderrRing.length>Nb&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),i.stdin?.on("error",s=>{this.log.warn("child stdin error",{err:String(s)})}),i.stdout?.on("error",s=>{this.log.warn("child stdout error",{err:String(s)})}),i.stderr?.on("error",s=>{this.log.warn("child stderr error",{err:String(s)})}),i.on("exit",(s,a)=>{this.stopped=!0,eh(i.pid),(s!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:s,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(s,a));for(let u of this.exitHandlers)u(s,a)}),i.on("error",s=>{let a=s,d=Kb(a,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(s),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",Wb(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()));ns(n.pid,"SIGTERM");let s=setTimeout(()=>{n.killed||ns(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Hb,phase2GateMs:Bb,livenessWindowMs:Fb,absoluteMaxMs:zb,approvalMaxMs:Gb,suspendThresholdMs:Ub,...n};return this.call("session/prompt",e,ch,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Hr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Gr(e,n))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Cn(e,n))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,n,i=ch,s){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=Xi(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let h=n.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let g={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(s){let w=this.now(),v={cfg:s,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Kr(0,!1,s),sessionId:u};g.promptTimeout=v;let _=()=>{let E={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},I=this.now(),A=ah(E,v.cfg,I),T=O=>{v.armedAt=I,v.expectedIntervalMs=O,g.timer=setTimeout(_,O)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(_,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(g.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,g);try{this.writeFrame(d)}catch(w){g.timer&&clearTimeout(g.timer),this.pending.delete(a),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(J0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Oo(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:qb(e.result)}),n.resolve(e.result));return}if($0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let s=i.promptTimeout;s&&(s.firstFrameSeen=!0,s.lastActivityAt=this.now(),this.trackToolCall(s,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(s=>this.log.warn("update handler failed (async)",{err:String(s)}))}catch(s){this.log.warn("update handler threw sync, swallowed",{err:String(s)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(W0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,s=i?.sessionUpdate;if(s!=="tool_call"&&s!=="tool_call_update")return;let 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";s==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Cn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let n of this.agentRequestHandlers)try{await n(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(Cn(e.id,es(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=V0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=oh(this.framework,jb(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(Mb).join(`
106
+ `),s=sh(this.framework,i);return s?new k(s.bridgeCode,s.message,{cause:{reason:s.reason,code:e,signal:n,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function $b(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=i));return e}var No=class extends wt{framework="claude-code";constructor(e){let{command:n,args:i}=xi("claude-code",e.command,e.args??[]),s={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return $b(e)}};xn();import{spawn as Vb}from"node:child_process";import{closeSync as Zb,existsSync as Dd,mkdirSync as Jb,mkdtempSync as Yb,openSync as Xb,readFileSync as mh,readSync as Qb,readdirSync as eE,rmSync as tE,statSync as nE}from"node:fs";import{homedir as rE,tmpdir as iE}from"node:os";import{join as Wr}from"node:path";var uh=["default","acceptEdits","plan","auto","bypassPermissions"],fh=["read-only","auto","full-access"];var hh=["default","accept_edits","dont_ask"];function Ut(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return uh.includes(e);case"codex":return fh.includes(e);case"hermes":return hh.includes(e);case"openclaw":return!1}}function Mo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function xh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Td(t){switch(t){case"claude-code":return uh.join("/");case"codex":return fh.join("/");case"hermes":return hh.join("/");case"openclaw":return""}}Ce();var Cd=9e4,sE=64*1024,oE=100;function aE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Cd:Math.max(1,Math.floor(e*1e3))}function cE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Cd:Math.max(1,Math.floor(e))}function dE(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return Object.keys(e).length>0?e:void 0}function ph(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:Cd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let n=typeof e.command=="string"?e.command.trim():"";if(!n)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,s=dE(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?aE(e.timeout):cE(e.timeout_ms),...i?{cwd:i}:{},...s?{env:s}:{}}}function Pd(t){if(Array.isArray(t))return t.flatMap(i=>Pd(i));if(!t||typeof t!="object"){let i=ph(t);return i?[i]:[]}let e=t;if(e.hooks)return Pd(e.hooks);let n=ph(e);return n?[n]:[]}function lE(t){let e=Wr(t,"hooks.json");if(!Dd(e))return[];let n=JSON.parse(mh(e,"utf8")),s=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return Pd(s.Stop??s.stop)}function uE(t,e){let n=Wr(t,"sessions");if(!Dd(n))return;let i=[],s=a=>{let d;try{d=eE(a,{withFileTypes:!0})}catch{return}for(let u of d){let h=Wr(a,u.name);if(u.isDirectory())s(h);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:h,mtimeMs:nE(h).mtimeMs})}catch{}}};s(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,oE))if(fE(a.path,e))return a.path}function fE(t,e){let n;try{n=Xb(t,"r");let i=Buffer.alloc(sE),s=Qb(n,i,0,i.length,0),a=i.subarray(0,s).toString("utf8");return a.includes(JSON.stringify(e))||a.includes(e)}catch{return!1}finally{if(n!==void 0)try{Zb(n)}catch{}}}function hE(t){return Qn(t??J().agentEnvFile)}function xE(t){let e=t.trim();if(e.length>=2){let n=e[0];if((n==='"'||n==="'")&&e.endsWith(n)){let i=e.slice(1,-1);return n==='"'?i.replace(/\\n/g,`
107
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function pE(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.startsWith("export ")?i.slice(7).trimStart():i,a=s.indexOf("=");if(a<=0)continue;let d=s.slice(0,a).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=xE(s.slice(a+1)))}return e}function gE(t){let e=Wr(t,"cozeloop.env");return Dd(e)?pE(mh(e,"utf8")):{}}function gh(t){let e=t?.trim();return e||void 0}function mE(t){let e=hE(t.agentEnvFile),n=gh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=gh(t.env?.HOME??e.HOME??process.env.HOME)??rE();return Wr(i,".codex")}var Bo=class extends wt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:s,args:a}=xi("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Yb(Wr(iE(),"coze-bridge-codex-home-")):mE(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Jb(d,{recursive:!0});let h=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:s,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...h?{env:h}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=Ut("codex",e.modeId)?Mo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(wE(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=lE(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let s=uE(n,e),a=JSON.stringify({hook_event_name:"Stop",session_id:e,...s?{transcript_path:s}:{},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,s)=>{let a=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=a?gE(a):{},u=So(process.env,this.opts.agentEnvFile??J().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 h=Vb(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",g=setTimeout(()=>{h.kill("SIGTERM"),s(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);h.stderr?.setEncoding("utf8"),h.stderr?.on("data",w=>{x+=w,x.length>4e3&&(x=x.slice(-4e3))}),h.on("error",w=>{clearTimeout(g),s(w)}),h.on("close",(w,v)=>{if(clearTimeout(g),w===0){i();return}s(new Error(`hook exited code=${w} signal=${v} stderr=${x.slice(-1e3)}`))}),h.stdin.end(`${n}
108
+ `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{tE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function wE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=xh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var _E=K("hermes-downstream"),Fo=class extends wt{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(n){_E.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}};Ye();var yE=3e4,$r=class extends wt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let s={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},yE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};$t();Ye();ne();Ce();function Rd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}xn();var Rn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((n,i)=>{this.slots.push({task:e,resolve:n,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let n=await e.task();e.resolve(n)}catch(n){e.reject(n)}}}finally{this.running=!1}}}};var zo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Rn,this.sessionQueues.set(e,n)),n}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let n=this.sessionQueues.get(e);return!!n&&!n.isDisposed}async dispose(e){this.status="stopped";let n=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(n);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let n=[];for(let[,i]of this.sessions)Vr(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 Vr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function nn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}tn();ne();import{constants as wh}from"node:fs";import{access as bE,readFile as EE}from"node:fs/promises";import{delimiter as vE,dirname as SE,join as _h}from"node:path";var it=K("framework-detector"),yh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},IE=[".exe",".cmd",".bat",".ps1"],nr=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??ct,access:e.access??bE,readFile:e.readFile??EE}}async detect(e){let n=yh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return it.debug("framework binary not found",{framework:e,bin:n}),null;let s=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,s),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(yh).map(async i=>[i,await this.detect(i)])),n={};for(let[i,s]of e)s&&(n[i]=s);return n}async which(e){let n=this.env.pathEnv.split(vE).filter(Boolean),i=this.env.platform==="win32"?["",...IE]:[""];for(let s of n)for(let a of i){let d=_h(s,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?wh.F_OK:wh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(d){return it.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let s=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!s)return it.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=_h(SE(s),"hermes-acp");return await this.isExecutable(a)?(it.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(it.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:a}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return it.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return it.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return it.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let s=JSON.parse(i[0]);if(!Array.isArray(s))return it.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=s.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(it.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(it.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return it.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(s),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return it.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||it.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let s={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(s.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(s.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(s.detail=d.rpc.error)}catch(d){it.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return s}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(kE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let s="",a=!1,d,u=h=>{a||(a=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{s+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:s}))}catch{u(null)}})}},AE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function kE(t){return t.replace(AE,"")}import{homedir as Eh}from"node:os";import{join as Ho}from"node:path";$t();tn();xr();Ye();ne();async function vh(){let t=Ho(Eh(),".openclaw/openclaw.json");return pn(t)}async function Sh(){return(await vh())?.gateway?.auth?.token??""}var rr=K("openclaw.config"),TE=[0,5e3,5e3],PE=Qe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),bh="models.providers.",Uo="agents.defaults.models",DE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function Zr(t,e){let n=Array.isArray(t)?[...t]:[],i=new Set(n);for(let s of e)i.has(s)||(i.add(s),n.push(s));return n}var Go=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Rn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??TE,this.cliTimeoutMs=e.cliTimeoutMs??PE,this.openclawDir=e.openclawDir??Ho(Eh(),".openclaw")}async withRetry(e,n){let i;for(let s=0;s<this.retryDelaysMs.length;s++){let a=this.retryDelaysMs[s]??0;a>0&&await new Promise(d=>setTimeout(d,a));try{return await n()}catch(d){i=d,rr.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let s=ct(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};s.stderr?.on("data",x=>{a+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),s.on("error",x=>u(()=>i(x))),s.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let s=String(i);if(n.some(a=>s.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){rr.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",`${bh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${bh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Uo}[${e}]`,()=>this.runCli(["config","set",Uo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Uo}[${e}]`,`${Uo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await vh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let s=`${e}/`,a=[];for(let d of Object.keys(i))d.startsWith(s)&&a.push(d.slice(s.length));return a}ensureAgent(e,n,i){let s=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&s.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["already exists","already registered"])))}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=Ho(this.openclawDir,"identity","device.json"),i=(await pn(e))?.deviceId?.trim();if(!i)return rr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let s=Ho(this.openclawDir,"devices","paired.json"),a=await pn(s),d=a?.[i];if(!a||!d)return rr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,h=Zr(Zr(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(E=>E.startsWith("operator.")),x=Zr([...DE],h),g=Zr(d.scopes,x),w=Zr(d.approvedScopes,x),v=u?Zr(u.scopes,x):void 0;return g.length!==(d.scopes?.length??0)||w.length!==(d.approvedScopes?.length??0)||u!==void 0&&v?.length!==(u.scopes?.length??0)?(d.scopes=g,d.approvedScopes=w,u&&v&&(u.scopes=v),await gn(s,a,{mode:384}),rr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(rr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return rr.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 CE,writeFile as RE}from"node:fs/promises";import{join as OE}from"node:path";var LE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
109
+ `),NE=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
110
+ `);function ME(t){return t.length===0?t:`${(t.endsWith(`
103
111
  `)?t.slice(0,-1):t).split(`
104
112
  `).map(s=>s.endsWith("\r")?s.slice(0,-1):s).join(`
105
113
  `)}
106
- `}async function dx(t){let e=dE(t,"HEARTBEAT.md"),r=await aE(e,"utf8");return fE(r)!==lE?!1:(await cE(e,uE),!0)}var ee=j("agent-manager"),_E=["hooks.json","cozeloop.env"],yE=["hooks"];async function bE(t,e){let r=Xt(ze(t,e).root,"codex-home"),i=Xt(fx(),".codex");if(r!==i){await Oo(r,{recursive:!0});for(let s of yE){let c=Xt(i,s),l=Xt(r,s);try{await Sd(l);continue}catch{}try{await hE(c,l,{recursive:!0,errorOnExist:!0,filter:u=>{let x=wE(u);return!x.endsWith(".log")&&!x.includes(".bak")}}),ee.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&ee.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}for(let s of _E){let c=Xt(i,s),l=Xt(r,s);try{await Sd(l);continue}catch{}try{if(s==="cozeloop.env"){let x=(await pE(c,"utf8")).split(/\r?\n/).filter(h=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(h)).join(`
107
- `);await mE(l,x,{mode:384})}else await xE(c,l);ee.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&ee.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}}}var Id="acceptEdits",xx="full-access",hx="read-only";function EE(t){return{INITIAL_AGENT_MODE:ko(t)}}var vE=(t,e,r,i,s,c,l,u,x,h,m,w)=>{switch(t){case"claude-code":{let S={...s?{...l0(s),...x0(s,l,u,w)}:{},...x??{},IS_SANDBOX:"1"};return new Ao({cwd:r,env:S,agentId:i})}case"codex":{let S=xx;h!==void 0&&(Bt("codex",h)?S=h:ee.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let y={...s?{...f0(s),...u0(s,l,u,w)}:{},...EE(S),...s?{NO_BROWSER:"1"}:{},...x??{},...s?{COZELAB_ONBOARD_CLOUD:"true"}:{}},E=!!s;return new To({cwd:r,agentId:i,...Object.keys(y).length>0?{env:y}:{},...E?{authMethodId:"api-key",isolateCodexHome:!0,...m?{codexHomeDir:m}:{}}:{}})}case"openclaw":return new qr({command:e,cwd:r,agentId:i,...c?{sessionName:Ed(c)}:{}})}};function vd(t){return t==="claude-code"||t==="codex"}function SE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let s=t[i];s!==void 0&&(IE(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
108
- `)}
109
- `}function IE(t){if(t.includes(`
110
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var AE={path:"",version:"cloud-deployed"},lx="openclaw_gateway_unavailable",kE="openclaw_default_agent_missing";function ux(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 TE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},CE=6e4,Lo=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??vE,this.createTimeoutMs=e.createTimeoutMs??CE,this.detectorFactory=e.detectorFactory??(()=>new Yn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Do({command:r,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??Xt(fx(),".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=>{ee.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=Xt(e,".env");if(await Sd(r).then(c=>c.isFile()).catch(()=>!1)){ee.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let s=SE({...process.env,...$i(this.paths.agentEnvFile)});await un(r,s,{mode:384}),ee.info("openclaw .env bootstrapped",{envFile:r,bytes:s.length}),await this.getOpenclawConfig().restartGateway(),ee.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await Re(e.agentId,this.paths).catch(()=>null),s=po(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")ee.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>ee.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(s&&c.deployType!=="cloud")ee.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>ee.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ee.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await Re(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Ue(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ee.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await Re(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Ue(T,this.paths))}return ee.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!s&&!this.config.frameworksCache?.[e.framework])throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=ze(e.agentId,this.paths),x=s?"cloud":"local",h=e.framework==="openclaw"&&x==="local",m;h&&!r?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=m??(h?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??w??u.workspace,y=new AbortController,E=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{s&&vd(e.framework)&&await hr(e.framework,y.signal);let T=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await Oo(u.root,{recursive:!0}),await Oo(S,{recursive:!0}),await Oo(u.logs,{recursive:!0}),T(),h||await pr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(x==="cloud"?await Ga(S,"cloud"):await Ga(S,"local",Id)),T();let C=i,b=c0({model:e.model??C?.model}),R=Vf(e._meta)??C?.accountId,D=e.patToken??C?.patToken,F=x==="cloud"?e.modelInfo??C?.modelInfo:void 0;if(I=new Co({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Nt,deployType:x,...R?{accountId:R}:{},...D?{patToken:D}:{},...F?{modelInfo:F}:{}}),I.status="ok",C?.sessions){let V=x==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,te]of Object.entries(C.sessions)){let ae={acpSessionId:te.acpSessionId,modelToken:te.modelToken,tokenGeneratedAt:te.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?te.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",ee.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:ae.permissionMode})):Bt(e.framework,te.permissionMode)?ae.permissionMode=te.permissionMode:ee.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:te.permissionMode}):te.permissionMode!==void 0&&ee.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:x}),te.cozeGroupId&&(ae.cozeGroupId=te.cozeGroupId),te.tokenGroupId&&(ae.tokenGroupId=te.tokenGroupId),te.requestScene&&(ae.requestScene=te.requestScene),I.sessions.set(X,ae)}let se=Object.keys(C.sessions).length;se>0&&ee.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:se})}this.registry.register(I),A=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:C?.createdAt??Date.now(),sessions:C?.sessions??{},model:b.model};if(x==="cloud"&&(B.deployType="cloud"),R&&(B.accountId=R),D&&(B.patToken=D),F&&(B.modelInfo=F),C?.skills&&(B.skills=C.skills),C?.agentName&&(B.agentName=C.agentName),C?.description&&(B.description=C.description),B.skillsRefreshedForVersion=C?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&x==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):ee.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await dx(S)&&ee.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:S})}catch(V){ee.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:S,err:String(V)})}}let J=e.initialSkills??[];if(J.length>0){let V=[...B.skills??[]],se=new Map(V.map((ae,P)=>[ae.skillId,P])),X=await Promise.allSettled(J.map(ae=>yo({agentId:e.agentId,workspace:S,framework:e.framework,skill:ae}))),te=0;for(let[ae,P]of X.entries()){let q=J[ae];q&&(P.status==="fulfilled"?(bo(V,se,P.value),te++):ee.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:q.skillId,skillName:q.skillName,err:String(P.reason)}))}te>0&&(B.skills=V,ee.info("initialSkills installed",{agentId:e.agentId,installed:te,requested:J.length}))}return await Ue(B,this.paths),ee.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:x}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(T){throw ee.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await gE(u.root,{recursive:!0,force:!0}).catch(C=>ee.warn("rm agent dir failed (ignored)",{err:String(C)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,r,i,s,c,l){let x=this.config.frameworksCache?.[e.framework];if(!x)if(e.deployType==="cloud"&&vd(e.framework))x=AE;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);vd(e.framework)&&!bs(e.framework)&&(ee.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await hr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,m;if(e.framework==="openclaw")m=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:s,mockScenario:c,requestScene:l,command:x.path});else{let w=e.sessions.get(i),S=Yt(e)?w?.permissionMode??xx:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await bE(e.agentId,this.paths),m=this.factory(e.framework,x.path,e.workspace,e.agentId,h,i,s,c,this.buildBinShimPathEnv(),S,e.framework==="codex"&&e.deployType==="cloud"?Xt(ze(e.agentId,this.paths).root,"codex-home"):void 0,l)}try{return await m.start(),await m.initialize(TE),m}catch(w){let S=m instanceof Mt?m.getStderrTail():[];throw S.length>0&&ee.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof k?w.code:"unknown",recentStderr:S}),await m.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,x.path,w)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let s=await this.detectorFactory().probeOpenclawGateway(r);if(!s.reachable)return new k("AGENT_ENV_NOT_READY",ux(s),{cause:{reason:lx}})}catch(s){ee.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(s)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};ee.warn("openclaw default agent stale or missing, attempting lazy re-detect");let r=await this.detectorFactory().detect("openclaw");if(r?.defaultAgent?.id&&r.defaultAgent.workspace)return ee.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:kE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new k("AGENT_ENV_NOT_READY",ux(r),{cause:{reason:lx}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:s,cozeEnv:c,mockScenario:l,requestScene:u,command:x}=e,h=Ed(s);if(r.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new qr({command:x,cwd:S.workspace,agentId:S.id,sessionName:h})}let m=await cx();try{let S=this.getOpenclawConfig();await S.ensureAcpDeviceScopes()&&await S.restartGateway()}catch(S){ee.warn("acp device scope ensure failed (ignored)",{err:String(S)})}let w;if(i?.modelToken){let S=id(s),y=sd(i),E=`${S}/${y}`,I=JSON.stringify({modelConfig:i,cozeEnv:c,mockScenario:l,requestScene:u});if(this.ensuredProviders.get(E)!==I){let A=this.getOpenclawConfig(),T=await A.getAllowlistModelsForProvider(S),C=h0(i,c,l,T,u);C&&(await A.ensureProvider(S,C),await A.addModelToAllowlist(E),this.ensuredProviders.set(E,I))}w=E}return new qr({command:x,cwd:r.workspace,agentId:r.agentId,sessionName:h,...m?{gatewayToken:m}:{},...w?{slashModelOnStart:w}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e,r){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,s=r??e.model;for(let c of e.sessions.keys()){let l=id(c),u=`${l}/${s}`,x=!0;try{await i.removeProvider(l)}catch(h){x=!1,ee.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:l,err:String(h)})}try{await i.removeModelFromAllowlist(u)}catch(h){x=!1,ee.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(h)})}x&&this.ensuredProviders.delete(u)}}};import{randomUUID as yx}from"node:crypto";import{promises as ME}from"node:fs";import{basename as bx}from"node:path";Ve();ie();import{promises as RE}from"node:fs";import{basename as PE}from"node:path";var px=j("file-upload"),DE="/api/coze_claw/file/agent_upload",OE=6e4;async function gx(t,e={}){let i=`${Or(Lr(e.handshakeBase))}${DE}`,s=e.timeoutMs??OE,c=await RE.readFile(t.path),l=new FormData;l.append("agent_id",t.agentId),l.append("session_id",t.sessionId),l.append("file_name",t.name),l.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},x=new AbortController,h=setTimeout(()=>x.abort(),s);px.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:l,signal:x.signal}),w=m.headers.get("x-tt-logid")??"";if(!m.ok){let E=await m.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${w}: ${E.slice(0,200)}`)}let S=await m.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${w}`);let y=S.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(S).slice(0,200)}`);return px.info("file upload ok",{uri:y,logid:w}),{uri:y}}catch(m){throw m instanceof k?m:m.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${s}ms) for ${PE(t.path)}`):new k("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(h)}}Ve();ie();import{extname as LE}from"node:path";var NE={".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 mx(t){let e=LE(t).toLowerCase();return NE[e]??"application/octet-stream"}Ce();var No=j("agent-send"),_x=50*1024*1024;function Ex(t,e,r){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let s=i.sessions.get(r);if(!s)throw new k("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:s}}async function vx(t,e,r,i,s,c){let u;for(let x=0;x<=2;x++)try{await t.core.sendAgentFileUpdate(e,r,i,s);return}catch(h){u=h,x<2&&(No.warn("sendAgentFileUpdate failed, retrying",{attempt:x+1,err:String(h)}),await new Promise(m=>setTimeout(m,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function Sx(t,e){let{session:r,runtime:i}=Ex(e.core,t.agentId,t.sessionId);if(!await di(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let s=await ME.stat(t.path).catch(()=>null);if(!s||!s.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(s.size>_x)throw new k("FILE_TOO_LARGE",`${s.size} bytes > limit ${_x}`);let c=await mx(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let l=t.name??bx(t.path),u;try{u=await gx({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:s.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(h){throw No.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.size,mime:c,code:h instanceof k?h.code:"UNKNOWN",message:h instanceof Error?h.message:String(h)}),h}let x={sessionUpdate:"agent_file",messageId:yx(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:l,sizeBytes:s.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await vx(e,r,i,t.sessionId,x,"agent file uploaded to cloud but sendAgentFileUpdate failed"),No.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:s.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:s.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Ix(t,e){let{session:r,runtime:i}=Ex(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let s=t.name??bx(t.path),c={sessionUpdate:"group_file",messageId:yx(),content:{uri:t.path,name:s,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await vx(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),No.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:s,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function Ax(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),s=Math.max(r.length,i.length);for(let c=0;c<s;c++){let l=r[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}Zt();ie();dn();var Ft=j("coze-cli-installer"),kx="@coze/cli@latest",BE="coze",Tx="0.1.8",FE=5e3,zE=5e3,UE=9e4,Cx=1e4,Zi=null,Mo=!1;async function kd(t,e={}){if(Mo)return;if(Zi)return Zi;let r=e.exec??e0;return Zi=(async()=>{try{let i=await HE(BE,r),s=!1;if(i){let l=await qE(r);if(l===void 0)Ft.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Ax(l,Tx))Ft.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:Tx}),s=!0;else{Ft.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),Mo=!0;return}}let c=s?"upgrade-only":"full";Ft.info("coze-cli install start",{package:kx,mode:c});try{await r("npm",["i","-g","--prefer-online",kx],{timeout:UE,maxBuffer:10*1024*1024}),Ft.info("coze-cli install ok")}catch(l){Ft.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(s){Mo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:Cx}),Ft.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Ft.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:Cx}),Ft.info("coze auth login ok")}catch(l){Ft.warn("coze auth login failed",{err:String(l)});return}Mo=!0}finally{Zi=null}})(),Zi}async function HE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:FE});return Ha(i)}catch{return}}async function qE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:zE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}xn();Ce();var GE=10*6e4;function Rx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?GE:e}function Bo(t){return ln(t??Z().configFile)}function Yi(t,e){return fn(e??Z().configFile,t)}import{randomBytes as dv}from"node:crypto";lr();Ve();ie();import{createReadStream as jE}from"node:fs";import{mkdir as WE,readFile as KE,realpath as $E,stat as VE,writeFile as JE}from"node:fs/promises";import{basename as ZE,dirname as Td,isAbsolute as YE,join as XE,relative as QE,resolve as Px,sep as ev}from"node:path";import{createInterface as tv}from"node:readline";var Ox=j("fs-rpc"),Xi=Ye("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Lx(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Xi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Xi} bytes`);let i=await Mx(t.path,e);return await WE(Td(i),{recursive:!0}),await JE(i,t.content,"utf8"),Ox.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Nx(t,e){let r=await Mx(t.path,e),i=await VE(r),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Xi&&!s)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Xi} bytes`);let c;if(s&&i.size>Xi)c=await nv(r,t.line??1,t.limit);else{let l=await KE(r,"utf8");if(s){let u=l.split(`
111
- `),x=Math.max(0,(t.line??1)-1),h=typeof t.limit=="number"?x+t.limit:void 0;c=u.slice(x,h).join(`
112
- `)}else c=l}return Ox.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function nv(t,e,r){let i=tv({input:jE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),s=Math.max(0,e-1),c=typeof r=="number"?s+r:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let x of i)if(u>=s&&u<c&&l.push(x),u++,u>=c)break}finally{i.close()}return l.join(`
113
- `)}async function Mx(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([Dx(Px(e)),Dx(Px(t))]),s=QE(r,i);if(rv(s,ev,YE(s)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function rv(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Dx(t){let e=[],r=t;for(;r!==Td(r);)try{let i=await $E(r);return e.length?XE(i,...e.reverse()):i}catch{e.push(ZE(r)),r=Td(r)}return t}ie();var Bx=j("prompt-multimodal"),Fx=10*1024*1024,iv=15e3,sv=6;async function zx(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,l=t[c];l!==void 0&&(e[c]=await ov(l))}}let s=Array.from({length:Math.min(sv,t.length)},()=>i());return await Promise.all(s),e}function Ux(t){return t.some(e=>e.type==="image")}async function ov(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!zi(e.uri))return t;try{let{buf:r,contentType:i}=await cv(e.uri),s=e.mimeType||av(i)||"application/octet-stream";return Bx.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:s}),{type:"image",data:r.toString("base64"),mimeType:s}}catch(r){return Bx.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function av(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function cv(t){let e=new AbortController,r=setTimeout(()=>e.abort(),iv);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let s=await i.arrayBuffer();if(s.byteLength>Fx)throw new Error(`image too large: ${s.byteLength} bytes (max ${Fx})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}hn();Ve();ie();var $=j("core"),lv=3e4,uv=/^(boe|ppe)_[A-Za-z0-9_-]+$/,fv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",xv="\u5BA1\u6279\u5DF2\u8D85\u65F6",hv=3e4,Fo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Fr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Rx(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}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(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(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,r,i){let s=i.downstream;s&&(s.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),s.onAgentRequest(c=>{this.handleAgentRequest(e,s,c)}),s.onExit((c,l)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),Gr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(s,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[s,c]of this.pendingUpstream)c.downstream===e&&i.push(s);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let s of i){let c=this.pendingUpstream.get(s);if(c){this.pendingUpstream.delete(s),this.upstream.send(Cn(s,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(l=>$.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(vo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&uv.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let s=e.params,c=Jf(s?._meta),l=s?.sessionId;if(e.method==="session/prompt"&&typeof l=="string"){let u=this.requestSceneBySession.get(l);c&&u!==c?(this.requestSceneBySession.set(l,c),$.info("cached request_scene for session",{sessionId:l,requestScene:c})):!c&&u!==void 0&&(this.requestSceneBySession.delete(l),$.info("cleared request_scene for session",{sessionId:l}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let x=await u(e,this);r!==null&&await this.upstream.send(Br(r,x));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Br(r,u));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Br(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(u){$.error("handleFrame failed",{method:e.method,err:String(u)}),r!==null&&await this.upstream.send(Cn(r,Ki(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(i);if(!s)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(s,e.method,r);if(e.method==="session/prompt"){let x=s.sessions.get(c);if(x?.pendingPermission){let h=r._meta?.cozeTriggerMsgId,m=go(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:c}),this.synthesizePromptReply(s,x,c,fv,h,m)}}let l=Date.now(),u=!1;try{let x=await s.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(s,e.method,r));return u=!0,x}finally{$.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:s}=Yf(i);switch(r){case"session/new":{let c=pv();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=s;return $.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=s,l=c.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Yt(e)?Zf(i._meta):void 0;if(u!==void 0&&!Bt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${wd(e.framework)}`);let x=go(i._meta),h=this.requestSceneBySession.get(l),m=await this.ensureRuntime(e,l,x,h);if(u!==void 0&&m.permissionMode===void 0&&(m.permissionMode=u,await this.persistSessionMapping(e)),m.replySeq=0,await this.ensureDownstream(e,l,m),!m.downstream||!m.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&m.permissionMode!==void 0&&m.permissionMode!==u){let y=m.permissionMode;m.permissionMode=u,await this.persistSessionMapping(e);try{await m.downstream.setSessionMode({sessionId:m.acpSessionId,modeId:u})}catch(E){throw m.permissionMode=y,await this.persistSessionMapping(e).catch(()=>{}),E}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(m.acpSessionId,w):e.activeTriggers.delete(m.acpSessionId),x?e.activeGroupIds.set(m.acpSessionId,x):e.activeGroupIds.delete(m.acpSessionId),x&&m.cozeGroupId!==x&&(m.cozeGroupId=x,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Ux(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let S=await zx(c.prompt);try{let y=await m.downstream.sessionPrompt({...c,sessionId:m.acpSessionId,prompt:S});return m.lastActiveAt=Date.now(),y}catch(y){if(y instanceof k&&y.code==="AGENT_APPROVAL_TIMEOUT"){let E=m.pendingPermission;E&&(E.downstream.respondAgentRequest(E.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(E.upstreamId),m.pendingPermission=void 0);let I=m.acpSessionId,A=I?e.activeTriggers.get(I):void 0,T=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:l}),await this.synthesizePromptReply(e,m,l,xv,A,T)}throw y}finally{if(e.activeTriggers.delete(m.acpSessionId),e.activeGroupIds.delete(m.acpSessionId),m.pendingPermission=void 0,m.reloadAfterTurn){m.reloadAfterTurn=!1;let y=m.downstream;y&&(m.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:m.acpSessionId}),y.stop("reload-after-turn").catch(E=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(E)})))}else m.downstream?.isAlive()&&this.armIdleTimer(e,l,m)}}case"session/cancel":{let l=s.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let x=e.getSessionQueue(l);x.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:x.size}),x.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=s,l=c.sessionId,u=c.modeId,x=go(i._meta);if(!l)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Yt(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Bt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${wd(e.framework)}`);if(x)return await this.handleGroupSetMode(e,x,u);let h=e.sessions.get(l)??await this.ensureRuntime(e,l);if(h.permissionMode===u)return{};let m=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(w){throw h.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),w}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let s=[];for(let[l,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&s.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(s.length===0)return $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:s.length});for(let l of s)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of s){let u=l.runtime.downstream,x=l.runtime.acpSessionId;u?.isAlive()&&x&&c.push({downstream:u,acpSessionId:x,oldMode:l.oldMode,runtime:l.runtime})}for(let l of c)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let x of s)x.runtime.permissionMode=x.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r,i,s){let c=e.sessions.get(r);if(c){let x=c.cozeGroupId!==i,h=e.deployType==="cloud"&&c.tokenGroupId!==i,m=c.requestScene!==s;if(h&&(c.modelToken=await this.requestSessionToken(e.agentId,r,i),c.tokenGeneratedAt=Date.now(),c.tokenGroupId=i),h||m){Gr(c);let w=c.downstream;c.downstream=void 0,w&&await w.stop("request-context-changed")}return c.cozeGroupId=i,c.requestScene=s,(x||h||m)&&await this.persistSessionMapping(e),c}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...s?{requestScene:s}:{}};return Yt(e)&&(u.permissionMode=e.framework==="claude-code"?Id:hx),e.sessions.set(r,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,r,i){let s={sessionId:r,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let c=await this.sendRequest(ht.GEN_MODEL_TOKEN,s,hv);if(!c?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return c.modelToken}catch(c){throw c instanceof k&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new k("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,r,i){if(Gr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=3,c=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=s&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let x;try{let h=this.requestSceneBySession.get(r);h&&$.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:r,requestScene:h}),x=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario,h)}catch(h){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=s&&i.acpSessionId&&($.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),h}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=x,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await x.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(h){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),i.acpSessionId=void 0;let m=await x.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let h=await x.sessionNew({cwd:e.workspace});i.acpSessionId=h.sessionId,await this.persistSessionMapping(e)}}catch(h){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),await x.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,h}if(x.afterSessionEstablished&&i.acpSessionId&&await x.afterSessionEstablished(i.acpSessionId),Yt(e)&&i.acpSessionId&&i.permissionMode)try{await x.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(h){$.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(h)})}}armIdleTimer(e,r,i){if(Gr(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let s=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),s&&s.stop("idle timeout").catch(c=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,s){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let l=e.activeTriggers.get(r.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Mr("session/update",{sessionId:i,update:s,_meta:c}))}async synthesizePromptReply(e,r,i,s,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Mr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(x=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(x)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,s=this.reverseSessionId(e,i);if(!s){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(s);if(!c){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(wv(r)){$.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=r.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Yt(e)){let m=l.currentModeId;Bt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(w=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof m=="string"&&!Bt(e.framework,m)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},x=e.activeTriggers.get(i);x&&(u.cozeTriggerMsgId=x);let h=e.activeGroupIds.get(i);h&&(u.cozeGroupId=h),this.upstream.send(Mr("session/update",{...r,sessionId:s,_meta:u})).catch(m=>$.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}$.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let s=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},l=await Lx(c,s);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await Nx(c,s);r.respondAgentRequest(i.id,l)}}catch(s){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),r.respondAgentRequestError(i.id,Ki(s))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let s=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,x=u?e.activeTriggers.get(u):void 0,h={cozeAgentId:e.agentId};x&&(h.cozeTriggerMsgId=x);let m=u?e.activeGroupIds.get(u):void 0;m&&(h.cozeGroupId=m);let w=u?this.reverseSessionId(e,u):void 0,S=w?e.sessions.get(w):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:s});let y={...c,...w?{sessionId:w}:{},_meta:h};this.pendingUpstream.set(s,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(ji(s,"session/request_permission",y)).catch(E=>{this.pendingUpstream.delete(s),$.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),r.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let s=r.value;this.clearPendingPermissionFor(s),e.error?($.info("upstream \u2192 permission response (error)",{agentId:s.agentId,upstreamId:e.id,method:s.method,error:e.error}),s.downstream.respondAgentRequestError(s.agentRequestId,e.error)):(s.method==="session/request_permission"&&gv(e.result,s),$.info("upstream \u2192 permission response (result)",{agentId:s.agentId,upstreamId:e.id,method:s.method,result:e.result}),s.downstream.respondAgentRequest(s.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Eo(e.error)):i.value.resolve(e.result);return}$.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let s=e.get(r);if(s)return{value:s,key:r};if(typeof r=="number"){let c=String(r),l=e.get(c);if(l)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=lv){let s=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),l(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(ji(s,e,r)).catch(x=>{let h=this.pendingBridge.get(s);h&&(clearTimeout(h.timer),this.pendingBridge.delete(s)),l(x)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,s]of e.sessions){let c={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(c.acpSessionId=s.acpSessionId),s.permissionMode&&Yt(e)&&(c.permissionMode=s.permissionMode),s.cozeGroupId&&(c.cozeGroupId=s.cozeGroupId),s.tokenGroupId&&(c.tokenGroupId=s.tokenGroupId),s.requestScene&&(c.requestScene=s.requestScene),r.set(i,c)}await li(e.agentId,r,this.paths)}catch(r){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,s]of e.sessions.entries())if(s.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(Cn(e,{code:r,message:i,data:{bridgeVersion:Lt}}))}};function pv(){return dv(16).toString("hex")}function gv(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){$.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){$.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var mv=["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."],Hx="Warning: ";function wv(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let s=i.text.startsWith(Hx)?i.text.slice(Hx.length):i.text;return mv.some(c=>s.startsWith(c))}xn();ie();Ce();import{randomBytes as _v}from"node:crypto";import{createServer as yv}from"node:http";var bv=1e6,qx=j("ipc"),zo=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Z()}async start(){this.token=_v(32).toString("hex");let e=yv((i,s)=>{this.dispatch(i,s)});this.server=e,await new Promise((i,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>i())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),qx.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(s=>s?i(s):r())}),this.server=null)}async persistAuthFiles(){await un(this.paths.portFile,String(this.port)),await un(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Qi(r,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(s);if(!c){Qi(r,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await Ev(e)}catch(u){Qi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);Qi(r,200,u??{ok:!0})}catch(u){qx.error("IPC handler failed",{key:s,err:String(u)}),Qi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Qi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function Ev(t){let e=[],r=0;for await(let s of t){let c=s;if(r+=c.length,r>bv)throw new Error("body too large");e.push(c)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var qS=Gt(Bh(),1),GS=Gt(Vo(),1),jS=Gt($r(),1),WS=Gt(zd(),1),KS=Gt(qd(),1),$S=Gt(Vd(),1),Kh=Gt(Xo(),1),VS=Gt(Wh(),1);var $h=Kh.default;Ve();ie();var{FWS:l1}=ip(),De=j("upstream.frontier"),op="application/json",ap="none",u1=15e3;function f1(t){class e extends $h{constructor(i){super(i,n0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>De.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,s){this.guardTeardown(),super.close(i,s)}terminate(){this.guardTeardown(),super.terminate()}send(i,...s){if(Fl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let l=Buffer.from(c.slice(0,128)).toString("hex");De.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){De.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...s)}}return e}var cs=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){De.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:r0,...kn(this.opts.ppeOverride)},r=f1(e),i=s0(this.opts.urlOverride),s={url:i,ws:r,fpID:t0,aID:mo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:op,force:!0},payloadEncoding:{encoding:ap,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new l1(s),l=!1,u=null,x,h,m=new Promise((y,E)=>{x=y,h=E}),w=y=>{l||(l=!0,u&&(clearTimeout(u),u=null),y?h(y):x())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;De.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&w();for(let E of this.connectHandlers)Promise.resolve(E({initial:y})).catch(I=>De.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,De.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{De.warn("frontier error",{code:y.code,msg:y.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let S=this.opts.openTimeoutMs??u1;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await m}catch(y){try{c.close(1e3,"open failed")}catch(E){De.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){De.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw De.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(De.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let s=JSON.stringify(e),c=e;cp(c)||De.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:s.length});try{await r.send(s,{service:33555712,method:1,payloadType:op,payloadEncoding:ap})}catch(u){throw De.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let s=r(i.cozeAgentId);s&&(i.cozePatToken=s)}handleMessage(e){let r=e.message?.service;if(r!==33555712){De.debug("drop non-adapter frontier frame",{service:r});return}let i=p1(e);if(!i){De.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){De.debug("frame received but no onFrame handler",{size:i.length});return}let s;try{s=JSON.parse(i)}catch(l){De.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=s;cp(c)||De.info("frontier frame in",{logid:h1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:x1(i)}),Promise.resolve(this.handler(s)).catch(l=>De.warn("frontier frame handler threw",{err:String(l)}))}};function cp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var dp=2e3;function x1(t){return t.length<=dp?t:`${t.slice(0,dp)}...<truncated, total ${t.length} chars>`}function h1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function p1(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}Ve();ie();var Xd=j("skill-publish"),g1="/api/marketplace/product/skill/publish_with_assets",m1=15e4;async function lp(t,e={}){let i=`${Or(Lr(e.handshakeBase))}${g1}`,s=e.timeoutMs??m1,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let l={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,x=setTimeout(()=>u.abort(),s);Xd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...l,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let h=await fetch(i,{method:"POST",headers:l,body:c,signal:u.signal}),m=h.headers.get("x-tt-logid")??"";if(!h.ok){let y=await h.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${h.status} logid=${m}: ${y.slice(0,200)}`)}let w=await h.json();if(Xd.info("skill publish response",{logid:m,httpStatus:h.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${m}`);let S={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(S.skillId=String(w.data.skill_id)),w.data?.version&&(S.version=w.data.version),Xd.info("skill publish ok",{logid:m,skillId:S.skillId??"",version:S.version??""}),S}catch(h){throw h instanceof k?h:h.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${s}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(h),{cause:h})}finally{clearTimeout(x)}}ie();var Qd=j("upstream.switchable"),aa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Qd.info("swap upstream",{reason:r});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let s of this.connectHandlers)e.onConnect(s);try{await e.start()}catch(s){throw Qd.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(r??"swapped").catch(s=>Qd.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ie();var el=j("upstream"),Qr=class{handler=null;async start(){el.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){el.info("NoopUpstream stopped",{reason:e})}async send(e){el.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();ie();xn();ie();Ce();import{promises as w1}from"node:fs";var up=j("pat-token-store");async function ca(t=Z()){try{let r=(await w1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(up.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):r}catch(e){let r=e?.code;return r!=="ENOENT"&&up.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ds(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await un(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as da}from"node:fs";import{join as _1}from"node:path";function y1(t,e){return`#!/bin/sh
114
+ `}async function Ih(t){let e=OE(t,"HEARTBEAT.md"),n=await CE(e,"utf8");return ME(n)!==LE?!1:(await RE(e,NE),!0)}var re=K("agent-manager"),qE=["hooks.json","cozeloop.env"],jE=["hooks"];async function KE(t,e){let n=rn(Ne(t,e).root,"codex-home"),i=rn(Th(),".codex");if(n!==i){await qo(n,{recursive:!0});for(let s of jE){let a=rn(i,s),d=rn(n,s);try{await Ld(d);continue}catch{}try{await FE(a,d,{recursive:!0,errorOnExist:!0,filter:u=>{let h=GE(u);return!h.endsWith(".log")&&!h.includes(".bak")}}),re.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}for(let s of qE){let a=rn(i,s),d=rn(n,s);try{await Ld(d);continue}catch{}try{if(s==="cozeloop.env"){let h=(await zE(a,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
115
+ `);await HE(d,h,{mode:384})}else await BE(a,d);re.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}}}var Nd="acceptEdits",Ph="full-access",Dh="read-only";function WE(t){return{INITIAL_AGENT_MODE:Mo(t)}}var $E=(t,e,n,i,s,a,d,u,h,x,g,w)=>{switch(t){case"claude-code":{let v={...s?{..._0(s),...E0(s,d,u,w)}:{},...h??{},IS_SANDBOX:"1"};return new No({cwd:n,env:v,agentId:i})}case"codex":{let v=Ph;x!==void 0&&(Ut("codex",x)?v=x:re.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...s?{...b0(s),...y0(s,d,u,w)}:{},...WE(v),...s?{NO_BROWSER:"1"}:{},...h??{},...s?{COZELAB_ONBOARD_CLOUD:"true"}:{}},E=!!s;return new Bo({cwd:n,agentId:i,...Object.keys(_).length>0?{env:_}:{},...E?{authMethodId:"api-key",isolateCodexHome:!0,...g?{codexHomeDir:g}:{}}:{}})}case"openclaw":return new $r({command:e,cwd:n,agentId:i,...a?{sessionName:Rd(a)}:{}});case"hermes":return new Fo({command:e,cwd:n,agentId:i,...h&&Object.keys(h).length>0?{env:{...h}}:{},...s?.model?{modelId:s.model}:{}})}};function Od(t){return t==="claude-code"||t==="codex"}var VE={path:"",version:"cloud-deployed"},Ah="openclaw_gateway_unavailable",ZE="openclaw_default_agent_missing";function kh(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var JE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},YE=6e4,jo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Map;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??$E,this.createTimeoutMs=e.createTimeoutMs??YE,this.detectorFactory=e.detectorFactory??(()=>new nr),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Go({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??rn(Th(),".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=rn(e,".env");if(await Ld(n).then(a=>a.isFile()).catch(()=>!1)){re.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let s=Wi({...process.env,...Qn(this.paths.agentEnvFile)});await xt(n,s,{mode:384}),re.info("openclaw .env bootstrapped",{envFile:n,bytes:s.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 ke(e.agentId,this.paths).catch(()=>null),s=Eo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")re.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>re.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(s&&a.deployType!=="cloud")re.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>re.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){re.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await ke(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await je(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){re.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await ke(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await je(T,this.paths))}return re.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!s&&!this.config.frameworksCache?.[e.framework]){let O=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${O}`)}let u=Ne(e.agentId,this.paths),h=s?"cloud":"local",x=e.framework==="openclaw"&&h==="local",g;x&&!n?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??w??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{s&&Od(e.framework)&&await wr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await qo(u.root,{recursive:!0}),await qo(v,{recursive:!0}),await qo(u.logs,{recursive:!0}),T(),x||await _r(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Qa(v,"cloud"):await Qa(v,"local",Nd)),T();let O=i,b=m0({model:e.model??O?.model}),L=r0(e._meta)??O?.accountId,N=e.patToken??O?.patToken,H=h==="cloud"?e.modelInfo??O?.modelInfo:void 0;if(I=new zo({agentId:e.agentId,framework:e.framework,workspace:v,model:b.model??Pt,deployType:h,...L?{accountId:L}:{},...N?{patToken:N}:{},...H?{modelInfo:H}:{}}),I.status="ok",O?.sessions){let Z=e.framework==="hermes"||h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,se]of Object.entries(O.sessions)){let de={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};Z?se.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:Q,framework:e.framework,fallback:de.permissionMode})):Ut(e.framework,se.permissionMode)?de.permissionMode=se.permissionMode:re.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&re.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:h}),se.cozeGroupId&&(de.cozeGroupId=se.cozeGroupId),se.tokenGroupId&&(de.tokenGroupId=se.tokenGroupId),se.requestScene&&(de.requestScene=se.requestScene),I.sessions.set(Q,de)}let ae=Object.keys(O.sessions).length;ae>0&&re.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ae})}this.registry.register(I),A=!0;let z={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:O?.createdAt??Date.now(),sessions:O?.sessions??{},model:b.model};if(h==="cloud"&&(z.deployType="cloud"),L&&(z.accountId=L),N&&(z.patToken=N),H&&(z.modelInfo=H),O?.skills&&(z.skills=O.skills),O?.agentName&&(z.agentName=O.agentName),O?.description&&(z.description=O.description),z.skillsRefreshedForVersion=O?.skillsRefreshedForVersion??zt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):re.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Ih(v)&&re.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(Z){re.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(Z)})}}let Y=e.initialSkills??[];if(Y.length>0){let Z=[...z.skills??[]],ae=new Map(Z.map((de,C)=>[de.skillId,C])),Q=await Promise.allSettled(Y.map(de=>Do({agentId:e.agentId,workspace:v,framework:e.framework,skill:de,paths:this.paths}))),se=0;for(let[de,C]of Q.entries()){let q=Y[de];q&&(C.status==="fulfilled"?(Co(Z,ae,C.value),se++):re.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:q.skillId,skillName:q.skillName,err:String(C.reason)}))}se>0&&(z.skills=Z,re.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:Y.length}))}return await je(z,this.paths),re.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(T){throw re.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),re.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await UE(u.root,{recursive:!0,force:!0}).catch(O=>re.warn("rm agent dir failed (ignored)",{err:String(O)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,n,i,s,a,d){let h=this.config.frameworksCache?.[e.framework];if(!h)if(e.deployType==="cloud"&&Od(e.framework))h=VE;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`);Od(e.framework)&&!Ts(e.framework)&&(re.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await wr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,g;if(e.framework==="openclaw")g=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:s,mockScenario:a,requestScene:d,command:h.path});else if(e.framework==="hermes"){let w={...this.buildBinShimPathEnv()};x&&(await T0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:s,mockScenario:a}),w.HERMES_HOME=tr(e.agentId,this.paths)),g=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,s,a,w)}else{let w=e.sessions.get(i),v=nn(e)?w?.permissionMode??Ph:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await KE(e.agentId,this.paths),g=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,s,a,this.buildBinShimPathEnv(),v,e.framework==="codex"&&e.deployType==="cloud"?rn(Ne(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await g.start(),await g.initialize(JE),g}catch(w){let v=g instanceof wt?g.getStderrTail():[];throw v.length>0&&re.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof k?w.code:"unknown",recentStderr:v}),await g.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,h.path,w)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let s=await this.detectorFactory().probeOpenclawGateway(n);if(!s.reachable)return new k("AGENT_ENV_NOT_READY",kh(s),{cause:{reason:Ah}})}catch(s){re.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(s)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};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:ZE}})}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",kh(n),{cause:{reason:Ah}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:s,cozeEnv:a,mockScenario:d,requestScene:u,command:h}=e,x=Rd(s);if(n.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new $r({command:h,cwd:v.workspace,agentId:v.id,sessionName:x})}let g=await Sh();try{let v=this.getOpenclawConfig();await v.ensureAcpDeviceScopes()&&await v.restartGateway()}catch(v){re.warn("acp device scope ensure failed (ignored)",{err:String(v)})}let w;if(i?.modelToken){let v=hd(s),_=xd(i),E=`${v}/${_}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(E)!==I){let A=this.getOpenclawConfig(),T=await A.getAllowlistModelsForProvider(v),O=v0(i,a,d,T,u);O&&(await A.ensureProvider(v,O),await A.addModelToAllowlist(E),this.ensuredProviders.set(E,I))}w=E}return new $r({command:h,cwd:n.workspace,agentId:n.agentId,sessionName:x,...g?{gatewayToken:g}:{},...w?{slashModelOnStart:w}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,s=n??e.model;for(let a of e.sessions.keys()){let d=hd(a),u=`${d}/${s}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,re.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,re.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as Nh}from"node:crypto";import{promises as iv}from"node:fs";import{basename as Mh}from"node:path";Ye();ne();import{promises as XE}from"node:fs";import{basename as QE}from"node:path";var Ch=K("file-upload"),ev="/api/coze_claw/file/agent_upload",tv=6e4;async function Rh(t,e={}){let i=`${Br(Fr(e.handshakeBase))}${ev}`,s=e.timeoutMs??tv,a=await XE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Pn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),s);Ch.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),w=g.headers.get("x-tt-logid")??"";if(!g.ok){let E=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${w}: ${E.slice(0,200)}`)}let v=await g.json();if(v.code!==void 0&&v.code!==0)throw new k("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${w}`);let _=v.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(v).slice(0,200)}`);return Ch.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${s}ms) for ${QE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}Ye();ne();import{extname as nv}from"node:path";var rv={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function Oh(t){let e=nv(t).toLowerCase();return rv[e]??"application/octet-stream"}Ce();var Ko=K("agent-send"),Lh=50*1024*1024;function Bh(t,e,n){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let s=i.sessions.get(n);if(!s)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:s}}async function Fh(t,e,n,i,s,a){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,n,i,s);return}catch(x){u=x,h<2&&(Ko.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function zh(t,e){let{session:n,runtime:i}=Bh(e.core,t.agentId,t.sessionId);if(!await pi(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let s=await iv.stat(t.path).catch(()=>null);if(!s||!s.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(s.size>Lh)throw new k("FILE_TOO_LARGE",`${s.size} bytes > limit ${Lh}`);let a=await Oh(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??Mh(t.path),u;try{u=await Rh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:d,sizeBytes:s.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Ko.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.size,mime:a,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:Nh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:d,sizeBytes:s.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Fh(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Ko.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:s.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:s.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Uh(t,e){let{session:n,runtime:i}=Bh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let s=t.name??Mh(t.path),a={sessionUpdate:"group_file",messageId:Nh(),content:{uri:t.path,name:s,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Fh(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Ko.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:s,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function Hh(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),s=Math.max(n.length,i.length);for(let a=0;a<s;a++){let d=n[a]??0,u=i[a]??0;if(d<u)return!0;if(d>u)return!1}return!1}tn();ne();xn();var Ht=K("coze-cli-installer"),Gh="@coze/cli@latest",sv="coze",qh="0.1.8",ov=5e3,av=5e3,cv=9e4,jh=1e4,rs=null,Wo=!1;async function Bd(t,e={}){if(Wo)return;if(rs)return rs;let n=e.exec??d0;return rs=(async()=>{try{let i=await dv(sv,n),s=!1;if(i){let d=await lv(n);if(d===void 0)Ht.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Hh(d,qh))Ht.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:qh}),s=!0;else{Ht.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Wo=!0;return}}let a=s?"upgrade-only":"full";Ht.info("coze-cli install start",{package:Gh,mode:a});try{await n("npm",["i","-g","--prefer-online",Gh],{timeout:cv,maxBuffer:10*1024*1024}),Ht.info("coze-cli install ok")}catch(d){Ht.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(s){Wo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:jh}),Ht.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Ht.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:jh}),Ht.info("coze auth login ok")}catch(d){Ht.warn("coze auth login failed",{err:String(d)});return}Wo=!0}finally{rs=null}})(),rs}async function dv(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:ov});return Ya(i)}catch{return}}async function lv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:av});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Vt();$t();Ce();var uv=10*6e4;function Kh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?uv:e}function $o(t){return pn(t??J().configFile)}function is(t,e){return gn(e??J().configFile,t)}import{randomBytes as Cv}from"node:crypto";xr();Ye();ne();import{createReadStream as fv}from"node:fs";import{mkdir as hv,readFile as xv,realpath as pv,stat as gv,writeFile as mv}from"node:fs/promises";import{basename as wv,dirname as Fd,isAbsolute as _v,join as yv,relative as bv,resolve as Wh,sep as Ev}from"node:path";import{createInterface as vv}from"node:readline";var Vh=K("fs-rpc"),ss=Qe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Zh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>ss)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${ss} bytes`);let i=await Yh(t.path,e);return await hv(Fd(i),{recursive:!0}),await mv(i,t.content,"utf8"),Vh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Jh(t,e){let n=await Yh(t.path,e),i=await gv(n),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>ss&&!s)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${ss} bytes`);let a;if(s&&i.size>ss)a=await Sv(n,t.line??1,t.limit);else{let d=await xv(n,"utf8");if(s){let u=d.split(`
116
+ `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;a=u.slice(h,x).join(`
117
+ `)}else a=d}return Vh.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function Sv(t,e,n){let i=vv({input:fv(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),s=Math.max(0,e-1),a=typeof n=="number"?s+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=s&&u<a&&d.push(h),u++,u>=a)break}finally{i.close()}return d.join(`
118
+ `)}async function Yh(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([$h(Wh(e)),$h(Wh(t))]),s=bv(n,i);if(Iv(s,Ev,_v(s)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Iv(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function $h(t){let e=[],n=t;for(;n!==Fd(n);)try{let i=await pv(n);return e.length?yv(i,...e.reverse()):i}catch{e.push(wv(n)),n=Fd(n)}return t}ne();var Xh=K("prompt-multimodal"),Qh=10*1024*1024,Av=15e3,kv=6;async function ex(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let a=n++,d=t[a];d!==void 0&&(e[a]=await Tv(d))}}let s=Array.from({length:Math.min(kv,t.length)},()=>i());return await Promise.all(s),e}function tx(t){return t.some(e=>e.type==="image")}async function Tv(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ki(e.uri))return t;try{let{buf:n,contentType:i}=await Dv(e.uri),s=e.mimeType||Pv(i)||"application/octet-stream";return Xh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:s}),{type:"image",data:n.toString("base64"),mimeType:s}}catch(n){return Xh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Pv(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function Dv(t){let e=new AbortController,n=setTimeout(()=>e.abort(),Av);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let s=await i.arrayBuffer();if(s.byteLength>Qh)throw new Error(`image too large: ${s.byteLength} bytes (max ${Qh})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Vt();Ye();ne();var V=K("core"),Rv=3e4,Ov=/^(boe|ppe)_[A-Za-z0-9_-]+$/,Lv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",Nv="\u5BA1\u6279\u5DF2\u8D85\u65F6",Mv=3e4,Vo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new qr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Kh(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),V.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){V.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),V.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){V.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)&&V.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let s=i.downstream;s&&(s.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),s.onAgentRequest(a=>{this.handleAgentRequest(e,s,a)}),s.onExit((a,d)=>{V.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),Vr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(s,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[s,a]of this.pendingUpstream)a.downstream===e&&i.push(s);if(i.length!==0){V.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let s of i){let a=this.pendingUpstream.get(s);if(a){this.pendingUpstream.delete(s),this.upstream.send(Cn(s,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>V.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){V.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:X.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Oo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&Ov.test(i)?this.currentCozeEnv=i:i&&V.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let s=e.params,a=i0(s?._meta),d=s?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),V.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),V.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,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):V.warn("drop notification: extension not registered",{method:e.method});return}let h=await u(e,this);n!==null&&await this.upstream.send(Gr(n,h));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Gr(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Gr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):V.warn("drop unknown notification",{method:e.method})}catch(u){V.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Cn(n,es(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 s=this.agents.get(i);if(!s)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let 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(s,e.method,n);if(e.method==="session/prompt"){let h=s.sessions.get(a);if(h?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,g=vo(n._meta);return V.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:a}),this.synthesizePromptReply(s,h,a,Lv,x,g)}}let d=Date.now(),u=!1;try{let h=await s.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(s,e.method,n));return u=!0,h}finally{V.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:s}=o0(i);switch(n){case"session/new":{let a=Bv();return V.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=s;return V.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=s,d=a.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=nn(e)?s0(i._meta):void 0;if(u!==void 0&&!Ut(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Td(e.framework)}`);let h=vo(i._meta),x=this.requestSceneBySession.get(d),g=await this.ensureRuntime(e,d,h,x);if(u!==void 0&&g.permissionMode===void 0&&(g.permissionMode=u,await this.persistSessionMapping(e)),g.replySeq=0,await this.ensureDownstream(e,d,g),!g.downstream||!g.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&g.permissionMode!==void 0&&g.permissionMode!==u){let _=g.permissionMode;g.permissionMode=u,await this.persistSessionMapping(e);try{await g.downstream.setSessionMode({sessionId:g.acpSessionId,modeId:u})}catch(E){throw g.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),E}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(g.acpSessionId,w):e.activeTriggers.delete(g.acpSessionId),h?e.activeGroupIds.set(g.acpSessionId,h):e.activeGroupIds.delete(g.acpSessionId),h&&g.cozeGroupId!==h&&(g.cozeGroupId=h,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&tx(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let v=await ex(a.prompt);try{let _=await g.downstream.sessionPrompt({...a,sessionId:g.acpSessionId,prompt:v});return g.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof k&&_.code==="AGENT_APPROVAL_TIMEOUT"){let E=g.pendingPermission;E&&(E.downstream.respondAgentRequest(E.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(E.upstreamId),g.pendingPermission=void 0);let I=g.acpSessionId,A=I?e.activeTriggers.get(I):void 0,T=I?e.activeGroupIds.get(I):void 0;return V.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,g,d,Nv,A,T)}throw _}finally{if(e.activeTriggers.delete(g.acpSessionId),e.activeGroupIds.delete(g.acpSessionId),g.pendingPermission=void 0,g.reloadAfterTurn){g.reloadAfterTurn=!1;let _=g.downstream;_&&(g.downstream=void 0,V.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:g.acpSessionId}),_.stop("reload-after-turn").catch(E=>V.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(E)})))}else g.downstream?.isAlive()&&this.armIdleTimer(e,d,g)}}case"session/cancel":{let d=s.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(V.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=s,d=a.sessionId,u=a.modeId,h=vo(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!nn(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(!Ut(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Td(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let g=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),w}else V.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let s=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&s.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(s.length===0)return V.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};V.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:s.length});for(let d of s)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of s){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&a.push({downstream:u,acpSessionId:h,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let h of s)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,s){let a=e.sessions.get(n);if(a){let h=a.cozeGroupId!==i,x=e.deployType==="cloud"&&a.tokenGroupId!==i,g=a.requestScene!==s;if(x&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),x||g){Vr(a);let w=a.downstream;a.downstream=void 0,w&&await w.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=s,(h||x||g)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...s?{requestScene:s}:{}};return nn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?I0:A0:u.permissionMode=e.framework==="claude-code"?Nd:Dh),e.sessions.set(n,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,n,i){let s={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(mt.GEN_MODEL_TOKEN,s,Mv);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(Vr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=s&&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 h;try{let x=this.requestSceneBySession.get(n);x&&V.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),h=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=s&&i.acpSessionId&&(V.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=h,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),V.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){V.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let g=await h.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw V.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),nn(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){V.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(Vr(i),this.isRuntimeBusy(e,i)){V.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)){V.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}V.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let s=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),s&&s.stop("idle timeout").catch(a=>V.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 s of this.pendingUpstream.values())if(s.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,s){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(Hr("session/update",{sessionId:i,update:s,_meta:a}))}async synthesizePromptReply(e,n,i,s,a,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(u.cozeTriggerMsgId=a),d&&(u.cozeGroupId=d),await this.upstream.send(Hr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(h=>V.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,s=this.reverseSessionId(e,i);if(!s){V.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(s);if(!a){V.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(Uv(n)){V.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"&&nn(e)){let g=d.currentModeId;Ut(e.framework,g)&&a.permissionMode!==g?(a.permissionMode=g,this.persistSessionMapping(e).catch(w=>V.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof g=="string"&&!Ut(e.framework,g)&&V.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Hr("session/update",{...n,sessionId:s,_meta:u})).catch(g=>V.warn("forward update failed",{agentId:e.agentId,err:String(g)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}V.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let s=e.workspace;if(i.method==="fs/write_text_file"){let a=i.params??{},d=await Zh(a,s);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Jh(a,s);n.respondAgentRequest(i.id,d)}}catch(s){V.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),n.respondAgentRequestError(i.id,es(s))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let s=this.upstreamIds.next("session/request_permission"),a=i.params??{},u=a.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let w=u?this.reverseSessionId(e,u):void 0,v=w?e.sessions.get(w):void 0;v&&(v.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:s});let _={...a,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(s,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),V.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:u,cloudSessionId:w,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(Xi(s,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(s),V.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),n.respondAgentRequestError(i.id,{code:X.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 s=n.value;this.clearPendingPermissionFor(s),e.error?(V.info("upstream \u2192 permission response (error)",{agentId:s.agentId,upstreamId:e.id,method:s.method,error:e.error}),s.downstream.respondAgentRequestError(s.agentRequestId,e.error)):(s.method==="session/request_permission"&&Fv(e.result,s),V.info("upstream \u2192 permission response (result)",{agentId:s.agentId,upstreamId:e.id,method:s.method,result:e.result}),s.downstream.respondAgentRequest(s.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Ro(e.error)):i.value.resolve(e.result);return}V.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let s=e.get(n);if(s)return{value:s,key:n};if(typeof n=="number"){let a=String(n),d=e.get(a);if(d)return V.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=Rv){let s=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(Xi(s,e,n)).catch(h=>{let x=this.pendingBridge.get(s);x&&(clearTimeout(x.timer),this.pendingBridge.delete(s)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,s]of e.sessions){let a={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(a.acpSessionId=s.acpSessionId),s.permissionMode&&nn(e)&&(a.permissionMode=s.permissionMode),s.cozeGroupId&&(a.cozeGroupId=s.cozeGroupId),s.tokenGroupId&&(a.tokenGroupId=s.tokenGroupId),s.requestScene&&(a.requestScene=s.requestScene),n.set(i,a)}await gi(e.agentId,n,this.paths)}catch(n){V.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,s]of e.sessions.entries())if(s.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Cn(e,{code:n,message:i,data:{bridgeVersion:zt}}))}};function Bv(){return Cv(16).toString("hex")}function Fv(t,e){if(!t||typeof t!="object"){V.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){V.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"){V.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")&&V.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var zv=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."],nx="Warning: ";function Uv(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let s=i.text.startsWith(nx)?i.text.slice(nx.length):i.text;return zv.some(a=>s.startsWith(a))}$t();ne();Ce();import{randomBytes as Hv}from"node:crypto";import{createServer as Gv}from"node:http";var qv=1e6,rx=K("ipc"),Zo=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=Hv(32).toString("hex");let e=Gv((i,s)=>{this.dispatch(i,s)});this.server=e,await new Promise((i,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),rx.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(s=>s?i(s):n())}),this.server=null)}async persistAuthFiles(){await xt(this.paths.portFile,String(this.port)),await xt(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){os(n,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(s);if(!a){os(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await jv(e)}catch(u){os(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);os(n,200,u??{ok:!0})}catch(u){rx.error("IPC handler failed",{key:s,err:String(u)}),os(n,500,{error:u instanceof Error?u.message:String(u)})}}};function os(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function jv(t){let e=[],n=0;for await(let s of t){let a=s;if(n+=a.length,n>qv)throw new Error("body too large");e.push(a)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var l1=Wt(Qx(),1),u1=Wt(ia(),1),f1=Wt(Xr(),1),h1=Wt(Zd(),1),x1=Wt(Xd(),1),p1=Wt(il(),1),cp=Wt(ca(),1),g1=Wt(ap(),1);var dp=cp.default;Ye();ne();var{FWS:R1}=yp(),Be=K("upstream.frontier"),Ep="application/json",vp="none",O1=15e3;function L1(t){class e extends dp{constructor(i){super(i,u0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Be.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,s){this.guardTeardown(),super.close(i,s)}terminate(){this.guardTeardown(),super.terminate()}send(i,...s){if($l("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let d=Buffer.from(a.slice(0,128)).toString("hex");Be.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Be.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...s)}}return e}var ps=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Be.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:f0,...Pn(this.opts.ppeOverride)},n=L1(e),i=x0(this.opts.urlOverride),s={url:i,ws:n,fpID:l0,aID:Io,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Ep,force:!0},payloadEncoding:{encoding:vp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new R1(s),d=!1,u=null,h,x,g=new Promise((_,E)=>{h=_,x=E}),w=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Be.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&w();for(let E of this.connectHandlers)Promise.resolve(E({initial:_})).catch(I=>Be.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=_=>{this.opened=!1,Be.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Be.warn("frontier error",{code:_.code,msg:_.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let v=this.opts.openTimeoutMs??O1;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await a.connect();try{await g}catch(_){try{a.close(1e3,"open failed")}catch(E){Be.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Be.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Be.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Be.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let s=JSON.stringify(e),a=e;Sp(a)||Be.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:s.length});try{await n.send(s,{service:33555712,method:1,payloadType:Ep,payloadEncoding:vp})}catch(u){throw Be.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let s=n(i.cozeAgentId);s&&(i.cozePatToken=s)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Be.debug("drop non-adapter frontier frame",{service:n});return}let i=B1(e);if(!i){Be.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Be.debug("frame received but no onFrame handler",{size:i.length});return}let s;try{s=JSON.parse(i)}catch(d){Be.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=s;Sp(a)||Be.info("frontier frame in",{logid:M1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:N1(i)}),Promise.resolve(this.handler(s)).catch(d=>Be.warn("frontier frame handler threw",{err:String(d)}))}};function Sp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Ip=2e3;function N1(t){return t.length<=Ip?t:`${t.slice(0,Ip)}...<truncated, total ${t.length} chars>`}function M1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function B1(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Ye();ne();var cl=K("skill-publish"),F1="/api/marketplace/product/skill/publish_with_assets",z1=15e4;async function Ap(t,e={}){let i=`${Br(Fr(e.handshakeBase))}${F1}`,s=e.timeoutMs??z1,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Pn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),s);cl.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${_.slice(0,200)}`)}let w=await x.json();if(cl.info("skill publish response",{logid:g,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${g}`);let v={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(v.skillId=String(w.data.skill_id)),w.data?.version&&(v.version=w.data.version),cl.info("skill publish ok",{logid:g,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${s}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ne();var dl=K("upstream.switchable"),ma=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;dl.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let s of this.connectHandlers)e.onConnect(s);try{await e.start()}catch(s){throw dl.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(n??"swapped").catch(s=>dl.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var ll=K("upstream"),ii=class{handler=null;async start(){ll.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){ll.info("NoopUpstream stopped",{reason:e})}async send(e){ll.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)}};Ye();ne();$t();ne();Ce();import{promises as U1}from"node:fs";var kp=K("pat-token-store");async function wa(t=J()){try{let n=(await U1.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(kp.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"&&kp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function gs(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await xt(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as _a}from"node:fs";import{join as H1}from"node:path";function G1(t,e){return`#!/bin/sh
114
119
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
115
- `}function b1(t,e){return`@echo off\r
120
+ `}function q1(t,e){return`@echo off\r
116
121
  "${e}" "${t}" %*\r
117
- `}async function fp(t,e=Z()){let r=e.binDir;await da.mkdir(r,{recursive:!0});let i=_1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,c=process.platform==="win32"?b1(t,s):y1(t,s);return await da.readFile(i,"utf8").catch(()=>null)===c||(await da.writeFile(i,c,"utf8"),process.platform!=="win32"&&await da.chmod(i,493)),r}ie();Ce();import{execSync as xp}from"node:child_process";import{readFileSync as hp,unlinkSync as E1}from"node:fs";import{mkdir as v1,open as S1,readFile as pp,unlink as tl,writeFile as I1}from"node:fs/promises";import{dirname as A1}from"node:path";var k1=j("single-instance"),T1=t=>new Promise(e=>setTimeout(e,t)),la=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Z().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Vi(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&k1.warn("removing stale pid file",{stalePid:i}),await I1(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return r.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),r}async release(){if(this.acquired){try{(await pp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await tl(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let r=await pp(e,"utf8"),i=Number.parseInt(r.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(r){if(r.code==="ENOENT")return null;throw r}}async withClaimLock(e){let r=`${this.pidFile}.lock`;await v1(A1(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await S1(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(r);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await T1(this.claimLockIntervalMs);continue}await tl(r).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await tl(r).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${r} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=hp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(zr)||r.includes("lib/index.js"))}catch{}try{let r=xp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(zr)||r.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 s=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return s.includes("node")||s.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{hp(this.pidFile,"utf8").trim()===String(this.selfPid)&&E1(this.pidFile)}catch{}})}};ua();ie();var ir=j("daemon.upstream-watchdog"),M1=12e4,B1=9e5,F1=3e4;function rl(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var fa=class{constructor(e){this.opts=e;this.softMs=e.softMs??rl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",M1),this.hardMs=e.hardMs??rl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",B1),this.intervalMs=e.intervalMs??rl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",F1),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?.(),ir.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&&ir.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&&ir.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,ir.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){ir.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:r,hardMs:this.hardMs}),this.opts.onFatal(r);return}r>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,ir.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>ir.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var W=j("daemon");async function wp(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ml({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>ze(P,t).logs,listAgentIds:()=>Es(t)});try{let{writeFileSync:P}=await import("node:fs");P(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
122
+ `}async function Tp(t,e=J()){let n=e.binDir;await _a.mkdir(n,{recursive:!0});let i=H1(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,a=process.platform==="win32"?q1(t,s):G1(t,s);return await _a.readFile(i,"utf8").catch(()=>null)===a||(await _a.writeFile(i,a,"utf8"),process.platform!=="win32"&&await _a.chmod(i,493)),n}ne();Ce();import{execSync as Pp}from"node:child_process";import{readFileSync as Dp,unlinkSync as j1}from"node:fs";import{mkdir as K1,open as W1,readFile as Cp,unlink as ul,writeFile as $1}from"node:fs/promises";import{dirname as V1}from"node:path";var Z1=K("single-instance"),J1=t=>new Promise(e=>setTimeout(e,t)),ya=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??J().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>ts(n),isDaemon:n=>this.matchesDaemonTitle(n)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let n=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&Z1.warn("removing stale pid file",{stalePid:i}),await $1(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return n.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),n}async release(){if(this.acquired){try{(await Cp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await ul(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await Cp(e,"utf8"),i=Number.parseInt(n.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(n){if(n.code==="ENOENT")return null;throw n}}async withClaimLock(e){let n=`${this.pidFile}.lock`;await K1(V1(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await W1(n,"wx")}catch(a){if(a.code!=="EEXIST")throw a;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await J1(this.claimLockIntervalMs);continue}await ul(n).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await ul(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=Dp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(jr)||n.includes("lib/index.js"))}catch{}try{let n=Pp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(jr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Pp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let s=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return s.includes("node")||s.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Dp(this.pidFile,"utf8").trim()===String(this.selfPid)&&j1(this.pidFile)}catch{}})}};ba();ne();var dr=K("daemon.upstream-watchdog"),iI=12e4,sI=9e5,oI=3e4;function hl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var Ea=class{constructor(e){this.opts=e;this.softMs=e.softMs??hl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",iI),this.hardMs=e.hardMs??hl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",sI),this.intervalMs=e.intervalMs??hl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",oI),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),dr.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&&dr.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&&dr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,dr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){dr.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,dr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>dr.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 $=K("daemon");async function Lp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Kl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>Ne(C,t).logs,listAgentIds:()=>Ps(t)});try{let{writeFileSync:C}=await import("node:fs");C(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
118
123
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
119
124
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
120
- `)}catch{}}let e=new la({processTitle:zr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Bo(),s=i??{};ws({pid:process.pid}),W.info(i?"loaded bridge config":"initialized bridge config");let c=new aa(new Qr),l=null,u=new Fo({upstream:c,paths:t,bridgeConfig:s,sessionSpawner:async(P,q,K,ne,Ze,ue)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(P,q,K,ne,Ze,ue)}}),x=new Lo({paths:t,config:s,registry:u});l=x;let h,m,w=null,S={},y,E=null,I=null,A=null,T=new Rn;function C(P,q){return T.enqueue(()=>R(P,q))}function b(){I||(I=new fa({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>A?C(A,{force:!0}):void 0,onFatal:P=>{if(process.env[ls]==="1"){W.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}W.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function R(P,q){let K=P,ne=K?.privatecode;if(!ne)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Ze=Hi(K.env),ue=K.handshake_url,ge=K.frontier_url,At=mp(K.env,ue,ge);if(A=K,!q?.force&&h===ne&&m===At){let _e=await z1(t);return u.agents.size===0&&_e?(W.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ha(t,x).catch(ke=>W.warn("connect-noop auto-revive error (ignored)",{err:String(ke)}))):W.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let mt=!!h&&h!==ne,sn=m!==void 0&&m!==At,qt=mt||sn,on=await Qc({privatecode:ne,...ue?{endpoint:ue}:{},ppeOverride:Ze});if(qt){W.warn("connect config switched, resetting agents",{pcChanged:mt,envChanged:sn,previousPc:h?xa(h):"",nextPc:xa(ne)});for(let _e of[...u.agents.values()])await _e.dispose("connect config switch").catch(()=>{}),u.agents.delete(_e.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Qr,"connect switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),kd({patToken:ne,env:K.env}).catch(_e=>W.warn("coze-cli setup error (ignored)",{err:String(_e)}));let ii=new cs({handshake:on,privatecode:ne,...ge?{urlOverride:ge}:{},ppeOverride:Ze,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(ii,"connect"),h=ne,m=At,S=Ze,y=ue,K.mock_scenario!==void 0&&(u.setMockScenario(K.mock_scenario),W.info("mock scenario set",{scenario:K.mock_scenario})),E||(E=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(_e=>W.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:J})),E.start(),b(),qt&&ha(t,x).catch(_e=>W.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),ds(ne,t).catch(_e=>W.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),W.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>x.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let D={},F=new _o({agents:u.agents,publishSkillToMarketplace:async P=>{let q=u.agents.get(P.agentId)?.patToken??h;if(!q)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return lp({patToken:q,zip:P.zip,...P.skillId?{skillId:P.skillId}:{},skillName:P.skillName,...P.description?{description:P.description}:{},agentId:P.agentId,...P.accountId?{accountId:P.accountId}:{}},{handshakeBase:y,ppeOverride:S})},disposeAndMarkDisconnected:async(P,q)=>{let K=u.agents.get(P);if(K){await x.cleanupOpenclawSessionProviders(K).catch(Ze=>W.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Ze)}));let ne=!0;try{await K.dispose(`disconnect: ${q}`)}catch(Ze){ne=!1,W.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Ze)}),K.status="error"}ne&&(K.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,q)=>{let K=u.agents.get(P);K&&(await x.cleanupOpenclawSessionProviders(K).catch(ne=>W.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(ne)})),await K.dispose(`delete: ${q}`).catch(ne=>W.warn("dispose during delete failed (ignored)",{agentId:P,err:String(ne)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!D.ref)throw new Error("agent-detail-sync not initialized yet");await D.ref.syncOne(P)},cleanupOpenclawProviders:async(P,q)=>{await x.cleanupOpenclawSessionProviders(P,q)},openclawRepair:async(P,q)=>{await x.openclawRepair(P,q)},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>F.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>F.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>F.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>F.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>F.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>F.getFileContent(P.params)),u.registerExtension("_agent/update",P=>F.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>F.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>F.switchModel(P.params)),u.registerExtension("_agent/reset",P=>F.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>F.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>F.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>F.upgradeBridge(P.params));let B=new Is({paths:t,handlers:F,agentManager:x,sendDetail:P=>u.sendRequest("_agent/detail",P)});D.ref=B;let J=async P=>{await Promise.allSettled(P.map(async q=>{try{await F.disconnectAgent({agentId:q.agentId,reason:`auth_failure: code=${q.code} ${q.message}`}),W.info("agent disconnected due to auth failure from heartbeat response",{agentId:q.agentId,code:q.code,message:q.message})}catch(K){W.warn("disconnect during authFailure handling failed (ignored)",{agentId:q.agentId,err:String(K)})}}))};c.onConnect(({initial:P})=>{W.info("frontier upstream connected, triggering detail sync",{initial:P}),B.syncAll(P?"initial-connect":"reconnect").catch(q=>W.warn("detail sync top-level error (ignored)",{err:String(q)}))});let V=new zo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let P=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ls]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:s.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let q=P,K=q?.privatecode,ne=q?.pairing_code;if(!K||!ne)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ze=Hi(q.env),ue=q.handshake_url,ge=q.frontier_url,At=mp(q.env,ue,ge),mt=!!h&&h!==K,sn=m!==void 0&&m!==At,qt=mt||sn,on=await Qc({privatecode:K,...ue?{endpoint:ue}:{},ppeOverride:Ze});if(qt){W.warn("pair config switched, resetting agents",{pcChanged:mt,envChanged:sn,previousPc:h?xa(h):"",nextPc:xa(K),previousEnvKey:m??"",nextEnvKey:At});for(let ke of[...u.agents.values()])await ke.dispose("pair config switch").catch(()=>{}),u.agents.delete(ke.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Qr,"pair switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),kd({patToken:K,env:q.env}).catch(ke=>W.warn("coze-cli setup error (ignored)",{err:String(ke)}));let ii=new cs({handshake:on,privatecode:K,...ge?{urlOverride:ge}:{},ppeOverride:Ze,getPatTokenForAgent:ke=>u.agents.get(ke)?.patToken});await c.swap(ii,"pair");try{let ke=new Yn;s.frameworksCache=await ke.detectAll(),await Yi(s),W.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(ke){W.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ke)})}let _e=Object.keys(s.frameworksCache??{});try{let ke=await u.sendRequest("_agent/pair",{pairCode:ne,patToken:K,frameworks:_e,_meta:{cozeDeviceId:w}});W.info("_agent/pair ok",{pairResult:ke}),h=K,m=At,S=Ze,y=ue,q.mock_scenario!==void 0&&(u.setMockScenario(q.mock_scenario),W.info("mock scenario set",{scenario:q.mock_scenario})),ds(K,t).catch(Le=>W.warn("writePatToken after /pair failed (ignored)",{err:String(Le)})),E||(E=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(Le=>W.warn("detailSync.retryPending failed (ignored)",{err:String(Le)})),onAuthFailures:J})),E.start(),b(),qt&&ha(t,x).catch(Le=>W.warn("post-pair-switch auto-revive error (ignored)",{err:String(Le)}));let sr;return q.agent_id&&(sr=await H1(q.agent_id,t,x,Le=>u.sendRequest("_agent/detail",Le),K).catch(Le=>(W.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(Le)}),{ok:!1,agentId:q.agent_id??"",note:String(Le)}))),{ok:!0,note:"paired with cloud",...sr?{agent:sr}:{}}}catch(ke){return W.error("_agent/pair failed",{err:String(ke)}),{ok:!1,note:`pair failed: ${String(ke)}`}}}},{method:"POST",path:"/connect",handler:P=>C(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let q=P;return{ok:!0,result:await x.createAgent(q)}}},{method:"POST",path:"/agent/send",handler:async P=>{let q=P;if(!q?.agentId||!q?.sessionId||!q?.kind||!q?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!h)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let K=q;return await(K.groupFile?Ix:Sx)(K,{core:u,patToken:h,handshakeBase:y,ppeOverride:S})}catch(K){if(K instanceof k)return{ok:!1,code:K.code,message:K.message};throw K}}},{method:"POST",path:"/reload",handler:async P=>{let q=P?.agent_id,K=await u.reloadAgents(q);return W.info("IPC /reload: recycled agent subprocesses",{agentId:q??"(all)",recycled:K}),{ok:!0,recycled:K}}},{method:"POST",path:"/shutdown",handler:async()=>(W.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:se,token:X}=await V.start();try{await fp(t.libEntry,t)}catch(P){W.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),q1({paths:t,core:u,agentManager:x,detectAll:async()=>(s.frameworksCache=await new Yn().detectAll(),await Yi(s),s.frameworksCache)}).catch(P=>W.warn("startup warmup error (ignored)",{err:String(P)})),Kl().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(dn(),jl));for(let q of["claude-code","codex"]){let K=await P(q);K&&W.info("acp wrapper version",{framework:q,version:K})}}).catch(P=>W.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let te=null,ae={port:se,token:X,core:u,ipc:V,shutdown(P){return te||(W.info("daemon shutdown",{reason:P}),te=(async()=>{E?.stop(),I?.stop(),await u.stop(P),await V.stop(),await e.release()})(),te)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{ae.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>H0()),process.on("unhandledRejection",P=>{W.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{W.error("uncaughtException (will exit, supervisor will restart)",{message:P.message,stack:P.stack,name:P.name});try{process.stderr.write(`FATAL uncaughtException: ${P.stack??P.message}
121
- `)}catch{}process.exit(1)}),W.info("daemon ready",{port:se,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),j1({cliSpawned:process.env[ls]==="1",readPatToken:()=>ca(t),connect:C}).catch(P=>W.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),ae}async function z1(t){return Es(t).length>0}function xa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function mp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function U1(t,e){let r=Es(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(hn(),Ss));for(let c of r){await s(c,t).catch(l=>W.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),W.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),W.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){W.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function H1(t,e,r,i,s){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(hn(),Ss)),l=await c(t,e);if(l){if(l.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);W.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let m=_p(l),w={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...s?{patToken:s}:{},...m?{_meta:m}:{}};return await r.createAgent(w),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}W.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let x={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...s?{patToken:s}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(x);let h=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:h?"cloud agent acknowledged":"created from cloud detail"}}async function q1(t){let e=t.logger??W;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await U1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ha(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await G1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ha(t,e){let{readdir:r}=await import("node:fs/promises"),i;try{i=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(hn(),Ss));W.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let x;try{x=await s(u,t)}catch(h){W.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(h)}),l+=1;continue}if(!x){l+=1;continue}if(x.deletedAt){W.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:x.deletedAt}),l+=1;continue}if(x.disconnectedAt){W.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:x.disconnectedAt}),l+=1;continue}try{W.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:x.framework});let h=_p(x);await e.createAgent({agentId:x.agentId,framework:x.framework,...x.cozeIdentity?{cozeIdentity:x.cozeIdentity}:{},...x.model?{model:x.model}:{},...h?{_meta:h}:{}},{revive:!0}),c+=1}catch(h){W.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:x.framework,err:String(h)}),l+=1}}return W.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function G1(t){let{readdir:e}=await import("node:fs/promises"),r;try{r=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(r.length===0)return{refreshed:0,total:0};let i=0;for(let s of r)try{(await C0(s,t)).status==="refreshed"&&(i+=1)}catch(c){W.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(c)})}return i>0&&W.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function j1(t){let e=t.logger??W;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function _p(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ua();Ce();import{readFile as yp}from"node:fs/promises";var rn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let r=await pa(this.paths);if(!r)return{kind:"not-running"};try{let i=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...r,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:K1(i)}}}async request(e){let r=await pa(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,s={Authorization:`Bearer ${e.token}`};i&&(s["content-type"]="application/json");let c=new AbortController,l=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:s,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),x=await u.text();return{status:u.status,body:W1(x)}}finally{clearTimeout(l)}}};async function pa(t){try{let[e,r]=await Promise.all([yp(t.portFile,"utf8"),yp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),s=r.trim();return!Number.isFinite(i)||i<=0||!s?null:{port:i,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}function W1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function K1(t){return t instanceof Error?t.message:String(t)}Zt();ie();lr();import{spawn as $1}from"node:child_process";import{userInfo as Ep}from"node:os";var il="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",V1=new Set(["bash","zsh","sh","dash","ksh"]),bp=Ye("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),J1=2e3;function Z1(t,e=il){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let s=t.slice(r+e.length,i),c={};for(let l of s.split(`
122
- `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function Y1(){let t=(process.env.SHELL??"").trim()||(Ep().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return V1.has(e)?t:null}function X1(t){return new Promise(e=>{let r=`printf '%s' '${il}'; env; printf '%s' '${il}'`,i;try{i=$1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Ep().homedir}})}catch{e(null);return}let s="",c=!1,l=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(x),clearTimeout(h),e(m))};i.stdout?.on("data",m=>{s+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(s.length>0?s:null));let x=setTimeout(()=>l("SIGTERM"),bp),h=setTimeout(()=>{l("SIGKILL"),u(s.length>0?s:null)},bp+J1)})}async function sl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=Y1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??X1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=Z1(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Ce();function On(t,...e){let r=[],i;for(let s=0;s<t.length;s++){let c=t[s],l=!1;for(let u of e){if(c===u){i=t[s+1],s+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||r.push(c)}return{value:i,rest:r}}dn();import{chmod as Q1,copyFile as vp,mkdir as Ip,readFile as fs,rename as Sp,rm as cl,stat as Ap,writeFile as eI}from"node:fs/promises";import{homedir as gO}from"node:os";import{dirname as tI,join as Oe,resolve as dl,sep as us}from"node:path";import{fileURLToPath as nI}from"node:url";Zt();ie();Ce();function ei(t,e,r,i){it(t.bridgeLogsDir,e,"dist-install",r,i)}function kp(){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 rI(){return{darwin:{arm64:Oe("vendor","aarch64-apple-darwin","bin","codex"),x64:Oe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Oe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Oe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Oe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Oe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function iI(t){let e=nI(t),r=tI(e),i=`${us}src${us}`;if(r.includes(i)||r.endsWith(`${us}src${us}cli`))return null;let s=dl(r,"index.js"),c=dl(r,"..","package.json");return{dist:s,pkgJson:c}}async function ll(t={}){let e=t.paths??Z(),r=iI(import.meta.url),i=t.sourceDist??r?.dist,s=t.sourcePackageJson??r?.pkgJson;if(!i||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,l;try{let E=JSON.parse(await fs(s,"utf8"));c=E.version??"unknown",l=E.dependencies??{}}catch(E){throw ei(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=ys.map(E=>({name:E,spec:l[E]??"latest"})),x=u.map(({name:E,spec:I})=>`${E}@${I}`),h=await Bo(e.configFile)??{},m=h.libVersion,w=await fs(e.libEntry).then(()=>!0).catch(()=>!1),S=m===c,y=await Tp(e,u);if(S&&w&&y)return{kind:"already-current",libVersion:c};if(!S||!w){await Ip(e.libDir,{recursive:!0}),await vp(i,e.libEntry),await vp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=dl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
123
- `;await fs(E,"utf8").catch(()=>null)!==I&&await eI(E,I)}return y||(t.installWrappers?await t.installWrappers(e,x):await aI(e,x,u)),h.libVersion=c,await Yi(h,e.configFile),ei(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),S&&w?{kind:"already-current",libVersion:c}:m?{kind:"version-changed",fromVersion:m,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Tp(t,e){for(let r of e){let i=Oe(t.libDir,"node_modules",...r.name.split("/"),"package.json"),s;try{s=JSON.parse(await fs(i,"utf8"))}catch(l){return ei(t,"debug","wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(l)}),!1}let c=s.version;if(!c)return ei(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!sI(c,r.spec))return ei(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await Cp(Oe(t.libDir,"node_modules"))}function sI(t,e){let r=ol(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=ol(i.slice(1));if(!c)return!0;if(al(r,c)<0)return!1;let l=oI(c);return al(r,l)<0}let s=ol(i);return s?al(r,s)===0:!0}function oI(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function ol(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function al(t,e){for(let r=0;r<3;r++){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return 0}async function aI(t,e,r){await lI(t.installLock,async()=>{if(await Tp(t,r))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${us}.staging-${process.pid}-${i}`,c=Oe(s,"node_modules"),l=Oe(t.libDir,"node_modules");try{await Ip(s,{recursive:!0}),await cI(e,s),await dI(c);let u=`${l}.trash-${i}`;await Sp(l,u).catch(()=>{}),await Sp(c,l),await cl(u,{recursive:!0,force:!0}).catch(()=>{}),ei(t,"info","wrapper closure installed",{liveNm:l,specs:e})}finally{await cl(s,{recursive:!0,force:!0}).catch(()=>{})}})}function cI(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,s)=>{let c=ot("npm",r,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",x=>{l.length<8192&&(l+=x.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",x=>{clearTimeout(u),s(new Error(`spawn npm failed: ${String(x)}`))}),c.once("close",x=>{clearTimeout(u),x===0?i():s(new Error(`npm install \u9000\u51FA\u7801 ${x}: ${l.trim().slice(0,2e3)}`))})})}async function dI(t){for(let e of ys){let r=Oe(t,...e.split("/")),i=JSON.parse(await fs(Oe(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let s=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!s)throw new Error(`${e}: package.json \u7F3A bin`);let c=Oe(t,".bin",s),l=await Ap(c);process.platform!=="win32"&&!(l.mode&73)&&await Q1(c,l.mode|73).catch(()=>{})}if(!await Cp(t)){let e=kp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Cp(t){let e=kp(),r=rI();if(!e||!r)return!0;let i=Oe(t,"@openai","codex"),s=Oe(t,...e.split("/")),c=[Oe(i,"package.json"),Oe(i,"bin","codex.js"),Oe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Oe(s,"package.json"),Oe(s,r)];return(await Promise.all(c.map(u=>Ap(u).then(x=>x.isFile()).catch(()=>!1)))).every(Boolean)}async function lI(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let s=0;s<60&&!i;s++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await cl(t,{force:!0}).catch(()=>{})}}Ba();ie();Ce();import{closeSync as Pp,fstatSync as Dp,openSync as Op,readFileSync as uI,readSync as fI,readdirSync as xI,statSync as hI}from"node:fs";import{join as ga}from"node:path";var pI=new Set(["debug","info","warn","error"]);function Lp(t){let e=t,r=On(e,"--agent-id");e=r.rest;let i=On(e,"--date");e=i.rest;let s=On(e,"-n","--lines");e=s.rest;let c=On(e,"--level");e=c.rest;let l=On(e,"--grep");e=l.rest;let u=s.value===void 0?200:Number(s.value),x=Number.isInteger(u)&&u>=0?u:200,h=c.value&&pI.has(c.value)?c.value:void 0,m={lines:x,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(m.agentId=r.value),i.value&&(m.date=i.value),h&&(m.level=h),l.value&&(m.grep=l.value),m}function gI(t,e){return t.agentId?ga(ze(t.agentId,e).logs,ur("agent",t.date)):ga(e.bridgeLogsDir,ur("bridge",t.date))}function mI(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function wI(t,e){let r;try{r=xI(t)}catch{return[]}let i=[];for(let s of r){let c=Ma(s,e);if(!c)continue;let l=0;try{l=hI(ga(t,s)).size}catch{}i.push({file:ga(t,s),date:c,size:l})}return i.sort((s,c)=>c.date.localeCompare(s.date)),i}function Np(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!zl(r,e.level))return!1}return!0}var Rp={debug:"90",info:"36",warn:"33",error:"31"},_I=new Set(["ts","level","module","msg"]);function yI(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Mp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=yI(r.ts),s=typeof r.level=="string"?r.level:"",c=s.toUpperCase().padEnd(5);e.color&&Rp[s]&&(c=`\x1B[${Rp[s]}m${c}\x1B[0m`);let l=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",x=Object.entries(r).filter(([h])=>!_I.has(h)).map(([h,m])=>` ${h}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${l} ${u}${x}`}function bI(t,e,r){let c=uI(t,"utf8").split(`
124
- `).filter(l=>l.length>0).filter(l=>Np(l,{level:e.level,grep:e.grep}));for(let l of mI(c,e.lines))process.stdout.write(`${Mp(l,{raw:e.raw,color:r})}
125
- `)}async function Bp(t,e){let r=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?ze(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",x=wI(l,u);if(x.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
126
- `),1;for(let h of x)process.stdout.write(`${h.date} ${(h.size/1024).toFixed(1)}KB ${h.file}
127
- `);return 0}let s=t.date??Nn(new Date),c=gI({agentId:t.agentId,date:s},r);try{bI(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
125
+ `)}catch{}}let e=new ya({processTitle:jr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await $o(),s=i??{};Is({pid:process.pid}),$.info(i?"loaded bridge config":"initialized bridge config");let a=new ma(new ii),d=null,u=new Vo({upstream:a,paths:t,bridgeConfig:s,sessionSpawner:async(C,q,W,te,qe,pe)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(C,q,W,te,qe,pe)}}),h=new jo({paths:t,config:s,registry:u});d=h;let x,g,w=null,v={},_,E=null,I=null,A=null,T=new Rn;function O(C,q){return T.enqueue(()=>L(C,q))}function b(){I||(I=new Ea({isConnected:()=>a.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>A?O(A,{force:!0}):void 0,onFatal:C=>{if(process.env[ms]==="1"){$.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}$.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),I.start()}async function L(C,q){let W=C,te=W?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let qe=Vi(W.env),pe=W.handshake_url,_e=W.frontier_url,Ct=Op(W.env,pe,_e);if(A=W,!q?.force&&x===te&&g===Ct){let ve=await aI(t);return u.agents.size===0&&ve?($.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Sa(t,h).catch(Oe=>$.warn("connect-noop auto-revive error (ignored)",{err:String(Oe)}))):$.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let bt=!!x&&x!==te,ln=g!==void 0&&g!==Ct,Kt=bt||ln,un=await ld({privatecode:te,...pe?{endpoint:pe}:{},ppeOverride:qe});if(Kt){$.warn("connect config switched, resetting agents",{pcChanged:bt,envChanged:ln,previousPc:x?va(x):"",nextPc:va(te)});for(let ve of[...u.agents.values()])await ve.dispose("connect config switch").catch(()=>{}),u.agents.delete(ve.agentId);u.disconnectedAgents.size>0&&($.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ii,"connect switch").catch(()=>{})}w=un.deviceId,Is({deviceId:w,pid:process.pid}),Bd({patToken:te,env:W.env}).catch(ve=>$.warn("coze-cli setup error (ignored)",{err:String(ve)}));let di=new ps({handshake:un,privatecode:te,..._e?{urlOverride:_e}:{},ppeOverride:qe,getPatTokenForAgent:ve=>u.agents.get(ve)?.patToken});return await a.swap(di,"connect"),x=te,g=Ct,v=qe,_=pe,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),$.info("mock scenario set",{scenario:W.mock_scenario})),E||(E=new Yi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>z.retryPending().catch(ve=>$.warn("detailSync.retryPending failed (ignored)",{err:String(ve)})),onAuthFailures:Y})),E.start(),b(),Kt&&Sa(t,h).catch(ve=>$.warn("post-connect-switch auto-revive error (ignored)",{err:String(ve)})),gs(te,t).catch(ve=>$.warn("writePatToken after /connect failed (ignored)",{err:String(ve)})),$.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>h.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let N={},H=new Po({agents:u.agents,paths:t,publishSkillToMarketplace:async C=>{let q=u.agents.get(C.agentId)?.patToken??x;if(!q)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Ap({patToken:q,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:_,ppeOverride:v})},disposeAndMarkDisconnected:async(C,q)=>{let W=u.agents.get(C);if(W){await h.cleanupOpenclawSessionProviders(W).catch(qe=>$.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(qe)})),W.framework==="hermes"&&W.deployType==="cloud"&&await md(C,t).catch(qe=>$.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(qe)}));let te=!0;try{await W.dispose(`disconnect: ${q}`)}catch(qe){te=!1,$.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(qe)}),W.status="error"}te&&(W.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,q)=>{let W=u.agents.get(C);W&&(await h.cleanupOpenclawSessionProviders(W).catch(te=>$.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(te)})),W.framework==="hermes"&&W.deployType==="cloud"&&await md(C,t).catch(te=>$.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(te)})),await W.dispose(`delete: ${q}`).catch(te=>$.warn("dispose during delete failed (ignored)",{agentId:C,err:String(te)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!N.ref)throw new Error("agent-detail-sync not initialized yet");await N.ref.syncOne(C)},cleanupOpenclawProviders:async(C,q)=>{await h.cleanupOpenclawSessionProviders(C,q)},openclawRepair:async(C,q)=>{await h.openclawRepair(C,q)},hermesReset:async(C,q)=>{let W=await ke(C).catch(()=>null);!W||W.framework!=="hermes"||W.deployType!=="cloud"||await k0({paths:t,agentId:C,model:W.model,modelInfo:W.modelInfo,cozeEnv:q,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>H.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>H.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>H.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>H.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>H.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>H.getFileContent(C.params)),u.registerExtension("_agent/update",C=>H.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>H.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>H.switchModel(C.params)),u.registerExtension("_agent/reset",C=>H.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>H.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>H.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>H.upgradeBridge(C.params));let z=new Rs({paths:t,handlers:H,agentManager:h,sendDetail:C=>u.sendRequest("_agent/detail",C)});N.ref=z;let Y=async C=>{await Promise.allSettled(C.map(async q=>{try{await H.disconnectAgent({agentId:q.agentId,reason:`auth_failure: code=${q.code} ${q.message}`}),$.info("agent disconnected due to auth failure from heartbeat response",{agentId:q.agentId,code:q.code,message:q.message})}catch(W){$.warn("disconnect during authFailure handling failed (ignored)",{agentId:q.agentId,err:String(W)})}}))};a.onConnect(({initial:C})=>{$.info("frontier upstream connected, triggering detail sync",{initial:C}),z.syncAll(C?"initial-connect":"reconnect").catch(q=>$.warn("detail sync top-level error (ignored)",{err:String(q)}))});let Z=new Zo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ms]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:s.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let q=C,W=q?.privatecode,te=q?.pairing_code;if(!W||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let qe=Vi(q.env),pe=q.handshake_url,_e=q.frontier_url,Ct=Op(q.env,pe,_e),bt=!!x&&x!==W,ln=g!==void 0&&g!==Ct,Kt=bt||ln,un=await ld({privatecode:W,...pe?{endpoint:pe}:{},ppeOverride:qe});if(Kt){$.warn("pair config switched, resetting agents",{pcChanged:bt,envChanged:ln,previousPc:x?va(x):"",nextPc:va(W),previousEnvKey:g??"",nextEnvKey:Ct});for(let Oe of[...u.agents.values()])await Oe.dispose("pair config switch").catch(()=>{}),u.agents.delete(Oe.agentId);u.disconnectedAgents.size>0&&($.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ii,"pair switch").catch(()=>{})}w=un.deviceId,Is({deviceId:w,pid:process.pid}),Bd({patToken:W,env:q.env}).catch(Oe=>$.warn("coze-cli setup error (ignored)",{err:String(Oe)}));let di=new ps({handshake:un,privatecode:W,..._e?{urlOverride:_e}:{},ppeOverride:qe,getPatTokenForAgent:Oe=>u.agents.get(Oe)?.patToken});await a.swap(di,"pair");try{let Oe=new nr;s.frameworksCache=await Oe.detectAll(),await is(s),$.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(Oe){$.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Oe)})}let ve=Object.keys(s.frameworksCache??{});try{let Oe=await u.sendRequest("_agent/pair",{pairCode:te,patToken:W,frameworks:ve,_meta:{cozeDeviceId:w}});$.info("_agent/pair ok",{pairResult:Oe}),x=W,g=Ct,v=qe,_=pe,q.mock_scenario!==void 0&&(u.setMockScenario(q.mock_scenario),$.info("mock scenario set",{scenario:q.mock_scenario})),gs(W,t).catch(ze=>$.warn("writePatToken after /pair failed (ignored)",{err:String(ze)})),E||(E=new Yi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>z.retryPending().catch(ze=>$.warn("detailSync.retryPending failed (ignored)",{err:String(ze)})),onAuthFailures:Y})),E.start(),b(),Kt&&Sa(t,h).catch(ze=>$.warn("post-pair-switch auto-revive error (ignored)",{err:String(ze)}));let lr;return q.agent_id&&(lr=await dI(q.agent_id,t,h,ze=>u.sendRequest("_agent/detail",ze),W).catch(ze=>($.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(ze)}),{ok:!1,agentId:q.agent_id??"",note:String(ze)}))),{ok:!0,note:"paired with cloud",...lr?{agent:lr}:{}}}catch(Oe){return $.error("_agent/pair failed",{err:String(Oe)}),{ok:!1,note:`pair failed: ${String(Oe)}`}}}},{method:"POST",path:"/connect",handler:C=>O(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let q=C;return{ok:!0,result:await h.createAgent(q)}}},{method:"POST",path:"/agent/send",handler:async C=>{let q=C;if(!q?.agentId||!q?.sessionId||!q?.kind||!q?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let W=q;return await(W.groupFile?Uh:zh)(W,{core:u,patToken:x,handshakeBase:_,ppeOverride:v})}catch(W){if(W instanceof k)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async C=>{let q=C?.agent_id,W=await u.reloadAgents(q);return $.info("IPC /reload: recycled agent subprocesses",{agentId:q??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>($.info("IPC /shutdown received"),setImmediate(()=>{de.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ae,token:Q}=await Z.start();try{await Tp(t.libEntry,t)}catch(C){$.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),lI({paths:t,core:u,agentManager:h,detectAll:async()=>(s.frameworksCache=await new nr().detectAll(),await is(s),s.frameworksCache)}).catch(C=>$.warn("startup warmup error (ignored)",{err:String(C)})),tu().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(xn(),Ql));for(let q of["claude-code","codex"]){let W=await C(q);W&&$.info("acp wrapper version",{framework:q,version:W})}}).catch(C=>$.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let se=null,de={port:ae,token:Q,core:u,ipc:Z,shutdown(C){return se||($.info("daemon shutdown",{reason:C}),se=(async()=>{E?.stop(),I?.stop(),await u.stop(C),await Z.stop(),await e.release()})(),se)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{de.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>th()),process.on("unhandledRejection",C=>{$.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{$.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
126
+ `)}catch{}process.exit(1)}),$.info("daemon ready",{port:ae,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),fI({cliSpawned:process.env[ms]==="1",readPatToken:()=>wa(t),connect:O}).catch(C=>$.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),de}async function aI(t){return Ps(t).length>0}function va(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Op(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function cI(t,e){let n=Ps(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(Vt(),Cs));for(let a of n){await s(a,t).catch(d=>$.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),$.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),$.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){$.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function dI(t,e,n,i,s){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(Vt(),Cs)),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`);$.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=Np(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...s?{patToken:s}:{},...g?{_meta:g}:{}};return await n.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}$.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...s?{patToken:s}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function lI(t){let e=t.logger??$;try{let n=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(n??{})})}catch(n){e.warn("framework detection failed (using cached)",{err:String(n)})}await cI(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Sa(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await uI(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Sa(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(Vt(),Cs));$.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=0;for(let u of i){let h;try{h=await s(u,t)}catch(x){$.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){$.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){$.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{$.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=Np(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),a+=1}catch(x){$.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return $.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function uI(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let s of n)try{(await q0(s,t)).status==="refreshed"&&(i+=1)}catch(a){$.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(a)})}return i>0&&$.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function fI(t){let e=t.logger??$;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 Np(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ba();Ce();import{readFile as Mp}from"node:fs/promises";var dn=class{paths;constructor(e){this.paths=e??J()}async probe(e=1e3){let n=await Ia(this.paths);if(!n)return{kind:"not-running"};try{let i=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...n,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:xI(i)}}}async request(e){let n=await Ia(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,s={Authorization:`Bearer ${e.token}`};i&&(s["content-type"]="application/json");let 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:s,body:i?JSON.stringify(n.body):void 0,signal:a.signal}),h=await u.text();return{status:u.status,body:hI(h)}}finally{clearTimeout(d)}}};async function Ia(t){try{let[e,n]=await Promise.all([Mp(t.portFile,"utf8"),Mp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),s=n.trim();return!Number.isFinite(i)||i<=0||!s?null:{port:i,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}function hI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function xI(t){return t instanceof Error?t.message:String(t)}tn();ne();xr();import{spawn as pI}from"node:child_process";import{userInfo as Fp}from"node:os";var xl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",gI=new Set(["bash","zsh","sh","dash","ksh"]),Bp=Qe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),mI=2e3;function wI(t,e=xl){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let s=t.slice(n+e.length,i),a={};for(let d of s.split(`
127
+ `)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function _I(){let t=(process.env.SHELL??"").trim()||(Fp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return gI.has(e)?t:null}function yI(t){return new Promise(e=>{let n=`printf '%s' '${xl}'; env; printf '%s' '${xl}'`,i;try{i=pI(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Fp().homedir}})}catch{e(null);return}let s="",a=!1,d=g=>{try{i.pid&&process.kill(-i.pid,g)}catch{}},u=g=>{a||(a=!0,clearTimeout(h),clearTimeout(x),e(g))};i.stdout?.on("data",g=>{s+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(s.length>0?s:null));let h=setTimeout(()=>d("SIGTERM"),Bp),x=setTimeout(()=>{d("SIGKILL"),u(s.length>0?s:null)},Bp+mI)})}async function pl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=_I();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??yI)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=wI(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Ce();function Nn(t,...e){let n=[],i;for(let s=0;s<t.length;s++){let a=t[s],d=!1;for(let u of e){if(a===u){i=t[s+1],s+=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}}xn();import{chmod as bI,copyFile as zp,mkdir as Hp,readFile as _s,rename as Up,rm as wl,stat as Gp,writeFile as EI}from"node:fs/promises";import{homedir as a3}from"node:os";import{dirname as vI,join as Fe,resolve as _l,sep as ws}from"node:path";import{fileURLToPath as SI}from"node:url";tn();ne();Ce();function si(t,e,n,i){ot(t.bridgeLogsDir,e,"dist-install",n,i)}function qp(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function II(){return{darwin:{arm64:Fe("vendor","aarch64-apple-darwin","bin","codex"),x64:Fe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Fe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Fe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Fe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Fe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function AI(t){let e=SI(t),n=vI(e),i=`${ws}src${ws}`;if(n.includes(i)||n.endsWith(`${ws}src${ws}cli`))return null;let s=_l(n,"index.js"),a=_l(n,"..","package.json");return{dist:s,pkgJson:a}}async function yl(t={}){let e=t.paths??J(),n=AI(import.meta.url),i=t.sourceDist??n?.dist,s=t.sourcePackageJson??n?.pkgJson;if(!i||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let a,d;try{let E=JSON.parse(await _s(s,"utf8"));a=E.version??"unknown",d=E.dependencies??{}}catch(E){throw si(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=ks.map(E=>({name:E,spec:d[E]??"latest"})),h=u.map(({name:E,spec:I})=>`${E}@${I}`),x=await $o(e.configFile)??{},g=x.libVersion,w=await _s(e.libEntry).then(()=>!0).catch(()=>!1),v=g===a,_=await jp(e,u);if(v&&w&&_)return{kind:"already-current",libVersion:a};if(!v||!w){await Hp(e.libDir,{recursive:!0}),await zp(i,e.libEntry),await zp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=_l(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
128
+ `;await _s(E,"utf8").catch(()=>null)!==I&&await EI(E,I)}return _||(t.installWrappers?await t.installWrappers(e,h):await PI(e,h,u)),x.libVersion=a,await is(x,e.configFile),si(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:a}),v&&w?{kind:"already-current",libVersion:a}:g?{kind:"version-changed",fromVersion:g,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function jp(t,e){for(let n of e){let i=Fe(t.libDir,"node_modules",...n.name.split("/"),"package.json"),s;try{s=JSON.parse(await _s(i,"utf8"))}catch(d){return si(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let a=s.version;if(!a)return si(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!kI(a,n.spec))return si(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await Kp(Fe(t.libDir,"node_modules"))}function kI(t,e){let n=gl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=gl(i.slice(1));if(!a)return!0;if(ml(n,a)<0)return!1;let d=TI(a);return ml(n,d)<0}let s=gl(i);return s?ml(n,s)===0:!0}function TI(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function gl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function ml(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 PI(t,e,n){await RI(t.installLock,async()=>{if(await jp(t,n))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${ws}.staging-${process.pid}-${i}`,a=Fe(s,"node_modules"),d=Fe(t.libDir,"node_modules");try{await Hp(s,{recursive:!0}),await DI(e,s),await CI(a);let u=`${d}.trash-${i}`;await Up(d,u).catch(()=>{}),await Up(a,d),await wl(u,{recursive:!0,force:!0}).catch(()=>{}),si(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await wl(s,{recursive:!0,force:!0}).catch(()=>{})}})}function DI(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,s)=>{let a=ct("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",h=>{clearTimeout(u),s(new Error(`spawn npm failed: ${String(h)}`))}),a.once("close",h=>{clearTimeout(u),h===0?i():s(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function CI(t){for(let e of ks){let n=Fe(t,...e.split("/")),i=JSON.parse(await _s(Fe(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let s=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!s)throw new Error(`${e}: package.json \u7F3A bin`);let a=Fe(t,".bin",s),d=await Gp(a);process.platform!=="win32"&&!(d.mode&73)&&await bI(a,d.mode|73).catch(()=>{})}if(!await Kp(t)){let e=qp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Kp(t){let e=qp(),n=II();if(!e||!n)return!0;let i=Fe(t,"@openai","codex"),s=Fe(t,...e.split("/")),a=[Fe(i,"package.json"),Fe(i,"bin","codex.js"),Fe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Fe(s,"package.json"),Fe(s,n)];return(await Promise.all(a.map(u=>Gp(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function RI(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let s=0;s<60&&!i;s++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(a=>setTimeout(a,500))}try{return await e()}finally{i&&await wl(t,{force:!0}).catch(()=>{})}}$a();ne();Ce();import{closeSync as $p,fstatSync as Vp,openSync as Zp,readFileSync as OI,readSync as LI,readdirSync as NI,statSync as MI}from"node:fs";import{join as Aa}from"node:path";var BI=new Set(["debug","info","warn","error"]);function Jp(t){let e=t,n=Nn(e,"--agent-id");e=n.rest;let i=Nn(e,"--date");e=i.rest;let s=Nn(e,"-n","--lines");e=s.rest;let a=Nn(e,"--level");e=a.rest;let d=Nn(e,"--grep");e=d.rest;let u=s.value===void 0?200:Number(s.value),h=Number.isInteger(u)&&u>=0?u:200,x=a.value&&BI.has(a.value)?a.value:void 0,g={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(g.agentId=n.value),i.value&&(g.date=i.value),x&&(g.level=x),d.value&&(g.grep=d.value),g}function FI(t,e){return t.agentId?Aa(Ne(t.agentId,e).logs,pr("agent",t.date)):Aa(e.bridgeLogsDir,pr("bridge",t.date))}function zI(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function UI(t,e){let n;try{n=NI(t)}catch{return[]}let i=[];for(let s of n){let a=Wa(s,e);if(!a)continue;let d=0;try{d=MI(Aa(t,s)).size}catch{}i.push({file:Aa(t,s),date:a,size:d})}return i.sort((s,a)=>a.date.localeCompare(s.date)),i}function Yp(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"&&!Vl(n,e.level))return!1}return!0}var Wp={debug:"90",info:"36",warn:"33",error:"31"},HI=new Set(["ts","level","module","msg"]);function GI(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Xp(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=GI(n.ts),s=typeof n.level=="string"?n.level:"",a=s.toUpperCase().padEnd(5);e.color&&Wp[s]&&(a=`\x1B[${Wp[s]}m${a}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",h=Object.entries(n).filter(([x])=>!HI.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${a} ${d} ${u}${h}`}function qI(t,e,n){let a=OI(t,"utf8").split(`
129
+ `).filter(d=>d.length>0).filter(d=>Yp(d,{level:e.level,grep:e.grep}));for(let d of zI(a,e.lines))process.stdout.write(`${Xp(d,{raw:e.raw,color:n})}
130
+ `)}async function Qp(t,e){let n=e.paths??J(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ne(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=UI(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
131
+ `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
132
+ `);return 0}let s=t.date??Bn(new Date),a=FI({agentId:t.agentId,date:s},n);try{qI(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
128
133
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
129
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
130
- `),1}return t.follow&&await SI(c,t,i),0}var EI=500;function vI(t){try{let e=Op(t,"r");try{return Dp(e).size}finally{Pp(e)}}catch{return 0}}async function SI(t,e,r){let i=vI(t),s="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let x=Op(t,"r");try{let h=Dp(x).size;if(h>i){let m=Buffer.allocUnsafe(h-i),w=fI(x,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{Pp(x)}}catch{}if(u){let x=(s+u).split(`
131
- `);s=x.pop()??"";for(let h of x)h.length>0&&Np(h,{level:e.level,grep:e.grep})&&process.stdout.write(`${Mp(h,{raw:e.raw,color:r})}
132
- `)}await new Promise(x=>setTimeout(x,EI))}}finally{process.off("SIGINT",l)}}import{basename as II,resolve as AI}from"node:path";Ce();var kI=9e4,TI={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1,SKILL_NOT_FOUND:1,SKILL_ZIP_TOO_LARGE:1};function CI(t){return TI[t]??1}async function Fp(t,e={}){let r=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>
134
+ (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
135
+ `),1}return t.follow&&await WI(a,t,i),0}var jI=500;function KI(t){try{let e=Zp(t,"r");try{return Vp(e).size}finally{$p(e)}}catch{return 0}}async function WI(t,e,n){let i=KI(t),s="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let h=Zp(t,"r");try{let x=Vp(h).size;if(x>i){let g=Buffer.allocUnsafe(x-i),w=LI(h,g,0,g.length,i);u=g.subarray(0,w).toString("utf8"),i+=w}}finally{$p(h)}}catch{}if(u){let h=(s+u).split(`
136
+ `);s=h.pop()??"";for(let x of h)x.length>0&&Yp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Xp(x,{raw:e.raw,color:n})}
137
+ `)}await new Promise(h=>setTimeout(h,jI))}}finally{process.off("SIGINT",d)}}import{basename as $I,resolve as VI}from"node:path";Ce();var ZI=9e4,JI={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1,SKILL_NOT_FOUND:1,SKILL_ZIP_TOO_LARGE:1};function YI(t){return JI[t]??1}async function eg(t,e={}){let n=e.paths??J();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
133
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.
134
- `),3;let i=await pa(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
135
- `),4;let s={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:AI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},c;try{c=await RI(i,"/agent/send",s,kI)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
136
- `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
137
- `),CI(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
138
- `);else{let l=t.name??II(s.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
139
- `)}else process.stdout.write(`Sent ${t.kind} ${l} (${PI(c.bytes)})
140
- `)}return 0}async function RI(t,e,r,i){let s=new AbortController,c=setTimeout(()=>s.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:s.signal}),u=await l.text(),x=u?JSON.parse(u):null;return x&&typeof x=="object"&&"ok"in x?x:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function PI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Vp=j("cli");function Ke(t,e){let{value:r,rest:i}=On(t,e);return{value:r,rest:i}}function Ea(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
141
- `)}function t2(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:C}=Ke(e.slice(1),"--agent-id");return C?{mode:"reload",agentId:C}:{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 n2(e.slice(1));if(e[0]==="log")return{mode:"log",...Lp(e.slice(1))};if(e[0]==="connect")return r2(e.slice(1));if(e.includes("--status"))return Ea("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ea("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ea("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ea("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:s}=Ke(r,"--pat-token");r=s;let{value:c,rest:l}=Ke(r,"--pair-code");r=l;let{value:u,rest:x}=Ke(r,"--env");r=x;let{value:h,rest:m}=Ke(r,"--handshake-url");r=m;let{value:w,rest:S}=Ke(r,"--frontier-url");r=S;let{value:y,rest:E}=Ke(r,"--mock-scenario");r=E;let{value:I}=Ke(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:c};return u&&(T.env=u),h&&(T.handshakeUrl=h),w&&(T.frontierUrl=w),y&&(T.mockScenario=y),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function n2(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:s,rest:c}=Ke(i,"--caption");i=c;let{value:l,rest:u}=Ke(i,"--name");i=u;let{value:x,rest:h}=Ke(i,"--agent-id");i=h;let{value:m,rest:w}=Ke(i,"--session-id");i=w;let{value:S,rest:y}=Ke(i,"--mime");i=y;let E=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return s&&(A.caption=s),l&&(A.name=l),x&&(A.agentId=x),m&&(A.sessionId=m),E&&(A.groupFile=!0),S&&(A.mimeType=S),A}function r2(t){let e=t,{value:r,rest:i}=Ke(e,"--pat-token");e=i;let{value:s,rest:c}=Ke(e,"--env");e=c;let{value:l,rest:u}=Ke(e,"--handshake-url");e=u;let{value:x,rest:h}=Ke(e,"--frontier-url");e=h;let{value:m,rest:w}=Ke(e,"--mock-scenario");e=w;let S=e.includes("--skip-rebuild-env"),y={mode:"connect"};return r&&(y.privatecode=r),s&&(y.env=s),l&&(y.handshakeUrl=l),x&&(y.frontierUrl=x),m&&(y.mockScenario=m),S&&(y.skipRebuildEnv=!0),y}var i2=`
139
+ `),3;let i=await Ia(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
+ `),4;let s={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:VI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},a;try{a=await XI(i,"/agent/send",s,ZI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
141
+ `),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
142
+ `),YI(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
143
+ `);else{let d=t.name??$I(s.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
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${QI(a.bytes)})
145
+ `)}return 0}async function XI(t,e,n,i){let s=new AbortController,a=setTimeout(()=>s.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:s.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(a)}}function QI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var lg=K("cli");function Je(t,e){let{value:n,rest:i}=Nn(t,e);return{value:n,rest:i}}function Ra(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
146
+ `)}function vA(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:O}=Je(e.slice(1),"--agent-id");return O?{mode:"reload",agentId:O}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return SA(e.slice(1));if(e[0]==="log")return{mode:"log",...Jp(e.slice(1))};if(e[0]==="connect")return IA(e.slice(1));if(e.includes("--status"))return Ra("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ra("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ra("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ra("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:s}=Je(n,"--pat-token");n=s;let{value:a,rest:d}=Je(n,"--pair-code");n=d;let{value:u,rest:h}=Je(n,"--env");n=h;let{value:x,rest:g}=Je(n,"--handshake-url");n=g;let{value:w,rest:v}=Je(n,"--frontier-url");n=v;let{value:_,rest:E}=Je(n,"--mock-scenario");n=E;let{value:I}=Je(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:a};return u&&(T.env=u),x&&(T.handshakeUrl=x),w&&(T.frontierUrl=w),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function SA(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:s,rest:a}=Je(i,"--caption");i=a;let{value:d,rest:u}=Je(i,"--name");i=u;let{value:h,rest:x}=Je(i,"--agent-id");i=x;let{value:g,rest:w}=Je(i,"--session-id");i=w;let{value:v,rest:_}=Je(i,"--mime");i=_;let E=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return s&&(A.caption=s),d&&(A.name=d),h&&(A.agentId=h),g&&(A.sessionId=g),E&&(A.groupFile=!0),v&&(A.mimeType=v),A}function IA(t){let e=t,{value:n,rest:i}=Je(e,"--pat-token");e=i;let{value:s,rest:a}=Je(e,"--env");e=a;let{value:d,rest:u}=Je(e,"--handshake-url");e=u;let{value:h,rest:x}=Je(e,"--frontier-url");e=x;let{value:g,rest:w}=Je(e,"--mock-scenario");e=w;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),s&&(_.env=s),d&&(_.handshakeUrl=d),h&&(_.frontierUrl=h),g&&(_.mockScenario=g),v&&(_.skipRebuildEnv=!0),_}var AA=`
142
147
  coze-bridge - local bridge daemon for cloud Agent Service
143
148
 
144
149
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -219,57 +224,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
219
224
 
220
225
  Internal:
221
226
  <node> <entry> --daemon daemon mode (OS supervisor only)
222
- `.trimStart();async function Jp(t=process.argv,e={}){let r=t2(t);switch(r.mode){case"help":return process.stdout.write(i2),0;case"version":return process.stdout.write(`${Lt}
223
- `),0;case"daemon":{try{await wp()}catch(i){return Vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return s2(e);case"stop":return Yp(e);case"reload":return c2(r.agentId,e);case"log":return Bp(r,e);case"update":return o2(e);case"purge":return l2(e);case"service-install":return u2(e);case"service-uninstall":return f2(e);case"pair":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),x2(r.privatecode,r.pairingCode,e,i,r.agentId,r.skipRebuildEnv)}case"connect":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),h2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Fp({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function Zp(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 s2(t){let e=t.paths??Z(),r=new rn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
224
- `),1;if(i.kind==="stale")return await Zp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
225
- `),1;let s=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
227
+ `.trimStart();async function ug(t=process.argv,e={}){let n=vA(t);switch(n.mode){case"help":return process.stdout.write(AA),0;case"version":return process.stdout.write(`${zt}
228
+ `),0;case"daemon":{try{await Lp()}catch(i){return lg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return kA(e);case"stop":return hg(e);case"reload":return DA(n.agentId,e);case"log":return Qp(n,e);case"update":return TA(e);case"purge":return RA(e);case"service-install":return OA(e);case"service-uninstall":return LA(e);case"pair":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),NA(n.privatecode,n.pairingCode,e,i,n.agentId,n.skipRebuildEnv)}case"connect":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),MA(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return eg({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 fg(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function kA(t){let e=t.paths??J(),n=new dn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
229
+ `),1;if(i.kind==="stale")return await fg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
230
+ `),1;let s=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
226
231
  ${JSON.stringify(s.body,null,2)}
227
- `),0}async function Yp(t){let e=t.paths??Z(),r=new rn(e),i=t.daemonSweep??(async()=>{let x=q0();return await G0(x),x}),s=async()=>{t.skipProcessKill||await i(e)},c=await hs(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(x){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(x)}
228
- `)}let u=await r.probe();if(u.kind==="not-running")return await s(),process.stdout.write(l?`coze-bridge: stopped
232
+ `),0}async function hg(t){let e=t.paths??J(),n=new dn(e),i=t.daemonSweep??(async()=>{let h=nh();return await rh(h),h}),s=async()=>{t.skipProcessKill||await i(e)},a=await bs(t),d=!1;if(a)try{await a.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
233
+ `)}let u=await n.probe();if(u.kind==="not-running")return await s(),process.stdout.write(d?`coze-bridge: stopped
229
234
  `:`coze-bridge: not running
230
- `),0;if(u.kind==="stale")return await Zp(e),await s(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
231
- `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await s(),process.stdout.write(`coze-bridge: stopped
232
- `),0}catch(x){return(await r.probe()).kind!=="connected"?(await s(),process.stdout.write(`coze-bridge: stopped
233
- `),0):(await s(),process.stdout.write(`coze-bridge: stop failed: ${String(x)}
234
- `),1)}}async function o2(t){return await Yp(t),(t.spawnNpx??a2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function a2(t){return new Promise(e=>{let r=ot("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
235
- `),e(1)})})}async function c2(t,e){let r=new rn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
236
- `),1;try{let s=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(s.status===200&&s.body?.ok){let c=s.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
237
- `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
235
+ `),0;if(u.kind==="stale")return await fg(e),await s(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
236
+ `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await s(),process.stdout.write(`coze-bridge: stopped
237
+ `),0}catch(h){return(await n.probe()).kind!=="connected"?(await s(),process.stdout.write(`coze-bridge: stopped
238
+ `),0):(await s(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
239
+ `),1)}}async function TA(t){return await hg(t),(t.spawnNpx??PA)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function PA(t){return new Promise(e=>{let n=ct("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 DA(t,e){let n=new dn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
241
+ `),1;try{let s=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(s.status===200&&s.body?.ok){let a=s.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
+ `):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
238
243
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(s.body)}
239
244
  `),1}catch(s){return process.stderr.write(`coze-bridge: reload failed: ${String(s)}
240
- `),1}}async function hs(t){if(t.supervisor){let c=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(l,u),uninstall:()=>c.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Wp(),jp)),i=e(),s=r();return{platform:i.platform,install:c=>i.install(s,c),uninstall:()=>i.uninstall(s)}}async function Xp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,s=t.sleep??p2,c=t.paths??Z();if(r.kind==="connected"){if(!d2(r.body))return r;it(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:r.body}),await e.request({method:"POST",path:"/shutdown"}).catch(x=>it(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(x)})),await $p(c.pidFile,s)}let l=t.spawnDaemon??gp,u=await hs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let x=await Kp(e,i,s);if(x.kind==="connected")return x;it(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(x){it(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(x)})}it(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await $p(c.pidFile,s)}else u&&await u.install({activate:!1}).catch(x=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(x)}
245
+ `),1}}async function bs(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(()=>(ag(),og)),i=e(),s=n();return{platform:i.platform,install:a=>i.install(s,a),uninstall:()=>i.uninstall(s)}}async function xg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,s=t.sleep??BA,a=t.paths??J();if(n.kind==="connected"){if(!CA(n.body))return n;ot(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(h=>ot(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await dg(a.pidFile,s)}let d=t.spawnDaemon??Rp,u=await bs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await cg(e,i,s);if(h.kind==="connected")return h;ot(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){ot(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}ot(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 dg(a.pidFile,s)}else u&&await u.install({activate:!1}).catch(h=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(h)}
241
246
  `));return process.stdout.write(`coze-bridge: starting daemon...
242
- `),await l({paths:t.paths}),Kp(e,i,s)}function d2(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 l2(t){let e=new rn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
243
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
244
- `)}await new Promise(l=>setTimeout(l,500))}let i=await hs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
245
- `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
246
- `)}let s=t.paths??Z(),{rm:c}=await import("node:fs/promises");try{await c(s.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${s.bridgeRoot}
247
- `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
247
+ `),await d({paths:t.paths}),cg(e,i,s)}function CA(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 RA(t){let e=new dn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
248
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
249
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await bs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
250
+ `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
251
+ `)}let s=t.paths??J(),{rm:a}=await import("node:fs/promises");try{await a(s.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${s.bridgeRoot}
252
+ `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
248
253
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
249
- `),0}async function u2(t){let e=await hs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
254
+ `),0}async function OA(t){let e=await bs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
250
255
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
251
- `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
252
- `),1}}async function f2(t){let e=await hs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
253
- `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
254
- `),1}}async function Qp(t,e,r){if(e)return it(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(it(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(it(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)
255
- `),it(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function x2(t,e,r,i={},s,c){let l=new rn(r.paths),u=r.paths??Z(),x=await Qp(u,c,r.reconstructEnv??sl);if(await gd(u,x).catch(w=>it(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!r.skipDistInstall){let w=await ll({paths:r.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
256
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
257
- `)}let h=await Xp(r,l);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
258
- `),1;let m={privatecode:t,pairing_code:e};i.env&&(m.env=i.env),i.handshakeUrl&&(m.handshake_url=i.handshakeUrl),i.frontierUrl&&(m.frontier_url=i.frontierUrl),i.mockScenario&&(m.mock_scenario=i.mockScenario),s&&(m.agent_id=s);try{let w=await l.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let S=w.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
256
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
257
+ `),1}}async function LA(t){let e=await bs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
258
+ `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
259
+ `),1}}async function pg(t,e,n){if(e)return ot(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(ot(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ot(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
+ `),ot(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function NA(t,e,n,i={},s,a){let d=new dn(n.paths),u=n.paths??J(),h=await pg(u,a,n.reconstructEnv??pl);if(await dd(u,h).catch(w=>ot(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!n.skipDistInstall){let w=await yl({paths:n.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
261
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
262
+ `)}let x=await xg(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
263
+ `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),s&&(g.agent_id=s);try{let w=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let v=w.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
259
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"
260
265
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
261
266
  `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
262
- `),1}}async function h2(t,e,r={},i){let s=e.paths??Z(),c=t??await ca(s);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new rn(e.paths),u=await Qp(s,i,e.reconstructEnv??sl);if(await gd(s,u).catch(m=>it(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await ll({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
263
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
264
- `)}let x=await Xp(e,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
265
- `),1;let h={privatecode:c};r.env&&(h.env=r.env),r.handshakeUrl&&(h.handshake_url=r.handshakeUrl),r.frontierUrl&&(h.frontier_url=r.frontierUrl),r.mockScenario&&(h.mock_scenario=r.mockScenario);try{let m=await l.request({method:"POST",path:"/connect",body:h,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
266
- `),t!==void 0&&await ds(c,s).catch(w=>Vp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
267
- `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
268
- `),1}}async function Kp(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let s=await t.probe(500);if(s.kind==="connected")return s;await r(200)}return t.probe(500)}async function $p(t,e,r=60,i=200){let{readFile:s}=await import("node:fs/promises");for(let c=0;c<r;c++){let l;try{l=await s(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Vi(u))return;await e(i)}}function p2(t){return new Promise(e=>setTimeout(e,t))}ie();function g2(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function eg(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=g2(t);if(i==="ok")return;let s=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${s} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
269
- `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${s},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
267
+ `),1}}async function MA(t,e,n={},i){let s=e.paths??J(),a=t??await wa(s);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 dn(e.paths),u=await pg(s,i,e.reconstructEnv??pl);if(await dd(s,u).catch(g=>ot(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await yl({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
268
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
269
+ `)}let h=await xg(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.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 g=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
271
+ `),t!==void 0&&await gs(a,s).catch(w=>lg.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
272
+ `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
273
+ `),1}}async function cg(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let s=await t.probe(500);if(s.kind==="connected")return s;await n(200)}return t.probe(500)}async function dg(t,e,n=60,i=200){let{readFile:s}=await import("node:fs/promises");for(let a=0;a<n;a++){let d;try{d=await s(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!ts(u))return;await e(i)}}function BA(t){return new Promise(e=>setTimeout(e,t))}ne();function FA(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let n=Number(e[1]),i=Number(e[2]??0);return n<18||n===18&&i<4?"fatal":n<20?"warn":"ok"}function gg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=FA(t);if(i==="ok")return;let s=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${s} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
274
+ `),n(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${s},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
270
275
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
271
276
  npx -y coze-bridge@latest stop
272
277
  npx -y coze-bridge@latest connect
273
278
 
274
- `)}eg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Bl("warn");Jp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
279
+ `)}gg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Wl("warn");ug(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
275
280
  `),process.exit(1)});