coze-bridge 0.2.7-beta.2 → 0.2.7-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +95 -97
  2. package/package.json +7 -3
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 jm=Object.create;var Ma=Object.defineProperty;var Km=Object.getOwnPropertyDescriptor;var Wm=Object.getOwnPropertyNames;var $m=Object.getPrototypeOf,Vm=Object.prototype.hasOwnProperty;var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var it=(t,e)=>()=>(t&&(e=t(t=0)),e);var le=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ba=(t,e)=>{for(var n in e)Ma(t,n,{get:e[n],enumerable:!0})},Jm=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wm(e))!Vm.call(t,o)&&o!==n&&Ma(t,o,{get:()=>e[o],enumerable:!(i=Km(e,o))||i.enumerable});return t};var qt=(t,e,n)=>(n=t!=null?jm($m(t)):{},Jm(e||!t||!t.__esModule?Ma(n,"default",{value:t,enumerable:!0}):n,t));function Xe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ar=it(()=>{"use strict"});import{createWriteStream as Zm,mkdirSync as Ym,readdirSync as Xm,unlinkSync as Qm}from"node:fs";import{join as Cl}from"node:path";function Dn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function cr(t,e){return`${t}-${e}.log`}function Fa(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function eg(t,e,n){let i=c=>{let[l,u,h]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>n}function ws(t,e,n,i){let o;try{o=Xm(t)}catch{return}for(let c of o){let l=Fa(c,e);if(l&&eg(l,n,i))try{Qm(Cl(t,c))}catch{}}}var si,za=it(()=>{"use strict";si=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Dn(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{Ym(this.dir,{recursive:!0});let n=Zm(Cl(this.dir,cr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
- `)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&ws(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 tg,mkdirSync as ng}from"node:fs";import{join as rg}from"node:path";function Ol(t){let e=t.retentionDays??og,n=t.clock??(()=>Dn(new Date));ys={bridgeSink:new si(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new si(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();ws(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ws(t.agentLogsDir(o),"agent",i,e)}function ag(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Ll(t){Ua=t}function Nl(t){return dr[Ua]<=dr[t]}function Ml(t,e){let n=dr[t];return n===void 0?!0:n>=dr[e]}function bs(t){Dl={...t}}function Bl(t){let e=(u,h=2)=>String(u).padStart(h,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",o=Math.abs(n),c=e(Math.floor(o/60)),l=e(o%60);return`${Dn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function st(t,e,n,i,o){try{let c=`${JSON.stringify({ts:Bl(new Date),level:e,module:n,msg:i,...o})}
11
- `;ng(t,{recursive:!0}),tg(rg(t,cr("bridge",Dn(new Date))),c)}catch{}}function cg(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function _s(t,e,n,i,o){if(dr[t]<dr[Ua])return;let c=`${JSON.stringify({ts:Bl(new Date),level:t,module:e,msg:n,...Dl,...i})}
12
- `;if(ys){let l=cg(o,i),u=l?ag(ys,l):ys.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?sg.write(c):ig.write(c)}function K(t,e){return{debug:(n,i)=>_s("debug",t,n,i,e),info:(n,i)=>_s("info",t,n,i,e),warn:(n,i)=>_s("warn",t,n,i,e),error:(n,i)=>_s("error",t,n,i,e),child:n=>K(`${t}.${n}`,e),forAgent:n=>K(t,n)}}var dr,Ua,ig,sg,Dl,og,ys,ne=it(()=>{"use strict";ar();za();dr={debug:10,info:20,warn:30,error:40},Ua=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),ig=process.stdout,sg=process.stderr,Dl={},og=Xe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ys=null});var k,Ve=it(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Gl={};Ba(Gl,{ACP_WRAPPER_NPM_PACKAGES:()=>Es,_resetAcpInstallerForTests:()=>xg,_setBinaryPathCacheForTests:()=>pg,buildAcpSpawn:()=>ai,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>vs,pickWhichLine:()=>qa,probeAcpVersion:()=>hg,resolveAcpCommand:()=>Ul});import{readFileSync as Fl}from"node:fs";import{createRequire as dg}from"node:module";import{dirname as lg,resolve as ug}from"node:path";function qa(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(o=>o.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function fg(t){let e=zl.resolve(`${t.npmPackage}/package.json`),n=lg(e),i=JSON.parse(Fl(e,"utf8")),o=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!o)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return ug(n,o)}async function lr(t,e){let n=Ha[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=oi.get(t);if(i)return i;try{let o=fg(n);return oi.set(t,o),Ga.info("acp wrapper resolved",{framework:t,binary:n.binary,path:o}),o}catch(o){throw Ga.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(o)}),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:o})}}async function hg(t){let e=Ha[t];if(e)try{let n=zl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Fl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Ga.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function vs(t){return oi.get(t)}function Ul(t,e){if(e)return e;let n=vs(t);if(!n)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return n}function ai(t,e,n){if(e)return{command:e,args:[...n]};let i=Ul(t);return{command:process.execPath,args:[i,...n]}}function xg(){oi.clear()}function pg(t,e){oi.set(t,e)}var Ga,Ha,Es,zl,oi,ln=it(()=>{"use strict";Ve();ne();Ga=K("agents.acp-installer"),Ha={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Es=Object.values(Ha).filter(t=>t!==void 0).map(t=>t.npmPackage),zl=dg(import.meta.url),oi=new Map});import{chmod as gg,mkdir as wg,readFile as _g,rename as yg,rm as bg,writeFile as Eg}from"node:fs/promises";import{dirname as vg}from"node:path";async function ur(t){try{let e=await _g(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ht(t,e,n){await wg(vg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Eg(i,e,{encoding:"utf8",mode:n?.mode}),await yg(i,t),n?.mode!==void 0&&await gg(t,n.mode)}catch(o){throw await bg(i,{force:!0}).catch(()=>{}),o}}async function fr(t,e,n){await ht(t,`${JSON.stringify(e,null,2)}
14
- `,n)}var jt=it(()=>{"use strict"});import{promises as jl,readdirSync as Sg}from"node:fs";import{homedir as Ig}from"node:os";import{sep as Ag,join as Re,resolve as Kl}from"node:path";function Y(t){let e=t??Ig(),n=Re(e,".coze"),i=Re(n,"bridge"),o=Re(i,"lib"),c=Re(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Re(o,"index.js"),binDir:Re(i,"bin"),pidFile:Re(i,"bridge.pid"),portFile:Re(i,"bridge.port"),tokenFile:Re(i,"bridge.token"),patTokenFile:Re(i,"pat-token"),agentEnvFile:Re(i,"agent-env.json"),logFile:Re(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Re(c,"daemon-stdio.log"),installLock:Re(i,"install.lock"),configFile:Re(i,"config.json"),agentsRoot:Re(n,"agents")}}function Ue(t,e=Y()){let n=Re(e.agentsRoot,t);return{root:n,config:Re(n,"config.json"),workspace:Re(n,"workspace"),logs:Re(n,"logs")}}function Ss(t=Y()){try{return Sg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ci(t,e){let n=await jl.realpath(Kl(t)).catch(()=>null);if(!n)return!1;let i=await jl.realpath(Kl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?n.toLowerCase():n,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+Ag)}var Pe=it(()=>{"use strict"});var As={};Ba(As,{AGENT_CONFIG_FILE_MODE:()=>Is,enforceAgentConfigMode:()=>Rg,loadAgentConfig:()=>Se,persistAgentSessions:()=>di,persistAgentSkills:()=>li,saveAgentConfig:()=>Ge});import{chmod as kg,stat as Tg}from"node:fs/promises";function Se(t,e){return ur(Ue(t,e).config)}function Ge(t,e){return fr(Ue(t.agentId,e).config,t,{mode:Is})}async function Rg(t,e){if(process.platform==="win32")return;let n=Ue(t,e).config;try{let i=await Tg(n);if(!i.isFile())return;let o=i.mode&511;o!==Is&&(await kg(n,Is),Wl.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Wl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function di(t,e,n){let i=await Se(t,n);i&&(i.sessions=Object.fromEntries(e),await Ge(i,n))}async function li(t,e,n){let i=await Se(t,n);i&&(i.skills=e,await Ge(i,n))}var Wl,Is,Kt=it(()=>{"use strict";jt();ne();Pe();Wl=K("agent-config"),Is=384});var Wa=le((L2,Jl)=>{Jl.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 Ts=le(Yl=>{var Zl={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 Ng(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(Zl))Yl[t]=Ng(Zl[t])});var nu=le((M2,tu)=>{var Mg=xe("fs"),Me=xe("path"),Xl=Wa(),Bg=Ts(),Fg=typeof process=="object"&&process.platform==="win32",Ql=t=>typeof t=="object"&&t!==null,eu=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 Ie(t){this.sep=Me.sep,this.fs=Mg,Ql(t)&&Ql(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}tu.exports=Ie;Ie.prototype.makeDir=function(t){let e=this;function n(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var l;try{l=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(l&&l.isFile())throw Bg.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Ie.prototype.writeFileTo=function(t,e,n,i){let o=this;if(o.fs.existsSync(t)){if(!n)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var l=Me.dirname(t);o.fs.existsSync(l)||o.makeDir(l);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ie.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!n)return o(!1);c.fs.stat(t,function(u,h){if(l&&h.isDirectory())return o(!1);var x=Me.dirname(t);c.fs.exists(x,function(m){m||c.makeDir(x),c.fs.open(t,"w",438,function(w,v){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ie.prototype.findFiles=function(t){let e=this;function n(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let h=Me.join(i,u),x=e.fs.statSync(h);(!o||o.test(h))&&l.push(Me.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(l=l.concat(n(h,o,c)))}),l}return n(t,void 0,!0)};Ie.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(o,c){if(o)return e(o);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=Me.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Me.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--l||e(null,i)}):--l||e(null,i))})})})};Ie.prototype.getAttributes=function(){};Ie.prototype.setAttributes=function(){};Ie.crc32update=function(t,e){return eu[(t^e)&255]^t>>>8};Ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ie.crc32update(n,t[i++]);return~n>>>0};Ie.methodToString=function(t){switch(t){case Xl.STORED:return"STORED ("+t+")";case Xl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ie.canonical=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.join(".",e)};Ie.zipnamefix=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.posix.join(".",e)};Ie.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ie.sanitize=function(t,e){t=Me.resolve(Me.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var c=Me.normalize(Me.join(t,n.slice(i,o).join(Me.sep)));if(c.indexOf(t)===0)return c}return Me.normalize(Me.join(t,Me.basename(e)))};Ie.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ie.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Ie.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ie.fromDate2DOS=function(t){let e=0,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};Ie.isWin=Fg;Ie.crcTable=eu});var iu=le((B2,ru)=>{var zg=xe("path");ru.exports=function(t,{fs:e}){var n=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(o=e.statSync(n),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=zg.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 ou=le((F2,su)=>{su.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=le((z2,xr)=>{xr.exports=nu();xr.exports.Constants=Wa();xr.exports.Errors=Ts();xr.exports.FileAttr=iu();xr.exports.decoder=ou()});var cu=le((U2,au)=>{var un=pr(),j=un.Constants;au.exports=function(){var t=20,e=10,n=0,i=0,o=0,c=0,l=0,u=0,h=0,x=0,m=0,w=0,v=0,_=0,E=0;t|=un.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 o=un.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 un.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=un.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=A(b)},get timeHighByte(){return O(o>>>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 h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return 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+m},get realDataOffset(){return E+j.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var D=b.slice(E,E+j.LOCHDR);if(D.readUInt32LE(0)!==j.LOCSIG)throw un.Errors.INVALID_LOC();I.version=D.readUInt16LE(j.LOCVER),I.flags=D.readUInt16LE(j.LOCFLG),I.flags_desc=(I.flags&j.FLG_DESC)>0,I.method=D.readUInt16LE(j.LOCHOW),I.time=D.readUInt32LE(j.LOCTIM),I.crc=D.readUInt32LE(j.LOCCRC),I.compressedSize=D.readUInt32LE(j.LOCSIZ),I.size=D.readUInt32LE(j.LOCLEN),I.fnameLen=D.readUInt16LE(j.LOCNAM),I.extraLen=D.readUInt16LE(j.LOCEXT);let L=E+j.LOCHDR+I.fnameLen,G=L+I.extraLen;return b.slice(L,G)},loadFromBinary:function(b){if(b.length!==j.CENHDR||b.readUInt32LE(0)!==j.CENSIG)throw un.Errors.INVALID_CEN();t=b.readUInt16LE(j.CENVEM),e=b.readUInt16LE(j.CENVER),n=b.readUInt16LE(j.CENFLG),i=b.readUInt16LE(j.CENHOW),o=b.readUInt32LE(j.CENTIM),c=b.readUInt32LE(j.CENCRC),l=b.readUInt32LE(j.CENSIZ),u=b.readUInt32LE(j.CENLEN),h=b.readUInt16LE(j.CENNAM),x=b.readUInt16LE(j.CENEXT),m=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(o,j.LOCTIM),b.writeUInt32LE(c,j.LOCCRC),b.writeUInt32LE(l,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+m);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(o,j.CENTIM),b.writeUInt32LE(c,j.CENCRC),b.writeUInt32LE(l,j.CENSIZ),b.writeUInt32LE(u,j.CENLEN),b.writeUInt16LE(h,j.CENNAM),b.writeUInt16LE(x,j.CENEXT),b.writeUInt16LE(m,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(D){return D+" bytes"};return{made:t,version:e,flags:n,method:un.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(l),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(m),diskNumStart:w,inAttr:v,attr:_,offset:E,centralHeaderSize:b(j.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var lu=le((G2,du)=>{var mr=pr(),be=mr.Constants;du.exports=function(){var t=0,e=0,n=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return n},set size(c){n=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return be.ENDHDR+o},loadFromBinary:function(c){if((c.length!==be.ENDHDR||c.readUInt32LE(0)!==be.ENDSIG)&&(c.length<be.ZIP64HDR||c.readUInt32LE(0)!==be.ZIP64SIG))throw mr.Errors.INVALID_END();c.readUInt32LE(0)===be.ENDSIG?(t=c.readUInt16LE(be.ENDSUB),e=c.readUInt16LE(be.ENDTOT),n=c.readUInt32LE(be.ENDSIZ),i=c.readUInt32LE(be.ENDOFF),o=c.readUInt16LE(be.ENDCOM)):(t=mr.readBigUInt64LE(c,be.ZIP64SUB),e=mr.readBigUInt64LE(c,be.ZIP64TOT),n=mr.readBigUInt64LE(c,be.ZIP64SIZE),i=mr.readBigUInt64LE(c,be.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(be.ENDHDR+o);return c.writeUInt32LE(be.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,be.ENDSUB),c.writeUInt16LE(e,be.ENDTOT),c.writeUInt32LE(n,be.ENDSIZ),c.writeUInt32LE(i,be.ENDOFF),c.writeUInt16LE(o,be.ENDCOM),c.fill(" ",be.ENDHDR),c},toJSON:function(){let c=function(l,u){let h=l.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Va=le($a=>{$a.EntryHeader=cu();$a.MainHeader=lu()});var fu=le((q2,uu)=>{uu.exports=function(t){var e=xe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),c=[],l=0;o.on("data",function(u){c.push(u),l+=u.length}),o.on("end",function(){var u=Buffer.alloc(l),h=0;u.fill(0);for(var x=0;x<c.length;x++){var m=c[x];m.copy(u,h),h+=m.length}i&&i(u)}),o.end(t)}}}});var xu=le((j2,hu)=>{var Ug=+(process.versions?process.versions.node:"").split(".")[0]||0;hu.exports=function(t,e){var n=xe("zlib");let i=Ug>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var c=n.createInflateRaw(i),l=[],u=0;c.on("data",function(h){l.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var m=0;m<l.length;m++){var w=l[m];w.copy(h,x),x+=w.length}o&&o(h)}),c.end(t)}}}});var _u=le((K2,wu)=>{"use strict";var{randomFillSync:pu}=xe("crypto"),Gg=Ts(),Hg=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),gu=(t,e)=>Math.imul(t,e)>>>0,mu=(t,e)=>Hg[(t^e)&255]^t>>>8,ui=()=>typeof pu=="function"?pu(Buffer.alloc(12)):ui.node();ui.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 Rs={genSalt:ui};function Ps(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])}Ps.prototype.updateKeys=function(t){let e=this.keys;return e[0]=mu(e[0],t),e[1]+=e[0]&255,e[1]=gu(e[1],134775813)+1,e[2]=mu(e[2],e[1]>>>24),t};Ps.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return gu(t,t^1)>>8&255};function qg(t){let e=new Ps(t);return function(n){let i=Buffer.alloc(n.length),o=0;for(let c of n)i[o++]=e.updateKeys(c^e.next());return i}}function jg(t){let e=new Ps(t);return function(n,i,o=0){i||(i=Buffer.alloc(n.length));for(let c of n){let l=e.next();i[o++]=c^l,e.updateKeys(c)}return i}}function Kg(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=qg(n),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Gg.WRONG_PASSWORD();return i(t.slice(12))}function Wg(t){Buffer.isBuffer(t)&&t.length>=12?Rs.genSalt=function(){return t.slice(0,12)}:t==="node"?Rs.genSalt=ui.node:Rs.genSalt=ui}function $g(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=jg(n),c=Rs.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return o(c,l),o(t,l,12)}wu.exports={decrypt:Kg,encrypt:$g,_salter:Wg}});var yu=le(Cs=>{Cs.Deflater=fu();Cs.Inflater=xu();Cs.ZipCrypto=_u()});var Za=le(($2,bu)=>{var ue=pr(),Vg=Va(),Ae=ue.Constants,Ja=yu();bu.exports=function(t,e){var n=new Vg.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:ue.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(ue.crc32(b)!==n.localHeader.crc)return!1}else{let D={},L=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(L)==Ae.LOCSIG||e.readUInt32LE(L)==Ae.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(L)==Ae.EXTSIG)D.crc=e.readUInt32LE(L+Ae.EXTCRC),D.compressedSize=e.readUInt32LE(L+Ae.EXTSIZ),D.size=e.readUInt32LE(L+Ae.EXTLEN);else if(e.readUInt16LE(L+12)===19280)D.crc=e.readUInt32LE(L+Ae.EXTCRC-4),D.compressedSize=e.readUInt32LE(L+Ae.EXTSIZ-4),D.size=e.readUInt32LE(L+Ae.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==n.compressedSize||D.size!==n.size||D.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(b)!==D.crc)return!1}return!0}function E(b,D,L){if(typeof D>"u"&&typeof b=="string"&&(L=b,b=void 0),c)return b&&D&&D(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var G=v();if(G.length===0)return b&&D&&D(G),G;if(n.encrypted){if(typeof L!="string"&&!Buffer.isBuffer(L))throw ue.Errors.INVALID_PASS_PARAM();G=Ja.ZipCrypto.decrypt(G,n,L)}var U=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(G.copy(U),_(U))return b&&D&&D(U),U;throw b&&D&&D(U,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var Z=new Ja.Inflater(G,n.size);if(b)Z.inflateAsync(function(J){J.copy(J,0),D&&(_(J)?D(J):D(J,ue.Errors.BAD_CRC()))});else{if(Z.inflate(U).copy(U,0),!_(U))throw ue.Errors.BAD_CRC(`"${w.decode(i)}"`);return U}break;default:throw b&&D&&D(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(b,D){if((!l||!l.length)&&Buffer.isBuffer(e))return b&&D&&D(v()),v();if(l.length&&!c){var L;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,L=Buffer.alloc(l.length),l.copy(L),b&&D&&D(L),L;default:case ue.Constants.DEFLATED:var G=new Ja.Deflater(l);if(b)G.deflateAsync(function(Z){L=Buffer.alloc(Z.length),n.compressedSize=Z.length,Z.copy(L),D&&D(L)});else{var U=G.deflate();return n.compressedSize=U.length,U}G=null;break}}else if(b&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,D){return ue.readBigUInt64LE(b,D)}function T(b){try{for(var D=0,L,G,U;D+4<b.length;)L=b.readUInt16LE(D),D+=2,G=b.readUInt16LE(D),D+=2,U=b.slice(D,D+G),D+=G,Ae.ID_ZIP64===L&&O(U)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function O(b){var D,L,G,U;b.length>=Ae.EF_ZIP64_SCOMP&&(D=A(b,Ae.EF_ZIP64_SUNCOMP),n.size===Ae.EF_ZIP64_OR_32&&(n.size=D)),b.length>=Ae.EF_ZIP64_RHO&&(L=A(b,Ae.EF_ZIP64_SCOMP),n.compressedSize===Ae.EF_ZIP64_OR_32&&(n.compressedSize=L)),b.length>=Ae.EF_ZIP64_DSN&&(G=A(b,Ae.EF_ZIP64_RHO),n.offset===Ae.EF_ZIP64_OR_32&&(n.offset=G)),b.length>=Ae.EF_ZIP64_DSN+4&&(U=b.readUInt32LE(Ae.EF_ZIP64_DSN),n.diskNumStart===Ae.EF_ZIP64_OR_16&&(n.diskNumStart=U))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ue.toBuffer(b,w.encode);var D=i[i.length-1];c=D===47||D===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,n.extraLength=b.length,T(b)},get comment(){return w.decode(o)},set comment(b){if(o=ue.toBuffer(b,w.encode),n.commentLength=o.length,o.length>65535)throw ue.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=ue.toBuffer(b,ue.decoder.encode),!c&&l.length?(n.size=l.length,n.method=ue.Constants.DEFLATED,n.crc=ue.crc32(b),n.changed=!0):n.method=ue.Constants.STORED},getData:function(b){return n.changed?l:E(!1,null,b)},getDataAsync:function(b,D){n.changed?b(l):E(!0,b,D)},set attr(b){n.attr=b},get attr(){return n.attr},set header(b){n.loadFromBinary(b)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var b=n.centralHeaderToBinary(),D=ue.Constants.CENHDR;return i.copy(b,D),D+=i.length,u.copy(b,D),D+=n.extraLength,o.copy(b,D),b},packLocalHeader:function(){let b=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let D=n.localHeaderToBinary(),L=Buffer.alloc(D.length+i.length+n.extraLocalLength);return D.copy(L,b),b+=D.length,i.copy(L,b),b+=i.length,h.copy(L,b),b+=h.length,L},toJSON:function(){let b=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:b(e),data:b(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Su=le((V2,vu)=>{var Eu=Za(),Jg=Va(),Je=pr();vu.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),c=new Jg.MainHeader,l=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:w}=x;t?E(x.readEntries):l=!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 D=O.slice(0,b+1).join("/")+"/";A.add(D)}}for(let T of A)if(!(T in i)){let O=new Eu(x);O.entryName=T,O.attr=16,O.temporary=!0,n.push(O),i[O.entryName]=O,h.add(O)}}function _(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(c.diskEntries);for(var A=c.offset,T=0;T<n.length;T++){var O=A,b=new Eu(x,t);b.header=t.slice(O,O+=Je.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-Je.Constants.ENDHDR,O=Math.max(0,T-65535),b=O,D=t.length,L=-1,G=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(O=0),T;T>=b;T--)if(t[T]===80){if(t.readUInt32LE(T)===Je.Constants.ENDSIG){L=T,G=T,D=T+Je.Constants.ENDHDR,b=T-Je.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Je.Constants.END64SIG){b=O;continue}if(t.readUInt32LE(T)===Je.Constants.ZIP64SIG){L=T,D=T+Je.readBigUInt64LE(t,T+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(L==-1)throw Je.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(L,D)),c.commentLength&&(o=t.slice(G+Je.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!m&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return l||_(),n.filter(A=>!h.has(A))},get comment(){return w.decode(o)},set comment(A){o=Je.toBuffer(A,w.encode),c.commentLength=o.length},getEntryCount:function(){return l?n.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||_(),i[A]||null},setEntry:function(A){l||_(),n.push(A),i[A.entryName]=A,c.totalEntries=n.length},deleteFile:function(A,T=!0){l||_();let O=i[A];this.getEntryChildren(O,T).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||_();let T=i[A],O=n.indexOf(T);O>=0&&(n.splice(O,1),delete i[A],c.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(l||_(),typeof A=="object")if(A.isDirectory&&T){let O=[],b=A.entryName;for(let D of n)D.entryName.startsWith(b)&&O.push(D);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(){l||_(),I();let A=[],T=[],O=0,b=0;c.size=0,c.offset=0;let D=0;for(let U of this.entries){let Z=U.getCompressedData();U.header.offset=b;let J=U.packLocalHeader(),ie=J.length+Z.length;b+=ie,A.push(J),A.push(Z);let Q=U.packCentralHeader();T.push(Q),c.size+=Q.length,O+=ie+Q.length,D++}O+=c.mainHeaderSize,c.offset=b,c.totalEntries=D,b=0;let L=Buffer.alloc(O);for(let U of A)U.copy(L,b),b+=U.length;for(let U of T)U.copy(L,b),b+=U.length;let G=c.toBinary();return o&&o.copy(G,Je.Constants.ENDHDR),G.copy(L,b),t=L,l=!1,L},toAsyncBuffer:function(A,T,O,b){try{l||_(),I();let D=[],L=[],G=0,U=0,Z=0;c.size=0,c.offset=0;let J=function(ie){if(ie.length>0){let Q=ie.shift(),ce=Q.entryName+Q.extra.toString();O&&O(ce),Q.getCompressedDataAsync(function(de){b&&b(ce),Q.header.offset=U;let P=Q.packLocalHeader(),H=P.length+de.length;U+=H,D.push(P),D.push(de);let W=Q.packCentralHeader();L.push(W),c.size+=W.length,G+=H+W.length,Z++,J(ie)})}else{G+=c.mainHeaderSize,c.offset=U,c.totalEntries=Z,U=0;let Q=Buffer.alloc(G);D.forEach(function(de){de.copy(Q,U),U+=de.length}),L.forEach(function(de){de.copy(Q,U),U+=de.length});let ce=c.toBinary();o&&o.copy(ce,Je.Constants.ENDHDR),ce.copy(Q,U),t=Q,l=!1,A(Q)}};J(Array.from(this.entries))}catch(D){T(D)}}}}});var ku=le((J2,Au)=>{var ve=pr(),Ee=xe("path"),Zg=Za(),Yg=Su(),On=(...t)=>ve.findLast(t,e=>typeof e=="boolean"),Iu=(...t)=>ve.findLast(t,e=>typeof e=="string"),Xg=(...t)=>ve.findLast(t,e=>typeof e=="function"),Qg={noSort:!1,readEntries:!1,method:ve.Constants.NONE,fs:null};Au.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Qg);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=ve.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ve(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ve.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ve.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw ve.Errors.INVALID_FILENAME();let c=new Yg(n,i),{canonical:l,sanitize:u,zipnamefix:h}=ve;function x(_){if(_&&c){var E;if(typeof _=="string"&&(E=c.getEntry(Ee.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=c.getEntry(_.entryName)),E)return E}return null}function m(_){let{join:E,normalize:I,sep:A}=Ee.posix;return E(Ee.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===o.sep?o.sep:"",Ee.relative(_,E)+I};return{readFile:function(_,E){var I=x(_);return I&&I.getData(E)||null},childCount:function(_){let E=x(_);if(E)return c.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&&c.deleteFile(I.entryName,E)},deleteEntry:function(_){var E=x(_);E&&c.deleteEntry(E.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,E){var I=x(_);I&&(I.comment=E)},getZipEntryComment:function(_){var E=x(_);return E&&E.comment||""},updateFile:function(_,E){var I=x(_);I&&I.setData(E)},addLocalFile:function(_,E,I,A){if(o.fs.existsSync(_)){E=E?m(E):"";let T=Ee.win32.basename(Ee.win32.normalize(_));E+=I||T;let O=o.fs.statSync(_),b=O.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);O.isDirectory()&&(E+=o.sep),this.addFile(E,b,A,O)}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let I=Ee.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:O}=_,b=this;o.fs.stat(I,function(D,L){if(D)return E(D,!1);T=T?m(T):"";let G=Ee.win32.basename(Ee.win32.normalize(I));if(T+=O||G,L.isFile())o.fs.readFile(I,function(U,Z){return U?E(U,!1):(b.addFile(T,Z,A,L),setImmediate(E,void 0,!0))});else if(L.isDirectory())return T+=o.sep,b.addFile(T,Buffer.alloc(0),A,L),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,I){if(I=w(I),E=E?m(E):"",_=Ee.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let O of A){let b=Ee.join(E,v(_,O));I(b)&&T.addLocalFile(O,Ee.dirname(b))}}else throw ve.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,I,A){A=w(A),I=I?m(I):"",_=Ee.normalize(_);var T=this;o.fs.open(_,"r",function(O){if(O&&O.code==="ENOENT")E(void 0,ve.Errors.FILE_NOT_FOUND(_));else if(O)E(void 0,O);else{var b=o.findFiles(_),D=-1,L=function(){if(D+=1,D<b.length){var G=b[D],U=v(_,G).split("\\").join("/");U=U.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(U)?o.fs.stat(G,function(Z,J){Z&&E(void 0,Z),J.isFile()?o.fs.readFile(G,function(ie,Q){ie?E(void 0,ie):(T.addFile(I+U,Q,"",J),L())}):(T.addFile(I+U+"/",Buffer.alloc(0),"",J),L())}):process.nextTick(()=>{L()})}else E(!0,void 0)};L()}})},addLocalFolderAsync2:function(_,E){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Ee.resolve(m(_.localPath));let{zipPath:A,filter:T,namefix:O}=_;T instanceof RegExp?T=(function(L){return function(G){return L.test(G)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?m(A):"",O=="latin1"&&(O=L=>L.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof O!="function"&&(O=L=>L);let b=L=>Ee.join(A,O(v(localPath,L))),D=L=>Ee.win32.basename(Ee.win32.normalize(O(L)));o.fs.open(localPath,"r",function(L){L&&L.code==="ENOENT"?E(void 0,ve.Errors.FILE_NOT_FOUND(localPath)):L?E(void 0,L):o.findFilesAsync(localPath,function(G,U){if(G)return E(G);U=U.filter(Z=>T(b(Z))),U.length||E(void 0,!1),setImmediate(U.reverse().reduce(function(Z,J){return function(ie,Q){if(ie||Q===!1)return setImmediate(Z,ie,!1);I.addLocalFileAsync({localPath:J,zipPath:Ee.dirname(b(J)),zipName:D(J)},Z)}},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 Zg(i),T.entryName=_),T.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(T.header.time=A.mtime);var D=T.isDirectory?16:0;let L=T.isDirectory?16384:32768;return b?L|=4095&A.mode:typeof A=="number"?L|=4095&A:L|=T.isDirectory?493:420,D=(D|L<<16)>>>0,T.attr=D,T.setData(E),O||c.setEntry(T),T},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,E,I,A,T,O){A=On(!1,A),T=On(!1,T),I=On(!0,I),O=Iu(T,O);var b=x(_);if(!b)throw ve.Errors.NO_ENTRY();var D=l(b.entryName),L=u(E,O&&!b.isDirectory?O:I?D:Ee.basename(D));if(b.isDirectory){var G=c.getEntryChildren(b);return G.forEach(function(J){if(J.isDirectory)return;var ie=J.getData();if(!ie)throw ve.Errors.CANT_EXTRACT_FILE();var Q=l(J.entryName),ce=u(E,I?Q:Ee.basename(Q));let de=T?J.header.fileAttr:void 0;o.writeFileTo(ce,ie,A,de)}),!0}var U=b.getData(c.password);if(!U)throw ve.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(L)&&!A)throw ve.Errors.CANT_OVERRIDE();let Z=T?_.header.fileAttr:void 0;return o.writeFileTo(L,U,A,Z),!0},test:function(_){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,E,I,A){if(I=On(!1,I),A=Iu(I,A),E=On(!1,E),!c)throw ve.Errors.NO_ZIP();c.entries.forEach(function(T){var O=u(_,l(T.entryName));if(T.isDirectory){o.makeDir(O);return}var b=T.getData(A);if(!b)throw ve.Errors.CANT_EXTRACT_FILE();let D=I?T.header.fileAttr:void 0;o.writeFileTo(O,b,E,D);try{o.fs.utimesSync(O,T.header.time,T.header.time)}catch{throw ve.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,I,A){if(A=Xg(E,I,A),I=On(!1,I),E=On(!1,E),!A)return new Promise((L,G)=>{this.extractAllToAsync(_,E,I,function(U){U?G(U):L(this)})});if(!c){A(ve.Errors.NO_ZIP());return}_=Ee.resolve(_);let T=L=>u(_,Ee.normalize(l(L.entryName))),O=(L,G)=>new Error(L+': "'+G+'"'),b=[],D=[];c.entries.forEach(L=>{L.isDirectory?b.push(L):D.push(L)});for(let L of b){let G=T(L),U=I?L.header.fileAttr:void 0;try{o.makeDir(G),U&&o.fs.chmodSync(G,U),o.fs.utimesSync(G,L.header.time,L.header.time)}catch{A(O("Unable to create folder",G))}}D.reverse().reduce(function(L,G){return function(U){if(U)L(U);else{let Z=Ee.normalize(l(G.entryName)),J=u(_,Z);G.getDataAsync(function(ie,Q){if(Q)L(Q);else if(!ie)L(ve.Errors.CANT_EXTRACT_FILE());else{let ce=I?G.header.fileAttr:void 0;o.writeFileToAsync(J,ie,E,ce,function(de){de||L(O("Unable to write file",J)),o.fs.utimes(J,G.header.time,G.header.time,function(P){P?L(O("Unable to set times",J)):L()})})}})}}},A)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((T,O)=>{!_&&i.filename&&(_=i.filename),_||O("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let D=L=>L?T(L):O("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,I,A,D)},O)})},toBufferPromise:function(){return new Promise((_,E)=>{c.toAsyncBuffer(_,E)})},toBuffer:function(_,E,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,E,I,A),null):c.compressToBuffer()}}}});import{execFile as sy,spawn as oy,spawnSync as hk}from"node:child_process";import{promisify as ay}from"node:util";function dy(t){if(process.platform!=="win32")return!1;if($f.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace($f,"").toLowerCase();return cy.has(n)}function Vf(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return dy(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function at(t,e=[],n={}){return oy(t,e,Vf(t,n))}function Jf(t,e=[],n={}){return ly(t,e,Vf(t,n))}var cy,$f,ly,Xt=it(()=>{"use strict";cy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),$f=/\.(cmd|bat|ps1)$/i;ly=ay(sy)});var en=le((bC,jh)=>{"use strict";var Hh=["nodebuffer","arraybuffer","fragments"],qh=typeof Blob<"u";qh&&Hh.push("blob");jh.exports={BINARY_TYPES:Hh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ts=le((EC,Ho)=>{"use strict";var{EMPTY_BUFFER:tv}=en(),kd=Buffer[Symbol.species];function nv(t,e){if(t.length===0)return tv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];n.set(c,i),i+=c.length}return i<e?new kd(n.buffer,n.byteOffset,i):n}function Kh(t,e,n,i,o){for(let c=0;c<o;c++)n[i+c]=t[c]^e[c&3]}function Wh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function rv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Td(t){if(Td.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new kd(t):ArrayBuffer.isView(t)?e=new kd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Td.readOnly=!1),e}Ho.exports={concat:nv,mask:Kh,toArrayBuffer:rv,toBuffer:Td,unmask:Wh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Ho.exports.mask=function(e,n,i,o,c){c<48?Kh(e,n,i,o,c):t.mask(e,n,i,o,c)},Ho.exports.unmask=function(e,n){e.length<32?Wh(e,n):t.unmask(e,n)}}catch{}});var Jh=le((vC,Vh)=>{"use strict";var $h=Symbol("kDone"),Rd=Symbol("kRun"),Pd=class{constructor(e){this[$h]=()=>{this.pending--,this[Rd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Rd]()}[Rd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$h])}}};Vh.exports=Pd});var qr=le((SC,Qh)=>{"use strict";var ns=xe("zlib"),Zh=ts(),iv=Jh(),{kStatusCode:Yh}=en(),sv=Buffer[Symbol.species],ov=Buffer.from([0,0,255,255]),jo=Symbol("permessage-deflate"),tn=Symbol("total-length"),Gr=Symbol("callback"),Tn=Symbol("buffers"),Hr=Symbol("error"),qo,Cd=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,!qo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;qo=new iv(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[Gr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let o=n[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=o})}),e}decompress(e,n,i){qo.add(o=>{this._decompress(e,n,(c,l)=>{o(),i(c,l)})})}compress(e,n,i){qo.add(o=>{this._compress(e,n,(c,l)=>{o(),i(c,l)})})}_decompress(e,n,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?ns.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=ns.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[jo]=this,this._inflate[tn]=0,this._inflate[Tn]=[],this._inflate.on("error",cv),this._inflate.on("data",Xh)}this._inflate[Gr]=i,this._inflate.write(e),n&&this._inflate.write(ov),this._inflate.flush(()=>{let c=this._inflate[Hr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Zh.concat(this._inflate[Tn],this._inflate[tn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[tn]=0,this._inflate[Tn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,n,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?ns.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=ns.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[tn]=0,this._deflate[Tn]=[],this._deflate.on("data",av)}this._deflate[Gr]=i,this._deflate.write(e),this._deflate.flush(ns.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Zh.concat(this._deflate[Tn],this._deflate[tn]);n&&(c=new sv(c.buffer,c.byteOffset,c.length-4)),this._deflate[Gr]=null,this._deflate[tn]=0,this._deflate[Tn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Qh.exports=Cd;function av(t){this[Tn].push(t),this[tn]+=t.length}function Xh(t){if(this[tn]+=t.length,this[jo]._maxPayload<1||this[tn]<=this[jo]._maxPayload){this[Tn].push(t);return}this[Hr]=new RangeError("Max payload size exceeded"),this[Hr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hr][Yh]=1009,this.removeListener("data",Xh),this.reset()}function cv(t){if(this[jo]._inflate=null,this[Hr]){this[Gr](this[Hr]);return}t[Yh]=1007,this[Gr](t)}});var jr=le((IC,Ko)=>{"use strict";var{isUtf8:ex}=xe("buffer"),{hasBlob:dv}=en(),lv=[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 uv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Dd(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 fv(t){return dv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ko.exports={isBlob:fv,isValidStatusCode:uv,isValidUTF8:Dd,tokenChars:lv};if(ex)Ko.exports.isValidUTF8=function(t){return t.length<24?Dd(t):ex(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Ko.exports.isValidUTF8=function(e){return e.length<32?Dd(e):t(e)}}catch{}});var Bd=le((AC,ax)=>{"use strict";var{Writable:hv}=xe("stream"),tx=qr(),{BINARY_TYPES:xv,EMPTY_BUFFER:nx,kStatusCode:pv,kWebSocket:mv}=en(),{concat:Od,toArrayBuffer:gv,unmask:wv}=ts(),{isValidStatusCode:_v,isValidUTF8:rx}=jr(),Wo=Buffer[Symbol.species],wt=0,ix=1,sx=2,ox=3,Ld=4,Nd=5,$o=6,Md=class extends hv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||xv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[mv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=wt}_write(e,n,i){if(this._opcode===8&&this._state==wt)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Wo(i.buffer,i.byteOffset+e,i.length-e),new Wo(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=n.length-e;e>=i.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new Wo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case wt:this.getInfo(e);break;case ix:this.getPayloadLength16(e);break;case sx:this.getPayloadLength64(e);break;case ox:this.getMask();break;case Ld:this.getData(e);break;case Nd:case $o:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(n[0]&64)===64;if(i&&!this._extensions[tx.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=ix:this._payloadLength===127?this._state=sx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=ox:this._state=Ld}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ld}getData(e){let n=nx;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&&wv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Nd,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[tx.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return n(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(l);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let l=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(l);return}this._fragments.push(c)}this.dataMessage(n),this._state===wt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=wt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Od(i,n):this._binaryType==="arraybuffer"?o=gv(Od(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=wt):(this._state=$o,setImmediate(()=>{this.emit("message",o,!0),this._state=wt,this.startLoop(e)}))}else{let o=Od(i,n);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Nd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=wt):(this._state=$o,setImmediate(()=>{this.emit("message",o,!1),this._state=wt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,nx),this.end();else{let i=e.readUInt16BE(0);if(!_v(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(c);return}let o=new Wo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=wt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=wt):(this._state=$o,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=wt,this.startLoop(n)}))}createError(e,n,i,o,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(l,this.createError),l.code=c,l[pv]=o,l}};ax.exports=Md});var Ud=le((TC,lx)=>{"use strict";var{Duplex:kC}=xe("stream"),{randomFillSync:yv}=xe("crypto"),{types:{isUint8Array:bv}}=xe("util"),cx=qr(),{EMPTY_BUFFER:Ev,kWebSocket:vv,NOOP:Sv}=en(),{isBlob:Kr,isValidStatusCode:Iv}=jr(),{mask:dx,toBuffer:Yn}=ts(),_t=Symbol("kByteLength"),Av=Buffer.alloc(4),Vo=8*1024,Xn,Wr=Vo,Tt=0,kv=1,Tv=2,Fd=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Tt,this.onerror=Sv,this[vv]=void 0}static frame(e,n){let i,o=!1,c=2,l=!1;n.mask&&(i=n.maskBuffer||Av,n.generateMask?n.generateMask(i):(Wr===Vo&&(Xn===void 0&&(Xn=Buffer.alloc(Vo)),yv(Xn,0,Vo),Wr=0),i[0]=Xn[Wr++],i[1]=Xn[Wr++],i[2]=Xn[Wr++],i[3]=Xn[Wr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!n.mask||l)&&n[_t]!==void 0?u=n[_t]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.readOnly&&!l);let h=u;u>=65536?(c+=8,h=127):u>125&&(c+=2,h=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],l?[x,e]:o?(dx(e,i,x,c,u),[x]):(dx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let c;if(e===void 0)c=Ev;else{if(typeof e!="number"||!Iv(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");if(c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof n=="string")c.write(n,2);else if(bv(n))c.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let l={[_t]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Tt?this.enqueue([this.dispatch,c,!1,l,o]):this.sendFrame(t.frame(c,l),o)}ping(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Kr(e)?(o=e.size,c=!1):(e=Yn(e),o=e.length,c=Yn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Kr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Kr(e)?(o=e.size,c=!1):(e=Yn(e),o=e.length,c=Yn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Kr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,n,i){let o=this._extensions[cx.extensionName],c=n.binary?2:1,l=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Kr(e)?(u=e.size,h=!1):(e=Yn(e),u=e.length,h=Yn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=o._threshold),this._compress=l):(l=!1,c=0),n.fin&&(this._firstFragment=!0);let x={[_t]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:l};Kr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Tt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[_t],this._state=Tv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(zd,this,u,o);return}this._bufferedBytes-=i[_t];let l=Yn(c);n?this.dispatch(l,n,i,o):(this._state=Tt,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(Rv,this,c,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[cx.extensionName];this._bufferedBytes+=i[_t],this._state=kv,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");zd(this,h,o);return}this._bufferedBytes-=i[_t],this._state=Tt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_t],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_t],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};lx.exports=Fd;function zd(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function Rv(t,e,n){zd(t,e,n),t.onerror(e)}});var yx=le((RC,_x)=>{"use strict";var{kForOnEventAttribute:rs,kListener:Gd}=en(),ux=Symbol("kCode"),fx=Symbol("kData"),hx=Symbol("kError"),xx=Symbol("kMessage"),px=Symbol("kReason"),$r=Symbol("kTarget"),mx=Symbol("kType"),gx=Symbol("kWasClean"),nn=class{constructor(e){this[$r]=null,this[mx]=e}get target(){return this[$r]}get type(){return this[mx]}};Object.defineProperty(nn.prototype,"target",{enumerable:!0});Object.defineProperty(nn.prototype,"type",{enumerable:!0});var Qn=class extends nn{constructor(e,n={}){super(e),this[ux]=n.code===void 0?0:n.code,this[px]=n.reason===void 0?"":n.reason,this[gx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ux]}get reason(){return this[px]}get wasClean(){return this[gx]}};Object.defineProperty(Qn.prototype,"code",{enumerable:!0});Object.defineProperty(Qn.prototype,"reason",{enumerable:!0});Object.defineProperty(Qn.prototype,"wasClean",{enumerable:!0});var Vr=class extends nn{constructor(e,n={}){super(e),this[hx]=n.error===void 0?null:n.error,this[xx]=n.message===void 0?"":n.message}get error(){return this[hx]}get message(){return this[xx]}};Object.defineProperty(Vr.prototype,"error",{enumerable:!0});Object.defineProperty(Vr.prototype,"message",{enumerable:!0});var is=class extends nn{constructor(e,n={}){super(e),this[fx]=n.data===void 0?null:n.data}get data(){return this[fx]}};Object.defineProperty(is.prototype,"data",{enumerable:!0});var Pv={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[rs]&&o[Gd]===e&&!o[rs])return;let i;if(t==="message")i=function(c,l){let u=new is("message",{data:l?c:c.toString()});u[$r]=this,Jo(e,this,u)};else if(t==="close")i=function(c,l){let u=new Qn("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[$r]=this,Jo(e,this,u)};else if(t==="error")i=function(c){let l=new Vr("error",{error:c,message:c.message});l[$r]=this,Jo(e,this,l)};else if(t==="open")i=function(){let c=new nn("open");c[$r]=this,Jo(e,this,c)};else return;i[rs]=!!n[rs],i[Gd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Gd]===e&&!n[rs]){this.removeListener(t,n);break}}};_x.exports={CloseEvent:Qn,ErrorEvent:Vr,Event:nn,EventTarget:Pv,MessageEvent:is};function Jo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Zo=le((PC,bx)=>{"use strict";var{tokenChars:ss}=jr();function zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Cv(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,c=!1,l,u,h=-1,x=-1,m=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),l===void 0)if(m===-1&&ss[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);x===44?(zt(e,_,n),n=Object.create(null)):l=_,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&ss[x]===1)h===-1&&(h=w);else if(x===32||x===9)m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w),zt(n,t.slice(h,m),!0),x===44&&(zt(e,l,n),n=Object.create(null),l=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,w),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(ss[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),o=!1}else if(c)if(ss[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)c=!1,m=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)c=!0;else if(m===-1&&ss[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))m===-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);i&&(_=_.replace(/\\/g,""),i=!1),zt(n,u,_),x===44&&(zt(e,l,n),n=Object.create(null),l=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=w);let v=t.slice(h,m);return l===void 0?zt(e,v,n):(u===void 0?zt(n,v,!0):i?zt(n,u,v.replace(/\\/g,"")):zt(n,u,v),zt(e,l,n)),e}function Dv(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(l=>l===!0?o:`${o}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bx.exports={format:Dv,parse:Cv}});var ea=le((OC,Ox)=>{"use strict";var Ov=xe("events"),Lv=xe("https"),Nv=xe("http"),Sx=xe("net"),Mv=xe("tls"),{randomBytes:Bv,createHash:Fv}=xe("crypto"),{Duplex:CC,Readable:DC}=xe("stream"),{URL:Hd}=xe("url"),Rn=qr(),zv=Bd(),Uv=Ud(),{isBlob:Gv}=jr(),{BINARY_TYPES:Ex,CLOSE_TIMEOUT:Hv,EMPTY_BUFFER:Yo,GUID:qv,kForOnEventAttribute:qd,kListener:jv,kStatusCode:Kv,kWebSocket:We,NOOP:Ix}=en(),{EventTarget:{addEventListener:Wv,removeEventListener:$v}}=yx(),{format:Vv,parse:Jv}=Zo(),{toBuffer:Zv}=ts(),Ax=Symbol("kAborted"),jd=[8,13],rn=["CONNECTING","OPEN","CLOSING","CLOSED"],Yv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends Ov{constructor(e,n,i){super(),this._binaryType=Ex[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yo,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]),kx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ex.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let o=new zv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new Uv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[We]=this,c[We]=this,e[We]=this,o.on("conclude",eS),o.on("drain",tS),o.on("error",nS),o.on("message",rS),o.on("ping",iS),o.on("pong",sS),c.onerror=oS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Px),e.on("data",Qo),e.on("end",Cx),e.on("error",Dx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Rn.extensionName]&&this._extensions[Rn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ut(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())}),Rx(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){Kd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yo,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){Kd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yo,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){Kd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Rn.extensionName]||(o.compress=!1),this._sender.send(e||Yo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ut(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_e,"CONNECTING",{enumerable:!0,value:rn.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:rn.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:rn.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:rn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[qd])return e[jv];return null},set(e){for(let n of this.listeners(t))if(n[qd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[qd]:!0})}})});_e.prototype.addEventListener=Wv;_e.prototype.removeEventListener=$v;Ox.exports=_e;function kx(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Hv,protocolVersion:jd[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!jd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${jd.join(", ")})`);let c;if(e instanceof Hd)c=e;else try{c=new Hd(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:",h;if(c.protocol!=="ws:"&&!l&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?h="The URL's pathname is empty":c.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;Xo(t,I);return}let x=l?443:80,m=Bv(16).toString("base64"),w=l?Lv.request:Nv.request,v=new Set,_;if(o.createConnection=o.createConnection||(l?Qv:Xv),o.defaultPort=o.defaultPort||x,o.port=c.port||x,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Rn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Vv({[Rn.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!Yv.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=w(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(o);o.timeout&&E.on("timeout",()=>{ut(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Ax]||(E=t._req=null,Xo(t,I))}),E.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ut(t,E,"Maximum redirects exceeded");return}E.abort();let O;try{O=new Hd(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);Xo(t,D);return}kx(t,O,n,i)}else t.emit("unexpected-response",E,I)||ut(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==_e.CONNECTING)return;E=t._req=null;let O=I.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){ut(t,A,"Invalid Upgrade header");return}let b=Fv("sha1").update(m+qv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){ut(t,A,"Invalid Sec-WebSocket-Accept header");return}let D=I.headers["sec-websocket-protocol"],L;if(D!==void 0?v.size?v.has(D)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":v.size&&(L="Server sent no subprotocol"),L){ut(t,A,L);return}D&&(t._protocol=D);let G=I.headers["sec-websocket-extensions"];if(G!==void 0){if(!_){ut(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Jv(G)}catch{ut(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Z=Object.keys(U);if(Z.length!==1||Z[0]!==Rn.extensionName){ut(t,A,"Server indicated an extension that was not requested");return}try{_.accept(U[Rn.extensionName])}catch{ut(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Xo(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Xv(t){return t.path=t.socketPath,Sx.connect(t)}function Qv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Sx.isIP(t.host)?"":t.host),Mv.connect(t)}function ut(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ut),e.setHeader?(e[Ax]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Kd(t,e,n){if(e){let i=Gv(e)?e.size:Zv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${rn[t.readyState]})`);process.nextTick(n,i)}}function eS(t,e){let n=this[We];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[We]!==void 0&&(n._socket.removeListener("data",Qo),process.nextTick(Tx,n._socket),t===1005?n.close():n.close(t,e))}function tS(){let t=this[We];t.isPaused||t._socket.resume()}function nS(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",Qo),process.nextTick(Tx,e._socket),e.close(t[Kv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vx(){this[We].emitClose()}function rS(t,e){this[We].emit("message",t,e)}function iS(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,Ix),e.emit("ping",t)}function sS(t){this[We].emit("pong",t)}function Tx(t){t.resume()}function oS(t){let e=this[We];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,Rx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Rx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Px(){let t=this[We];if(this.removeListener("close",Px),this.removeListener("data",Qo),this.removeListener("end",Cx),t._readyState=_e.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vx),t._receiver.on("finish",vx))}function Qo(t){this[We]._receiver.write(t)||this.pause()}function Cx(){let t=this[We];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function Dx(){let t=this[We];this.removeListener("error",Dx),this.on("error",Ix),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Bx=le((NC,Mx)=>{"use strict";var LC=ea(),{Duplex:aS}=xe("stream");function Lx(t){t.emit("close")}function cS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nx(t){this.removeListener("error",Nx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function dS(t,e){let n=!0,i=new aS({...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||(n=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Lx,i);return}let l=!1;t.once("error",function(h){l=!0,c(h)}),t.once("close",function(){l||c(o),process.nextTick(Lx,i)}),n&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,l)});return}t.send(o,l)},i.on("end",cS),i.on("error",Nx),i}Mx.exports=dS});var Wd=le((MC,Fx)=>{"use strict";var{tokenChars:lS}=jr();function uS(t){let e=new Set,n=-1,i=-1,o=0;for(o;o<t.length;o++){let l=t.charCodeAt(o);if(i===-1&&lS[l]===1)n===-1&&(n=o);else if(o!==0&&(l===32||l===9))i===-1&&n!==-1&&(i=o);else if(l===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(n,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Fx.exports={parse:uS}});var Kx=le((FC,jx)=>{"use strict";var fS=xe("events"),ta=xe("http"),{Duplex:BC}=xe("stream"),{createHash:hS}=xe("crypto"),zx=Zo(),er=qr(),xS=Wd(),pS=ea(),{CLOSE_TIMEOUT:mS,GUID:gS,kWebSocket:wS}=en(),_S=/^[+/0-9A-Za-z]{22}==$/,Ux=0,Gx=1,qx=2,$d=class extends fS{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:mS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:pS,...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=ta.createServer((i,o)=>{let c=ta.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=yS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,l)=>{this.handleUpgrade(o,c,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ux}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===qx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(os,this);return}if(e&&this.once("close",e),this._state!==Gx)if(this._state=Gx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(os,this):process.nextTick(os,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{os(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,o){n.on("error",Hx);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,n,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){tr(this,e,n,400,"Invalid Upgrade header");return}if(c===void 0||!_S.test(c)){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){tr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){as(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=xS.parse(h)}catch{tr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&m!==void 0){let v=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=zx.parse(m);_[er.extensionName]&&(v.accept(_[er.extensionName]),w[er.extensionName]=v)}catch{tr(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 as(n,E||401,I,A);this.completeUpgrade(w,c,x,e,n,i,o)});return}if(!this.options.verifyClient(v))return as(n,401)}this.completeUpgrade(w,c,x,e,n,i,o)}completeUpgrade(e,n,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[wS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ux)return as(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hS("sha1").update(n+gS).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),m._protocol=w)}if(e[er.extensionName]){let w=e[er.extensionName].params,v=zx.format({[er.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
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 fe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var nt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(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})},Xg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Vg(e))!Zg.call(t,o)&&o!==r&&La(t,o,{get:()=>e[o],enumerable:!(i=$g(e,o))||i.enumerable});return t};var qt=(t,e,r)=>(r=t!=null?Kg(Jg(t)):{},Xg(e||!t||!t.__esModule?La(r,"default",{value:t,enumerable:!0}):r,t));function Xe(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var dr=nt(()=>{"use strict"});import{createWriteStream as Yg,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 lr(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[d,u,h]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>r}function ps(t,e,r,i){let o;try{o=em(t)}catch{return}for(let c of o){let d=Ma(c,e);if(d&&nm(d,r,i))try{tm(Ll(t,c))}catch{}}}var ai,Ba=nt(()=>{"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=Yg(Ll(this.dir,lr(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:o=>new ai(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();ps(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ps(t.agentLogsDir(o),"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 ur[Fa]<=ur[t]}function zl(t,e){let r=ur[t];return r===void 0?!0:r>=ur[e]}function ws(t){Nl={...t}}function Ul(t){let e=(u,h=2)=>String(u).padStart(h,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),d=e(o%60);return`${Nn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function rt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Ul(new Date),level:e,module:r,msg:i,...o})}
11
+ `;im(t,{recursive:!0}),rm(sm(t,lr("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,o){if(ur[t]<ur[Fa])return;let c=`${JSON.stringify({ts:Ul(new Date),level:t,module:e,msg:r,...Nl,...i})}
12
+ `;if(ms){let d=lm(o,i),u=d?dm(ms,d):ms.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?am.write(c):om.write(c)}function G(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=>G(`${t}.${r}`,e),forAgent:r=>G(t,r)}}var ur,Fa,om,am,Nl,cm,ms,re=nt(()=>{"use strict";dr();Ba();ur={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=Xe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ms=null});var A,Ke=nt(()=>{"use strict";A=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:()=>ql});import{readFileSync as Hl}from"node:fs";import{createRequire as um}from"node:module";import{dirname as fm,resolve as hm}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(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function xm(t){let e=Gl.resolve(`${t.npmPackage}/package.json`),r=fm(e),i=JSON.parse(Hl(e,"utf8")),o=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!o)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return hm(r,o)}async function hr(t,e){let r=za[t];if(!r)throw new A("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=fr.get(t);if(i)return i;let o=Ua(t);if(o)return fr.set(t,o),_s.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let c=xm(r);return fr.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 A("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=Gl.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 fr.get(t)}function ql(t,e){if(e)return e;let r=Ua(t);if(r)return r;let i=bs(t);if(!i)throw new A("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function ci(t,e,r){if(e)return{command:e,args:[...r]};let i=Ua(t);if(i)return{command:i,args:[...r]};let o=ql(t);return{command:process.execPath,args:[o,...r]}}function gm(){fr.clear()}function mm(t,e){fr.set(t,e)}var _s,za,ys,Gl,fr,dn=nt(()=>{"use strict";Ke();re();_s=G("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),Gl=um(import.meta.url),fr=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(o){throw await vm(i,{force:!0}).catch(()=>{}),o}}async function fn(t,e,r){await un(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var hn=nt(()=>{"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 ke,resolve as Vl}from"node:path";function Z(t){let e=t??km(),r=ke(e,".coze"),i=ke(r,"bridge"),o=ke(i,"lib"),c=ke(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:ke(o,"index.js"),binDir:ke(i,"bin"),pidFile:ke(i,"bridge.pid"),portFile:ke(i,"bridge.port"),tokenFile:ke(i,"bridge.token"),patTokenFile:ke(i,"pat-token"),agentEnvFile:ke(i,"agent-env.json"),logFile:ke(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:ke(c,"daemon-stdio.log"),installLock:ke(i,"install.lock"),configFile:ke(i,"config.json"),agentsRoot:ke(r,"agents")}}function Fe(t,e=Z()){let r=ke(e.agentsRoot,t);return{root:r,config:ke(r,"config.json"),workspace:ke(r,"workspace"),logs:ke(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 o=process.platform==="win32"?r.toLowerCase():r,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+Tm)}var Te=nt(()=>{"use strict"});var Ss={};Na(Ss,{AGENT_CONFIG_FILE_MODE:()=>vs,enforceAgentConfigMode:()=>Dm,loadAgentConfig:()=>Ce,persistAgentSessions:()=>li,persistAgentSkills:()=>ui,saveAgentConfig:()=>ze});import{chmod as Cm,stat as Rm}from"node:fs/promises";function Ce(t,e){return ln(Fe(t,e).config)}function ze(t,e){return fn(Fe(t.agentId,e).config,t,{mode:vs})}async function Dm(t,e){if(process.platform==="win32")return;let r=Fe(t,e).config;try{let i=await Rm(r);if(!i.isFile())return;let o=i.mode&511;o!==vs&&(await Cm(r,vs),Jl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.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 Ce(t,r);i&&(i.sessions=Object.fromEntries(e),await ze(i,r))}async function ui(t,e,r){let i=await Ce(t,r);i&&(i.skills=e,await ze(i,r))}var Jl,vs,xn=nt(()=>{"use strict";hn();re();Te();Jl=G("agent-config"),vs=384});var ja=ae((t2,Yl)=>{Yl.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=ae(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=ae((r2,iu)=>{var Fm=fe("fs"),Le=fe("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 Ee(t){this.sep=Le.sep,this.fs=Fm,nu(t)&&nu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}iu.exports=Ee;Ee.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw zm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ee.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Le.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ee.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!r)return o(!1);c.fs.stat(t,function(u,h){if(d&&h.isDirectory())return o(!1);var x=Le.dirname(t);c.fs.exists(x,function(m){m||c.makeDir(x),c.fs.open(t,"w",438,function(w,v){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ee.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Le.join(i,u),x=e.fs.statSync(h);(!o||o.test(h))&&d.push(Le.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(r(h,o,c)))}),d}return r(t,void 0,!0)};Ee.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Le.join(t,u),r.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Le.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};Ee.prototype.getAttributes=function(){};Ee.prototype.setAttributes=function(){};Ee.crc32update=function(t,e){return ru[(t^e)&255]^t>>>8};Ee.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ee.crc32update(r,t[i++]);return~r>>>0};Ee.methodToString=function(t){switch(t){case tu.STORED:return"STORED ("+t+")";case tu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ee.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};Ee.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.posix.join(".",e)};Ee.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]};Ee.sanitize=function(t,e){t=Le.resolve(Le.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Le.normalize(Le.join(t,r.slice(i,o).join(Le.sep)));if(c.indexOf(t)===0)return c}return Le.normalize(Le.join(t,Le.basename(e)))};Ee.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ee.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ee.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)};Ee.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};Ee.isWin=Um;Ee.crcTable=ru});var au=ae((i2,ou)=>{var Hm=fe("path");ou.exports=function(t,{fs:e}){var r=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(o=e.statSync(r),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=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=ae((s2,cu)=>{cu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var gr=ae((o2,pr)=>{pr.exports=su();pr.exports.Constants=ja();pr.exports.Errors=As();pr.exports.FileAttr=au();pr.exports.decoder=du()});var uu=ae((a2,lu)=>{var pn=gr(),z=pn.Constants;lu.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,h=0,x=0,m=0,w=0,v=0,_=0,E=0;t|=pn.isWin?2560:768,r|=z.FLG_EFS;let S={extraLen:0},I=b=>Math.max(0,b)>>>0,k=b=>Math.max(0,b)&65535,R=b=>Math.max(0,b)&255;return o=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&z.FLG_EFS)>0},set flags_efs(b){b?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(b){b?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(b){switch(b){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=b},get time(){return pn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=pn.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=I(b)},get timeHighByte(){return R(o>>>8)},get crc(){return c},set crc(b){c=I(b)},get compressedSize(){return d},set compressedSize(b){d=I(b)},get size(){return u},set size(b){u=I(b)},get fileNameLength(){return h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return S.extraLen},set extraLocalLength(b){S.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return w},set diskNumStart(b){w=I(b)},get inAttr(){return v},set inAttr(b){v=I(b)},get attr(){return _},set attr(b){_=I(b)},get fileAttr(){return(_||0)>>16&4095},get offset(){return E},set offset(b){E=I(b)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+m},get realDataOffset(){return E+z.LOCHDR+S.fnameLen+S.extraLen},get localHeader(){return S},loadLocalHeaderFromBinary:function(b){var D=b.slice(E,E+z.LOCHDR);if(D.readUInt32LE(0)!==z.LOCSIG)throw pn.Errors.INVALID_LOC();S.version=D.readUInt16LE(z.LOCVER),S.flags=D.readUInt16LE(z.LOCFLG),S.flags_desc=(S.flags&z.FLG_DESC)>0,S.method=D.readUInt16LE(z.LOCHOW),S.time=D.readUInt32LE(z.LOCTIM),S.crc=D.readUInt32LE(z.LOCCRC),S.compressedSize=D.readUInt32LE(z.LOCSIZ),S.size=D.readUInt32LE(z.LOCLEN),S.fnameLen=D.readUInt16LE(z.LOCNAM),S.extraLen=D.readUInt16LE(z.LOCEXT);let O=E+z.LOCHDR+S.fnameLen,F=O+S.extraLen;return b.slice(O,F)},loadFromBinary:function(b){if(b.length!==z.CENHDR||b.readUInt32LE(0)!==z.CENSIG)throw pn.Errors.INVALID_CEN();t=b.readUInt16LE(z.CENVEM),e=b.readUInt16LE(z.CENVER),r=b.readUInt16LE(z.CENFLG),i=b.readUInt16LE(z.CENHOW),o=b.readUInt32LE(z.CENTIM),c=b.readUInt32LE(z.CENCRC),d=b.readUInt32LE(z.CENSIZ),u=b.readUInt32LE(z.CENLEN),h=b.readUInt16LE(z.CENNAM),x=b.readUInt16LE(z.CENEXT),m=b.readUInt16LE(z.CENCOM),w=b.readUInt16LE(z.CENDSK),v=b.readUInt16LE(z.CENATT),_=b.readUInt32LE(z.CENATX),E=b.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(z.LOCHDR);return b.writeUInt32LE(z.LOCSIG,0),b.writeUInt16LE(e,z.LOCVER),b.writeUInt16LE(r,z.LOCFLG),b.writeUInt16LE(i,z.LOCHOW),b.writeUInt32LE(o,z.LOCTIM),b.writeUInt32LE(c,z.LOCCRC),b.writeUInt32LE(d,z.LOCSIZ),b.writeUInt32LE(u,z.LOCLEN),b.writeUInt16LE(h,z.LOCNAM),b.writeUInt16LE(S.extraLen,z.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(z.CENHDR+h+x+m);return b.writeUInt32LE(z.CENSIG,0),b.writeUInt16LE(t,z.CENVEM),b.writeUInt16LE(e,z.CENVER),b.writeUInt16LE(r,z.CENFLG),b.writeUInt16LE(i,z.CENHOW),b.writeUInt32LE(o,z.CENTIM),b.writeUInt32LE(c,z.CENCRC),b.writeUInt32LE(d,z.CENSIZ),b.writeUInt32LE(u,z.CENLEN),b.writeUInt16LE(h,z.CENNAM),b.writeUInt16LE(x,z.CENEXT),b.writeUInt16LE(m,z.CENCOM),b.writeUInt16LE(w,z.CENDSK),b.writeUInt16LE(v,z.CENATT),b.writeUInt32LE(_,z.CENATX),b.writeUInt32LE(E,z.CENOFF),b},toJSON:function(){let b=function(D){return D+" bytes"};return{made:t,version:e,flags:r,method:pn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(m),diskNumStart:w,inAttr:v,attr:_,offset:E,centralHeaderSize:b(z.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var hu=ae((c2,fu)=>{var mr=gr(),_e=mr.Constants;fu.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return _e.ENDHDR+o},loadFromBinary:function(c){if((c.length!==_e.ENDHDR||c.readUInt32LE(0)!==_e.ENDSIG)&&(c.length<_e.ZIP64HDR||c.readUInt32LE(0)!==_e.ZIP64SIG))throw mr.Errors.INVALID_END();c.readUInt32LE(0)===_e.ENDSIG?(t=c.readUInt16LE(_e.ENDSUB),e=c.readUInt16LE(_e.ENDTOT),r=c.readUInt32LE(_e.ENDSIZ),i=c.readUInt32LE(_e.ENDOFF),o=c.readUInt16LE(_e.ENDCOM)):(t=mr.readBigUInt64LE(c,_e.ZIP64SUB),e=mr.readBigUInt64LE(c,_e.ZIP64TOT),r=mr.readBigUInt64LE(c,_e.ZIP64SIZE),i=mr.readBigUInt64LE(c,_e.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(_e.ENDHDR+o);return c.writeUInt32LE(_e.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,_e.ENDSUB),c.writeUInt16LE(e,_e.ENDTOT),c.writeUInt32LE(r,_e.ENDSIZ),c.writeUInt32LE(i,_e.ENDOFF),c.writeUInt16LE(o,_e.ENDCOM),c.fill(" ",_e.ENDHDR),c},toJSON:function(){let c=function(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ka=ae(Wa=>{Wa.EntryHeader=uu();Wa.MainHeader=hu()});var pu=ae((l2,xu)=>{xu.exports=function(t){var e=fe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<c.length;x++){var m=c[x];m.copy(u,h),h+=m.length}i&&i(u)}),o.end(t)}}}});var mu=ae((u2,gu)=>{var Gm=+(process.versions?process.versions.node:"").split(".")[0]||0;gu.exports=function(t,e){var r=fe("zlib");let i=Gm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),d=[],u=0;c.on("data",function(h){d.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var m=0;m<d.length;m++){var w=d[m];w.copy(h,x),x+=w.length}o&&o(h)}),c.end(t)}}}});var Eu=ae((f2,bu)=>{"use strict";var{randomFillSync:wu}=fe("crypto"),qm=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),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function Km(t){let e=new Ts(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let d=e.next();i[o++]=c^d,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),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw qm.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 o=Km(r),c=ks.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(c,d),o(t,d,12)}bu.exports={decrypt:$m,encrypt:Jm,_salter:Vm}});var vu=ae(Cs=>{Cs.Deflater=pu();Cs.Inflater=mu();Cs.ZipCrypto=Eu()});var Va=ae((x2,Su)=>{var ce=gr(),Zm=Ka(),ve=ce.Constants,$a=vu();Su.exports=function(t,e){var r=new Zm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:ce.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let D={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==ve.LOCSIG||e.readUInt32LE(O)==ve.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==ve.EXTSIG)D.crc=e.readUInt32LE(O+ve.EXTCRC),D.compressedSize=e.readUInt32LE(O+ve.EXTSIZ),D.size=e.readUInt32LE(O+ve.EXTLEN);else if(e.readUInt16LE(O+12)===19280)D.crc=e.readUInt32LE(O+ve.EXTCRC-4),D.compressedSize=e.readUInt32LE(O+ve.EXTSIZ-4),D.size=e.readUInt32LE(O+ve.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==r.compressedSize||D.size!==r.size||D.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==D.crc)return!1}return!0}function E(b,D,O){if(typeof D>"u"&&typeof b=="string"&&(O=b,b=void 0),c)return b&&D&&D(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=v();if(F.length===0)return b&&D&&D(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();F=$a.ZipCrypto.decrypt(F,r,O)}var M=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(F.copy(M),_(M))return b&&D&&D(M),M;throw b&&D&&D(M,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var V=new $a.Inflater(F,r.size);if(b)V.inflateAsync(function(K){K.copy(K,0),D&&(_(K)?D(K):D(K,ce.Errors.BAD_CRC()))});else{if(V.inflate(M).copy(M,0),!_(M))throw ce.Errors.BAD_CRC(`"${w.decode(i)}"`);return M}break;default:throw b&&D&&D(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function S(b,D){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&D&&D(v()),v();if(d.length&&!c){var O;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),b&&D&&D(O),O;default:case ce.Constants.DEFLATED:var F=new $a.Deflater(d);if(b)F.deflateAsync(function(V){O=Buffer.alloc(V.length),r.compressedSize=V.length,V.copy(O),D&&D(O)});else{var M=F.deflate();return r.compressedSize=M.length,M}F=null;break}}else if(b&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function I(b,D){return ce.readBigUInt64LE(b,D)}function k(b){try{for(var D=0,O,F,M;D+4<b.length;)O=b.readUInt16LE(D),D+=2,F=b.readUInt16LE(D),D+=2,M=b.slice(D,D+F),D+=F,ve.ID_ZIP64===O&&R(M)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function R(b){var D,O,F,M;b.length>=ve.EF_ZIP64_SCOMP&&(D=I(b,ve.EF_ZIP64_SUNCOMP),r.size===ve.EF_ZIP64_OR_32&&(r.size=D)),b.length>=ve.EF_ZIP64_RHO&&(O=I(b,ve.EF_ZIP64_SCOMP),r.compressedSize===ve.EF_ZIP64_OR_32&&(r.compressedSize=O)),b.length>=ve.EF_ZIP64_DSN&&(F=I(b,ve.EF_ZIP64_RHO),r.offset===ve.EF_ZIP64_OR_32&&(r.offset=F)),b.length>=ve.EF_ZIP64_DSN+4&&(M=b.readUInt32LE(ve.EF_ZIP64_DSN),r.diskNumStart===ve.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,w.encode);var D=i[i.length-1];c=D===47||D===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,k(b)},get comment(){return w.decode(o)},set comment(b){if(o=ce.toBuffer(b,w.encode),r.commentLength=o.length,o.length>65535)throw ce.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 S(!1,null)},getCompressedDataAsync:function(b){S(!0,b)},setData:function(b){d=ce.toBuffer(b,ce.decoder.encode),!c&&d.length?(r.size=d.length,r.method=ce.Constants.DEFLATED,r.crc=ce.crc32(b),r.changed=!0):r.method=ce.Constants.STORED},getData:function(b){return r.changed?d:E(!1,null,b)},getDataAsync:function(b,D){r.changed?b(d):E(!0,b,D)},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(),D=ce.Constants.CENHDR;return i.copy(b,D),D+=i.length,u.copy(b,D),D+=r.extraLength,o.copy(b,D),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=h.length;let D=r.localHeaderToBinary(),O=Buffer.alloc(D.length+i.length+r.extraLocalLength);return D.copy(O,b),b+=D.length,i.copy(O,b),b+=i.length,h.copy(O,b),b+=h.length,O},toJSON:function(){let b=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:b(e),data:b(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ku=ae((p2,Au)=>{var Iu=Va(),Xm=Ka(),$e=gr();Au.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Xm.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:w}=x;t?E(x.readEntries):d=!0;function v(){let I=new Set;for(let k of Object.keys(i)){let R=k.split("/");if(R.pop(),!!R.length)for(let b=0;b<R.length;b++){let D=R.slice(0,b+1).join("/")+"/";I.add(D)}}for(let k of I)if(!(k in i)){let R=new Iu(x);R.entryName=k,R.attr=16,R.temporary=!0,r.push(R),i[R.entryName]=R,h.add(R)}}function _(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/$e.Constants.CENHDR)throw $e.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var I=c.offset,k=0;k<r.length;k++){var R=I,b=new Iu(x,t);b.header=t.slice(R,R+=$e.Constants.CENHDR),b.entryName=t.slice(R,R+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(R,R+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(R,R+b.header.commentLength)),I+=b.header.centralHeaderSize,r[k]=b,i[b.entryName]=b}h.clear(),v()}function E(I){var k=t.length-$e.Constants.ENDHDR,R=Math.max(0,k-65535),b=R,D=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(R=0),k;k>=b;k--)if(t[k]===80){if(t.readUInt32LE(k)===$e.Constants.ENDSIG){O=k,F=k,D=k+$e.Constants.ENDHDR,b=k-$e.Constants.END64HDR;continue}if(t.readUInt32LE(k)===$e.Constants.END64SIG){b=R;continue}if(t.readUInt32LE(k)===$e.Constants.ZIP64SIG){O=k,D=k+$e.readBigUInt64LE(t,k+$e.Constants.ZIP64SIZE)+$e.Constants.ZIP64LEAD;break}}if(O==-1)throw $e.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,D)),c.commentLength&&(o=t.slice(F+$e.Constants.ENDHDR)),I&&_()}function S(){r.length>1&&!m&&r.sort((I,k)=>I.entryName.toLowerCase().localeCompare(k.entryName.toLowerCase()))}return{get entries(){return d||_(),r.filter(I=>!h.has(I))},get comment(){return w.decode(o)},set comment(I){o=$e.toBuffer(I,w.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(I){this.entries.forEach(I)},getEntry:function(I){return d||_(),i[I]||null},setEntry:function(I){d||_(),r.push(I),i[I.entryName]=I,c.totalEntries=r.length},deleteFile:function(I,k=!0){d||_();let R=i[I];this.getEntryChildren(R,k).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(I){d||_();let k=i[I],R=r.indexOf(k);R>=0&&(r.splice(R,1),delete i[I],c.totalEntries=r.length)},getEntryChildren:function(I,k=!0){if(d||_(),typeof I=="object")if(I.isDirectory&&k){let R=[],b=I.entryName;for(let D of r)D.entryName.startsWith(b)&&R.push(D);return R}else return[I];return[]},getChildCount:function(I){if(I&&I.isDirectory){let k=this.getEntryChildren(I);return k.includes(I)?k.length-1:k.length}return 0},compressToBuffer:function(){d||_(),S();let I=[],k=[],R=0,b=0;c.size=0,c.offset=0;let D=0;for(let M of this.entries){let V=M.getCompressedData();M.header.offset=b;let K=M.packLocalHeader(),ie=K.length+V.length;b+=ie,I.push(K),I.push(V);let Y=M.packCentralHeader();k.push(Y),c.size+=Y.length,R+=ie+Y.length,D++}R+=c.mainHeaderSize,c.offset=b,c.totalEntries=D,b=0;let O=Buffer.alloc(R);for(let M of I)M.copy(O,b),b+=M.length;for(let M of k)M.copy(O,b),b+=M.length;let F=c.toBinary();return o&&o.copy(F,$e.Constants.ENDHDR),F.copy(O,b),t=O,d=!1,O},toAsyncBuffer:function(I,k,R,b){try{d||_(),S();let D=[],O=[],F=0,M=0,V=0;c.size=0,c.offset=0;let K=function(ie){if(ie.length>0){let Y=ie.shift(),te=Y.entryName+Y.extra.toString();R&&R(te),Y.getCompressedDataAsync(function(oe){b&&b(te),Y.header.offset=M;let P=Y.packLocalHeader(),U=P.length+oe.length;M+=U,D.push(P),D.push(oe);let j=Y.packCentralHeader();O.push(j),c.size+=j.length,F+=U+j.length,V++,K(ie)})}else{F+=c.mainHeaderSize,c.offset=M,c.totalEntries=V,M=0;let Y=Buffer.alloc(F);D.forEach(function(oe){oe.copy(Y,M),M+=oe.length}),O.forEach(function(oe){oe.copy(Y,M),M+=oe.length});let te=c.toBinary();o&&o.copy(te,$e.Constants.ENDHDR),te.copy(Y,M),t=Y,d=!1,I(Y)}};K(Array.from(this.entries))}catch(D){k(D)}}}}});var Ru=ae((g2,Cu)=>{var be=gr(),ye=fe("path"),Ym=Va(),Qm=ku(),Mn=(...t)=>be.findLast(t,e=>typeof e=="boolean"),Tu=(...t)=>be.findLast(t,e=>typeof e=="string"),ew=(...t)=>be.findLast(t,e=>typeof e=="function"),tw={noSort:!1,readEntries:!1,method:be.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=be.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new be(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=be.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=be.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw be.Errors.INVALID_FILENAME();let c=new Qm(r,i),{canonical:d,sanitize:u,zipnamefix:h}=be;function x(_){if(_&&c){var E;if(typeof _=="string"&&(E=c.getEntry(ye.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=c.getEntry(_.entryName)),E)return E}return null}function m(_){let{join:E,normalize:S,sep:I}=ye.posix;return E(ye.isAbsolute(_)?"/":".",S(I+_.split("\\").join(I)+I))}function w(_){return _ instanceof RegExp?(function(E){return function(S){return E.test(S)}})(_):typeof _!="function"?()=>!0:_}let v=(_,E)=>{let S=E.slice(-1);return S=S===o.sep?o.sep:"",ye.relative(_,E)+S};return{readFile:function(_,E){var S=x(_);return S&&S.getData(E)||null},childCount:function(_){let E=x(_);if(E)return c.getChildCount(E)},readFileAsync:function(_,E){var S=x(_);S?S.getDataAsync(E):E(null,"getEntry failed for:"+_)},readAsText:function(_,E){var S=x(_);if(S){var I=S.getData();if(I&&I.length)return I.toString(E||"utf8")}return""},readAsTextAsync:function(_,E,S){var I=x(_);I?I.getDataAsync(function(k,R){if(R){E(k,R);return}k&&k.length?E(k.toString(S||"utf8")):E("")}):E("")},deleteFile:function(_,E=!0){var S=x(_);S&&c.deleteFile(S.entryName,E)},deleteEntry:function(_){var E=x(_);E&&c.deleteEntry(E.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,E){var S=x(_);S&&(S.comment=E)},getZipEntryComment:function(_){var E=x(_);return E&&E.comment||""},updateFile:function(_,E){var S=x(_);S&&S.setData(E)},addLocalFile:function(_,E,S,I){if(o.fs.existsSync(_)){E=E?m(E):"";let k=ye.win32.basename(ye.win32.normalize(_));E+=S||k;let R=o.fs.statSync(_),b=R.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);R.isDirectory()&&(E+=o.sep),this.addFile(E,b,I,R)}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let S=ye.resolve(_.localPath),{comment:I}=_,{zipPath:k,zipName:R}=_,b=this;o.fs.stat(S,function(D,O){if(D)return E(D,!1);k=k?m(k):"";let F=ye.win32.basename(ye.win32.normalize(S));if(k+=R||F,O.isFile())o.fs.readFile(S,function(M,V){return M?E(M,!1):(b.addFile(k,V,I,O),setImmediate(E,void 0,!0))});else if(O.isDirectory())return k+=o.sep,b.addFile(k,Buffer.alloc(0),I,O),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,S){if(S=w(S),E=E?m(E):"",_=ye.normalize(_),o.fs.existsSync(_)){let I=o.findFiles(_),k=this;if(I.length)for(let R of I){let b=ye.join(E,v(_,R));S(b)&&k.addLocalFile(R,ye.dirname(b))}}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,S,I){I=w(I),S=S?m(S):"",_=ye.normalize(_);var k=this;o.fs.open(_,"r",function(R){if(R&&R.code==="ENOENT")E(void 0,be.Errors.FILE_NOT_FOUND(_));else if(R)E(void 0,R);else{var b=o.findFiles(_),D=-1,O=function(){if(D+=1,D<b.length){var F=b[D],M=v(_,F).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),I(M)?o.fs.stat(F,function(V,K){V&&E(void 0,V),K.isFile()?o.fs.readFile(F,function(ie,Y){ie?E(void 0,ie):(k.addFile(S+M,Y,"",K),O())}):(k.addFile(S+M+"/",Buffer.alloc(0),"",K),O())}):process.nextTick(()=>{O()})}else E(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,E){let S=this;_=typeof _=="object"?_:{localPath:_},localPath=ye.resolve(m(_.localPath));let{zipPath:I,filter:k,namefix:R}=_;k instanceof RegExp?k=(function(O){return function(F){return O.test(F)}})(k):typeof k!="function"&&(k=function(){return!0}),I=I?m(I):"",R=="latin1"&&(R=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof R!="function"&&(R=O=>O);let b=O=>ye.join(I,R(v(localPath,O))),D=O=>ye.win32.basename(ye.win32.normalize(R(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?E(void 0,be.Errors.FILE_NOT_FOUND(localPath)):O?E(void 0,O):o.findFilesAsync(localPath,function(F,M){if(F)return E(F);M=M.filter(V=>k(b(V))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(V,K){return function(ie,Y){if(ie||Y===!1)return setImmediate(V,ie,!1);S.addLocalFileAsync({localPath:K,zipPath:ye.dirname(b(K)),zipName:D(K)},V)}},E))})})},addLocalFolderPromise:function(_,E){return new Promise((S,I)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},E),(k,R)=>{k&&I(k),R&&S(this)})})},addFile:function(_,E,S,I){_=h(_);let k=x(_),R=k!=null;R||(k=new Ym(i),k.entryName=_),k.comment=S||"";let b=typeof I=="object"&&I instanceof o.fs.Stats;b&&(k.header.time=I.mtime);var D=k.isDirectory?16:0;let O=k.isDirectory?16384:32768;return b?O|=4095&I.mode:typeof I=="number"?O|=4095&I:O|=k.isDirectory?493:420,D=(D|O<<16)>>>0,k.attr=D,k.setData(E),R||c.setEntry(k),k},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,E,S,I,k,R){I=Mn(!1,I),k=Mn(!1,k),S=Mn(!0,S),R=Tu(k,R);var b=x(_);if(!b)throw be.Errors.NO_ENTRY();var D=d(b.entryName),O=u(E,R&&!b.isDirectory?R:S?D:ye.basename(D));if(b.isDirectory){var F=c.getEntryChildren(b);return F.forEach(function(K){if(K.isDirectory)return;var ie=K.getData();if(!ie)throw be.Errors.CANT_EXTRACT_FILE();var Y=d(K.entryName),te=u(E,S?Y:ye.basename(Y));let oe=k?K.header.fileAttr:void 0;o.writeFileTo(te,ie,I,oe)}),!0}var M=b.getData(c.password);if(!M)throw be.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!I)throw be.Errors.CANT_OVERRIDE();let V=k?_.header.fileAttr:void 0;return o.writeFileTo(O,M,I,V),!0},test:function(_){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var S=c.entries[E].getData(_);if(!S)return!1}catch{return!1}return!0},extractAllTo:function(_,E,S,I){if(S=Mn(!1,S),I=Tu(S,I),E=Mn(!1,E),!c)throw be.Errors.NO_ZIP();c.entries.forEach(function(k){var R=u(_,d(k.entryName));if(k.isDirectory){o.makeDir(R);return}var b=k.getData(I);if(!b)throw be.Errors.CANT_EXTRACT_FILE();let D=S?k.header.fileAttr:void 0;o.writeFileTo(R,b,E,D);try{o.fs.utimesSync(R,k.header.time,k.header.time)}catch{throw be.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,S,I){if(I=ew(E,S,I),S=Mn(!1,S),E=Mn(!1,E),!I)return new Promise((O,F)=>{this.extractAllToAsync(_,E,S,function(M){M?F(M):O(this)})});if(!c){I(be.Errors.NO_ZIP());return}_=ye.resolve(_);let k=O=>u(_,ye.normalize(d(O.entryName))),R=(O,F)=>new Error(O+': "'+F+'"'),b=[],D=[];c.entries.forEach(O=>{O.isDirectory?b.push(O):D.push(O)});for(let O of b){let F=k(O),M=S?O.header.fileAttr:void 0;try{o.makeDir(F),M&&o.fs.chmodSync(F,M),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{I(R("Unable to create folder",F))}}D.reverse().reduce(function(O,F){return function(M){if(M)O(M);else{let V=ye.normalize(d(F.entryName)),K=u(_,V);F.getDataAsync(function(ie,Y){if(Y)O(Y);else if(!ie)O(be.Errors.CANT_EXTRACT_FILE());else{let te=S?F.header.fileAttr:void 0;o.writeFileToAsync(K,ie,E,te,function(oe){oe||O(R("Unable to write file",K)),o.fs.utimes(K,F.header.time,F.header.time,function(P){P?O(R("Unable to set times",K)):O()})})}})}}},I)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var S=c.compressToBuffer();if(S){var I=o.writeFileTo(_,S,!0);typeof E=="function"&&E(I?null:new Error("failed"),"")}}},writeZipPromise:function(_,E){let{overwrite:S,perm:I}=Object.assign({overwrite:!0},E);return new Promise((k,R)=>{!_&&i.filename&&(_=i.filename),_||R("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let D=O=>O?k(O):R("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,S,I,D)},R)})},toBufferPromise:function(){return new Promise((_,E)=>{c.toAsyncBuffer(_,E)})},toBuffer:function(_,E,S,I){return typeof _=="function"?(c.toAsyncBuffer(_,E,S,I),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 hy(t){if(process.platform!=="win32")return!1;if(Yf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Yf,"").toLowerCase();return fy.has(r)}function Qf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return hy(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function st(t,e=[],r={}){return ly(t,e,Qf(t,r))}function e0(t,e=[],r={}){return xy(t,e,Qf(t,r))}var fy,Yf,xy,Zt=nt(()=>{"use strict";fy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Yf=/\.(cmd|bat|ps1)$/i;xy=uy(dy)});var Qt=ae((SD,jh)=>{"use strict";var Gh=["nodebuffer","arraybuffer","fragments"],qh=typeof Blob<"u";qh&&Gh.push("blob");jh.exports={BINARY_TYPES:Gh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var es=ae((ID,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 o=0;o<t.length;o++){let c=t[o];r.set(c,i),i+=c.length}return i<e?new Cd(r.buffer,r.byteOffset,i):r}function Wh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Kh(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:Wh,toArrayBuffer:Iv,toBuffer:Rd,unmask:Kh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=fe("bufferutil");Uo.exports.mask=function(e,r,i,o,c){c<48?Wh(e,r,i,o,c):t.mask(e,r,i,o,c)},Uo.exports.unmask=function(e,r){e.length<32?Kh(e,r):t.unmask(e,r)}}catch{}});var Jh=ae((AD,Vh)=>{"use strict";var $h=Symbol("kDone"),Dd=Symbol("kRun"),Pd=class{constructor(e){this[$h]=()=>{this.pending--,this[Dd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Dd]()}[Dd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$h])}}};Vh.exports=Pd});var Kr=ae((kD,Qh)=>{"use strict";var ts=fe("zlib"),Zh=es(),Av=Jh(),{kStatusCode:Xh}=Qt(),kv=Buffer[Symbol.species],Tv=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),en=Symbol("total-length"),jr=Symbol("callback"),Dn=Symbol("buffers"),Wr=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[jr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){Ho.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Ho.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?ts.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=ts.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Go]=this,this._inflate[en]=0,this._inflate[Dn]=[],this._inflate.on("error",Rv),this._inflate.on("data",Yh)}this._inflate[jr]=i,this._inflate.write(e),r&&this._inflate.write(Tv),this._inflate.flush(()=>{let c=this._inflate[Wr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Zh.concat(this._inflate[Dn],this._inflate[en]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[en]=0,this._inflate[Dn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?ts.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=ts.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[en]=0,this._deflate[Dn]=[],this._deflate.on("data",Cv)}this._deflate[jr]=i,this._deflate.write(e),this._deflate.flush(ts.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Zh.concat(this._deflate[Dn],this._deflate[en]);r&&(c=new kv(c.buffer,c.byteOffset,c.length-4)),this._deflate[jr]=null,this._deflate[en]=0,this._deflate[Dn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Qh.exports=Od;function Cv(t){this[Dn].push(t),this[en]+=t.length}function Yh(t){if(this[en]+=t.length,this[Go]._maxPayload<1||this[en]<=this[Go]._maxPayload){this[Dn].push(t);return}this[Wr]=new RangeError("Max payload size exceeded"),this[Wr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Wr][Xh]=1009,this.removeListener("data",Yh),this.reset()}function Rv(t){if(this[Go]._inflate=null,this[Wr]){this[jr](this[Wr]);return}t[Xh]=1007,this[jr](t)}});var $r=ae((TD,qo)=>{"use strict";var{isUtf8:ex}=fe("buffer"),{hasBlob:Dv}=Qt(),Pv=[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 Dv&&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:Lv,isValidStatusCode:Ov,isValidUTF8:Ld,tokenChars:Pv};if(ex)qo.exports.isValidUTF8=function(t){return t.length<24?Ld(t):ex(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=fe("utf-8-validate");qo.exports.isValidUTF8=function(e){return e.length<32?Ld(e):t(e)}}catch{}});var zd=ae((CD,ax)=>{"use strict";var{Writable:Nv}=fe("stream"),tx=Kr(),{BINARY_TYPES:Mv,EMPTY_BUFFER:nx,kStatusCode:Bv,kWebSocket:Fv}=Qt(),{concat:Nd,toArrayBuffer:zv,unmask:Uv}=es(),{isValidStatusCode:Hv,isValidUTF8:rx}=$r(),jo=Buffer[Symbol.species],xt=0,ix=1,sx=2,ox=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=xt}_write(e,r,i){if(this._opcode===8&&this._state==xt)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],o=r.length-e;e>=i.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new 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 xt:this.getInfo(e);break;case ix:this.getPayloadLength16(e);break;case sx:this.getPayloadLength64(e);break;case ox: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 o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(r[0]&64)===64;if(i&&!this._extensions[tx.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=ix:this._payloadLength===127?this._state=sx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=ox:this._state=Md}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Md}getData(e){let r=nx;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[tx.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(d);return}this._fragments.push(c)}this.dataMessage(r),this._state===xt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=xt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Nd(i,r):this._binaryType==="arraybuffer"?o=zv(Nd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=xt):(this._state=Wo,setImmediate(()=>{this.emit("message",o,!0),this._state=xt,this.startLoop(e)}))}else{let o=Nd(i,r);if(!this._skipUTF8Validation&&!rx(o)){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",o,!1),this._state=xt):(this._state=Wo,setImmediate(()=>{this.emit("message",o,!1),this._state=xt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,nx),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 o=new jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=xt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xt):(this._state=Wo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xt,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(d,this.createError),d.code=c,d[Bv]=o,d}};ax.exports=Fd});var Gd=ae((DD,lx)=>{"use strict";var{Duplex:RD}=fe("stream"),{randomFillSync:Gv}=fe("crypto"),cx=Kr(),{EMPTY_BUFFER:qv,kWebSocket:jv,NOOP:Wv}=Qt(),{isBlob:Vr,isValidStatusCode:Kv}=$r(),{mask:dx,toBuffer:Qn}=es(),pt=Symbol("kByteLength"),$v=Buffer.alloc(4),Ko=8*1024,er,Jr=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,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||$v,r.generateMask?r.generateMask(i):(Jr===Ko&&(er===void 0&&(er=Buffer.alloc(Ko)),Gv(er,0,Ko),Jr=0),i[0]=er[Jr++],i[1]=er[Jr++],i[2]=er[Jr++],i[3]=er[Jr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[pt]!==void 0?u=r[pt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let h=u;u>=65536?(c+=8,h=127):u>125&&(c+=2,h=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:o?(dx(e,i,x,c,u),[x]):(dx(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=qv;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 d={[pt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Vr(e)?(o=e.size,c=!1):(e=Qn(e),o=e.length,c=Qn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Vr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Vr(e)?(o=e.size,c=!1):(e=Qn(e),o=e.length,c=Qn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Vr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[cx.extensionName],c=r.binary?2:1,d=r.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Vr(e)?(u=e.size,h=!1):(e=Qn(e),u=e.length,h=Qn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),r.fin&&(this._firstFragment=!0);let x={[pt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};Vr(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==It?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[pt],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,o);return}this._bufferedBytes-=i[pt];let d=Qn(c);r?this.dispatch(d,r,i,o):(this._state=It,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(Zv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[cx.extensionName];this._bufferedBytes+=i[pt],this._state=Vv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");Hd(this,h,o);return}this._bufferedBytes-=i[pt],this._state=It,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][pt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][pt],this._queue.push(e)}sendFrame(e,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)}};lx.exports=Ud;function Hd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function Zv(t,e,r){Hd(t,e,r),t.onerror(e)}});var yx=ae((PD,_x)=>{"use strict";var{kForOnEventAttribute:ns,kListener:qd}=Qt(),ux=Symbol("kCode"),fx=Symbol("kData"),hx=Symbol("kError"),xx=Symbol("kMessage"),px=Symbol("kReason"),Zr=Symbol("kTarget"),gx=Symbol("kType"),mx=Symbol("kWasClean"),tn=class{constructor(e){this[Zr]=null,this[gx]=e}get target(){return this[Zr]}get type(){return this[gx]}};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[ux]=r.code===void 0?0:r.code,this[px]=r.reason===void 0?"":r.reason,this[mx]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[ux]}get reason(){return this[px]}get wasClean(){return this[mx]}};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[hx]=r.error===void 0?null:r.error,this[xx]=r.message===void 0?"":r.message}get error(){return this[hx]}get message(){return this[xx]}};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[fx]=r.data===void 0?null:r.data}get data(){return this[fx]}};Object.defineProperty(rs.prototype,"data",{enumerable:!0});var Xv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[ns]&&o[qd]===e&&!o[ns])return;let i;if(t==="message")i=function(c,d){let u=new rs("message",{data:d?c:c.toString()});u[Zr]=this,$o(e,this,u)};else if(t==="close")i=function(c,d){let u=new tr("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Zr]=this,$o(e,this,u)};else if(t==="error")i=function(c){let d=new Xr("error",{error:c,message:c.message});d[Zr]=this,$o(e,this,d)};else if(t==="open")i=function(){let c=new tn("open");c[Zr]=this,$o(e,this,c)};else return;i[ns]=!!r[ns],i[qd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[qd]===e&&!r[ns]){this.removeListener(t,r);break}}};_x.exports={CloseEvent:tr,ErrorEvent:Xr,Event:tn,EventTarget:Xv,MessageEvent:rs};function $o(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Vo=ae((OD,bx)=>{"use strict";var{tokenChars:is}=$r();function zt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Yv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,h=-1,x=-1,m=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(m===-1&&is[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);x===44?(zt(e,_,r),r=Object.create(null)):d=_,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&is[x]===1)h===-1&&(h=w);else if(x===32||x===9)m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w),zt(r,t.slice(h,m),!0),x===44&&(zt(e,d,r),r=Object.create(null),d=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,w),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(is[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),o=!1}else if(c)if(is[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)c=!1,m=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)c=!0;else if(m===-1&&is[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))m===-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);i&&(_=_.replace(/\\/g,""),i=!1),zt(r,u,_),x===44&&(zt(e,d,r),r=Object.create(null),d=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=w);let v=t.slice(h,m);return d===void 0?zt(e,v,r):(u===void 0?zt(r,v,!0):i?zt(r,u,v.replace(/\\/g,"")):zt(r,u,v),zt(e,d,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(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bx.exports={format:Qv,parse:Yv}});var Yo=ae((MD,Ox)=>{"use strict";var eS=fe("events"),tS=fe("https"),nS=fe("http"),Sx=fe("net"),rS=fe("tls"),{randomBytes:iS,createHash:sS}=fe("crypto"),{Duplex:LD,Readable:ND}=fe("stream"),{URL:jd}=fe("url"),Pn=Kr(),oS=zd(),aS=Gd(),{isBlob:cS}=$r(),{BINARY_TYPES:Ex,CLOSE_TIMEOUT:dS,EMPTY_BUFFER:Jo,GUID:lS,kForOnEventAttribute:Wd,kListener:uS,kStatusCode:fS,kWebSocket:je,NOOP:Ix}=Qt(),{EventTarget:{addEventListener:hS,removeEventListener:xS}}=yx(),{format:pS,parse:gS}=Vo(),{toBuffer:mS}=es(),Ax=Symbol("kAborted"),Kd=[8,13],nn=["CONNECTING","OPEN","CLOSING","CLOSED"],wS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends eS{constructor(e,r,i){super(),this._binaryType=Ex[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]),kx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ex.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,i){let o=new 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=o,this._sender=c,this._socket=e,o[je]=this,c[je]=this,e[je]=this,o.on("conclude",bS),o.on("drain",ES),o.on("error",vS),o.on("message",SS),o.on("ping",IS),o.on("pong",AS),c.onerror=kS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Rx),e.on("data",Xo),e.on("end",Dx),e.on("error",Px),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[Pn.extensionName]&&this._extensions[Pn.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){dt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Cx(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 o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Pn.extensionName]||(o.compress=!1),this._sender.send(e||Jo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[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})}})});me.prototype.addEventListener=hS;me.prototype.removeEventListener=xS;Ox.exports=me;function kx(t,e,r,i){let o={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=o.autoPong,t._closeTimeout=o.closeTimeout,!Kd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.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 d=c.protocol==="wss:",u=c.protocol==="ws+unix:",h;if(c.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?h="The URL's pathname is empty":c.hash&&(h="The URL contains a fragment identifier"),h){let S=new SyntaxError(h);if(t._redirects===0)throw S;Zo(t,S);return}let x=d?443:80,m=iS(16).toString("base64"),w=d?tS.request:nS.request,v=new Set,_;if(o.createConnection=o.createConnection||(d?yS:_S),o.defaultPort=o.defaultPort||x,o.port=c.port||x,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Pn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=pS({[Pn.extensionName]:_.offer()})),r.length){for(let S of r){if(typeof S!="string"||!wS.test(S)||v.has(S))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(S)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let S=o.path.split(":");o.socketPath=S[0],o.path=S[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let S=i&&i.headers;if(i={...i,headers:{}},S)for(let[I,k]of Object.entries(S))i.headers[I.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let S=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!S||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,S||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=w(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(o);o.timeout&&E.on("timeout",()=>{dt(t,E,"Opening handshake has timed out")}),E.on("error",S=>{E===null||E[Ax]||(E=t._req=null,Zo(t,S))}),E.on("response",S=>{let I=S.headers.location,k=S.statusCode;if(I&&o.followRedirects&&k>=300&&k<400){if(++t._redirects>o.maxRedirects){dt(t,E,"Maximum redirects exceeded");return}E.abort();let R;try{R=new jd(I,e)}catch{let D=new SyntaxError(`Invalid URL: ${I}`);Zo(t,D);return}kx(t,R,r,i)}else t.emit("unexpected-response",E,S)||dt(t,E,`Unexpected server response: ${S.statusCode}`)}),E.on("upgrade",(S,I,k)=>{if(t.emit("upgrade",S),t.readyState!==me.CONNECTING)return;E=t._req=null;let R=S.headers.upgrade;if(R===void 0||R.toLowerCase()!=="websocket"){dt(t,I,"Invalid Upgrade header");return}let b=sS("sha1").update(m+lS).digest("base64");if(S.headers["sec-websocket-accept"]!==b){dt(t,I,"Invalid Sec-WebSocket-Accept header");return}let D=S.headers["sec-websocket-protocol"],O;if(D!==void 0?v.size?v.has(D)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":v.size&&(O="Server sent no subprotocol"),O){dt(t,I,O);return}D&&(t._protocol=D);let F=S.headers["sec-websocket-extensions"];if(F!==void 0){if(!_){dt(t,I,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=gS(F)}catch{dt(t,I,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(M);if(V.length!==1||V[0]!==Pn.extensionName){dt(t,I,"Server indicated an extension that was not requested");return}try{_.accept(M[Pn.extensionName])}catch{dt(t,I,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Pn.extensionName]=_}t.setSocket(I,k,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Zo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function _S(t){return t.path=t.socketPath,Sx.connect(t)}function yS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Sx.isIP(t.host)?"":t.host),rS.connect(t)}function dt(t,e,r){t._readyState=me.CLOSING;let i=new Error(r);Error.captureStackTrace(i,dt),e.setHeader?(e[Ax]=!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[je];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[je]!==void 0&&(r._socket.removeListener("data",Xo),process.nextTick(Tx,r._socket),t===1005?r.close():r.close(t,e))}function ES(){let t=this[je];t.isPaused||t._socket.resume()}function vS(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",Xo),process.nextTick(Tx,e._socket),e.close(t[fS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vx(){this[je].emitClose()}function SS(t,e){this[je].emit("message",t,e)}function IS(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,Ix),e.emit("ping",t)}function AS(t){this[je].emit("pong",t)}function Tx(t){t.resume()}function kS(t){let e=this[je];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,Cx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Cx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Rx(){let t=this[je];if(this.removeListener("close",Rx),this.removeListener("data",Xo),this.removeListener("end",Dx),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vx),t._receiver.on("finish",vx))}function Xo(t){this[je]._receiver.write(t)||this.pause()}function Dx(){let t=this[je];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function Px(){let t=this[je];this.removeListener("error",Px),this.on("error",Ix),t&&(t._readyState=me.CLOSING,this.destroy())}});var Bx=ae((FD,Mx)=>{"use strict";var BD=Yo(),{Duplex:TS}=fe("stream");function Lx(t){t.emit("close")}function CS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nx(t){this.removeListener("error",Nx),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,d){let u=!d&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Lx,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(o),process.nextTick(Lx,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,d)});return}t.send(o,d)},i.on("end",CS),i.on("error",Nx),i}Mx.exports=RS});var Vd=ae((zD,Fx)=>{"use strict";var{tokenChars:DS}=$r();function PS(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&DS[d]===1)r===-1&&(r=o);else if(o!==0&&(d===32||d===9))i===-1&&r!==-1&&(i=o);else if(d===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Fx.exports={parse:PS}});var Wx=ae((HD,jx)=>{"use strict";var OS=fe("events"),Qo=fe("http"),{Duplex:UD}=fe("stream"),{createHash:LS}=fe("crypto"),zx=Vo(),nr=Kr(),NS=Vd(),MS=Yo(),{CLOSE_TIMEOUT:BS,GUID:FS,kWebSocket:zS}=Qt(),US=/^[+/0-9A-Za-z]{22}==$/,Ux=0,Hx=1,qx=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,o)=>{let c=Qo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=HS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,d)=>{this.handleUpgrade(o,c,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ux}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===qx){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!==Hx)if(this._state=Hx,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,o){r.on("error",Gx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){rr(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.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 h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=NS.parse(h)}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 v=new nr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=zx.parse(m);_[nr.extensionName]&&(v.accept(_[nr.extensionName]),w[nr.extensionName]=v)}catch{rr(this,e,r,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,S,I)=>{if(!_)return os(r,E||401,S,I);this.completeUpgrade(w,c,x,e,r,i,o)});return}if(!this.options.verifyClient(v))return os(r,401)}this.completeUpgrade(w,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,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>Ux)return os(c,503);let x=["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,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),m._protocol=w)}if(e[nr.extensionName]){let w=e[nr.extensionName].params,v=zx.format({[nr.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Hx),m.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(os,this)})),u(m,o)}};jx.exports=$d;function yS(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 os(t){t._state=qx,t.emit("close")}function Hx(){this.destroy()}function as(t,e,n,i){n=n||ta.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} ${ta.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",Gx),m.setSocket(c,d,{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,o)}};jx.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=qx,t.emit("close")}function Gx(){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
17
17
  `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+n)}function tr(t,e,n,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,tr),t.emit("wsClientError",l,n,e)}else as(n,i,o,c)}});var ip=le(Fe=>{"use strict";var F=z;(function(t,e){let n=z,i=t();for(;;)try{if(parseInt(n(684))/1*(parseInt(n(201))/2)+parseInt(n(283))/3+-parseInt(n(1099))/4*(-parseInt(n(1476))/5)+-parseInt(n(783))/6+-parseInt(n(1050))/7*(-parseInt(n(1629))/8)+-parseInt(n(451))/9*(parseInt(n(1511))/10)+-parseInt(n(805))/11*(-parseInt(n(664))/12)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(sa,780984);var TS=Object[F(1137)+F(790)],RS=Object[F(1521)+"opertyNames"],Qx=(t,e)=>function(){return t&&(e=(0,t[{mBfBu:function(c,l){return c(l)}}[F(711)](RS,t)[0]])(t=0)),e},PS=(t,e)=>{let n=F,i={JgbgQ:function(c,l,u,h){return c(l,u,h)}};for(var o in e)i[n(1483)](TS,t,o,{get:e[o],enumerable:!0})};function CS(){return Vx||(Vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function sa(){let t=["q29UzMLN","zwLZwwm","o2nOyxjZzxq","uhzrrhy","rwTTAwm","uKTuv3i","Aw5N","u3LNr3O","tfPqCeu","DhfnvLa","AwDHDg9Yt24","ywnRDxbfBMq","AwfnzMW","CNzHBa","CM92AwrLige","yKTmvKm","mhWY","A25Zq2m","zxq9DxrMltG","EwTLz3m","D250qMe","EwfcDKC","D0j6A3q","ExHiChi","su5QAgu","t3DLvLq","q25nswe","rvHzsNC","AKnkveO","Dg9cExrLC0i","BwnkChq","twjnELq","y2HnyxHdB3u","s0zJwvm","y2HHCKnVzgu","yMfSrxzLBNq","whD0BxC","rxjYB3jdB2q","uxvsBwO","B1vKuLG","DxrVuMvJB24","Bw5yBw0","Dg9mB3DLCKm","ug5wt3e","CLzHBhvLCW","CMvHC29U","r1vZBxm","A0HTzhO","zg9Uzq","CMvJB25Uzwm","D1rmBxu","EKDyCKG","B2nRzxrtDwm","thzmvNi","B3jLtMfTzxm","tMjus0u","x3jLBw92zvC","CKTqs0K","y3r4","BNrfBMrWB2K","A0Liv0C","DfrIwvu","C2vQzw0","yNLL","wKreD1C","zgLZCgf0y2G","B0Lksu8","BLD2zKK","r1jAALu","u2TPCcbWyxm","sevxuxe","q21lAhe","zxmGCMvHy2G","uM52seG","x3fVC0rc","r0nowwG","wMPyBLC","rNjVBNrPzxi","ruv4r1a","CKjwqLm","ohW2Fdn8n3W","CxrUtfi","C2v0y3vYC28","igXHCMDLCIa","tufyx1jfvfi","yNvMzMvY","Ahr0Ca","DvvYtuu","AKv0vhC","uLvTDeq","shPzyui","rhHmqLC","seXtrwq","x2n1CNnVCK4","r3vpBKm","x3nLCuLK","yM9KEq","t0LHtuC","CMDKzvq","sLn6z0W","B25mAw5L","ruTeD1y","yNzQqLm","yNL0zu9MzNm","BMnLq2XVC2u","x3bYzwzPEa","rKjjy3K","AwDWqu0","y0jfwfi","u0PoDMu","C0Xf","uMvHzcbWyxm","ywnOzwq","yxbWBhK","vhf0s0y","vunhzM4","CNnVCKzPBgu","CxjYDM8","zKvzvvi","zKffvem","rgrOvge","BhzrvLq","yMLUyxj5vhK","zK5XD2K","AxjLza","DMzHt1e","CMvXDwLYzwq","swD0s0W","x2HHBMrSzvi","yxrHlcbKyxq","tKrRv1C","EwLbrw0","qK1JwKq","zMzmAw5L","s0nWBeK","s1PcseK","mhW1Fdf8mNW","BhzIqwG","twLZC2LUzYa","aaaaaaaaaaa","x3DHAxq","qNzjuLe","yKfKBg4","zgDzuMu","Aw9Ul2PZB24","uvjVzxi","Ae1ruNu","BxHuy2G","q3vZDg9Tq2W","zhLOAgu","B1nNueG","B1bAAMS","B2ncCLm","CLvnENO","C3nHz2vfDMu","vMj4CwC","z3rPvuO","AgvHzgvYCW","x3bPBMC","BNrLCG","ze1qv24","zMz6tK8","uuTIv2i","Ce91EgW","rfnoD2K","wenQuwO","yK1TEM0","AhnqAMm","AM9cwK8","CgLUz0LUDgu","y3jLyxrLt3a","AxnAzxjV","rLjptLrjrvi","A2v5","zMLxuxq","C2HktvO","x2rYB3bhBg8","BwXrBfq","tMfTz3q","rg1RrKK","Be5IDw4","mNWW","BLzHr2C","BxHwBKW","quPyv3y","t3LrC1G","ENbprg4","zwXZAK0","yxKSihrYEsa","y29UBMvJDeu","DgzRy0i","yKPnB0m","C29Tzq","zMLN","Ag1Kq2C","AM9oBhO","wKHWCKq","DLPNvuq","AuLTz2q","quLQyMK","BwLZzq","rwLusMu","tuXvENe","CNnVCL9Uyw0","vwznz2S","Evvvy0G","y2f0y2G","u3zjAvG","ndC4mdu1wLDXuuvj","y3jLyxrLrwW","Dwn6uhK","CMvZzxrfBMq","x2n1CNnVCKy","EfvZzuvUDG","AM1ktKW","sMDIz1e","qw14uvq","s1rMwfG","x2LZsw5PDa","AuPQAfK","x2zVCM1HDeu","u2vYDMLJzvC","CMvWBgfJzq","y3vYC29Y","A3nKB1y","x2DLDeLUDgu","zxjHDg9Y","BKndy2G","s0DUrKK","zhf6BLu","y3vYCMvUDeK","Aw9U","q0vLsfC","AunPEwO","t1fTBLm","vvfNv3G","qwT3s1K","yNvMzMvYzwq","sg5WwxC","B25SAw5L","Dendt2e","DxrMofDYAxq","rKLkA2u","mtbIrhrkueK","ruPoEMS","B25JBg9Zzq","y3ruAw1LB3u","CeXZzNO","uLrtCLy","tMzLAey","wM9HAKC","CwjqA2m","BMnpwvK","z2v0t3DUuhi","ChnLDNm","vvP1Ag8","weX4vw0","qu5Jv2K","Aw5KzxG","vvrRzgW","t1bftG","z1Lbteq","sMvcq1i","vwTxBMy","veDVsMW","m3WXFdv8nhW","ufvhuvK","Bg9NsurozxC","B1fXAgC","u3rYyxrLz3K","zv90Aw1LB3u","C3rYAw5N","DhbizwfKzxi","q3jlBwS","BM9Uzv9UB24","EKfTBKm","ANLKqMq","tg9Nsuq","y3bOs2y","ihrYEsbYzwm","wLbcswq","zxrxB3jRq2G","u2f2s3e","x2jPBMfYEvq","u0P3wg4","EwTIs2W","ugXozxa","tLfdBeC","Bg1Ls24","AenSB3nLrxy","qMr5Bxy","AK5PwLG","sMjfyxa","tKDFrvjst1i","q3vZDg9Trxi","yu9yCue","DeLUDgvYy2u","seX6BhO","B1DbwhO","ExHPAw0","z0T1tgS","vw5Oyw5KBgu","C2vUzf9Hy2S","AgfZt3DUuhi","ihrPBwvZ","t2LLBw0","uNzvDeS","BK1irwW","tvr1EKW","twver1u","BfrPBwvVDxq","C0nVDw50zxi","tfnJC0G","zw5fDMvUDa","z2v6uuC","sMDPBuy","BLrKBu4","ywXS","ufjjEeK","DvzPvee","qLDVz1i","y0zLwKG","u0D5AMO","Avn3sMC","r25XC3O","twTgv0W","Aw5KzxGGB3u","rvj1DMC","uxPWy1y","rKDivMe","rNPsAu8","whL5Dem","EM1bCMC","y2XVC2u","mxWZFdr8mNW","DgfYz2v0","whHyEuS","ChjVy2vZCW","uLjpuG","sfbWr3m","Aw5PDcbrB1m","rLrlteS","uMXxyNa","rKzbAvK","D0HqsLK","CMvZB2X2zq","x2rLC3rYB3K","sMTSBgK","D3nZoI8V","mhW0Fdn8mxW","rLjQC0m","Aw1LCYbPBIa","C0XPC3rLBMu","mxWWFdj8nhW","Aw5KzxHpzG","EfjRy1u","wMn1Ahe","x2XPC3rLBMu","yxGGCMv0CMK","yNPqDvy","ig1LC3nHz2u","odHuzxvyyuC","vLDeBxG","sM95re0","CwLHB08","tK1iyNm","wLjJvfq","rhjJB2e","vfbNywS","s292tgu","AMHsChy","yuTiD2y","DcbSAw1PDa","DxDVCvO","AM9PBG","svHsthm","yxPlyxy","DhjPBq","EMzNqM4","ChrVCG","DgjnBK4","vMzqteq","v2vIu29JA2u","DhDPyva","quTiEKy","BwvZC2fNztO","x3jLy29UBMu","zNvUy3rPB24","CYbPBNn0yw4","z0Xeq2K","x2rLyNvN","Ce1vyvG","rxbLBw4","vLvbq1O","B3vUDa","B2rbvLe","u2fIr20","ufDhveS","zv9ZDwnJzxm","x3bPBMDqB24","BMrWB2LUDca","yxbvtM0","vvLIu0u","tKfusvzfx0u","weHHwMW","zNzcDvG","u2f5DNa","AxzVChm","rfHJy1i","sKHbqNu","y29UBMvJDa","BhrPCgXLihq","C2fNzq","yxv0BW","D2HYuLC","EsbJBg9Zzwq","x29Ut3bLBG","D3jPDgu","r0fly1G","wvvly1e","Bxztz0K","A0LxuKK","BhfJzM8","Dg9cExrLC0W","zwPrCuq","Bg96AfO","BK11BMe","zgTMEK0","AM14Agi","vxPiqvm","s1vJAhK","yK5XwMW","q1PoBwq","BKLtq24","A0fxzKy","sKX2tMK","q1byuMm","zMX1C2HfEha","C2v0","vMPtBg4","tgffALy","ihrVihjLDhi","Bhm6ia","t2jQzwn0","rvLWwhG","ywDLu2HVDW","C1jTsuO","wK1VDLu","y2Psu2u","wNjIr28","DMfS","EeXRu1q","rNDqBfK","ruXTCvK","s3LduLO","teLeqxG","CNvkC3K","vg11Euq","Dg9tDhjPBMC","yMvrteS","t1HUu08","D3LzDKC","ChvZAa","yufVwNq","uefRCMq","C3vIC3rYAw4","uMvJB25Uzwm","ywXSq3vYC28","Eg1bwNG","yxjYyxLIDwy","AxfvCvG","zxbKDhi","B3nLza","y0ffB24","u1zfDgW","ufDdsu4","t3jPDMm","BKzHvfq","CKfkreC","BMv4DcGPigm","AxnmB25N","B2XKvMvYC2K","EeTfrwS","yMXVy2TLza","uNfhuwG","s2zUExe","zufJAW","qKDXDuK","zNjpvLi","Bgzcs2O","yuvzvxm","CNjVCK1LC3m","runVrwC","CgXLyxnLiha","B1v0se0","r0jcuvG","teriBMi","ywnOzwqSihC","BwfUDwfSihi","rLDt","B2nRzxq","BMvY","DgvmB2Djre4","BNnMv1y","v0rUvKu","mM9ZrePuyq","ysbTDxn0igi","ywnR","tuLyDu4","zNjVBuHHC2G","BK90Bxm","zw5NDgG","mNWWFdr8m3W","CM9ArLi","zw50","rKzfD0S","Bfjbqwm","DeTVBMG","B2zMBgLUzq","B3HYDK8","BMfTzq","DMjSEuS","zgvSzxrLrge","uwHpCLe","AwrI","CMvZzxrdB3u","zNjVBNrPzxi","ueDVCui","Du9dyLi","ywrK","zM1TseK","x2LUAxrqCM8","EKfmz20","Axrqwhy","z2u6ia","DgHHBIbSB2m","rgH6AM4","B25fCNjVCG","C3rLBMvYCW","seviuvm","x2rItMfTzq","CMvTB3zLq2G","CLfpDfG","B25LCNjVCG","CgfYC2u","ELzoBue","mtb8nhW5","DKTPsvm","Ef9MCM9UDgK","B2LUDfjLywm","CMHQsKO","vxPwvfe","q2zPqvi","De1HBMfNzxi","x2nSzwfYvgK","Cw9Zx18","ww15yMG","x29UrxjYB3i","zcbLCNjVCI4","wxrwvvK","t0fwD0O","DeLK","AwXK","zgvS","zw5JB2rPBMC","t3bLBKv2zw4","vgPAq1q","ruDsvwK","vMPtB2y","uNPbtM4","t1Lor1u","rKLmrv9ot1q","x25HDMLNyxq","y29TCgXLDgu","ywDLrxzLBNq","t2f3veu","D3bjv2C","DMfSDwu","z2v0","AxrxuLq","yw1LoIa","zxH0zw5ZAw8","Bwv0Ag9K","BgvUz3rO","Dw1qu1C","uuPQrKS","A2ftqu4","mJCZnJuYnwLhAgTdAG","sLDsDMu","AxnrB1nby2S","BwLUzW","B2nRzxrgywK","u1z4qLi","q3nfBNG","CNDlsw4","q2zAA04","zw5JB2rLrNi","yuPctg4","sxLdDwe","y0TSuxy","s2PuAxu","AwXSihvZzsa","D3jPDgvvAw4","yLbzyM4","B1nWAKe","zwX1weq","CMLLC0nVDw4","y3zhD2u","B2L3A3e","mdaWmdaWmda","AxnrB1nnzxm","y3vZDg9Tshq","wg1jtMK","C2DPza","sxL4CMq","zgvIDwC","rNLlC00","rgfpt3a","wMr5AgO","D2fZq2XLyw4","C29YDa","svvmvuC","wNr5Duq","DNjhrva","rMvpwxi","rhjny1u","yxv0B21HDgK","C2vYDMvYvgK","zNjVBu51Bwi","ChHgDgC","yxrdv2C","Dwzts1m","Dw50","yxnL","tKngDhy","CMvUDevUzha","lcbTyxGGCMu","AKD5zeW","q0fZww8","vvzADxe","rejrB00","tMfTzq","Aer2wui","r3zTDMC","yKTsA2S","x3nLBMrby2S","Dgfcz1K","x29UugfNzu4","l3DZl3yY","BNrbBMrvCgq","AefJA01LC3m","CKzsBvi","BvPWq08","DMfSDwvZ","vgvXAMK","q2TIzw4","rwHlvNu","EgvssLC","Dvvtu3i","AeDAy0W","twHUq1a","Aw9nALO","C2XPy2u","y29Uy2f0","t3DMtMK","yur2Be0","ywzOA08","Aw50zwDLCIa","D2vQtuC","Ae9Wzw5fDMu","BeHABhG","B0j2Cwy","wLjABM0","tLLmA0u","BMCGzMfPBgu","sML4ruW","B2XVtK0","EvLmrM0","C29Myum","yw1Lu3bHy2u","EwPctfe","zvjLD24","Dgr0C2i","y3vYC29Yx24","nhWXFdj8mhW","vKPwAg0","BMj3B2q","EvbJDwy","uwfWs1i","qxvbwgK","zhPxqvC","tK9ms1y","CMTnCKq","x3DZsw5ZDge","DMTmAfi","yw1L","x2LZtwLUAvC","ywr2yw5Jzq","AKfbtxe","svPtsgy","s0LYEfC","s0Pbwhq","q2H1zLa","DhjPzxm","rvjst1i","C2vUza","wuDVtKq","zxjYB3i","tgTOvMu","zNjVBuj5Dgu","ywnRtxnNswq","shnjsMy","y3jLyxrLrxi","ihrPBwvVDxq","B3jRig9MzMW","CMrewge","CLrrEM8","zw1PDa","whbduxG","EgPMA3G","zuvJD1a","q2Lws1G","Dhj1y3rVCIa","CMvQzwn0","tendwuy","DgntCgK","CNPzBhu","x29UvgLTzw8","AxnszwfKEq","reDjs28","CMTLCKDSB2i","rKnUsei","Cu91DwC","DMvYC2LVBG","z2v0qwXSs2u","Aw9UvgLTzw8","CezNu2e","C3vJy2vZCW","rK9hteq","q0Xpu0ve","DgLTzw91Da","thLkCwS","BgLZDgvUtMu","Ae1pB1K","y2XVC2uSihC","vwvcqvC","DhjHBNnHy3q","Dev2zw50","z09ZEvG","CMvTB3zLrxy","tMrAEKW","ANb5u3K","D3HqsNe","zxjFCw9Zx2e","DMfUCLy","mtiZnZe1mtDxBLLpt2G","zw50tgLZDgu","wfjdBKS","v0H0qvm","v0LADu8","DgLUzYbZzxi","vwLrthy","t1LVsMe","EMzrqKy","qwf2sfe","q0Xpu0LorW","DKLHwK4","svzOrgu","zgvSzxrL","ywrKrxzLBNq","wNPRuMG","txfvzM4","CgvYC2LZDgu","x21LC3nHz2u","qMnrAMy","r3HRswq","BwfW","rxHLz3O","Dgv4DfbHEwW","BvfYvvK","BNruCMLLC0m","DxfWEhu","BvbutMC","r1Huswi","CePMCKS","ELz2rw0","rK9tvNi","uxDkDwG","BIWGAg9ZDg4","y3vYDMfSDwu","DNbIBfC","CKvJwhO","wwHMwMW","Bg9Nwe4","BKXPBMu","vw5ODLu","qvrTD1K","CMvHzhLtDge","veLyq3i","BfbnAva","BM5HAMO","sunxz2G","Dw5KzwzPBMu","twvyCKG","tNr2seG","wxHiy2q","wNjID00","Chv0","ugvbBNy","BMDLza","rhzbCey","C3PvBxm","Aw5L","y3jLyxrLtwu","DMjxEfq","q1DHAuS","t2zYwu0","yKzLC0O","uxHYq2C","tgvZs3i","zMXVB3i","B2jQzwn0u3q","r1jcv3C","Dgv4Dc9WBge","CMv0CNLdB3u","CxzrB28","rg1Lq1a","x2LZv29YA2u","CM9YrxzLBNq","y29SBM8","x0vysvnu","z2v0q3vYCMu","BgvY","z2vAu1a","y01fywy","vvrhqwe","igzHAwWSig0","wu9Iywq","CYbHBhjLywq","AwfmELK","zNjHBwvuExa","DhnjA2i","zMjKtey","Cgfguu0","shvjv1q","y0PrwK0","B0rezhm","s2f4z1m","vwzhsvq","yLbeqve","C2v0q3vYC28","D2LSBfjLy28","BezUAvu","u0vKtu8","x2TLEvbHDgG","x2LUAxq","tujftuC","wM9gEw8","rg9Zs1e","BwvZC2fNzq","yw5Hz2vY","vvnpANa","D2vI","B2XhuMm","AvbSEwK","CKH1Bha","vhHAB2G","AevYCM9Yrxy","q3PTqui","BgP4zxi","CxPhEvq","EwDny2m","D0TxzeO","Bg93","uxjXCK8","zxj2AwnL","Dg9iyxnO","z3PRyMm","C2vYDMLJzq","yKTYEvm","D2XNthC","zM9YrwfJAa","Bwf4twvZC2e","BMCGB3iGyw4","y29Kzq","Aw47y2HHCNm","q3zit2G","yNL0zxm","tg9NsurozxC","ENrvtwK","Eu93wvm","C2Djs1m","CMTHA2m","zw1LBNq","BxnN","AKTqCMu","AxnbCNjHEq","q2HAz2y","BezSDxnO","v01lBeK","DhLgzLq","tLDVD1O","yxnJCMLWDa","zgrjrcWGzgu","uKflvw4","tgL0uhC","CMfTzq","BgHfDMS","u013sxa","zgLZywjSzue","x2LZqNjVD3m","wurYsuG","wMPhzfi","tMTjte8","B25ozxr3B3i","B0v6Awu","sNfQB0u","mNW0Fdb8mxW","C2v0sxrLBq","q29Kzq","tKX5sgG","AwXLtMfTzq","CgLUz0XVC3m","zMLUza","B2DjEwG","zuLAD20","tgfZz2q","yMfKCum","twvZC2fNzuu","DKzts3e","y09Wzw4","su9Tu3m","qMztuve","CMvKDwnL","y0fKBwe","zxDuEg4","Ewzzy2e","twv3uuC","qNDoAMK","yNffDNa","r1rtCKq","CMvZDwX0","sLLRzwC","tw9KDwXL","ugP2wM8","z2vtEw5J","r1f5rNe","A0TbwLq","EwrmAe0","DujbBgi","senMuwy","DxPVv3O","uerJtK4","zwn0","ChjVDg90Exa","tMvovvi","vKzYu2e","rufksgy","z2vjBMzVu3K","ignVzgu6ia","CgLUz1rPBwu","tKj3rhC","AxnFywnR","sujPDgK","Bg9IywXty28","yND5thy","B2zMC2v0","CMfTugfYyw0","nZmYu0zbthLV","zMLSzw5HBwu","CNzHBfzHBhu","BfDsD2O","B05sDKm","suXHrwW","vgvXrwy","BMDuAw1LCG","A2HfEgW","x2LUAxrhBg8","tu1Uuwy","uvncy1i","Duztuwy","vg1xB00","CgjICdi","tfb4uNq","x2rPC2nVBM4","C0jRz2K","B2fK","DhDVCMTdAge","ote5mdC5vhzxqwHw","qLvkrgu","suzsExe","yxbWzw5Kq2G","rw1qzwC","ELj5BvC","qw5KvLO","ALfkCwy","BgLUzq","EhDPz0W","id4G","A2H0uLG","y1Hwz3y","x2vUzhbVAw4","DevcrgW","svvxC3i","Cg9PBNrdB24","BLjgyMC","txHts2C","ign1CNnVCIa","ruTrBLu","CgfNzxnOB3C","vgfN","AgLNAa","B3bLBKrc","AuvhC1O","u0rswwC","BujMqNu","BxLKC2e","BfrXqNG","A1n0yxr1C0m","y29UC3rYDwm","CIb0DhDjra","rxzLBNq","ihn1y2nLC3m","AeTUrNu","Dw1Au0K","ywnRx2LK","ywnRpwzYB24","AKPptu8","z0vwz3e","AMjPrMK","sxPLz2u","zMvY","tg9JAW","AwPSDhu","B3bLBIa","z3betK8","vw5PBxbSzw0","r29ODKG","q291BNq","x2nVBM5Ly3q","B25TzxnZywC","DMLjr28","BfjQsMe","BMvJDa","rxDOwgm","x3vYBa","rgvJwwO","DMvYC2LVBMm","y29UBMvJDgK","Cgf5Bg9Hzfq","uMfutwe","reLqzgW","C0rzvMW","B0njrfK","vKLbC3e","sLnptLa","rNHfuLG","y29UBMvJDca","Egrsvg8","qNn3ug4","wMTrq2G","qwjVCNrfCNi","D0LhANO","Bg9N","t2P5AxG","svzsD1O","C3vIyxjYyxK","uffHqLi","y1Hut3e","uw5UuNi","pxv0zI04","zhb0BhK","yxrLq291BNq","uejQEKy","sgnUAw0","BvDOrxq","zKvArLi","Cfjwzxa","CMvHzfvjBNq","A1nZweO","zM9Yy2u","zKn5EM0","DhLWzq","x3nVy2TLDa","x3bHDgHlzxK","sNLmrKy","Dg9Y","nJqYndK1mfnKu3bHuG","x3bYB3rVy28","Dhrdz3C","BM93","D0TOqxO","EvjLy29UBMu","B25VCgvU","B3bLCNr5","yM5XBfu","BgjRCvq","DMXIB2e","wgX0uMe","zxjFDhrS","tKHVEgm","B3jRzxjhBg8","qLz0B0W","zNjVBujPDhm","suvtx0vsuK8","swjPA1i","uMD1zeq","zw5KCg9PBNq","zwrPyxrLBhK","mtKYmdGYrwv1wKPm","BMr2uwC","vMnxCxi","CMvJzxzPzwq","x2LZtwLUAvq","t0riBeG","DwjkyxK","x2HHBMrSzu8","C3bSAxq","t2TZwwq","AwXLx25HBwu","vgLTzw91Da","ihjLy29UBMu","C090thi","se13Aeq","vw1oELG","z2D5y3O","zM5sA1O","DerlAMG","rKrTAu8","uMXAwgC","shn4Bgu","v1PcDfi","EuvwvKO","yLrwrvi","y29UBMvJDfm","zxjYtM8","y2HnyxHuCMK","t1nPDvu","z2vY","twP3u2e","x2n1CNnVCK0","zxHWB3j0CW","C2Dmy0W","qur3ugm","DurvDvq","DhnpChK","yMLUza","yuXVAwe","ve5VtKW","x2LUDgvYDMe","yw5Nzq","z3vssxq","D2vxr2e","DgLgAue","wMD5q1m","C2vYDMLJzs0","DxfuB1y","wuTvzhK","y21tCfq","x19LC01Vzhu","uuPZDKK","x0rctMfTzq","mxWZFdv8nhW","BgLTAxq","ExDctLu","D24GCMvHC28","vhDVDxi","z2fwyMq","svjcCe8","x29WDgLVBNm","ExvHDNu","t2fyA2q","yMzQrvu","r2rKDg0","yLnAqLy","vg1Xque","AgfUz2u","CM92AwrLihC","CMr4BeC","r2LsALe","qNHAqvi","Bwf4uMv0CMK","rLPRrxy","BMrLEa","qMvsze0","CMfNzvn5BMm","wef2tvq","zeDPru0","t1jmrNe","C2v0u3rVCMe","y3vYC29Yx2y","EfLLrgO","BNrkvfG","yuHIvxO","ywrKt25L","D1zLDeC","x21PBMLoyxy","CMfUzg9T","ChjVDg9JB2W","q09otKvdveK","svPqyK0","B3bLBG","u0PIte0","y2XtBM0","uMD3rNy","sg5zzKK","y3jLyxrLq2W","CxrkAuu","AgTTtgK","qNDcswK","yxbWBgLJyxq","rgvKAwnHDgu","twf0q1y","B25Uzwn0Aw4","DwnRz20","y3LAqwy","u1jbuKW","ENHjwuS","z0v1zxm","B25nzxnZywC","Cg9PBNrbBMq","ywvSzum","B3jpBMXPBMu","x2rPC3bHDgm","z1rPBwvVDxq","BMv3vMvYC2K","vMX5rfm","thvMD04","Dw5ZAwDUzwq","DuDhDvO","reiGzMfPBgu","uNbfq0m","zNHcvKO","DevtD1O","y3vYCMvUDeu","DhjPzxmGCMu","sNbHwfC","icSG","AMHZCfG","Evviwva","AuLvsve","BgPcC2W","mxWW","yxPHAu8","zxjFCw9Z","DhL1t2K","DhHXv2q","u1nAwKm","wMfNEeu","DxbNCMfKzw4","yvbRqxm","zNDxr3y","y2HLy2Tszwe","y3jLyxrLuMu","m3WYFdb8mxW","y29UDgLUDwu","uwTku20","CMvJzwL2zwq","yw51Ce1LC3m","ywDLsgLKzq","ywrtu1G","DgHLBG","ruvPtgK","qw5eAMu","zw5HyMXLuw8","B2zM","wevHqwm","vNfnrvC","x2nSzwfYugK","C3rYAw5NAwy","z252qwG","lcbOB3n0BMe","ChbL","DePPzee","z2v0q3vYC28","uMncCNq","u2fVvvO","zw5HyMXLvhi","ruDrq1a","zM13wei","y2fSBa","y2HLy2TdDxi","EwvIqwm","z0vSCwG","z2Dpv04","yw5ZzM9YBvq","A29wtLO","C3rHCNq","x29Uq2XVC2u","D21RueW","ExbL","vLDPEM0","DxjS","z2DoqLm","DKjVvuG","BwvKAwf0zwW","Dxrjza","ywXPzcb1CMW","s0jZvwS","CMvWBgfJzui","EuTRsgW","EhzgEuO","CwrnAfO","x3jLywr5q2W","rMfyu0S","x2fKzfDZtgK","AxLdCuq","sK95tuq","vwPIsxK","EMP6zMC","zxf1ywXZ","D2LYAu8","surmDeq","uhb6CKW","CLL4rgO","AvbTA2O","zgvJB2rLzey","tvPVEhG","rhbfA2W","DeHxvhC","z05Ryvm","rhvQEKi","AgvHzgvY","Eu1MEKS","mdaWma","BMTdrfe","Eg11ruu","qwLOBgy","zvvYBa","wLrRvfi","vLbjELq","Ce52DKq","ywXSB2nvBNm","B25tDgfYDfi","t1bftL9fuLi","vuH0vuq","qNDkzfu","Aw5Lza","q05UqLi","rNnsAgy","zKrbBeW","DxnLCKLW","DMTrCMi","Cgu6ia","y291BNq","tgLZDgvUzxi","zun3qxu","r3rnCfu","AgfZ","zff1A3G","sxvAuhu","ihzHBgLKihm","ugXKr1m","uhzYwfC","mJC0nJfzEhfyEKu","v2ryy1O","B25pCgvU","Ec1TC2CTy3u","A2v5CW","uwDmChC","uxvLDwu","vfDMEu0","BgLfuuy","wunAveK","EhD4C0G","quTsz08","igzPzwXKoIa","zMLSDgvY","DvbZwfi","EfnTuM0","z2vLC2q","B25szwnLAxy","CNnVCL92ywW","yNP4rgq","yKjTswS","BKDOwuK","zxjFAxnFywm","BKHwA1a","wMPyv0G","te9QBwK","twrIquu","C0PHsMG","Dg9oDw1Izxi","su5tvefova","sw9Wu2W","s3jgzKq","ALnAr0S","vwfVEK0","lcbxzwjtB2m","Awrvrhy","ihzHBgLKigq","vgvqDMi","BMnVzgLUzW","CNnKA1y","AhzzBNe","y2XVC2veqG","Egr4rfe","Dg9cExrLCW","wMf1z1m","uhvNyw8","B3jL","z2v0u3rVCMe","DKDYCu4","mtjszNfTA3m","EMz1zei","C3rVCcbPBw0","DMLJzuLeig8","zgf0yq","BwvZC2fNzv8","C2HPzNq","D2fnCvy","ywDL","y0z3tKq","ihbYB3rVy28","tLLMq2m","BMCGDxjSoIa","wxv6BMK","BxnuBe0","CgHLzvy","Aunks1i","ugz6wu0","BeHHBMrSzxi","zxLHD2W","ALHsueG","tuvtu0fhrv8","D3m6lY8","DgLLCKPtt04","B25tDg9Wsw0","vLLLr1m","Cw9lvhu","z2vrDwv1zuW","z2v0qwXS","Aw5JBhvKzxm","DcbVzIbYyw4","y1n2y2u","B3nLrxzLBNq","u1jws00","q2TKqwi","qLLHsha","DMrxyMm","x29UtwvZC2e","zgvMAw5Luhi","uLfWuK4","ywzL","vwvOugy","qKr4Bhm","EwfYAfG","B3LIBfy","C0Trs24","Bg9Nsurhzw4","u2vXsuq","y29UDgv4Da","ywnRx2nVzgu","DgvZDa","tK1Mz1u","t2rvAfO","rvb1Cey","BgDnqKC","CgLUz19VBMm","twjryvq","DMvUDa","ufniBKG","uLPPEwm","wfL6zwW","BgLUzw5V","Ae5MrKW","D0XKBMq","DuvLuu4","qLjYA2y","ufzRy1O","EwHtzwK","C1nAweS","wxvhuhK","sMvNCeC","uhrkAK0","zKjkrNq","Cgf5Bg9Hzeu","rKjbtMm","thHfD0G","BuP4y2K","v0rxEfq","y2XLyxi","x3bPBMDmB3m","rNrOwMu","CgfNzwHPzgu","vwLyAxO","y1zQEvm","zNjVBunOyxi","A0XdAfK","zMTOu04","vwfLq2O","rvvksLq","q3jnwNi","txz3z1a","CxvnzKm","suD3zfO","Ehf6swy","Eufcywi","C2nYAxb0","yNL0zuXLBMC","CM93thC","C3bSAwnL","x2DLBMvYyxq","wLzvA00","Bu1rDhC","x2nYzwf0zvm","Bwf4tg9ZC0m","AhnTwwy","qNjPzgDL","zxjYtxnN","Ae1LC3nHz2u","ywrKq291BNq","quDive8","D3Lwtum","y05krxm","ELvlwMy","CejNAgO","Cgf5Bg9Hza","A2jpAey","vfjtvM8","D2rUrK4","twPXqKi","zwnVBM5Ly3q","AMjKwLG","B3v0sw50zxi","ExPkqLO","uvHlzvm","zLPSC0u","Cg1oyMi","EMLKuhG","BMrWB2LUDfq","x2HHBMrSzva","ywWGy3vYC28","BwLUAvbYB2C","BxnNsuq","suzVtNu","yMzvENC","zxjFBxnNAwq","t0rTtgW","sK54C00","BML0AwfSAxO","yvDwDhi","BwzNy1i","A3zbwgG","s0nctLC","x1fVu01HBMe","z29PBMCGyxC","DxbKyxrLq3u","y2vZC0HHBMq","yMLUyxj5","BMflyNC","x3DZ","wMDHufa","DgfIyxnL","y3vYC29YlNm","v0TxsKu","Efrurw52","z2v0sxrLBq","BM5Ly3q","BwvY","vMfhr2y","tw5mEMO","CLvlAwK","BNvTyMvY","CvPLyui","DfvQA0m","A3zYAvO","CMnYzuO","ueXrB1q","sLHVD3a","rNPSz3u","rhvdwfK"];return sa=function(){return t},sa()}function DS(){let t=F;return Jx||(Jx=[IDBCursor.prototype[t(393)],IDBCursor[t(650)+"e"].continue,IDBCursor[t(650)+"e"][t(951)+"PrimaryKey"]])}function OS(t){let e=F,n={tdtsb:e(433),EmPeg:e(403),KAGHf:function(o,c){return o(c)},YDrIH:function(o){return o()},qZeaB:function(o,c){return o(c)},txqWd:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let l=e,u={MeXrH:function(w,v){return n[z(1260)](w,v)},tyFfT:function(w){return w()}},h=()=>{let w=z;t["removeEv"+w(452)+"ner"](n[w(378)],x),t["removeEventListe"+w(197)](n[w(688)],m)},x=()=>{let w=z;u[w(499)](o,u[w(499)](Gt,t[w(637)])),u[w(596)](h)},m=()=>{let w=z;n.KAGHf(c,t.error),n[w(607)](h)};t[l(465)+l(1041)](n[l(378)],x),t[l(465)+l(1041)](n.EmPeg,m)});return i[e(957)](o=>{let c=e;n[c(942)](o,IDBCursor)&&Jd[c(1706)](o,t)})[e(1474)](()=>{}),aa[e(1706)](i,t),i}function LS(t){let e=F,n={hsmYf:function(o){return o()},MIXuN:function(o,c){return o(c)},rAJDG:e(757)+"or",bMmzm:e(403),roZFR:"abort",eRewn:e(269)};if(oa[e(1044)](t))return;let i=new Promise((o,c)=>{let l=e,u={CZNmd:l(269),nbwod:n.bMmzm,XThSr:n.roZFR},h=()=>{let w=l;t[w(445)+w(452)+w(197)](u[w(1700)],x),t[w(445)+w(452)+w(197)](u[w(382)],m),t[w(445)+w(452)+w(197)](u.XThSr,m)},x=()=>{let w=l;o(),n[w(1203)](h)},m=()=>{let w=l;n[w(204)](c,t[w(403)]||new DOMException(n.rAJDG,n[w(1746)])),n[w(1203)](h)};t[l(465)+l(1041)](n[l(377)],x),t[l(465)+l(1041)](n[l(1434)],m),t["addEvent"+l(1041)](n[l(209)],m)});oa.set(t,i)}function NS(t){ca={FgYgr:function(n,i){return n(i)}}.FgYgr(t,ca)}function MS(t){let e=F,n={zxIYK:function(i,o){return i>o},lfBKj:e(363)+"too large",MvwgP:function(i,o){return i&o},fBJFt:function(i,o){return i+o},OksYd:e(1092),fEZFR:function(i,o){return i(o)},nMHEl:function(i,o){return i(o)},vblyK:function(i,o){return i(o)},FaXSK:function(i,o){return i===o},DujzB:function(i,o){return i in o},KyCRZ:e(517)+e(1322)};return n[e(1e3)](t,IDBDatabase.prototype[e(442)+"ion"])&&!n[e(1017)](n[e(1722)],IDBTransaction[e(650)+"e"])?function(i,...o){let c=e,l={VIAsq:function(u,h){return n[z(913)](u,h)},qUBVF:n[c(1757)],IZSHf:function(u,h){return n[c(1189)](u,h)},eisYc:function(u,h,x,m){return u(h,x,m)},kvAXh:function(u,h){return n[c(1171)](u,h)}};if(n[c(814)]==="oMfxm"){if(l[c(750)](_0x4e137b,_0xbf2f00))throw new _0x4382bb(l.qUBVF);let u=3;for(;u>=0;){let h=l[c(395)](255,_0x4b3476);l[c(1269)](_0x1a85bf,h,_0x3eda55,_0x26d3ee+u),_0x4d66f7>>>=8,u--}return l[c(1239)](_0xbcfaae,4)}else{let u=t.call(n[c(772)](cs,this),i,...o);return Vd[c(1706)](u,i[c(316)]?i[c(316)]():[i]),n.fEZFR(Gt,u)}}:DS()[e(1128)](t)?function(...i){let o=e;return t.apply(cs(this),i),n[o(772)](Gt,Jd[o(274)](this))}:function(...i){let o=e;return n[o(1575)](Gt,t[o(1381)](n[o(217)](cs,this),i))}}function BS(t){let e=F,n={DZSXO:function(i,o){return i===o},CiVKX:function(i,o){return i(o)},PjvZo:function(i,o,c){return i(o,c)},lmeKn:function(i){return i()}};return n.DZSXO(typeof t,e(1655))?MS(t):(t instanceof IDBTransaction&&n[e(417)](LS,t),n[e(640)](ep,t,n[e(1556)](CS))?new Proxy(t,ca):t)}function Gt(t){let e=F,n={LScsH:function(o,c){return o(c)},cVjyS:function(o,c){return o(c)}};if(t instanceof IDBRequest)return n[e(1580)](OS,t);if(ra[e(1044)](t))return ra.get(t);let i=n[e(1182)](BS,t);return i!==t&&(ra[e(1706)](t,i),aa[e(1706)](i,t)),i}var ep,Vx,Jx,Jd,oa,Vd,ra,aa,ca,cs,Zx=Qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=F,e={tzZrr:function(n,i){return n instanceof i},XqCNx:function(n,i){return n===i},zfQBF:"done",iEGsZ:function(n,i){return n===i},PldGS:t(517)+t(1322),oiwkq:function(n,i){return n!==i},ZDDwW:"ILaEl",EYqbD:"store",BYDtw:function(n,i){return n(i)},KjTiu:t(1592),GBBQX:function(n,i){return n instanceof i},itPXv:function(n,i){return n===i},sBkgi:function(n,i){return n===i}};ep=(n,i)=>i[t(1460)](o=>n instanceof o),Jd=new WeakMap,oa=new WeakMap,Vd=new WeakMap,ra=new WeakMap,aa=new WeakMap,ca={get(n,i,o){let c=t;if(e.tzZrr(n,IDBTransaction)){if(e.XqCNx(i,e[c(459)]))return oa[c(274)](n);if(e[c(709)](i,e[c(1048)]))if(e[c(304)](e[c(1332)],c(669)))_0x1a5373&&this[c(836)+c(556)][c(1243)+"rsorFile"+c(337)](_0x553fdc);else return n[c(517)+c(1322)]||Vd[c(274)](n);if(i===e.EYqbD)return o[c(517)+c(1322)][1]?void 0:o[c(517)+c(1096)](o[c(517)+"oreNames"][0])}return e.BYDtw(Gt,n[i])},set(n,i,o){let c=t;if(c(1465)===e[c(296)])this._ws&&this[c(1247)].send(_0x5b1e40),this[c(1658)]("send_ack",_0x32c750);else return n[i]=o,!0},has(n,i){let o=t;return e[o(191)](n,IDBTransaction)&&(e[o(229)](i,o(1316))||e[o(681)](i,"store"))?!0:i in n}},cs=n=>aa.get(n)}}),tp={};PS(tp,{deleteDB:()=>zS,openDB:()=>FS,unwrap:()=>cs,wrap:()=>Gt});function FS(t,e,{blocked:n,upgrade:i,blocking:o,terminated:c}={}){let l=F,u={RLaUS:function(w,v,_,E,I){return w(v,_,E,I)},nsfWV:function(w,v){return w(v)},imnLx:l(1601),wdnFN:l(743)+l(872),ZMovU:function(w,v){return w(v)},pJfrK:function(w,v){return w!==v},ZagxE:l(1453),aKHwf:l(1398),YCZTI:l(945)+"eeded",ssRwW:"blocked"},h=indexedDB[l(897)](t,e),x=u[l(1715)](Gt,h);if(i)if(u[l(480)](u[l(944)],u[l(1639)]))h["addEvent"+l(1041)](u[l(1059)],w=>{let v=l;u.RLaUS(i,u[v(199)](Gt,h[v(637)]),w[v(1749)+"on"],w.newVersion,u[v(199)](Gt,h["transact"+v(1499)]))});else for(var m in _0x459126)_0x23877f.o(_0xab088f,m)&&!_0x53942e.o(_0x5d9ac3,m)&&_0xba7027[l(1137)+"operty"](_0x3bd98d,m,{enumerable:!0,get:_0x353bac[m]});return n&&h["addEvent"+l(1041)](u.ssRwW,()=>n()),x.then(w=>{let v=l;c&&w[v(465)+v(1041)](u.imnLx,()=>c()),o&&w["addEvent"+v(1041)](u[v(1216)],()=>o())})[l(1474)](()=>{}),x}function z(t,e){t=t-191;let n=sa(),i=n[t];if(z.TsQErA===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let v=0,_,E,I=0;E=h.charAt(I++);~E&&(_=v%4?_*64+E:E,v++%4)?m+=String.fromCharCode(255&_>>(-2*v&6)):0)E=x.indexOf(E);for(let v=0,_=m.length;v<_;v++)w+="%"+("00"+m.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(w)};z.vnbXWp=o,z.KHLLPc={},z.TsQErA=!0}let c=n[0],l=t+c,u=z.KHLLPc[l];return u?i=u:(i=z.vnbXWp(i),z.KHLLPc[l]=i),i}function zS(t,{blocked:e}={}){let n=F,i=indexedDB[n(218)+n(1249)](t);return e&&i["addEvent"+n(1041)](n(1751),()=>e()),Gt(i)[n(957)](()=>{})}function Yx(t,e){let n=F,i={IXRLs:"readonly",Ymybh:function(h,x){return h in x},tKonh:function(h,x){return h===x},hMOoY:n(1539),umZSI:function(h,x){return h!==x}};if(!(t instanceof IDBDatabase&&!i[n(252)](e,t)&&i[n(213)](typeof e,i[n(439)])))return;if(ia[n(274)](e))return ia.get(e);let o=e.replace(/FromIndex$/,""),c=i[n(720)](e,o),l=rp[n(1128)](o);if(!i[n(252)](o,(c?IDBIndex:IDBObjectStore)[n(650)+"e"])||!(l||np[n(1128)](o)))return;let u=async function(h,...x){let m=n,w=this[m(442)+m(1499)](h,l?"readwrite":i[m(1643)]),v=w.store;return c&&(v=v[m(1526)](x[m(1105)]())),(await Promise[m(1585)]([v[o](...x),l&&w.done]))[0]};return ia[n(1706)](e,u),u}var np,rp,ia,US=Qx({"node_modules/idb/build/index.js"(){let t=F,e={NYfCc:t(858)+t(1449),RneyO:function(o,c){return o(c)},beQLK:function(o){return o()},FzRiO:t(503),UCHlz:t(1177),paFQM:t(1040)},n=e[t(1110)][t(813)]("|"),i=0;for(;;){switch(n[i++]){case"0":e.RneyO(NS,o=>({...o,get:(c,l,u)=>Yx(c,l)||o.get(c,l,u),has:(c,l)=>!!Yx(c,l)||o.has(c,l)}));continue;case"1":Zx();continue;case"2":ia=new Map;continue;case"3":e[t(1727)](Zx);continue;case"4":rp=[e[t(1598)],t(225),t(464),e.UCHlz];continue;case"5":np=[t(274),"getKey",t(1127),t(430)+"ys",e[t(539)]];continue}break}}}),GS={idb:function(t){let e=F;t[e(837)]=Promise[e(1613)]().then(()=>(US(),tp)).then(function(n){return n})}},Xx={};function Ut(t){let e=F,n={LxEwH:function(u,h){return u!==h}},i=(e(208)+"1").split("|"),o=0;for(;;){switch(i[o++]){case"0":if(n[e(1174)](void 0,c))return c[e(837)];continue;case"1":return l[e(837)];case"2":var c=Xx[t];continue;case"3":GS[t](l,l[e(837)],Ut);continue;case"4":var l=Xx[t]={exports:{}};continue}break}}Ut.d=(t,e)=>{let n=z;for(var i in e)Ut.o(e,i)&&!Ut.o(t,i)&&Object[n(1137)+n(790)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=F;Ut.o=(e,n)=>Object[t(650)+"e"][t(1571)+"operty"][t(976)](e,n)})(),(()=>{let t=F,e={qtJiE:t(498)+"d",Jklli:t(639),lgMBG:t(855)+"le"};Ut.r=n=>{let i=t;e[i(903)]!=typeof Symbol&&Symbol["toString"+i(706)]&&Object[i(1137)+i(790)](n,Symbol[i(1726)+i(706)],{value:e[i(1615)]}),Object["definePr"+i(790)](n,e[i(1153)],{value:!0})}})();var De={};(()=>{let t=F,e={NYLkE:function(a,r){return a===r},XHaZl:"OfGFK",sgIKS:function(a,r){return a(r)},vanrV:function(a,r){return a+r},DxLBW:function(a,r){return a+r},kvriZ:function(a,r){return a*r},EXYJw:function(a,r){return a(r)},OaXkd:function(a,r,s){return a(r,s)},yarhX:function(a,r){return a+r},aPkAs:function(a,r,s){return a(r,s)},mMQtw:function(a,r){return a(r)},uUrME:function(a,r){return a+r},gzkbc:function(a,r){return a(r)},Ekmic:t(1020),UkWnf:"ffff",UfMgk:function(a,r){return a<r},bzxDd:function(a,r){return a<<r},qoKTu:function(a,r){return a===r},hvYnq:t(434),JeBCR:function(a,r){return a(r)},BDxls:"00000000"+t(305)+t(305)+t(305),wKWdJ:function(a,r){return a&r},OweVT:function(a,r){return a>>>r},DIPdl:function(a,r){return a&r},NeNUR:function(a,r){return a>>>r},waNDr:function(a,r){return a>>>r},rzYlu:function(a,r){return a===r},OYoJa:function(a,r){return a<r},wyYvG:function(a,r,s){return a(r,s)},GAKcX:function(a,r){return a<<r},FBANc:function(a,r){return a>r},yMfzK:function(a,r){return a<r},oSgPH:function(a,r){return a===r},lRAAc:t(1644),ivops:function(a,r){return a!==r},VYeGS:function(a,r){return a-r},Namgt:function(a,r){return a-r},ssPNP:function(a,r){return a<r},ZTkTR:function(a,r){return a<r},fAETC:function(a,r){return a<r},WDnVE:function(a,r){return a!==r},iqUqX:t(631),ZRcTT:t(1130),BvIRQ:t(1497),WrNnN:function(a,r,s){return a(r,s)},BGquI:function(a,r){return a!==r},iPlyi:function(a,r,s){return a(r,s)},DSNwi:function(a,r){return a(r)},aOXqA:function(a,r){return a>>>r},jAAMq:function(a,r){return a&r},XTCYP:"Missing "+t(1394)+" field: "+t(273),fkhSN:function(a){return a()},HPpGs:function(a,r,s){return a(r,s)},SavKq:t(403),RlWbp:function(a,r,s){return a(r,s)},FeOYr:function(a,r,s){return a(r,s)},lFniU:function(a,r){return a!==r},BswPn:function(a,r){return a(r)},FdaFb:t(1022),rdDXa:t(1466),BcQjf:function(a,r,s){return a(r,s)},nWvfI:function(a,r,s){return a(r,s)},EUJJT:function(a,r){return a!==r},TeqEf:"Ebikw",uOCbR:function(a,r,s){return a(r,s)},jhspX:function(a,r){return a!==r},IZPbM:function(a,r,s){return a(r,s)},aEYUs:function(a,r,s){return a(r,s)},AIjbi:function(a,r){return a!==r},TPgak:function(a,r,s){return a(r,s)},ZPBId:function(a,r,s){return a(r,s)},hkmLi:function(a,r,s){return a(r,s)},mZpCO:function(a,r,s){return a(r,s)},iSwJg:function(a,r){return a(r)},GiRjQ:function(a,r){return a(r)},lqcfo:function(a,r){return a>>>r},ATmwY:function(a,r,s){return a(r,s)},GuOnC:function(a,r,s){return a(r,s)},SVEtl:function(a,r){return a(r)},OwfNi:function(a,r,s){return a(r,s)},zUKZf:function(a,r){return a(r)},IyCua:function(a,r){return a(r)},wntBa:function(a,r,s){return a(r,s)},gOsyX:function(a,r){return a(r)},iCiyj:function(a,r){return a(r)},yxHpr:function(a,r){return a&r},kHmdz:t(1406)+"required"+t(1062)+t(1146),uBAlb:t(1406)+t(1394)+t(1062)+t(1545),Drcoa:function(a,r){return a===r},CzmAB:t(1406)+t(1394)+" field: "+t(574),gKuLk:t(1406)+t(1394)+t(1062)+t(278),xeRJW:function(a,r){return a(r)},FDmiO:function(a,r,s){return a(r,s)},geZSP:function(a,r){return a>=r},QhOrQ:function(a,r){return a!==r},hSZUL:t(543),Gdkkn:"zCNix",pFgSa:t(1692),yEVVJ:function(a,r){return a+r},SJNve:t(1337)+t(1640),vFSKq:function(a,r){return a===r},hMQRu:t(1002),PpzrL:function(a,r){return a*r},LkhVe:function(a,r){return a>r},IOmSs:t(1379)+"t limit",Gddtm:function(a,r,s){return a(r,s)},ODmLl:function(a,r,s){return a(r,s)},jmJNL:function(a,r){return a instanceof r},Hsxle:function(a,r){return a|r},yYLFm:function(a,r){return a<r},vGrqN:function(a,r){return a+r},pLsfz:function(a,r){return a&r},eluXD:function(a,r){return a&r},frOVR:function(a,r){return a>=r},BMcZD:function(a,r){return a+r},xvFyJ:function(a,r){return a+r},bFesJ:t(628),OSiuU:t(674),ZtyuD:function(a,r){return a|r},lbkqT:function(a,r){return a<<r},rsdkV:function(a,r){return a==r},cyZAf:function(a,r){return a+r},KTfXX:function(a,r){return a!==r},yxiim:t(487),JegpG:function(a,r){return a+r},ViQov:function(a,r){return a+r},tiFiA:function(a,r){return a|r},FOSVr:function(a,r){return a|r},RgwFv:function(a,r){return a<<r},atCWg:function(a,r){return a<=r},HxGtE:t(838),PvrXW:t(262),afhkO:function(a,r){return a+r},Lasgd:function(a,r){return a+r},Yuzni:function(a,r){return a+r},CpISS:function(a,r){return a+r},hDvYB:function(a,r){return a|r},aAoZt:function(a,r){return a<<r},SJwXn:function(a,r){return a|r},LitPw:function(a,r){return a<<r},ERuvg:function(a,r){return a<r},eEcwP:function(a,r){return a>r},iIUIQ:function(a,r){return a+r},SaoUZ:t(1404)+t(1348)+t(242),yABab:t(1018),OIaMG:function(a,r,s,d){return a(r,s,d)},elsjM:t(851)+t(216),VjSof:t(574),XAvMT:"curvalue",yOwYS:t(216),RvUtK:function(a,r){return a(r)},aWVtr:function(a,r){return a|r},jhRpv:function(a,r){return a<<r},hNfFL:function(a,r){return a<r},MnLzj:t(1192),YUKcQ:function(a,r){return a-r},bAdln:function(a,r){return a<r},CWaiK:function(a,r){return a<r},rhjJJ:function(a,r,s){return a(r,s)},vfaOQ:function(a,r){return a+r},ZyeiJ:function(a,r){return a<r},wVetG:function(a,r){return a!==r},kAWfF:t(454),PWCIN:function(a,r){return a<r},oIJIO:function(a,r){return a&r},ELmqY:function(a,r){return a===r},qWTlV:t(860),adSSX:function(a,r){return a>>r},pxFtg:function(a,r){return a|r},tqMVP:function(a,r){return a&r},LesKr:t(206),TIXCr:function(a,r,s){return a(r,s)},yPcuf:function(a,r){return a<r},RlZXg:function(a,r){return a&r},tEBDl:function(a,r){return a>=r},UQgWx:function(a,r,s){return a(r,s)},tfkcB:function(a,r){return a(r)},GQyFq:function(a,r){return a!==r},zRymW:t(1388),EiTJe:t(290),cKlQv:function(a,r){return a(r)},NMHbs:function(a,r){return a(r)},gLDCi:function(a,r){return a&r},xwigL:function(a,r){return a(r)},RkDRo:function(a,r){return a<<r},zALgm:function(a,r){return a&r},CAsYo:function(a,r){return a&r},UiXiz:function(a,r){return a<<r},bTVER:function(a,r){return a|r},ntJTX:function(a,r){return a>>>r},xLkST:function(a,r){return a<<r},JyLFF:function(a,r){return a>>>r},oUdRX:function(a,r){return a<r},nMuna:function(a,r){return a+r},yUHYP:function(a,r){return a&r},iPmkj:function(a,r){return a>>>r},VjSln:function(a,r){return a+r},fNqwi:function(a,r){return a!==r},SDRYg:function(a,r){return a&r},PtJjM:function(a,r){return a+r},FFEwK:function(a,r){return a|r},zidPx:function(a,r){return a+r},jCJTJ:function(a,r){return a!==r},xmAZx:function(a,r){return a|r},OYNGU:function(a,r){return a&r},OawTE:function(a,r){return a>>>r},GRBWw:function(a,r){return a+r},OVrBo:function(a,r){return a|r},NfehF:function(a,r){return a&r},EhKVu:function(a,r){return a!==r},QrqrO:function(a,r){return a&r},iKTnK:function(a,r){return a|r},bKLVC:function(a,r){return a+r},EYpXx:function(a,r){return a>>>r},CCxQW:function(a,r){return a|r},sIaPM:function(a,r){return a&r},zjzfg:t(886)+t(815),cXVgv:t(1631),gJsGS:function(a,r){return a|r},gEVgq:function(a,r){return a|r},Mujgi:"3|2|1|4|0",bPYbn:function(a,r){return a<r},rdxlG:function(a,r){return a+r},bwyLv:function(a,r,s,d){return a(r,s,d)},oUtHM:function(a,r){return a===r},NHoxc:t(376),CsEnx:function(a,r){return a===r},BUJDe:t(603),jQJqf:t(415),fEYUR:function(a,r){return a|r},RZiyc:function(a,r){return a<<r},lRjJa:function(a,r){return a<<r},cvGwe:function(a,r){return a|r},oWAXz:function(a,r){return a<<r},aHbUz:function(a,r){return a<<r},DuCXY:function(a,r){return a|r},wTLmu:function(a,r){return a|r},ogIyh:function(a,r){return a<<r},PWGTK:function(a,r){return a>>>r},Orivc:function(a,r){return a|r},Fzlgu:function(a,r){return a<<r},AJqjZ:function(a,r){return a<<r},VPIzT:function(a,r){return a!==r},nCCch:"nkJyp",SoZAf:function(a,r){return a&r},sofaC:function(a,r){return a&r},HMwhD:function(a,r){return a>=r},UTkdl:function(a,r){return a+r},gtiUJ:function(a,r){return a%r},RKTWr:function(a,r){return a/r},PSHnH:t(1317)+"t",KovLe:t(1101)+t(804)+t(817)+"ct",gaVbd:function(a,r){return a!==r},vdWbc:t(1760),vFQCh:"eoFIb",qnzEp:function(a,r){return a>>>r},tUjkC:function(a,r){return a+r},SgYeM:function(a,r){return a*r},OJFXf:function(a,r){return a>>>r},RaTMa:function(a,r){return a>>>r},sKQKn:function(a,r){return a>>>r},LyJqk:function(a,r){return a&r},RqGQh:function(a,r){return a>>>r},oNRvC:function(a,r){return a&r},IVhDe:"KXloI",LvLVr:function(a,r){return a&r},bKRkk:function(a,r){return a&r},PLQoT:function(a,r){return a>>>r},wmkPL:function(a,r){return a<<r},BwBIi:function(a,r){return a|r},RQpRN:"zfdWc",ljxer:function(a,r){return a!==r},ydoIG:function(a,r){return a>>>r},sDYVl:function(a,r){return a===r},ncOYY:function(a,r){return a===r},knsCc:function(a,r){return a+r},Zcuhq:function(a,r){return a===r},TxZoh:t(652),kSsXJ:t(1604),wyVMC:function(a,r){return a>>>r},wpIWg:function(a,r){return a&r},HMIFh:function(a,r){return a&r},apUNm:function(a,r){return a&r},DpEkl:function(a,r){return a>>>r},zVvEm:function(a,r){return a>>>r},Exegz:function(a,r){return a>>>r},ndvQg:function(a,r){return a&r},WDWxT:function(a,r){return a&r},mfgcR:t(1533)+t(1284),NBwDw:t(1030)+"OR",KDudE:t(895)+t(1561),PUGQY:t(1671)+t(1606),rkakc:t(1120)+t(400),fCyzm:t(1352)+t(800)+"R",pTgDl:function(a,r,s){return a(r,s)},SLttv:function(a,r){return a!==r},fwWGv:function(a,r){return a(r)},liEQF:"QgLpw",QuRmj:"Module",xRkcU:t(855)+"le",CNnBR:t(192),UZuho:"LdKdC",EGRUi:t(630),vIaZN:t(731),joNlz:function(a,r){return a===r},tDKjh:function(a,r){return a>r},cFeZH:function(a,r){return a+r},bJMoC:function(a,r){return a===r},WWYEH:function(a,r){return a===r},IgtKL:t(1543),WdXcZ:function(a,r){return a===r},uPsXR:t(1443),nkCDQ:t(752),UHtUD:function(a,r,s){return a(r,s)},ukrUw:function(a,r,s){return a(r,s)},JqjoE:t(1601),VLTom:function(a,r){return a+r},nnhCR:function(a,r){return a-r},VWDmx:function(a,r){return a+r},cXTOq:t(925),SxocV:"Urcew",zGXrH:function(a,r,s){return a(r,s)},OfrYM:function(a,r){return a&r},ZRZnm:function(a,r){return a>>r},IFoNu:function(a,r){return a&r},ZjXWH:t(1716),PBjzF:t(897),SvIiX:t(555),rowLw:function(a,r){return a instanceof r},DecYj:t(676),JbEap:t(1454),jydBd:function(a,r){return a+r},LOjmi:"pISiF",CnMIa:t(901),KJAXt:function(a,r){return a===r},BeRdM:t(958),JLvNi:t(1704),MbMzT:t(471),MkFWL:function(a,r,s){return a(r,s)},rwXWM:"vpQxZ",BwNji:function(a,r){return a||r},ZjXnW:function(a,r){return a!=r},UehPf:t(498)+"d",Xwtmw:function(a,r){return a||r},FGHVa:t(613)+"3",uViTA:"aLTbC",HCfQf:t(975),joBZO:t(1747)+"alled mu"+t(1679)+t(1619)+t(1605),YuRMg:function(a,r){return a(r)},UmNzX:function(a,r){return a<r},mvSgI:function(a,r){return a-r},ggycz:function(a,r){return a<r},nnajj:function(a,r){return a&r},UCGfn:function(a,r){return a|r},AVwAt:function(a,r){return a<<r},weWGa:function(a,r){return a&r},eyawl:function(a,r){return a<<r},DwaAL:function(a,r){return a&r},sRmIJ:function(a,r){return a|r},MjqBB:function(a,r){return a<<r},NMfgU:function(a,r){return a&r},twiaP:function(a,r){return a&r},ZrbGo:function(a,r){return a+r},CrMZr:function(a,r){return a&r},VWizm:function(a,r){return a<r},HnpYw:function(a,r){return a!==r},XMrhC:"PIUuQ",MchJz:function(a,r){return a|r},aLoia:function(a,r){return a>>r},IuZPu:function(a,r){return a===r},XRCnK:function(a,r){return a&r},bSZBV:function(a,r){return a===r},AKRgO:function(a,r){return a&r},idUDv:"5|4|3|2|"+t(938),lozhZ:function(a,r){return a|r},IRBpO:function(a,r){return a&r},UfGIT:function(a,r){return a&r},FIJke:function(a,r){return a|r},WMKlI:function(a,r){return a>>r},naKbw:function(a,r){return a+r},GoDXN:function(a,r){return a&r},zXSvX:function(a,r){return a&r},gnvAh:function(a,r){return a>>r},BFVPG:function(a,r){return a>>r},TmqAA:"string",rKPKI:function(a,r){return a<<r},JpaXW:function(a,r){return a(r)},WPVXR:function(a,r){return a&r},KTKta:function(a,r){return a!==r},FCnHB:t(1027),gElqh:t(906)+"ion/json",NGoUL:t(519)+t(581)+t(1286),bPDAQ:"boe",KhyYZ:t(968),EfiXo:function(a,r){return a!==r},AndVZ:t(1411),uwoqZ:t(1071),mcJpt:function(a,r){return a>=r},vpblW:"unknown "+t(1313),ttCgw:t(1194),kKAZT:"text/jav"+t(598),DaOOp:t(1354),pOuxl:function(a,r,s,d){return a(r,s,d)},xdRTo:function(a,r){return a+r},mtiJS:function(a,r){return a+r},yiAEm:function(a,r){return a<<r},EWjbd:function(a,r){return a&r},UfLhC:function(a,r){return a&r},FZkEv:function(a,r){return a===r},OXnSO:t(1701),bvjBS:t(436),RUmtD:function(a,r){return a!==r},VaGGf:"maOWv",uqpxu:t(672),kwuqn:t(756),dGiEM:t(953),xBztZ:t(327),XEaAc:t(1133),YuGPy:"FeoXV",taBgY:t(387),Ckben:function(a,r){return a||r},geesd:function(a,r){return a||r},Izege:function(a,r){return a||r},OdkIF:function(a,r){return a||r},mlOpx:function(a,r){return a||r},SJbLM:function(a,r){return a!=r},EKDwV:function(a,r,s){return a(r,s)},cMEaf:"qos",ZjGdR:t(1104)+"id",DmkFI:function(a,r,s){return a(r,s)},XLxUm:"Sayvp",MdbAE:function(a,r){return a>>r},psevs:function(a,r){return a===r},yhSei:t(241),sskRX:function(a,r){return a!==r},nTdmN:t(1739),uDUuT:function(a,r,s){return a(r,s)},kvbos:t(943),XltRa:t(1462),uUSSr:function(a,r){return a(r)},JHABu:function(a,r,s,d){return a(r,s,d)},EJNzk:t(244)+t(449)+"ck",bqEvp:"x_fronti"+t(1072)+"k",UzHAS:function(a,r,s){return a(r,s)},vIhCq:t(244)+"er_ack_m"+t(309),tsOpy:"need_ack",Ojyix:function(a,r,s,d){return a(r,s,d)},FthZe:t(658),WZBtR:function(a,r){return a&&r},Pugao:function(a,r){return a||r},HEHQS:t(1148),VfPLD:function(a){return a()},MatCV:function(a,r){return a(r)},bzPuV:function(a,r){return a instanceof r},PDcNN:"applicat"+t(1412)+t(1270)+t(766),kIzoP:t(1542)+"e",UaozM:t(1245),iJjhY:function(a,r,s,d){return a(r,s,d)},PRIxI:function(a){return a()},RzANn:function(a,r){return a>r},JCQOF:function(a,r){return a+r},UiQLv:function(a,r){return a(r)},ZiWGg:function(a,r){return a&r},wKhAz:function(a,r){return a+r},ANcWi:function(a,r){return a(r)},UYbSE:function(a,r){return a+r},zfgBn:t(933),tHWTw:t(694),PGoqB:function(a,r,s,d){return a(r,s,d)},azaiO:t(549),PfzYM:"integer too large",KrFfD:function(a,r){return a+r},vkLhR:function(a,r){return a>>>r},WKWJE:function(a,r){return a<<r},jHSfF:t(1621)+"3",wPFPR:function(a,r){return a<r},sJaJh:function(a,r){return a+r},vbWxT:function(a,r){return a+r},faNlR:function(a,r){return a+r},ODHlH:function(a,r){return a<<r},bDHNs:function(a,r){return a+r},rcreJ:function(a,r){return a<<r},OplzG:function(a,r){return a&r},tBDlS:function(a,r){return a>>>r},cphKf:function(a,r){return a+r},vlboa:function(a,r){return a>>>r},Bdymv:function(a,r){return a>>>r},lvQVT:function(a,r){return a&r},HLzlz:function(a,r){return a+r},NkILO:function(a,r){return a>>>r},rBVBS:function(a,r){return a<r},AnxKp:function(a,r){return a&r},dQukx:function(a,r){return a===r},tJidA:t(1532),GRZjU:function(a,r){return a(r)},kIHWG:function(a,r){return a||r},FRjsC:t(1366),DTEZK:t(1250)+t(571),ZoajG:function(a,r,s){return a(r,s)},qdMhZ:function(a,r){return a===r},WLRkS:t(604),aeleC:t(267)+"_EXIST",hsPjc:t(379)+t(391),RnvHH:t(1735)+t(1312),JgimF:function(a,r,s,d){return a(r,s,d)},oDDds:"CONTINUE",qvQoo:function(a){return a()},NCFtv:"setdb",MqUfn:function(a,r){return a===r},Zdyhj:t(1208),ZgaPP:t(1350)+"r",jKPre:t(1423),ubJay:function(a,r){return a>>>r},shoGQ:function(a,r){return a+r},hiqRD:function(a,r){return a&r},EPupF:function(a,r){return a+r},TQvnf:function(a,r){return a&r},JXowp:function(a,r){return a+r},bfjEU:function(a,r){return a>>>r},KCplI:function(a,r,s,d){return a(r,s,d)},XYzpz:t(580),jUwpC:function(a,r,s,d){return a(r,s,d)},kLChY:t(244)+t(1233),Omlwc:function(a,r,s){return a(r,s)},SRVKM:t(244)+t(795),badqC:"x-msg-qos",gYALD:t(1053)+t(1471)+"e",inOWu:function(a,r){return a(r)},zfudB:"x-msg-cu"+t(1068)+"ue",qtnLR:function(a){return a()},tyuOi:function(a,r){return a!==r},Gvmvg:t(576),IGwdZ:function(a,r){return a+r},PAkrd:function(a){return a()},NbTKE:t(910),yfYca:function(a){return a()},NQClG:function(a){return a()},zmArg:"wTpHI",NtvHH:function(a,r,s){return a(r,s)},fnRkZ:function(a){return a()},jXRPH:function(a,r){return a(r)},QnnRr:"XQFWY",QxrCg:t(1698),pRVep:function(a,r){return a<r},GohvH:function(a,r){return a===r},YsQTD:"WXYvA",jdJqF:function(a,r){return a===r},OdUhZ:function(a,r){return a===r},JSzgL:"ping_once_success",mQrUY:function(a,r){return a===r},HbaAr:function(a,r){return a!==r},CEeHW:t(1507),ZgyCS:t(214),whrRW:function(a,r,s){return a(r,s)},AavHQ:function(a,r,s){return a(r,s)},AVDro:"hMFkI",uqToV:function(a,r){return a!==r},TmWoM:t(478),wEroU:function(a,r,s){return a(r,s)},XYzel:function(a,r){return a(r)},oyblV:function(a,r){return a===r},YGoND:t(1382),Kfnyq:t(1737)+t(727),AnDje:t(678),fDAlL:function(a,r){return a/r},viIGo:t(1681),ORLFq:function(a,r){return a==r},TddeF:t(1761)+"rovide v"+t(993),olGRc:function(a,r){return a!==r},rwuue:t(255),GXTIb:t(280),HsIJf:function(a,r,s){return a(r,s)},QJjFK:function(a,r){return a||r},hKnFu:t(1190),VlyDS:t(1180),XpCQx:t(705),rUMzz:function(a,r){return a===r},ffzNO:"function",EdWky:function(a,r){return a(r)},ydLhM:t(770),FBewE:function(a,r){return a!==r},Twour:t(1725),UjbIy:"nlPBK",TePvb:function(a,r){return a!==r},LKxHO:t(1616),qHszA:t(1121),JCsdp:"bd_did",PlNep:"device_id",PVkcZ:function(a,r){return a||r},yebAc:function(a,r,s){return a(r,s)},wejMG:"fws_1.0.0",MewQG:function(a,r){return a>=r},TWfyM:function(a,r,s){return a(r,s)},pBghj:function(a,r){return a&r},vxMKj:function(a,r,s){return a(r,s)},rFRmR:t(1164),MOsmX:t(1661),ioMjZ:function(a,r,s){return a(r,s)},UnhvU:t(983),TRSVo:t(945)+"eeded",qzGyT:function(a,r){return a===r},dyhhe:t(372),hYTNb:function(a,r){return a(r)},XmINi:t(1440)+">",tcSpi:t(1154)+t(1538)+"t",VqMEW:t(248),rHulp:function(a,r){return a-r},USOjp:function(a,r){return a===r},fvBuX:function(a,r){return a!==r},mnXmm:t(501),cAEon:"LeHsM",mxTch:function(a,r,s){return a(r,s)},KFcYS:t(1242)+t(1456)+t(1317)+t(456)+"ver",tjRvT:function(a,r,s){return a(r,s)},qiaoO:t(1038),MAHEV:t(380)+"3",QJsvI:t(1617)+"2",ChZgf:function(a,r){return a!==r},dgdCu:t(616),uczPy:t(1516),bfUzw:t(1242)+"ay, netw"+t(410)+t(508),MhnCP:function(a,r){return a!==r},EGQCP:"XzbDr",oiOkx:t(203),IbikR:"EVNmR",JYkeg:function(a,r){return a===r},dptly:"close, w"+t(534)+t(1683),khtRX:function(a){return a()},uzoWz:function(a,r){return a==r},ykegs:t(1761)+"rovide a"+t(1086)+t(1397)+t(202)+"e a stri"+t(579)+" arraybuffer",IULUG:function(a,r){return a==r},ChufP:t(1259),eIZwm:function(a,r){return a!=r},rUKii:function(a,r){return a(r)},UCNGG:function(a,r){return a(r)},SGyjj:t(1761)+t(1282)+t(1047)+"ervice",bBmIk:function(a,r){return a instanceof r},UVZuq:function(a,r){return a===r},rQOtX:"sent",cmSpT:t(1664),QmgmE:function(a,r){return a||r},zsXjc:t(194)+t(1218)+t(1274),oBvqf:t(215),sejem:t(1502),hwOgx:function(a,r){return a(r)},KIrxW:function(a,r){return a&r},GUsms:function(a,r){return a&r},VJVhm:"jffcz",QKbWb:t(1199),EAJHf:t(506),QSBcR:t(502),QapKR:t(723),LPxRt:function(a,r){return a(r)},YJDEZ:"success",CrKmk:function(a,r,s){return a(r,s)},oQqhg:t(412),FFAiY:t(1407),cBEXR:"Window",aJBLn:function(a,r){return a!=r},ZoFyo:function(a,r){return a===r},LyvJu:function(a,r){return a!=r},rkMrD:function(a,r){return a!=r},KBsUk:t(1711),iaLzY:function(a,r){return a!=r},ukdGS:function(a,r){return a!=r},DrMcU:function(a,r){return a===r},dkfzM:t(907)+"dWorkerG"+t(660)+"pe",qbPkc:"SharedWo"+t(426)+"alScope",NWowZ:t(1489)+t(797)+"balScope",Teqji:function(a,r){return a!=r},ksdoV:function(a,r){return a===r},MBEMG:function(a,r){return a!=r},BwJdU:function(a,r,s){return a(r,s)},NdZzL:"__x_msg_"+t(251)};Ut.r(De),Ut.d(De,{FWS:()=>qm,CustomErrorEvent:()=>pl,createCloseEvent:()=>bt,ReconnectEvent:()=>xl,createErrorEvent:()=>ft,decodedFrame:()=>on,createOpenEvent:()=>bl,CustomCloseEvent:()=>ml,createReconnectEvent:()=>Ia,FrontierMessageEvent:()=>wl,encodeFrame:()=>Ht,createMessageEvent:()=>yl,OpenEvent:()=>_l,ErrorCode:()=>cn,Event:()=>ir,MessageEvent:()=>gl});let n="";function i(a=""){let r=t;if(e[r(369)](e[r(1672)],e[r(1672)])){let d=""+Date[r(786)](),f=n||(n=e.sgIKS(h,a)),p=Math.random()[r(1726)](16)[r(358)](-6);return e[r(450)](e.DxLBW("02"+d,f),p)}else return new _0x1d68b2(_0x122d56)}function o(){let a=t;return e[a(1359)](e[a(1262)](1e4,Date.now()),Math[a(516)](1e4*Math[a(893)]()))}function c(a){let r=t;return(e[r(1295)](Array,8)[r(1642)]("0")+e[r(867)](parseInt,a,10)[r(1726)](2)).slice(-8)}function l(a){let r=t;return e[r(1142)](e.EXYJw(Array,4).join("0"),e[r(946)](parseInt,a,2)[r(1726)](16))[r(358)](-4)}function u(a){let r=t,s=a.split(/\./)[r(472)](p=>c(p)),d=[];return d[0]=e.mMQtw(l,e[r(1355)](s[0],s[1])),d[1]=e.gzkbc(l,s[2]+s[3]),[e.Ekmic,r(1020),e[r(1272)],e.Ekmic,r(1020),e[r(1531)],d[0],d[1]][r(1642)]("")}function h(a){let r=t;if(e[r(1125)](e[r(1090)],r(434))){let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(1149)](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 s?e.JeBCR(u,a):d?e.EXYJw(x,a):e[r(1141)]}else _0x2beda8=_0x2c88ea(_0x30ecb5),e[r(1472)](_0x33b32f,32)&&(_0x5e0ca7|=e[r(1069)](127&_0x23ec5c,_0xf598b)),_0x24da06+=7}function x(a){let r=t,s={EwhXc:function(R,C){return e[z(422)](R,C)},BWogR:function(R,C){return e.DxLBW(R,C)},jpySy:function(R,C){return e[z(458)](R,C)},cJQZM:function(R,C,N){return e.wyYvG(R,C,N)},WIZuO:function(R,C){return e[z(1686)](R,C)}},d="",f=[],p=0,y=0,S=!0,g=e[r(1272)];if(e[r(1173)](a[r(1622)]("::"),-1)){let R=a.split("::");for(let N=0;e[r(1019)](N,R[r(279)]);N++)if(r(1271)==="dArfR")this["_cursorF"+r(617)]=_0x5394db;else{let q=R[N];if(e.FBANc(q[r(1622)](":"),0))if(e[r(1418)]("dlDLl",e[r(212)])){let B=_0x36f4ca(_0x4e7a77);this[r(1247)]&&s[r(740)](this[r(1247)][r(493)+"te"],this[r(1528)])&&(this[r(1247)]&&this[r(1247)][r(401)](B),this[r(1658)](r(1570),_0x452dc9))}else{let B=q.split(":");S&&(p=B[r(279)]),y+=B.length;for(let M=0;M<B[r(279)];M++)if(e[r(1675)](4,B[M][r(279)])){let oe=g.substring(0,e[r(1124)](4,B[M][r(279)])),ze=oe.concat(B[M]);f.push(ze)}else f[r(1730)](B[M]);S=!1}else{if(q[r(279)]!==4){let B=g[r(1733)+"g"](0,e[r(1446)](4,q[r(279)])),M=B[r(359)](q);f.push(M)}else f[r(1730)](q);S&&(p+=1),y+=1,S=!1}}let C="";for(let N=0;e.ssPNP(N,e[r(1446)](8,y));N++)C=C[r(359)](g);for(let N=0;e[r(1025)](N,f[r(279)]);N++)e[r(1418)](N,p)&&(d=d.concat(C)),d=d[r(359)](f[N]);return d}{let R=a[r(813)](":");for(let C=0;e[r(1387)](C,R[r(279)]);C++)if(e.WDnVE(e[r(1738)],e[r(1634)])){let N=R[C];if(e.WDnVE(4,R[C].length))if(e[r(1409)]===r(428)){let q=0,B=_0x3c1f0a,M=s[r(1588)](_0x2bc102,4);for(;s[r(447)](B,M);){let{value:oe,offset:ze}=s[r(541)](_0x553203,_0x435240,B);B=ze,q=s[r(455)](q,8)>>>0,q+=oe}return{value:q,offset:M}}else{let q=g[r(1733)+"g"](0,4-R[C][r(279)]),B=q.concat(N);d=d[r(359)](B)}else d=d[r(359)](N)}else return _0x2bcda9[r(1183)+"Code"](e[r(568)](255,this[r(569)]),e.OweVT(this[r(569)],8)&255,e[r(568)](e[r(1293)](this[r(569)],16),255),this.low>>>24,255&this[r(707)],e[r(747)](this[r(707)]>>>8,255),e[r(747)](e.NeNUR(this.high,16),255),e.waNDr(this.high,24));return d}}function m(a,r){let s=t,d=a[s(1441)];e.WDnVE(void 0,d)&&(ge(r,10),e.WrNnN(H,r,d));let f=a[s(273)];e[s(1755)](void 0,f)&&(e[s(560)](ge,r,18),e[s(867)](H,r,f))}function w(a){let r=t,s={};e:for(;!e[r(1432)](J,a);){let d=e[r(573)](me,a);switch(e[r(1563)](d,3)){case 0:break e;case 1:s.key=P(a,e[r(1530)](me,a));break;case 2:s.value=e[r(867)](P,a,e[r(1200)](me,a));break;default:e[r(867)](T,a,e[r(394)](7,d))}}if(e[r(369)](void 0,s.key))throw new Error(r(1406)+r(1394)+" field: "+r(1441));if(e.oSgPH(void 0,s[r(273)]))throw new Error(e.XTCYP);return s}function v(a){let r=t,s=e[r(1185)](D);return e[r(1607)](_,a,s),e[r(1200)](U,s)}function _(a,r){let s=t,d={RcBrt:e[s(1550)]},f=a[s(1146)];e[s(1675)](void 0,f)&&(e[s(1610)](ge,r,8),e.FeOYr(yt,r,f));let p=a.LogID;e.BGquI(void 0,p)&&(e[s(946)](ge,r,16),yt(r,p));let y=a[s(574)];e[s(548)](void 0,y)&&(e[s(946)](ge,r,24),e[s(867)](yt,r,e.BswPn(O,y)));let S=a[s(278)];S!==void 0&&(ge(r,32),e[s(320)](yt,r,e.EXYJw(O,S)));let g=a[s(1425)];if(e[s(200)](void 0,g))for(let ze of g)if(e.FdaFb!==e[s(411)]){e[s(1607)](ge,r,42);let Ye=e[s(1185)](D);e[s(867)](m,ze,Ye),ge(r,Ye[s(859)]),e[s(470)](W,r,Ye),L(Ye)}else{let Ye=_0x5d1e4a(d[s(971)],{message:_0x2e4c77[s(555)],code:_0x295402[s(1120)+s(400)],error:_0x464f5d});this[s(919)+s(563)+s(210)](Ye)}let R=a[s(1172)+s(1088)];R!==void 0&&(e[s(1335)](ge,r,50),e[s(560)](H,r,R));let C=a[s(745)+s(986)];e[s(1187)](void 0,C)&&(e[s(369)](e[s(670)],e[s(670)])?(e.FeOYr(ge,r,58),e[s(1607)](H,r,C)):(_0x48ea9c[s(474)+s(682)]="",_0x191d46[s(759)](_0x324b84)));let N=a[s(1213)];e[s(1187)](void 0,N)&&(e[s(224)](ge,r,66),ge(r,N[s(279)]),e[s(470)](de,r,N));let q=a[s(584)];e.jhspX(void 0,q)&&(e[s(896)](ge,r,74),e[s(1758)](H,r,q));let B=a[s(323)+s(286)];e[s(1467)](void 0,B)&&(e[s(1636)](ge,r,82),H(r,B));let M=a[s(1230)];e[s(934)](void 0,M)&&(e[s(1548)](ge,r,90),e[s(904)](H,r,M));let oe=a[s(536)+"e"];e.WDnVE(void 0,oe)&&(ge(r,96),e[s(348)](yt,r,e[s(1591)](O,oe)))}function E(a){let r=t;return e[r(755)](I,e[r(875)](G,a))}function I(a){let r=t,s={};e:for(;!e[r(1200)](J,a);){let d=me(a);switch(e[r(1690)](d,3)){case 0:break e;case 1:s.SeqID=e[r(492)](Rt,a,!0);break;case 2:s.LogID=e[r(1362)](Rt,a,!0);break;case 3:s.service=me(a);break;case 4:s.method=me(a);break;case 5:{let f=e[r(1742)](A,a);(s.headers||(s[r(1425)]=[]))[r(1730)](e.sgIKS(w,a)),a.limit=f;break}case 6:s[r(1172)+r(1088)]=P(a,e[r(1295)](me,a));break;case 7:s["payloadT"+r(986)]=e[r(360)](P,a,e[r(1211)](me,a));break;case 8:s[r(1213)]=e.OaXkd(ce,a,e[r(294)](me,a));break;case 9:s.LogIDNew=e[r(1288)](P,a,e[r(444)](me,a));break;case 10:s[r(323)+"ming"]=e[r(904)](P,a,e[r(1501)](me,a));break;case 11:s[r(1230)]=P(a,me(a));break;case 12:s[r(536)+"e"]=e.IyCua(me,a);break;default:e[r(1758)](T,a,e[r(1291)](7,d))}}if(e[r(422)](void 0,s[r(1146)]))throw new Error(e[r(1315)]);if(e[r(369)](void 0,s[r(1545)]))throw new Error(e[r(645)]);if(e[r(1635)](void 0,s[r(574)]))throw new Error(e[r(564)]);if(e[r(369)](void 0,s[r(278)]))throw new Error(e[r(1568)]);return s}function A(a){let r=t,s=e.BswPn(me,a),d=a.limit;return a[r(859)]=e[r(450)](a[r(662)],s),d}function T(a,r){let s=t;switch(r){case 0:for(;e[s(568)](128,e[s(353)](te,a)););break;case 2:e[s(824)](Z,a,e[s(353)](me,a));break;case 5:e[s(1636)](Z,a,4);break;case 1:e[s(360)](Z,a,8);break;default:throw new Error(s(732)+"ented ty"+s(1039)+r)}}function O(a){return a|=0,{low:a,high:a>>31,unsigned:e.geZSP(a,0)}}let b=[];function D(){let a=t;if(e[a(219)](a(659),e.hSZUL)){let r=b.pop();return r?(r.offset=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}else return!!this[a(1342)]}function L(a){let r=t;if(e.Gdkkn===e[r(432)])return null;b[r(1730)](a)}function G(a){return{bytes:a,offset:0,limit:a[t(279)]}}function U(a){let r=t,s=a[r(583)],d=a.limit;return e[r(369)](s[r(279)],d)?s:s[r(762)](0,d)}function Z(a,r){let s=t;if(e[s(1173)](e[s(828)](a.offset,r),a.limit))throw new Error(e[s(1377)]);a[s(662)]+=r}function J(a){let r=t;return e.geZSP(a[r(662)],a[r(859)])}function ie(a,r){let s=t;if(e[s(1187)](s(1445),"mlQlT"))return this[s(1247)]?this._ws[s(493)+"te"]:this._options["automati"+s(626)]?this.CONNECTING:this[s(435)];{let d=a[s(583)],f=a[s(662)],p=a[s(859)],y=f+r;if(e[s(1173)](y,d[s(279)]))if(e.vFSKq(e[s(1414)],e.hMQRu)){let S=new Uint8Array(e[s(1009)](2,y));S.set(d),a.bytes=S}else return s(222)+"_"+this[s(857)];return a[s(662)]=y,e[s(404)](y,p)&&(a[s(859)]=y),f}}function Q(a,r){let s=t,d=a[s(662)];if(e[s(404)](d+r,a[s(859)]))throw new Error(e[s(627)]);return a[s(662)]+=r,d}function ce(a,r){let s=t,d=e[s(869)](Q,a,r);return a[s(583)][s(762)](d,e[s(1359)](d,r))}function de(a,r){let s=t,d=e[s(1234)](ie,a,r[s(279)]);a[s(583)][s(1706)](r,d)}function P(a,r){let s=t,d=Q(a,r),f=String.fromCharCode,p=a[s(583)],y="\uFFFD",S="";for(let g=0;e[s(373)](g,r);g++){let R=p[e.vGrqN(g,d)],C,N,q,B;if(e[s(1515)](128,R)===0)S+=f(R);else if(e[s(301)](224,R)===192)e[s(1756)](e.BMcZD(g,1),r)?S+=y:(C=p[e[s(997)](g+d,1)],e[s(394)](192,C)!==128?S+=y:e[s(1125)](e[s(513)],e[s(833)])?mYkanF[s(1482)](_0x3f0ac9,_0x4a5f00)&&_0x485a45[s(1706)](_0x9666c6,_0x528c93):(B=e[s(318)](e[s(792)](e[s(747)](31,R),6),63&C),e[s(1019)](B,128)?S+=y:(S+=e[s(587)](f,B),g++)));else if(e[s(1089)](e[s(301)](240,R),224))if(e[s(529)](e[s(911)](g,2),r))S+=y;else if(e.KTfXX(e.yxiim,e[s(1567)]))try{return!!this[s(1342)]}catch(M){return _0x312192[s(759)](M),!1}else C=p[e[s(1355)](g+d,1)],N=p[e[s(1169)](e.ViQov(g,d),2)],e[s(394)](e[s(849)](C,N<<8),49344)!==32896?S+=y:(B=e.FOSVr(e.RgwFv(e[s(394)](15,R),12)|e[s(792)](63&C,6),63&N),B<2048||B>=55296&&e[s(326)](B,57343)?S+=y:(S+=f(B),g+=2));else e[s(1089)](248&R,240)?e.vGrqN(g,3)>=r?S+=y:e[s(200)](e.HxGtE,e[s(1049)])?(C=p[e[s(1355)](e[s(362)](g,d),1)],N=p[e[s(622)](e[s(1112)](g,d),2)],q=p[e[s(1112)](e.CpISS(g,d),3)],(e[s(338)](e[s(826)](C,e[s(1731)](N,8)),e[s(1069)](q,16))&12632256)!==8421504?S+=y:(B=e.SJwXn(e[s(1552)](e[s(601)](7&R,18),e[s(568)](63,C)<<12),e[s(1069)](e[s(301)](63,N),6))|63&q,e[s(1595)](B,65536)||e[s(416)](B,1114111)?S+=y:(B-=65536,S+=e.OaXkd(f,e[s(622)](B>>10,55296),e[s(936)](1023&B,56320)),g+=3))):(e[s(867)](_0x3c4dac,_0x259d4b,e[s(826)](e.jAAMq(127,_0x4b397a),128)),_0x2e96f9>>>=7):S+=y}return S}function H(a,r){let s=t,d={ygMcc:e[s(972)],AmxQT:s(1250)+"ervice",JWRve:e[s(1193)],GlrBI:function(g,R,C,N){return e[s(1365)](g,R,C,N)},CmKhq:e[s(1455)],tTbYU:function(g,R,C,N){return e[s(1365)](g,R,C,N)},AJXWv:e[s(264)],tbMnN:e[s(882)],xKEEk:e[s(586)],KGnFI:function(g,R){return e[s(1574)](g,R)},AuAXi:function(g,R){return e[s(1237)](g,R)},LdjQd:function(g,R){return g<<R},Iyxrd:function(g,R){return g<<R},RgudD:function(g,R){return e[s(1638)](g,R)},itWRT:function(g,R){return g<<R}},f=r[s(279)],p=0;for(let g=0;e[s(1161)](g,f);g++)if(e[s(1257)]!=="LnpDf"){let R=r.charCodeAt(g);e[s(1756)](R,55296)&&e[s(326)](R,56319)&&e[s(1161)](e[s(450)](g,1),f)&&(R=e[s(1687)](e[s(900)](R,10)+r.charCodeAt(++g),56613888)),p+=e[s(1410)](R,128)?1:e.CWaiK(R,2048)?2:R<65536?3:4}else{let[R,C]=_0x13ee01(_0x331dfc),N=d[s(1496)](_0x48290f,R),q=0;return _0x3f0f7e[s(577)](B=>{let M=s,oe=d[M(567)].split("|"),ze=0;for(;;){switch(oe[ze++]){case"0":_0x1c8cd3.log(d[M(1484)],B,B[M(574)]);continue;case"1":_0x5734ee[M(759)](d[M(284)],q);continue;case"2":q=d.GlrBI(_0x31b035,N,q,B[M(574)]||0);continue;case"3":_0x47708a[M(759)](d[M(1339)],q);continue;case"4":q=_0x2b3a49(_0x1adf3a[M(324)+"er"](B[M(1491)]||_0xdf27fd),N,q);continue;case"5":q=d[M(1329)](_0x1266e9,0,N,q);continue;case"6":q=d.GlrBI(_0x4c27ef,C[B[M(379)+M(391)]],N,q);continue;case"7":q=_0x5aa3df(B[M(379)+M(391)],N,q);continue;case"8":_0x39f671[M(759)](d[M(1452)],q);continue;case"9":_0x4badf3[M(759)](d[M(1648)],q);continue;case"10":_0x314dda.log(d[M(1750)],q);continue}break}}),{frameType:_0x587203,headers:[{key:s(886)+s(815),value:_0x43088f}],payload:N}}e[s(320)](ge,a,p);let y=e[s(246)](ie,a,p),S=a[s(583)];for(let g=0;e[s(511)](g,f);g++){let R=r[s(1302)+"At"](g);if(e[s(529)](R,55296)&&e[s(326)](R,56319)&&e.UfMgk(e[s(1393)](g,1),f)&&(R=e[s(1687)](e[s(997)](e.RgwFv(R,10),r[s(1302)+"At"](++g)),56613888)),e.ZyeiJ(R,128))S[y++]=R;else if(e[s(891)](e.kAWfF,e[s(1702)])){if(_0x316a78<=-_0x5e94f9)return _0x227f6f;if(e[s(1756)](_0x4fc419+1,_0x144083))return _0x3992fc}else{if(e[s(1472)](R,2048))S[y++]=e.SJwXn(R>>6&31,192);else{if(e[s(1743)](R,65536))S[y++]=e[s(318)](e.oIJIO(R>>12,15),224);else if(e[s(1721)](e.qWTlV,e.qWTlV))S[y++]=e[s(394)](e.adSSX(R,18),7)|240,S[y++]=e[s(956)](R,12)&63|128;else return new _0x5b333f(d[s(385)](d[s(385)](d.LdjQd(_0x1dd0fe[4],24)|d[s(310)](_0x1a1399[5],16),d[s(802)](_0x43f2e8[6],8)),_0x307e32[7]),d[s(385)](_0x1a8edc[0]<<24|d[s(275)](_0x42787b[1],16)|_0x22dff4[2]<<8,_0x1bb17b[3]),_0x578b06);S[y++]=R>>6&63|128}S[y++]=e.pxFtg(e.tqMVP(63,R),128)}}}function W(a,r){let s=t,d={FTKLK:function(f,p,y){return e[z(1758)](f,p,y)},AKHzF:function(f,p){return f(p)}};if(e[s(515)]==="USxdU"){_0x2ed173(_0x281d95,42);let f=_0x2921ad();wKXQkc[s(1609)](_0x483ac2,_0xf629f0,f),wKXQkc[s(1609)](_0x3a5085,_0x348060,f[s(859)]),_0x3124a2(_0x1a3378,f),wKXQkc[s(1652)](_0x53eefe,f)}else{let f=e[s(494)](ie,a,r[s(859)]),p=a[s(583)],y=r[s(583)];for(let S=0,g=r[s(859)];e[s(1387)](S,g);S++)p[e[s(1098)](S,f)]=y[S]}}function te(a){let r=t;return a[r(583)][e[r(224)](Q,a,1)]}function Ze(a,r){let s=t,d=ie(a,1);a[s(583)][d]=r}function me(a){let r=t,s=0,d=0,f;do f=e[r(1574)](te,a),e[r(383)](s,32)&&(d|=e[r(825)](127,f)<<s),s+=7;while(e[r(301)](128,f));return d}function ge(a,r){let s=t;for(r>>>=0;e[s(698)](r,128);)e[s(1503)](Ze,a,e[s(1552)](e[s(1515)](127,r),128)),r>>>=7;e.IZPbM(Ze,a,r)}function Rt(a,r){let s=t,d={ZHprD:function(g,R){return e[z(294)](g,R)},yzJBZ:function(g,R){return e.xeRJW(g,R)}},f=0,p=0,y=0,S;if(S=e[s(1458)](te,a),f=e.eluXD(127,S),e[s(301)](128,S)&&(S=e[s(1742)](te,a),f|=e.wKWdJ(127,S)<<7,128&S))if(e[s(642)](e[s(689)],e[s(1469)]))S=e[s(295)](te,a),f|=e[s(1069)](e[s(1334)](127,S),14),128&S&&(S=te(a),f|=e[s(825)](127,S)<<21,e[s(1334)](128,S)&&(S=e[s(1633)](te,a),p=127&S,e[s(1657)](128,S)&&(S=e[s(1530)](te,a),p|=e[s(1334)](127,S)<<7,e[s(747)](128,S)&&(S=e[s(693)](te,a),p|=e[s(1686)](127&S,14),128&S&&(S=e[s(1295)](te,a),p|=e.RkDRo(e[s(1515)](127,S),21),e[s(228)](128,S)&&(S=e.mMQtw(te,a),y=e[s(334)](127,S),128&S&&(S=e[s(1633)](te,a),y|=e[s(792)](127&S,7))))))));else{let g=_0x4e5f43.call(gfNytZ[s(1464)](_0xaf9a12,this),_0x1e0eca,..._0x5ba046);return _0x494681[s(1706)](g,_0x1cb02c[s(316)]?_0x36ee19[s(316)]():[_0x379967]),gfNytZ[s(1221)](_0x2e712b,g)}return{low:f|e[s(1181)](p,28),high:e[s(829)](e.ntJTX(p,4),e.xLkST(y,24)),unsigned:r}}function yt(a,r){let s=t,d=e[s(781)](r[s(569)],0),f=(r.low>>>28|e[s(1181)](r[s(707)],4))>>>0,p=r[s(707)]>>>24,y=e[s(422)](0,p)?f===0?d<16384?e[s(1595)](d,128)?1:2:e[s(1307)](d,2097152)?3:4:e.yPcuf(f,16384)?f<128?5:6:f<2097152?7:8:e[s(373)](p,128)?9:10,S=ie(a,y),g=a[s(583)];switch(y){case 10:g[e[s(1694)](S,9)]=e[s(935)](e.iPmkj(p,7),1);case 9:g[e[s(1707)](S,8)]=e.fNqwi(9,y)?e[s(1237)](128,p):e[s(710)](127,p);case 8:g[e[s(1170)](S,7)]=e.WDnVE(8,y)?e[s(211)](e[s(651)](f,21),128):e[s(1011)](f,21)&127;case 7:g[e[s(1225)](S,6)]=e[s(1296)](7,y)?e[s(1736)](f>>>14,128):e[s(394)](e.OweVT(f,14),127);case 6:g[e[s(1170)](S,5)]=e[s(934)](6,y)?f>>>7|128:e[s(266)](e[s(271)](f,7),127);case 5:g[e[s(518)](S,4)]=e[s(1391)](5,y)?e.OVrBo(128,f):e[s(1517)](127,f);case 4:g[S+3]=e.EhKVu(4,y)?e[s(211)](d>>>21,128):e[s(570)](e.waNDr(d,21),127);case 3:g[S+2]=e[s(352)](3,y)?e.iKTnK(e[s(781)](d,14),128):e[s(1277)](d>>>14,127);case 2:g[e[s(1283)](S,1)]=y!==2?e.hDvYB(e[s(1293)](d,7),128):e[s(1712)](d,7)&127;case 1:g[S]=e[s(219)](1,y)?e.CCxQW(128,d):e.sIaPM(127,d)}}function on(a){let r=t,s={fiWQt:e[r(1005)],ocBrS:r(267)+r(526)};return e[r(891)](e[r(696)],e[r(696)])?{frameType:_0x2b9b7f,headers:[{key:s[r(1442)],value:s[r(1420)]}],payload:void 0}:E(a)}function Ht(a){return v(a)}let an=65536,ei=e[t(1611)],ye=e.PpzrL(an,an),Te=ye*ye,rr=e[t(1036)](Te,2),Ne=String[t(650)+"e"][t(1302)+"At"];class pe{constructor(r,s,d){let f=t;this[f(1748)]=!0,this[f(569)]=e.gJsGS(0,r),this.high=e[f(724)](0,s),this[f(924)]=!!d}static[t(1748)](r){let s=t;if(e[s(1762)](e.NHoxc,e[s(796)]))return r&&e[s(289)](!0,r[s(1748)]);{let d=e.Mujgi[s(813)]("|"),f=0;for(;;){switch(d[f++]){case"0":return _0xc666ef(_0x1b9c37,_0x70aaaf,_0x1ed7a8)+_0x25f4ca;case"1":if(_0x24148e.utf8Write)return _0x2766fd.utf8Write(_0x2f6478,_0x441375)+_0x4eae03;continue;case"2":if(e.bPYbn(_0x40a0de.length,40))return e[s(874)](e[s(661)](_0x298356,_0x5b485d,_0x17de9f,_0x4df27d),_0x2a4d32);continue;case"3":if(!_0x429bd9)return _0xb4d570;continue;case"4":if(_0x4dc77b[s(1685)])return e.yarhX(_0x4da821[s(1685)](_0x233e26,_0x222997),_0x43ed99);continue}break}}}static fromBits(r,s,d){let f=t,p={SRARL:function(y,S,g){return y(S,g)},PnVOq:e.SavKq};if(f(489)!==e[f(685)])return new pe(r,s,d);{let y=_0x1f9903[f(1353)][f(358)](_0x146a52[f(1371)+"et"],e[f(1393)](_0x81ecbe[f(1195)+"th"],_0x1faefc[f(1371)+"et"]));this[f(779)]&&this[f(779)].send({data:y,fail:S=>{let g=f;this[g(413)](g(403),p[g(912)](_0x2ac083,p[g(1311)],{message:this[g(1488)+"rrorMess"+g(1107)](S)}))}})}}static[t(405)+"s"](r,s,d){let f=t;return d?pe["fromByte"+f(1378)](r,s):pe[f(405)+"sBE"](r,s)}static[t(405)+"sLE"](r,s){let d=t;return e[d(691)]===e[d(691)]?new pe(e.fEYUR(e[d(1736)](r[0]|e[d(1719)](r[1],8),e[d(1638)](r[2],16)),e[d(1158)](r[3],24)),r[4]|e.RkDRo(r[5],8)|e.aAoZt(r[6],16)|e[d(738)](r[7],24),s):this._qosDB?.[d(1706)]({message_id:_0x499733,timestamp:_0x2c9f72})}static[t(405)+"sBE"](r,s){let d=t;return new pe(e.cvGwe(e[d(1552)](e.xLkST(r[4],24),r[5]<<16)|e[d(1566)](r[6],8),r[7]),e[d(211)](e[d(1686)](r[0],24)|e[d(889)](r[1],16)|r[2]<<8,r[3]),s)}static[t(205)](r){let s=t;return e.Drcoa(r,ei)?hl:new pe(e.lqcfo(e.gJsGS(e[s(1267)](e[s(1318)](Ne.call(r,0),e[s(792)](Ne[s(976)](r,1),8)),e[s(620)](Ne[s(976)](r,2),16)),e[s(900)](Ne.call(r,3),24)),0),e[s(1665)](e[s(1744)](e[s(1552)](Ne.call(r,4),Ne[s(976)](r,5)<<8),e[s(1266)](Ne[s(976)](r,6),16))|e.AJqjZ(Ne[s(976)](r,7),24),0),!0)}[t(572)](){let r=t;if(e[r(1026)](e[r(1495)],e[r(1495)]))e[r(492)](_0x3ca07a,_0x34142a,96),_0x64be5c(_0x2f8c8e,_0xb03f2(_0x468b09));else return String[r(1183)+r(615)](e.SoZAf(255,this.low),e[r(374)](this.low>>>8,255),e[r(228)](this[r(569)]>>>16,255),this.low>>>24,e[r(228)](255,this[r(707)]),this[r(707)]>>>8&255,e.yUHYP(this[r(707)]>>>16,255),this[r(707)]>>>24)}static fromNumber(r,s=!0){let d=t;if(isNaN(r))return s?tm:hl;if(s){if(r>=Te)return rm}else{if(e[d(326)](r,-rr))return im;if(e[d(819)](e[d(1527)](r,1),rr))return nm}return pe[d(799)](e[d(1424)](r,ye)|0,e[d(318)](e[d(1273)](r,ye),0),s)}[t(1078)](){let r=t,s={eCwAu:function(d,f,p){return d(f,p)},GTSrD:e[r(1157)],fZlsE:e[r(1637)]};if(e[r(863)](e[r(1135)],e.vFQCh))return this[r(924)]?e[r(1169)](e.qnzEp(this[r(707)],0)*ye,this[r(569)]>>>0):e[r(1261)](e.SgYeM(this.high,ye),e.lqcfo(this.low,0));{this[r(1614)+r(1650)+"t"]();let d=s[r(1042)](_0x4c8ad3,s[r(636)],{message:s[r(1223)]});this[r(1123)+r(991)+"yReconnect"]&&this["onStopIm"+r(991)+"yReconnect"](d)}}[t(1439)](){let r=t;return e[r(1762)](0,this[r(707)])&&this[r(569)]===0}[t(225)](r){let s=t;if(e[s(463)]===e[s(463)]){pe[s(1748)](r)||(r=pe[s(324)+"er"](r));let d=e[s(1144)](this[s(707)],16),f=e.LvLVr(65535,this[s(707)]),p=e[s(1712)](this.low,16),y=65535&this[s(569)],S=r.high>>>16,g=e[s(374)](65535,r[s(707)]),R=e[s(746)](r[s(569)],16),C=e.bKRkk(65535,r[s(569)]),N=0,q=0,B=0,M=0;return M+=e[s(1261)](y,C),B+=M>>>16,M&=65535,B+=p+R,q+=e[s(651)](B,16),B&=65535,q+=f+g,N+=e[s(1264)](q,16),q&=65535,N+=d+S,N&=65535,pe[s(799)](e[s(985)](B,16)|M,e[s(905)](e[s(1719)](N,16),q),this[s(924)])}else{let d=this[s(707)],f=this[s(569)];return[e.OJFXf(d,24),e[s(935)](e.RaTMa(d,16),255),e.qnzEp(d,8)&255,255&d,e[s(1144)](f,24),e[s(437)](e[s(1752)](f,16),255),e[s(668)](f>>>8,255),e[s(334)](255,f)]}}[t(1006)](r){let s=t;if(e[s(352)](e[s(1138)],e[s(1138)]))_0x3e6c5d.log(_0x211df3);else return pe[s(1748)](r)||(r=pe[s(324)+"er"](r)),e[s(565)](this.unsigned,r[s(924)])&&e.oUtHM(e.ydoIG(this[s(707)],31),1)&&r[s(707)]>>>31===1?!1:e[s(748)](this.high,r[s(707)])&&e.qoKTu(this[s(569)],r[s(569)])}[t(890)](){let r=t;return e[r(1520)](-1,this[r(569)])&&this[r(707)]===-1?pe[r(799)](0,0,this[r(924)]):e.ncOYY(-1,this[r(569)])?pe[r(799)](0,e[r(1169)](this[r(707)],1),this[r(924)]):pe[r(799)](e[r(1285)](this[r(569)],1),this[r(707)],this[r(924)])}[t(1093)](r){let s=t;if(e[s(562)]!==e[s(775)])return r?this[s(1691)+"E"]():this[s(1297)+"E"]();{let d=this._listeners[_0x5349a2];if(d)for(let f=0;e[s(458)](f,d[s(279)]);)e[s(1624)](d[f].fn,_0x3991c5)?d[s(1197)](f,1):++f}}[t(1691)+"E"](){let r=t,s=this.high,d=this[r(569)];return[e[r(437)](255,d),e[r(888)](d,8)&255,e[r(935)](e[r(1209)](d,16),255),e.NeNUR(d,24),e[r(272)](255,s),e.HMIFh(e.PWGTK(s,8),255),e.apUNm(s>>>16,255),s>>>24]}toBytesBE(){let r=t,s=this[r(707)],d=this[r(569)];return[e[r(271)](s,24),e[r(781)](s,16)&255,e[r(1014)](s,8)&255,255&s,e[r(481)](d,24),e[r(668)](e[r(473)](d,16),255),e[r(806)](d>>>8,255),e[r(1176)](255,d)]}}let hl=new pe(0,0,!1),tm=new pe(0,0,!0),nm=pe[t(799)](-1,2147483647,!1),rm=pe[t(799)](-1,-1,!0),im=pe[t(799)](0,-2147483648,!1);var cn=(function(a){let r=t,s=e[r(1238)].split("|"),d=0;for(;;){switch(s[d++]){case"0":a[a[e[r(657)]]=5005]=r(1030)+"OR";continue;case"1":a[a[e.KDudE]=5002]=r(895)+r(1561);continue;case"2":return a;case"3":a[a[e[r(1534)]]=5001]="NATIVE_E"+r(1606);continue;case"4":a[a[e[r(588)]]=5004]=e[r(588)];continue;case"5":a[a[e[r(777)]]=5003]=r(1352)+"IES_ERROR";continue}break}})({});class ir{constructor(r){let s=t;if(e.SLttv(s(1470),"MLUzq")){let d=this[s(697)+s(249)]?.[s(948)+s(832)+"es"](),f=this[s(697)+s(249)]?.[s(527)+s(1327)+"nt"]();if(d&&!_0xa14177[s(555)]){let p="connect "+f+(s(532)+s(1626)+s(1340)+"ed");this["_dispatchErrorEv"+s(210)](e.pTgDl(_0x30d12a,e.SavKq,{message:p,code:_0x503f57[s(1352)+s(800)+"R"],error:_0xfa4987}));return}this._ws&&this[s(1247)][s(493)+"te"]===this[s(1528)]&&this[s(680)+"ect"](),this[s(919)+s(563)+s(210)](e.ZPBId(_0xd28ac,e.SavKq,{message:_0x49f6d3[s(555)],code:_0x1e96b9["NATIVE_E"+s(1606)],error:_0x20ab97}))}else this[s(778)]=r,this[s(1603)]=null}}class xl extends ir{constructor(r,s){let d=t;super(r),this[d(555)]=s&&s[d(555)]||null}}class pl extends ir{constructor(r,s){let d=t,f={HLSEd:function(p,y){return e[z(947)](p,y)}};if(d(1055)!==e[d(1058)])return function(p,...y){let S=d,g=_0x45fd04[S(976)](cJAbZG.HLSEd(_0x39089d,this),p,...y);return _0x253021[S(1706)](g,p[S(316)]?p[S(316)]():[p]),cJAbZG[S(1360)](_0x82463a,g)};{let p=(d(1602)+"6|0|5")[d(813)]("|"),y=0;for(;;){switch(p[y++]){case"0":this[d(555)]=s&&s[d(555)]||"";continue;case"1":super(r);continue;case"2":this[d(665)]=s&&s[d(665)]||"";continue;case"3":this.error=s&&s[d(403)]||null;continue;case"4":this[d(525)]=s&&s[d(525)]||0;continue;case"5":this.code=s&&s[d(580)]||5001;continue;case"6":this[d(1160)]=s&&s[d(1160)]||0;continue}break}}}}class ml extends ir{constructor(r,s){let d=t;super(r),this[d(580)]=s&&s.code||0,this.reason=s&&s[d(1313)]||"",this[d(315)]=s&&s[d(315)]||!1,this[d(547)+d(1254)]=s&&s[d(547)+"nnect"]||!1}}class gl extends ir{constructor(r,s){let d=t;super(r),this[d(1103)]=s&&s[d(1103)]||null}}class wl extends gl{constructor(r,s){let d=t;super(r),this.data=s&&s.data||null,this[d(555)]=s&&s[d(555)]||null}}class _l extends ir{constructor(r,s){let d=t,f={HzYaB:function(p,y){return p!=y},DnYfu:d(498)+"d",LaEjV:e[d(1306)],Aihlf:e[d(1623)]};e.wVetG(e[d(1034)],e[d(1523)])?(super(r),this[d(1103)]=s&&s[d(1103)]||null):_0x240f80.r=p=>{let y=d;gdvoVX[y(1358)](gdvoVX.DnYfu,typeof _0x230881)&&_0x55411e["toString"+y(706)]&&_0x1b3248[y(1137)+"operty"](p,_0xf96897[y(1726)+y(706)],{value:gdvoVX[y(1708)]}),_0x5abf7d[y(1137)+y(790)](p,gdvoVX[y(1023)],{value:!0})}}}function ft(a,{message:r,code:s,error:d}){return new pl(a,{message:r,code:s,error:d})}function bt(a,{code:r,reason:s,wasClean:d,willReconnect:f}){return new ml(a,{code:r,reason:s,wasClean:d,willReconnect:f})}function yl(a,{data:r,message:s}){let d=t;if(e[d(263)]!==e[d(462)])return new wl(a,{data:r,message:s});this._socket&&this[d(779)][d(1601)]({code:_0x375d46,reason:_0x494496})}function bl(a,{data:r}){return new _l(a,{data:r})}function Ia(a,{message:r}){return new xl(a,{message:r})}class El{constructor(r,s){let d=t;this.endpoints=r,this.maxRetries=s,this[d(1498)+d(879)]=0,this["currentE"+d(1226)+d(302)+"t"]=0}[t(1479)+t(700)+t(1461)](){let r=t;this[r(1498)+"ndex"]=0,this[r(930)+r(1226)+r(302)+"t"]=0}resetTries(){let r=t;this[r(930)+r(1226)+"riesCount"]=0}["getCurre"+t(1327)+"nt"](){let r=t;return this[r(803)+"s"][this[r(1498)+"ndex"]]}["getCurre"+t(1327)+t(476)+t(1662)](){let r=t;return this[r(930)+r(1226)+r(302)+"t"]}[t(948)+t(832)+"es"](){let r=t;return!!(this.currentIndex>=this[r(803)+"s"][r(279)]||this[r(1498)+r(879)]===e[r(1687)](this.endpoints.length,1)&&e[r(1463)](this[r(930)+r(1226)+r(302)+"t"],this[r(877)+"es"]))}[t(977)+t(331)+t(245)+"hedMaxRe"+t(399)](){let r=t;return this[r(1498)+r(879)]==this[r(803)+"s"][r(279)]?!0:e[r(823)](this[r(930)+r(1226)+r(302)+"t"],this[r(877)+"es"])}[t(995)+t(1279)+t(916)+"UpdateCo"+t(328)](){let r=t;return this[r(930)+r(1226)+"riesCount"]=1,this[r(1498)+r(879)]++,this[r(803)+"s"][this[r(1498)+r(879)]]}["getCurrentEndpointAndUpd"+t(768)](){let r=t;return this[r(930)+r(1226)+r(302)+"t"]++,this[r(527)+r(1327)+"nt"]()}}let sr=(e[t(1344)](e[t(1140)],typeof globalThis)&&e[t(1376)]===globalThis[t(715)+t(782)][t(216)]||e[t(293)](e[t(1140)],typeof window)&&e[t(553)](e.cBEXR,window[t(715)+"tor"][t(216)]))&&e.LyvJu(t(498)+"d",typeof document),Cn=e[t(388)](e[t(1140)],typeof globalThis)&&(e[t(994)]===globalThis["construc"+t(782)].name||"DedicatedWorkerG"+t(660)+"pe"===globalThis["construc"+t(782)].name)&&e[t(388)](e[t(1140)],typeof tt),ti=(e[t(535)](e[t(1140)],typeof globalThis)&&e[t(1520)](t(1711),globalThis[t(715)+t(782)].name)||e[t(317)](e[t(1140)],typeof globalThis)||e.LyvJu(e[t(1140)],typeof globalThis)&&!!globalThis["WeixinJS"+t(1204)])&&e[t(1140)]!=typeof wx,ni=e.ukdGS(e.UehPf,typeof globalThis)&&(e[t(321)](e[t(1695)],globalThis[t(715)+t(782)].name)||e[t(1519)]===globalThis[t(715)+t(782)][t(216)]||e.GohvH(e[t(597)],globalThis[t(715)+t(782)][t(216)]))&&e[t(350)](e[t(1140)],typeof self),sm=e[t(1140)]!=typeof globalThis&&t(1711)===globalThis["construc"+t(782)][t(216)]&&e[t(388)](t(498)+"d",typeof global)&&e[t(1492)](e[t(994)],global[t(715)+t(782)][t(216)])&&e[t(552)](e[t(1140)],typeof process)&&!!process[t(429)];class Aa{constructor(){this._listeners={}}[t(413)](r,...s){let d=t,f=this[d(1625)+"rs"][r];if(f)f.slice()[d(577)](p=>p.fn[d(1381)](p[d(1326)],s));else if(e.SavKq===r&&!this[d(239)]){let p=s.length&&s[0];if(p instanceof Error)throw p;let y=new Error(e[d(1170)](d(1569)+d(254),p?e[d(1589)](e[d(1400)](" (",p[d(555)]),")"):""));throw y[d(1147)]=p,p}return this}[t(961)](r,s){let d=t;if(r===void 0)this._listeners={};else if(e[d(625)](void 0,s))this._listeners[r]=null;else{let f=this._listeners[r];if(f)for(let p=0;p<f[d(279)];)e[d(1459)](f[p].fn,s)?f[d(1197)](p,1):++p}return this}on(r,s,d){let f=t,p={HEWQq:"close"};if(e.WWYEH(f(847),e[f(1395)]))this[f(413)](p[f(1338)],_0x4e35f5),this.onclose&&this[f(1513)](_0x7a3b04);else return(this[f(1625)+"rs"][r]||(this._listeners[r]=[]))[f(1730)]({fn:s,ctx:d||this}),this}}class om extends Aa{[t(1488)+"rrorMess"+t(1107)](r){let s=t;return r[s(1205)]||r[s(831)]?(s(1653)+" "+(r.errMsg||"")+s(655)+(r.errNo||""))[s(1645)]():JSON[s(965)+"y"](r)}constructor(r,s,d){let f=t;super(),this[f(779)]=null,ti&&wx[f(830)+f(196)]&&(this._socket=wx[f(830)+f(196)]({url:r,protocols:s,header:d,fail:this[f(1201)+f(287)+f(1117)][f(842)](this),success:this[f(1201)+f(1320)+f(1244)+"ler"][f(842)](this)})),Cn&&tt[f(830)+f(196)]&&(this[f(779)]=tt.connectSocket({url:r,protocols:s,header:d,fail:this[f(1201)+f(287)+"lHandler"][f(842)](this),success:this[f(1201)+f(1320)+f(1244)+f(528)][f(842)](this)}))}[t(1201)+t(1320)+t(1244)+"ler"](){let r=t;e[r(1051)](e[r(1064)],e[r(1021)])?this[r(930)+r(1226)+r(302)+"t"]=0:Promise[r(1613)]().then(()=>{let s=r;this[s(1001)+s(234)]()})}[t(1201)+t(287)+t(1117)](r){let s=t;Promise[s(1613)]().then(()=>{let d=s,f=e[d(1031)](ft,e[d(1550)],{message:this[d(1488)+d(1759)+d(1107)](r)});this[d(413)](e[d(1550)],f);let p=e.ukrUw(bt,e.JqjoE,{reason:this[d(1488)+d(1759)+d(1107)](r)});this[d(413)](e.JqjoE,p)})}[t(1001)+t(234)](){let r=t,s={cNJEs:function(d,f){return e[z(338)](d,f)},rYxDj:function(d,f){return e[z(956)](d,f)},lvbAh:function(d,f){return e[z(458)](d,f)},RpECC:function(d,f){return e[z(826)](d,f)},bKryS:function(d,f){return e[z(512)](d,f)},oPZjk:function(d,f){return e[z(368)](d,f)},uEeQN:function(d,f){return d&f},IUWsr:function(d,f){return e[z(1231)](d,f)},bbIbx:function(d,f){return e[z(482)](d,f)},xYeDj:function(d,f){return e[z(565)](d,f)},KbRWr:e[r(1074)],UeBAW:function(d,f,p){return e[r(867)](d,f,p)},nVaGg:e[r(769)],tCCOa:e.SvIiX,ykbKl:e[r(1550)]};this[r(779)][r(1052)](d=>{let f=r;s[f(887)]("cjRSe",s.KbRWr)?(_0x221ca6<2048?_0xf24a5d[_0x2f945a++]=gImMyT[f(1210)](gImMyT[f(1010)](_0x24de63,6)&31,192):(gImMyT[f(1405)](_0x46e6d6,65536)?_0x444cdb[_0x91cb9c++]=gImMyT.RpECC(gImMyT[f(575)](gImMyT[f(1419)](_0x89f77b,12),15),224):(_0x55fac3[_0x3782b5++]=gImMyT[f(927)](gImMyT[f(1163)](gImMyT.oPZjk(_0x56e9d9,18),7),240),_0x4ba228[_0xdf2e3f++]=gImMyT[f(927)](gImMyT.IUWsr(gImMyT[f(1010)](_0x52ac57,12),63),128)),_0x4edb97[_0x3f7a52++]=gImMyT.bbIbx(gImMyT[f(699)](gImMyT.rYxDj(_0xd1f383,6),63),128)),_0x257e5f[_0x37879a++]=gImMyT.uEeQN(63,_0x2192a5)|128):this[f(413)]("open",s[f(441)](bl,s[f(1450)],{...d,data:d[f(1205)]||""}))}),this[r(779)].onClose(d=>{let f=r,p={CvHOh:function(y,S){return e.atCWg(y,S)},nHVkP:function(y,S){return e.bAdln(y,S)},BYaHp:function(y,S){return e.VLTom(y,S)},MeDGU:function(y,S){return e.nnhCR(y,S)},nRFbg:function(y,S){return e[z(1630)](y,S)},igpAM:function(y,S){return e.LitPw(y,S)},DSaMi:function(y,S){return y<S}};if(e.oSgPH(e[f(764)],e.SxocV)){let y=_0x2c91d2[f(1302)+"At"](_0x4d6a7e);y>=55296&&xnEmbd[f(582)](y,56319)&&xnEmbd[f(1073)](xnEmbd[f(1134)](_0x43c438,1),_0x6cc49e)&&(y=xnEmbd[f(1577)](xnEmbd[f(701)](xnEmbd[f(1375)](y,10),_0x348aad[f(1302)+"At"](++_0x59f28b)),56613888)),_0x3e33f2+=xnEmbd[f(1073)](y,128)?1:xnEmbd[f(1073)](y,2048)?2:xnEmbd.DSaMi(y,65536)?3:4}else this[f(413)](f(1601),e[f(1319)](bt,e[f(612)],{...d}))}),this[r(779)][r(915)+"e"](d=>{let f=r;this[f(413)](f(555),yl(s[f(1508)],{...d}))}),this[r(779)][r(233)](d=>{let f=r;this[f(413)](s[f(1553)],s[f(441)](ft,s[f(1553)],{...d,message:d[f(1205)]||""}))})}send(r){let s=t,d={UzVTQ:s(403),pmNbb:function(f,p,y){return e.TIXCr(f,p,y)},fmmHI:e.JqjoE};if(e[s(1196)](r,Uint8Array))if(e.QhOrQ(e[s(742)],e[s(1560)])){let f=r.buffer[s(358)](r[s(1371)+"et"],e[s(1544)](r.byteLength,r.byteOffset));this[s(779)]&&this[s(779)][s(401)]({data:f,fail:p=>{let y=s;this[y(413)](d[y(247)],d[y(1224)](ft,d[y(247)],{message:this[y(1488)+y(1759)+y(1107)](p)}))}})}else _0x585857&&_0x4dbd2e[s(465)+"Listener"](QWlVhg[s(226)],()=>_0x53d942()),_0x31052b&&_0xc54b36[s(465)+"Listener"](s(743)+s(872),()=>_0x246113());else this._socket&&this[s(779)][s(401)]({data:r,fail:f=>{let p=s;this[p(413)](e[p(1550)],e[p(320)](ft,e[p(1550)],{message:this["_formatE"+p(1759)+p(1107)](f)}))}})}close(r,s){let d=t;e[d(1075)]!==e[d(1294)]?this[d(779)]&&this[d(779)][d(1601)]({code:r,reason:s}):(_0x52939f.set(_0x4d54b0,_0x316423),_0x48abdf[d(1706)](_0x2d3b3c,_0x280168))}["addEvent"+t(1041)](r,s){this.on(r,s)}[t(445)+t(452)+t(197)](r,s){let d=t,f={szFvT:function(p,y,S){return e[z(1610)](p,y,S)},oSpjA:e.JqjoE};if(e[d(397)](d(958),e[d(880)]))this.off(r,s);else{let p=this["_endpoin"+d(249)]?.["getCurre"+d(1327)+"nt"](),y=this[d(865)]["reconnec"+d(1564)+d(1647)](_0x1a1302[d(580)],_0x29303d[d(1313)]);this[d(919)+d(1557)+d(210)](f.szFvT(_0x14532e,f[d(300)],{code:1006,reason:_0x8cf20e.reason||d(744)+d(370)+"d, unkno"+d(861)+d(484)+d(276)+p,willReconnect:y})),y&&this[d(735)]();return}}get[t(493)+"te"](){let r=t;return this._socket[r(493)+"te"]}get[t(1390)+"pe"](){let r=t;if(e[r(1703)]===e[r(1299)])this[r(961)](_0x8dfe44,_0x53dca4);else return this._socket[r(1390)+"pe"]}set[t(1390)+"pe"](r){}get[t(988)](){let r=t;return this[r(779)][r(988)]}get[t(894)](){let r=t;return this[r(779)][r(894)]}get[t(277)+"ns"](){let r=t;return this[r(779)][r(277)+"ns"]}get[t(1505)+"Amount"](){return 0}}function am(a,r){let s=t,d={JixEL:function(f,p,y){return e[z(1593)](f,p,y)}};if(e[s(625)]("vpQxZ",e.rwXWM)){if(r)return new r(a[s(988)],a[s(894)]);if(ti||Cn)return new om(a[s(988)],a[s(894)],a.headers);if(e[s(634)](sr,ni)&&e[s(1344)](e[s(1140)],typeof WebSocket)&&WebSocket)return new WebSocket(a[s(988)],a.protocols)}else _0x5e0647(_0x3fac84,18),XUzqQP[s(371)](_0x68cf2f,_0x1fa993,_0x2a6c0c)}function cm(a){let r=t;return!!(a||ti&&wx[r(830)+"ocket"]||Cn&&tt[r(830)+"ocket"]||e[r(1304)](sr,ni)&&e.ZjXnW(r(498)+"d",typeof WebSocket)&&WebSocket)}function vl(a,r,s){let d=-1;async function f(p){let y=z,S={INjhe:e[y(1597)]};if(e[y(1296)](e[y(1587)],e[y(646)]))return e[y(326)](p,d)?Promise[y(419)](new Error(e[y(1436)])):(d=p,e.KJAXt(p,s.length)?Promise[y(1613)]():s[p][y(842)](a)(r,f[y(842)](null,e[y(874)](p,1))));{let g=S[y(1292)][y(813)]("|"),R=0;for(;;){switch(g[R++]){case"0":this[y(999)+"osed"]=!1;continue;case"1":this[y(1486)]=!0;continue;case"2":this[y(697)+"tManager"]?.["resetEnd"+y(700)+y(1461)]();continue;case"3":this._connect();continue;case"4":this["_pingLos"+y(1579)]?.[y(221)+"nter"]();continue}break}}}e.YuRMg(f,0)}function Sl(a){let r=t,s=0,d=0;for(let f=0;e.ZyeiJ(f,a[r(279)]);++f)d=a[r(1302)+"At"](f),e[r(820)](d,128)?s+=1:e[r(1019)](d,2048)?s+=2:e[r(935)](64512,d)===55296&&e.vFSKq(e[r(340)](64512,a.charCodeAt(e[r(1112)](f,1))),56320)?(++f,s+=4):s+=3;return s}function Il(a,r,s){let d=t;if(e[d(511)](e[d(1688)](s,r),1))return"";let f="";for(let p=r;p<s;){let y=a[p++];if(e.atCWg(y,127))f+=String[d(1183)+d(615)](y);else if(e.geZSP(y,192)&&e.ggycz(y,224))f+=String[d(1183)+d(615)](e[d(1267)](e[d(496)](31,y)<<6,e[d(437)](63,a[p++])));else if(e[d(698)](y,224)&&y<240)f+=String[d(1183)+"Code"](e[d(1383)](e[d(1267)](e.AVwAt(e[d(848)](15,y),12),e[d(1118)](e.DwaAL(63,a[p++]),6)),e.pLsfz(63,a[p++])));else if(e[d(819)](y,240)){let S=e[d(1446)](e[d(1736)](e[d(1714)](e[d(829)](e[d(1217)](e[d(1150)](7,y),18),e[d(1651)](63,a[p++])<<12),e[d(1657)](63,a[p++])<<6),63&a[p++]),65536);f+=String[d(1183)+d(615)](e.ZrbGo(55296,S>>10)),f+=String[d(1183)+d(615)](56320+e[d(1188)](1023,S))}}return f}function ka(a,r,s){let d=t,f=s,p,y;for(let S=0;e[d(987)](S,a[d(279)]);++S)if(e[d(1506)](e.XMrhC,d(1082)))if(p=a[d(1302)+"At"](S),p<128)r[s++]=p;else if(p<2048)r[s++]=e.MchJz(e.aLoia(p,6),192),r[s++]=e[d(338)](e[d(1651)](63,p),128);else if(e[d(1046)](e.XRCnK(64512,p),55296)&&e[d(870)](e[d(1061)](64512,y=a[d(1302)+"At"](e[d(518)](S,1))),56320)){let g=e[d(1085)].split("|"),R=0;for(;;){switch(g[R++]){case"0":r[s++]=e[d(1693)](e[d(864)](63,p),128);continue;case"1":r[s++]=e[d(849)](e.ZRZnm(p,6)&63,128);continue;case"2":r[s++]=e[d(1267)](e[d(544)](e[d(368)](p,12),63),128);continue;case"3":r[s++]=e[d(1510)](e[d(595)](p,18),240);continue;case"4":++S;continue;case"5":p=e[d(1169)](e[d(1246)](65536,e.GoDXN(1023,p)<<10),e.zXSvX(1023,y));continue}break}}else r[s++]=e[d(1386)](e[d(966)](p,12),224),r[s++]=e[d(1237)](e.BFVPG(p,6)&63,128),r[s++]=e[d(1176)](63,p)|128;else this[d(809)+"T"]||this[d(392)+"X"]?this[d(343)+d(1549)+"ange"]():this[d(606)+"er"]&&this._initGlobalEventListener();return e[d(1687)](s,f)}async function Al(a){let r=t;if(e[r(871)]==typeof a){let s=new Uint8Array(e[r(1501)](Sl,a));return e.OIaMG(ka,a,s,0),s}return e[r(1482)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[r(1353)],a[r(1371)+"et"],a.byteLength)}function dm(a){let r=t,s={ggOWN:function(d,f){return e[z(755)](d,f)},LZPpE:function(d,f){return e[z(1325)](d,f)},jmxhb:function(d,f){return e[z(806)](d,f)},kIWRI:function(d,f){return e[z(587)](d,f)},sSZXK:function(d,f){return e[z(453)](d,f)},BVtoL:function(d,f){return e[z(932)](d,f)},CfZkN:function(d,f){return e.WPVXR(d,f)}};try{if(e.KTKta(e.FCnHB,e[r(427)]))_0x47dda0=AqBvuG[r(980)](_0x44be4d,_0x34f63b),_0x59fee7|=AqBvuG[r(1276)](AqBvuG[r(1696)](127,_0x285021),21),AqBvuG[r(1696)](128,_0x11b024)&&(_0x509aaa=AqBvuG[r(1689)](_0x54bc1a,_0x40842f),_0x3982fa=AqBvuG[r(1167)](127,_0x34a6d6),AqBvuG.jmxhb(128,_0x51cf06)&&(_0x3cf957=AqBvuG[r(798)](_0x5bb803,_0x58f3ff),_0x511447|=AqBvuG.LZPpE(AqBvuG[r(291)](127,_0x3af920),7)));else return e[r(1344)](r(1539),typeof a)&&(e[r(1196)](a,ArrayBuffer)||a.buffer&&e[r(1196)](a[r(1353)],ArrayBuffer))||r(1539)!=typeof a?"":(JSON[r(240)](a),e.gElqh)}catch{return e[r(1089)](r(1539),typeof a)?e.NGoUL:""}}let lm=(a,r)=>{let s=t;switch(a){case e[s(545)]:case e.KhyYZ:return{["x-use-"+a]:1,"x-tt-env":r};default:return{}}};class um{constructor(r){let s=t,d={GCNYh:function(f,p){return e.BwNji(f,p)}};if(e.EfiXo(e[s(690)],e[s(1641)]))this[s(1202)+s(1662)]=r,this[s(1040)]=0;else{let f=this[s(1342)][s(1097)+s(641)](this[s(1373)]),p=_0x535efb.parse(d[s(1343)](f,"{}"));return p[_0xc17875]=void 0,this._qosDB[s(885)+s(641)](this[s(1373)],_0x169bff[s(965)+"y"](p))}}[t(1207)](){let r=t;this[r(1040)]++}[t(948)+t(1300)+"nt"](){let r=t;return e[r(1298)](this[r(1040)],this[r(1202)+r(1662)])}[t(221)+t(1427)](r=0){let s=t;this[s(1202)+s(1662)]=r,this[s(1040)]=0}}async function fm(a){let r=t,s={UaeCj:e[r(486)],CFieF:function(d,f){return e[r(1295)](d,f)},mydsa:e[r(785)],nFaTT:e[r(643)],DmeCP:e[r(313)],yKkHl:"&jscallb"+r(722)+r(1122)+"P"};return new Promise(d=>{let f=r;if(!sr)return s.CFieF(d,s[f(1186)]);try{let p=document[f(1477)+f(589)](s[f(712)]);window["frontier"+f(751)]=y=>{let S=f;document[S(1364)][S(237)+S(258)](p),window[S(222)+S(751)]=void 0,d(y&&y[S(590)]||s[S(1186)])},p[f(778)]=s[f(1745)],p.src=a[f(1490)](/^ws/,s[f(522)])+s[f(996)];try{document[f(1364)][f(687)+f(258)](p)}catch{document.body[f(237)+"ild"](p)}}catch{window[f(222)+f(751)]=void 0,d(s[f(1186)])}})}function dn(a,r,s){let d=t;return!!a?.[d(619)](f=>f[d(1441)]===r&&f.value===s)}function or(a,r){let s=t;return a?.[s(619)](d=>d[s(1441)]===r)?.[s(273)]}let Ta=null;async function hm(){let a=t;return Ta||(Ta=Promise.resolve()[a(957)](Ut[a(842)](Ut,a(220)))),Ta}class xm extends Aa{constructor(r,s){let d=t;super(),this._dbName=r,this[d(550)]=s,this[d(1342)]=void 0,this["_initPro"+d(1468)]=null}async[t(708)](){await this[t(551)]()}async _init(){let r=t,s={IDLtD:function(d){return e.fkhSN(d)},bNqZl:function(d,f,p,y){return e[z(1431)](d,f,p,y)},FyKsM:function(d,f){return d+f},IopSl:function(d,f){return e[z(754)](d,f)},SqcrF:function(d,f){return e[z(1717)](d,f)},QzpcV:function(d,f){return e[z(1283)](d,f)},QRycJ:function(d,f){return e.mtiJS(d,f)},pheeV:function(d,f){return d!==f},cLAYa:function(d,f){return d&f},Dhzjn:function(d,f){return e[z(1383)](d,f)},szUms:function(d,f){return e[z(1399)](d,f)},ztUMi:function(d,f){return d|f},aDvlM:function(d,f){return e.EWjbd(d,f)},TNoNL:function(d,f){return d<<f},dzWAW:function(d,f){return e.UfLhC(d,f)},RAKUn:function(d,f){return d>f},xSmRm:function(d,f,p){return e[z(320)](d,f,p)},ggNBS:function(d,f){return e[z(843)](d,f)},vrGEP:function(d,f){return e[z(1170)](d,f)}};if(e[r(878)](e[r(1728)],e[r(1728)])){if(this[r(1342)])return;if(this[r(227)+r(1468)])return this[r(227)+r(1468)];try{let d=this[r(236)],f=this[r(550)];this[r(227)+r(1468)]=(async()=>{let p=r,{openDB:y}=await s[p(1008)](hm);this[p(1342)]=await s[p(1699)](y,p(222)+"_"+d,1,{upgrade(S){S.createObjectStore(d,{keyPath:f})}})})(),await this[r(227)+"mise"]}catch(d){console[r(759)](d)}finally{this[r(227)+r(1468)]=null}}else _0x2cd6b3=_0x12d932[cEFjPK[r(312)](cEFjPK[r(1080)](_0x3cfb5d,_0x50602e),1)],_0x2f8fd0=_0x303b3e[cEFjPK.SqcrF(_0x163566+_0x22c2a8,2)],_0x3d44a9=_0x58c68c[cEFjPK[r(1596)](cEFjPK.QRycJ(_0x3f15f3,_0xefa433),3)],cEFjPK[r(1114)](cEFjPK.cLAYa(cEFjPK.Dhzjn(_0x47fa15|cEFjPK[r(507)](_0x4ca757,8),_0x4450ca<<16),12632256),8421504)?_0x523dbd+=_0x2375cf:(_0xf3d443=cEFjPK[r(232)](cEFjPK[r(585)](cEFjPK[r(507)](cEFjPK.aDvlM(7,_0x1c507e),18),cEFjPK[r(844)](cEFjPK.cLAYa(63,_0x31c1b2),12)),cEFjPK.cLAYa(63,_0x1838cc)<<6)|cEFjPK[r(386)](63,_0x8a48c5),_0x41b860<65536||cEFjPK[r(600)](_0x1ac55f,1114111)?_0x1cfdc4+=_0x24b400:(_0x5cbfa5-=65536,_0x509c74+=cEFjPK[r(1065)](_0x56a9a3,cEFjPK[r(989)](_0x143db5,10)+55296,cEFjPK[r(319)](cEFjPK[r(361)](1023,_0x5948ad),56320)),_0x55d34a+=3))}async get(r){let s=t;if(e[s(1391)](e[s(1256)],e[s(1256)]))this[s(1178)+s(1579)]?.addCount(),this[s(413)](s(1154)+"e_timeout",e[s(1370)]),this[s(1178)+s(1579)]?.[s(948)+s(1300)+"nt"]()?this[s(1396)+s(1218)]():this[s(1426)]();else try{if(e[s(1391)](e[s(477)],e.kwuqn))return await this[s(551)](),this[s(1342)]?.[s(274)](this[s(236)],r);{let p=(s(950)+"4").split("|"),y=0;for(;;){switch(p[y++]){case"0":var d=_0x4d59ea[_0x39c8a4]={exports:{}};continue;case"1":_0x1ff6dc[_0x530d80](d,d[s(837)],_0x5aebb8);continue;case"2":if(mYkanF[s(1357)](void 0,f))return f[s(837)];continue;case"3":var f=_0x46cbed[_0x349a04];continue;case"4":return d[s(837)]}break}}}catch(p){console[s(759)](p)}}async set(r,s){let d=t;return await this[d(551)](),this[d(1342)]?.[d(503)](this._dbName,r)}async[t(259)](r){let s=t;try{return await this._init(),this[s(1342)]?.delete(this[s(236)],r)}catch(d){console.log(d)}}async clear(){let r=t,s={dMPWn:e[r(883)],ijltu:function(d){return e.fkhSN(d)}};try{return await this[r(551)](),this[r(1342)]?.[r(1177)](this[r(236)])}catch(d){e.xBztZ===e[r(962)]?(this[r(1658)](s[r(1428)],_0x170d00[r(555)]),s[r(729)](_0x354745)):console[r(759)](d)}}async[t(1054)](){let r=t;return await this[r(551)](),this[r(1342)]?.[r(430)+"ys"](this[r(236)])}async[t(1127)](){let r=t,s={PeAnv:function(d,f){return e[z(622)](d,f)},EExGP:r(1020),KZBHI:e.UkWnf};if(e[r(1168)]===e[r(342)]){let d=_0x36461b[r(813)](/\./)[r(472)](y=>_0x53ddcd(y)),f=[];return f[0]=_0x254d30(d[0]+d[1]),f[1]=_0x23605f(sXJZeU[r(504)](d[2],d[3])),[sXJZeU[r(1346)],sXJZeU[r(1346)],r(1020),sXJZeU[r(1346)],sXJZeU.EExGP,sXJZeU[r(1403)],f[0],f[1]][r(1642)]("")}else return await this[r(551)](),this[r(1342)]?.getAll(this[r(236)])}async[t(1091)](){let r=t;try{this[r(1342)]?.[r(1601)](),this._qosDB=void 0}catch(s){console[r(759)](s)}}get[t(424)](){let r=t;try{return!!this._qosDB}catch(s){return console[r(759)](s),!1}}}class pm{constructor(r,s){let d=t;this._DBName=r,this[d(780)]=s,this[d(1342)]=localStorage}async[t(708)](){}get[t(1373)](){let r=t;return r(222)+"_"+this[r(857)]}async get(r){let s=t,d=this._qosDB.getItem(this[s(1373)]);return JSON.parse(e[s(634)](d,"{}"))[r]}async[t(1706)](r,s){let d=t,f=this._qosDB[d(1253)](this[d(1373)]),p=JSON[d(240)](f||"{}");return p[s||r[this._pathKey]]=r,this[d(1342)][d(614)](this[d(1373)],JSON[d(965)+"y"](p)),s||r[this[d(780)]]}async[t(259)](r){let s=t,d=this[s(1342)][s(1253)](this[s(1373)]),f=JSON[s(240)](e[s(351)](d,"{}"));return f[r]=void 0,this[s(1342)][s(614)](this[s(1373)],JSON[s(965)+"y"](f))}async[t(1177)](){let r=t;return this._qosDB[r(1177)]()}async[t(1054)](){let r=t,s=this[r(1342)][r(1253)](this[r(1373)]),d=JSON.parse(s||"{}");return Object[r(1054)](d)}async[t(1127)](){let r=t,s=this[r(1342)][r(1253)](this._prefix),d=JSON.parse(e[r(1066)](s,"{}"));return Object.values(d)}closeDB(){return Promise[t(1613)]()}get[t(424)](){return!!this[t(1342)]}}class mm{constructor(r,s){let d=t;this[d(857)]=r,this._pathKey=s,this[d(1342)]=Cn?tt:ti?wx:null}async[t(708)](){}get _prefix(){return t(222)+"_"+this._DBName}async[t(274)](r){let s=t,d=this[s(1342)][s(1097)+s(641)](this[s(1373)]);return JSON[s(240)](e[s(351)](d,"{}"))[r]}async[t(1706)](r,s){let d=t,f=this[d(1342)]["getStora"+d(641)](this[d(1373)]),p=JSON[d(240)](e[d(726)](f,"{}"));return p[s||r[this[d(780)]]]=r,this[d(1342)][d(885)+d(641)](this[d(1373)],JSON[d(965)+"y"](p)),s||r[this._pathKey]}async[t(259)](r){let s=t,d=this._qosDB[s(1097)+s(641)](this[s(1373)]),f=JSON[s(240)](e[s(1066)](d,"{}"));return f[r]=void 0,this[s(1342)][s(885)+"geSync"](this[s(1373)],JSON[s(965)+"y"](f))}async clear(){let r=t;return this[r(1342)]["clearSto"+r(881)]()}async[t(1054)](){let r=t,s=this[r(1342)][r(1097)+r(654)+"nc"](this._prefix),d=JSON.parse(s||"{}");return Object.keys(d)}async[t(1127)](){let r=t,s=this[r(1342)][r(1097)+r(654)+"nc"](this._prefix),d=JSON[r(240)](e.OdkIF(s,"{}"));return Object[r(349)](d)}closeDB(){return Promise[t(1613)]()}get[t(424)](){return!!this[t(1342)]}}function kl(a,r){let s=t;if(e.mlOpx(Cn,Cn))return new mm(a,r);if(e[s(1066)](sr,ni)&&e[s(898)](e.UehPf,typeof indexedDB))return new xm(a,r);if(e.Ckben(sr,ni)&&e.UehPf!=typeof localStorage)return new pm(a,r);throw new Error(s(1608)+s(926)+"d")}class gm{constructor(){let r=t;this._intervalTimeoutId=null,this[r(845)+"l"]=36e5,this._qosDB=e[r(1369)](kl,e[r(530)],e[r(608)])}async[t(845)+t(594)](){let r=t,s={ZzkRh:function(d,f){return e.UCGfn(d,f)},ICWgh:function(d,f){return e[z(1566)](d,f)},MxSKg:function(d,f){return e[z(1277)](d,f)},kaSAN:function(d,f){return e.iIUIQ(d,f)},gEues:function(d,f){return e[z(1076)](d,f)},TaBwk:function(d,f){return e[z(1657)](d,f)}};e.psevs(r(1155),e[r(1166)])?(e[r(824)](_0x4376d7,_0x1adbe6,10),e[r(1447)](_0x529f0c,_0x21014a,_0x568839)):(clearInterval(this["_interva"+r(1578)+"Id"]),this["_interva"+r(1578)+"Id"]=setInterval(()=>{let d=r;if(e.KJAXt(d(1674),e[d(1524)]))this[d(1705)+d(1392)]();else{let f=(wILQYl[d(466)](wILQYl[d(466)]((7&_0x1f9433)<<18,wILQYl[d(497)](63&_0x13a9d0[_0x3d23e5++],12)),wILQYl[d(497)](63&_0x186587[_0x36219f++],6))|wILQYl[d(702)](63,_0x5cd303[_0x1c386b++]))-65536;_0x4f8a6f+=_0x2955c7[d(1183)+d(615)](wILQYl[d(282)](55296,wILQYl[d(914)](f,10))),_0x43d1ff+=_0x562f6e[d(1183)+d(615)](wILQYl.kaSAN(56320,wILQYl.TaBwk(1023,f)))}},this[r(845)+"l"]))}async[t(708)](){let r=t;e.sskRX(r(1094),e[r(1584)])?await this[r(1342)][r(708)]().then(()=>{let s=r;this[s(845)+s(594)]()}):(_0x5d6337[_0x290bbc++]=_0x5c0808>>6|192,_0x1dd236[_0x38a893++]=e[r(1267)](63&_0x306de7,128))}async flushExpired(){let r=t;(await this[r(1342)]?.[r(1127)]()||[])[r(1063)](({timestamp:f})=>f<Date[r(786)]())[r(577)](f=>{let p=r;this[p(1342)]?.[p(259)](f.message_id)})}async[t(259)](r){let s=t;return this[s(1342)]?.[s(259)](r)}async[t(1706)](r,s){let d=t,f={xCXjZ:function(p){return e[z(1185)](p)},lPMiP:function(p,y,S){return e[z(840)](p,y,S)},cFwND:function(p,y){return p(y)}};if(e.kvbos!==e[d(794)])return this._qosDB?.[d(1706)]({message_id:r,timestamp:s});{let p=NywdKt.xCXjZ(_0x5ab418);return NywdKt[d(495)](_0x1f15ab,_0x1c1654,p),NywdKt[d(1108)](_0x5282d5,p)}}async get(r){return this[t(1342)]?.get(r)}async[t(1091)](){let r=t;e[r(354)](clearInterval,this["_interva"+r(1578)+"Id"]),await this[r(1342)]?.[r(1091)]()}get[t(424)](){let r=t;return this[r(1342)]?.[r(424)]}}function Ra(a){let r=t,s=!!this._options[r(960)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e[r(661)](dn,a[r(555)][r(1425)],r(244)+r(940),"2"),f=d&&e[r(1677)](dn,a[r(555)][r(1425)],e[r(1512)],"1"),p=d&&e[r(1431)](dn,a.message[r(1425)],e[r(635)],"1"),y=p?e[r(1697)](or,a[r(555)].headers,e.vIhCq)?.[r(813)](",")[r(1063)](Boolean)||[]:[];return{enabled:s,isQoSMessage:d,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:y}}async function Tl(){let a=t;return this[a(1241)+a(834)]||(this[a(1241)+a(834)]=new gm),this["_QoSMana"+a(834)][a(424)]||await this[a(1241)+a(834)].openDB(),this[a(1241)+a(834)]}async function wm(a,r){let s=t,{enableAutoAck:d}=this._options,f=e[s(661)](dn,a[s(555)][s(1425)],e[s(841)],"1"),p=e[s(760)](dn,a.message[s(1425)],e[s(1179)],"1"),y=Ra[s(976)](this,a);if(e[s(827)](d,f)){let{SeqID:S,LogID:g,service:R,LogIDNew:C,method:N}=a[s(555)];this[s(341)]({SeqID:S,LogID:g,LogIDNew:C,service:R,method:N,headers:[{key:e[s(1179)],value:"1"},{key:s(721),value:e[s(1095)](C,"")},{key:e[s(235)],value:"0"}]})}p&&!y[s(285)]&&this[s(919)+"hAckMess"+s(270)](a),e[s(1649)](r)}async function _m(a,r){let s=t;this[s(1658)](s(953),a.message),r()}async function ym(a,r){let s=t,d=on(await e[s(908)](Al,a.data));try{if(e.bzPuV(d[s(1213)],Uint8Array)){let f=e.rowLw(this[s(865)][s(1172)+s(1088)],Object)?{force:!!this[s(865)][s(1172)+"ncoding"][s(776)],encoding:this[s(865)][s(1172)+"ncoding"][s(260)]?this[s(865)][s(1172)+"ncoding"][s(260)][s(1490)](/\s/g,"")[s(1310)+s(329)]():""}:{force:!1,encoding:this[s(865)][s(1172)+s(1088)]?this[s(865)][s(1172)+s(1088)][s(1490)](/\s/g,"")[s(1310)+s(329)]():""},p=d["payloadE"+s(1088)]?d[s(1172)+s(1088)].replace(/\s/g,"")[s(1310)+"ase"]():"",y=e[s(1482)](this._options["payloadT"+s(986)],Object)?{force:!!this[s(865)][s(745)+"ype"][s(776)],type:this[s(865)][s(745)+s(986)][s(778)]?this[s(865)][s(745)+s(986)].type[s(1490)](/\s/g,"")["toLowerC"+s(329)]():""}:{force:!1,type:this[s(865)][s(745)+s(986)]?this[s(865)][s(745)+s(986)][s(1490)](/\s/g,"")[s(1310)+s(329)]():""},S=d[s(745)+s(986)]?d["payloadT"+s(986)][s(1490)](/\s/g,"")[s(1310)+s(329)]():"",g=y[s(776)]?y.type:S||y.type,R=f.force?f[s(260)]:p||f[s(260)],C=[e.NGoUL,e[s(979)],e[s(648)],e.TmqAA],N=[e.kIzoP,e[s(1083)]];this._options[s(973)+s(981)+"extPayload"]&&C[s(1128)](g)&&(!R||N[s(1128)](R))?d[s(474)+s(682)]=e[s(1487)](Il,d[s(1213)],0,d[s(1213)].byteLength):d[s(474)+"oad"]=""}else d["textPayl"+s(682)]=""}catch(f){d[s(474)+"oad"]="",console.log(f)}a[s(555)]=d,e[s(1586)](r)}function bm(a,r,s){let d=t,f={vBoUH:function(R,C){return e[z(1432)](R,C)},yUUcH:function(R,C){return e[z(265)](R,C)},QRoer:function(R,C){return e.JCQOF(R,C)},XCjQj:function(R,C){return e[z(457)](R,C)},Epemn:function(R,C){return e.ZiWGg(R,C)},HuIWT:function(R,C){return e[z(787)](R,C)}},p=e.Pugao(s,8192),y=e[d(481)](p,1),S=null,g=p;return function(R){let C=d;if(R<1||R>y)return f[C(990)](a,R);f[C(1473)](f[C(1413)](g,R),p)&&(S=f[C(1433)](a,p),g=0);let N=r.call(S,g,g+=R);return f[C(1660)](7,g)&&(g=f[C(540)](7|g,1)),N}}let Em=4294967295;function vm(a,r,s){let d=t;return e[d(1525)](RangeError,e[d(1670)](e[d(874)](e[d(1169)](e[d(1359)](d(1594)+d(1129)+d(230),a),e[d(1646)]),e[d(1095)](r,1))+e[d(1015)],s))}function Sm(a,r,s){let d=t;if(e[d(1418)](e[d(939)],e[d(939)])){if(e.LkhVe(s,Em))throw new Error(e[d(1116)]);let f=3;for(;f>=0;){let p=255&s;e[d(1487)](Ca,p,a,e[d(1081)](r,f)),s>>>=8,f--}return e.vfaOQ(r,4)}else e[d(223)](_0x2f8d03,this,_0x470618,[_0x3e521d,_0x365bc3,_0x399981,_0x1f4a08,_0x1e065e,_0x57081e])}function Im(a,r){let s=t,d=0,f=r,p=e[s(1670)](r,4);for(;e.CWaiK(f,p);){let{value:y,offset:S}=Pa(a,f);f=S,d=e[s(390)](e[s(1251)](d,8),0),d+=y}return{value:d,offset:p}}function Am(a,r,s){let d=t,f=e.jHSfF.split("|"),p=0;for(;;){switch(f[p++]){case"0":if(e.wPFPR(a[d(279)],40))return e[d(1077)](ka(a,r,s),s);continue;case"1":if(!a)return s;continue;case"2":if(r.utf8Write)return e[d(1246)](r[d(1509)+"e"](a,s),s);continue;case"3":return e[d(510)](e.OIaMG(ka,a,r,s),s);case"4":if(r[d(1685)])return e.faNlR(r[d(1685)](a,s),s);continue}break}}function km(a,r){let s=t,d=new pe(e[s(829)](e[s(810)](a[e[s(1169)](r,4)],24)|a[e.bDHNs(r,5)]<<16|e[s(738)](a[r+6],8),a[e[s(1285)](r,7)]),e[s(325)](e[s(303)](e[s(620)](a[r+0],24),e.RgwFv(a[e[s(1527)](r,1)],16)),e[s(1263)](a[r+2],8))|a[e.CpISS(r,3)],!0);return r+=8,{value:d,offset:e[s(1261)](r,8)}}function Tm(a,r,s){let d=t,f=a[d(569)],p=a[d(707)];return r[s]=e[d(1014)](p,24),r[s+1]=e.OplzG(e.tBDlS(p,16),255),r[e[d(1546)](s,2)]=e[d(1669)](e[d(793)](p,8),255),r[e[d(1098)](s,3)]=e[d(1176)](255,p),r[s+4]=e[d(1558)](f,24),r[e[d(1169)](s,5)]=e[d(1321)](e[d(271)](f,16),255),r[e.knsCc(s,6)]=f>>>8&255,r[s+7]=e[d(1291)](255,f),s+=8,s}function Pa(a,r){let s=t;return a.readUInt8?{value:a[s(774)+"8"](r),offset:e[s(754)](r,1)}:{value:e[s(1389)](255,a[r]),offset:e[s(1077)](r,1)}}function Ca(a,r,s){let d=t;return r.writeUint8?r[d(298)+"t8"](a,s):r[s]=e[d(1150)](255,a),e[d(1565)](s,1)}let Rm=function(a){return new Uint8Array(a)},Pm=e.aJBLn(t(498)+"d",typeof Buffer)?Buffer[t(1028)+t(1139)]:e[t(1032)](bm,Rm,Uint8Array[t(650)+"e"].subarray),Cm=16,Da=32;function Dm(a){let r=t;if(e[r(1045)](e[r(969)],e[r(969)])){let s=0,d={};for(let f=0;e[r(987)](f,a[r(279)]);f++)d[a[f][r(379)+r(391)]]=e[r(1336)](Sl,a[f][r(379)+"ame"]),s+=e.KrFfD(14,d[a[f][r(379)+r(391)]]);return[s,d]}else this[r(1498)+"ndex"]=0,this[r(930)+r(1226)+"riesCount"]=0}function Rl(a,r,s){let d=t,f={msTlM:function(R,C){return e[z(1328)](R,C)},fbdLF:function(R,C){return e[z(1045)](R,C)},uEQtU:e[d(1618)],itvUQ:e.DTEZK,waMqV:function(R,C,N,q){return R(C,N,q)},qrrvo:d(1018),VtqFn:e.VjSof,bnqlU:function(R,C,N,q){return e[d(1677)](R,C,N,q)},wBzkt:"service-"+d(216),oEzie:d(216),iCJKR:function(R,C,N,q){return e.bwyLv(R,C,N,q)},YhfZl:d(485)},[p,y]=Dm(a),S=Pm(p),g=0;return a[d(577)](R=>{let C=d,N={XyytC:function(q,B){return f[z(1113)](q,B)}};if(f[C(538)](C(1366),f.uEQtU))console[C(759)](f.itvUQ,R,R[C(574)]),g=f[C(1106)](Ca,0,S,g),console.log(f[C(1385)],g),g=Sm(S,g,R[C(574)]||0),console[C(759)](f.VtqFn,g),g=f[C(791)](Ca,y[R[C(379)+C(391)]],S,g),console[C(759)](f[C(1290)],g),g=f[C(791)](Am,R[C(379)+C(391)],S,g),console[C(759)](f[C(611)],g),g=f[C(1115)](Tm,pe[C(324)+"er"](R[C(1491)]||r),S,g),console[C(759)](f[C(488)],g);else{let q=this._qosDB.getItem(this[C(1373)]),B=_0x51532c[C(240)](fzKBpg[C(1599)](q,"{}"));return B[_0x2058cc||_0x22ca29[this[C(780)]]]=_0x38392d,this[C(1342)][C(614)](this[C(1373)],_0x171b2d.stringify(B)),_0x1c67a7||_0x33aeaa[this._pathKey]}}),{frameType:Da,headers:[{key:d(886)+"ile_name",value:s}],payload:S}}function Om(a){let r=t,s=0,d=[];for(;e[r(821)](s,a[r(1195)+"th"]);){let{offset:f}=Pa(a,s);s=f;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=e.pTgDl(Im,a,s);p.service=y,s=S;let{value:g,offset:R}=Pa(a,s);s=R,p[r(379)+r(391)]=e[r(1677)](Il,a,s,s+g),s+=g;let{value:C,offset:N}=e[r(1518)](km,a,s);p.cursor=C[r(1078)](),s=N,d.push(p)}return d}function Lm(){let a=t;return e[a(998)](e.WLRkS,a(1235))?_0x20e64f||(_0x9a7766=[_0xb85b66.prototype[a(393)],_0x2390a4[a(650)+"e"][a(951)],_0x3a47d7[a(650)+"e"][a(951)+"PrimaryKey"]]):{frameType:Da,headers:[{key:e[a(1005)],value:e[a(917)]}],payload:void 0}}class Nm{constructor(r,s,d){let f=t;this[f(1361)+f(375)]=r,this[f(1480)+"ileName"]=s,this[f(469)+"Strategy"]=d,this[f(1342)]=kl(this[f(1361)+f(375)],e[f(1435)])}async[t(708)](){await this._qosDB.openDB()}async[t(970)+"rs"](){let r=t;if(!this[r(1342)].isReady)return;let s=this[r(469)+r(1537)],d=await this[r(1342)][r(1127)]();switch(console[r(759)](e[r(1341)],d),s){case"ALL":return d&&d[r(279)]?e[r(1583)](Rl,d,0,this[r(1480)+"ileName"]):void 0;case r(1079):return;case e[r(542)]:return d&&d[r(279)]?e.Ojyix(Rl,d,0,this[r(1480)+"ileName"]):e[r(521)](Lm)}}async[t(1706)](r,s,d){let f=t;return console[f(759)](e[f(330)],r,s,d),this[f(1342)][f(1706)]({cursor_name:r,cursor:s,service:d})}async[t(546)+"rs"](r){let s=t;if(e[s(467)]("BFtww",s(1289)))return _0x4d9a2c?.[s(619)](d=>d[s(1441)]===_0x3afe7e)?.value;{let d=e.uUSSr(Om,r);for(let f of d)if(e.joNlz(e[s(314)],"AGHTO"))console[s(759)](e[s(1248)],d),await this[s(1342)][s(1706)](f);else return this[s(1342)]?.[s(274)](_0x36eb02)}}async[t(274)](r){let s=t;return(await this[s(1342)][s(274)](r))?.[s(1491)]}async[t(1091)](){let r=t;await this[r(1342)][r(1091)]()}[t(1243)+t(1384)+t(337)](r){let s=t;this[s(1480)+s(617)]=r}get isReady(){let r=t;return this[r(1342)][r(424)]}}let Mm=e[t(446)];async function Pl(a){let r=t;if(!this._options.enableQoS)return null;let{aID:s,fpID:d,messageStrategy:f}=this._options,p=e[r(726)](a,Mm);try{if(this["_cursorM"+r(556)]){if(r(1423)!==e[r(591)])return this[r(1342)][r(424)];a&&this._cursorManager["updateCu"+r(1384)+r(337)](a)}else this[r(836)+r(556)]=new Nm(d+"_"+s+"_"+p,p,f);return this[r(836)+r(556)][r(424)]||await this[r(836)+r(556)][r(708)](),this[r(836)+"anager"]}catch{return null}}async function Bm(a,r){let s=t,d={tsIkb:function(B,M){return e[z(811)](B,M)},FsRhf:function(B,M){return e.shoGQ(B,M)},jbiFi:function(B,M){return e[z(1291)](B,M)},DosKQ:function(B,M){return e.hiqRD(B,M)},wLdnd:function(B,M){return e[z(1152)](B,M)},UTGAa:function(B,M){return e.knsCc(B,M)},sOtLr:function(B,M){return e.TQvnf(B,M)},QkJSm:function(B,M){return e[z(1265)](B,M)},jNiZX:function(B,M){return e[z(301)](B,M)},lTqBx:function(B,M){return e[z(868)](B,M)},lNbun:function(B,M){return B<M},xwxsH:function(B,M,oe){return e[z(224)](B,M,oe)},wIGjz:function(B,M,oe,ze){return e[z(1402)](B,M,oe,ze)}},f=dn(a[s(555)][s(1425)],e.XYzpz,"-1"),p=e.jUwpC(dn,a.message[s(1425)],e[s(1179)],"1"),y=e.iPlyi(or,a[s(555)][s(1425)],e[s(1184)]),S=e[s(1458)](Number,e.Omlwc(or,a[s(555)].headers,e[s(1132)]))||0,g=Ra[s(976)](this,a),R=dn(a[s(555)].headers,e[s(623)],"2"),C=e.FeOYr(or,a[s(555)].headers,e[s(1529)]),N=e.inOWu(Number,or(a[s(555)][s(1425)],e[s(1100)]));if(g[s(285)])return e[s(1349)](r);let q=g[s(306)+s(1680)]?await Tl[s(976)](this):null;if(e.eEcwP(a[s(555)][s(574)],0)&&p&&!f||e.LkhVe(a[s(555)].service,0)){if(y&&g[s(306)+s(1680)]&&q)if(e[s(941)](e[s(339)],s(576))){let B=_0x1c410f[s(569)],M=_0x2a1c5e.high;return _0x104207[_0x5a707c]=IiLpwI[s(537)](M,24),_0x27eb88[IiLpwI[s(1035)](_0x52b9f4,1)]=IiLpwI[s(725)](IiLpwI.tsIkb(M,16),255),_0x4eceac[_0x216c69+2]=IiLpwI[s(554)](M>>>8,255),_0x3ce6ff[IiLpwI[s(1162)](_0xa2d6ba,3)]=IiLpwI[s(725)](255,M),_0x52306a[IiLpwI[s(531)](_0x2c9113,4)]=IiLpwI[s(537)](B,24),_0x234f64[_0x83c03f+5]=IiLpwI.sOtLr(IiLpwI.tsIkb(B,16),255),_0x5ba099[IiLpwI[s(952)](_0x45db2f,6)]=IiLpwI[s(1559)](IiLpwI[s(713)](B,8),255),_0x743ce3[IiLpwI.QkJSm(_0x3c14b9,7)]=IiLpwI[s(818)](255,B),_0x1e64cf+=8,_0x24b3b5}else{if(!!!await q[s(274)](y))if(e.jhspX(s(1573),s(1573))){let M=0,oe=[];for(;IiLpwI[s(1448)](M,_0x6d7068.byteLength);){let{offset:ze}=_0x2d71b2(_0x454a6f,M);M=ze;let Ye={cursor_name:"",cursor:0,service:0},{value:ms,offset:Oa}=IiLpwI[s(1060)](_0x2356aa,_0x57c2ea,M);Ye[s(574)]=ms,M=Oa;let{value:gs,offset:ri}=IiLpwI[s(1060)](_0x6f7643,_0x1a7631,M);M=ri,Ye[s(379)+s(391)]=IiLpwI[s(758)](_0x5ac5d8,_0x21c03e,M,M+gs),M+=gs;let{value:La,offset:ii}=IiLpwI.xwxsH(_0x290029,_0x2a324c,M);Ye[s(1491)]=La[s(1078)](),M=ii,oe[s(1730)](Ye)}return oe}else this["_dispatc"+s(1206)+s(717)](a),await q[s(1706)](y,e[s(1191)](Date.now(),S));return e[s(1732)](r)}if(R){let B=await Pl[s(976)](this);if(!B)return this["_dispatchMessage"+s(717)](a),e[s(1586)](r);let M=await B.get(C)??-1;if(e[s(299)](M,N))if(e[s(1323)]===e[s(1323)])this[s(919)+s(1206)+s(717)](a),B[s(1706)](C,N,a.message[s(574)]);else return this[s(1342)]?.[s(424)];else throw new Error(s(808)+s(1628)+s(703)+N+(s(1351)+s(231)+s(1228)+"r ")+M);return e.fkhSN(r)}return this[s(919)+s(1206)+"Event"](a),e[s(632)](r)}}async function Fm(a,r){let s=t,d=Ra[s(976)](this,a);if(!d["isQoSMes"+s(1680)])return r();let f=await Tl[s(976)](this);if(d["isAckCle"+s(954)+"age"]&&d[s(406)+"s"][s(279)])for(let p of d.ackMsgIds)await f[s(259)](p);e[s(1555)](r)}async function zm(a,r){let s=t,d={ruJsy:function(f){return e.fkhSN(f)}};if(e[s(565)](e.zmArg,e[s(1600)])){let f=this["_endpoin"+s(249)]?.[s(527)+s(1327)+"nt"]();this[s(1658)](s(730)+f),d[s(1724)](_0x482ec8)}else{let f=a[s(555)].frameType===Cm,p=e[s(1051)](a[s(555)][s(536)+"e"],Da);if(!f&&!p)return e[s(1185)](r);let y=e[s(500)](or,a.message.headers,e[s(1005)]);if(!y)return e[s(822)](r);let S=await Pl.call(this,y);if(!S)return e.fnRkZ(r);if(f){let g=await S[s(970)+"rs"](),R={frameType:g?.[s(536)+"e"],SeqID:pe.fromNumber(this[s(1363)]++),LogID:pe[s(324)+"er"](this[s(865)][s(1145)+s(1494)]()),service:9e3,method:5,headers:g?.[s(1425)],payload:g?.[s(1213)]},C=e[s(1119)](v,R);this[s(1247)]&&this._ws[s(493)+"te"]&&this._ws[s(401)](C)}if(p){let g=a[s(555)][s(1213)];g&&S[s(546)+"rs"](g)}}}let Um=async function(a,r){this._isInit=!1,clearTimeout(this._connectionTimeoutId),r()},Gm=async function(a,r){let s=t,d={HBQfY:s(1601),wiriO:function(f,p,y){return e[s(470)](f,p,y)}};if(e.vFSKq(e[s(765)],e[s(514)]))this._isMiniTT?_0x2832c2[s(610)+s(714)+s(872)](({isConnected:f})=>{let p=s;this[p(892)+p(1278)+p(692)]=f,f?this[p(812)+p(490)]():this[p(812)+p(1401)]()}):this._isMiniWX&&_0x3940df[s(610)+s(714)+"hange"](({isConnected:f})=>{let p=s;this[p(892)+"igatorOn"+p(692)]=f,f?this[p(812)+p(490)]():this["_handleO"+p(1401)]()});else{if(!this[s(1247)]||this._ws.readyState!==this[s(1528)])return e[s(1732)](r);let{pingInterval:f}=this._options;this["_endpoin"+s(249)]?.[s(1479)+"pointCon"+s(1461)]();for(let y=0;e[s(773)](y,this[s(469)+s(1056)][s(279)]);y++){let S=this[s(469)+s(1056)][y];if(e.GohvH(this[s(1247)][s(493)+"te"],this[s(1528)])&&e[s(1485)](null,S))e.YsQTD!=="WXYvA"?this[s(413)](cyVyiF.HBQfY,cyVyiF[s(1007)](_0x2659e4,s(1601),{..._0x2ee7bf})):(this[s(1247)]&&this[s(1247)][s(401)](S),this[s(469)+s(1056)][y]=null);else break}this[s(469)+s(1056)]=this["_message"+s(1056)][s(1063)](y=>!!y),this[s(1667)+s(920)+"Id"]=e[s(492)](setTimeout,()=>this[s(1426)](),f),this[s(919)+s(365)+"nt"](a),this._isBrowser&&this._ws&&(this[s(1247)].binaryType=this[s(1551)+s(986)]);let p=this[s(697)+s(249)]?.["getCurre"+s(1327)+"nt"]();this._debug(s(730)+p+s(718)),r()}},Hm=async function(a,r){let s=t,d=this._endpointManager?.[s(527)+s(1327)+"nt"]();this[s(1658)]("open "+d),e.NQClG(r)};class qm extends Aa{constructor(r){let s=t,d={yuavu:function(f,p,y){return e[z(1682)](f,p,y)},lWRwj:function(f,p,y){return e[z(460)](f,p,y)},kbOhF:function(f,p){return e[z(1522)](f,p)},VcWqr:e.AVDro,fxBVJ:function(f,p){return e[z(852)](f,p)},OAVwJ:e[s(677)],gezQG:function(f,p,y){return e[s(1593)](f,p,y)},YKUdy:e[s(1550)],IVRwZ:function(f,p,y){return e.wEroU(f,p,y)},LIDAx:function(f,p,y){return e[s(896)](f,p,y)},BxZAR:function(f,p,y){return e.WrNnN(f,p,y)},odAVQ:function(f,p,y){return e.MkFWL(f,p,y)},LCCYF:"close",mWhEt:function(f,p){return e[s(1159)](f,p)},SVxBR:function(f,p,y){return e[s(492)](f,p,y)},NpLcS:function(f,p){return e[s(863)](f,p)}};if(e[s(1143)](e.YGoND,e[s(402)])){super(),this[s(892)+s(1278)+s(692)]=!0,this[s(606)+"er"]=sr,this._isNode=sm,this._isMiniTT=Cn,this[s(392)+"X"]=ti,this._isWorker=ni,this["_message"+s(1056)]=[],this[s(697)+s(249)]=null,this[s(999)+"osed"]=!1,this[s(1551)+"ype"]=e[s(1753)],this[s(735)+s(728)]=!1,this[s(735)+"ionTimeoutId"]=null,this["_reconne"+s(1514)+s(257)]=null,this[s(1667)+s(920)+"Id"]=null,this[s(1363)]=0,this._isInit=!1,this[s(741)]="",this[s(1241)+s(834)]=null,this[s(836)+s(556)]=null,this[s(1178)+"sCounter"]=null,this._protocols=e[s(959)],this.CLOSED=3,this[s(895)+"NG"]=0,this[s(1528)]=1,this[s(461)]=2,this[s(1684)]=S=>{let g=s,R={AkwKY:function(C,N,q){return d[z(667)](C,N,q)}};if(d[g(1214)](d[g(807)],d.VcWqr))try{vl(this,S,[Um,Gm,Hm])}catch(C){if(d[g(928)](g(478),d[g(256)]))return _0x17514c.bytes[uaMGeF[g(866)](_0x4e6901,_0xcd4e99,1)];{let N=d[g(1582)](ft,d.YKUdy,{message:C.message,code:cn[g(1030)+"OR"],error:C});this[g(919)+"hErrorEv"+g(210)](N)}}else{let C=xrAbLF[g(1504)](_0x9f452b,_0x189b44,_0x1134f4[g(279)]);_0x38caa7[g(583)][g(1706)](_0x4f63f4,C)}},this[s(1136)+"ge"]=async S=>{let g=s,{pingInterval:R,pingFrequency:C}=this[g(865)];if((e.jdJqF("hi",S[g(1103)])&&e[g(1520)]("always",C)||e[g(1151)]("auto",C))&&(this[g(964)+"ngTimer"](),this[g(413)](e.JSzgL,g(433)),this[g(1667)+"gTimeoutId"]=e.pTgDl(setTimeout,this[g(1426)][g(842)](this),R)),!e[g(475)]("hi",S[g(1103)]))try{vl(this,S,[ym,wm,Fm,zm,Bm,_m])}catch(N){let q=e[g(1729)](ft,e.SavKq,{message:N[g(555)],code:cn[g(1120)+g(400)],error:N});this[g(919)+"hErrorEv"+g(210)](q)}},this._onError=S=>{let g=s,R=this["_endpoin"+g(249)]?.["checkRea"+g(832)+"es"](),C=this["_endpoin"+g(249)]?.[g(527)+g(1327)+"nt"]();if(R&&!S[g(555)]){let N=g(753)+C+(g(532)+g(1626)+g(1340)+"ed");this[g(919)+"hErrorEv"+g(210)](d[g(761)](ft,g(403),{message:N,code:cn[g(1352)+"IES_ERROR"],error:S}));return}this[g(1247)]&&d[g(1214)](this[g(1247)][g(493)+"te"],this[g(1528)])&&this[g(680)+g(649)](),this["_dispatc"+g(563)+"ent"](d[g(1723)](ft,d[g(853)],{message:S.message,code:cn.NATIVE_ERROR,error:S}))},this[s(984)]=async S=>{let g=s;this["_clearTi"+g(1255)](),this[g(964)+g(671)](),this[g(1324)+g(1620)+"rs"](),this[g(1247)]=null,this[g(735)+g(728)]=!1;let R=this["_endpoin"+g(249)]?.[g(948)+g(832)+"es"]();if(!R&&this[g(268)+g(918)]()&&!this[g(999)+g(1740)]){let C=this[g(697)+g(249)]?.["getCurre"+g(1327)+"nt"](),N=this[g(865)]["reconnec"+g(1564)+g(1647)](S[g(580)],S[g(1313)]);this[g(919)+"hCloseEv"+g(210)](d.BxZAR(bt,g(1601),{code:1006,reason:S[g(1313)]||g(744)+g(370)+"d, unkno"+g(861)+g(484)+g(276)+C,willReconnect:N})),N&&this[g(735)]();return}if(d[g(928)](1e3,S.code)&&this["_readyCl"+g(1740)]){this["_dispatc"+g(1557)+g(210)](d[g(1663)](bt,d[g(420)],{code:1e3,reason:g(1331)})),this[g(697)+g(249)]?.[g(1479)+"pointCon"+g(1461)](),this[g(1178)+"sCounter"]?.[g(221)+g(1427)]();return}if(d[g(928)](1e3,S[g(580)])&&R){let C=this[g(697)+g(249)]?.[g(527)+g(1327)+"nt"](),N=S[g(1313)];N||(N=await d[g(771)](fm,this[g(741)])),N=g(744)+"ng failed, "+N+(g(967)+"me: ")+C+(g(332)+g(931)+"ached"),this[g(919)+g(1557)+g(210)](d.odAVQ(bt,d[g(420)],{code:S[g(580)],reason:N}));let q="connect "+C+(g(532)+g(1626)+g(1340)+"ed");this[g(919)+g(563)+g(210)](d[g(288)](ft,d[g(853)],{message:q,code:cn[g(1352)+g(800)+"R"]})),this["_endpoin"+g(249)]?.[g(1479)+"pointCon"+g(1461)](),this[g(1178)+"sCounter"]?.["resetCou"+g(1427)]();return}if(d.NpLcS(1e3,S.code)&&!S[g(1313)]){let C=this[g(697)+g(249)]?.[g(527)+g(1327)+"nt"]();this[g(919)+g(1557)+g(210)](d[g(876)](bt,d[g(420)],{code:S.code,reason:g(744)+"ng failed, unkno"+g(861)+g(484)+g(276)+C})),this[g(697)+g(249)]?.[g(1479)+"pointCon"+g(1461)](),this[g(1178)+g(1579)]?.[g(221)+g(1427)]();return}this["_dispatc"+g(1557)+g(210)](S),this[g(697)+g(249)]?.[g(1479)+g(700)+"fig"](),this[g(1178)+"sCounter"]?.[g(221)+"nter"]()},this[s(1513)]=null,this[s(239)]=null,this[s(736)+"e"]=null,this[s(789)]=null,this[s(1029)+s(1218)]=null,this.onReceiveAck=null,this[s(1123)+s(991)+"yReconnect"]=null,this[s(812)+s(490)]=this[s(812)+s(490)].bind(this),this[s(812)+s(1401)]=this["_handleO"+s(1401)][s(842)](this),this[s(1227)+s(955)]=this[s(1227)+s(955)][s(842)](this),this[s(1227)+s(1713)]=this[s(1227)+"ageShow"][s(842)](this),this[s(865)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1036)](1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(737)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.oDDds,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:p}=r,y=Array[s(592)](f)?f:e[s(884)](e.TmqAA,typeof f)?[f]:[];if(!y||e[s(733)](0,y[s(279)]))throw new Error(e.TddeF);if(!cm(p))throw new Error("please p"+s(873)+"s params"+s(1084)+"ket cons"+s(418)+"is undef"+s(1033));Object.assign(this[s(865)],r),this[s(697)+s(249)]=new El(y,this[s(865)][s(877)+"es"]),this[s(1178)+"sCounter"]=new um(this[s(865)][s(618)+"Count"]),this[s(865)]["automati"+s(626)]&&(this._isInit=!0,this[s(735)]()),this._options[s(438)+"tworkCha"+s(505)]&&(this._isMiniTT||this[s(392)+"X"]?this["_onPageNetWorkCh"+s(846)]():this[s(606)+"er"]&&this["_initGlo"+s(1303)+"Listener"]())}else _0x321847.persisted&&(this["_navigat"+s(918)]()&&(!this[s(1247)]||e.HbaAr(this[s(1247)][s(493)+"te"],this[s(1528)])||e[s(1391)](this[s(1247)][s(493)+"te"],this[s(895)+"NG"]))&&this[s(812)+s(490)](),this[s(606)+"er"]&&_0xb706e2[s(465)+s(1041)](e[s(1500)],this[s(812)+s(490)]),this[s(606)+"er"]&&_0x27706e[s(465)+s(1041)](e.ZgyCS,this[s(812)+s(1401)]))}[t(812)+t(490)](){let r=t;if(e[r(559)](e.rwuue,e[r(479)])){if(this[r(865)][r(605)+r(1308)+r(739)]||this[r(999)+r(1740)])return;this[r(1396)+"econnect"]()}else _0x11c20f[r(1706)](_0xb5bdb2,_0x4c7148)}[t(812)+t(1401)](){let r=t;this[r(1614)+r(1650)+"t"]();let s=e[r(407)](Ia,e[r(1157)],{message:e.KovLe});this[r(1123)+r(991)+r(788)+"ct"]&&this["onStopImmediatel"+r(788)+"ct"](s)}[t(673)+t(1303)+t(1041)](){let r=t,s={MTuzL:function(d,f){return e[z(281)](d,f)}};if(e.WWYEH(e[r(719)],r(835))){let d=this[r(1342)][r(1097)+r(654)+"nc"](this[r(1373)]),f=_0x50d870.parse(RoKNIA[r(1576)](d,"{}"));return _0x2944a6[r(1054)](f)}else this._isBrowser&&window[r(465)+r(1041)](r(1507),this[r(812)+r(490)]),this[r(606)+"er"]&&window[r(465)+"Listener"](e.ZgyCS,this[r(812)+r(1401)]),this[r(606)+"er"]&&window[r(465)+"Listener"](e[r(922)],this[r(1227)+r(955)]),this[r(606)+"er"]&&window["addEvent"+r(1041)](e[r(414)],this[r(1227)+"ageShow"])}[t(1444)+"balEvent"+t(1041)](){let r=t;this[r(606)+"er"]&&window[r(445)+r(452)+"ner"](e[r(1500)],this[r(812)+r(490)]),this[r(606)+"er"]&&window[r(445)+r(452)+r(197)](e.ZgyCS,this[r(812)+r(1401)]),this._isBrowser&&window[r(445)+r(452)+r(197)](e.VlyDS,this[r(1227)+r(955)]),this._isBrowser&&window["removeEventListe"+r(197)](e[r(414)],this[r(1227)+r(1713)])}["_handleP"+t(955)](r){let s=t,d={EKQnU:function(f,p){return e[z(1421)](f,p)},GtMpU:e.ffzNO,MZoxx:function(f,p){return e.EdWky(f,p)},oCIDY:function(f,p){return e[z(1482)](f,p)},bNVTl:function(f,p){return e.tfkcB(f,p)},SygGz:function(f,p,y){return e[z(869)](f,p,y)}};if(e[s(1506)](e[s(644)],e[s(644)]))return QpiLvV[s(704)](typeof _0x57245f,QpiLvV[s(1043)])?QpiLvV[s(1013)](_0x23559e,_0x131c96):(QpiLvV[s(749)](_0x1cf8fd,_0x5b2048)&&QpiLvV.bNVTl(_0x254bb0,_0x4b178c),QpiLvV[s(1275)](_0x343f89,_0x2cb325,_0x154ef0())?new _0x4f49f2(_0x3aabbd,_0x127102):_0x35a7fe);!r.persisted&&(this[s(606)+"er"]&&window["removeEv"+s(452)+"ner"](e[s(922)],this[s(1227)+s(955)]),this[s(606)+"er"]&&window["removeEv"+s(452)+s(197)](e[s(414)],this._handlePageShow),this[s(1601)]()),this[s(606)+"er"]&&window["removeEv"+s(452)+s(197)](e[s(1500)],this[s(812)+s(490)]),this[s(606)+"er"]&&window[s(445)+"entListe"+s(197)](e[s(850)],this[s(812)+s(1401)])}[t(1227)+t(1713)](r){let s=t;if(e.FBewE(e[s(862)],e[s(1004)]))r[s(468)+"d"]&&(this["_navigat"+s(918)]()&&(!this[s(1247)]||e[s(1087)](this[s(1247)].readyState,this[s(1528)])||e[s(352)](this[s(1247)][s(493)+"te"],this[s(895)+"NG"]))&&this[s(812)+s(490)](),this[s(606)+"er"]&&window[s(465)+s(1041)](e.CEeHW,this[s(812)+s(490)]),this[s(606)+"er"]&&window.addEventListener(e.ZgyCS,this["_handleO"+s(1401)]));else return _0x572645[s(517)+"oreNames"]||_0x4ad1df[s(274)](_0x504a89)}async[t(1198)+t(1024)](r){let s=t,{fpID:d,deviceID:f,bddID:p,ttwID:y,accessKey:S,aID:g,customParams:R={},enableAutoAck:C,enableQoS:N,QoSLevel:q,env:B}=this[s(865)],M,oe,ze;this[s(606)+"er"]||this._isMiniWX||this[s(809)+"T"]?(M=location&&e[s(884)]("https:",location[s(894)])?e.LKxHO:e.qHszA,oe=r[s(1490)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ze=/^wss(.*:\/\/)/[s(1149)](r)?r:""+M+oe):(M=s(1616),oe=r.replace(/(^http)((?:[s]*:\/\/))/,""),ze=/(^ws)((?:[s]*:\/\/))/[s(1149)](oe)?oe:""+M+oe);let Ye=p?e.JCsdp:y?"ttwid":e[s(1554)],ms=p||y||f;if(e[s(1165)](!ms,!Ye))throw new Error(s(1761)+"rovide b"+s(599)+s(1102)+s(716));let Oa=e.ORLFq(e[s(1429)],typeof R)?await e.PRIxI(R):R,gs=B?e[s(978)](lm,B[s(1481)],B[s(1252)]):{},ri=Object.assign({device_platform:s(558),version_code:e[s(364)],access_key:S,fpid:d,aid:g,[Ye]:ms,xsack:C?1:0,xaack:C?1:0,xsqos:N?1:0,qos_level:N?q:void 0,qos_sdk_version:2,...gs},Oa),La=Object[s(1054)](ri)[s(629)]((ii,Na)=>ri[Na]!==void 0?""+ii+(ii?"&":"?")+Na+"="+ri[Na]:ii,"");return ze+s(344)+La}async _connect(){let r=t;if(e[r(559)](e[r(347)],e.MOsmX)){if(this[r(735)+"Lock"]||this["_readyCl"+r(1740)])return;this[r(735)+r(728)]=!0;try{let s=this[r(697)+"tManager"]?.[r(977)+r(331)+r(245)+"hedMaxRe"+r(399)](),{timeoutInterval:d}=this[r(865)];if(s){let p=this[r(697)+r(249)]?.[r(527)+"ntEndpoint"](),y=this[r(697)+"tManager"]?.[r(995)+r(1279)+"pointAndUpdateCo"+r(328)](),S=this[r(697)+r(249)]?.[r(527)+r(1327)+r(476)+"ount"]();if(y){let g="connect "+p+(r(409)+r(332)+r(931)+r(193)+r(297)+"backup e"+r(1668))+y+(r(1709)+"y"),R=e[r(560)](ft,e[r(1550)],{message:g,code:cn[r(1352)+r(800)+"R"]});this._debug(g),this[r(919)+"hErrorEv"+r(210)](R),this._url=await this[r(1198)+r(1024)](y),this[r(1658)]("connect "+y+" "+S+r(1572)),this[r(1324)+"sListeners"]()}else{let g=r(753)+p+(r(409)+", max re"+r(931)+r(1380));this[r(1658)](g),this[r(919)+r(563)+r(210)](e[r(357)](ft,e[r(1550)],{message:g,code:cn[r(1352)+r(800)+"R"]}));return}}else{let p=this[r(697)+r(249)]?.[r(527)+r(1327)+r(345)+r(768)](),y=this[r(697)+r(249)]?.[r(527)+r(1327)+r(476)+r(1662)]();this[r(741)]=await this[r(1198)+r(1024)](p||""),this[r(1658)](r(753)+p+" "+y+" times"),this[r(1324)+r(1620)+"rs"]()}if(this[r(1486)])this[r(1486)]=!1;else{let p=e.wEroU(Ia,e[r(1157)],{message:e[r(491)]});this[r(1029)+r(1218)]&&this[r(1029)+r(1218)](p)}let f=this["_endpoin"+r(249)]?.[r(527)+r(1327)+"ntTriesC"+r(1662)]()||0;f>1&&await this[r(1408)](f-1),this[r(1658)](r(744)+r(1111)+this[r(741)]+(r(1109)+r(1710))+this[r(784)+"ls"]),this[r(1247)]=am({url:this._url,protocols:[this._protocols],headers:this[r(865)][r(1229)+r(663)+"s"][r(307)+r(1540)]},this[r(865)].ws),(this[r(606)+"er"]||this[r(523)+"r"])&&this[r(1247)]&&(this[r(1247)][r(1390)+"pe"]=this["_binaryT"+r(986)]),this[r(1001)+r(234)](),this["_connect"+r(431)+r(992)]=setTimeout(this[r(423)+"ut"][r(842)](this),d)}catch(s){throw this[r(735)+r(728)]=!1,s}}else{for(_0x3e25b4>>>=0;e[r(633)](_0x9590d2,128);)e[r(1057)](_0x15beb0,_0x515b1a,e[r(1237)](e[r(1212)](127,_0x1122ce),128)),_0x2e2091>>>=7;e.vxMKj(_0x14f8b1,_0xc644c8,_0x32fbbd)}}[t(250)+t(1255)](){let r=t;clearTimeout(this[r(735)+"ionTimeo"+r(992)]),this["_connectionTimeo"+r(992)]=null}[t(964)+t(671)](){let r=t,s={mxVnL:function(d,f,p,y,S){return d(f,p,y,S)},DXccR:function(d,f){return e[z(1525)](d,f)},pMUaX:e[r(1215)]};e[r(566)](e[r(1417)],r(372))?(e[r(1295)](clearTimeout,this["_pingPon"+r(920)+"Id"]),e.hYTNb(clearTimeout,this["_reconne"+r(1514)+r(257)]),this[r(1667)+r(920)+"Id"]=null,this[r(1654)+r(1514)+r(257)]=null):_0xebdc9d[r(465)+r(1041)](UrFeSq[r(1659)],d=>{let f=r;UrFeSq[f(1451)](_0x208e34,_0x18e0d1(_0x2a12b3[f(637)]),d[f(1749)+"on"],d[f(921)+"on"],UrFeSq[f(1676)](_0x2c47d8,_0x476b0c["transact"+f(1499)]))})}[t(1658)](...r){let s=t;this[s(865)][s(311)]&&console[s(759)][s(1381)](console,[e[s(308)],...r])}[t(1493)+t(666)+"e"](r){let s=t,d={FBIcy:function(f,p){return e[z(573)](f,p)},wxPJq:e[s(1367)],LuTIZ:e[s(421)]};if(e.NYLkE(s(982),e[s(963)]))d[s(1374)](_0x1e4854,s(433)),this[s(961)](d[s(448)],_0xe51b00),this[s(961)](d.LuTIZ,_0x2d2182);else{let{initReconnectInterval:f,maxReconnectInterval:p,reconnectIntervalGrowFactor:y}=this[s(865)],S=e.PpzrL(f,Math.pow(y,e[s(561)](r,1)));return S>p?p:S}}_ping(){let r=t;if(this[r(1247)]&&e[r(557)](this._ws[r(493)+"te"],this.CONNECTING))if(e[r(1673)](e[r(1309)],e[r(1741)])){this["_clearPi"+r(671)](),this[r(1667)+r(920)+"Id"]=setTimeout(this[r(1426)][r(842)](this),this._options[r(1437)+r(1281)]);return}else return!!_0x54867f?.[r(619)](s=>s.key===_0x4946d5&&s[r(273)]===_0x3c61c1);if(!this[r(1247)]||e[r(1675)](this[r(1247)][r(493)+"te"],this[r(1528)]))return void this._handleReconnect();this._ws&&this[r(1247)][r(401)]("hi"),this[r(1654)+r(1514)+r(257)]=e[r(1415)](setTimeout,this[r(1396)+"econnect"+r(816)][r(842)](this),this[r(865)][r(656)+r(1220)+r(1718)])}[t(1396)+"econnectTimeout"](){let r=t;this[r(1178)+r(1579)]?.addCount(),this[r(413)](e[r(421)],e[r(1370)]),this[r(1178)+r(1579)]?.[r(948)+r(1300)+"nt"]()?this[r(1396)+r(1218)]():this._ping()}[t(268)+t(918)](){let r=t;return this[r(809)+"T"]||this._isMiniWX?this[r(892)+"igatorOn"+r(692)]:(this[r(606)+"er"]||this[r(523)+"r"])&&this[r(865)][r(438)+r(683)+r(505)]?navigator[r(1368)]:!0}["_handleR"+t(1218)](){let r=t;!this[r(268)+r(918)]()||this[r(999)+r(1740)]||(this[r(697)+r(249)]?.["resetEnd"+r(700)+"fig"](),this[r(1178)+r(1579)]?.[r(221)+"nter"](),this[r(1247)]?this["_disconn"+r(649)](1001,e[r(1301)],!0):this[r(735)]())}[t(343)+t(1549)+"ange"](){let r=t;this[r(809)+"T"]?tt["onNetwor"+r(714)+r(872)](({isConnected:s})=>{let d=r;this[d(892)+d(1278)+d(692)]=s,s?this[d(812)+d(490)]():this[d(812)+d(1401)]()}):this[r(392)+"X"]&&wx["onNetwor"+r(714)+r(872)](({isConnected:s})=>{let d=r;this["_miniNav"+d(1278)+d(692)]=s,s?this["_handleO"+d(490)]():this[d(812)+d(1401)]()})}[t(1408)](r){let s={tESwZ:function(d,f,p){return e.Omlwc(d,f,p)}};return new Promise(d=>{let f=z;s[f(929)](setTimeout,d,this["_getInte"+f(666)+"e"](r))})}[t(680)+t(649)](r=1e3,s="",d=!1){let f=t,p={IFRyq:function(y,S,g){return e.tjRvT(y,S,g)}};if(e[f(565)]("vkQrb",e[f(1632)]))xuXDdK[f(686)](_0x3560f7,_0x1a4e42,16),_0x5be921(_0x23ddf3,_0x37ee43);else{if(!this[f(1247)])return;this["_destroy"+f(1650)+"t"](r,s,d)}}[t(423)+"ut"](){let r=t,s=this._endpointManager?.["getCurre"+r(1327)+"nt"]();this._debug(r(753)+s+r(409)),this["_disconn"+r(649)](1001,"timeout,"+r(1547)+r(909)+"g",!0)}_sendAck(r){let s=t,d=e.sgIKS(Ht,r);this[s(1247)]&&e[s(1635)](this[s(1247)][s(493)+"te"],this[s(1528)])&&(this._ws&&this._ws[s(401)](d),this[s(1658)](s(1570),r))}[t(1324)+t(1620)+"rs"](){let r=t,s=e.MAHEV[r(813)]("|"),d=0;for(;;){switch(s[d++]){case"0":this._ws["removeEventListe"+r(197)](e[r(1475)],this[r(1136)+"ge"]);continue;case"1":this[r(1247)][r(445)+r(452)+r(197)](e[r(769)],this[r(1684)]);continue;case"2":this[r(1247)][r(445)+r(452)+r(197)](e[r(612)],this[r(984)]);continue;case"3":this[r(1247)][r(445)+r(452)+"ner"](e[r(1550)],this[r(253)]);continue;case"4":if(!this[r(1247)])return;continue}break}}[t(1001)+t(234)](){let r=t,s=e[r(856)][r(813)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(!this[r(1247)])return;continue;case"1":this._ws[r(465)+r(1041)](e.SvIiX,this[r(1136)+"ge"]);continue;case"2":this[r(1247)]["addEvent"+r(1041)](e[r(1550)],this[r(253)]);continue;case"3":this[r(1247)].addEventListener(e.JqjoE,this[r(984)]);continue;case"4":this[r(1247)][r(465)+"Listener"](r(897),this[r(1684)]);continue}break}}[t(389)+"nceClose"](r=1e3,s=""){let d=t;try{e[d(593)](e.dgdCu,e[d(1478)])?this[d(1247)]&&this._ws.close(r,s):(_0x4a98b+=_0x27e8af(_0x131db9),_0x4abf64+=2)}catch{}}_destroyWebSocket(r=1e3,s="",d=!1){let f=t;if(this[f(964)+f(671)](),this[f(250)+f(1255)](),this["_removeW"+f(1620)+"rs"](),this[f(389)+f(1372)](1e3,s),this[f(735)+"Lock"]=!1,d&&this[f(268)+"orOnline"]()&&!this[f(999)+"osed"]){if(this["_endpoin"+f(249)]?.[f(948)+f(832)+"es"]()){let y=this["_endpoin"+f(249)]?.[f(527)+"ntEndpoint"]();this[f(919)+f(1557)+f(210)](e[f(1518)](bt,e[f(612)],{code:1006,reason:f(753)+y+(f(409)+", max re"+f(931)+f(1380)),wasClean:!0}))}else{let y=this._options[f(1317)+"tInterce"+f(1647)](r,s);this["_dispatc"+f(1557)+"ent"](bt("close",{code:r,reason:s,wasClean:!0,willReconnect:y})),y&&this._connect()}return}this[f(268)+f(918)]()||this[f(999)+f(1740)]?this[f(919)+"hCloseEv"+f(210)](bt(e[f(612)],{code:r,reason:"bye"})):this["_dispatchCloseEv"+f(210)](bt(e[f(612)],{code:1006,reason:e[f(1232)]})),this[f(1247)]=null,this[f(697)+"tManager"]?.["resetEndpointCon"+f(1461)](),this[f(1178)+f(1579)]?.[f(221)+"nter"]()}[t(919)+t(365)+"nt"](r){let s=t;this.emit(e[s(769)],r),this[s(789)]&&this[s(789)](r)}[t(919)+"hMessage"+t(717)](r){let s=t;this[s(413)](e.SvIiX,r),this[s(736)+"e"]&&this[s(736)+"e"](r)}[t(919)+t(346)+t(270)](r){let s=t;if(e[s(356)](e[s(974)],e.EGQCP))return this[s(930)+s(1226)+s(302)+"t"]=1,this[s(1498)+"ndex"]++,this[s(803)+"s"][this[s(1498)+s(879)]];this[s(413)](e.oiOkx,r),this[s(1067)+s(1754)]&&this[s(1067)+s(1754)](r)}[t(919)+t(563)+t(210)](r){let s=t;this.emit(e.SavKq,r),this[s(239)]&&this[s(239)](r)}["_dispatc"+t(1557)+t(210)](r){let s=t;this.emit(e[s(612)],r),this[s(1513)]&&this[s(1513)](r)}get binaryType(){let r=t;return this[r(1247)]?this[r(1247)][r(1390)+"pe"]:this._binaryType}set binaryType(r){let s=t;this._binaryType=r,this._ws&&(this[s(1247)][s(1390)+"pe"]=r)}get[t(520)+"nt"](){let r=t;return this[r(697)+"tManager"]?.["getCurre"+r(1327)+r(476)+r(1662)]()||0}get bufferedAmount(){let r=t,s={FwPlY:e[r(1550)]};return this[r(469)+r(1056)].reduce((f,p)=>{let y=r;if(e[y(1467)](e[y(801)],"EVNmR"))this[y(413)](xvocGt[y(1720)],_0x17c0fe),this[y(239)]&&this[y(239)](_0x56bdf8);else return f+=p&&p[y(1195)+"th"]||0,f},0)+(this._ws?this[r(1247)].bufferedAmount:0)}get[t(277)+"ns"](){let r=t;return this[r(1247)]?this[r(1247)][r(277)+"ns"]:""}get[t(894)](){let r=t;return this[r(1247)]?this[r(1247)][r(894)]:""}get[t(493)+"te"](){let r=t;return this._ws?this[r(1247)].readyState:this[r(865)][r(322)+r(626)]?this[r(895)+"NG"]:this[r(435)]}get url(){let r=t;return this[r(1247)]?this._ws[r(988)]:this._url}[t(1601)](r=1e3,s){let d=t;if(this[d(999)+d(1740)]=!0,this[d(250)+d(1255)](),this[d(964)+"ngTimer"](),this[d(1444)+d(1303)+d(1041)](),this[d(1241)+d(834)]?.[d(1091)](),!this[d(1247)])return void this[d(1658)](d(440)+d(1656)+"ce not i"+d(1236)+"ed");if(e[d(638)](this[d(1247)][d(493)+"te"],this[d(435)])||this._ws[d(493)+"te"]===this[d(461)])return void this._debug(e[d(767)]);this._destroyWebSocket(r,s)}async[t(401)](r,s){let d=t,f={LufwN:function(ze){return e[z(695)](ze)}};if(e[d(647)](null,r))throw new Error(e[d(1287)]);e[d(317)](e[d(398)],typeof r)&&(r=JSON.stringify(r)),e[d(621)](e[d(871)],typeof r)&&!e[d(1627)](r,ArrayBuffer)&&!(r.buffer&&e[d(1482)](r.buffer,ArrayBuffer))&&(r=JSON[d(965)+"y"](r));let p=await e.xwigL(Al,r),y=e[d(1258)](dm,r),{method:S=0,service:g=this._options.service,logID:R=this[d(865)][d(1145)+"erator"](),headers:C=this[d(865)][d(1425)],payloadEncoding:N=this[d(865)][d(1172)+d(1088)],payloadType:q=this[d(865)][d(745)+d(986)],logIDNew:B=this._options[d(1535)+d(1268)]["enableAutoGenera"+d(198)+"ew"]?e.UCNGG(i,this[d(865)]["logIDNew"+d(1268)][d(1037)]):""}=e[d(726)](s,{});if(!g)throw new Error(e[d(1590)]);let M={SeqID:pe.fromNumber(this[d(1363)]++),LogID:pe[d(324)+"er"](R),service:g,method:S,headers:C,payloadEncoding:e[d(1070)](N,Object)?N[d(260)]?N[d(260)]:"":N,payloadType:e[d(1482)](q,Object)?q.type?q[d(778)]:y:q||y,payload:p,LogIDNew:B},oe=Ht(M);if(this._ws&&e[d(335)](this[d(1247)][d(493)+"te"],this.OPEN)){if(e.ljxer(d(243),"vKiIS"))return!!this[d(1342)];this._ws&&this[d(1247)][d(401)](oe),this[d(1658)](e[d(238)],M)}else e[d(1387)](this[d(469)+d(1056)][d(279)],this[d(865)][d(578)+d(1126)+d(207)])?e.psevs(d(1664),e[d(854)])?(this[d(469)+d(1056)][d(1730)](oe),this[d(1658)]("enqueue",M)):(this[d(1486)]=!1,_0x299c93(this[d(735)+d(431)+d(992)]),TNvPvj[d(923)](_0x13fc47)):(this[d(469)+d(1056)].shift(),this[d(469)+d(1056)].push(oe));return{seqID:this._seqId,logID:R,logIDNew:B}}async[t(1317)+"t"](r){let s=t,{url:d}=e.QmgmE(r,{}),f=Array.isArray(d)?d:e[s(884)](e[s(871)],typeof d)?[d]:[];r&&Object.assign(this._options,r),f&&f[s(279)]?this[s(697)+s(249)]=new El(f,this._options[s(877)+"es"]):this[s(697)+"tManager"]?.["resetEndpointCon"+s(1461)](),this[s(1178)+s(1579)]?.[s(221)+"nter"](this[s(865)][s(618)+s(734)]),this[s(999)+s(1740)]=!1,this._ws&&this._ws[s(493)+"te"]!==this[s(435)]?this[s(680)+s(649)](1e3,e.zsXjc,!0):e[s(422)](e[s(367)],e[s(1330)])?this[s(1342)]?.[s(259)](_0x1886b9[s(1104)+"id"]):(this[s(1486)]=!0,this[s(735)]())}async[t(1678)](){let r=t;if(e[r(381)]===e[r(1430)])_0x1fb773=e.hwOgx(_0x30dc88,_0x52040d),_0x557523=e[r(396)](127,_0x20b29b),128&_0x38b060&&(_0x494f88=e[r(353)](_0xa2988c,_0x238f90),_0x29f9cd|=e[r(1314)](127,_0x33ed35)<<7);else if(!this[r(735)+r(728)])if(e.oyblV(e[r(653)],e[r(653)])){let s="0|2|3|4|1".split("|"),d=0;for(;;){switch(s[d++]){case"0":this[r(697)+r(249)]?.[r(1479)+"pointCon"+r(1461)]();continue;case"1":this[r(735)]();continue;case"2":this[r(1178)+r(1579)]?.resetCounter();continue;case"3":this[r(999)+r(1740)]=!1;continue;case"4":this[r(1486)]=!0;continue}break}}else return _0x4d98da.log(e[r(330)],_0x121d66,_0x40c9dc,_0x3559f7),this[r(1342)][r(1706)]({cursor_name:_0x48e420,cursor:_0x2b5e42,service:_0x4bfc78})}addEventListener(r,s){let d=t;if(e[d(675)]===e[d(384)])return new _0x1c6b38(_0xd34ea5,{message:_0x4de245,code:_0x162531,error:_0x2cdeb7});this.on(r,s)}[t(1333)+t(717)](r){let{type:s}=r;this.emit(s,r)}[t(445)+t(452)+t(197)](r,s){this[t(961)](r,s)}pingOnce(){let r=t,s={jGydL:function(d,f){return e[z(679)](d,f)},JOyMD:e.YJDEZ,jbdZX:e[r(421)],lHZlx:function(d,f,p){return e[r(1541)](d,f,p)}};if(e[r(1391)](e[r(1536)],r(412)))!this[r(735)+"Lock"]&&(this["_endpoin"+r(249)]?.[r(1479)+r(700)+"fig"](),this["_pingLos"+r(1579)]?.[r(221)+r(1427)](),this[r(999)+r(1740)]=!1,this[r(1486)]=!0,this[r(735)]());else return new Promise((d,f)=>{let p=r,y={hGZcL:function(R,C){return s[z(333)](R,C)},YObad:s[p(1003)],clSnm:p(1154)+p(1666)+"s",QwJuh:s[p(1219)],fbzVW:p(436)};this[p(964)+p(671)](),this[p(1667)+p(920)+"Id"]=s[p(366)](setTimeout,this[p(1426)][p(842)](this),this._options.pingInterval);let S=()=>{let R=p;y.hGZcL(d,y[R(533)]),this[R(961)](y[R(899)],S),this[R(961)](y[R(483)],g)},g=()=>{let R=p;y[R(355)](f,y.fbzVW),this[R(961)](y.clSnm,S),this[R(961)](y[R(483)],g)};this.on("ping_onc"+p(1666)+"s",S),this.on(s[p(1219)],g),this[p(1426)]()})}}})(),Fe[F(1416)+F(1131)]=De[F(1416)+F(1131)],Fe[F(1562)+F(524)]=De[F(1562)+"rorEvent"],Fe[F(1305)+"e"]=De.ErrorCode,Fe[F(717)]=De[F(717)],Fe.FWS=De[F(195)],Fe[F(1345)+F(624)+"vent"]=De["Frontier"+F(624)+F(1156)],Fe[F(624)+F(1156)]=De[F(624)+"vent"],Fe[F(261)+"t"]=De[F(261)+"t"],Fe[F(1734)+"tEvent"]=De[F(1734)+F(443)],Fe[F(902)+"oseEvent"]=De[F(902)+F(1131)],Fe["createEr"+F(524)]=De[F(408)+F(524)],Fe[F(509)+F(1422)+"nt"]=De[F(509)+F(1422)+"nt"],Fe[F(1438)+F(1581)]=De[F(1438)+F(1581)],Fe[F(949)+F(1457)+F(1156)]=De[F(949)+F(1457)+"vent"],Fe.decodedFrame=De[F(1012)+F(602)],Fe[F(292)+F(391)]=De[F(292)+F(391)];for(na in De)[F(1416)+F(1131),"CustomEr"+F(524),"ErrorCode",F(717),F(195),F(1345)+F(624)+F(1156),"MessageE"+F(1156),F(261)+"t",F(1734)+F(443),F(902)+F(1131),F(408)+F(524),"createMe"+F(1422)+"nt",F(1438)+F(1581),F(949)+F(1457)+F(1156),"decodedF"+F(602),F(292)+F(391)][F(1622)](na)===-1&&(Fe[na]=De[na]);var na;Object[F(1137)+"operty"](Fe,F(855)+"le",{value:!0})});import{existsSync as c1,openSync as d1}from"node:fs";import{mkdir as l1}from"node:fs/promises";import{dirname as u1}from"node:path";import{fileURLToPath as f1}from"node:url";function x1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function el(t=Y()){return c1(t.libEntry)?t.libEntry:f1(new URL("../index.ts",import.meta.url))}async function mp(t={}){let e=t.paths??Y(),n=t.entryOverride??el(e),i=x1(e,process.env.COZE_BRIDGE_LOG_MODE);await l1(u1(i),{recursive:!0});let o=d1(i,"a"),l=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=at(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[us]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return h1.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var h1,us,ha=it(()=>{"use strict";Xt();ne();Pe();h1=K("spawn-daemon"),us="COZE_BRIDGE_DAEMON"});import{spawn as uI}from"node:child_process";import{mkdir as fI,unlink as hI,writeFile as xI}from"node:fs/promises";import{dirname as pI,join as mI}from"node:path";function Xr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function gI(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${Xr(n)}</key>
21
- <string>${Xr(i)}</string>`).join(`
20
+ `+r)}function rr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,rr),t.emit("wsClientError",d,r,e)}else os(r,i,o,c)}});var ip=ae(Me=>{"use strict";var N=H;(function(t,e){let r=H,i=t();for(;;)try{if(parseInt(r(1703))/1+-parseInt(r(538))/2*(parseInt(r(1791))/3)+parseInt(r(1048))/4+parseInt(r(1428))/5*(-parseInt(r(337))/6)+-parseInt(r(1063))/7+parseInt(r(1850))/8+parseInt(r(1743))/9*(parseInt(r(500))/10)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(oa,929423);var JS=Object[N(1566)+"operty"],ZS=Object["getOwnPr"+N(1621)+N(1433)],Qx=(t,e)=>function(){return t&&(e=(0,t[{vOyfk:function(o,c){return o(c)}}.vOyfk(ZS,t)[0]])(t=0)),e},XS=(t,e)=>{let r=N,i={GTIsh:function(c,d,u,h){return c(d,u,h)}};for(var o in e)i[r(1401)](JS,t,o,{get:e[o],enumerable:!0})};function YS(){return Vx||(Vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function QS(){let t=N;return Jx||(Jx=[IDBCursor[t(1157)+"e"][t(1826)],IDBCursor[t(1157)+"e"][t(1272)],IDBCursor[t(1157)+"e"]["continue"+t(1655)+"ey"]])}function e1(t){let e=N,r={SXQEv:function(o,c){return o&c},BtDFr:function(o,c){return o===c},hwgqu:"OTmkP",OZKKu:"IUBLf",BFsfu:e(787),jcDcS:e(1298),DCrrM:function(o,c){return o(c)},DKjdB:function(o){return o()},TsaBn:e(1854),UBRPp:function(o,c){return o===c},CJuEG:e(1135),JEyRw:e(1132)},i=new Promise((o,c)=>{let d=e,u={DLzQv:function(w){return r[H(1405)](w)}},h=()=>{let w=H,v={eToma:function(_,E){return _|E},JDAYQ:function(_,E){return r[H(1558)](_,E)},NJqno:function(_,E){return _>>E},ihpYM:function(_,E){return _|E}};r.BtDFr(r[w(1755)],r.OZKKu)?(_0x5e8065[_0x1d02c2++]=v.eToma(_0x5c2395>>12,224),_0xc02e9f[_0xc1e6ef++]=v[w(1344)](v[w(889)](v[w(1584)](_0x26fa0e,6),63),128),_0x1ab4f9[_0x112caf++]=v[w(679)](v[w(889)](63,_0x3ffc4c),128)):(t[w(1449)+"entListe"+w(434)](r[w(948)],x),t[w(1449)+"entListener"](r[w(495)],m))},x=()=>{let w=H;o(Ht(t[w(891)])),u[w(721)](h)},m=()=>{let w=H;r[w(1251)](c,t[w(1298)]),h()};t[d(1803)+"Listener"](r.BFsfu,x),t["addEvent"+d(1262)](r[d(495)],m)});return i[e(1323)](o=>{let c=e,d={NyMzS:r[c(1154)],hDyfm:r[c(495)],YmAPh:c(1771),cSbYc:c(623)};if(r[c(1752)](r[c(683)],r.JEyRw)){let u=(c(420)+"2")[c(1317)]("|"),h=0;for(;;){switch(u[h++]){case"0":if(!this[c(975)])return;continue;case"1":this[c(975)].addEventListener(d[c(960)],this[c(1839)]);continue;case"2":this[c(975)][c(1803)+"Listener"](d.hDyfm,this[c(1544)]);continue;case"3":this[c(975)].addEventListener(d[c(438)],this._onOpen);continue;case"4":this._ws["addEvent"+c(1262)](d[c(1557)],this[c(577)+"ge"]);continue}break}}else o instanceof IDBCursor&&Xd[c(1487)](o,t)})[e(1696)](()=>{}),ia[e(1487)](i,t),i}function t1(t){let e=N,r={EsbQI:e(1552),CQJoG:e(1598),NLaeu:function(o){return o()},IioGe:function(o,c){return o!==c},iDDnj:function(o,c){return o(c)},JzJyp:e(705)+"or",pvTVA:"error"};if(ra[e(1506)](t))return;let i=new Promise((o,c)=>{let d=e,u={bHeVy:r.EsbQI,lJili:r[d(854)],LvPtw:function(w){return w()},dfsBc:function(w){return r.NLaeu(w)},fLsbB:function(w,v){return r.IioGe(w,v)},phvaZ:"QxmPs",QTXbU:function(w,v){return r[d(794)](w,v)},XZasq:r[d(1143)],JYiyj:function(w){return w()}},h=()=>{let w=d;t[w(1449)+w(442)+w(434)](u[w(1184)],x),t.removeEventListener(w(1298),m),t["removeEv"+w(442)+w(434)](u[w(950)],m)},x=()=>{let w=d;u[w(1617)](o),u[w(1509)](h)},m=()=>{let w=d;if(u[w(1218)](u[w(526)],u.phvaZ))return this[w(975)]?this[w(975)].extensions:"";u.QTXbU(c,t[w(1298)]||new DOMException(w(705)+"or",u.XZasq)),u[w(691)](h)};t[d(1803)+d(1262)](r[d(1130)],x),t[d(1803)+d(1262)](r.pvTVA,m),t[d(1803)+d(1262)](r[d(854)],m)});ra[e(1487)](t,i)}function n1(t){sa={eHGlv:function(i,o){return i(o)}}[N(1171)](t,sa)}function r1(t){let e=N,r={MrXRr:function(i,o){return i(o)},IwqDB:function(i,o){return i(o)},ltKXg:function(i,o){return i(o)},rCIcS:function(i,o){return i===o},QzHrb:function(i,o){return i in o},yJIKq:e(1305)+e(1727),dfTFr:e(440),NWGvh:function(i){return i()}};if(r.rCIcS(t,IDBDatabase[e(1157)+"e"].transaction)&&!r[e(1760)](r[e(607)],IDBTransaction.prototype))if(r.dfTFr!==e(440))this[e(1512)]=!0,this[e(1205)]();else return function(i,...o){let c=e,d=t[c(1398)](r.MrXRr(as,this),i,...o);return Zd[c(1487)](d,i[c(652)]?i[c(652)]():[i]),r[c(700)](Ht,d)};return r[e(767)](QS)[e(1459)](t)?function(...i){let o=e;return t[o(728)](r[o(1762)](as,this),i),r.ltKXg(Ht,Xd[o(1519)](this))}:function(...i){let o=e;return r[o(1582)](Ht,t[o(728)](as(this),i))}}function i1(t){let e=N,r={ZDCJs:e(1360),tpuOT:function(i,o){return i instanceof o},hMAsH:function(i,o){return i(o)},RXTkf:function(i,o,c){return i(o,c)},FwREG:function(i){return i()}};return typeof t===r[e(1520)]?r1(t):(r.tpuOT(t,IDBTransaction)&&r.hMAsH(t1,t),r[e(1314)](ep,t,r[e(481)](YS))?new Proxy(t,sa):t)}function Ht(t){let e=N,r={LbQmd:function(o,c,d){return o(c,d)},GuidK:function(o,c){return o instanceof c},pQASR:function(o,c){return o(c)},ZrsTZ:function(o,c){return o(c)},TWIPu:function(o,c){return o!==c},AkEkN:function(o,c){return o!==c},sAfLp:e(1037),hKoAk:e(369)};if(r[e(925)](t,IDBRequest))return r.pQASR(e1,t);if(ta[e(1506)](t))return ta[e(1519)](t);let i=r[e(1118)](i1,t);if(r[e(1378)](i,t))if(r[e(907)](r[e(1068)],r[e(996)]))ta.set(t,i),ia[e(1487)](i,t);else return _0x4dff80.bytes[r[e(1533)](_0x41333d,_0x449cb7,1)];return i}var ep,Vx,Jx,Xd,ra,Zd,ta,ia,sa,as,Zx=Qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={VSyUA:function(r,i){return r(i)},EtzHH:function(r,i){return r instanceof i},KQWTk:function(r,i){return r===i},AtkEf:t(1837),OjevV:"done",UmSQd:function(r,i){return r===i},QNawT:"objectStoreNames",KaTRP:t(436),PqbRG:function(r,i){return r===i},mkZgd:function(r,i){return r instanceof i},ZKDXZ:function(r,i){return r===i},klagK:function(r,i){return r===i},bBiKS:t(847),IJAOJ:function(r,i){return r in i}};ep=(r,i)=>i[t(764)](o=>r instanceof o),Xd=new WeakMap,ra=new WeakMap,Zd=new WeakMap,ta=new WeakMap,ia=new WeakMap,sa={get(r,i,o){let c=t,d={YPjDE:function(u,h){return e[H(690)](u,h)}};if(e.EtzHH(r,IDBTransaction))if(e[c(1001)](e[c(786)],e[c(786)])){if(e[c(1001)](i,e[c(1180)]))return ra[c(1519)](r);if(e.UmSQd(i,e[c(1451)])){if(c(1511)!==e[c(587)])return r[c(1305)+c(1727)]||Zd[c(1519)](r);d[c(901)](_0x47dfcd,this[c(1588)+c(1099)+"Id"]),_0x31d14b(this[c(1188)+c(1820)+"tId"]),this[c(1588)+c(1099)+"Id"]=null,this[c(1188)+c(1820)+c(678)]=null}if(e[c(1603)](i,"store"))return o[c(1305)+c(1727)][1]?void 0:o[c(1305)+"ore"](o[c(1305)+c(1727)][0])}else return this[c(928)]?.set({message_id:_0x7a30f,timestamp:_0x35bf14});return e.VSyUA(Ht,r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e.mkZgd(r,IDBTransaction)&&(e[o(1394)](i,e[o(1180)])||e[o(639)](i,e[o(544)]))?!0:e[o(750)](i,r)}},as=r=>ia[t(1519)](r)}}),tp={};XS(tp,{deleteDB:()=>o1,openDB:()=>s1,unwrap:()=>as,wrap:()=>Ht});function s1(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=N,u={ZfCQg:function(m,w){return m!==w},SaXio:d(1565),Queul:function(m,w,v,_,E){return m(w,v,_,E)},JYKlU:function(m,w){return m(w)},BoxkL:"versionc"+d(1126),BXIZx:d(947)+"eeded",uhfxX:d(393)},h=indexedDB[d(1771)](t,e),x=u[d(1829)](Ht,h);return i&&h[d(1803)+d(1262)](u[d(1792)],m=>{let w=d;if(u[w(555)](u[w(1467)],u[w(1467)])){let v=_0x144ed2[w(623)].payload;v&&_0x1be9d4[w(1176)+"rs"](v)}else u.Queul(i,u[w(1829)](Ht,h[w(891)]),m.oldVersion,m[w(1150)+"on"],u[w(1829)](Ht,h[w(973)+w(594)]))}),r&&h[d(1803)+"Listener"](u.uhfxX,()=>r()),x.then(m=>{let w=d;c&&m[w(1803)+w(1262)](w(1854),()=>c()),o&&m[w(1803)+w(1262)](u[w(372)],()=>o())})[d(1696)](()=>{}),x}function o1(t,{blocked:e}={}){let r=N,i={iTHXW:r(393),NZvWn:function(c,d){return c(d)}},o=indexedDB[r(768)+r(944)](t);return e&&o[r(1803)+r(1262)](i.iTHXW,()=>e()),i[r(823)](Ht,o)[r(1323)](()=>{})}function Xx(t,e){let r=N,i={LTzXY:"readwrite",QRZEK:function(h,x){return h instanceof x},FLeDK:r(884),yADTT:function(h,x){return h!==x},snGvV:function(h,x){return h in x}};if(!(i[r(1518)](t,IDBDatabase)&&!(e in t)&&typeof e===i.FLeDK))return;if(na[r(1519)](e))return na.get(e);let o=e[r(795)](/FromIndex$/,""),c=i[r(1475)](e,o),d=rp.includes(o);if(!i[r(1465)](o,(c?IDBIndex:IDBObjectStore).prototype)||!(d||np.includes(o)))return;let u=async function(h,...x){let m=r,w=this[m(973)+"ion"](h,d?i[m(1628)]:m(933)),v=w.store;return c&&(v=v[m(1231)](x[m(924)]())),(await Promise[m(449)]([v[o](...x),d&&w.done]))[0]};return na[r(1487)](e,u),u}var np,rp,na,a1=Qx({"node_modules/idb/build/index.js"(){let t=N,e={aorcg:"get",ujVpp:"getKey",DgYID:t(498),jOnWI:t(472),pQAHW:t(844),uOSpK:function(r,i){return r(i)}};Zx(),Zx(),np=[e[t(491)],e[t(401)],e[t(737)],t(1252)+"ys",e[t(1537)]],rp=["put",e[t(942)],"delete",t(650)],na=new Map,e[t(582)](n1,r=>({...r,get:(i,o,c)=>Xx(i,o)||r[t(1519)](i,o,c),has:(i,o)=>!!Xx(i,o)||r.has(i,o)}))}}),c1={idb:function(t){let e=N;t.exports=Promise[e(1488)]()[e(1323)](()=>(a1(),tp)).then(function(r){return r})}},Yx={};function Ut(t){let e=N,r={uOSDF:e(1541)+"0",oAWwN:function(u,h){return u!==h}},i=r.uOSDF[e(1317)]("|"),o=0;for(;;){switch(i[o++]){case"0":return d[e(1329)];case"1":var c=Yx[t];continue;case"2":var d=Yx[t]={exports:{}};continue;case"3":c1[t](d,d[e(1329)],Ut);continue;case"4":if(r[e(702)](void 0,c))return c.exports;continue}break}}Ut.d=(t,e)=>{let r=H;for(var i in e)Ut.o(e,i)&&!Ut.o(t,i)&&Object["definePr"+r(970)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Ut.o=(e,r)=>Object.prototype[t(881)+t(970)][t(1398)](e,r)})(),(()=>{let t=N,e={CZvab:function(r,i){return r===i},GcHTD:t(1360),MRlPT:function(r,i){return r(i)},XeiLX:function(r,i){return r instanceof i},uOxiz:function(r,i,o){return r(i,o)},kuZfE:function(r){return r()},ZywBJ:t(581),MsvGd:t(1490),goROE:t(1302)+"d",CpJJK:t(1834),MzrUC:t(1326)+"le"};Ut.r=r=>{let i=t;if(e[i(399)](e[i(375)],e[i(642)]))return IpVOuz[i(399)](typeof _0x49152c,IpVOuz.GcHTD)?IpVOuz[i(1632)](_0x2160d5,_0x268ec5):(IpVOuz[i(482)](_0x324048,_0x21ec60)&&IpVOuz[i(1632)](_0x539bd1,_0x31fc4f),IpVOuz.uOxiz(_0x5e96a9,_0x1caba7,IpVOuz[i(1529)](_0x1532c7))?new _0x3bf3b4(_0x458731,_0x3a29e7):_0x5350c9);e.goROE!=typeof Symbol&&Symbol[i(560)+i(713)]&&Object[i(1566)+i(970)](r,Symbol["toString"+i(713)],{value:e[i(1294)]}),Object[i(1566)+i(970)](r,e.MzrUC,{value:!0})}})();function H(t,e){t=t-321;let r=oa(),i=r[t];if(H.lPoAjV===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let v=0,_,E,S=0;E=h.charAt(S++);~E&&(_=v%4?_*64+E:E,v++%4)?m+=String.fromCharCode(255&_>>(-2*v&6)):0)E=x.indexOf(E);for(let v=0,_=m.length;v<_;v++)w+="%"+("00"+m.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(w)};H.GXmyss=o,H.RGiowA={},H.lPoAjV=!0}let c=r[0],d=t+c,u=H.RGiowA[d];return u?i=u:(i=H.GXmyss(i),H.RGiowA[d]=i),i}var Re={};(()=>{let t=N,e={YElaR:function(a,n){return a+n},aKrbt:function(a,n){return a+n},xehFD:function(a,n){return a+n},HenWQ:function(a,n){return a(n)},fjVHL:function(a,n,s){return a(n,s)},djjMv:function(a,n){return a>>n},GNERA:function(a,n){return a>=n},qUfPJ:function(a,n){return a===n},pryiI:t(1622),QXvVF:t(403),dPZpZ:function(a,n){return a+n},lYrTy:t(1246),kdROD:t(1605),dkCwL:t(338),rUFip:function(a,n){return a!==n},DPBkh:t(1196),snScx:t(1478)+"00000000"+t(1478)+t(1478),kUzyV:t(1415)+t(1723)+t(518)+t(1042)+t(1794),bFiTg:function(a,n){return a>n},hAqvf:function(a,n){return a<n},LyYHU:function(a,n){return a<n},myfIR:function(a,n){return a!==n},VyVmE:function(a,n){return a-n},GLIFp:function(a,n){return a!==n},JpeHB:function(a,n){return a<n},EoUzO:t(1645),OdUSw:"gdDbz",vBbox:function(a,n){return a!==n},rpleJ:t(665),iwdJE:function(a,n,s){return a(n,s)},edPHg:function(a,n,s){return a(n,s)},wTjRW:function(a,n,s){return a(n,s)},QkrcJ:function(a,n){return a&n},bZQan:t(852)+t(340)+" field: "+t(412),IpbPX:function(a,n){return a<n},nYeaC:function(a,n){return a>n},IMfjB:function(a,n){return a|n},jwfqL:function(a,n){return a===n},dRFJL:t(1010),aWYZa:"GfVcj",DwJCK:function(a){return a()},UowLN:function(a,n){return a(n)},ieiPz:function(a,n){return a==n},bvvas:"text/plain;chars"+t(1782),auGAP:t(1686)+t(754),wUzzB:function(a,n){return a*n},hFvGj:t(917),oQVYc:t(1217),UDBMw:function(a,n,s){return a(n,s)},cBvUk:function(a,n){return a!==n},LSblA:function(a,n,s){return a(n,s)},RSGZT:function(a,n,s){return a(n,s)},xQtvM:function(a,n){return a(n)},PFigN:function(a,n){return a!==n},LAaTP:function(a,n){return a===n},bxcmc:t(810),rpjqD:t(1456),iNMMN:function(a,n){return a(n)},boInv:function(a,n){return a!==n},tpMZH:t(1618),fjoHg:t(1731),kEdcz:function(a){return a()},cBwuL:function(a,n,s){return a(n,s)},iaBaf:function(a,n){return a!==n},RMteQ:function(a,n){return a!==n},EMTxN:function(a,n,s){return a(n,s)},ruuVA:function(a,n,s){return a(n,s)},sKqnV:function(a,n){return a!==n},kDjEW:function(a,n){return a!==n},uGPSU:t(632),SNDmO:function(a,n,s){return a(n,s)},GYsRb:function(a,n,s){return a(n,s)},BmAYh:function(a,n){return a<n},GGBSV:function(a,n){return a|n},TFUaU:function(a,n){return a!==n},ONEGZ:t(1108),eiKUm:t(1074),BXZJk:function(a,n){return a(n)},MSNky:function(a,n,s){return a(n,s)},YLpdC:function(a,n){return a(n)},OFfii:function(a,n){return a(n)},NYvmV:function(a,n,s){return a(n,s)},wPqZx:function(a,n){return a(n)},fcwHq:function(a,n,s){return a(n,s)},yWYFW:function(a,n){return a(n)},uAvBM:function(a,n,s){return a(n,s)},KnYCW:t(852)+"required"+t(1473)+"SeqID",aJnQs:function(a,n){return a===n},AjBSe:t(852)+t(340)+t(1473)+t(421),FZSHl:function(a,n){return a===n},rmZke:t(852)+t(340)+t(1473)+t(1264),vwTTg:function(a,n){return a&n},ZdHUF:function(a,n,s){return a(n,s)},CRgof:function(a,n){return a+n},lvvrs:t(1606)+t(1256),GkKDt:function(a,n){return a>=n},qvcWc:function(a,n){return a>n},EQPQJ:function(a,n){return a+n},RRBRn:t(1232)+t(1256),tbaSR:function(a,n,s){return a(n,s)},AqBFX:t(1854),dkLxi:function(a,n){return a===n},YDVFS:function(a,n){return a&n},WKjRM:function(a,n){return a===n},JmmXS:function(a,n){return a&n},etedy:function(a,n){return a+n},ywXib:function(a,n){return a&n},lHVve:function(a,n){return a<<n},DzXSz:function(a,n){return a&n},ZcMgh:function(a,n){return a&n},oypxS:function(a,n){return a+n},vqmFG:function(a,n){return a+n},hXiPS:function(a,n){return a+n},eHykB:function(a,n){return a+n},RqdrI:function(a,n){return a!==n},tEdcG:function(a,n){return a&n},kowAZ:function(a,n){return a|n},VfTin:function(a,n){return a<<n},NJiEG:function(a,n){return a&n},UEzqK:function(a,n){return a>=n},dOarj:function(a,n){return a<=n},rierQ:function(a,n){return a(n)},MBBHL:function(a,n){return a==n},WMBye:function(a,n){return a>=n},TXZzG:function(a,n){return a+n},dHtwQ:function(a,n){return a+n},cLAFt:function(a,n){return a+n},hhwkP:function(a,n){return a|n},rWNLl:function(a,n){return a<<n},qgdja:"kXLpJ",zdbxW:function(a,n){return a|n},nlCrf:function(a,n){return a<<n},Zquuh:function(a,n){return a&n},SinHa:function(a,n){return a&n},hsZET:function(a,n){return a<<n},wRAQZ:function(a,n){return a&n},aGKEW:function(a,n){return a<n},qKAzW:function(a,n){return a&n},tPzIO:function(a,n){return a<n},lBfDM:function(a,n){return a<=n},SyfoG:function(a,n){return a<n},TXomv:function(a,n){return a+n},hHlXY:function(a,n){return a<n},chaBY:function(a,n,s){return a(n,s)},Qrvqu:function(a,n,s){return a(n,s)},JbrBa:function(a,n){return a<n},YPEtw:function(a,n){return a+n},BERXX:function(a,n){return a<<n},waWIV:function(a,n){return a&n},zGDHQ:function(a,n){return a>>n},razEy:function(a,n){return a>>n},wyxbW:function(a,n){return a>>n},upVRa:function(a,n){return a<n},vOAjI:t(1437),KCecC:t(1849),wZbnP:function(a,n){return a===n},ncQVF:"oynrz",ukFkw:function(a,n){return a<n},boTJX:function(a,n){return a&n},IErPE:function(a,n){return a&n},fMaQo:function(a,n){return a>=n},foLvg:function(a,n){return a(n)},zAhOK:function(a,n){return a===n},Ipfzw:t(837),bPmPe:function(a,n){return a(n)},uAPEt:function(a,n){return a&n},EMkff:function(a,n){return a&n},jMmOp:function(a,n){return a&n},mBCHD:function(a,n){return a(n)},GQNqH:function(a,n){return a&n},TDrDV:function(a,n){return a<<n},UyjCT:function(a,n){return a&n},UzWsl:function(a,n){return a&n},joqIl:function(a,n){return a(n)},NiSRo:function(a,n){return a&n},fSJJt:function(a,n){return a&n},zzOQf:function(a,n){return a(n)},LdVvL:function(a,n){return a<<n},YmmTq:function(a,n){return a|n},bBthj:function(a,n){return a<<n},ycJHk:function(a,n){return a>>>n},QymjU:function(a,n){return a<<n},oArcE:function(a,n){return a===n},pCgUQ:t(1608),ZiXTI:function(a,n){return a>>>n},hcUcv:function(a,n){return a===n},XCqpB:function(a,n){return a<n},drZIX:function(a,n){return a<n},gvSta:function(a,n){return a&n},XdvGg:function(a,n){return a!==n},XcWPq:function(a,n){return a+n},LoSiP:function(a,n){return a!==n},oddId:function(a,n){return a|n},oSzEF:function(a,n){return a>>>n},hOqqE:function(a,n){return a+n},vrLAG:function(a,n){return a>>>n},CYHpA:function(a,n){return a+n},GGTyc:function(a,n){return a>>>n},kxEru:function(a,n){return a|n},NvJhp:function(a,n){return a!==n},eXWwJ:function(a,n){return a|n},fsEQW:function(a,n){return a>>>n},mUqUQ:function(a,n){return a+n},eBpZy:function(a,n){return a&n},sLBky:function(a,n){return a>>>n},nVmEg:function(a,n){return a+n},DQrYn:function(a,n){return a|n},YpVco:function(a,n){return a!==n},CgtoV:function(a,n){return a&n},loOgO:t(1614),DJyWH:"TNmNr",fVYHq:function(a,n){return a(n)},ffNQA:"qMjKq",BqZRA:t(687),QuRjG:function(a,n){return a|n},wIIgw:function(a,n){return a<<n},qKTPd:function(a,n){return a|n},AcgVY:function(a,n){return a|n},nCyIM:function(a,n){return a|n},aSAhk:function(a,n){return a<<n},RWFpZ:function(a,n){return a>>>n},hwSSO:function(a,n){return a|n},qLVRV:function(a,n){return a|n},kZypW:function(a,n){return a<<n},epNHw:function(a,n){return a<<n},QxIIH:function(a,n){return a<<n},agzZo:function(a,n){return a&n},pZTpa:function(a,n){return a&n},JRNMS:function(a,n){return a>>>n},szvId:function(a,n){return a&n},ddQRa:function(a,n){return a>>>n},RNIDJ:function(a,n){return a>>>n},dNXZT:function(a,n){return a>=n},ydMIg:function(a,n){return a<=n},SZEJX:function(a,n){return a>=n},KkcLO:function(a,n){return a+n},ChcBU:function(a,n){return a|n},DUTRD:function(a,n){return a|n},grool:function(a,n){return a/n},EEtoV:function(a,n){return a+n},yUXqM:function(a,n){return a>>>n},QSerl:function(a,n){return a+n},vjCkX:function(a,n){return a*n},WEXqy:function(a,n){return a>>>n},mHhGc:function(a,n){return a===n},FLtBk:function(a,n){return a&n},eyRin:function(a,n){return a+n},UUYtx:function(a,n){return a+n},jGjVq:function(a,n){return a===n},cJnYj:function(a,n){return a>>>n},lhaQQ:function(a,n){return a===n},laMiX:function(a,n){return a instanceof n},DiEtb:t(1197),aBiOX:t(817),fWbDZ:function(a,n){return a===n},MVmMs:function(a,n){return a+n},oTrJK:function(a,n){return a+n},BTEIx:function(a,n){return a&n},FwRXD:function(a,n){return a>>>n},HNoyU:function(a,n){return a&n},eWtdy:function(a,n){return a>>>n},xXnRm:function(a,n){return a>>>n},poEAI:function(a,n){return a>>>n},vaHvM:function(a,n){return a>>>n},KoPbC:function(a,n){return a&n},WvbEd:function(a,n){return a>>>n},PAwCc:t(1170)+t(465),ZSRoF:t(1583)+t(1066)+"R",GbwJq:t(1283)+"OR",zkfzT:t(1447)+t(329),cXGEG:"NATIVE_E"+t(893),UARYO:function(a,n){return a===n},xsHRk:"jOINZ",REqEV:function(a,n){return a!==n},kyvjV:t(1057),zFsOn:function(a,n){return a!==n},VSbjh:t(743),SrLmX:t(761),pivrx:function(a,n){return a|n},xncKt:function(a,n){return a+n},PdcaB:function(a,n){return a<<n},kvnVl:function(a,n){return a|n},zFPXJ:function(a,n){return a<<n},VEnDu:t(1469),Tollk:t(1162),YLMdn:t(1070),RwFvZ:function(a,n){return a>n},jhAiV:t(850)+t(836),IMctB:function(a,n){return a===n},iDKaY:function(a,n){return a===n},tlRay:function(a,n){return a&n},QrvWi:function(a,n){return a+n},Dfktr:function(a,n){return a+n},fAoBJ:t(478),qXdNQ:function(a,n,s){return a(n,s)},vdQCx:function(a,n,s){return a(n,s)},AxcSI:t(1298),yHQYN:t(1771),mLmrK:t(623),QNxQr:"JGtxu",qlNlS:"vBKcQ",zwBkk:function(a,n,s){return a(n,s)},BuNEQ:t(584),poBNj:function(a,n){return a instanceof n},KtqQc:function(a,n){return a+n},rmaTM:function(a,n){return a<n},QwqNg:t(1089),vEUkk:function(a,n){return a(n)},GrQab:function(a,n){return a!==n},SkRKN:"BWZzl",zIlin:function(a,n){return a||n},KJfUh:function(a,n){return a||n},CGNYe:t(953)+t(1126),hrBLV:"JGeEZ",zbbmc:t(1464)+"3",Kjuvf:function(a,n){return a||n},iWzmW:function(a,n){return a!=n},PwRLE:t(1302)+"d",klHOh:function(a,n){return a<=n},WLiTs:function(a,n){return a(n)},gsZIj:function(a,n){return a<n},QFIIL:function(a,n){return a<n},OVZkt:function(a,n){return a<n},ioUpG:function(a,n){return a&n},HomRV:function(a,n){return a===n},TZHRn:function(a,n){return a&n},tyGcB:function(a,n){return a+n},HdOLr:t(1399),GPxpd:function(a,n){return a<n},pDLMY:function(a,n){return a&n},DqqrS:function(a,n){return a>=n},qsWTU:function(a,n){return a|n},nZgrg:function(a,n){return a&n},WXmpq:function(a,n){return a&n},yPXEC:function(a,n){return a>=n},twrJP:function(a,n){return a|n},Aseae:function(a,n){return a<<n},nnzVl:function(a,n){return a&n},wCIlf:function(a,n){return a&n},BSbQj:function(a,n){return a+n},MRNvc:function(a,n){return a&n},iJgkv:function(a,n){return a<n},KlTDx:function(a,n){return a<n},nhNJJ:function(a,n){return a>>n},WlFNo:"2|5|3|1|"+t(646),aZsTX:function(a,n){return a&n},iIEJe:function(a,n){return a>>n},ZtAJG:function(a,n){return a|n},WDxpT:function(a,n){return a&n},XnHrN:function(a,n){return a>>n},PrToE:function(a,n){return a|n},xgjuw:function(a,n){return a-n},JBbqT:t(1777)+t(1297)+t(1610)+t(1445)+"ed",ceopx:"close, w"+t(962)+t(1581),QTRJZ:function(a,n){return a!==n},Radyn:"rQzuI",GIvEb:"NjIWp",ziIdd:function(a,n){return a(n)},FIvbc:t(884),AQYeR:function(a,n){return a!=n},AmkUw:function(a,n){return a===n},Ocbqo:t(958),TBKUR:function(a,n){return a==n},NaZQj:t(1562),gjaLC:function(a,n){return a>=n},NmIYz:t(1090),ottRD:function(a,n){return a(n)},Ighxy:function(a,n){return a(n)},Trmrh:t(425)+t(629),FAORE:function(a,n){return a+n},CfmpQ:t(1491),LQTgG:"&jscallb"+t(902)+t(1285)+"P",GasiE:t(1597),WXOpB:t(1061),CFrYo:function(a,n,s){return a(n,s)},MYBTa:function(a,n){return a!==n},UwcpE:t(1559),KCrnt:t(1257),BtuEm:function(a){return a()},XYvxA:function(a,n,s,l){return a(n,s,l)},WYnob:function(a,n){return a|n},tyWwt:t(804),oYgeE:t(1458),HcfhD:function(a,n){return a||n},AWWYw:function(a,n){return a||n},esuqr:"aIJnp",SvUch:"NAVXc",YUujv:function(a){return a()},vBTMq:function(a,n){return a===n},HtBqo:t(873),DxTCz:t(1571),NoMLa:function(a,n){return a||n},kMrXp:t(408),IzNyu:t(848),QqhPA:function(a,n){return a!==n},sEwel:t(807),gTgxx:"DIBIn",qYKXi:function(a,n){return a||n},YOMgD:function(a,n){return a||n},VJZYd:"init QoS"+t(826)+"d",thAWi:t(1357),KdoYr:t(1052)+"id",DRefP:function(a,n){return a===n},turQI:t(1560),MfwIF:t(929),VnVVF:t(681),sxBVp:function(a,n,s,l){return a(n,s,l)},qbdFy:t(396)+t(1594),hrWHu:function(a,n,s,l){return a(n,s,l)},dMYtc:"x_fronti"+t(1693)+"ck",cWEpP:t(396)+"er_is_ack",rDdmY:t(396)+"er_ack_m"+t(597),WKZAY:t(1301),uCvTu:t(592),wNyiB:function(a,n){return a&&n},qtmND:"ack_id",Wyypr:t(1697),IxfmV:function(a){return a()},vWsbb:t(1714),LkMuu:function(a,n){return a(n)},mjsMR:function(a,n,s,l){return a(n,s,l)},KomWo:function(a,n){return a instanceof n},HLKuB:function(a,n){return a(n)},ZLnbR:function(a,n){return a<<n},QrAht:function(a,n){return a(n)},qdAmo:function(a,n){return a&n},yaWmF:function(a,n){return a&n},dyikf:function(a,n){return a&n},KUMBC:function(a,n){return a(n)},xhhCL:function(a,n){return a&n},tbmJw:function(a,n){return a===n},sLdOD:t(1022),zRgaV:t(1046),hQMOE:function(a,n){return a(n)},dzfsB:function(a,n){return a instanceof n},zQDFQ:function(a,n){return a instanceof n},ZUXxQ:"applicat"+t(859),dftXR:"application/json;charset"+t(1324),Ffwib:t(734)+"e",QnzxC:t(982),HXxfR:function(a,n,s,l){return a(n,s,l)},jYyIe:function(a,n){return a!==n},lNyKh:function(a){return a()},IeLiC:function(a,n){return a<n},sOlyj:function(a,n){return a(n)},frCls:function(a,n){return a|n},aFxUr:function(a,n){return a>>>n},RTxCZ:function(a,n){return a+n},CDYJf:function(a,n){return a+n},WhcOl:function(a,n){return a+n},GAJhG:"index out of ran"+t(1104),jjuHv:t(1335),OPOnU:t(1719),RAAAK:function(a,n){return a>n},MDKZU:t(1072)+t(1750)+"e",uTsTm:function(a,n){return a>=n},XmUSf:function(a,n){return a&n},EhoTj:function(a,n){return a+n},sYXnM:function(a,n){return a+n},treLL:function(a,n,s){return a(n,s)},ItlGE:function(a,n){return a>>>n},cjrrJ:function(a,n){return a(n)},wkWIG:function(a,n){return a&n},cXykS:function(a,n){return a&n},fOMiY:function(a,n){return a<<n},SdnbO:function(a,n){return a&n},hOkCZ:"CtPtY",RcxdQ:t(1287)+"4",Bnxxe:function(a,n){return a+n},VHSWc:function(a,n){return a<n},AYShd:function(a,n,s,l){return a(n,s,l)},RSpuK:function(a,n){return a+n},XZSOY:function(a,n){return a+n},FHdkn:function(a,n){return a<<n},szNsM:function(a,n){return a+n},ZhITr:function(a,n){return a<<n},FpwWw:function(a,n){return a+n},RosDR:function(a,n){return a+n},Uxuen:function(a,n){return a+n},OBskJ:function(a,n){return a&n},fgVdi:function(a,n){return a+n},NTWfi:function(a,n){return a>>>n},YKpxM:function(a,n){return a&n},GnlEy:function(a,n){return a+n},vbPji:function(a,n){return a+n},kCqbG:function(a,n){return a+n},yADWF:function(a,n){return a&n},bKITu:function(a,n){return a&n},ChPyu:function(a,n){return a!==n},mQQDQ:"fMzHb",IUBdR:function(a,n){return a+n},Wxvww:function(a,n){return a+n},TZvOj:t(972),lbNDx:function(a,n){return a&n},KWmwH:function(a,n){return a<=n},eKMuw:function(a,n){return a>=n},GozTz:function(a,n){return a|n},VEEmI:function(a,n){return a<n},ALhUa:function(a,n){return a>>>n},KoqIo:function(a,n){return a|n},LOrfe:function(a,n,s,l){return a(n,s,l)},BPRVA:function(a,n){return a===n},hflEt:t(1281),KsTzN:function(a,n){return a<n},gpvIm:function(a,n){return a(n)},RwZVv:"cursor.s"+t(800),VdjvC:function(a,n,s,l){return a(n,s,l)},RczYe:t(493),lQWHz:t(733),xlPex:function(a,n){return a(n)},INPFo:"cursor_f"+t(563),SJGZm:function(a,n){return a<n},nHWBI:function(a,n,s){return a(n,s)},ihNRs:function(a,n,s,l){return a(n,s,l)},ZJdQv:t(1797)+t(565),pKNkh:t(410)+t(1268),pArKs:t(714),VuurF:"INSTANT",Gavrk:"CONTINUE",XhLEC:function(a,n,s,l){return a(n,s,l)},nYiAg:t(389),jlfxN:function(a,n){return a(n)},geUWm:function(a,n){return a!=n},pnyRj:function(a,n){return a instanceof n},YVFXq:function(a,n){return a==n},vFiPj:function(a,n){return a===n},BSdpZ:t(789),hOFha:function(a,n){return a!==n},JtUxO:t(824),JaBka:"jrjGK",edXyH:function(a,n){return a||n},dyCEq:t(1482),eQQBy:function(a,n){return a||n},RtmiX:t(1209),LalBU:function(a,n,s){return a(n,s)},DqfcV:function(a,n,s){return a(n,s)},JTLhL:t(396)+"er_ttl",PdXAg:function(a,n,s,l){return a(n,s,l)},jtWEL:t(385)+"s",dcgHT:function(a,n,s){return a(n,s)},fsJFg:t(1331)+"rsor_name",ltmPu:function(a,n,s){return a(n,s)},QZyhp:function(a,n){return a>n},LqoHC:function(a,n){return a>n},uJCEq:function(a){return a()},xMcvV:function(a,n){return a<n},OLFoF:function(a){return a()},BkeoK:function(a){return a()},HSjCp:function(a){return a()},MDevT:function(a,n){return a&&n},uAnSR:function(a,n){return a(n)},GsAne:t(1477),aAWZQ:t(1038),jiXwi:t(359),oCnHI:function(a){return a()},CKMGA:function(a,n){return a!==n},yOVwQ:function(a,n){return a<n},TRFeM:function(a,n,s){return a(n,s)},xKKpE:function(a){return a()},vTahP:function(a,n){return a===n},Eucsd:function(a,n){return a===n},zCGOa:"auto",sDUFg:t(1015)+t(626)+"s",JoYBf:t(787),LzILe:t(523),euJKf:function(a,n,s){return a(n,s)},mYULk:function(a,n,s){return a(n,s)},KnRAj:function(a,n){return a===n},vLXDf:function(a,n,s){return a(n,s)},OQjXZ:function(a,n){return a!==n},Frtkw:t(429),RQCUC:"kAZjL",tOrbH:function(a,n,s){return a(n,s)},msEYS:t(593),xLQjt:t(914),TSeiK:t(1859),CvYsG:t(1185)+"fer",USLfB:t(323),BBKyH:function(a,n){return a/n},uLCSt:function(a,n){return a===n},NQcVl:t(1077)+t(825)+t(723),YXSAI:function(a,n){return a(n)},HkIHG:t(1077)+t(484)+"s params"+t(1173)+t(1225)+t(1404)+t(1161)+t(1091),qHCIl:function(a,n){return a===n},XKIpJ:t(861),Jmuzo:t(518)+"t",dnskl:t(1436)+t(831)+" reconnect",tNHsd:"offline",APImi:"pagehide",Rmcvb:t(1832),WRZsy:"online",zYLyC:t(1667),WIOUf:t(1018),SHGIG:"bd_did",ITxmp:function(a,n){return a||n},iRKTQ:t(1077)+t(653)+"ddID, de"+t(1564)+t(1515),arDlb:t(1360),JtZyl:function(a){return a()},JHLve:t(601),aJsYh:"fws_1.0.0",RjCuK:function(a,n){return a(n)},pgRXc:function(a,n){return a!==n},EeRfA:function(a,n,s){return a(n,s)},hPtfm:function(a,n){return a!==n},Gaoxd:t(1615),hbpxm:t(1856),RaBDh:function(a,n){return a||n},hlwOc:function(a,n,s){return a(n,s)},uUUVT:function(a,n){return a>n},Mflpk:function(a,n){return a-n},vEJbi:function(a,n,s){return a(n,s)},xVuYA:function(a,n){return a(n)},burqG:t(1388),nsOKP:t(1757)+">",InKYm:function(a,n,s){return a(n,s)},jDxlw:t(1015)+t(667)+"t",RAxvd:t(1127),uuEVT:t(1830),rSlqx:t(1476),SMgZa:function(a,n,s){return a(n,s)},AYePB:function(a,n,s){return a(n,s)},uaEmc:function(a,n,s){return a(n,s)},NjmRT:function(a,n){return a===n},jgfGF:t(1561),dszcQ:function(a,n,s){return a(n,s)},eBIZl:function(a,n){return a!==n},ubkzW:"upXRc",Cjpwc:function(a,n){return a===n},bYtzV:t(350)+"1",PoiyI:function(a,n,s,l){return a(n,s,l)},RkBsk:function(a,n){return a===n},OZyRb:t(890),CxWRv:t(1671),jKyEG:function(a,n){return a===n},lsrUO:t(1275),kxeyq:t(984),wLKLT:function(a,n,s){return a(n,s)},dgdqM:function(a,n,s){return a(n,s)},CNClJ:t(1415)+t(649)+t(451)+t(528),lzkBY:function(a,n){return a instanceof n},HuxLt:"BYOCU",QTXzF:t(610),rVOXH:function(a,n,s){return a(n,s)},hdeUG:t(1248),tVbdN:function(a,n){return a+n},eEsjd:t(1426),tONUu:"bSEoS",VgSfv:function(a,n){return a+n},fVVal:function(a,n,s){return a(n,s)},GpRTV:t(1843),RpUEM:t(719),uWqQk:t(503)+t(1676),RsSwj:function(a,n){return a>>>n},QyeSa:function(a,n){return a>>>n},jJrRA:function(a,n){return a<n},tXKKj:function(a,n){return a<n},bKfyL:function(a,n){return a+n},WDGxA:function(a,n){return a>>>n},AlZhW:function(a,n){return a+n},bfRka:function(a,n){return a!==n},gLawA:function(a,n){return a&n},wQZfo:function(a,n){return a&n},WXCOx:function(a,n){return a>>>n},JIcuR:function(a,n){return a&n},SLvBJ:function(a,n){return a+n},GszAQ:function(a,n){return a|n},DCiGm:function(a,n){return a>>>n},ALtVQ:function(a,n){return a&n},YznpS:function(a,n){return a&n},HVECm:function(a,n){return a|n},ugTMn:function(a,n){return a&n},xWllN:function(a,n){return a>>>n},iGOMx:function(a,n){return a!==n},CGuqa:function(a,n){return a!==n},xZLlx:t(386),jsWNh:function(a,n){return a==n},xFUDR:t(1640),PESwM:function(a,n){return a!=n},kUVjI:function(a,n){return a instanceof n},YGXKm:function(a,n){return a instanceof n},HSPte:function(a,n){return a(n)},XXWsW:function(a,n){return a||n},MlxUl:function(a,n){return a instanceof n},hjwjc:function(a,n){return a(n)},NexPD:function(a,n){return a===n},NzRDN:t(1778),ShnOq:function(a,n){return a==n},bFEnb:t(755)+t(1243)+t(1435),XXXKb:function(a,n){return a!==n},zTSex:t(456),DkxhG:function(a,n){return a!==n},yWyXN:"ThpGs",umyqs:t(1551),wqNrb:function(a,n,s){return a(n,s)},MHSWV:t(1424),VmWjT:function(a,n){return a!=n},oissD:t(1315),zeJMa:function(a,n){return a===n},apuiK:t(654)+t(1587)+t(516)+"pe",cNGFV:function(a,n){return a===n},LwPNh:"Object",YWlhI:function(a,n){return a!=n},QJiPq:function(a,n){return a===n},sLukw:t(612)+"rkerGlobalScope",UrhEB:"ServiceWorkerGlobalScope",fGZvj:function(a,n){return a!=n},Rzmia:function(a,n){return a===n},NDahK:function(a,n){return a!=n},QVIfI:function(a,n){return a!=n},FfxsF:t(908)+t(1503)};Ut.r(Re),Ut.d(Re,{FWS:()=>qg,CustomErrorEvent:()=>ml,createCloseEvent:()=>mt,ReconnectEvent:()=>gl,createErrorEvent:()=>lt,decodedFrame:()=>sn,createOpenEvent:()=>vl,CustomCloseEvent:()=>wl,createReconnectEvent:()=>va,FrontierMessageEvent:()=>yl,encodeFrame:()=>Gt,createMessageEvent:()=>El,OpenEvent:()=>bl,ErrorCode:()=>an,Event:()=>or,MessageEvent:()=>_l});let r="";function i(a=""){let n=t,s="02",l=""+Date[n(370)](),f=r||(r=h(a)),p=Math.random()[n(560)](16)[n(956)](-6);return e[n(1102)](e[n(1102)](e[n(1082)](s,l),f),p)}function o(){let a=t;return e[a(573)](1e4*Date[a(370)](),Math[a(519)](1e4*Math[a(1241)]()))}function c(a){let n=t;return e[n(1102)](e[n(912)](Array,8).join("0"),e[n(1307)](parseInt,a,10).toString(2))[n(956)](-8)}function d(a){let n=t;return e[n(1319)](e.pryiI,e[n(812)])?(_0x73d141|=0,{low:_0xddb4aa,high:e[n(1098)](_0x2e960c,31),unsigned:e.GNERA(_0x12b3c0,0)}):e[n(1102)](e[n(912)](Array,4).join("0"),e[n(1307)](parseInt,a,2)[n(560)](16))[n(956)](-4)}function u(a){let n=t,s=a[n(1317)](/\./)[n(400)](p=>c(p)),l=[];return l[0]=e[n(912)](d,e[n(535)](s[0],s[1])),l[1]=d(e[n(535)](s[2],s[3])),[e[n(1670)],n(1246),n(1246),n(1246),e[n(1670)],e[n(1500)],l[0],l[1]][n(994)]("")}function h(a){let n=t;if(e[n(1183)](e.DPBkh,"xcKXZ"))switch(_0x3096de){case n(1562):case e.dkCwL:return{[n(1369)+_0x3c20e9]:1,"x-tt-env":_0x102816};default:return{}}else{let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(416)](a),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(a);return s?e[n(912)](u,a):l?x(a):e[n(1316)]}}function x(a){let n=t,s="",l=[],f=0,p=0,y=!0,g=e[n(1670)];if(e[n(922)](a[n(509)]("::"),-1)){let T=a[n(1317)]("::");for(let L=0;e.hAqvf(L,T[n(1273)]);L++){let B=T[L];if(e.bFiTg(B.indexOf(":"),0)){let $=B[n(1317)](":");y&&(f=$.length),p+=$[n(1273)];for(let J=0;e[n(1024)](J,$[n(1273)]);J++)if(e.myfIR(4,$[J].length)){let Be=g[n(1556)+"g"](0,e[n(473)](4,$[J].length)),wt=Be[n(1710)]($[J]);l[n(1097)](wt)}else l[n(1097)]($[J]);y=!1}else{if(e.GLIFp(4,B[n(1273)])){let $=g[n(1556)+"g"](0,4-B[n(1273)]),J=$[n(1710)](B);l[n(1097)](J)}else l.push(B);y&&(f+=1),p+=1,y=!1}}let C="";for(let L=0;e[n(1024)](L,e[n(473)](8,p));L++)C=C[n(1710)](g);for(let L=0;e[n(622)](L,l[n(1273)]);L++)e[n(1319)](L,f)&&(s=s[n(1710)](C)),s=s[n(1710)](l[L]);return s}{let T=a[n(1317)](":");for(let C=0;e[n(1211)](C,T.length);C++)if(e[n(1808)]!==e[n(1497)]){let L=T[C];if(e[n(1345)](4,T[C][n(1273)])){if(e.vBbox(n(665),e[n(467)]))return this[n(570)+n(324)+n(1159)](_0x18960e),_0x482067();{let B=g[n(1556)+"g"](0,e.VyVmE(4,T[C][n(1273)])),$=B.concat(L);s=s[n(1710)]($)}}else s=s[n(1710)](L)}else{if(!this[n(1718)+n(874)]()||this["_readyCl"+n(979)])return;this[n(1340)+"tManager"]?.[n(1121)+"pointCon"+n(915)](),this["_pingLos"+n(1325)]?.[n(468)+n(798)](),this[n(975)]?this[n(1106)+n(710)](1001,e.kUzyV,!0):this[n(1205)]()}return s}}function m(a,n){let s=t,l=a[s(412)];e[s(886)](void 0,l)&&(e[s(635)](pe,n,10),e[s(1306)](U,n,l));let f=a[s(897)];e[s(886)](void 0,f)&&(e.fjVHL(pe,n,18),U(n,f))}function w(a){let n=t,s={};e:for(;!K(a);){let l=e[n(912)](le,a);switch(l>>>3){case 0:break e;case 1:s[n(412)]=e[n(1306)](P,a,le(a));break;case 2:s[n(897)]=e[n(788)](P,a,le(a));break;default:e[n(788)](k,a,e[n(640)](7,l))}}if(e[n(1319)](void 0,s[n(412)]))throw new Error(e[n(1239)]);if(e.qUfPJ(void 0,s.value))throw new Error(n(852)+n(340)+n(1473)+n(897));return s}function v(a){let n=t;if(e[n(1421)](e[n(1818)],e[n(880)])){if(e[n(1021)](_0x54f810,1)||_0x3155bc>_0x419dc3)return e[n(912)](_0x224f6c,_0x1cf694);e.nYeaC(e[n(1102)](_0x3e59b2,_0x46c3f6),_0x41aa6a)&&(_0x357a8d=e[n(912)](_0x11f189,_0xc4512d),_0x21b356=0);let s=_0x5830b0[n(1398)](_0x389bb0,_0xe7756b,_0x305212+=_0x198355);return e[n(640)](7,_0x35ae6b)&&(_0x7dcc94=e[n(573)](e[n(1858)](7,_0x1b7273),1)),s}else{let s=e[n(1026)](D);return _(a,s),e[n(1263)](M,s)}}function _(a,n){let s=t,l={BTZbo:function(Je,Ze,oi){return e[H(1307)](Je,Ze,oi)},XSxrQ:function(Je,Ze){return Je(Ze)},RFPNE:e[s(1419)],RJqBB:function(Je,Ze){return e[s(345)](Je,Ze)}},f=a.SeqID;if(e[s(886)](void 0,f)){if(e[s(1319)](e[s(515)],e[s(1058)]))return e[s(1013)](s(884),typeof _0x133eba)?e[s(674)]:"";e[s(542)](pe,n,8),e[s(1307)](gt,n,f)}let p=a.LogID;e.cBvUk(void 0,p)&&(e[s(635)](pe,n,16),gt(n,p));let y=a[s(421)];e.GLIFp(void 0,y)&&(e[s(1299)](pe,n,24),e.RSGZT(gt,n,e[s(1147)](R,y)));let g=a[s(1264)];if(e.PFigN(void 0,g)){if(e[s(602)](e[s(864)],e[s(1444)]))return new _0x1104af(Je=>{let Ze=s;l[Ze(715)](_0x173164,Je,this[Ze(328)+"rvalValue"](_0x574246))});pe(n,32),e[s(1299)](gt,n,e[s(796)](R,g))}let T=a.headers;if(e[s(1345)](void 0,T))for(let Je of T)if(e.boInv(e[s(1861)],e.fjoHg)){pe(n,42);let Ze=e.kEdcz(D);e[s(1796)](m,Je,Ze),e[s(1848)](pe,n,Ze.limit),e.iwdJE(j,n,Ze),e[s(912)](O,Ze)}else _0x3f7c2f[s(1694)]["removeCh"+s(508)](_0x5af763),_0x151aea[s(1148)+s(1742)]=void 0,l[s(1220)](_0x33d936,_0xeac700&&_0x2b4002.msg||l[s(381)]);let C=a[s(1403)+s(1781)];e.iaBaf(void 0,C)&&(pe(n,50),e[s(635)](U,n,C));let L=a[s(896)+s(1230)];e[s(1427)](void 0,L)&&(e[s(991)](pe,n,58),e[s(1721)](U,n,L));let B=a[s(448)];B!==void 0&&(pe(n,66),pe(n,B.length),e[s(1848)](oe,n,B));let $=a.LogIDNew;e[s(1555)](void 0,$)&&(e.LSblA(pe,n,74),e[s(1848)](U,n,$));let J=a["serverTi"+s(1312)];if(e[s(886)](void 0,J))if(e[s(829)](e[s(1789)],"YecKp"))e[s(1214)](pe,n,82),e.UDBMw(U,n,J);else{let Je=new _0x25abf6(l.RJqBB(2,_0x1361ff));Je[s(1487)](_0x425d41),_0x2c66a1[s(1738)]=Je}let Be=a[s(951)];Be!==void 0&&(e[s(1299)](pe,n,90),U(n,Be));let wt=a[s(1027)+"e"];wt!==void 0&&(e[s(1371)](pe,n,96),e.UDBMw(gt,n,R(wt)))}function E(a){let n=t,s={GIyYj:function(l,f){return e[H(1211)](l,f)},QZASw:function(l,f){return e[H(1858)](l,f)},vkhbT:function(l,f){return e.QkrcJ(l,f)},KsmgW:function(l,f){return e[H(1707)](l,f)},QCSnt:function(l,f){return e.GGBSV(l,f)},LhXoV:function(l,f){return l&f},mmDuv:function(l,f){return e[H(1098)](l,f)},Hepid:function(l,f){return l>>f},qZEkr:function(l,f){return e.GGBSV(l,f)}};if(e[n(878)](e.ONEGZ,e[n(530)]))return e.xQtvM(S,e[n(384)](F,a));s[n(903)](_0x2d6c23,2048)?_0x1c7d74[_0x2b56b1++]=s[n(1690)](s.vkhbT(_0x42e44e>>6,31),192):(s[n(1593)](_0x1a8f29,65536)?_0xff208c[_0x346640++]=s.QCSnt(s.LhXoV(s[n(1191)](_0x178cc8,12),15),224):(_0x423d58[_0x1d1c13++]=s[n(1690)](s[n(1191)](_0x5737b8,18)&7,240),_0x2b127f[_0x4c8e43++]=s[n(698)](_0x4657b5,12)&63|128),_0x337234[_0x557add++]=s[n(857)](s[n(698)](_0x47a88d,6)&63,128)),_0x50ebeb[_0x3846ab++]=s[n(932)](63,_0x2f1d11)|128}function S(a){let n=t,s={};e:for(;!e[n(384)](K,a);){let l=le(a);switch(l>>>3){case 0:break e;case 1:s.SeqID=e[n(504)](At,a,!0);break;case 2:s[n(1756)]=At(a,!0);break;case 3:s.service=le(a);break;case 4:s[n(1264)]=e[n(586)](le,a);break;case 5:{let f=I(a);(s.headers||(s.headers=[])).push(e[n(1334)](w,a)),a[n(418)]=f;break}case 6:s[n(1403)+n(1781)]=e[n(788)](P,a,e[n(796)](le,a));break;case 7:s[n(896)+n(1230)]=e[n(474)](P,a,e.wPqZx(le,a));break;case 8:s[n(448)]=e[n(923)](te,a,e[n(919)](le,a));break;case 9:s[n(377)]=e.uAvBM(P,a,e.xQtvM(le,a));break;case 10:s[n(1547)+n(1312)]=e[n(923)](P,a,e[n(1263)](le,a));break;case 11:s[n(951)]=e.fjVHL(P,a,e[n(1334)](le,a));break;case 12:s.frameType=e[n(1334)](le,a);break;default:e[n(1214)](k,a,7&l)}}if(s.SeqID===void 0)throw new Error(e[n(762)]);if(e[n(672)](void 0,s[n(1756)]))throw new Error(n(852)+"required"+n(1473)+n(1756));if(e[n(1421)](void 0,s[n(421)]))throw new Error(e[n(507)]);if(e[n(1149)](void 0,s.method))throw new Error(e[n(1240)]);return s}function I(a){let n=t,s=e[n(1147)](le,a),l=a[n(418)];return a.limit=e[n(535)](a[n(546)],s),l}function k(a,n){let s=t;switch(n){case 0:for(;e[s(534)](128,ne(a)););break;case 2:V(a,e[s(586)](le,a));break;case 5:e[s(1848)](V,a,4);break;case 1:e[s(1432)](V,a,8);break;default:throw new Error(e[s(535)]("Unimplem"+s(1785)+"pe: ",n))}}function R(a){let n=t;return a|=0,{low:a,high:e[n(1098)](a,31),unsigned:e[n(1709)](a,0)}}let b=[];function D(){let a=t,n=b[a(676)]();return n?(n[a(546)]=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){b[t(1097)](a)}function F(a){return{bytes:a,offset:0,limit:a[t(1273)]}}function M(a){let n=t,s=a.bytes,l=a[n(418)];return e[n(1421)](s.length,l)?s:s[n(790)](0,l)}function V(a,n){let s=t;if(e[s(1123)](e[s(875)](a[s(546)],n),a[s(418)]))throw new Error(e[s(1009)]);a[s(546)]+=n}function K(a){let n=t;return e[n(634)](a[n(546)],a[n(418)])}function ie(a,n){let s=t,l=a.bytes,f=a.offset,p=a[s(418)],y=f+n;if(y>l[s(1273)]){let g=new Uint8Array(e[s(345)](2,y));g[s(1487)](l),a[s(1738)]=g}return a[s(546)]=y,e[s(922)](y,p)&&(a.limit=y),f}function Y(a,n){let s=t,l=a[s(546)];if(e.qvcWc(e[s(1201)](l,n),a[s(418)]))throw new Error(e.RRBRn);return a[s(546)]+=n,l}function te(a,n){let s=t,l=e[s(1114)](Y,a,n);return a.bytes.subarray(l,e[s(875)](l,n))}function oe(a,n){let s=t,l=e[s(1796)](ie,a,n[s(1273)]);a[s(1738)][s(1487)](n,l)}function P(a,n){let s=t,l=Y(a,n),f=String[s(1155)+"Code"],p=a[s(1738)],y="\uFFFD",g="";for(let T=0;e[s(1024)](T,n);T++){let C=p[T+l],L,B,$,J;e[s(1480)](e[s(1078)](128,C),0)?g+=f(C):e[s(1543)](e[s(1643)](224,C),192)?e[s(634)](T+1,n)?g+=y:(L=p[e[s(1599)](e[s(1102)](T,l),1)],e[s(1183)](e.ywXib(192,L),128)?g+=y:(J=e.lHVve(e[s(708)](31,C),6)|e[s(640)](63,L),e[s(622)](J,128)?g+=y:(g+=f(J),T++))):e.ZcMgh(240,C)==224?e[s(1607)](T,2)>=n?g+=y:(L=p[e[s(954)](e[s(1110)](T,l),1)],B=p[e[s(573)](e[s(1753)](T,l),2)],e.RqdrI(e[s(397)](e[s(1036)](L,e[s(785)](B,8)),49344),32896)?g+=y:(J=e[s(871)](e.VfTin(e[s(534)](15,C),12)|e[s(785)](e[s(1238)](63,L),6),63&B),J<2048||e[s(1682)](J,55296)&&e[s(443)](J,57343)?g+=y:(g+=e.rierQ(f,J),T+=2))):e.MBBHL(e[s(708)](248,C),240)?e.WMBye(e[s(1409)](T,3),n)?g+=y:(L=p[e.xehFD(T,l)+1],B=p[e.dHtwQ(e.EQPQJ(T,l),2)],$=p[e[s(1387)](e.oypxS(T,l),3)],e.kDjEW(e[s(1406)](e[s(1036)](L,e[s(1647)](B,8)),e[s(945)]($,16))&12632256,8421504)?g+=y:s(999)===e[s(747)]?(J=e.zdbxW(e[s(1406)](e.nlCrf(e.Zquuh(7,C),18),e.rWNLl(e[s(1289)](63,L),12)),e[s(1216)](63&B,6))|e.wRAQZ(63,$),e[s(703)](J,65536)||e[s(922)](J,1114111)?g+=y:(J-=65536,g+=f(e[s(1387)](e[s(1098)](J,10),55296),e[s(1054)](1023,J)+56320),T+=3)):(this[s(778)](e.AqBFX,_0x328c39),this[s(1634)]&&this.onclose(_0x393711))):g+=y}return g}function U(a,n){let s=t,l=n[s(1273)],f=0;for(let g=0;e[s(1442)](g,l);g++){let T=n[s(711)+"At"](g);T>=55296&&e[s(1112)](T,56319)&&e[s(532)](g+1,l)&&(T=e[s(1802)](T<<10,n[s(711)+"At"](++g))-56613888),f+=T<128?1:e[s(780)](T,2048)?2:e[s(780)](T,65536)?3:4}e[s(1578)](pe,a,f);let p=e.Qrvqu(ie,a,f),y=a[s(1738)];for(let g=0;e[s(1828)](g,l);g++){let T=n[s(711)+"At"](g);e[s(1682)](T,55296)&&e.lBfDM(T,56319)&&e[s(703)](e.YPEtw(g,1),l)&&(T=e[s(1607)](e[s(1134)](T,10),n[s(711)+"At"](++g))-56613888),e[s(1211)](T,128)?y[p++]=T:(T<2048?y[p++]=e.djjMv(T,6)&31|192:(T<65536?y[p++]=e[s(871)](T>>12&15,224):(y[p++]=e[s(435)](e[s(1402)](T,18),7)|240,y[p++]=e[s(1631)](T,12)&63|128),y[p++]=e[s(1406)](e[s(1044)](T,6)&63,128)),y[p++]=e[s(871)](e[s(397)](63,T),128))}}function j(a,n){let s=t,l=e[s(1307)](ie,a,n[s(418)]),f=a[s(1738)],p=n.bytes;for(let y=0,g=n[s(418)];e[s(1330)](y,g);y++)f[y+l]=p[y]}function ne(a){let n=t;if(n(887)!=="xfdYP"){let s=_0x199eef[n(1738)],l=_0x3ec906[n(418)];return s.length===l?s:s[n(790)](0,l)}else return a.bytes[e[n(1534)](Y,a,1)]}function Ve(a,n){let s=t,l={MXQOU:function(f,p){return f+p}};if(e[s(602)](e.vOAjI,e[s(583)])){let f=this[s(964)+"Queue"][s(363)]((p,y)=>(p+=y&&y.byteLength||0,p),0);return l.MXQOU(f,this[s(975)]?this[s(975)][s(751)+"Amount"]:0)}else{let f=ie(a,1);a[s(1738)][f]=n}}function le(a){let n=t,s=0,l=0,f;do e.wZbnP(n(1505),e[n(1215)])?(f=ne(a),e.ukFkw(s,32)&&(l|=e[n(945)](e.boTJX(127,f),s)),s+=7):_0x46845b.d=(p,y)=>{let g=n;for(var T in y)_0x1ccc0a.o(y,T)&&!_0x5d86a0.o(p,T)&&_0x5996ad[g(1566)+"operty"](p,T,{enumerable:!0,get:y[T]})};while(e[n(809)](128,f));return l}function pe(a,n){let s=t;for(n>>>=0;e.fMaQo(n,128);)Ve(a,e[s(1036)](e[s(1460)](127,n),128)),n>>>=7;Ve(a,n)}function At(a,n){let s=t,l={hllCw:function(T,C){return e[H(1769)](T,C)}},f=0,p=0,y=0,g;if(g=e[s(1334)](ne,a),f=e[s(976)](127,g),e.tEdcG(128,g)&&(g=e[s(486)](ne,a),f|=e[s(1134)](e[s(1779)](127,g),7),e[s(1289)](128,g)&&(g=ne(a),f|=e[s(1107)](e[s(1054)](127,g),14),e[s(435)](128,g)))){if(e[s(452)](s(1485),e.Ipfzw))return l[s(520)](this.count,this[s(322)+"ount"]);g=e.bPmPe(ne,a),f|=(127&g)<<21,e.uAPEt(128,g)&&(g=e.iNMMN(ne,a),p=e[s(1352)](127,g),e[s(534)](128,g)&&(g=e.bPmPe(ne,a),p|=e[s(1452)](127,g)<<7,e[s(708)](128,g)&&(g=e[s(356)](ne,a),p|=e[s(1011)](127,g)<<14,128&g&&(g=ne(a),p|=e[s(906)](e[s(1431)](127,g),21),e[s(616)](128,g)&&(g=e[s(693)](ne,a),y=e.NiSRo(127,g),e[s(511)](128,g)&&(g=e[s(834)](ne,a),y|=e[s(1355)](127&g,7)))))))}return{low:e[s(1092)](f,e.bBthj(p,28)),high:e[s(342)](p,4)|e.QymjU(y,24),unsigned:n}}function gt(a,n){let s=t;if(e[s(735)](e[s(636)],s(514)))try{return!!this._qosDB}catch(l){return _0x48e3f2[s(446)](l),!1}else{let l=e.ycJHk(n[s(1396)],0),f=e[s(342)](e[s(1092)](e[s(1086)](n[s(1396)],28),e[s(906)](n[s(1228)],4)),0),p=e[s(1086)](n[s(1228)],24),y=e[s(927)](0,p)?f===0?e[s(1707)](l,16384)?e[s(413)](l,128)?1:2:e[s(1021)](l,2097152)?3:4:e[s(780)](f,16384)?e[s(1442)](f,128)?5:6:e[s(1207)](f,2097152)?7:8:e[s(1828)](p,128)?9:10,g=ie(a,y),T=a[s(1738)];switch(y){case 10:T[e[s(1102)](g,9)]=e[s(1267)](e[s(342)](p,7),1);case 9:T[e[s(875)](g,8)]=e[s(502)](9,y)?128|p:127&p;case 8:T[e[s(513)](g,7)]=e.LoSiP(8,y)?e[s(1025)](e[s(1100)](f,21),128):e[s(867)](e[s(342)](f,21),127);case 7:T[e[s(1846)](g,6)]=y!==7?e[s(644)](f,14)|128:e[s(1086)](f,14)&127;case 6:T[e[s(599)](g,5)]=e[s(1555)](6,y)?e[s(644)](f,7)|128:e[s(1290)](f,7)&127;case 5:T[g+4]=y!==5?e[s(1784)](128,f):127&f;case 4:T[e[s(573)](g,3)]=e[s(971)](4,y)?e[s(802)](l>>>21,128):e[s(867)](e.fsEQW(l,21),127);case 3:T[e[s(1195)](g,2)]=e.PFigN(3,y)?e[s(862)](e[s(1100)](l,14),128):e.eBpZy(e[s(1045)](l,14),127);case 2:T[e[s(1591)](g,1)]=y!==2?e[s(549)](e[s(342)](l,7),128):e.YDVFS(l>>>7,127);case 1:T[g]=e.YpVco(1,y)?e[s(1092)](128,l):e[s(1342)](127,l)}}}function sn(a){return e[t(834)](E,a)}function Gt(a){let n=t;return e.DJyWH===e[n(815)]?e[n(512)](v,a):(_0x26fe2c||(_0x22024c=_0x2aa9ee[n(1488)]()[n(1323)](_0x11fe4b.bind(_0x538871,e[n(1514)]))),_0x2ed8d8)}let on=65536,ri=e[t(742)],we=on*on,Ae=e.vjCkX(we,we),sr=e[t(840)](Ae,2),Oe=String[t(1157)+"e"][t(711)+"At"];class ue{constructor(n,s,l){let f=t,p={tmPQQ:function(y,g,T){return e.cBwuL(y,g,T)},htaBd:f(1298)};e[f(1495)]===e.BqZRA?this[f(778)](f(1298),p[f(992)](_0x19e2df,p[f(494)],{message:this[f(457)+f(1350)+f(1702)](_0x24e2b5)})):(this.isLong=!0,this[f(1396)]=e[f(549)](0,n),this[f(1228)]=e[f(997)](0,s),this[f(692)]=!!l)}static isLong(n){return n&&n[t(1660)]===!0}static[t(1616)](n,s,l){return new ue(n,s,l)}static fromBytes(n,s,l){let f=t;return l?ue[f(1179)+f(1144)](n,s):ue[f(1179)+f(1646)](n,s)}static["fromByte"+t(1144)](n,s){let l=t;return new ue(e[l(1025)](e[l(1784)](n[0]|e[l(1107)](n[1],8),e[l(1601)](n[2],16)),e[l(455)](n[3],24)),e[l(1092)](e[l(862)](e[l(1784)](n[4],n[5]<<8),e.TDrDV(n[6],16)),n[7]<<24),s)}static["fromByte"+t(1646)](n,s){let l=t;return new ue(e[l(1347)](e[l(1730)](e.wIIgw(n[4],24)|n[5]<<16,e.bBthj(n[6],8)),n[7]),e[l(1744)](e[l(871)](e[l(1343)](n[0],24),e[l(1647)](n[1],16))|e[l(1343)](n[2],8),n[3]),s)}static[t(1786)](n){let s=t;return n===ri?pl:new ue(e[s(930)](e[s(1700)](e[s(1804)](e[s(1347)](Oe.call(n,0),e[s(1051)](Oe.call(n,1),8)),e.epNHw(Oe[s(1398)](n,2),16)),e[s(941)](Oe[s(1398)](n,3),24)),0),e[s(342)](e[s(1025)](e[s(802)](Oe[s(1398)](n,4),Oe[s(1398)](n,5)<<8)|e.kZypW(Oe[s(1398)](n,6),16),Oe[s(1398)](n,7)<<24),0),!0)}toHash(){let n=t;return String.fromCharCode(e[n(1219)](255,this[n(1396)]),e[n(976)](this.low>>>8,255),e[n(918)](e.ZiXTI(this[n(1396)],16),255),e[n(1100)](this[n(1396)],24),e[n(1431)](255,this[n(1228)]),e[n(943)](e.JRNMS(this.high,8),255),e[n(1384)](e[n(1235)](this[n(1228)],16),255),e[n(524)](this[n(1228)],24))}static fromNumber(n,s=!0){let l=t;if(e.OFfii(isNaN,n))return s?tg:pl;if(s){if(e[l(682)](n,Ae))return rg}else{if(e[l(1341)](n,-sr))return ig;if(e[l(1745)](e[l(1510)](n,1),sr))return ng}return ue[l(1616)](e[l(872)](n%we,0),e[l(1580)](e.grool(n,we),0),s)}[t(1274)](){let n=t;return this.unsigned?e[n(355)](e[n(345)](e[n(1733)](this.high,0),we),e[n(644)](this[n(1396)],0)):e[n(424)](e[n(537)](this[n(1228)],we),e[n(1585)](this[n(1396)],0))}[t(1374)](){let n=t;return e[n(1421)](0,this[n(1228)])&&e[n(732)](0,this[n(1396)])}[t(844)](n){let s=t;ue[s(1660)](n)||(n=ue[s(845)+"er"](n));let l=e[s(1733)](this.high,16),f=e[s(325)](65535,this[s(1228)]),p=this.low>>>16,y=65535&this[s(1396)],g=e[s(1733)](n[s(1228)],16),T=e[s(1643)](65535,n[s(1228)]),C=e[s(1290)](n.low,16),L=e.DzXSz(65535,n[s(1396)]),B=0,$=0,J=0,Be=0;return Be+=e[s(422)](y,L),J+=e.RWFpZ(Be,16),Be&=65535,J+=p+C,$+=e[s(1086)](J,16),J&=65535,$+=e[s(1816)](f,T),B+=e[s(1585)]($,16),$&=65535,B+=e[s(573)](l,g),B&=65535,ue[s(1616)](e[s(1744)](e[s(1601)](J,16),Be),e[s(997)](B<<16,$),this[s(692)])}[t(1668)](n){let s=t;return ue[s(1660)](n)||(n=ue[s(845)+"er"](n)),e[s(1284)](this[s(692)],n[s(692)])&&e[s(1733)](this[s(1228)],31)===1&&e[s(781)](e[s(1429)](n[s(1228)],31),1)?!1:e.qUfPJ(this[s(1228)],n[s(1228)])&&e[s(1448)](this[s(1396)],n[s(1396)])}[t(447)](){let n=t,s={AgPsy:function(l,f){return e[H(1800)](l,f)},wSrrS:function(l,f){return l+f},qsCNn:function(l,f){return e[H(599)](l,f)}};if(e[n(1149)](e[n(1698)],e[n(571)])){let l=_0x35705b[n(1273)]&&_0x2d6b7c[0];if(s[n(1291)](l,_0x46faf1))throw l;let f=new _0x241bec(s[n(1417)](n(850)+n(836),l?s[n(1417)](s[n(637)](" (",l[n(623)]),")"):""));throw f[n(1177)]=l,l}else return this[n(1396)]===-1&&e[n(1149)](-1,this[n(1228)])?ue.fromBits(0,0,this[n(692)]):e.fWbDZ(-1,this[n(1396)])?ue[n(1616)](0,e[n(1528)](this.high,1),this[n(692)]):ue[n(1616)](e.oTrJK(this.low,1),this.high,this.unsigned)}[t(663)](n){let s=t;return n?this[s(1016)+"E"]():this[s(900)+"E"]()}[t(1016)+"E"](){let n=t,s=this[n(1228)],l=this[n(1396)];return[e[n(1194)](255,l),e[n(1733)](l,8)&255,e.FwRXD(l,16)&255,e[n(644)](l,24),255&s,e[n(655)](s>>>8,255),e[n(525)](s,16)&255,e[n(1328)](s,24)]}toBytesBE(){let n=t,s=this.high,l=this[n(1396)];return[s>>>24,e[n(1290)](s,16)&255,e[n(1779)](e[n(648)](s,8),255),255&s,e[n(738)](l,24),e.KoPbC(e[n(1093)](l,16),255),e[n(1290)](l,8)&255,255&l]}}let pl=new ue(0,0,!1),tg=new ue(0,0,!0),ng=ue.fromBits(-1,2147483647,!1),rg=ue[t(1616)](-1,-1,!0),ig=ue[t(1616)](0,-2147483648,!1);var an=(function(a){let n=t,s=(n(957)+n(379))[n(1317)]("|"),l=0;for(;;){switch(s[l++]){case"0":a[a[e[n(633)]]=5002]=e[n(633)];continue;case"1":return a;case"2":a[a[e[n(756)]]=5003]=e[n(756)];continue;case"3":a[a[e[n(1174)]]=5005]=e[n(1174)];continue;case"4":a[a[e[n(1665)]]=5004]=e[n(1665)];continue;case"5":a[a[n(1151)+n(893)]=5001]=e[n(458)];continue}break}})({});class or{constructor(n){let s=t;this[s(321)]=n,this.target=null}}class gl extends or{constructor(n,s){let l=t;super(n),this.message=s&&s[l(623)]||null}}class ml extends or{constructor(n,s){let l=t,f=(l(327)+l(858))[l(1317)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[l(623)]=s&&s[l(623)]||"";continue;case"1":this[l(1688)]=s&&s.filename||"";continue;case"2":super(n);continue;case"3":this[l(1298)]=s&&s[l(1298)]||null;continue;case"4":this[l(1209)]=s&&s[l(1209)]||5001;continue;case"5":this[l(1295)]=s&&s[l(1295)]||0;continue;case"6":this[l(1067)]=s&&s[l(1067)]||0;continue}break}}}class wl extends or{constructor(n,s){let l=t,f="1|0|4|3|2"[l(1317)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[l(1209)]=s&&s[l(1209)]||0;continue;case"1":super(n);continue;case"2":this[l(437)+l(1535)]=s&&s[l(437)+l(1535)]||!1;continue;case"3":this[l(1813)]=s&&s[l(1813)]||!1;continue;case"4":this[l(754)]=s&&s.reason||"";continue}break}}}class _l extends or{constructor(n,s){let l=t,f={LPcuW:function(p,y){return p<y},eytmk:function(p,y){return p!==y},mvQiR:function(p,y){return e[H(473)](p,y)}};if(e[l(1680)](l(1260),e[l(647)]))super(n),this[l(466)]=s&&s[l(466)]||null;else{let p=_0x9d1f90[l(1317)](":");for(let y=0;eIMDZb[l(1663)](y,p[l(1273)]);y++){let g=p[y];if(eIMDZb[l(1308)](4,p[y][l(1273)])){let T=_0x123283[l(1556)+"g"](0,eIMDZb[l(1111)](4,p[y][l(1273)])),C=T.concat(g);_0xce5169=_0xe0f237[l(1710)](C)}else _0x9fed03=_0x4b8d85[l(1710)](g)}return _0x490a9e}}}class yl extends _l{constructor(n,s){let l=t;super(n),this.data=s&&s[l(466)]||null,this.message=s&&s[l(623)]||null}}class bl extends or{constructor(n,s){let l=t,f={xzfyw:e[l(633)],QORCh:e.zkfzT,NMQkc:e[l(458)],vEVBD:e[l(1174)]};if(e[l(1773)](l(946),e[l(651)]))super(n),this.data=s&&s[l(466)]||null;else{let p=(l(1814)+l(394))[l(1317)]("|"),y=0;for(;;){switch(p[y++]){case"0":return _0x257a57;case"1":_0x3e7f26[_0x404eaf[yCNTZU.xzfyw]=5002]=yCNTZU.xzfyw;continue;case"2":_0x56160f[_0x2072ef[yCNTZU.QORCh]=5004]=yCNTZU[l(541)];continue;case"3":_0xdc5d5f[_0x37da62["MAX_RETR"+l(1066)+"R"]=5003]="MAX_RETR"+l(1066)+"R";continue;case"4":_0x44f6a7[_0x29cded[yCNTZU[l(1286)]]=5001]=yCNTZU[l(1286)];continue;case"5":_0x25ecc6[_0x65cc8d[yCNTZU[l(803)]]=5005]=yCNTZU[l(803)];continue}break}}}}function lt(a,{message:n,code:s,error:l}){return new ml(a,{message:n,code:s,error:l})}function mt(a,{code:n,reason:s,wasClean:l,willReconnect:f}){return new wl(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function El(a,{data:n,message:s}){return new yl(a,{data:n,message:s})}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,s){let l=t;this.endpoints=n,this[l(380)+"es"]=s,this[l(483)+"ndex"]=0,this["currentE"+l(1684)+l(1790)+"t"]=0}[t(1121)+t(614)+t(915)](){let n=t;this[n(483)+n(974)]=0,this[n(1592)+n(1684)+n(1790)+"t"]=0}[t(1087)+"es"](){let n=t;this["currentE"+n(1684)+"riesCount"]=0}[t(1712)+t(398)+"nt"](){let n=t;if(e[n(1313)](e[n(547)],e[n(931)]))return this[n(548)+"s"][this.currentIndex];if(this._options["disableAutoRecon"+n(671)]||this[n(1636)+n(979)])return;this[n(497)+"econnect"]()}[t(1712)+t(398)+t(1253)+t(1438)](){let n=t;return this[n(1592)+"ndpointT"+n(1790)+"t"]}[t(744)+t(1071)+"es"](){let n=t,s={MnAxb:function(l,f){return e[H(1650)](l,f)},SHXdB:function(l,f){return e[H(771)](l,f)},GdMkY:function(l,f){return e[H(983)](l,f)},GRTuR:function(l,f){return l+f},RkYLK:function(l,f){return e.kvnVl(l,f)},EVAsJ:function(l,f){return e[H(573)](l,f)},bwvJR:function(l,f){return e.zFPXJ(l,f)},iuUVQ:function(l,f){return l+f}};if(e[n(1773)](n(1840),e[n(471)]))return!!(e.dNXZT(this[n(483)+"ndex"],this.endpoints[n(1273)])||e[n(822)](this[n(483)+n(974)],e[n(473)](this[n(548)+"s"][n(1273)],1))&&this[n(1592)+n(1684)+n(1790)+"t"]===this[n(380)+"es"]);{let l=new _0xf732b0(s[n(462)](s.MnAxb(s[n(462)](_0x84e686[s[n(1481)](_0x4b904f,4)]<<24,s[n(1638)](_0x3cc195[s[n(1146)](_0x330cac,5)],16)),s[n(1638)](_0x3a0713[_0xc73691+6],8)),_0x3c7d97[_0x4ad8a1+7]),s[n(805)](s[n(1638)](_0x3cb4be[_0x98576e+0],24)|s[n(1638)](_0x537a9a[s[n(842)](_0x325ddf,1)],16),s[n(1029)](_0x171495[s[n(842)](_0x1dc267,2)],8))|_0x5e33be[_0x3ff6a6+3],!0);return _0x513d93+=8,{value:l,offset:s[n(730)](_0x5285ac,8)}}}[t(1400)+t(590)+"ointReachedMaxRetries"](){let n=t;if(e[n(502)](e[n(1540)],e[n(895)]))return this["currentI"+n(974)]==this[n(548)+"s"].length?!0:e[n(1708)](this[n(1592)+n(1684)+n(1790)+"t"],this[n(380)+"es"]);_0x5d1486(_0x501861,58),_0x727976(_0x2b063f,_0x3aed61)}[t(480)+t(727)+t(1664)+t(688)+t(1590)](){let n=t;return this[n(1592)+n(1684)+n(1790)+"t"]=1,this["currentI"+n(974)]++,this[n(548)+"s"][this["currentI"+n(974)]]}[t(1712)+"ntEndpointAndUpd"+t(1741)](){let n=t;return this.currentEndpointTriesCount++,this["getCurre"+n(398)+"nt"]()}}let ar=(e.VmWjT(e.PwRLE,typeof globalThis)&&e.oissD===globalThis[t(1397)+t(556)][t(493)]||e[t(1064)](e[t(414)],typeof window)&&e[t(1596)](t(1315),window[t(1397)+t(556)].name))&&e.geUWm(e[t(414)],typeof document),Ln=e[t(1489)](e[t(414)],typeof globalThis)&&(e[t(339)](t(631),globalThis[t(1397)+t(556)][t(493)])||e[t(349)](e[t(432)],globalThis[t(1397)+"tor"].name))&&e[t(414)]!=typeof tt,ii=(e[t(414)]!=typeof globalThis&&e[t(656)](e[t(1860)],globalThis["construc"+t(556)][t(493)])||t(1302)+"d"==typeof globalThis||e[t(1062)]("undefined",typeof globalThis)&&!!globalThis[t(745)+"Bridge"])&&e[t(1489)](e[t(414)],typeof wx),si=e[t(986)](e[t(414)],typeof globalThis)&&(e.LAaTP(e[t(432)],globalThis[t(1397)+t(556)][t(493)])||e[t(828)](e[t(1339)],globalThis[t(1397)+"tor"][t(493)])||e[t(1199)](e.UrhEB,globalThis[t(1397)+t(556)][t(493)]))&&e[t(1059)](e[t(414)],typeof self),sg=e.VmWjT(t(1302)+"d",typeof globalThis)&&e.Rzmia(e[t(1860)],globalThis.constructor[t(493)])&&e.NDahK(e[t(414)],typeof global)&&e[t(662)](e.LwPNh,global[t(1397)+"tor"][t(493)])&&e.PwRLE!=typeof process&&!!process[t(1788)];class Sa{constructor(){this._listeners={}}[t(778)](n,...s){let l=t,f=this._listeners[n];if(f)f[l(956)]()[l(540)](p=>p.fn.apply(p[l(1365)],s));else if(l(1298)===n&&!this.onerror){let p=s[l(1273)]&&s[0];if(p instanceof Error)throw p;let y=new Error(e[l(1679)]+(p?e[l(1387)](" (",p[l(623)])+")":""));throw y[l(1177)]=p,p}return this}[t(838)](n,s){let l=t;if(n===void 0)this[l(1532)+"rs"]={};else if(e[l(349)](void 0,s))this[l(1532)+"rs"][n]=null;else{let f=this[l(1532)+"rs"][n];if(f)for(let p=0;e[l(1021)](p,f.length);)e[l(1250)](f[p].fn,s)?f[l(1122)](p,1):++p}return this}on(n,s,l){let f=t;return(this[f(1532)+"rs"][n]||(this._listeners[n]=[]))[f(1097)]({fn:s,ctx:l||this}),this}}class og extends Sa{[t(457)+t(1350)+"age"](n){let s=t;return n[s(1259)]||n[s(1440)]?(s(454)+" "+(n[s(1259)]||"")+s(1793)+(n[s(1440)]||""))[s(677)]():JSON[s(870)+"y"](n)}constructor(n,s,l){let f=t;super(),this[f(911)]=null,ii&&wx[f(936)+f(1739)]&&(this[f(911)]=wx[f(936)+"ocket"]({url:n,protocols:s,header:l,fail:this["_createS"+f(921)+"lHandler"][f(977)](this),success:this[f(1178)+"ocketSuc"+f(660)+f(1446)][f(977)](this)})),Ln&&tt[f(936)+f(1739)]&&(this[f(911)]=tt[f(936)+"ocket"]({url:n,protocols:s,header:l,fail:this[f(1178)+f(921)+"lHandler"][f(977)](this),success:this[f(1178)+f(1713)+"cessHand"+f(1446)].bind(this)}))}[t(1178)+t(1713)+t(660)+t(1446)](){let n=t;Promise[n(1488)]()[n(1323)](()=>{let s=n,l={wWeva:function(f,p){return e[H(443)](f,p)},GIZcV:function(f,p){return f>=p},PUwDA:function(f,p){return e[H(1025)](f,p)},FEXHI:function(f,p){return e[H(1372)](f,p)},rIhFc:function(f,p){return f<<p},UVUiw:function(f,p){return f&p},LruYR:function(f,p){return f&p},bCois:function(f,p){return e[H(1682)](f,p)},nVAaL:function(f,p){return e.VyVmE(f,p)},EBcuP:function(f,p){return e[H(1700)](f,p)},fYxqS:function(f,p){return f<<p},VDYug:function(f,p){return e[H(534)](f,p)},MjrDl:function(f,p){return f&p},HczDS:function(f,p){return e[H(1079)](f,p)},SRaoE:function(f,p){return e.Dfktr(f,p)},kYhMb:function(f,p){return e[H(1779)](f,p)}};if(e[s(1149)](s(478),e.fAoBJ))this[s(1521)+s(1507)]();else{let f=_0x1db455[_0x2c3873++];if(l[s(1020)](f,127))_0x5f5222+=_0x56afa5[s(1155)+s(1366)](f);else if(l[s(531)](f,192)&&f<224)_0x275c63+=_0x32cdb6["fromChar"+s(1366)](l[s(961)](l[s(783)](31,f)<<6,l[s(783)](63,_0xf2718[_0x12ac67++])));else if(l[s(531)](f,224)&&f<240)_0x210f50+=_0x70283[s(1155)+"Code"](l.PUwDA(l[s(1656)](l[s(1844)](15,f),12),l[s(1656)](63&_0x266257[_0x5cc1ba++],6))|l[s(1055)](63,_0x5bfdb1[_0x4f3227++]));else if(l[s(860)](f,240)){let p=l[s(940)](l[s(1073)](l[s(1656)](l[s(1844)](7,f),18),l[s(331)](63&_0x1cf7b0[_0x5e14bd++],12))|l.rIhFc(l[s(1206)](63,_0xfe28dd[_0x4ca537++]),6)|l[s(485)](63,_0x58bd0a[_0x97049a++]),65536);_0x4b1370+=_0x2e4e42["fromChar"+s(1366)](l[s(591)](55296,p>>10)),_0x5ce667+=_0x41cf94.fromCharCode(l.SRaoE(56320,l.kYhMb(1023,p)))}}})}[t(1178)+t(921)+"lHandler"](n){let s=t,l={nsgyd:"error",lqSpD:function(f,p,y){return e[H(883)](f,p,y)},JcoRF:e[s(638)]};Promise[s(1488)]()[s(1323)](()=>{let f=s,p=lt(f(1298),{message:this[f(457)+f(1350)+"age"](n)});this[f(778)](l[f(1163)],p);let y=l[f(1857)](mt,l[f(1573)],{reason:this[f(457)+f(1350)+"age"](n)});this[f(778)](l[f(1573)],y)})}[t(1521)+t(1507)](){let n=t,s={lRMeH:function(l,f,p){return e[H(504)](l,f,p)},TvNLL:e[n(1483)],zVDSm:e.mLmrK};if(e.hcUcv(e[n(1526)],e[n(777)])){let l=s.lRMeH(_0x2a5ec2,n(1298),{message:_0x262ed5.message,code:_0x59a777.OPEN_ERROR,error:_0xf0081});this[n(570)+n(717)+n(1172)](l)}else this[n(911)][n(444)](l=>{let f=n;this[f(778)](s[f(716)],vl(s[f(716)],{...l,data:l[f(1259)]||""}))}),this[n(911)][n(464)](l=>{let f=n;this[f(778)](e[f(638)],e[f(1729)](mt,e[f(638)],{...l}))}),this[n(911)].onMessage(l=>{let f=n;this[f(778)](s[f(427)],s[f(1811)](El,f(623),{...l}))}),this[n(911)][n(1699)](l=>{let f=n;this[f(778)](f(1298),e.UDBMw(lt,e[f(1318)],{...l,message:l[f(1259)]||""}))})}[t(1642)](n){let s=t;if(e[s(770)](e[s(792)],e[s(792)]))return!!_0x3808f3?.[s(558)](l=>l[s(412)]===_0x4a9f62&&l[s(897)]===_0x4d9217);if(e[s(1392)](n,Uint8Array)){let l=n[s(1683)][s(956)](n[s(489)+"et"],e.KtqQc(n[s(1474)+"th"],n.byteOffset));this[s(911)]&&this[s(911)].send({data:l,fail:f=>{let p=s;this[p(778)]("error",e[p(1525)](lt,e[p(1318)],{message:this[p(457)+p(1350)+p(1702)](f)}))}})}else this[s(911)]&&this[s(911)][s(1642)]({data:n,fail:l=>{let f=s;this[f(778)](f(1298),lt("error",{message:this[f(457)+f(1350)+f(1702)](l)}))}})}[t(1854)](n,s){let l=t;this[l(911)]&&this[l(911)][l(1854)]({code:n,reason:s})}[t(1803)+t(1262)](n,s){this.on(n,s)}["removeEv"+t(442)+t(434)](n,s){this[t(838)](n,s)}get readyState(){let n=t;return this[n(911)][n(1841)+"te"]}get[t(1393)+"pe"](){let n=t;return this[n(911)][n(1393)+"pe"]}set[t(1393)+"pe"](n){}get[t(1661)](){let n=t;if(e[n(822)](n(1089),e[n(505)]))return this[n(911)][n(1661)];_0x420f9a=_0x58bd8c.charCodeAt(_0x326ab5),e[n(703)](_0x186c13,128)?_0x679ed8+=1:e[n(841)](_0x1f494f,2048)?_0x5d561d+=2:e[n(1149)](64512&_0x382268,55296)&&e[n(325)](64512,_0x1dd054[n(711)+"At"](_0x134b8a+1))===56320?(++_0x29ad6a,_0x4faa4b+=4):_0x454e3c+=3}get[t(773)](){let n=t;return this[n(911)][n(773)]}get[t(731)+"ns"](){let n=t;return this._socket[n(731)+"ns"]}get[t(751)+t(441)](){return 0}}function ag(a,n){let s=t;if(e[s(1527)](e[s(1288)],s(1827))){let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[s(416)](_0x58fe8e),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]))/[s(416)](_0x1e0ac2);return l?e.vEUkk(_0x43b10b,_0x1ed3e6):f?e[s(919)](_0x1bfd5f,_0x773cb0):s(1478)+s(1478)+s(1478)+s(1478)}else{if(n)return new n(a[s(1661)],a[s(773)]);if(e.zIlin(ii,Ln))return new og(a[s(1661)],a[s(773)],a.headers);if(e[s(1691)](ar,si)&&s(1302)+"d"!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(1661)],a[s(773)+"s"])}}function cg(a){let n=t,s={wFoRW:e[n(638)],dhyca:e[n(814)]};if(e.hrBLV===e[n(1649)]){let l=e[n(352)][n(1317)]("|"),f=0;for(;;){switch(l[f++]){case"0":if(a)return!0;continue;case"1":if(e[n(376)](ar,si)&&e[n(718)](e[n(414)],typeof WebSocket)&&WebSocket)return!0;continue;case"2":if(Ln&&tt["connectS"+n(1739)])return!0;continue;case"3":return!1;case"4":if(ii&&wx.connectSocket)return!0;continue}break}}else _0x2ce8d6&&_0x5b3bbf["addEvent"+n(1262)](BRpnnq.wFoRW,()=>_0x7674f7()),_0x1a15d1&&_0xdc403a[n(1803)+n(1262)](BRpnnq.dhyca,()=>_0x254753())}function Il(a,n,s){let l=t,f=-1;async function p(y){let g=H;return e.klHOh(y,f)?Promise.reject(new Error(g(1413)+g(775)+g(624)+g(463)+"process")):(f=y,y===s[g(1273)]?Promise[g(1488)]():s[y][g(977)](a)(n,p[g(977)](null,y+1)))}e[l(1222)](p,0)}function Al(a){let n=t,s=0,l=0;for(let f=0;e[n(1208)](f,a[n(1273)]);++f)l=a[n(711)+"At"](f),e.QFIIL(l,128)?s+=1:e[n(459)](l,2048)?s+=2:e[n(1543)](e[n(1677)](64512,l),55296)&&e[n(938)](e[n(1158)](64512,a[n(711)+"At"](e[n(1654)](f,1))),56320)?(++f,s+=4):s+=3;return s}function kl(a,n,s){let l=t;if(e[l(532)](s-n,1))return"";let f="";for(let p=n;p<s;){if(e.HdOLr!==l(1399))return this[l(928)].clear();{let y=a[p++];if(y<=127)f+=String[l(1155)+l(1366)](y);else if(y>=192&&e.GPxpd(y,224))f+=String[l(1155)+l(1366)](e.qLVRV(e[l(1134)](e.pDLMY(31,y),6),e[l(1460)](63,a[p++])));else if(e[l(1212)](y,224)&&e[l(703)](y,240))f+=String[l(1155)+l(1366)](e.qsWTU(e[l(1134)](e.nZgrg(15,y),12)|e.zFPXJ(e.YDVFS(63,a[p++]),6),e[l(926)](63,a[p++])));else if(e[l(1711)](y,240)){let g=e[l(473)](e[l(1092)](e[l(832)](e.aSAhk(e[l(1194)](7,y),18),e.UyjCT(63,a[p++])<<12),e[l(1376)](e[l(739)](63,a[p++]),6))|e[l(1502)](63,a[p++]),65536);f+=String["fromChar"+l(1366)](e[l(1094)](55296,g>>10)),f+=String[l(1155)+l(1366)](56320+e.MRNvc(1023,g))}}}return f}function Ia(a,n,s){let l=t,f=s,p,y;for(let g=0;e.iJgkv(g,a.length);++g)if(p=a[l(711)+"At"](g),e.OVZkt(p,128))n[s++]=p;else if(e[l(1625)](p,2048))n[s++]=e[l(1761)](e.nhNJJ(p,6),192),n[s++]=63&p|128;else if(e[l(781)](64512&p,55296)&&e[l(809)](64512,y=a.charCodeAt(g+1))===56320){let T=e[l(1637)][l(1317)]("|"),C=0;for(;;){switch(T[C++]){case"0":n[s++]=e[l(1280)](e.iIEJe(p,6),63)|128;continue;case"1":n[s++]=e[l(1041)](e[l(1342)](e[l(1631)](p,12),63),128);continue;case"2":p=e[l(875)](e[l(1802)](65536,(1023&p)<<10),e[l(341)](1023,y));continue;case"3":n[s++]=e[l(1701)](p,18)|240;continue;case"4":n[s++]=e[l(1267)](63,p)|128;continue;case"5":++g;continue}break}}else n[s++]=e.twrJP(e.djjMv(p,12),224),n[s++]=e[l(392)](e[l(1631)](p,6)&63,128),n[s++]=e[l(1761)](e[l(976)](63,p),128);return e[l(758)](s,f)}async function Tl(a){let n=t,s={QNItx:e[n(1050)],NUnJp:e.ceopx};if(n(884)==typeof a)if(e.QTRJZ(e[n(963)],e.GIvEb)){let l=new Uint8Array(e[n(1764)](Al,a));return Ia(a,l,0),l}else{if(this[n(1636)+n(979)]=!0,this[n(1499)+n(830)](),this[n(388)+n(415)](),this[n(1600)+n(819)+n(1262)](),this["_QoSMana"+n(332)]?.[n(1375)](),!this[n(975)])return void this[n(617)](s[n(333)]);if(this[n(975)][n(1841)+"te"]===this[n(1611)]||this[n(975)][n(1841)+"te"]===this[n(1354)])return void this[n(617)](s[n(343)]);this[n(1783)+n(1395)+"t"](_0x4084eb,_0x24ee1c)}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a[n(1683)],a[n(489)+"et"],a[n(1474)+"th"])}function dg(a){let n=t,s={EMTDl:function(l,f){return l||f}};try{return e.FIvbc!=typeof a&&(e.laMiX(a,ArrayBuffer)||a[n(1683)]&&e[n(1800)](a.buffer,ArrayBuffer))||e[n(1064)](n(884),typeof a)?"":(JSON[n(1740)](a),n(1798)+n(859))}catch{if(e[n(934)](e[n(387)],n(958)))return e[n(1137)](n(884),typeof a)?e.bvvas:"";{let l=this._qosDB.getItem(this[n(1244)]),f=_0xfb386c[n(1740)](s.EMTDl(l,"{}"));return _0x569774[n(373)](f)}}}let lg=(a,n)=>{let s=t;switch(a){case e[s(1030)]:case e.dkCwL:return{[s(1369)+a]:1,"x-tt-env":n};default:return{}}};class ug{constructor(n){let s=t;this[s(322)+s(1438)]=n,this[s(472)]=0}[t(1140)](){let n=t;this[n(472)]++}[t(744)+t(1221)+"nt"](){let n=t;return e.gjaLC(this.count,this["maxLossC"+n(1438)])}[t(468)+"nter"](n=0){let s=t;if(e[s(499)](s(1687),e.NmIYz))this[s(322)+s(1438)]=n,this[s(472)]=0;else return _0x5c5afb[_0x131bb4]=_0x45dac9,!0}}async function fg(a){let n=t,s={DUShc:function(l,f){return e.ottRD(l,f)},WczKe:e.auGAP,qENFe:function(l,f){return e[H(1524)](l,f)},rEcSY:e[n(1136)],VcDFg:function(l,f){return e.FAORE(l,f)},lIFJo:e[n(428)],bqsXl:e[n(1754)],fzfmB:e[n(569)]};return e[n(1543)](n(1061),e[n(1546)])?new Promise(l=>{let f=n;if(!ar)return s.qENFe(l,s[f(995)]);try{let p=document[f(618)+f(1575)](f(620));window.frontierJSONP=y=>{let g=f;document.body["removeCh"+g(508)](p),window[g(1148)+g(1742)]=void 0,s.DUShc(l,y&&y[g(335)]||s[g(995)])},p.type=s[f(1019)],p[f(1245)]=s.VcDFg(a[f(795)](/^ws/,s[f(752)]),s[f(1787)]);try{document[f(1694)][f(1356)+"ild"](p)}catch{document.body.removeChild(p)}}catch{if(s[f(404)]===s.fzfmB)window[f(1148)+f(1742)]=void 0,s[f(686)](l,s[f(995)]);else return new _0x540230(_0x5ac3d5,{message:_0x5e0ff9,code:_0x3da178,error:_0xa93031})}}):(_0x1c169f[n(772)+"t8"]?_0x480a45.writeUint8(_0xd3fb3d,_0x5333e0):_0x3ac259[_0x10ff28]=255&_0x4dd2cb,_0x5226b2+1)}function cn(a,n,s){let l=t;return!!a?.find(f=>f[l(412)]===n&&f[l(897)]===s)}function cr(a,n){let s=t;return a?.[s(558)](l=>l[s(412)]===n)?.value}let Aa=null;async function hg(){let a=t;return Aa||(Aa=Promise[a(1488)]()[a(1323)](Ut[a(977)](Ut,a(1614)))),Aa}class xg extends Sa{constructor(n,s){let l=t;e[l(1666)](e[l(1493)],e.KCrnt)?(super(),this[l(1441)]=n,this[l(661)]=s,this[l(928)]=void 0,this[l(816)+"mise"]=null):(e.CFrYo(_0x32b6c9,_0x34d9f6,24),_0x268e06(_0x1440b2,_0x14ef3a(_0x47426f)))}async[t(1083)](){await this[t(1443)]()}async[t(1443)](){let n=t;if(!this[n(928)]){if(this[n(816)+n(1076)])return this[n(816)+n(1076)];try{let s=this._dbName,l=this[n(661)];this[n(816)+"mise"]=(async()=>{let f=n,{openDB:p}=await e[f(346)](hg);this[f(928)]=await e[f(855)](p,f(1148)+"_"+s,1,{upgrade(y){let g=f;y[g(1261)+g(793)+"e"](s,{keyPath:l})}})})(),await this[n(816)+n(1076)]}catch(s){console[n(446)](s)}finally{this._initPromise=null}}}async get(n){let s=t;try{return await this[s(1443)](),this[s(928)]?.[s(1519)](this[s(1441)],n)}catch(l){e[s(927)](e.tyWwt,e[s(1759)])?(this[s(1660)]=!0,this[s(1396)]=0|_0x36884f,this[s(1228)]=e[s(1770)](0,_0x117b3e),this[s(692)]=!!_0xa180b9):console[s(446)](l)}}async[t(1487)](n,s){let l=t;return await this[l(1443)](),this[l(928)]?.[l(1131)](this[l(1441)],n)}async[t(1192)](n){let s=t;try{return await this._init(),this[s(928)]?.[s(371)](this[s(1441)],n)}catch(l){console[s(446)](l)}}async[t(650)](){let n=t;try{return await this[n(1443)](),this[n(928)]?.[n(650)](this[n(1441)])}catch(s){console[n(446)](s)}}async[t(1270)](){let n=t;return await this[n(1443)](),this[n(928)]?.[n(1252)+"ys"](this[n(1441)])}async getAll(){let n=t;return await this[n(1443)](),this[n(928)]?.[n(498)](this[n(1441)])}async[t(1375)](){let n=t;try{this[n(928)]?.[n(1854)](),this[n(928)]=void 0}catch(s){console[n(446)](s)}}get[t(806)](){let n=t;try{return!!this[n(928)]}catch(s){return console[n(446)](s),!1}}}class pg{constructor(n,s){let l=t;this._DBName=n,this._pathKey=s,this[l(928)]=localStorage}async openDB(){}get[t(1244)](){let n=t;return n(1148)+"_"+this[n(1471)]}async get(n){let s=t,l=this[s(928)][s(469)](this[s(1244)]);return JSON[s(1740)](e[s(1363)](l,"{}"))[n]}async set(n,s){let l=t,f=this[l(928)][l(469)](this[l(1244)]),p=JSON.parse(e[l(856)](f,"{}"));return p[s||n[this[l(554)]]]=n,this[l(928)].setItem(this._prefix,JSON[l(870)+"y"](p)),s||n[this._pathKey]}async[t(1192)](n){let s=t;if(e[s(502)](e[s(1113)],e[s(553)])){let l=this._qosDB[s(469)](this[s(1244)]),f=JSON[s(1740)](e[s(856)](l,"{}"));return f[n]=void 0,this[s(928)][s(1043)](this[s(1244)],JSON[s(870)+"y"](f))}else _0xa39c0a&&this["_cursorM"+s(1200)][s(351)+"rsorFile"+s(1806)](_0x207d34)}async[t(650)](){let n=t,s={BztUP:"AbortError",oUcUL:function(l){return e[H(1349)](l)}};if(e[n(1040)](e.HtBqo,e[n(1202)]))return this[n(928)][n(650)]();_0x2cd639(_0x4aac65[n(1298)]||new _0x46f5df(cqLERv[n(695)],cqLERv[n(695)])),cqLERv[n(1776)](_0x164a7d)}async[t(1270)](){let n=t,s=this[n(928)].getItem(this._prefix),l=JSON[n(1740)](e[n(1363)](s,"{}"));return Object[n(1270)](l)}async[t(498)](){let n=t;if(e[n(1115)]!==e[n(1115)])this[n(816)+"mise"]=null;else{let s=this[n(928)].getItem(this[n(1244)]),l=JSON[n(1740)](e[n(856)](s,"{}"));return Object[n(373)](l)}}closeDB(){return Promise.resolve()}get[t(806)](){return!!this[t(928)]}}class gg{constructor(n,s){let l=t;this._DBName=n,this._pathKey=s,this[l(928)]=Ln?tt:ii?wx:null}async[t(1083)](){}get[t(1244)](){return"frontier_"+this[t(1471)]}async[t(1519)](n){let s=t,l=this._qosDB[s(1203)+s(391)](this[s(1244)]);return JSON[s(1740)](e[s(1258)](l,"{}"))[n]}async[t(1487)](n,s){let l=t,f=this._qosDB[l(1203)+l(391)](this[l(1244)]),p=JSON[l(1740)](e[l(1258)](f,"{}"));return p[s||n[this._pathKey]]=n,this[l(928)][l(364)+l(391)](this[l(1244)],JSON[l(870)+"y"](p)),s||n[this[l(554)]]}async[t(1192)](n){let s=t;if(e.wZbnP(s(1373),e[s(533)]))return"frontier_"+this._DBName;{let l=this._qosDB["getStora"+s(391)](this._prefix),f=JSON[s(1740)](e.Kjuvf(l,"{}"));return f[n]=void 0,this[s(928)][s(364)+s(391)](this[s(1244)],JSON[s(870)+"y"](f))}}async[t(650)](){let n=t;return this._qosDB[n(572)+n(1236)]()}async keys(){let n=t,s=this[n(928)][n(1203)+n(1462)+"nc"](this._prefix),l=JSON[n(1740)](e[n(1333)](s,"{}"));return Object[n(1270)](l)}async[t(498)](){let n=t,s=this._qosDB["getStora"+n(1462)+"nc"](this[n(1244)]),l=JSON[n(1740)](e.NoMLa(s,"{}"));return Object[n(373)](l)}closeDB(){return Promise[t(1488)]()}get[t(806)](){let n=t;if(e[n(913)](e[n(1463)],e[n(347)]))return!!this[n(928)];this[n(975)]&&this._ws[n(1642)](_0x4b8966),this[n(617)](e[n(1310)],_0x41a9fd)}}function Cl(a,n){let s=t;if(e[s(934)]("pftNH","EErim"))return _0x339018&&(_0x4d894e=(0,_0x309214[_0x2b834e(_0x276ec9)[0]])(_0x33bd28=0)),_0x28ecac;if(e[s(1539)](Ln,Ln))return new gg(a,n);if((ar||si)&&e[s(414)]!=typeof indexedDB)return new xg(a,n);if(e[s(1579)](ar,si)&&e[s(1064)](s(1302)+"d",typeof localStorage))return new pg(a,n);throw new Error(e[s(1604)])}class mg{constructor(){let n=t;this["_interva"+n(1619)+"Id"]=null,this[n(669)+"l"]=36e5,this._qosDB=e[n(991)](Cl,e[n(1129)],e[n(521)])}async[t(669)+t(1852)](){let n=t;e[n(796)](clearInterval,this[n(669)+"lTimeoutId"]),this._intervalTimeoutId=e[n(696)](setInterval,()=>{this.flushExpired()},this[n(669)+"l"])}async[t(1083)](){let n=t;await this[n(928)].openDB()[n(1323)](()=>{let s=n;this[s(669)+s(1852)]()})}async[t(419)+t(1337)](){let n=t;(await this[n(928)]?.[n(498)]()||[])[n(1548)](({timestamp:f})=>f<Date[n(370)]())[n(540)](f=>{let p=n;this[p(928)]?.[p(1192)](f[p(1052)+"id"])})}async[t(1192)](n){return this[t(928)]?.del(n)}async[t(1487)](n,s){let l=t;if(e[l(589)](e[l(1612)],l(1560)))return this._qosDB?.[l(1487)]({message_id:n,timestamp:s});this[l(1166)+"T"]||this._isMiniWX?this._onPageNetWorkChange():this[l(330)+"er"]&&this["_initGlo"+l(819)+"Listener"]()}async[t(1519)](n){return this[t(928)]?.get(n)}async[t(1375)](){let n=t;e[n(512)](clearInterval,this[n(669)+"lTimeoutId"]),await this[n(928)]?.[n(1375)]()}get[t(806)](){let n=t,s={DYHNe:function(l,f,p,y){return e[H(855)](l,f,p,y)}};if(e[n(813)]===e[n(1576)])s.DYHNe(_0x4ca339,this,_0x1aaa95,[_0x3a3606,_0x537aff,_0x249e70]);else return this[n(928)]?.[n(806)]}}function ka(a){let n=t,s=!!this._options[n(1824)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(1210)](cn,a[n(623)].headers,e[n(578)],"2"),f=l&&e[n(1484)](cn,a.message[n(1498)],e[n(1006)],"1"),p=l&&e.XYvxA(cn,a.message[n(1498)],e.cWEpP,"1"),y=p?cr(a[n(623)][n(1498)],e[n(899)])?.[n(1317)](",")[n(1548)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:y}}async function Rl(){let a=t;return this["_QoSMana"+a(332)]||(this[a(1300)+a(332)]=new mg),this[a(1300)+a(332)][a(806)]||await this["_QoSMana"+a(332)].openDB(),this[a(1300)+a(332)]}async function wg(a,n){let s=t,{enableAutoAck:l}=this[s(374)],f=e[s(855)](cn,a.message[s(1498)],e[s(1145)],"1"),p=e[s(855)](cn,a.message[s(1498)],e[s(585)],"1"),y=ka[s(1398)](this,a);if(e.wNyiB(l,f)){let{SeqID:g,LogID:T,service:C,LogIDNew:L,method:B}=a[s(623)];this[s(724)]({SeqID:g,LogID:T,LogIDNew:L,service:C,method:B,headers:[{key:e[s(585)],value:"1"},{key:e[s(1609)],value:e.zIlin(L,"")},{key:e[s(1075)],value:"0"}]})}p&&!y[s(1383)]&&this[s(570)+s(1035)+s(496)](a),e[s(1120)](n)}async function _g(a,n){let s=t;this._debug(e[s(405)],a.message),n()}async function yg(a,n){let s=t;if(e.tbmJw(e[s(1085)],e[s(1095)])){if(e.MBBHL(e[s(539)],typeof _0x182b19)){let l=new _0x2b3bea(e[s(811)](_0x1378d6,_0x37dad7));return e.mjsMR(_0x4dbd6a,_0x31b47d,l,0),l}return e[s(1227)](_0x57211f,_0x2d233c)?new _0x133037(_0x36c7f2):new _0x5002cd(_0x56f7a3[s(1683)],_0x3d62e7[s(489)+"et"],_0x2d211c[s(1474)+"th"])}else{let l=e.OFfii(sn,await e[s(666)](Tl,a[s(466)]));try{if(e[s(987)](l[s(448)],Uint8Array)){let f=this._options.payloadEncoding instanceof Object?{force:!!this[s(374)][s(1403)+"ncoding"][s(1553)],encoding:this[s(374)]["payloadE"+s(1781)][s(1278)]?this[s(374)].payloadEncoding[s(1278)][s(795)](/\s/g,"")[s(1513)+s(1190)]():""}:{force:!1,encoding:this._options[s(1403)+"ncoding"]?this[s(374)][s(1403)+s(1781)][s(795)](/\s/g,"")[s(1513)+s(1190)]():""},p=l[s(1403)+s(1781)]?l[s(1403)+s(1781)][s(795)](/\s/g,"")["toLowerC"+s(1190)]():"",y=e[s(1748)](this._options[s(896)+s(1230)],Object)?{force:!!this._options[s(896)+"ype"][s(1553)],type:this._options[s(896)+s(1230)][s(321)]?this._options[s(896)+s(1230)][s(321)].replace(/\s/g,"")["toLowerC"+s(1190)]():""}:{force:!1,type:this[s(374)]["payloadT"+s(1230)]?this[s(374)]["payloadT"+s(1230)][s(795)](/\s/g,"")[s(1513)+s(1190)]():""},g=l[s(896)+s(1230)]?l[s(896)+s(1230)][s(795)](/\s/g,"")[s(1513)+"ase"]():"",T=y[s(1553)]?y[s(321)]:g||y.type,C=f[s(1553)]?f[s(1278)]:p||f[s(1278)],L=["text/plain;charset=utf-8",e[s(1766)],e.dftXR,e.FIvbc],B=[e[s(1496)],e[s(613)]];this[s(374)][s(1681)+"ansformT"+s(689)+"ad"]&&L[s(1459)](T)&&(!C||B[s(1459)](C))?l[s(1181)+s(1765)]=e.HXxfR(kl,l[s(448)],0,l[s(448)][s(1474)+"th"]):l["textPayl"+s(1765)]=""}else l[s(1181)+s(1765)]=""}catch(f){e.jYyIe(s(1836),s(1836))?(_0x3c14c9=e[s(527)](_0x213062,_0x3c0815),_0x5dd2b6|=e.ZLnbR(127&_0x4cdd2f,14),e[s(1384)](128,_0x3b636c)&&(_0x4159f4=e[s(877)](_0x4758f0,_0x2512d4),_0xd65037|=e[s(1343)](e[s(988)](127,_0x119885),21),e[s(1767)](128,_0x570001)&&(_0x300b51=_0x3d4e29(_0x3585f7),_0x14415f=e.dyikf(127,_0x17c8aa),e.aZsTX(128,_0x2a4156)&&(_0x1c605a=e[s(1039)](_0x4e408c,_0x15cf57),_0x4f6303|=e[s(1673)](127,_0x16be1a)<<7)))):(l[s(1181)+s(1765)]="",console.log(f))}a[s(623)]=l,e.lNyKh(n)}}function bg(a,n,s){let l=t,f={BofQt:function(C,L){return e[H(1746)](C,L)},sIYwQ:function(C,L){return e[H(922)](C,L)},DjYHr:function(C,L){return e[H(965)](C,L)},GiDKM:function(C,L){return C+L},YgUWU:function(C,L){return e[H(1263)](C,L)},YlOVO:function(C,L){return e.QkrcJ(C,L)},Jqpbj:function(C,L){return e[H(937)](C,L)}},p=e[l(1691)](s,8192),y=e[l(559)](p,1),g=null,T=p;return function(C){let L=l;if(f[L(1322)](C,1)||f.sIYwQ(C,y))return f[L(1720)](a,C);f[L(1780)](f[L(1653)](T,C),p)&&(g=f[L(1282)](a,p),T=0);let B=n[L(1398)](g,T,T+=C);return f.YlOVO(7,T)&&(T=f[L(1653)](f[L(990)](7,T),1)),B}}let Eg=4294967295;function vg(a,n,s){let l=t;return RangeError(e[l(411)](e[l(1311)](e.CRgof(e[l(1387)](e[l(1031)](e[l(808)],a),e.jjuHv),n||1),e[l(1706)]),s))}function Sg(a,n,s){let l=t;if(e.RAAAK(s,Eg))throw new Error(e[l(1296)]);let f=3;for(;e.uTsTm(f,0);){let p=e[l(1182)](255,s);e[l(1210)](Ca,p,a,e[l(355)](n,f)),s>>>=8,f--}return e[l(1346)](n,4)}function Ig(a,n){let s=t,l=0,f=n,p=e[s(608)](n,4);for(;f<p;){let{value:y,offset:g}=e[s(1271)](Ta,a,f);f=g,l=e.ItlGE(e[s(378)](l,8),0),l+=y}return{value:l,offset:p}}function Ag(a,n,s){let l=t,f={HotqG:function(p,y){return e[H(1674)](p,y)},sgMwk:function(p,y){return p<<y},KIdes:function(p,y){return e[H(1128)](p,y)},ZyAxH:function(p,y){return e.aZsTX(p,y)},ELhXs:function(p,y){return e[H(965)](p,y)},aoqAh:function(p,y){return e[H(1795)](p,y)},CdJHC:function(p,y){return e[H(1263)](p,y)},qRNlK:function(p,y){return e[H(326)](p,y)},veEJV:function(p,y){return e.SdnbO(p,y)}};if(e[l(1345)]("CtPtY",e[l(1028)]))_0x39b427=HPxzzd[l(1380)](_0x2d7a10,_0x546458),_0x3ac6df|=HPxzzd[l(776)](HPxzzd[l(1774)](127,_0x3f2524),21),HPxzzd[l(628)](128,_0x4eaf79)&&(_0xe4fb97=HPxzzd[l(833)](_0x478c37,_0xebf7be),_0x5de058=HPxzzd[l(909)](127,_0x18ae68),128&_0xb58847&&(_0x34eb9a=HPxzzd[l(600)](_0x375f21,_0x5ee3c5),_0x56df71|=HPxzzd[l(694)](HPxzzd.veEJV(127,_0x3de40e),7)));else{let p=e[l(453)][l(1317)]("|"),y=0;for(;;){switch(p[y++]){case"0":if(n.utf8Write)return e[l(1105)](n[l(1453)+"e"](a,s),s);continue;case"1":if(n.write)return n[l(431)](a,s)+s;continue;case"2":if(!a)return s;continue;case"3":if(e[l(367)](a[l(1273)],40))return e.AYShd(Ia,a,n,s)+s;continue;case"4":return e[l(968)](Ia,a,n,s)+s}break}}}function kg(a,n){let s=t;if(e[s(1345)]("RkXOw",s(1626))){let l=new ue(e.eXWwJ(e[s(1041)](e[s(1784)](a[e[s(1065)](n,4)]<<24,e.wIIgw(a[e[s(1105)](n,5)],16)),e[s(945)](a[e[s(1657)](n,6)],8)),a[n+7]),e[s(1804)](e[s(746)](a[e[s(821)](n,0)],24),e.ZhITr(a[e[s(513)](n,1)],16))|e[s(983)](a[e[s(1409)](n,2)],8)|a[e[s(1689)](n,3)],!0);return n+=8,{value:l,offset:e[s(1669)](n,8)}}else{let l=255&_0x2fdae4;_0x21c974(l,_0x3dff95,e[s(1846)](_0x42df02,_0x2185e0)),_0x40047a>>>=8,_0x1ea36d--}}function Tg(a,n,s){let l=t,f=a[l(1396)],p=a[l(1228)];return n[s]=e[l(1045)](p,24),n[e[l(1685)](s,1)]=e[l(1819)](e.vrLAG(p,16),255),n[e[l(564)](s,2)]=e[l(809)](e[l(529)](p,8),255),n[e.RSpuK(s,3)]=e[l(1732)](255,p),n[e.GnlEy(s,4)]=f>>>24,n[e[l(1651)](s,5)]=e[l(1128)](f>>>16,255),n[e[l(725)](s,6)]=e.yADWF(f>>>8,255),n[e[l(1079)](s,7)]=e[l(1508)](255,f),s+=8,s}function Ta(a,n){let s=t;return e.ChPyu(e[s(1168)],e[s(1168)])?_0x18bb9d["objectSt"+s(1727)]||_0x3fad91[s(1519)](_0x3b31c3):a[s(985)+"8"]?{value:a.readUInt8(n),offset:e[s(1351)](n,1)}:{value:255&a[n],offset:e[s(1775)](n,1)}}function Ca(a,n,s){let l=t;return e[l(971)](e[l(1418)],"eGWMO")?(n[l(772)+"t8"]?n[l(772)+"t8"](a,s):n[s]=e[l(1008)](255,a),e[l(1094)](s,1)):_0x28d441[l(1488)]()}let Cg=function(a){return new Uint8Array(a)},Rg=e[t(1457)](e[t(414)],typeof Buffer)?Buffer["allocUns"+t(1815)]:bg(Cg,Uint8Array.prototype[t(790)]);(()=>{let a=t,n={XGNeB:function(l,f){return l(f)},IlHAm:function(l,f){return e[H(1801)](l,f)},fwiyk:function(l,f){return e[H(445)](l,f)},vWfZj:function(l,f){return l+f},MVCst:function(l,f){return e[H(740)](l,f)},jYBbs:function(l,f){return l%f},QtgVc:function(l,f){return e[H(1347)](l,f)},xBccy:function(l,f){return l/f},iktnB:function(l,f){return l>>>f},cTEvU:function(l,f){return e.VEEmI(l,f)},QqgMl:function(l,f){return e.boTJX(l,f)},IuNGY:function(l,f){return e[H(1139)](l,f)},Osfyo:function(l,f){return l|f},TAMbj:function(l,f){return l|f},FyvDb:function(l,f){return e.kvnVl(l,f)},VMRoW:function(l,f){return l<<f},szBgm:function(l,f){return e[H(943)](l,f)},CnzqW:function(l,f){return e[H(657)](l,f)},xdZut:a(1353),snoTo:function(l,f,p,y){return e[a(1338)](l,f,p,y)}},s=4294967295;return function(l,f,p=!0){let y=a;if(s=n.iktnB(127&l[f],0),n[y(1407)](l[f++],128))return{value:p?s:n[y(1060)](0,s),offset:f};if(s=n.iktnB(n[y(1060)](s,n[y(1734)](127,l[f])<<7),0),n[y(1407)](l[f++],128))return{value:p?s:0|s,offset:f};if(s=n.IuNGY(n[y(980)](s,(127&l[f])<<14),0),l[f++]<128)return{value:p?s:n[y(354)](0,s),offset:f};if(s=n.iktnB(n.TAMbj(s,(127&l[f])<<21),0),n.cTEvU(l[f++],128))return{value:p?s:0|s,offset:f};if(s=n[y(1751)](n[y(741)](s,n[y(658)](n[y(876)](15,l[f]),28)),0),n.cTEvU(l[f++],128))return{value:p?s:n[y(1550)](0,s),offset:f};if((f+=5)>l[y(1273)]){if(n.xdZut===n.xdZut)throw f=l.length,n[y(707)](vg,f,10,l[y(1273)]);if(TLOqIT[y(753)](_0x2ff709,_0x5385a5))return _0x3dc7b8?_0x5b421c:_0x2ce4b0;if(_0x5bf74d){if(_0x2379e4>=_0x5578e0)return _0x31679a}else{if(TLOqIT[y(1293)](_0x27c8fa,-_0x1652a8))return _0x2ff7cc;if(TLOqIT[y(1845)](TLOqIT[y(1117)](_0x123171,1),_0x2b9f03))return _0x3354a9}return _0x104534[y(1616)](TLOqIT[y(1060)](TLOqIT[y(1007)](_0x170271,_0x120503),0),TLOqIT.QtgVc(TLOqIT[y(1662)](_0x8c044a,_0x55ff8a),0),_0x5cbd41)}return{value:p?s:n.MVCst(0,s),offset:f}}})();let Dg=16,Ra=32;function Pg(a){let n=t;if(e.BPRVA(e[n(383)],e.hflEt)){let s=0,l={};for(let f=0;e.KsTzN(f,a[n(1273)]);f++)l[a[f][n(1542)+"ame"]]=e[n(774)](Al,a[f][n(1542)+n(1470)]),s+=14+l[a[f][n(1542)+n(1470)]];return[s,l]}else return n(1148)+"_"+this[n(1471)]}function Dl(a,n,s){let l=t,[f,p]=e.xlPex(Pg,a),y=e.hQMOE(Rg,f),g=0;return a[l(540)](T=>{let C=l;console[C(446)](e[C(1833)],T,T[C(421)]),g=Ca(0,y,g),console[C(446)](C(579),g),g=e.VdjvC(Sg,y,g,T[C(421)]||0),console.log(C(421),g),g=Ca(p[T[C(1542)+"ame"]],y,g),console[C(446)](C(879)+"name",g),g=e[C(1338)](Ag,T[C(1542)+C(1470)],y,g),console[C(446)](e[C(1423)],g),g=e[C(1381)](Tg,ue[C(845)+"er"](T[C(959)]||n),y,g),console[C(446)](e[C(1193)],g)}),{frameType:Ra,headers:[{key:e.INPFo,value:s}],payload:y}}function Og(a){let n=t,s=0,l=[];for(;e[n(1570)](s,a[n(1474)+"th"]);){let{offset:f}=e[n(1729)](Ta,a,s);s=f;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:g}=e.nHWBI(Ig,a,s);p[n(421)]=y,s=g;let{value:T,offset:C}=Ta(a,s);s=C,p[n(1542)+n(1470)]=e[n(1109)](kl,a,s,e.KkcLO(s,T)),s+=T;let{value:L,offset:B}=e.nHWBI(kg,a,s);p[n(959)]=L.toNumber(),s=B,l[n(1097)](p)}return l}function Lg(){let a=t;return{frameType:Ra,headers:[{key:e[a(916)],value:e[a(1320)]}],payload:void 0}}class Ng{constructor(n,s,l){let f=t;this._cursorNameSpace=n,this._cursorFileName=s,this[f(964)+f(1348)]=l,this[f(928)]=e[f(1525)](Cl,this[f(1229)+"ameSpace"],f(1542)+f(1470))}async[t(1083)](){let n=t;await this._qosDB[n(1083)]()}async[t(818)+"rs"](){let n=t;if(!this[n(928)][n(806)])return;let s=this[n(964)+"Strategy"],l=await this[n(928)][n(498)]();switch(console.log(e.pKNkh,l),s){case e.pArKs:return l&&l.length?Dl(l,0,this[n(477)+n(1167)]):void 0;case e[n(1226)]:return;case e.Gavrk:return l&&l.length?e.XhLEC(Dl,l,0,this[n(477)+n(1167)]):e[n(346)](Lg)}}async[t(1487)](n,s,l){let f=t;return console[f(446)](e.nYiAg,n,s,l),this[f(928)][f(1487)]({cursor_name:n,cursor:s,service:l})}async[t(1176)+"rs"](n){let s=t,l=e[s(475)](Og,n);for(let f of l)console[s(446)](s(791)+"r",l),await this._qosDB[s(1487)](f)}async get(n){let s=t;if(e[s(757)](e[s(510)],s(1012)))try{return e[s(1062)](e.FIvbc,typeof _0x363e5f)&&(e[s(882)](_0x35666f,_0x523e5a)||_0x4f2003[s(1683)]&&e.poBNj(_0x317a62[s(1683)],_0x15b5eb))||e[s(539)]!=typeof _0x3da639?"":(_0x5bd9f9.parse(_0xc9a80e),e[s(1766)])}catch{return e.YVFXq(e[s(539)],typeof _0x12cfff)?e[s(674)]:""}else return(await this[s(928)][s(1519)](n))?.[s(959)]}async[t(1375)](){let n=t;if(e[n(1414)](e[n(1014)],e[n(433)]))await this[n(928)].closeDB();else return new _0x528e45(_0x5d97e6,{message:_0x484b15})}[t(351)+t(748)+t(1806)](n){let s=t,l={FeXyh:function(f,p){return e[H(846)](f,p)}};if(s(1482)===e[s(1726)])this[s(477)+"ileName"]=n;else{let f=this[s(928)]["getStora"+s(391)](this[s(1244)]),p=_0x5835d3[s(1740)](DwmzEd.FeXyh(f,"{}"));return p[_0x2803dd]=void 0,this[s(928)]["setStora"+s(391)](this._prefix,_0x4e466f.stringify(p))}}get[t(806)](){let n=t;return this[n(928)][n(806)]}}let Mg=e[t(576)];async function Pl(a){let n=t;if(!this[n(374)][n(1824)+"S"])return null;let{aID:s,fpID:l,messageStrategy:f}=this[n(374)],p=e.eQQBy(a,Mg);try{return this[n(869)+n(1200)]?a&&this[n(869)+n(1200)][n(351)+n(748)+n(1806)](a):this[n(869)+n(1200)]=new Ng(l+"_"+s+"_"+p,p,f),this[n(869)+n(1200)][n(806)]||await this["_cursorM"+n(1200)][n(1083)](),this[n(869)+"anager"]}catch{return null}}async function Bg(a,n){let s=t,l=e[s(1338)](cn,a[s(623)].headers,e[s(1572)],"-1"),f=cn(a[s(623)][s(1498)],e[s(585)],"1"),p=e[s(904)](cr,a[s(623)][s(1498)],s(396)+s(801)),y=Number(e[s(1554)](cr,a[s(623)][s(1498)],e.JTLhL))||0,g=ka[s(1398)](this,a),T=e[s(1266)](cn,a[s(623)].headers,e[s(706)],"2"),C=e[s(439)](cr,a[s(623)].headers,e[s(1822)]),L=Number(e[s(1847)](cr,a[s(623)][s(1498)],s(1331)+s(1047)+"ue"));if(g[s(1383)])return n();let B=g[s(827)+"sage"]?await Rl[s(1398)](this):null;if(e[s(1096)](a.message[s(421)],0)&&f&&!l||e[s(1629)](a.message[s(421)],0)){if(p&&g[s(827)+"sage"]&&B)return!!!await B.get(p)&&(this[s(570)+s(324)+s(1159)](a),await B.set(p,Date[s(370)]()+y)),n();if(T){let $=await Pl[s(1398)](this);if(!$)return this[s(570)+s(324)+s(1159)](a),e[s(1269)](n);let J=await $[s(1519)](C)??-1;if(e[s(699)](J,L))this[s(570)+s(324)+s(1159)](a),$[s(1487)](C,L,a[s(623)][s(421)]);else throw new Error("recevied"+s(1749)+" cursor "+L+(s(1648)+s(1586)+s(568)+"r ")+J);return e.OLFoF(n)}return this[s(570)+s(324)+s(1159)](a),e[s(346)](n)}}async function Fg(a,n){let s=t,l=ka.call(this,a);if(!l[s(827)+s(763)])return e[s(1466)](n);let f=await Rl[s(1398)](this);if(l[s(736)+s(1361)+s(1702)]&&l.ackMsgIds[s(1273)])for(let p of l.ackMsgIds)await f[s(1192)](p);e[s(1494)](n)}async function zg(a,n){let s=t,l=e[s(1250)](a[s(623)].frameType,Dg),f=e[s(732)](a.message[s(1027)+"e"],Ra);if(e[s(407)](!l,!f))return e[s(1531)](n);let p=e[s(1214)](cr,a[s(623)].headers,e[s(916)]);if(!p)return e[s(1349)](n);let y=await Pl[s(1398)](this,p);if(!y)return e[s(1494)](n);if(l){let g=await y[s(818)+"rs"](),T={frameType:g?.[s(1027)+"e"],SeqID:ue.fromNumber(this[s(1747)]++),LogID:ue[s(845)+"er"](this[s(374)][s(898)+s(1084)]()),service:9e3,method:5,headers:g?.headers,payload:g?.[s(448)]},C=e.uAnSR(v,T);this._ws&&this._ws[s(1841)+"te"]&&this._ws[s(1642)](C)}if(f){if(e[s(1408)]!==e.GsAne)return _0x22033d.offset>=_0x2f48ed[s(418)];{let g=a[s(623)][s(448)];g&&y.setCursors(g)}}}let Ug=async function(a,n){let s=t;e.AmkUw(e.aAWZQ,e[s(1595)])?_0x250216[s(446)](_0x24806c):(this[s(1512)]=!1,clearTimeout(this[s(1205)+s(701)+"utId"]),e.oCnHI(n))},Hg=async function(a,n){let s=t;if(!this[s(975)]||e[s(390)](this._ws[s(1841)+"te"],this[s(517)]))return n();let{pingInterval:l}=this[s(374)];this[s(1340)+"tManager"]?.[s(1121)+s(614)+s(915)]();for(let p=0;e[s(1659)](p,this[s(964)+s(1309)].length);p++){let y=this[s(964)+s(1309)][p];if(e[s(757)](this[s(975)][s(1841)+"te"],this[s(517)])&&y!==null)this[s(975)]&&this._ws[s(1642)](y),this[s(964)+s(1309)][p]=null;else break}this[s(964)+s(1309)]=this[s(964)+"Queue"][s(1548)](p=>!!p),this[s(1588)+"gTimeoutId"]=e.TRFeM(setTimeout,()=>this[s(1169)](),l),this[s(570)+s(1672)+"nt"](a),this[s(330)+"er"]&&this[s(975)]&&(this._ws[s(1393)+"pe"]=this[s(729)+s(1230)]);let f=this["_endpoin"+s(1336)]?.[s(1712)+s(398)+"nt"]();this._debug(s(1367)+f+" success"),e.BkeoK(n)},Gg=async function(a,n){let s=t,l=this["_endpoin"+s(1336)]?.["getCurre"+s(398)+"nt"]();this[s(617)](s(1367)+l),e.xKKpE(n)};class qg extends Sa{constructor(n){let s=t;super(),this[s(1545)+s(625)+"line"]=!0,this[s(330)+"er"]=ar,this[s(1853)]=sg,this[s(1166)+"T"]=Ln,this[s(1725)+"X"]=ii,this[s(574)+"r"]=si,this[s(964)+s(1309)]=[],this[s(1340)+s(1336)]=null,this["_readyCl"+s(979)]=!1,this[s(729)+s(1230)]=e.CvYsG,this[s(1205)+s(1116)]=!1,this[s(1205)+s(701)+s(641)]=null,this[s(1188)+"ctTimeou"+s(678)]=null,this[s(1588)+s(1099)+"Id"]=null,this[s(1747)]=0,this[s(1512)]=!1,this[s(604)]="",this[s(1300)+s(332)]=null,this[s(869)+s(1200)]=null,this["_pingLos"+s(1325)]=null,this[s(1391)+"ls"]=e[s(843)],this[s(1611)]=3,this[s(1170)+"NG"]=0,this[s(517)]=1,this[s(1354)]=2,this[s(1455)]=y=>{let g=s;try{Il(this,y,[Ug,Hg,Gg])}catch(T){let C=lt("error",{message:T[g(623)],code:an[g(1283)+"OR"],error:T});this[g(570)+g(717)+"ent"](C)}},this[s(577)+"ge"]=async y=>{let g=s,{pingInterval:T,pingFrequency:C}=this[g(374)];if((e[g(1234)]("hi",y.data)&&e[g(1005)](g(1658),C)||e[g(822)](e[g(366)],C))&&(this[g(388)+"ngTimer"](),this[g(778)](e[g(704)],e[g(1715)]),this["_pingPon"+g(1099)+"Id"]=e.tbaSR(setTimeout,this._ping[g(977)](this),T)),!e[g(781)]("hi",y[g(466)]))try{Il(this,y,[yg,wg,Fg,zg,Bg,_g])}catch(L){if(e[g(672)](g(598),e[g(1165)]))return _0x12495a[g(1259)]||_0x274bb3[g(1440)]?(g(454)+" "+(_0xd4ae0d[g(1259)]||"")+g(1793)+(_0x4913a6[g(1440)]||""))[g(677)]():_0x2ce620.stringify(_0x5d69ef);{let B=e[g(365)](lt,e[g(1318)],{message:L[g(623)],code:an[g(1447)+g(329)],error:L});this[g(570)+g(717)+"ent"](B)}}},this[s(1544)]=y=>{let g=s,T=this[g(1340)+g(1336)]?.[g(744)+g(1071)+"es"](),C=this[g(1340)+g(1336)]?.["getCurre"+g(398)+"nt"]();if(T&&!y[g(623)]){let L=g(588)+C+(g(952)+g(1223)+g(1175)+"ed");this[g(570)+"hErrorEvent"](e[g(1768)](lt,e[g(1318)],{message:L,code:an[g(1583)+g(1066)+"R"],error:y}));return}this[g(975)]&&e[g(1763)](this[g(975)].readyState,this[g(517)])&&this[g(1106)+g(710)](),this[g(570)+g(717)+g(1172)](e[g(1641)](lt,g(1298),{message:y[g(623)],code:an[g(1151)+g(893)],error:y}))},this[s(1839)]=async y=>{let g=s;if(e.OQjXZ(e[g(492)],e.RQCUC)){this[g(1499)+g(830)](),this[g(388)+g(415)](),this[g(1362)+g(1835)+"rs"](),this._ws=null,this[g(1205)+"Lock"]=!1;let C=this["_endpoin"+g(1336)]?.[g(744)+g(1071)+"es"]();if(!C&&this[g(1718)+"orOnline"]()&&!this["_readyCl"+g(979)]){let L=this[g(1340)+g(1336)]?.[g(1712)+g(398)+"nt"](),B=this._options["reconnec"+g(782)+g(993)](y[g(1209)],y[g(754)]);this["_dispatc"+g(1810)+g(1172)](e[g(685)](mt,e[g(638)],{code:1006,reason:y[g(754)]||"connecti"+g(981)+g(885)+g(487)+"n, hostn"+g(1479)+L,willReconnect:B})),B&&this[g(1205)]();return}if(e[g(673)](1e3,y[g(1209)])&&this["_readyCl"+g(979)]){this[g(570)+g(1810)+g(1172)](mt(e[g(638)],{code:1e3,reason:e[g(1817)]})),this[g(1340)+g(1336)]?.[g(1121)+g(614)+g(915)](),this[g(910)+g(1325)]?.[g(468)+"nter"]();return}if(e[g(1183)](1e3,y[g(1209)])&&C){let L=this["_endpoin"+g(1336)]?.[g(1712)+g(398)+"nt"](),B=y[g(754)];B||(B=await e[g(1764)](fg,this[g(604)])),B=g(1536)+"ng faile"+g(423)+B+(g(1692)+"me: ")+L+(g(1379)+g(1390)+"ached"),this[g(570)+g(1810)+g(1172)](e[g(1114)](mt,g(1854),{code:y[g(1209)],reason:B}));let $=g(588)+L+(g(952)+g(1223)+"es reached");this[g(570)+g(717)+g(1172)](e.UDBMw(lt,e[g(1318)],{message:$,code:an[g(1583)+g(1066)+"R"]})),this[g(1340)+g(1336)]?.[g(1121)+g(614)+g(915)](),this[g(910)+g(1325)]?.[g(468)+g(798)]();return}if(e[g(1427)](1e3,y[g(1209)])&&!y[g(754)])if(e.xLQjt!==e[g(1416)]){let L=this["_endpoin"+g(1336)]?.getCurrentEndpoint();this[g(570)+g(1810)+g(1172)](e[g(904)](mt,e[g(638)],{code:y[g(1209)],reason:g(1536)+"ng failed, unkno"+g(487)+g(488)+g(1479)+L})),this["_endpoin"+g(1336)]?.[g(1121)+g(614)+g(915)](),this[g(910)+g(1325)]?.["resetCou"+g(798)]();return}else for(var T in _0x9b045f)_0x3180d7.o(_0x398d47,T)&&!_0x36dc8d.o(_0x3cbd82,T)&&_0x4cb32d[g(1566)+g(970)](_0x3dca60,T,{enumerable:!0,get:_0x18b303[T]});this[g(570)+"hCloseEvent"](y),this[g(1340)+g(1336)]?.[g(1121)+"pointCon"+g(915)](),this["_pingLos"+g(1325)]?.[g(468)+"nter"]()}else{let{type:C}=_0x1e79ef;this[g(778)](C,_0x1c1843)}},this[s(1634)]=null,this.onerror=null,this[s(1838)+"e"]=null,this[s(615)]=null,this[s(1153)+"econnect"]=null,this[s(1569)+"eAck"]=null,this["onStopIm"+s(905)+s(621)+"ct"]=null,this[s(1004)+s(668)]=this[s(1004)+"nLine"][s(977)](this),this[s(1004)+s(749)]=this[s(1004)+s(749)][s(977)](this),this[s(1237)+s(1613)]=this["_handleP"+s(1613)][s(977)](this),this._handlePageShow=this[s(1237)+s(1563)][s(977)](this),this[s(374)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(840)](1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(366)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(894)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:l,ws:f}=n,p=Array[s(799)](l)?l:e[s(1420)](e[s(539)],typeof l)?[l]:[];if(!p||e.uLCSt(0,p[s(1273)]))throw new Error(e[s(334)]);if(!e[s(1204)](cg,f))throw new Error(e[s(1842)]);Object[s(759)](this[s(374)],n),this["_endpoin"+s(1336)]=new Sl(p,this[s(374)].maxRetries),this["_pingLos"+s(1325)]=new ug(this[s(374)][s(1504)+s(1809)]),this[s(374)][s(766)+s(1410)]&&(this[s(1512)]=!0,this[s(1205)]()),this._options[s(769)+s(1265)+s(839)]&&(this[s(1166)+"T"]||this[s(1725)+"X"]?this["_onPageNetWorkCh"+s(1823)]():this._isBrowser&&this[s(1851)+s(819)+s(1262)]())}["_handleO"+t(668)](){let n=t;this[n(374)][n(645)+"utoRecon"+n(671)]||this[n(1636)+n(979)]||this[n(497)+"econnect"]()}[t(1004)+t(749)](){let n=t;if(e.qHCIl(e.XKIpJ,"CdkXB")){this[n(1783)+n(1395)+"t"]();let s=e[n(1114)](va,e[n(1623)],{message:e[n(1434)]});this["onStopIm"+n(905)+n(621)+"ct"]&&this["onStopIm"+n(905)+n(621)+"ct"](s)}else _0x29d29b[n(1488)]()[n(1323)](()=>{this[n(1521)+"steners"]()})}[t(1851)+"balEventListener"](){let n=t;this[n(330)+"er"]&&window[n(1803)+n(1262)](n(580),this["_handleO"+n(668)]),this[n(330)+"er"]&&window[n(1803)+"Listener"](e[n(966)],this["_handleO"+n(749)]),this._isBrowser&&window.addEventListener(e[n(1003)],this._handlePageHide),this[n(330)+"er"]&&window[n(1803)+n(1262)](e[n(1032)],this[n(1237)+n(1563)])}[t(1600)+t(819)+t(1262)](){let n=t;this._isBrowser&&window["removeEv"+n(442)+n(434)](e[n(1717)],this["_handleO"+n(668)]),this[n(330)+"er"]&&window[n(1449)+n(442)+"ner"]("offline",this[n(1004)+"ffLine"]),this[n(330)+"er"]&&window[n(1449)+n(442)+n(434)](n(939),this._handlePageHide),this[n(330)+"er"]&&window[n(1449)+n(442)+n(434)](e[n(1032)],this[n(1237)+n(1563)])}[t(1237)+t(1613)](n){let s=t;!n.persisted&&(this[s(330)+"er"]&&window[s(1449)+s(442)+s(434)](s(939),this[s(1237)+"ageHide"]),this[s(330)+"er"]&&window[s(1449)+s(442)+"ner"](e.Rmcvb,this[s(1237)+s(1563)]),this[s(1854)]()),this[s(330)+"er"]&&window[s(1449)+s(442)+s(434)](e[s(1717)],this["_handleO"+s(668)]),this._isBrowser&&window[s(1449)+s(442)+s(434)](e[s(966)],this[s(1004)+"ffLine"])}[t(1237)+t(1563)](n){let s=t;n[s(619)+"d"]&&(this[s(1718)+"orOnline"]()&&(!this._ws||e[s(1414)](this[s(975)].readyState,this[s(517)])||e[s(829)](this._ws.readyState,this.CONNECTING))&&this._handleOnLine(),this[s(330)+"er"]&&window[s(1803)+s(1262)](e[s(1717)],this[s(1004)+s(668)]),this[s(330)+"er"]&&window[s(1803)+s(1262)](e[s(966)],this[s(1004)+s(749)]))}async[t(461)+"eUrl"](n){let s=t,{fpID:l,deviceID:f,bddID:p,ttwID:y,accessKey:g,aID:T,customParams:C={},enableAutoAck:L,enableQoS:B,QoSLevel:$,env:J}=this[s(374)],Be,wt,Je;this[s(330)+"er"]||this[s(1725)+"X"]||this[s(1166)+"T"]?(Be=location&&e[s(1013)](e[s(1292)],location[s(773)])?e[s(1138)]:s(1812),wt=n[s(795)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),Je=/^wss(.*:\/\/)/[s(416)](n)?n:""+Be+wt):(Be=s(1018),wt=n[s(795)](/(^http)((?:[s]*:\/\/))/,""),Je=/(^ws)((?:[s]*:\/\/))/[s(416)](wt)?wt:""+Be+wt);let Ze=p?e.SHGIG:y?"ttwid":s(1002)+"d",oi=p||y||f;if(e.ITxmp(!oi,!Ze))throw new Error(e[s(1141)]);let Ol=e[s(1321)]==typeof C?await e[s(501)](C):C,jg=J?e[s(1214)](lg,J.xUseEnv,J[s(561)]):{},Da=Object[s(759)]({device_platform:e.JHLve,version_code:e[s(1799)],access_key:g,fpid:l,aid:T,[Ze]:oi,xsack:L?1:0,xaack:L?1:0,xsqos:B?1:0,qos_level:B?$:void 0,qos_sdk_version:2,...jg},Ol),Wg=Object[s(1270)](Da).reduce((Pa,Oa)=>Da[Oa]!==void 0?""+Pa+(Pa?"&":"?")+Oa+"="+Da[Oa]:Pa,"");return Je+"/ws/v2"+Wg}async _connect(){let n=t,s={mNnyB:function(p,y){return e.pgRXc(p,y)}};if(!(this["_connect"+n(1116)]||this[n(1636)+n(979)])){this["_connect"+n(1116)]=!0;try{let p=this[n(1340)+"tManager"]?.[n(1400)+"rentEndpointReac"+n(1602)+n(1855)](),{timeoutInterval:y}=this[n(374)];if(p){let T=this["_endpoin"+n(1336)]?.["getCurre"+n(398)+"nt"](),C=this[n(1340)+n(1336)]?.[n(480)+n(727)+n(1664)+n(688)+n(1590)](),L=this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]();if(C){let B="connect "+T+(n(1450)+", max re"+n(1390)+n(358)+n(1359)+n(562)+"ndpoint ")+C+(n(536)+"y"),$=e[n(1368)](lt,e.AxcSI,{message:B,code:an[n(1583)+"IES_ERROR"]});this._debug(B),this["_dispatc"+n(717)+n(1172)]($),this[n(604)]=await this["_generat"+n(1678)](C),this[n(617)](n(588)+C+" "+L+n(784)),this[n(1362)+"sListeners"]()}else if(e[n(709)](e.Gaoxd,e[n(357)])){let B=(n(1088)+"1")[n(1317)]("|"),$=0;for(;;){switch(B[$++]){case"0":var l=_0x3a461e[_0x1f36ac]={exports:{}};continue;case"1":return l.exports;case"2":var f=_0x2aabbc[_0x27530f];continue;case"3":_0x15a9de[_0x210ef8](l,l[n(1329)],_0x40482a);continue;case"4":if(KzsAts[n(1568)](void 0,f))return f[n(1329)];continue}break}}else{let B=n(588)+T+(n(1450)+", max re"+n(1390)+n(863));this[n(617)](B),this[n(570)+n(717)+"ent"](e[n(685)](lt,e.AxcSI,{message:B,code:an[n(1583)+n(1066)+"R"]}));return}}else if(e[n(339)](n(1461),e[n(1644)]))_0x119bd8=e[n(1277)](_0x3f5da1,_0x5ccebf),_0x2f0305=127&_0xe82d4c,e[n(1767)](128,_0x1d2804)&&(_0x4e28f9=e[n(486)](_0x404f40,_0x199dc2),_0x366fa0|=e[n(1355)](e[n(1238)](127,_0x171112),7));else{let T=this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1425)+"ateCount"](),C=this["_endpoin"+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]();this._url=await this[n(461)+n(1678)](e[n(1198)](T,"")),this[n(617)]("connect "+T+" "+C+n(784)),this[n(1362)+n(1835)+"rs"]()}if(this._isInit)this[n(1512)]=!1;else{let T=e[n(1549)](va,e[n(1623)],{message:n(1830)});this[n(1153)+"econnect"]&&this[n(1153)+"econnect"](T)}let g=this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]()||0;e.uUUVT(g,1)&&await this[n(1538)](e[n(680)](g,1)),this[n(617)](n(1536)+n(1370)+this[n(604)]+(n(611)+"ls: ")+this._protocols),this[n(975)]=e[n(406)](ag,{url:this[n(604)],protocols:[this[n(1391)+"ls"]],headers:this[n(374)][n(1133)+n(1630)+"s"][n(551)+n(1635)]},this[n(374)].ws),(this[n(330)+"er"]||this[n(574)+"r"])&&this[n(975)]&&(this[n(975)][n(1393)+"pe"]=this._binaryType),this[n(1521)+"steners"](),this[n(1205)+"ionTimeo"+n(641)]=setTimeout(this[n(1486)+"ut"][n(977)](this),y)}catch(p){throw this[n(1205)+n(1116)]=!1,p}}}["_clearTi"+t(830)](){let n=t;e[n(384)](clearTimeout,this["_connect"+n(701)+n(641)]),this["_connect"+n(701)+"utId"]=null}["_clearPi"+t(415)](){let n=t;e[n(1255)](clearTimeout,this[n(1588)+"gTimeoutId"]),e.WLiTs(clearTimeout,this[n(1188)+"ctTimeou"+n(678)]),this[n(1588)+n(1099)+"Id"]=null,this[n(1188)+n(1820)+n(678)]=null}[t(617)](...n){let s=t;s(1388)===e[s(361)]?this[s(374)].debug&&console.log[s(728)](console,[e[s(1382)],...n]):(this[s(778)](s(1298),_0x195be6),this[s(1276)]&&this.onerror(_0x2f3cbf))}[t(328)+t(1125)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:p}=this[s(374)],y=l*Math.pow(p,e[s(680)](n,1));return y>f?f:y}[t(1169)](){let n=t;if(this[n(975)]&&e[n(452)](this[n(975)][n(1841)+"te"],this.CONNECTING)){this[n(388)+n(415)](),this[n(1588)+n(1099)+"Id"]=e.InKYm(setTimeout,this._ping[n(977)](this),this._options[n(1081)+"rval"]);return}if(!this[n(975)]||e.zFsOn(this[n(975)][n(1841)+"te"],this[n(517)]))return void this[n(497)+n(1243)]();this[n(975)]&&this[n(975)][n(1642)]("hi"),this[n(1188)+"ctTimeou"+n(678)]=setTimeout(this[n(497)+n(1243)+n(522)][n(977)](this),this[n(374)][n(630)+"outInter"+n(1053)])}[t(497)+t(1243)+t(522)](){let n=t;this[n(910)+n(1325)]?.[n(1140)](),this[n(778)](e[n(1758)],e[n(1386)]),this[n(910)+"sCounter"]?.[n(744)+"chMaxCount"]()?this[n(497)+n(1243)]():this[n(1169)]()}["_navigat"+t(874)](){let n=t,s={pWdMb:function(l,f,p){return e[H(1306)](l,f,p)},LVaSQ:e.Jmuzo,hvykm:e[n(557)]};if(e.HomRV(e[n(1249)],e[n(1249)]))return this[n(1166)+"T"]||this[n(1725)+"X"]?this[n(1545)+n(625)+"line"]:(this._isBrowser||this._isWorker)&&this[n(374)][n(769)+n(1265)+n(839)]?navigator[n(1e3)]:!0;{let l=CiLhuX[n(989)](_0x25b465,CiLhuX.LVaSQ,{message:CiLhuX[n(1705)]});this[n(1153)+n(1243)]&&this[n(1153)+"econnect"](l)}}[t(497)+t(1243)](){let n=t;!this[n(1718)+n(874)]()||this[n(1636)+n(979)]||(this[n(1340)+n(1336)]?.["resetEnd"+n(614)+n(915)](),this[n(910)+"sCounter"]?.["resetCou"+n(798)](),this._ws?this[n(1106)+n(710)](1001,e[n(1056)],!0):this._connect())}_onPageNetWorkChange(){let n=t;this[n(1166)+"T"]?tt[n(1825)+"kStatusC"+n(1126)](({isConnected:s})=>{let l=n;this[l(1545)+l(625)+l(1411)]=s,s?this[l(1004)+l(668)]():this._handleOffLine()}):this[n(1725)+"X"]&&wx[n(1825)+n(820)+n(1126)](({isConnected:s})=>{let l=n;this[l(1545)+l(625)+l(1411)]=s,s?this[l(1004)+"nLine"]():this._handleOffLine()})}[t(1538)](n){let s=t,l={ZIVOx:function(f,p,y){return e[H(1577)](f,p,y)},RpmxH:e.AqBFX,xdJwu:function(f,p,y){return e[H(426)](f,p,y)},SUtvC:e[s(1817)]};if(e.NjmRT(e[s(1522)],s(1561)))return new Promise(f=>{let p=s;e[p(1304)](setTimeout,f,this["_getInte"+p(1125)+"e"](n))});if(this["_clearPi"+s(415)](),this["_clearTi"+s(830)](),this[s(1362)+s(1835)+"rs"](),this["_wsInsta"+s(853)](1e3,_0x337bac),this[s(1205)+s(1116)]=!1,_0x44b738&&this[s(1718)+s(874)]()&&!this[s(1636)+s(979)]){if(this[s(1340)+s(1336)]?.[s(744)+s(1071)+"es"]()){let p=this[s(1340)+"tManager"]?.["getCurre"+s(398)+"nt"]();this[s(570)+s(1810)+s(1172)](l[s(1530)](_0x3c4ce0,l[s(955)],{code:1006,reason:s(588)+p+(s(1450)+s(1379)+s(1390)+"ached"),wasClean:!0}))}else{let p=this._options[s(518)+s(782)+"ptor"](_0x11f126,_0x8a26f1);this[s(570)+s(1810)+"ent"](l[s(1530)](_0x16c583,l[s(955)],{code:_0x51e127,reason:_0x5b9ff5,wasClean:!0,willReconnect:p})),p&&this._connect()}return}this._navigatorOnline()||this[s(1636)+s(979)]?this["_dispatchCloseEv"+s(1172)](l[s(1589)](_0x1d74d2,l[s(955)],{code:_0x362c4,reason:l[s(1523)]})):this[s(570)+s(1810)+s(1172)](_0x2d7310(l[s(955)],{code:1006,reason:"going aw"+s(649)+s(451)+"ine"})),this[s(975)]=null,this["_endpoin"+s(1336)]?.[s(1121)+s(614)+"fig"](),this[s(910)+s(1325)]?.[s(468)+s(798)]()}["_disconn"+t(710)](n=1e3,s="",l=!1){let f=t;this[f(975)]&&this["_destroy"+f(1395)+"t"](n,s,l)}[t(1486)+"ut"](){let n=t,s={hoGsU:e[n(1318)],Xpkzz:function(l,f,p){return e.dszcQ(l,f,p)}};if(e[n(1303)](n(476),e[n(1119)]))this[n(778)](HtpPwV[n(779)],HtpPwV[n(892)](_0x3def81,HtpPwV.hoGsU,{message:this["_formatE"+n(1350)+n(1702)](_0x208d24)}));else{let l=this[n(1340)+n(1336)]?.[n(1712)+"ntEndpoint"]();this[n(617)](n(588)+l+" timeout"),this[n(1106)+n(710)](1001,n(1160)+n(605)+"onnecting",!0)}}[t(724)](n){let s=t,l=e[s(796)](Gt,n);this[s(975)]&&e[s(662)](this[s(975)].readyState,this[s(517)])&&(this[s(975)]&&this[s(975)][s(1642)](l),this._debug("send_ack",n))}[t(1362)+"sListeners"](){let n=t,s=(n(1033)+"1").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(975)][n(1449)+n(442)+n(434)](e[n(1483)],this[n(1455)]);continue;case"1":this[n(975)][n(1449)+n(442)+"ner"](n(1298),this._onError);continue;case"2":this[n(975)][n(1449)+n(442)+n(434)](e.AqBFX,this[n(1839)]);continue;case"3":if(!this[n(975)])return;continue;case"4":this[n(975)]["removeEv"+n(442)+n(434)](e[n(336)],this[n(577)+"ge"]);continue}break}}["_addWsLi"+t(1507)](){let n=t,s=e[n(1627)][n(1317)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(975)][n(1803)+n(1262)](e.mLmrK,this[n(577)+"ge"]);continue;case"1":this[n(975)]["addEvent"+n(1262)](n(1298),this[n(1544)]);continue;case"2":this[n(975)][n(1803)+n(1262)](n(1771),this[n(1455)]);continue;case"3":this[n(975)]["addEvent"+n(1262)](e[n(638)],this[n(1839)]);continue;case"4":if(!this._ws)return;continue}break}}[t(1735)+"nceClose"](n=1e3,s=""){let l=t;try{if(e[l(1454)](e.OZyRb,e[l(595)]))try{e.PoiyI(_0x4dc453,this,_0x1b12e1,[_0x3c2206,_0x5a9661,_0x40cc14])}catch(f){let p=e[l(635)](_0x832633,e[l(1318)],{message:f[l(623)],code:_0x429f99[l(1283)+"OR"],error:f});this[l(570)+l(717)+l(1172)](p)}else this._ws&&this[l(975)][l(1854)](n,s)}catch{}}[t(1783)+t(1395)+"t"](n=1e3,s="",l=!1){let f=t;if(this[f(388)+"ngTimer"](),this[f(1499)+f(830)](),this[f(1362)+f(1835)+"rs"](),this[f(1735)+f(853)](1e3,s),this[f(1205)+f(1116)]=!1,l&&this[f(1718)+f(874)]()&&!this[f(1636)+f(979)]){if(this[f(1340)+"tManager"]?.[f(744)+f(1071)+"es"]())if(e[f(797)](e[f(470)],e[f(543)]))_0x406b0c.exports=_0x4c6ef5[f(1488)]()[f(1323)](()=>(_0x26ba17(),_0x3e7144))[f(1323)](function(y){return y});else{let y=this[f(1340)+"tManager"]?.[f(1712)+f(398)+"nt"]();this[f(570)+f(1810)+f(1172)](mt(e.AqBFX,{code:1006,reason:f(588)+y+(f(1450)+f(1379)+f(1390)+f(863)),wasClean:!0}))}else{let y=this[f(374)][f(518)+f(782)+f(993)](n,s);this[f(570)+f(1810)+f(1172)](e[f(720)](mt,e.AqBFX,{code:n,reason:s,wasClean:!0,willReconnect:y})),y&&this[f(1205)]()}return}this[f(1718)+f(874)]()||this["_readyCl"+f(979)]?this["_dispatc"+f(1810)+f(1172)](e.dgdqM(mt,e[f(638)],{code:n,reason:f(593)})):this[f(570)+f(1810)+f(1172)](e[f(1721)](mt,e[f(638)],{code:1006,reason:e[f(1156)]})),this[f(975)]=null,this[f(1340)+f(1336)]?.[f(1121)+f(614)+f(915)](),this[f(910)+f(1325)]?.resetCounter()}[t(570)+t(1672)+"nt"](n){let s=t;this[s(778)](e[s(1483)],n),this.onopen&&this[s(615)](n)}["_dispatc"+t(324)+t(1159)](n){let s=t;this.emit(e.mLmrK,n),this[s(1838)+"e"]&&this[s(1838)+"e"](n)}["_dispatc"+t(1035)+"ageEvent"](n){let s=t,l={Qmurl:function(f,p){return e[H(1064)](f,p)},GytWb:e[s(539)],EzicJ:function(f,p){return e[s(1736)](f,p)},RxzMT:e[s(1766)]};if(e[s(1421)](s(1358),e.HuxLt))this[s(778)](e[s(348)],n),this[s(1569)+s(920)]&&this[s(1569)+s(920)](n);else return vdTqyH[s(450)](vdTqyH[s(1332)],typeof _0x56c498)&&(_0x3286e8 instanceof _0x2d6eef||_0x12f7ef[s(1683)]&&vdTqyH[s(506)](_0x576cf0[s(1683)],_0x579b90))||s(884)!=typeof _0x313d4e?"":(_0x49411d[s(1740)](_0x54516d),vdTqyH[s(395)])}[t(570)+"hErrorEv"+t(1172)](n){let s=t;if(e.NjmRT(e[s(866)],s(643))){let l={TzYFe:function(f,p,y){return e[s(1675)](f,p,y)},IsVER:e[s(638)]};_0x12c68e[s(1488)]()[s(1323)](()=>{let f=s,p=l[f(567)](_0xab7f8a,f(1298),{message:this["_formatE"+f(1350)+"age"](_0x51c6d)});this[f(778)](f(1298),p);let y=_0x4bd5ab("close",{reason:this[f(457)+f(1350)+f(1702)](_0x2b8542)});this[f(778)](l[f(1247)],y)})}else this[s(778)](s(1298),n),this.onerror&&this[s(1276)](n)}[t(570)+t(1810)+t(1172)](n){let s=t;if(e[s(1427)](e[s(575)],e[s(575)])){let l=_0x48ca4f[s(1317)](/\./)[s(400)](y=>_0x4cfddd(y)),f=[];return f[0]=e[s(368)](_0x3406d4,e[s(935)](l[0],l[1])),f[1]=e[s(1147)](_0x56a802,l[2]+l[3]),[e[s(1670)],e[s(1670)],e[s(1670)],"0000",s(1246),e.kdROD,f[0],f[1]][s(994)]("")}else this[s(778)](s(1854),n),this[s(1634)]&&this.onclose(n)}get[t(1393)+"pe"](){let n=t;return this._ws?this._ws[n(1393)+"pe"]:this[n(729)+n(1230)]}set[t(1393)+"pe"](n){let s=t;if(s(1704)===e[s(888)])return null;this[s(729)+s(1230)]=n,this._ws&&(this[s(975)][s(1393)+"pe"]=n)}get retryCount(){let n=t;return this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]()||0}get[t(751)+t(441)](){let n=t,s=this["_message"+n(1309)].reduce((l,f)=>(l+=f&&f.byteLength||0,l),0);return e[n(722)](s,this[n(975)]?this[n(975)][n(751)+"Amount"]:0)}get extensions(){let n=t;if(e[n(1345)](e[n(362)],e[n(1831)]))return this[n(975)]?this[n(975)][n(731)+"ns"]:"";{this[n(1783)+n(1395)+"t"]();let s=e[n(726)](_0x52e249,e.Jmuzo,{message:e.dnskl});this[n(1023)+"mediatel"+n(621)+"ct"]&&this["onStopIm"+n(905)+n(621)+"ct"](s)}}get[t(773)](){let n=t;return this[n(975)]?this[n(975)][n(773)]:""}get[t(1841)+"te"](){let n=t;return this[n(975)]?this[n(975)][n(1841)+"te"]:this[n(374)][n(766)+n(1410)]?this.CONNECTING:this.CLOSED}get[t(1661)](){let n=t;return this[n(975)]?this[n(975)][n(1661)]:this[n(604)]}[t(1854)](n=1e3,s){let l=t,f=e[l(344)][l(1317)]("|"),p=0;for(;;){switch(f[p++]){case"0":if(!this._ws)return void this[l(617)](e[l(1050)]);continue;case"1":this._destroyWebSocket(n,s);continue;case"2":this[l(1499)+l(830)]();continue;case"3":this[l(388)+l(415)]();continue;case"4":this[l(1600)+l(819)+l(1262)]();continue;case"5":this["_QoSMana"+l(332)]?.[l(1375)]();continue;case"6":this[l(1636)+l(979)]=!0;continue;case"7":if(e[l(757)](this[l(975)][l(1841)+"te"],this[l(1611)])||e[l(602)](this[l(975)][l(1841)+"te"],this[l(1354)]))return void this._debug(e[l(360)]);continue}break}}async send(n,s){let l=t;if(e[l(1345)](l(386),e[l(1439)])){let f=e[l(525)](_0x4cfccf[l(1396)],0),p=e[l(1429)](e[l(997)](e.RsSwj(_0x1d93a5[l(1396)],28),_0x578ece[l(1228)]<<4),0),y=e[l(868)](_0x5d4dbe[l(1228)],24),g=e[l(735)](0,y)?p===0?e[l(1017)](f,16384)?e[l(550)](f,128)?1:2:f<2097152?3:4:e[l(479)](p,16384)?e[l(1069)](p,128)?5:6:p<2097152?7:8:e[l(1746)](y,128)?9:10,T=e[l(923)](_0x58e440,_0x26dda1,g),C=_0xda81d3.bytes;switch(g){case 10:C[e.bKfyL(T,9)]=e[l(325)](e[l(1412)](y,7),1);case 9:C[e.AlZhW(T,8)]=e[l(1624)](9,g)?e.KoqIo(128,y):e.gLawA(127,y);case 8:C[T+7]=e[l(499)](8,g)?e[l(524)](p,21)|128:e.wQZfo(p>>>21,127);case 7:C[T+6]=e.XdvGg(7,g)?e[l(392)](e[l(417)](p,14),128):e[l(1639)](e[l(648)](p,14),127);case 6:C[e[l(1728)](T,5)]=e[l(390)](6,g)?e[l(552)](e[l(409)](p,7),128):e[l(1186)](p>>>7,127);case 5:C[e[l(659)](T,4)]=e[l(673)](5,g)?128|p:e[l(1049)](127,p);case 4:C[T+3]=g!==4?e[l(1242)](e.RNIDJ(f,21),128):e[l(1652)](f>>>21,127);case 3:C[T+2]=g!==3?e[l(1025)](e[l(868)](f,14),128):e[l(664)](f,14)&127;case 2:C[T+1]=e[l(1722)](2,g)?e.RNIDJ(f,7)|128:e[l(511)](f>>>7,127);case 1:C[T]=e[l(490)](1,g)?128|f:e[l(969)](127,f)}}else{if(e[l(670)](null,n))throw new Error("please provide a"+l(1724)+l(765)+l(998)+l(1567)+l(1472)+l(1633)+"ffer");e.MBBHL(e.xFUDR,typeof n)&&(n=JSON[l(870)+"y"](n)),e[l(1489)](l(884),typeof n)&&!e[l(1737)](n,ArrayBuffer)&&!(n.buffer&&e.YGXKm(n[l(1683)],ArrayBuffer))&&(n=JSON[l(870)+"y"](n));let f=await e.HSPte(Tl,n),p=e[l(1255)](dg,n),{method:y=0,service:g=this[l(374)].service,logID:T=this[l(374)][l(898)+l(1084)](),headers:C=this[l(374)][l(1498)],payloadEncoding:L=this[l(374)][l(1403)+l(1781)],payloadType:B=this[l(374)][l(896)+l(1230)],logIDNew:$=this[l(374)][l(675)+l(851)][l(865)+l(627)+l(1152)+"ew"]?e[l(1124)](i,this[l(374)].logIDNewConfig[l(1574)]):""}=e.XXWsW(s,{});if(!g)throw new Error(l(1077)+l(1805)+l(1224)+l(800));let J={SeqID:ue[l(845)+"er"](this._seqId++),LogID:ue.fromNumber(T),service:g,method:y,headers:C,payloadEncoding:e[l(987)](L,Object)?L.encoding?L[l(1278)]:"":L,payloadType:e.MlxUl(B,Object)?B[l(321)]?B[l(321)]:p:B||p,payload:f,LogIDNew:$},Be=e[l(978)](Gt,J);return this[l(975)]&&e[l(1199)](this[l(975)].readyState,this[l(517)])?(this[l(975)]&&this[l(975)][l(1642)](Be),this[l(617)](e[l(1310)],J)):this._messageQueue[l(1273)]<this._options["maxMessa"+l(1080)+l(1187)]?(this[l(964)+l(1309)].push(Be),this[l(617)](e.NzRDN,J)):(this._messageQueue[l(924)](),this[l(964)+l(1309)][l(1097)](Be)),{seqID:this._seqId,logID:T,logIDNew:$}}}async reconnect(n){let s=t,{url:l}=e[s(1539)](n,{}),f=Array[s(799)](l)?l:e.ShnOq(e[s(539)],typeof l)?[l]:[];n&&Object[s(759)](this[s(374)],n),f&&f[s(1273)]?this["_endpoin"+s(1336)]=new Sl(f,this[s(374)][s(380)+"es"]):this[s(1340)+"tManager"]?.["resetEnd"+s(614)+s(915)](),this[s(910)+"sCounter"]?.[s(468)+s(798)](this[s(374)]["pingLoss"+s(1809)]),this[s(1636)+s(979)]=!1,this[s(975)]&&this[s(975)][s(1841)+"te"]!==this[s(1611)]?this[s(1106)+"ect"](1e3,e[s(1142)],!0):(this[s(1512)]=!0,this[s(1205)]())}async[t(609)](){let n=t,s={nzVMH:e[n(1715)]};if(e.XXXKb(e[n(1377)],n(456)))this[n(388)+n(415)](),this[n(778)]("ping_onc"+n(626)+"s",CBdsYh[n(1695)]),this[n(1588)+n(1099)+"Id"]=_0x2dd74f(this._ping[n(977)](this),_0x59cfdd);else if(!this[n(1205)+n(1116)]){let l="0|2|4|3|1"[n(1317)]("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(1340)+"tManager"]?.[n(1121)+"pointCon"+n(915)]();continue;case"1":this._connect();continue;case"2":this._pingLossCounter?.[n(468)+n(798)]();continue;case"3":this[n(1512)]=!0;continue;case"4":this[n(1636)+n(979)]=!1;continue}break}}}[t(1803)+t(1262)](n,s){this.on(n,s)}["dispatch"+t(1159)](n){let s=t,{type:l}=n;this[s(778)](l,n)}[t(1449)+t(442)+t(434)](n,s){let l=t,f={BEQHW:function(p,y){return p(y)},NqzmP:function(p,y){return p+y},GDhVH:function(p,y){return e[H(708)](p,y)},RPiRR:function(p,y){return p||y}};if(e[l(1492)](e.yWyXN,e.yWyXN)){let p={eAMAV:function(L,B){return L>B},pftFz:function(L,B){let $=l;return aFfjQg[$(684)](L,B)},SFucI:function(L,B){let $=l;return aFfjQg[$(849)](L,B)},KSqDq:function(L,B){return aFfjQg.GDhVH(L,B)},bBARp:function(L,B){return aFfjQg.NqzmP(L,B)},jIVKS:function(L,B){return L|B}},y=aFfjQg.RPiRR(_0x173d3f,8192),g=y>>>1,T=null,C=y;return function(L){let B=l;if(L<1||p[B(760)](L,g))return p.pftFz(_0xec9762,L);p.eAMAV(p[B(1034)](C,L),y)&&(T=p.pftFz(_0x54280f,y),C=0);let $=_0x34ec67[B(1398)](T,C,C+=L);return p[B(1422)](7,C)&&(C=p[B(1364)](p[B(949)](7,C),1)),$}}else this[l(838)](n,s)}[t(1101)](){let n=t,s={WJpUH:function(l,f){return l!==f},CxfnI:e[n(1517)],axNyu:function(l,f){return l(f)},SYfpD:e[n(704)],hhvBl:e[n(1483)],JMvak:function(l,f,p){return e[n(1807)](l,f,p)}};return new Promise((l,f)=>{let p=n,y={oiqBb:s[p(1189)]};this[p(388)+p(415)](),this[p(1588)+p(1099)+"Id"]=s[p(1468)](setTimeout,this[p(1169)].bind(this),this[p(374)][p(1081)+p(603)]);let g=()=>{let C=p;s[C(1279)](C(1620),s[C(1430)])?(s[C(430)](l,"success"),this[C(838)](s[C(1716)],g),this[C(838)](C(1015)+C(667)+"t",T)):this.emit(GdToer[C(545)],_0x2eceed(GdToer[C(545)],{..._0x29f45e,data:_0x31c523[C(1259)]||""}))},T=()=>{let C=p;f(C(1127)),this.off(s[C(1716)],g),this[C(838)](C(1015)+"e_timeout",T)};this.on(p(1015)+p(626)+"s",g),this.on("ping_onc"+p(667)+"t",T),this[p(1169)]()})}}})(),Me[N(1327)+"oseEvent"]=Re[N(1327)+N(460)],Me[N(1516)+N(1164)]=Re.CustomErrorEvent,Me[N(1821)+"e"]=Re[N(1821)+"e"],Me[N(1159)]=Re[N(1159)],Me[N(382)]=Re[N(382)],Me[N(353)+"MessageE"+N(1213)]=Re[N(353)+N(1501)+N(1213)],Me[N(1501)+N(1213)]=Re[N(1501)+N(1213)],Me[N(835)+"t"]=Re[N(835)+"t"],Me.ReconnectEvent=Re[N(1233)+"tEvent"],Me["createCl"+N(460)]=Re[N(1103)+"oseEvent"],Me.createErrorEvent=Re[N(1389)+N(1164)],Me[N(596)+"ssageEvent"]=Re[N(596)+N(712)+"nt"],Me[N(967)+N(1254)]=Re["createOp"+N(1254)],Me[N(1385)+N(566)+"vent"]=Re[N(1385)+N(566)+"vent"],Me["decodedF"+N(697)]=Re["decodedF"+N(697)],Me[N(1772)+N(1470)]=Re[N(1772)+N(1470)];function oa(){let t=["u2LREuW","y2HLy2TdDxi","r1rjC2G","EKDesfe","Cgf5Bg9Hzeu","Dhj1y3rVCIa","reTQzei","AgH3A1a","y1rfDLu","r3nbBMu","vfHAEKC","y09Wzw4","BgLUzq","v0rhEee","BMv4DcGPigm","Ae9gAge","z29PBMCGyxC","vfnLAuS","D1nYCLm","vfP2t2O","yxvhqva","wvzgwhe","ANDMCuW","s1nXrhe","uMn6wwu","aaaaaaaaaaa","BNrbBMrvCgq","EwrbzgS","uK10zve","ntbODfzLqMu","y0PUwwO","q3HMBKK","vxLQq1q","wMrivuy","BwvZ","zg5ZA2W","Aw5N","C3rVCcbPBw0","tMLUBw8","B3vUDa","EfPmBhG","zxjYtM8","x2rItMfTzq","Dfb6su8","x2LUAxq","CNbQCuq","BML0AwfSAxO","BgvY","tuvtu0fhrv8","BgHHuve","CMvTB3zLrxy","ihrPBwvVDxq","uu5HD1q","AK1Tt3a","DxrMofDYAxq","uMTcC2S","x29Ut3bLBG","u2Lnvey","uvzjzKK","zefsve0","Aw5JBhvKzxm","wMnnz2G","sgH1zwe","z2vjBMzVu3K","C0v3zwW","mhW0Fdj8mxW","C25hDLy","qMTLB0S","u2fyAw8","sK12ywS","BxPysgq","yw1L","x0rctMfTzq","BMCGB3iGyw4","igzPzwXKoIa","yNL0zuXLBMC","Eufevfq","r1fxuKG","Bg1iAMe","mdaWmdaWmda","yw1LoIa","zgTmEgK","u0Hyzei","DeDiy1O","EuHrwu4","Ahjxshu","we9vtgS","x29UvgLTzw8","C2v0","CMvZB2X2zq","uevtD00","rw1hCMS","Ahr0Ca","rgT4AeC","vxDJCeu","sfnQq3a","zMzouue","rMz3Awi","t2rvu3C","AgvHzgvYCW","x2nSzwfYvgK","A2rst0q","twvZC2fNzuu","D0njBgy","Cw9Zx18","CgLUz0XVC3m","B3LUCNO","AgfZ","C3rLBMvYCW","yKTjvhu","zgzZqMm","s2TJte8","qxHZv3C","x2LZsw5PDa","Dg9mB3DLCKm","Bg9pz08","CIb0DhDjra","q3vZDg9Trxi","Dw15Cxm","uvjAruS","z2v0","wKrdsNm","x2fKzfDZtgK","AMDMr0y","u1v0DKm","swDOEhK","ENDcA2S","uu54uxi","r3jrywi","tvzTtxm","A3vAzKu","wKLwt3G","t0XgB0y","x2XPC3rLBMu","tgjrBwq","uxj2Cxu","BM5Ly3q","y29UBMvJDgK","AK9Uv0K","x3DHAxq","CvLlwgK","vg9SBgS","mxW0Fdj8m3W","y3vYC29Yx24","v0TQuK0","x29UrxjYB3i","x21PBMLoyxy","v1HpCei","C2vYDMvYvgK","zMLSDgvY","AgX3t2m","q256CvC","rxzAExG","y29TCgXLDgu","zM9Yy2u","rhfMy1y","C0TXBLy","C3vIC3rYAw4","y1nIwwm","u1Hrrxy","zuvQq1u","ruLnA2C","BgzuywS","yM9L","ywDLu2HVDW","DMLJzuLeig8","vhPVr24","zgvMAw5Luhi","zsbHihn0CMK","Bu5UEui","B25szwnLAxy","u0PhwM0","qLHTDKC","uNrTAvG","sMnVuKy","DxnLCKLW","zw1LBNq","vM5wvKy","qvLLuei","y2HHqLK","wu9nz0q","rfvuuKq","EsbJBg9Zzwq","BhrlwgC","tufyx1jfvfi","tKPXBM8","v0vyCxK","DgHHBIbSB2m","zfDVCMTLCKC","x3bPBMDqB24","EgrkD3u","Dw50","BLzTrwC","y3vYCMvUDeu","s3nTz1C","zxjFCw9Z","AMLyD2K","EMvktwe","tgnPBeS","ywjVCNq","zxrLzhK","x2rYB3bhBg8","yKj0AgO","AgvKtwf4uMu","uhfIuKC","vKPAwwq","zMzMzG","u2TPCcbWyxm","B3LWEfm","zfz6wKK","CxrTtKq","y2uGBM90igK","q0Xpu0ve","DhvYuuK","ywDLsgLKzq","AwrI","AwDOvLe","zNjVBujPDhm","thzqDhC","z0XoC2O","BfrPBwvVDxq","vhHptg0","B3bLCNr5tMe","Eej4twy","sM11EM8","yMzsA2e","s2XurhG","s0rRr0C","yLL0ELy","tfr6wfK","thfVsem","CMfTugfYyw0","CMf6rxK","tvjSufq","igfYCMf5yNu","B25JBg9Zzq","DhbizwfKzxi","x3jLywr5q2W","v2XgtM8","r2rnA1K","sKLJDvi","BNvTyMvY","DKXyrgy","C2vUza","sM1Twfm","AgjWEg0","ExfOC0y","C0jf","BeHwDMu","igXHCMDLCIa","Ahjctfy","CgL2CNG","DMjqAMK","DwDutw4","r2Les00","DhLhy0i","uhjPBwfYEuS","CKLOrMm","wfPtt1K","ywX3yxLZ","Eu9wD1e","AxnmB25N","DxjS","EejJy3K","tfbJDvC","Cg9PBNrbBMq","EMTMELq","tvLcvge","Ahr0Chm6","zxf1ywXZ","uM9Zrfi","BfLYvhK","sKTxBwm","Ae9Wzw5fDMu","EgHOq0W","y2PYCKO","CLzpweG","nxWWFdD8mq","Aw9vCeC","zvvYBa","AMHbAvy","vufswu8","zw5HyMXLvhi","vuv6CuS","yNvMzMvY","BMrWB2LUDfq","vxH1zw4","Dw5RBM93BIa","vKfLtvy","zMLSzw5HBwu","rNb3v3C","uvPbu3C","s0PMvwG","lcbOB3n0BMe","zxjFCw9Zx2e","yM9KEq","BNPwtuG","y2f0y2G","ywnRx2nVzgu","rgLfDgi","B25fCNjVCG","AhDtu08","wg5iCK4","ywDL","mti1nduWmxbnvvPYuG","EgjKwNG","Ahz5A20","t1bpBLu","qM1bwwG","uNDgDLO","r05fuKe","y29Uy2f0","Evbyrum","z2v0q3vYCMu","B2nRzxrtDwm","CMvJzwL2zwq","sM9zqMy","u1LMCeq","v1jAC3K","x25HDMLNyxq","id4G","rgPzshi","CNv1vKe","AuDptxG","yxKSihrYEsa","ihzHBgLKigq","x2LZtwLUAvC","zhLdrxe","B3jLtMfTzxm","u0X2qKO","DMrrq3G","qwnNvLK","thPkBvy","wuTWEe0","EvvyCu0","uxfNtwW","x3DZsw5ZDge","BhPRqLK","A1vwAKK","yNL0zxm","B2nRzxq","CgfYC2u","yxrLq291BNq","sLnptLa","mJG4ndy4oxH2ywfbsG","BKn5su0","u1PfsLG","swvmAum","x3nLCuLK","ELferLe","ig1LC3nHz2u","Dg9VigXHCMC","sxvor1K","vujsuha","zuH5A0i","tffuz0C","AhDNCxu","tg9Nsuq","rLjptLrjrvi","AKr4BhC","B1LNzuu","uxPiCMi","Cxnxvfu","sxDXrei","s25sqwO","EMLjzgq","B2fK","wLvyEfe","EwfxBuy","BvLvtgS","zK1Huw8","v1LUB2i","B3bLBG","zw5JB2rLrNi","uKvXrvy","s0LKzxm","v3H2D3C","B1vJvuW","y2XVC2uSihC","zw5XDwv1zq","wNf1DwG","C0LzD1e","BMnVzgLUzW","zxq9DxrMltG","x2rLC3rYB3K","A3HfCNu","zw50zwqGDhK","zNjVBuHHC2G","yNfZwgW","DMvYC2LVBG","DuDqu1u","CMLLC0nVDw4","mty4odfuELbXEwC","qLHjwNG","ignVzgu6ia","DMvY","y1H5A1m","uLnhwLq","rKLmrv9ot1q","yxbWBgLJyxq","yuPZwwG","BgfnAvG","s1DTD0G","vfHVBxy","ywrKrxzLBNq","CuXwuLy","CM92AwrLige","tMfTzq","D3foCMi","rw9vEK8","q291BNq","AenSB3nLrxy","BfjnzuG","D3m6lY8","D2fZq2XLyw4","nhWXFdn8mNW","ywzL","vvvzDhG","Bxnfwvm","zfjgsKW","t0jZA0O","y3ruAw1LB3u","rxjYB3jdB2q","zNnkrMC","yw5Nzq","zw5HyMXLuw8","B25ozxr3B3i","ywr2yw5Jzq","qLDAEMW","sMjYqMe","sLLlBfu","C3rHCNq","uNbvru0","CgfNzxnOB3C","uNDAvNy","tw9KDwXL","C0XPC3rLBMu","zgjMDgC","DMjyqw8","B25TzxnZywC","x29Uq2XVC2u","Bu1hs1m","CMvHzhLtDge","sgTjseC","zwHRCNK","vvzvAxC","zNDPEwS","Ae9XCuu","BhrTuhu","y0j3DuW","y3zrtwG","nZi4nZyXnMDyC2zwyG","x2LUAxrhBg8","BezSDxnO","x2LZtM9Kzq","y2XVC2u","DhjPzxm","D3Hhtwy","BhftCeq","su1MAKi","wMj3vgS","thDqtMG","DhbnwKG","DhLWzq","Bwf4tg9ZC0m","CgjICdi","Ae1LC3nHz2u","rKX0qMS","zK9nAvK","mNWZFdv8mxW","x2DLDeLUDgu","rvjst1i","x2LZqNjVD3m","zLL4Cvm","z2vY","uu5jDhG","tLfJvMW","BxnN","BuXTCKS","mZy2otqYrhzQqKnn","ChbL","DuXdu3q","CMvXDwLYzwq","v0r4Cfq","EwnksgS","tLvUsNa","DvDXuwS","D1v6EKi","qNr1rw0","z1rNEhG","uvryEKy","su1JDei","nhWYFdn8mhW","DxbKyxrLq3u","EMjIBwm","rNjVBNrPzxi","vefnyMO","ruv0B1y","Bujdseq","r2fVEgq","ywnOzwqSihC","B2nkEe8","y2vVChG","yNvYCuC","r3bsvfy","CMvKDwnL","C2v0u3rVCMe","zxvks2y","EKnht2e","vKHtv2m","EgXqzxG","uhffyxq","BM93","zgvSzxrL","qM94A0W","DMfSDwvZ","x29WDgLVBNm","wNL3qKO","s2P1DMy","tg9NsurozxC","EKzqweO","m3WX","Bwf4uMv0CMK","uKzqtKu","rLDt","AgzSrxq","qLHAsMS","Ec1TC2CTCw8","sLDqt3i","t2nICw8","x2nSzwfYugK","C2v0zgi","q0Tnr0e","z2vtEw5J","uhjuB0u","yMXVy2TLza","nxWW","uNH6tvq","Ef9MCM9UDgK","DevKy0C","BNrfBMrWB2K","q1P2ywi","BwfW","DwPwCha","Dev2zw50","BffqDwe","zNPMBui","DLDZyMi","DKvkyMK","turLDLq","CgvYquu","renPr20","ywXSq3vYC28","uLr4q1O","A2v5","wenXCei","uhDsteu","BMDuAw1LCG","DgvZDa","v1Hdt3G","BgLTAxq","zMX1C2HfEha","mhWZFdf8nhW","C2vYDMLJzq","zxLsAw4","zcWG","uvnLCMW","Dgv4Dc9Qyxy","DwffBwm","ELzeu20","q2zTCfe","zgv4wNi","yxHoExu","D3jPDgu","yxb1AuS","sMfcA2e","BMvY","D2fxsvy","EKvcz3a","D2LSBfjLy28","ww1bugG","zgnNsfq","CuLoBMu","qw1VDw50","zw50tgLZDgu","ze9HCMO","B25pCgvU","zuTnDxC","Bg9N","ywrKt25L","Cgf5Bg9Hza","ywXS","uw11CMW","B3jRig9MzMW","EKfOt0S","uMn4zfe","BwvZC2fNztO","D0Ljz3C","z2rWzNa","x2zVCM1HDeu","y1HhruC","t1zAA3q","B3nLrxzLBNq","x2DLBMvYyxq","tw5bEgi","Aw1LCYbPBIa","B25dBg9Zzq","tKDFrvjst1i","zgf0yq","CNbSzuO","CMvZzxrdB3u","z2v0sxrLBq","BhnYvu8","vKvUrhu","y291BNq","vNLwBuu","tLL2Bvy","AMXMEe4","DxbyuMm","x2n1CNnVCKy","u0DZuwG","AuPNA3y","CMvWBgfJzui","rNDsruC","wgvPtfG","y3vYCMvUDeK","CM92AwrLihC","twPYrgW","zM9mDMC","D24GCMvHC28","BIWGAg9ZDg4","yNL0zu9MzNm","q0D1Cwe","yw9Yy2C","rNj0A3C","BMfTzq","AhrHqMq","AMney1m","ywDLrxzLBNq","x2HHBMrSzvi","z2v0qwXS","DKjIB3G","nJbOD0rjq2C","sNrAEwW","wgr2r2C","nNWYFdn8nhW","tvnoA3K","uxDXtMC","rxPPy0O","qwPcu2u","AwXK","Aw5KzxHpzG","qLnKCfO","zLnksNq","zLzzshe","wgnxuhe","ywrxrhu","Aez2r2O","Bg9IywXty28","t1bftG","CMvJB25Uzwm","zMXVB3i","AgXSq3C","s2rVwxi","vgLTzw91Da","CfHXwLi","uK5jreO","zvD0zhK","CgH2yvO","seXlDui","Aw5L","tLrxzMK","zwLlvw0","r0LAy1y","u3LMB0C","A01Ywha","DNDuvgC","zfbACfO","ihrVihjLDhi","DMPdA1G","mZyWEu5RAeHe","rKL2yMm","zM9YrwfJAa","uu9sq2G","vurctxC","A3HLExe","yKjPs1m","B2LXqMi","B2zMC2v0","vLnIAMG","zw5KCg9PBNq","rffYww4","DfHls2O","y3vZDg9Tshq","r3n6qve","u3zvy2G","x3bHDgHlzxK","wMzduwC","Dg9Y","DxvfvLq","zMLUza","yuz4vxi","Dg9tDhjPBMC","Efrurw52","yMfJA3vWigu","AwXLx25HBwu","zMDwzgK","x0vysvnu","y29UBMvJDeu","vhPzrMu","ywWGy3vYC28","r2fZAuu","x2rPC3bHDgm","yujPt1G","y2XLyxjtDg8","EgvOrKq","x2LZv29YA2u","zuvZAMq","rMz4C0y","x29UtwvZC2e","CwjKrNK","AgvHzgvY","B25SAw5L","uMzkCNO","Du9tCeS","s0nLy0m","EMv3thG","Dun2vhu","wuXWzem","s2fuuLa","y29UBMvJDca","rfjLzLa","CMvUDevUzha","sgn6rfm","AxnFywnR","yNLL","Aw9U","q3HxuNy","y3jLyxrLtwu","C2DPza","C0HKqNm","q1LiCee","q2rksem","D2vI","tefHvfa","CNzHBa","x3vYBa","ihrYEsbYzwm","zgvJB2rLzey","EuPjs3e","C1LyBK0","y29UBMvJDa","ywnR","ihbYB3rVy28","u2HHCMvKv28","uw56Eem","Cg9PBNrdB24","B25VCgvU","vxPxC2W","x2rLyNvN","y3jLyxrLrwW","CgvYC2LZDgu","C2nYAxb0","EvjLy29UBMu","AefXDMy","BwvZC2fNzq","BhrPCgXLihq","AwDHDg9Yt24","zv9ZDwnJzxm","Dg9hzw5LCMe","wNLbEeG","yxnJCMLWDa","CgLUz1rPBwu","t2jQzwn0","Bwj0EM4","uef3q2m","r2Tlrhq","AxDKsKu","CenNvve","CxndtM4","qxfcrLG","A2XHz0S","uwTYy0O","Dxrjza","txn2r2q","Euj1B0O","DNjmquC","zgLZywjSzue","mhW0","EhniuMS","Cg9fquK","yxKSig5LDhC","y2XLyxi","A3L2ALy","C29YDa","CM92AwrLigi","rgvKAwnHDgu","se5VEvu","y05hrLy","s29Xsw8","vK1sB1C","wvbfDhC","y2vZC0HHBMq","x2TLEvbHDgG","q2PWD2m","Dg9cExrLCW","EfDSBe4","qxjbvxi","Affnt0u","zv90Aw1LB3u","BKXPBMu","x2LUDgvYDMe","ANnxtMG","BMvJDa","yuPUuxm","t1fQwfO","yNz2yxm","Bg9NsurozxC","Cg9W","DhjPBq","DeLK","AwHWwu0","twzSCgS","B3zqweu","ze5ywLq","q0P1ruC","qKvrsfC","De9YyKG","CuvorMu","wLbArui","vxbKyxrLq28","zxH0ugf5Bg8","vLn5vue","sLLPEwO","Dw5ZAwDUzwq","AM9XswW","CvjoBeS","qNP0vva","q0zYww8","CMfTzq","sgvWAwq","Ee1JDLy","txjyuNi","Aw9UvgLTzw8","B0fxD04","yuDlrvC","C0rvrMC","qwjVCNrfCNi","ANrxruW","C25Vvg8","rhPyu3O","Afb0zM0","zwn0","y2HHCKnVzgu","C3nHz2vfDMu","vgfN","quXm","qLrAyM8","vhzoteW","AevYCM9Yrxy","AvD6BvC","wgHfzw8","D0Xltfq","reX6uxy","vMDtzNy","ywXPzcb1CMW","x3nLBMrby2S","A0nXyKC","zLzwywW","ywnRDxbfBMq","yxbWBhK","x2jPBMfYEvq","AxvvvLe","zxH0zw5ZAw8","BuHOr2m","y3vYDMfSDwu","BM9Uzv9UB24","B0fYy0u","Axnby2TdBgu","rgDzsuq","DMfiDK0","BM56vMW","r296vhO","rNL2rgi","tuHtv1y","qK5Zvxu","y2HLy2Tszwe","v2vPEgLUsLm","rKHKA24","CwDKAMe","CNnVCKzPBgu","zMzmAw5L","suPbt0O","yNvMzMvYzwq","BeLgsM8","weDozui","CMvHC29U","BwfUDwfSihi","wLnsB0y","DKzPugO","EgDQDxC","yxnZAwDU","zufnqvy","v25jtwi","s25zq1C","C2fNzq","C29Tzq","yxrHlcbKyxq","yxv0B21HDgK","tLDhDMG","zgvSzxrLrge","BgLZDgvUtMu","yM9jBNy","Eg5Js3q","D3jPDgvvAw4","ChjVDg9JB2W","z3b2sw0","ywXSzwqGBxu","C2DnD2S","CwXoBfm","zw1PDa","Ag9hC1u","AeHSwfK","AKDQvNe","DeLUDgvYy2u","rKvyseK","ihrPBwvZ","vMzuAw4","qxrRrwy","C3vJy2vZCW","D1rQuLC","s2L0wuW","C3vIyxjYyxK","C2v0y3vYC28","qNvorve","AMvJDfn0B3i","AureBMO","CMvWBgfJzq","Au5ntu4","AKT5ruC","BNrLCG","AxnbCNjHEq","zxj2AwnL","zxjFBxnNAwq","zvHxD0O","DKvwqKq","wvzty1i","uMTzteS","AxnszwfKEq","A2TPyNa","r0fkAeC","suvYueu","uvP5ENi","tgTnDxu","uvH2vKy","twz3suy","q0Dowwu","reP5v0G","x2LUAxrqCM8","BgHwufq","z2v0q3vYC28","yMfSrxzLBNq","A1n0yxr1C0m","C3PoC00","D1PIBLa","tLP2v24","EuLwwNa","CM92AwrLihy","reiGzMfPBgu","AxnrB1nnzxm","uuPPuhe","A0rQrvC","BwvY","zwrPyxrLBhK","DhDYsLa","ruXOwhm","ENPpuwy","t3bLBKv2zw4","zcbLCNjVCI4","BvPSBKW","B2zM","BMDLza","qKjlEuG","CM1Hve0","rvzbC0O","vvnmzKi","ywrK","zNjVBu51Bwi","zwryEuG","C3rVCMu","C2vUDa","tNf6Bva","vw5Oyw5KBgu","q29UzMLN","twLZC2LUzYa","BMnLq2XVC2u","q1fkB0C","wfL2Eee","qvDxwxC","CvPfA3i","nNWWFdq","Aw9Ul2PZB24","yKnVAxm","q2rRwei","EMrIEfC","ywnOzwq","yNHJBwm","zw5HyMXLqxu","AgrLvuC","yM9usLG","uxLLu2e","x2n1CNnVCK0","C3rYAw5NAwy","r0Dcu1y","q2HJqLu","yxjmCwu","B3jpBMXPBMu","q1jNB2y","C3Pcz20","uxjbAhq","vezvyvu","C2vYDMLJzs0","yvDzwMe","AgfZt3DUuhi","Cg55uMO","CvHKtLe","C3rYAw5N","zcWGDw5RBM8","BxLMsvi","EgzKwva","De9ovxu","sKrbwve","DeL0Bxe","CMvZDwX0","whbRENO","uLjpuG","r2f2CMS","wuXnzg4","Cgf5Bg9Hzfq","DMfSDwu","Bg9Nsurhzw4","CKrKBvK","Dg9cExrLC0i","wvbQreu","ywnRpwzYB24","r0L5wwO","tgfSqLu","BwvKAwf0zwW","verYrfy","qwTfA04","x194x21Zz18","yw9XqwG","x3bPBMDmB3m","x3nVy2TLDa","sgvUv1e","uxfOuee","r1zXww0","zMLN","su5qrM8","AKvoCfi","ywD6wM8","EvDzrLC","zufJAW","B2nRzxrgywK","yKzPvgC","zMn3she","C2HPzNq","r3vPzeS","v1HTChe","Agnvy3y","x3fVC0rc","ww14t2y","uLDgCfO","u3jmBvG","tgHyB1y","CMvHzg9UBhK","qw1RvxC","DfzIze4","y29UBMvJDfm","zNjdBhm","sg9TuLy","CgfNzwHPzgu","BLzbyuW","uxHjsuG","CffbsfC","CfPuCge","DgfIyxnL","CLDotgW","y1PTwhy","DxbNCMfKzw4","qKzZzNu","AKLws1m","BePPBgK","BxnNsuq","igzHAwWSig0","DMvYC2LVBMm","DNfTrKC","uNbTEeG","C2XPy2u","nxWWFdj8nhW","rxrJAfO","y3vYC29Y","tNLnELm","ufv3ree","CYbHBhjLywq","uMfKEw4","x21LC3nHz2u","C09SEwO","De5iC2q","y3jLyxrLt3a","sfH4zLi","zhLPA2y","B3bLCNr5","tNzkAha","yvLbv3u","DhjHBNnHy3q","BMrLEa","x3DZ","ExDyAwi","yMLUza","AgP3AMm","B3nLza","t3nMEw8","BMCGzMfPBgu","yMLUyxj5","ugrJyui","vgLUt0m","CMvHzfvjBNq","wvDSAeK","zhPMC0i","CwrbBw8","CfDKtwi","sNfWyMO","ru1uEe4","Dg1quve","ChrVCG","AM9PBG","v2n6s2u","AeTVqwS","uxvsAKC","ysbTDxn0igi","A1HmCeO","B25mAw5L","s1fxvgS","zgv2AwnLx2K","qvbjBwK","x2HHBMrSzu8","rxvJC2q","ze1zDgm","ALLcyNm","BgjorhG","Bhz2CNm","BfLlB2q","r1foCuG","txLtBe8","AwvPuhO","sNrvEe8","CgLUz19VBMm","Dg9cExrLC0W","AKPYuKe","D3nZoI8V","CKvJu1K","D1DLDMe","sxbIufG","ANzvsvq","B25tDg9Wsw0","thLzsfu","B2rKswq","rhDkq0S","zNjHBwvuExa","Ae9Rq1O","yND2sLi","tMfAuwO","v2HJt2W","uM1JDMi","m3WWFdj8nhW","u0z1y0K","AefJA01LC3m","A293qvO","Egn3y0S","D1PAywe","s1vnqKm","DKjutxe","wNrbsKC","DgLUzYbZzxi","C2v0sxrLBq","D3L4yLC","C0XcA3K","Eefvt1e","CNnVCL92ywW","mtaYnZeZnNfyy0jPzq","wxPUCfm","sKjICvq","A1P5CfC","BwvZC2fNzv8","DMfS","CuTbELC","thj1wvi","A1v6Evy","ufjtu0e","B1fwwwm","zKDADMO","tvzdC3q","sK5HBhi","z2vvv20","mti1nda1nZb3CxnWuNm","qvfzzvi","uLnWDuS","suvtx0vsuK8","BgLUzw5V","C0fMtha","r1b4Cgq","BMT1zxG","y2HnyxHuCMK","Aw50zwDLCIa","rujJDva","vvrIAxi","v3L5Chi","BwLZzq","CgXLyxnLiha","wurwrLm","uxj2v2K","z2vrDwv1zuW","CgLUz0LUDgu","yuTYyNq","B3bLBKrc","zxjHDg9Y","C0XKt0q","wMLyveK","CMvZzxruCMK","mNW0Fdb8m3W","t2zNA0q","EvPNr3G","Aw5Lza","ww1Tvhe","v3zIrwq","qLnIuwO","ELjNyvy","uvP5Aha","ChvZAa","zgPQtxy","z1rPBwvVDxq","B1n6ruy","CgLUz09Uy2u","wuvSyvi","y3jLyxrLq2W","z2u6ia","qM54Egu","x2rPC2nVBM4","BMXdCMy","rNPswLG","AwHouNm","AfHPufm","BxzrAvi","BejMre0","zxn1Cxi","DgjHu1i","rhHuq3O","tg9JAW","DLDMwMO","wNjZvfO","DwjRELC","sxHMBvy","CMvZzxrfBMq","C3bSAwnL","BLLLyum","sfnqDgu","CNzHBfzHBhu","AgfUz2u","DgLTzw91Da","D2TxsuC","DgHbv2K","rxnIuuK","Chv0","ENLNvNO","BwLUAvbYB2C","qKvswfG","yMT6zhe","vhjTCMG","vejlvvi","v0Lpvwy","quXOvwe","ywrKq291BNq","Avjlvfe","yKzfBMi","sNPkExa","C0Xf","v0TAqvK","r1juDvi","Eff0DK0","zNjVBNrPzxi","rLPtsgW","BMv3vMvYC2K","tKfusvzfx0u","DgvmB2Djre4","B25tDgfYDfi","vhnHqM4","zNjVBunOyxi","q05dBeO","ChjVDg90Exa","vfPiuM4","rxzLBNq","DgLTzw91DcW","AxmGDw5Kzwy","AMDUtKO","BNnNEwq","CM9YrxzLBNq","thPjtgu","x2LZtwLUAvq","AwXLtMfTzq","Bvfrrfe","x3bPBMC","q09otKvdveK","zuHhBhy","zw50","lcbxzwjtB2m","r2j3sNe","zxmGCMvHy2G","C2v0q3vYC28","y29UDgv4Da","x2nYzwf0zvm","zNjVBuj5Dgu","t2PLDLy","Dgv4DfbHEwW","wg1vu2y","CLvgAxa","yKHLvNK","yxjYyxLIDwy","quX0vLe","zw5NDgG","x3jLy29UBMu","AgH2qMW","yxnL","Bw1eDxy","zgvS","BffxshO","qLrfsxG","BvvXvve","EgnlwfO","zKfpwvC","uMfcrgG","tMv4ueq","yw5Hz2vY","rvfquuO","shrcCw8","z2v0u3rVCMe","wvHtquK","x2nVBM5Ly3q","vKrzDwC","zhjAsvG","z3nAswO","y29Kzq","C3HcvNa","sNbLsei","rhfXCLm","DMvUDa","u05eBu8","BMnrvKy","AhnArvq","tLPXDNq","zKXZyKi","zujWwNK","wfn4CLe","y2HnyxHdB3u","v0XPvhm","yxGGCMv0CMK","ihzHBgLKihm","A2v0ignVBNm","vNv1CKy","s29Tv28","AgLNAa","x2n1CNnVCK4","ExbL","Aw5KzxG","uMvHzcbWyxm","uMvJB25Uzwm","DLrHAfa","zgrruMe","CMfNzvn5BMm","x2HHBMrSzva","tKPPruC","yLPryw4","CM1AA2u","CMfUzg9T","sfzfq20","zwnVBM5Ly3q","x3bYzwzPEa","C3jJ","mdaWma","sxnwrvi","z01RBKK","CLnSCxG","AurlyvK","renYCK0","z2v0qwXSs2u","BNruCMLLC0m","zw5fDMvUDa","Efz1wue","DcbSAw1PDa","wePnzui","tM9ntge","zxjYtxnN","AK9jtLO","y3jLyxrLt2i","tgLZDgvUzxi","vw93te4","Bwv0Ag9K","DhDVCMTdAge","ugryqwC","z3ztDge","CLzHBhvLCW","DuPdrxe","A2v5CW","DhjLteW","y29UDgLUDwu","BgvUz3rO","Dg9oDw1Izxi","Ce91vNu","B25LCNjVCG","uMPdDuS","zw5JB2rPBMC","v0PWvuG","yvPZvfG","uMXHChK","wwDvv1u","t1bftL9fuLi","uezPz04","DgLLCKPtt04","tK1rA2m","mNWZFdb8mxW","u2Tss04","u2LUsge","r0DuEwm","qwDqC3K","ELLmEum","swXiqw0","q3bksKS","y29SBM8","turlwLu","CYbPBNn0yw4","zxjYB3i","tfnIBee","x1fVu01HBMe","BMvLzf9Hy2S","Dw5KzwzPBMu","zujjwMW","u01NwMe","B2jQzwn0u3q","zwrqsgC","zMPwseW","zxL0BwS","uxvLDwu","sxPoExu","q0rzsMy","BwLUzW","EKzZt24","uLHuA2y","v2LUzg93","C25ty3G","C3bSAxq","qxHJu0K","CvvMueO","wKPKuxy","yxjeBgi","qM9Muxq","DgHLBG","pxv0zI04","C0nVDw50zxi","x19LC01Vzhu","q3vZDg9Tq2W","EfHUuM0","zxHWB3j0CW","DxbwuMe","Ec1TC2CTy3u","r3L0v2i","EKLSAw4","t0zMAwK","icSG","De1HBMfNzxi","AxjLza","te9YzMu","C0X1A3C","x2vUzhbVAw4","EwrnswC","q2D0B1y","yvnbAgS","zvrVBwe","r0XjrNa","rwHVvgO","CuTuugq","u3rYyxrLz3K","wvv1ANy","CNjVCK1LC3m","svvczfi","ru1RzMy","CgjAsuq","q0Xpu0LorW","tgrwDKW","yxbWzw5Kq2G","Cw9Z","qLLpq1u","AwXSihvZzsa","zNvUy3rPB24","yw51Ce1LC3m","x3jLBw92zvC","sgnMAeq","yKjbuNa","y3r4","q29Kzq","B3bLBIa","rwvszKe","Ec11C2uT","BMCGDxjSoIa","r1LZuMi","DgXsyxK","BeLvugK","AxnAzxjV","y2XVC2veqG","qxnLywu","ELrtzxG","vfDjuhu","lcbTyxGGCMu","sg90CuC","BwPZtvi","BNnps1a","AxnrB1nby2S","C3P2swq","y3jLyxrLuMu","uKf4DMq","y0XbrNq","AxDSAha","y3jLyxrLrxi","DhjPzxmGCMu","x3bYB3rVy28","Cg9ctMO","yMLUyxj5vhK","wKTewfO","v2vIu29JA2u","Bg93","y29UC3rYDwm","y2fSBa"];return oa=function(){return t},oa()}for(ea in Re)[N(1327)+N(460),"CustomEr"+N(1164),N(1821)+"e","Event",N(382),"Frontier"+N(1501)+N(1213),N(1501)+N(1213),"OpenEvent",N(1233)+N(402),N(1103)+"oseEvent","createEr"+N(1164),"createMessageEvent",N(967)+N(1254),N(1385)+N(566)+N(1213),N(606)+N(697),N(1772)+N(1470)][N(509)](ea)===-1&&(Me[ea]=Re[ea]);var ea;Object[N(1566)+N(970)](Me,N(1326)+"le",{value:!0})});import{existsSync as C1,openSync as R1}from"node:fs";import{mkdir as D1}from"node:fs/promises";import{dirname as P1}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 D1(P1(i),{recursive:!0});let o=R1(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=st(process.execPath,d,{detached:!0,stdio:["ignore",o,o],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=nt(()=>{"use strict";Zt();re();Te();L1=G("spawn-daemon"),ls="COZE_BRIDGE_DAEMON"});import{spawn as PI}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 ti(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>${ti(r)}</key>
21
+ <string>${ti(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function wI(t,e){return new Promise((n,i)=>{let o=uI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Yr,xs,_a,dl,zp=it(()=>{"use strict";ne();Yr=K("supervisor.launchd"),xs="ai.coze.bridge",_a=wI,dl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function zI(t,e){return new Promise((r,i)=>{let o=PI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ei,hs,ma,ul,zp=nt(()=>{"use strict";re();ei=G("supervisor.launchd"),hs="ai.coze.bridge",ma=zI,ul={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>${hs}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Xr(t.nodeBin)}</string>
35
- <string>${Xr(t.entry)}</string>
34
+ <string>${ti(t.nodeBin)}</string>
35
+ <string>${ti(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>${Xr(t.logFile)}</string>
45
+ <string>${ti(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Xr(t.logFile)}</string>${gI(t.env)}
47
+ <string>${ti(t.logFile)}</string>${FI(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return mI(t.homeDir,"Library","LaunchAgents",`${xs}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await fI(pI(i),{recursive:!0}),await xI(i,this.renderConfig(t),"utf8"),Yr.info("plist written",{plistPath:i,activate:n}),!n)return;await _a("launchctl",["unload","-w",i]).catch(c=>Yr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await _a("launchctl",["load","-w",i]),Yr.info("launchd job loaded",{label:xs});let o=process.getuid?.()??0;await _a("launchctl",["kickstart","-k",`gui/${o}/${xs}`]),Yr.info("launchd job kickstarted",{label:xs,uid:o})},async uninstall(t){let e=this.configPath(t);await _a("launchctl",["unload","-w",e]).catch(n=>Yr.warn("launchctl unload failed (ignored)",{err:String(n)})),await hI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Yr.info("launchd job removed",{plistPath:e})}}});import{spawn as _I}from"node:child_process";import{mkdir as yI,unlink as bI,writeFile as EI}from"node:fs/promises";import{dirname as vI,join as Up}from"node:path";function ba(t,e){return t.isRoot?e:["--user",...e]}function II(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function Ea(t,e){return new Promise((n,i)=>{let o=_I(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ya,Qr,SI,ll,Gp=it(()=>{"use strict";ne();ya=K("supervisor.systemd"),Qr="coze-bridge.service",SI="/etc/systemd/system";ll={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return BI(t.homeDir,"Library","LaunchAgents",`${hs}.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"),ei.info("plist written",{plistPath:i,activate:r}),!r)return;await ma("launchctl",["unload","-w",i]).catch(c=>ei.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ma("launchctl",["load","-w",i]),ei.info("launchd job loaded",{label:hs});let o=process.getuid?.()??0;await ma("launchctl",["kickstart","-k",`gui/${o}/${hs}`]),ei.info("launchd job kickstarted",{label:hs,uid:o})},async uninstall(t){let e=this.configPath(t);await ma("launchctl",["unload","-w",e]).catch(r=>ei.warn("launchctl unload failed (ignored)",{err:String(r)})),await LI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),ei.info("launchd job removed",{plistPath:e})}}});import{spawn as UI}from"node:child_process";import{mkdir as HI,unlink as GI,writeFile as qI}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 o=UI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var wa,ni,WI,fl,Hp=nt(()=>{"use strict";re();wa=G("supervisor.systemd"),ni="coze-bridge.service",WI="/etc/systemd/system";fl={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
- ${II(t.env)}
62
+ ${KI(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Up(SI,Qr):Up(t.homeDir,".config","systemd","user",Qr)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await yI(vI(i),{recursive:!0}),await EI(i,this.renderConfig(t),"utf8"),ya.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await Ea("systemctl",ba(t,["daemon-reload"])),await Ea("systemctl",ba(t,n?["enable","--now",Qr]:["enable",Qr])),ya.info("systemd unit enabled",{unitName:Qr,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await Ea("systemctl",ba(t,["disable","--now",Qr])).catch(n=>ya.warn("systemctl disable failed (ignored)",{err:String(n)})),await bI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Ea("systemctl",ba(t,["daemon-reload"])).catch(()=>{}),ya.info("systemd unit removed",{unitPath:e})}}});import{spawn as AI}from"node:child_process";import{join as kI}from"node:path";function Hp(t,e){return new Promise((n,i)=>{let o=AI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?n():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ul,va,fl,qp=it(()=>{"use strict";ne();ul=K("supervisor.taskscheduler"),va="CozeBridge",fl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Up(WI,ni):Up(t.homeDir,".config","systemd","user",ni)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await HI(jI(i),{recursive:!0}),await qI(i,this.renderConfig(t),"utf8"),wa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await ya("systemctl",_a(t,["daemon-reload"])),await ya("systemctl",_a(t,r?["enable","--now",ni]:["enable",ni])),wa.info("systemd unit enabled",{unitName:ni,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await ya("systemctl",_a(t,["disable","--now",ni])).catch(r=>wa.warn("systemctl disable failed (ignored)",{err:String(r)})),await GI(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 Gp(t,e){return new Promise((r,i)=>{let o=$I(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var hl,ba,xl,qp=nt(()=>{"use strict";re();hl=G("supervisor.taskscheduler"),ba="CozeBridge",xl={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,61 +86,59 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return kI(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 Hp("schtasks",["/Create","/SC","ONLOGON","/TN",va,"/TR",n,"/RU",t.userName,"/F"]),ul.info("task scheduler entry created",{task:va,logFile:t.logFile})},async uninstall(t){await Hp("schtasks",["/Delete","/TN",va,"/F"]).catch(e=>ul.warn("schtasks /Delete failed (ignored)",{err:String(e)})),ul.info("task scheduler entry removed",{task:va})}}});var jp={};Ba(jp,{buildContext:()=>OI,getSupervisor:()=>PI,launchdSupervisor:()=>dl,systemdSupervisor:()=>ll,taskSchedulerSupervisor:()=>fl});import{homedir as TI,userInfo as RI}from"node:os";function PI(t=process.platform){switch(t){case"darwin":return dl;case"linux":return ll;case"win32":return fl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function DI(){let t={};for(let e of CI){let n=process.env[e];n&&(t[e]=n)}return t}function OI(){let t=Y();return{nodeBin:process.execPath,entry:el(t),logFile:t.logFile,homeDir:TI(),userName:RI().username,isRoot:process.getuid?.()===0,env:DI()}}var CI,Kp=it(()=>{"use strict";Pe();ha();zp();Gp();qp();CI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();ln();var Hl=K("acp-installer-warmup"),mg=["claude-code","codex"];async function ql(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(mg.map(async o=>{let c=await e(o);Hl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Hl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}Kt();ne();import{readdir as Dg}from"node:fs/promises";import{mkdir as $l,readFile as Pg,writeFile as Vl}from"node:fs/promises";import{join as ja}from"node:path";var Cg={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function hr(t,e,n){await $l(t,{recursive:!0});let i=Cg[e],o=ja(t,i);return await Vl(o,n??"","utf8"),o}async function Ka(t,e,n){let i=ja(t,".claude");await $l(i,{recursive:!0});let o=ja(i,"settings.local.json"),c={};try{let u=await Pg(o,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(c=h)}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(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=n)}return c.permissions=l,await Vl(o,JSON.stringify(c,null,2),"utf8"),o}var et=K("agent-detail-sync"),Og=6e4,Lg=5*6e4,ks=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Dg(n)}catch(o){et.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}et.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Se(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){et.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){et.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),et.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){et.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){et.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await Se(e,this.opts.paths);if(!i){et.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){et.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),m=x?Math.min(x.currentDelay*2,Lg):Og;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(o.agentId&&o.agentId!==e){et.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,l=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,l=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(et.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&et.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){et.debug("detail sync: no diff",{agentId:e});return}await Ge(i,this.opts.paths),et.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}),et.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var gd=qt(ku(),1);import{createHash as Ey}from"node:crypto";import{lstat as dd,mkdir as ld,readFile as Eo,readdir as _0,rm as ud,stat as pd,writeFile as fd}from"node:fs/promises";import{homedir as vy}from"node:os";import{basename as m0,dirname as Sy,join as he,normalize as Iy,relative as md,resolve as hd,sep as y0}from"node:path";import{Readable as b0}from"node:stream";import{pipeline as E0}from"node:stream/promises";import nw from"events";import ot from"fs";import{EventEmitter as jc}from"node:events";import df from"node:stream";import{StringDecoder as rw}from"node:string_decoder";import ff from"node:path";import Ir from"node:fs";import{dirname as mw,parse as gw}from"path";import{EventEmitter as Iw}from"events";import Ic from"assert";import{Buffer as qn}from"buffer";import*as Du from"zlib";import Aw from"zlib";import{posix as wr}from"node:path";import{basename as Qw}from"node:path";import so from"fs";import Ot from"fs";import zu from"path";import{win32 as u_}from"node:path";import Wu from"path";import kf from"node:fs";import T_ from"node:assert";import{randomBytes as Tf}from"node:crypto";import se from"node:fs";import Be from"node:path";import Rf from"fs";import po from"node:fs";import Ri from"node:path";import lt from"node:fs";import N_ from"node:fs/promises";import co from"node:path";import{join as Uf}from"node:path";import dt from"node:fs";import qf from"node:path";var ew=Object.defineProperty,tw=(t,e)=>{for(var n in e)ew(t,n,{get:e[n],enumerable:!0})},Tu=typeof process=="object"&&process?process:{stdout:null,stderr:null},iw=t=>!!t&&typeof t=="object"&&(t instanceof Wn||t instanceof df||sw(t)||ow(t)),sw=t=>!!t&&typeof t=="object"&&t instanceof jc&&typeof t.pipe=="function"&&t.pipe!==df.Writable.prototype.pipe,ow=t=>!!t&&typeof t=="object"&&t instanceof jc&&typeof t.write=="function"&&typeof t.end=="function",Wt=Symbol("EOF"),$t=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),Ds=Symbol("emittingEnd"),fi=Symbol("emittedError"),Os=Symbol("closed"),Ru=Symbol("read"),Ls=Symbol("flush"),Pu=Symbol("flushChunk"),Et=Symbol("encoding"),gr=Symbol("decoder"),He=Symbol("flowing"),hi=Symbol("paused"),Er=Symbol("resume"),qe=Symbol("buffer"),nt=Symbol("pipes"),je=Symbol("bufferLength"),Ya=Symbol("bufferPush"),Ns=Symbol("bufferShift"),Qe=Symbol("objectMode"),ke=Symbol("destroyed"),Xa=Symbol("error"),Qa=Symbol("emitData"),Cu=Symbol("emitEnd"),ec=Symbol("emitEnd2"),Pt=Symbol("async"),tc=Symbol("abort"),Ms=Symbol("aborted"),xi=Symbol("signal"),Ln=Symbol("dataListeners"),ct=Symbol("discarded"),pi=t=>Promise.resolve().then(t),aw=t=>t(),cw=t=>t==="end"||t==="finish"||t==="prefinish",dw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,lw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),lf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Er](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},uw=class extends lf{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)}},fw=t=>!!t.objectMode,hw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Wn=class extends jc{[He]=!1;[hi]=!1;[nt]=[];[qe]=[];[Qe];[Et];[Pt];[gr];[Wt]=!1;[fn]=!1;[Ds]=!1;[Os]=!1;[fi]=null;[je]=0;[ke]=!1;[xi];[Ms]=!1;[Ln]=0;[ct]=!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");fw(e)?(this[Qe]=!0,this[Et]=null):hw(e)?(this[Et]=e.encoding,this[Qe]=!1):(this[Qe]=!1,this[Et]=null),this[Pt]=!!e.async,this[gr]=this[Et]?new rw(this[Et]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[nt]});let{signal:n}=e;n&&(this[xi]=n,n.aborted?this[tc]():n.addEventListener("abort",()=>this[tc]()))}get bufferLength(){return this[je]}get encoding(){return this[Et]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Qe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Pt]}set async(t){this[Pt]=this[Pt]||!!t}[tc](){this[Ms]=!0,this.emit("abort",this[xi]?.reason),this.destroy(this[xi]?.reason)}get aborted(){return this[Ms]}set aborted(t){}write(t,e,n){if(this[Ms])return!1;if(this[Wt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Pt]?pi:aw;if(!this[Qe]&&!Buffer.isBuffer(t)){if(lw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(dw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Qe]?(this[He]&&this[je]!==0&&this[Ls](!0),this[He]?this.emit("data",t):this[Ya](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[He]):t.length?(typeof t=="string"&&!(e===this[Et]&&!this[gr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Et]&&(t=this[gr].write(t)),this[He]&&this[je]!==0&&this[Ls](!0),this[He]?this.emit("data",t):this[Ya](t),this[je]!==0&&this.emit("readable"),n&&i(n),this[He]):(this[je]!==0&&this.emit("readable"),n&&i(n),this[He])}read(t){if(this[ke])return null;if(this[ct]=!1,this[je]===0||t===0||t&&t>this[je])return this[$t](),null;this[Qe]&&(t=null),this[qe].length>1&&!this[Qe]&&(this[qe]=[this[Et]?this[qe].join(""):Buffer.concat(this[qe],this[je])]);let e=this[Ru](t||null,this[qe][0]);return this[$t](),e}[Ru](t,e){if(this[Qe])this[Ns]();else{let n=e;t===n.length||t===null?this[Ns]():typeof n=="string"?(this[qe][0]=n.slice(t),e=n.slice(0,t),this[je]-=t):(this[qe][0]=n.subarray(t),e=n.subarray(0,t),this[je]-=t)}return this.emit("data",e),!this[qe].length&&!this[Wt]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[Wt]=!0,this.writable=!1,(this[He]||!this[hi])&&this[$t](),this}[Er](){this[ke]||(!this[Ln]&&!this[nt].length&&(this[ct]=!0),this[hi]=!1,this[He]=!0,this.emit("resume"),this[qe].length?this[Ls]():this[Wt]?this[$t]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[He]=!1,this[hi]=!0,this[ct]=!1}get destroyed(){return this[ke]}get flowing(){return this[He]}get paused(){return this[hi]}[Ya](t){this[Qe]?this[je]+=1:this[je]+=t.length,this[qe].push(t)}[Ns](){return this[Qe]?this[je]-=1:this[je]-=this[qe][0].length,this[qe].shift()}[Ls](t=!1){do;while(this[Pu](this[Ns]())&&this[qe].length);!t&&!this[qe].length&&!this[Wt]&&this.emit("drain")}[Pu](t){return this.emit("data",t),this[He]}pipe(t,e){if(this[ke])return t;this[ct]=!1;let n=this[fn];return e=e||{},t===Tu.stdout||t===Tu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[nt].push(e.proxyErrors?new uw(this,t,e):new lf(this,t,e)),this[Pt]?pi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[nt].find(n=>n.dest===t);e&&(this[nt].length===1?(this[He]&&this[Ln]===0&&(this[He]=!1),this[nt]=[]):this[nt].splice(this[nt].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ct]=!1,this[Ln]++,!this[nt].length&&!this[He]&&this[Er]();else if(t==="readable"&&this[je]!==0)super.emit("readable");else if(cw(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[fi]){let i=e;this[Pt]?pi(()=>i.call(this,this[fi])):i.call(this,this[fi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[ct]&&!this[nt].length&&(this[He]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[ct]&&!this[nt].length&&(this[He]=!1)),e}get emittedEnd(){return this[fn]}[$t](){!this[Ds]&&!this[fn]&&!this[ke]&&this[qe].length===0&&this[Wt]&&(this[Ds]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Os]&&this.emit("close"),this[Ds]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[Qe]&&!n?!1:this[Pt]?(pi(()=>this[Qa](n)),!0):this[Qa](n);if(t==="end")return this[Cu]();if(t==="close"){if(this[Os]=!0,!this[fn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[fi]=n,super.emit(Xa,n);let o=!this[xi]||this.listeners("error").length?super.emit("error",n):!1;return this[$t](),o}else if(t==="resume"){let o=super.emit("resume");return this[$t](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[$t](),i}[Qa](t){for(let n of this[nt])n.dest.write(t)===!1&&this.pause();let e=this[ct]?!1:super.emit("data",t);return this[$t](),e}[Cu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[Pt]?(pi(()=>this[ec]()),!0):this[ec]())}[ec](){if(this[gr]){let e=this[gr].end();if(e){for(let n of this[nt])n.dest.write(e);this[ct]||super.emit("data",e)}}for(let e of this[nt])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Qe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Qe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Qe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ke,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ct]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[Wt])return e();let i,o,c=x=>{this.off("data",l),this.off("end",u),this.off(ke,h),e(),o(x)},l=x=>{this.off("error",c),this.off("end",u),this.off(ke,h),this.pause(),i({value:x,done:!!this[Wt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(ke,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,m)=>{o=m,i=x,this.once(ke,h),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[ct]=!1;let t=!1,e=()=>(this.pause(),this.off(Xa,e),this.off(ke,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Xa,e),this.once(ke,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ke])return t?this.emit("error",t):this.emit(ke),this;this[ke]=!0,this[ct]=!0,this[qe].length=0,this[je]=0;let e=this;return typeof e.close=="function"&&!this[Os]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return iw}},xw=ot.writev,En=Symbol("_autoClose"),At=Symbol("_close"),mi=Symbol("_ended"),fe=Symbol("_fd"),nc=Symbol("_finished"),Yt=Symbol("_flags"),rc=Symbol("_flush"),vc=Symbol("_handleChunk"),Sc=Symbol("_makeBuf"),ki=Symbol("_mode"),Bs=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),ic=Symbol("_onread"),vr=Symbol("_onwrite"),vn=Symbol("_open"),It=Symbol("_path"),gn=Symbol("_pos"),Ct=Symbol("_queue"),Sr=Symbol("_read"),sc=Symbol("_readSize"),Zt=Symbol("_reading"),gi=Symbol("_remain"),oc=Symbol("_size"),$s=Symbol("_write"),Nn=Symbol("_writing"),Vs=Symbol("_defaultFlag"),Hn=Symbol("_errored"),Kc=class extends Wn{[Hn]=!1;[fe];[It];[sc];[Zt]=!1;[oc];[gi];[En];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[Hn]=!1,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[It]=t,this[sc]=e.readSize||16*1024*1024,this[Zt]=!1,this[oc]=typeof e.size=="number"?e.size:1/0,this[gi]=this[oc],this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[fe]=="number"?this[Sr]():this[vn]()}get fd(){return this[fe]}get path(){return this[It]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){ot.open(this[It],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[fe]=e,this.emit("open",e),this[Sr]())}[Sc](){return Buffer.allocUnsafe(Math.min(this[sc],this[gi]))}[Sr](){if(!this[Zt]){this[Zt]=!0;let t=this[Sc]();if(t.length===0)return process.nextTick(()=>this[ic](null,0,t));ot.read(this[fe],t,0,t.length,null,(e,n,i)=>this[ic](e,n,i))}}[ic](t,e,n){this[Zt]=!1,t?this[kr](t):this[vc](e,n)&&this[Sr]()}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Zt]=!0,this[At](),this.emit("error",t)}[vc](t,e){let n=!1;return this[gi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[gi]<=0)&&(n=!1,this[At](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[fe]=="number"&&this[Sr](),!1;case"error":return this[Hn]?!1:(this[Hn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},pw=class extends Kc{[vn](){let t=!0;try{this[Tr](null,ot.openSync(this[It],"r")),t=!1}finally{t&&this[At]()}}[Sr](){let t=!0;try{if(!this[Zt]){this[Zt]=!0;do{let e=this[Sc](),n=e.length===0?0:ot.readSync(this[fe],e,0,e.length,null);if(!this[vc](n,e))break}while(!0);this[Zt]=!1}t=!1}finally{t&&this[At]()}}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.closeSync(t),this.emit("close")}}},lo=class extends nw{readable=!1;writable=!0;[Hn]=!1;[Nn]=!1;[mi]=!1;[Ct]=[];[Bs]=!1;[It];[ki];[En];[fe];[Vs];[Yt];[nc]=!1;[gn];constructor(t,e){e=e||{},super(e),this[It]=t,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[ki]=e.mode===void 0?438:e.mode,this[gn]=typeof e.start=="number"?e.start:void 0,this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[gn]!==void 0?"r+":"w";this[Vs]=e.flags===void 0,this[Yt]=e.flags===void 0?n:e.flags,this[fe]===void 0&&this[vn]()}emit(t,...e){if(t==="error"){if(this[Hn])return!1;this[Hn]=!0}return super.emit(t,...e)}get fd(){return this[fe]}get path(){return this[It]}[kr](t){this[At](),this[Nn]=!0,this.emit("error",t)}[vn](){ot.open(this[It],this[Yt],this[ki],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[Vs]&&this[Yt]==="r+"&&t&&t.code==="ENOENT"?(this[Yt]="w",this[vn]()):t?this[kr](t):(this[fe]=e,this.emit("open",e),this[Nn]||this[rc]())}end(t,e){return t&&this.write(t,e),this[mi]=!0,!this[Nn]&&!this[Ct].length&&typeof this[fe]=="number"&&this[vr](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[fe]===void 0||this[Nn]||this[Ct].length?(this[Ct].push(t),this[Bs]=!0,!1):(this[Nn]=!0,this[$s](t),!0)}[$s](t){ot.write(this[fe],t,0,t.length,this[gn],(e,n)=>this[vr](e,n))}[vr](t,e){t?this[kr](t):(this[gn]!==void 0&&typeof e=="number"&&(this[gn]+=e),this[Ct].length?this[rc]():(this[Nn]=!1,this[mi]&&!this[nc]?(this[nc]=!0,this[At](),this.emit("finish")):this[Bs]&&(this[Bs]=!1,this.emit("drain"))))}[rc](){if(this[Ct].length===0)this[mi]&&this[vr](null,0);else if(this[Ct].length===1)this[$s](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],xw(this[fe],t,this[gn],(e,n)=>this[vr](e,n))}}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},uf=class extends lo{[vn](){let t;if(this[Vs]&&this[Yt]==="r+")try{t=ot.openSync(this[It],this[Yt],this[ki])}catch(e){if(e?.code==="ENOENT")return this[Yt]="w",this[vn]();throw e}else t=ot.openSync(this[It],this[Yt],this[ki]);this[Tr](null,t)}[At](){if(this[En]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ot.closeSync(t),this.emit("close")}}[$s](t){let e=!0;try{this[vr](null,ot.writeSync(this[fe],t,0,t.length,this[gn])),e=!1}finally{if(e)try{this[At]()}catch{}}}},ww=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"]]),_w=t=>!!t.sync&&!!t.file,yw=t=>!t.sync&&!!t.file,bw=t=>!!t.sync&&!t.file,Ew=t=>!t.sync&&!t.file,vw=t=>!!t.file,Sw=t=>ww.get(t)||t,Wc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=Sw(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Mi=(t,e,n,i,o)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let h=Wc(c);if(o?.(h,l),_w(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,l)}else if(yw(h)){let x=e(h,l);return u?x.then(()=>u(),u):x}else if(bw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,l)}else if(Ew(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),kw=Aw.constants||{ZLIB_VERNUM:4736},Nt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},kw)),Tw=qn.concat,Ou=Object.getOwnPropertyDescriptor(qn,"concat"),Rw=t=>t,ac=Ou?.writable===!0||Ou?.set!==void 0?t=>{qn.concat=t?Rw:Tw}:t=>{},jn=Symbol("_superWrite"),Fs=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"}},cc=Symbol("flushFlag"),$c=class extends Wn{#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 Du[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Du[e](t)}catch(n){throw new Fs(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 Fs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Ic(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(qn.alloc(0),{[cc]: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}[jn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=qn.from(t,e)),this.#e)return;Ic(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},ac(!0);let l;try{let h=typeof t[cc]=="number"?t[cc]:this.#r;l=this.#t._processChunk(t,h),ac(!1)}catch(h){ac(!1),this.#o(new Fs(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new Fs(h,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let h=l[0];u=this[jn](qn.from(h));for(let x=1;x<l.length;x++)u=this[jn](l[x])}else u=this[jn](qn.from(l));return n&&n(),u}},hf=class extends $c{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Nt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Nt.Z_FINISH,t.fullFlushFlag=Nt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Nt.Z_SYNC_FLUSH),Ic(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},Pw=class extends hf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[jn](t){return this.#e?(this.#e=!1,t[9]=255,super[jn](t)):super[jn](t)}},Cw=class extends hf{constructor(t){super(t,"Unzip")}},xf=class extends $c{constructor(t,e){t=t||{},t.flush=t.flush||Nt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Nt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Nt.BROTLI_OPERATION_FLUSH,super(t,e)}},Dw=class extends xf{constructor(t){super(t,"BrotliCompress")}},Ow=class extends xf{constructor(t){super(t,"BrotliDecompress")}},pf=class extends $c{constructor(t,e){t=t||{},t.flush=t.flush||Nt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Nt.ZSTD_e_end,t.fullFlushFlag=Nt.ZSTD_e_flush,super(t,e)}},Lw=class extends pf{constructor(t){super(t,"ZstdCompress")}},Nw=class extends pf{constructor(t){super(t,"ZstdDecompress")}},Mw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Fw(t,e):Bw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Bw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},Fw=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),n?e[i-1]=mf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=gf(o))}},zw=t=>{let e=t[0],n=e===128?Gw(t.subarray(1,t.length)):e===255?Uw(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},Uw=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),l;i?l=mf(c):c===0?l=c:(i=!0,l=gf(c)),l!==0&&(n-=l*Math.pow(256,e-o-1))}return n},Gw=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(n+=o*Math.pow(256,e-i-1))}return n},mf=t=>(255^t)&255,gf=t=>(255^t)+1&255,Hw={};tw(Hw,{code:()=>Vc,isCode:()=>Js,isName:()=>qw,name:()=>uo,normalFsTypes:()=>wf});var Js=t=>uo.has(t),qw=t=>Vc.has(t),wf=new Set(["0","","1","2","3","4","5","6","7","D"]),uo=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"]]),Vc=new Map(Array.from(uo).map(t=>[t[1],t[0]])),Kn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Mn(t,e+156,1),c=wf.has(o),l=c?n:void 0,u=c?i:void 0;if(this.path=l?.path??Mn(t,e,100),this.mode=l?.mode??u?.mode??wn(t,e+100,8),this.uid=l?.uid??u?.uid??wn(t,e+108,8),this.gid=l?.gid??u?.gid??wn(t,e+116,8),this.size=l?.size??u?.size??wn(t,e+124,12),this.mtime=l?.mtime??u?.mtime??dc(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),Js(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Mn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=l?.uname??u?.uname??Mn(t,e+265,32),this.gname=l?.gname??u?.gname??Mn(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??wn(t,e+329,8)??0,this.devmin=l?.devmin??u?.devmin??wn(t,e+337,8)??0,t[e+475]!==0){let x=Mn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Mn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??dc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??dc(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=jw(this.path||"",n),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Bn(t,e,100,o)||this.needPax,this.needPax=_n(t,e+100,8,this.mode)||this.needPax,this.needPax=_n(t,e+108,8,this.uid)||this.needPax,this.needPax=_n(t,e+116,8,this.gid)||this.needPax,this.needPax=_n(t,e+124,12,this.size)||this.needPax,this.needPax=lc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Bn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Bn(t,e+265,32,this.uname)||this.needPax,this.needPax=Bn(t,e+297,32,this.gname)||this.needPax,this.needPax=_n(t,e+329,8,this.devmaj)||this.needPax,this.needPax=_n(t,e+337,8,this.devmin)||this.needPax,this.needPax=Bn(t,e+345,n,c)||this.needPax,t[e+475]!==0?this.needPax=Bn(t,e+345,155,c)||this.needPax:(this.needPax=Bn(t,e+345,130,c)||this.needPax,this.needPax=lc(t,e+476,12,this.atime)||this.needPax,this.needPax=lc(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,_n(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:uo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Vc.get(t));if(Js(e)||e==="Unsupported")this.#e=e;else if(Js(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},jw=(t,e)=>{let n=t,i="",o,c=wr.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=wr.dirname(n),n=wr.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?o=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?o=[n.slice(0,99),i,!0]:(n=wr.join(wr.basename(i),n),i=wr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Mn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),dc=(t,e,n)=>Kw(wn(t,e,n)),Kw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,n)=>Number(t[e])&128?zw(t.subarray(e,e+n)):$w(t,e,n),Ww=t=>isNaN(t)?void 0:t,$w=(t,e,n)=>Ww(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Vw={12:8589934591,8:2097151},_n=(t,e,n,i)=>i===void 0?!1:i>Vw[n]||i<0?(Mw(i,t.subarray(e,e+n)),!0):(Jw(t,e,n,i),!1),Jw=(t,e,n,i)=>t.write(Zw(i,n),e,n,"ascii"),Zw=(t,e)=>Yw(Math.floor(t).toString(8),e),Yw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",lc=(t,e,n,i)=>i===void 0?!1:_n(t,e,n,i.getTime()/1e3),Xw=new Array(156).join("\0"),Bn=(t,e,n,i)=>i===void 0?!1:(t.write(i+Xw,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),io=class _f{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new Kn({path:("PaxHeader/"+Qw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,n,"utf8");for(let c=n+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,c=Buffer.byteLength(o),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,n,i=!1){return new _f(e_(t_(e),n),i)}},e_=(t,e)=>e?Object.assign({},e,t):t,t_=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(n_,Object.create(null)),n_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},r_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ee=r_!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),i_=class extends Wn{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))))}},fo=(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))},s_=1024*1024,Ac=Buffer.from([31,139]),kc=Buffer.from([40,181,47,253]),o_=Math.max(Ac.length,kc.length),xt=Symbol("state"),Fn=Symbol("writeEntry"),Vt=Symbol("readEntry"),uc=Symbol("nextEntry"),Lu=Symbol("processEntry"),Dt=Symbol("extendedHeader"),wi=Symbol("globalExtendedHeader"),hn=Symbol("meta"),Nu=Symbol("emitMeta"),we=Symbol("buffer"),Jt=Symbol("queue"),xn=Symbol("ended"),fc=Symbol("emittedEnd"),zn=Symbol("emit"),Ce=Symbol("unzip"),zs=Symbol("consumeChunk"),Us=Symbol("consumeChunkSub"),hc=Symbol("consumeBody"),Mu=Symbol("consumeMeta"),Bu=Symbol("consumeHeader"),_i=Symbol("consuming"),xc=Symbol("bufferConcat"),Gs=Symbol("maybeEnd"),_r=Symbol("writing"),pn=Symbol("aborted"),Hs=Symbol("onDone"),Un=Symbol("sawValidEntry"),qs=Symbol("sawNullBlock"),js=Symbol("sawEOF"),Fu=Symbol("closeStream"),a_=()=>!0,Ni=class extends Iw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Jt]=[];[we];[Vt];[Fn];[xt]="begin";[hn]="";[Dt];[wi];[xn]=!1;[Ce];[pn]=!1;[Un];[qs]=!1;[js]=!1;[_r]=!1;[_i]=!1;[fc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Hs,()=>{(this[xt]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Hs,t.ondone):this.on(Hs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||s_,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[Fu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){fo(this,t,e,n)}[Bu](t,e){this[Un]===void 0&&(this[Un]=!1);let n;try{n=new Kn(t,e,this[Dt],this[wi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[qs]?(this[js]=!0,this[xt]==="begin"&&(this[xt]="header"),this[zn]("eof")):(this[qs]=!0,this[zn]("nullBlock"));else if(this[qs]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let o=this[Fn]=new i_(n,this[Dt],this[wi]);if(!this[Un])if(o.remain){let c=()=>{o.invalid||(this[Un]=!0)};o.on("end",c)}else this[Un]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[zn]("ignoredEntry",o),this[xt]="ignore",o.resume()):o.size>0&&(this[hn]="",o.on("data",c=>this[hn]+=c),this[xt]="meta"):(this[Dt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[xt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[xt]="body":(this[xt]="header",o.end()),this[Vt]?this[Jt].push(o):(this[Jt].push(o),this[uc]())))}}}[Fu](){queueMicrotask(()=>this.emit("close"))}[Lu](t){let e=!0;if(!t)this[Vt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Vt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[uc]()),e=!1);return e}[uc](){do;while(this[Lu](this[Jt].shift()));if(this[Jt].length===0){let t=this[Vt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[hc](t,e){let n=this[Fn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(o),n.blockRemain||(this[xt]="header",this[Fn]=void 0,n.end()),o.length}[Mu](t,e){let n=this[Fn],i=this[hc](t,e);return!this[Fn]&&n&&this[Nu](n),i}[zn](t,e,n){this[Jt].length===0&&!this[Vt]?this.emit(t,e,n):this[Jt].push([t,e,n])}[Nu](t){switch(this[zn]("meta",this[hn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Dt]=io.parse(this[hn],this[Dt],!1);break;case"GlobalExtendedHeader":this[wi]=io.parse(this[hn],this[wi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Dt]??Object.create(null);this[Dt]=e,e.path=this[hn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Dt]||Object.create(null);this[Dt]=e,e.linkpath=this[hn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[pn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[pn])return n?.(),!1;if((this[Ce]===void 0||this.brotli===void 0&&this[Ce]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<o_)return this[we]=t,n?.(),!0;for(let l=0;this[Ce]===void 0&&l<Ac.length;l++)t[l]!==Ac[l]&&(this[Ce]=!1);let o=!1;if(this[Ce]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<kc.length;l++)if(t[l]!==kc[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Ce]===!1&&c)if(t.length<512)if(this[xn])this.brotli=!0;else return this[we]=t,n?.(),!0;else try{new Kn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ce]===void 0||this[Ce]===!1&&(this.brotli||o)){let l=this[xn];this[xn]=!1,this[Ce]=this[Ce]===void 0?new Cw({}):o?new Nw({}):new Ow({}),this[Ce].on("data",h=>this[zs](h)),this[Ce].on("error",h=>this.abort(h)),this[Ce].on("end",()=>{this[xn]=!0,this[zs]()}),this[_r]=!0;let u=!!this[Ce][l?"end":"write"](t);return this[_r]=!1,n?.(),u}}this[_r]=!0,this[Ce]?this[Ce].write(t):this[zs](t),this[_r]=!1;let i=this[Jt].length>0?!1:this[Vt]?this[Vt].flowing:!0;return!i&&this[Jt].length===0&&this[Vt]?.once("drain",()=>this.emit("drain")),n?.(),i}[xc](t){t&&!this[pn]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[Gs](){if(this[xn]&&!this[fc]&&!this[pn]&&!this[_i]){this[fc]=!0;let t=this[Fn];if(t&&t.blockRemain){let e=this[we]?this[we].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[we]&&t.write(this[we]),t.end()}this[zn](Hs)}}[zs](t){if(this[_i]&&t)this[xc](t);else if(!t&&!this[we])this[Gs]();else if(t){if(this[_i]=!0,this[we]){this[xc](t);let e=this[we];this[we]=void 0,this[Us](e)}else this[Us](t);for(;this[we]&&this[we]?.length>=512&&!this[pn]&&!this[js];){let e=this[we];this[we]=void 0,this[Us](e)}this[_i]=!1}(!this[we]||this[xn])&&this[Gs]()}[Us](t){let e=0,n=t.length;for(;e+512<=n&&!this[pn]&&!this[js];)switch(this[xt]){case"begin":case"header":this[Bu](t,e),e+=512;break;case"ignore":case"body":e+=this[hc](t,e);break;case"meta":e+=this[Mu](t,e);break;default:throw new Error("invalid state: "+this[xt])}e<n&&(this[we]=this[we]?Buffer.concat([t.subarray(e),this[we]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[pn]||(this[Ce]?(t&&this[Ce].write(t),this[Ce].end()):(this[xn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Gs]())),this}},Ti=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)},c_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},yf=(t,e)=>{let n=new Map(e.map(c=>[Ti(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||gw(c).root||".",h;if(c===u)h=!1;else{let x=n.get(c);h=x!==void 0?x:o(mw(c),u)}return n.set(c,h),h};t.filter=i?(c,l)=>i(c,l)&&o(Ti(c)):c=>o(Ti(c))},d_=t=>{let e=new Ni(t),n=t.file,i;try{i=Ir.openSync(n,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=Ir.readSync(i,l,0,o.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<o.size;){let h=Ir.readSync(i,u,0,c,l);if(h===0)break;l+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},l_=(t,e)=>{let n=new Ni(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{n.on("error",l),n.on("end",c),Ir.stat(o,(u,h)=>{if(u)l(u);else{let x=new Kc(o,{readSize:i,size:h.size});x.on("error",l),x.pipe(n)}})})},Rr=Mi(d_,l_,t=>new Ni(t),t=>new Ni(t),(t,e)=>{e?.length&&yf(t,e),t.noResume||c_(t)}),bf=(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:f_,parse:Uu}=u_,Jc=t=>{let e="",n=Uu(t);for(;f_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Uu(t)}return[e,t]},ho=["|","<",">","?",":"],Zc=ho.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),h_=new Map(ho.map((t,e)=>[t,Zc[e]])),x_=new Map(Zc.map((t,e)=>[t,ho[e]])),Gu=t=>ho.reduce((e,n)=>e.split(n).join(h_.get(n)),t),p_=t=>Zc.reduce((e,n)=>e.split(n).join(x_.get(n)),t),Ef=(t,e)=>e?(t=ee(t).replace(/^\.(\/|$)/,""),Ti(e)+"/"+t):ee(t),m_=16*1024*1024,Hu=Symbol("process"),qu=Symbol("file"),ju=Symbol("directory"),Tc=Symbol("symlink"),Ku=Symbol("hardlink"),yi=Symbol("header"),Zs=Symbol("read"),Rc=Symbol("lstat"),Ys=Symbol("onlstat"),Pc=Symbol("onread"),Cc=Symbol("onreadlink"),Dc=Symbol("openfile"),Oc=Symbol("onopenfile"),yn=Symbol("close"),oo=Symbol("mode"),Lc=Symbol("awaitDrain"),pc=Symbol("ondrain"),Lt=Symbol("prefix"),vf=class extends Wn{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=Wc(e);super(),this.path=ee(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||m_,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[c,l]=Jc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=p_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ee(n.absolute||zu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[Ys](o):this[Rc]()}warn(t,e,n={}){return fo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Rc](){Ot.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ys](e)})}[Ys](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=__(t),this.emit("stat",t),this[Hu]()}[Hu](){switch(this.type){case"File":return this[qu]();case"Directory":return this[ju]();case"SymbolicLink":return this[Tc]();default:return this.end()}}[oo](t){return bf(t,this.type==="Directory",this.portable)}[Lt](t){return Ef(t,this.prefix)}[yi](){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 Kn({path:this[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](this.linkpath):this.linkpath,mode:this[oo](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 io({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[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](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)}[ju](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[yi](),this.end()}[Tc](){Ot.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Cc](e)})}[Cc](t){this.linkpath=ee(t),this[yi](),this.end()}[Ku](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ee(zu.relative(this.cwd,t)),this.stat.size=0,this[yi](),this.end()}[qu](){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[Ku](e);this.linkCache.set(t,this.absolute)}if(this[yi](),this.stat.size===0)return this.end();this[Dc]()}[Dc](){Ot.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Oc](e)})}[Oc](t){if(this.fd=t,this.#e)return this[yn]();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[Zs]()}[Zs](){let{fd:t,buf:e,offset:n,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Ot.read(t,e,n,i,o,(c,l)=>{if(c)return this[yn](()=>this.emit("error",c));this[Pc](l)})}[yn](t=()=>{}){this.fd!==void 0&&Ot.close(this.fd,t)}[Pc](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[yn](()=>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[yn](()=>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[pc]():this[Lc](()=>this[pc]())}[Lc](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)}[pc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[yn](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[Zs]()}},g_=class extends vf{sync=!0;[Rc](){this[Ys](Ot.lstatSync(this.absolute))}[Tc](){this[Cc](Ot.readlinkSync(this.absolute))}[Dc](){this[Oc](Ot.openSync(this.absolute,"r"))}[Zs](){let t=!0;try{let{fd:e,buf:n,offset:i,length:o,pos:c}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let l=Ot.readSync(e,n,i,o,c);this[Pc](l),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[Lc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Ot.closeSync(this.fd),t()}},w_=class extends Wn{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 fo(this,t,e,n)}constructor(t,e={}){let n=Wc(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[oo](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 o=!1;if(!this.preservePaths){let[l,u]=Jc(this.path);l&&typeof u=="string"&&(this.path=u,o=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Kn({path:this[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new io({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[Lt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Lt](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)}[Lt](t){return Ef(t,this.prefix)}[oo](t){return bf(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}},__=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",y_=class Ar{tail;head;length=0;static create(e=[]){return new Ar(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)E_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)v_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,o=0;i;o++)e.call(n,i.value,o,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(n,i.value,o,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Ar;for(let o=this.head;o;)i.push(e.call(n,o.value,this)),o=o.next;return i}mapReverse(e,n){n=n||this;var i=new Ar;for(let o=this.tail;o;)i.push(e.call(n,o.value,this)),o=o.prev;return i}reduce(e,n){let i,o=this.head;if(arguments.length>1)i=n;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,n){let i,o=this.tail;if(arguments.length>1)i=n;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Ar;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<n;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Ar;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.length,c=this.tail;for(;c&&o>n;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let l=0;o&&l<e;l++)o=o.next;let c=[];for(let l=0;o&&l<n;l++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let l of i)o=b_(this,o,l);return c}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=n,this.tail=e,this}};function b_(t,e,n){let i=e,o=e?e.next:t.head,c=new Yc(n,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function E_(t,e){t.tail=new Yc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function v_(t,e){t.head=new Yc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Yc=class{list;next;prev;value;constructor(t,e,n,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},$u=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Vu=Buffer.alloc(1024),Xs=Symbol("onStat"),bi=Symbol("ended"),vt=Symbol("queue"),Ei=Symbol("pendingLinks"),mn=Symbol("current"),Gn=Symbol("process"),vi=Symbol("processing"),Ks=Symbol("processJob"),St=Symbol("jobs"),mc=Symbol("jobDone"),Qs=Symbol("addFSEntry"),Ju=Symbol("addTarEntry"),Nc=Symbol("stat"),Mc=Symbol("readdir"),eo=Symbol("onreaddir"),to=Symbol("pipe"),Zu=Symbol("entry"),gc=Symbol("entryOpt"),no=Symbol("writeEntryClass"),Sf=Symbol("write"),wc=Symbol("ondrain"),xo=class extends Wn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[no];onWriteEntry;[vt];[Ei]=new Map;[St]=0;[vi]=!1;[bi]=!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[no]=vf,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 Pw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Dw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Lw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[wc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[wc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[vt]=new y_,this[St]=0,this.jobs=Number(t.jobs)||4,this[vi]=!1,this[bi]=!1}[Sf](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[bi]=!0,this[Gn](),n&&n(),this}write(t){if(this[bi])throw new Error("write after end");return typeof t=="string"?this[Qs](t):this[Ju](t),this.flowing}[Ju](t){let e=ee(Wu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new $u(t.path,e);n.entry=new w_(t,this[gc](n)),n.entry.on("end",()=>this[mc](n)),this[St]+=1,this[vt].push(n)}this[Gn]()}[Qs](t){let e=ee(Wu.resolve(this.cwd,t));this[vt].push(new $u(t,e)),this[Gn]()}[Nc](t){t.pending=!0,this[St]+=1;let e=this.follow?"stat":"lstat";so[e](t.absolute,(n,i)=>{t.pending=!1,this[St]-=1,n?this.emit("error",n):this[Xs](t,i)})}[Xs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[mn])this[Ks](t);else{let n=`${e.dev}:${e.ino}`,i=this[Ei].get(n);i?i.push(t):this[Ei].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Gn]()}[Mc](t){t.pending=!0,this[St]+=1,so.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[St]-=1,e)return this.emit("error",e);this[eo](t,n)})}[eo](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Gn]()}[Gn](){if(!this[vi]){this[vi]=!0;for(let t=this[vt].head;t&&this[St]<this.jobs;t=t.next)if(this[Ks](t.value),t.value.ignore){let e=t.next;this[vt].removeNode(t),t.next=e}this[vi]=!1,this[bi]&&this[vt].length===0&&this[St]===0&&(this.zip?this.zip.end(Vu):(super.write(Vu),super.end()))}}get[mn](){return this[vt]&&this[vt].head&&this[vt].head.value}[mc](t){this[vt].shift(),this[St]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Ei].get(n);if(i){this[Ei].delete(n);for(let o of i)o.pending=!1,this[Ks](o)}}this[Gn]()}[Ks](t){if(t.pending&&t.pendingLink&&t===this[mn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[mn]&&!t.piped&&this[to](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Xs](t,e):this[Nc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[eo](t,e):this[Mc](t),!t.readdir)return}if(t.entry=this[Zu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[to](t)}}}[gc](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}}[Zu](t){this[St]+=1;try{return new this[no](t.path,this[gc](t)).on("end",()=>this[mc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[wc](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[to](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Qs](c+i)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",i=>{n.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,n={}){fo(this,t,e,n)}},Xc=class extends xo{sync=!0;constructor(t){super(t),this[no]=g_}pause(){}resume(){}[Nc](t){let e=this.follow?"statSync":"lstatSync";this[Xs](t,so[e](t.absolute))}[Mc](t){this[eo](t,so.readdirSync(t.absolute))}[to](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Qs](c+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Sf](i)})}},S_=(t,e)=>{let n=new Xc(t),i=new uf(t.file,{mode:t.mode||438});n.pipe(i),If(n,e)},I_=(t,e)=>{let n=new xo(t),i=new lo(t.file,{mode:t.mode||438});n.pipe(i);let o=new Promise((c,l)=>{i.on("error",l),i.on("close",c),n.on("error",l)});return Af(n,e).catch(c=>n.emit("error",c)),o},If=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Rr({file:ff.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Af=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Rr({file:ff.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},A_=(t,e)=>{let n=new Xc(t);return If(n,e),n},k_=(t,e)=>{let n=new xo(t);return Af(n,e).catch(i=>n.emit("error",i)),n},pA=Mi(S_,I_,A_,k_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),R_=process.env.__FAKE_PLATFORM__||process.platform,Pf=R_==="win32",{O_CREAT:Cf,O_NOFOLLOW:Yu,O_TRUNC:Df,O_WRONLY:Of}=Rf.constants,Lf=Number(process.env.__FAKE_FS_O_FILENAME__)||Rf.constants.UV_FS_O_FILEMAP||0,P_=Pf&&!!Lf,C_=512*1024,D_=Lf|Df|Cf|Of,Xu=!Pf&&typeof Yu=="number"?Yu|Df|Cf|Of:null,Nf=Xu!==null?()=>Xu:P_?t=>t<C_?D_:"w":()=>"w",Bc=(t,e,n)=>{try{return po.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},ao=(t,e,n,i)=>{po.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},O_=(t,e,n,i,o)=>{if(e.isDirectory())Mf(Ri.resolve(t,e.name),n,i,c=>{if(c)return o(c);let l=Ri.resolve(t,e.name);ao(l,n,i,o)});else{let c=Ri.resolve(t,e.name);ao(c,n,i,o)}},Mf=(t,e,n,i)=>{po.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return ao(t,e,n,i);let l=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--l===0)return ao(t,e,n,i)}};for(let x of c)O_(t,x,e,n,h)})},L_=(t,e,n,i)=>{e.isDirectory()&&Bf(Ri.resolve(t,e.name),n,i),Bc(Ri.resolve(t,e.name),n,i)},Bf=(t,e,n)=>{let i;try{i=po.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Bc(t,e,n);throw c}for(let o of i)L_(t,o,e,n);return Bc(t,e,n)},Ff=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},mo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},M_=(t,e)=>{lt.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new Ff(t,n?.code||"ENOTDIR")),e(n)})},B_=(t,e,n)=>{t=ee(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,h=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),x=e.preserve,m=e.unlink,w=ee(e.cwd),v=(E,I)=>{E?n(E):I&&h?Mf(I,l,u,A=>v(A)):c?lt.chmod(t,o,n):n()};if(t===w)return M_(t,v);if(x)return N_.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let _=ee(co.relative(w,t)).split("/");Fc(w,_,o,m,w,void 0,v)},Fc=(t,e,n,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),h=ee(co.resolve(t+"/"+u));lt.mkdir(h,n,zf(h,e,n,i,o,c,l))},zf=(t,e,n,i,o,c,l)=>u=>{u?lt.lstat(t,(h,x)=>{if(h)h.path=h.path&&ee(h.path),l(h);else if(x.isDirectory())Fc(t,e,n,i,o,c,l);else if(i)lt.unlink(t,m=>{if(m)return l(m);lt.mkdir(t,n,zf(t,e,n,i,o,c,l))});else{if(x.isSymbolicLink())return l(new mo(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Fc(t,e,n,i,o,c,l))},F_=t=>{let e=!1,n;try{e=lt.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new Ff(t,n??"ENOTDIR")}},z_=(t,e)=>{t=ee(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),h=e.preserve,x=e.unlink,m=ee(e.cwd),w=E=>{E&&u&&Bf(E,c,l),o&&lt.chmodSync(t,i)};if(t===m)return F_(m),w();if(h)return w(lt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=ee(co.relative(m,t)).split("/"),_;for(let E=v.shift(),I=m;E&&(I+="/"+E);E=v.shift()){I=ee(co.resolve(I));try{lt.mkdirSync(I,i),_=_||I}catch{let A=lt.lstatSync(I);if(A.isDirectory())continue;if(x){lt.unlinkSync(I),lt.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new mo(I,I+"/"+v.join("/"))}}return w(_)},_c=Object.create(null),Qu=1e4,yr=new Set,U_=t=>{yr.has(t)?yr.delete(t):_c[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=_c[t],n=yr.size-Qu;if(n>Qu/10){for(let i of yr)if(yr.delete(i),delete _c[i],--n<=0)break}return e},G_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,H_=G_==="win32",q_=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Uf(i,n)),e.push(n||"/"),e},[]),j_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=H_?["win32 parallelization disabled"]:t.map(i=>Ti(Uf(U_(i))));let n=new Set(t.map(i=>q_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of n){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,o=new Set;for(let c of n){let l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")o.add(u);else for(let h of u)o.add(h)}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 h=l[0];typeof h=="function"&&o.add(h)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},K_=()=>process.umask(),ef=Symbol("onEntry"),zc=Symbol("checkFs"),tf=Symbol("checkFs2"),Uc=Symbol("isReusable"),pt=Symbol("makeFs"),Gc=Symbol("file"),Hc=Symbol("directory"),ro=Symbol("link"),nf=Symbol("symlink"),rf=Symbol("hardlink"),Ai=Symbol("ensureNoSymlink"),sf=Symbol("unsupported"),of=Symbol("checkPath"),yc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),Ke=Symbol("onError"),Ws=Symbol("pending"),af=Symbol("pend"),br=Symbol("unpend"),bc=Symbol("ended"),Ec=Symbol("maybeClose"),qc=Symbol("skip"),Pi=Symbol("doChown"),Ci=Symbol("uid"),Di=Symbol("gid"),Oi=Symbol("checkedCwd"),W_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Li=W_==="win32",$_=1024,V_=(t,e)=>{if(!Li)return se.unlink(t,e);let n=t+".DELETE."+Tf(16).toString("hex");se.rename(t,n,i=>{if(i)return e(i);se.unlink(n,e)})},J_=t=>{if(!Li)return se.unlinkSync(t);let e=t+".DELETE."+Tf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},cf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,Qc=class extends Ni{[bc]=!1;[Oi]=!1;[Ws]=0;reservations=new j_;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[bc]=!0,this[Ec]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:$_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Li,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ee(Be.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:K_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[ef](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Ec](){this[bc]&&this[Ws]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[yc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,c]=Jc(n),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Li&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=Be.posix.dirname(t.path),h=Be.posix.normalize(Be.posix.join(u,l.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:n})),!0}[of](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[yc](t,"path")||!this[yc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?ee(Be.resolve(t.path)):ee(Be.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:ee(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Be.win32.parse(String(t.absolute));t.absolute=i+Gu(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+Gu(t.path.slice(o.length))}return!0}[ef](t){if(!this[of](t))return t.resume();switch(T_.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[zc](t);default:return this[sf](t)}}[Ke](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[bn](t,e,n){B_(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)}[Pi](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ci](t){return cf(this.uid,t.uid,this.processUid)}[Di](t){return cf(this.gid,t.gid,this.processGid)}[Gc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new lo(String(t.absolute),{flags:Nf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[Ke](u,t),e()});let o=1,c=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[Ke](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,h=>{h?this[Ke](h,t):this[br](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,m=t.mtime;se.futimes(h,x,m,w=>w?se.utimes(u,x,m,v=>c(v&&w)):c())}if(typeof h=="number"&&this[Pi](t)){o++;let x=this[Ci](t),m=this[Di](t);typeof x=="number"&&typeof m=="number"&&se.fchown(h,x,m,w=>w?se.chown(u,x,m,v=>c(v&&w)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[Ke](u,t),e()}),t.pipe(l)),l.pipe(i)}[Hc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),n,i=>{if(i){this[Ke](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Pi](t)&&(o++,se.chown(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)),c)),c()})}[sf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[nf](t,e){let n=ee(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ai](t,this.cwd,n,()=>this[ro](t,String(t.linkpath),"symlink",e),i=>{this[Ke](i,t),e()})}[rf](t,e){let n=ee(Be.resolve(this.cwd,String(t.linkpath))),i=ee(String(t.linkpath)).split("/");this[Ai](t,this.cwd,i,()=>this[ro](t,n,"link",e),o=>{this[Ke](o,t),e()})}[Ai](t,e,n,i,o){let c=n.shift();if(this.preservePaths||c===void 0)return i();let l=Be.resolve(e,c);se.lstat(l,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new mo(l,Be.resolve(l,n.join("/"))));this[Ai](t,l,n,i,o)})}[af](){this[Ws]++}[br](){this[Ws]--,this[Ec]()}[qc](t){this[br](),t.resume()}[Uc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Li}[zc](t){this[af]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[tf](t,n))}[tf](t,e){let n=l=>{e(l)},i=()=>{this[bn](this.cwd,this.dmode,l=>{if(l){this[Ke](l,t),n();return}this[Oi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=ee(Be.dirname(String(t.absolute)));if(l!==this.cwd)return this[bn](l,this.dmode,u=>{if(u){this[Ke](u,t),n();return}c()})}c()},c=()=>{se.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[qc](t),n();return}if(l||this[Uc](t,u))return this[pt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[pt](m??null,t,n);return h?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),h=>this[pt](h??null,t,n))}if(t.absolute===this.cwd)return this[pt](null,t,n);V_(String(t.absolute),h=>this[pt](h??null,t,n))})};this[Oi]?o():i()}[pt](t,e,n){if(t){this[Ke](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Gc](e,n);case"Link":return this[rf](e,n);case"SymbolicLink":return this[nf](e,n);case"Directory":case"GNUDumpDir":return this[Hc](e,n)}}[ro](t,e,n,i){se[n](e,String(t.absolute),o=>{o?this[Ke](o,t):(this[br](),t.resume()),i()})}},Si=t=>{try{return[null,t()]}catch(e){return[e,null]}},Gf=class extends Qc{sync=!0;[pt](t,e){return super[pt](t,e,()=>{})}[zc](t){if(!this[Oi]){let o=this[bn](this.cwd,this.dmode);if(o)return this[Ke](o,t);this[Oi]=!0}if(t.absolute!==this.cwd){let o=ee(Be.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[Ke](c,t)}}let[e,n]=Si(()=>se.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[qc](t);if(e||this[Uc](t,n))return this[pt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[l]=c?Si(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[pt](l,t)}let[o]=Si(()=>se.rmdirSync(String(t.absolute)));this[pt](o,t)}let[i]=t.absolute===this.cwd?[]:Si(()=>J_(String(t.absolute)));this[pt](i,t)}[Gc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{se.closeSync(o)}catch(h){u=h}(l||u)&&this[Ke](l||u,t),e()},o;try{o=se.openSync(String(t.absolute),Nf(t.size),n)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[Ke](l,t)),t.pipe(c)),c.on("data",l=>{try{se.writeSync(o,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{se.futimesSync(o,u,h)}catch(x){try{se.utimesSync(String(t.absolute),u,h)}catch{l=x}}}if(this[Pi](t)){let u=this[Ci](t),h=this[Di](t);try{se.fchownSync(o,Number(u),Number(h))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(h))}catch{l=l||x}}}i(l)})}[Hc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),n);if(i){this[Ke](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Pi](t))try{se.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Di](t)))}catch{}e(),t.resume()}[bn](t,e){try{return z_(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}}[Ai](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let c=e;for(let l of n){c=Be.resolve(c,l);let[u,h]=Si(()=>se.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new mo(c,Be.resolve(e,n.join("/"))))}i()}[ro](t,e,n,i){let o=`${n}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ke](c,t)}}},Z_=t=>{let e=new Gf(t),n=t.file,i=kf.statSync(n),o=t.maxReadSize||16*1024*1024;new pw(n,{readSize:o,size:i.size}).pipe(e)},Y_=(t,e)=>{let n=new Qc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{n.on("error",l),n.on("close",c),kf.stat(o,(u,h)=>{if(u)l(u);else{let x=new Kc(o,{readSize:i,size:h.size});x.on("error",l),x.pipe(n)}})})},Hf=Mi(Z_,Y_,t=>new Gf(t),t=>new Qc(t),(t,e)=>{e?.length&&yf(t,e)}),X_=(t,e)=>{let n=new Xc(t),i=!0,o,c;try{try{o=dt.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=dt.openSync(t.file,"w+");else throw h}let l=dt.fstatSync(o),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=dt.readSync(o,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 h=new Kn(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>l.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,Q_(t,n,c,o,e)}finally{if(i)try{dt.closeSync(o)}catch{}}},Q_=(t,e,n,i,o)=>{let c=new uf(t.file,{fd:i,start:n});e.pipe(c),ty(e,o)},ey=(t,e)=>{e=Array.from(e);let n=new xo(t),i=(o,c,l)=>{let u=(v,_)=>{v?dt.close(o,E=>l(v)):l(null,_)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),w=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return dt.read(o,m,x,m.length-x,h+x,w);if(h===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let E=new Kn(m);if(!E.cksumValid)return u(null,h);let I=512*Math.ceil((E.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,dt.read(o,m,0,512,h,w)};dt.read(o,m,0,512,h,w)};return new Promise((o,c)=>{n.on("error",c);let l="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&l==="r+")return l="w+",dt.open(t.file,l,u);if(h||!x)return c(h);dt.fstat(x,(m,w)=>{if(m)return dt.close(x,()=>c(m));i(x,w.size,(v,_)=>{if(v)return c(v);let E=new lo(t.file,{fd:x,start:_});n.pipe(E),E.on("error",c),E.on("close",o),ny(n,e)})})};dt.open(t.file,l,u)})},ty=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Rr({file:qf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},ny=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Rr({file:qf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Ii=Mi(X_,ey,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!vw(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")}),PA=Mi(Ii.syncFile,Ii.asyncFile,Ii.syncNoFile,Ii.asyncNoFile,(t,e=[])=>{Ii.validate?.(t,e),ry(t)}),ry=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))};Kt();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 go(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function jf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function wo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Kf(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function Wf(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function $n(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Xt();Ve();ne();Pe();Ve();function Pr(t,e){if(go(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Bi(t){return t.startsWith("http://")||t.startsWith("https://")}function Cr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as bk}from"node:fs";import{dirname as vk,join as Sk}from"node:path";import{fileURLToPath as Ak}from"node:url";var Mt="0.2.7-beta.2";import{mkdir as yy,rm as u0}from"node:fs/promises";import{join as Hi}from"node:path";jt();import{readFileSync as uy}from"node:fs";var fy=384;async function ed(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await fr(t.agentEnvFile,n,{mode:fy})}function Fi(t){try{let e=JSON.parse(uy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Zf(t,e,n={},i=o=>o){return{...i({...t,...Fi(e)}),...n}}jt();function zi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(hy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
92
- `)}
93
- `}function hy(t){if(t.includes(`
94
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ne();Pe();import{homedir as my}from"node:os";import{join as gy}from"node:path";Ve();ne();var _o="1008033",Yf="1289";var Xf="pbbp2",Qf="https://www.coze.cn",e0="/api/coze_claw/resource/get_frontier_key",xy="https://www.coze.cn",py="wss://frontier.coze.cn";function Dr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??xy}function t0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??py}function Sn(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 Gi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Ui=K("handshake");async function td(t){let e=Dr(t.endpoint),n=t.timeoutMs??1e4,i=`${Cr(e)}${e0}?aid=${encodeURIComponent(_o)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),n);Ui.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.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 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=${h}`);let w=m.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(m).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${E}`)}return Ui.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:v,deviceId:_}}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:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw Ui.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(l)}}var yo=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",kt="auto",nd=19e4,n0=8192;function i0(t){return{model:rd(t.model)??kt,...t.modelToken?{modelToken:t.modelToken}:{}}}function s0(t){return!t||t===kt}var wy=new Set(["auto","\u81EA\u52A8"]);function rd(t){let e=t?.trim();if(e)return wy.has(e.toLowerCase())?kt:e}function o0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=yo,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||kt;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else s0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function a0(t,e,n){let i={};if(t.modelToken?i.model=t.model||kt:s0(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${yo}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=bo(e,n);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??nd}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function c0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function bo(t,e){let{ttEnv:n,usePpe:i}=Gi(t),o={};return n&&(o["x-tt-env"]=n),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function d0(t,e,n){if(!t.modelToken)return{};let i=bo(e,n);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
95
- `)}}function id(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function sd(t){return t.model||kt}function r0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function l0(t,e,n,i){if(!t.modelToken)return null;let o=sd(t),c=bo(e,n),l=["text"];t.modelInfo?.capabilities?.image===!0&&l.push("image");let u=[r0(o,l,t.modelInfo?.contextWindow??nd,t.modelInfo?.maxOutput??n0)],h=new Set([o]);for(let m of i??[])!m||h.has(m)||(h.add(m),u.push(r0(m,["text"],nd,n0)));let x={baseUrl:`${yo}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}function _y(t){if(t!==void 0)return t?"auto":"text"}function od(t,e,n){let i=bo(e,n),o=t.model||kt,c=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${yo}/v1`];if(t.modelInfo?.contextWindow&&c.push(` context_length: ${t.modelInfo.contextWindow}`),t.modelInfo?.maxOutput&&c.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&c.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){c.push(" default_headers:");for(let[u,h]of Object.entries(i))c.push(` ${u}: ${JSON.stringify(h)}`)}c.push("compression:"),c.push(" threshold: 0.8"),c.push("approvals:"),c.push(` mode: ${JSON.stringify("off")}`),c.push(` cron_mode: ${JSON.stringify("approve")}`);let l=_y(t.modelInfo?.capabilities?.image);return l&&(c.push("agent:"),c.push(` image_input_mode: ${JSON.stringify(l)}`)),c.push("skills:"),c.push(" external_dirs:"),c.push(` - ${gy(my(),".hermes","skills")}`),`${c.join(`
96
- `)}
97
- `}var Vn=K("hermes-config"),f0="dont_ask",h0="default";function Jn(t,e){return Hi(Ue(t,e).root,"hermes-home")}async function by(t){let e=Jn(t.agentId,t.paths);await yy(e,{recursive:!0,mode:448});let n=zi({...process.env,...Fi(t.paths.agentEnvFile)});await ht(Hi(e,".env"),n,{mode:384});let i=od(t.modelConfig,t.cozeEnv,t.mockScenario);await ht(Hi(e,"config.yaml"),i,{mode:384}),Vn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function x0(t){let e=Jn(t.agentId,t.paths),n=Hi(e,"state.db"),i=Hi(e,"config.yaml");Vn.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 u0(n,{force:!0}).catch(c=>Vn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=od({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ht(i,o,{mode:384}).catch(c=>Vn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(c)})),Vn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function cd(t,e){let n=Jn(t,e);Vn.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 u0(n,{recursive:!0,force:!0}).catch(i=>Vn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var ad=new Map;function p0(t){let e=ad.get(t.agentId);if(e)return e;let n=by(t).finally(()=>ad.delete(t.agentId));return ad.set(t.agentId,n),n}var re=K("agent-handlers"),g0=5*1024*1024,Ay=1,ky=6,Ty=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ry=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Py=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Cy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Dy(t){let e=t?.trim();return e?Cy.test(e)||Py.test(e)?e:(re.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Oy(t){return new Promise((e,n)=>{let i=at("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=l=>{o||(o=!0,l?n(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}function Ly(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var vo=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Y()}async listSkills(e){e._meta;let n=$n(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Ue(n,this.paths).workspace,c=i?.framework??"claude-code",l=i?.skills??[],{base:u}=Lr(c,n,o,this.paths),h=[],x=new Set;for(let w of l){let v=he(u,w.relPath,"SKILL.md");await pd(v).then(E=>E.isFile()).catch(()=>!1)&&(h.push(zy(w)),x.add(w.relPath))}if(e.scanLocal){let w=await T0(n,o,c,this.paths),v=await R0(n,c);for(let _ of[...w,...v])x.has(_.relPath)||(x.add(_.relPath),h.push(_.skill))}return{skills:c==="hermes"?h.filter(w=>w.skillName!=="yuanbao"):h}}async addSkills(e){e._meta;let n=$n(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((h,x)=>[h.skillId,x])),u=[];for(let h of o){let x=await So({agentId:n,workspace:i.workspace,framework:i.framework,skill:h,paths:this.paths});Io(c,l,x),u.push(h)}return await li(n,c),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=$n(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),c=i.skills??[],l=[],{base:u}=Lr(i.framework,n,i.workspace,this.paths);for(let h of c){if(!o.has(h.skillId)){l.push(h);continue}let x=he(u,h.relPath);re.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 ud(x,{recursive:!0,force:!0}),re.info("skill removed",{agentId:n,skillId:h.skillId,relPath:h.relPath})}return await li(n,l),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=$n(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");re.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),o=i?.workspace??Ue(n,this.paths).workspace,c=i?.framework??"claude-code",l=e.isGlobal??!1,u=await My(n,o,c,e.skillName,l,this.paths);if(!u){let O=l?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${O}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:m}=u,w=he(h,"SKILL.md"),v=new gd.default;v.addLocalFolder(h,m);let _=v.toBuffer();if(_.length>w0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${w0}`);let E=await Eo(w,{encoding:"utf8"}).then(O=>A0(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}:{}}):re.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??I0(n,x);if(i&&!l){let O=i.skills??[],b=O.find(D=>D.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 li(n,O)}return re.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,re.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let h=c.downstream;c.downstream=void 0,re.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:l}),h.stop(n).catch(x=>re.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return re.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Se(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return re.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw re.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Ge(i),re.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 Se(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Bi(e.registry)&&o.push(`--registry=${e.registry}`);let c=Dy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&Ry.test(l)&&o.push("--env",l);let u=await Oy(o);return re.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Se(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ge(i),re.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}):(re.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`);re.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 Se(n),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let l=Ue(n);return c==="cloud"?(re.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:n,path:l.root,deployType:c,reason:e.reason??""}),await ud(l.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ge(i)),re.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Pr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=rd(e.model)??kt,i=await Se(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 Ge(i),re.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return re.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model,l=o.modelInfo;o.model=n,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(x=>re.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=o.framework==="hermes"&&Ly(l,o.modelInfo);if(o.framework==="hermes"&&!u){let x=[];for(let[m,w]of o.allSessionQueues())x.push(w.enqueue(async()=>{let v=o.sessions.get(m);if(!(!v?.downstream||!v.acpSessionId))try{await v.downstream.setSessionModel?.({sessionId:v.acpSessionId,modelId:n})}catch(_){re.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:m,acpId:v.acpSessionId,err:String(_)})}}));return await Promise.all(x),re.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,m]of o.allSessionQueues())h.push(m.enqueue(async()=>{let w=o.sessions.get(x);w?.downstream&&(await w.downstream.stop(`switchModel: ${n}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(h),re.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(Pr(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=>re.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),re.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,l]of i.sessions)o.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt,permissionMode:l.permissionMode,cozeGroupId:l.cozeGroupId});await di(e,o)}async clearPersistedAcpSessionIds(e){let n=await Se(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let o of Object.values(n.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Ge(n)}async repairAgent(e){if(Pr(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){re.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){re.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){re.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Pr(e._meta,"_agent/getFileTree");let n=e._meta,i=$n(n),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await dd(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 ci(l,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=Yy(e.depth);return u.isDirectory()?{tree:await Zy(o,l,c,h)}:{tree:[{name:Xy(c),path:D0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Pr(e._meta,"_agent/getFileContent");let n=$n(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await dd(o).catch(()=>null);if(!c||!c.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await ci(o,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 Eo(o);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await Se(e).catch(()=>null))?.workspace??Ue(e).workspace}safeJoin(e,n){let i=hd(e,n||"."),o=md(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${y0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Se(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 v0(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 Lr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:he(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:he(".agents","skills")};case"hermes":return{base:Jn(e,i??Y()),subdir:"skills"}}}function S0(t){let e=vy();if(t==="claude-code")return[he(e,".claude","skills")];if(t==="codex")return[he(e,".agents","skills"),he(e,".codex","skills")];if(t==="openclaw")return[he(e,".agents","skills"),he(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||he(e,"AppData","Local");return[he(n,"hermes","skills"),he(e,".hermes","skills")]}return[he(e,".hermes","skills")]}return[]}async function Ny(t,e,n,i,o,c){let l=async u=>pd(he(u,"SKILL.md")).then(h=>h.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:h}=Lr(n,t,e,c),x=he(h,i),m=he(u,x);return await l(m)?{absDir:m,relPath:x}:null}for(let u of S0(n)){let h=he(u,i);if(await l(h))return{absDir:h,relPath:h}}return null}async function My(t,e,n,i,o,c){let l=v0(i),u=await Ny(t,e,n,l,o,c);if(u)return{...u,dirName:l};let x=(o?await R0(t,n):await T0(t,e,n,c)).filter(v=>v.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${x.map(v=>m0(v.relPath)).join(", ")} \u2014 rename or remove duplicates`);let m=x[0];return m?{absDir:o?m.relPath:he(e,m.relPath),relPath:m.relPath,dirName:m0(m.relPath)}:null}function I0(t,e){return(Ey("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function A0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
- ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.split(`
102
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let l=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function k0(t,e,n,i){let o=await _0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let l of o){let u=l.isDirectory();if(!u&&l.isSymbolicLink()&&(u=!!(await pd(he(e,l.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=l.name,x=he(n,h),m=he(e,h,"SKILL.md"),w=await Eo(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let v=A0(w);c.push({relPath:x,skill:{skillId:I0(t,x),skillName:v.name||h,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function T0(t,e,n,i){let{base:o,subdir:c}=Lr(n,t,e,i);return k0(t,he(o,c),c,!1)}async function R0(t,e){let n=[],i=new Set;for(let o of S0(e)){let c=await k0(t,o,o,!0);for(let l of c)i.has(l.relPath)||(i.add(l.relPath),n.push(l))}return n}var By=3e4,Fy=50*1024*1024,w0=10*1024*1024,Or=3e4;async function So(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:c}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let l=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!l&&!u)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let h=v0(o.skillName),{base:x,subdir:m}=Lr(i,e,n,c),w=he(m,h),v=he(x,w);if(await ld(v,{recursive:!0}),l){let E=Buffer.from(o.content,"utf8");qi(E.length),await fd(he(v,"SKILL.md"),E,"utf8")}else{let E=await Gy(o.downloadUrl);qy(E)?await $y(E,v):jy(E)?await Ky(E,v):await fd(he(v,"SKILL.md"),E.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:w,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return re.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:w,source:l?"content":"downloadUrl"}),_}function Io(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 zy(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 Uy(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 P0(t,e){let n=await Se(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Mt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Ge(n,e),{status:"seeded",count:0};let c=[...n.skills??[]],l=new Map(c.map((w,v)=>[w.skillId,v])),u=c.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Ge(n,e),{status:"noop",count:0};let h=0,x=0,{base:m}=Lr(n.framework,t,n.workspace,e);re.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:m,builtinCount:u.length,builtinRelPaths:u.map(w=>w.relPath)});for(let w of u)try{let v=he(m,w.relPath);re.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:v}),await ud(v,{recursive:!0,force:!0});let _=await So({agentId:t,workspace:n.workspace,framework:n.framework,skill:Uy(w),...e?{paths:e}:{}});Io(c,l,_),h+=1}catch(v){x+=1,re.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(v)})}return n.skills=c,x===0&&(n.skillsRefreshedForVersion=i),await Ge(n,e),re.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function Gy(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);qi(e);let n=Hy(t);return qi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Eo(e);return qi(n.length),n}if(Bi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),By);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return qi(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function qi(t){if(t>Fy)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Hy(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 qy(t){return t.length>=2&&t[0]===31&&t[1]===139}function jy(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 xd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Ky(t,e){let n,i;try{n=new gd.default(t),i=n.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||xd(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=l.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 o=Wy(i),c=hd(e);for(let l of i){if(xd(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=hd(e,u),x=md(c,h);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await ld(h,{recursive:!0});continue}await ld(Sy(h),{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 fd(h,m)}}function Wy(t){let e;for(let n of t){let i=n.entryName;if(!i||xd(i))continue;let o=i.indexOf("/");if(o<=0)return;let c=i.slice(0,o+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function $y(t,e){await Vy(t);let n=Hf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await E0(b0.from(t),n)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Vy(t){let e=[],n=Rr({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await E0(b0.from(t),n)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Jy=5e3;async function Zy(t,e,n,i){return C0(t,e,n,i,{count:0})}async function C0(t,e,n,i,o){if(i<=0)return[];let c;try{c=await _0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(Ty.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Jy){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=he(e,u.name),x=Iy(he(n,u.name)),m=null;try{m=await dd(h)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let w={name:u.name,path:D0(md(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await C0(t,h,x,i-1,o)),l.push(w)}return l.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),l}function Yy(t){return!t||t<=0?Ay:Math.min(t,ky)}function Xy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function D0(t){return t.split(y0).join("/")}ne();var In=K("agent-health-reporter"),Qy=1e4,eb=3,ji=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Qy,this.livenessFailureThreshold=e.livenessFailureThreshold??eb}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()}),In.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),In.info("heartbeat stopped"))}async tick(){if(this.inFlight){In.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,In.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let l of this.opts.core.agents.values()){let u=tb(l);if(!u)continue;let h={agentId:l.agentId,status:u};l.patToken&&(h.patToken=l.patToken),l.accountId&&(h.accountId=l.accountId),n.push(h)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Mt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(l){this.consecutiveFailures+=1,In.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(In.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){In.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){In.warn("onTickEnd hook failed",{err:String(n)})}}};function tb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Kt();import{mkdir as bd,rm as Qb,stat as eE}from"node:fs/promises";import{homedir as tE}from"node:os";import{join as lh}from"node:path";ln();import{existsSync as fb}from"node:fs";import{release as hb}from"node:os";import{basename as xb,isAbsolute as pb}from"node:path";function Ki(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Nr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Mr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function An(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var Ao=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 O0(t){return"method"in t&&"id"in t&&t.id!==void 0}function L0(t){return"method"in t&&!("id"in t)}function ko(t){return!("method"in t)&&"id"in t}var nb={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 rb(t){if(t!=null)return t instanceof Error?{name:t.name,message:Wi(t.message)}:typeof t=="string"?Wi(t):typeof t=="object"?sb(t):t}var ib=[[/\/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[n,i]of ib)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]=Wi(i):e[n]=i;return e}function $i(t){if(t instanceof k){let e=rb(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:nb[t.code]??X.INTERNAL_ERROR,message:Wi(t.message),data:n}}return{code:X.INTERNAL_ERROR,message:Wi(t instanceof Error?t.message:String(t))}}function N0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:l,...u}=e;c=u}return new k(n,o,{retriable:e?.retriable??!1,cause:c})}function B0(t){return`${JSON.stringify(t)}
103
- `}var M0=10*1024*1024,To=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>M0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${M0} bytes`)}),[]}let n=this.buffer.split(`
104
- `);this.buffer=n.pop()??"";let i=[];for(let o of n){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var z0={"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"},kT=Object.fromEntries(Object.entries(z0).map(([t,e])=>[e,t])),ob={"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:[]},Br=class{seq=0;next(e,n){this.seq+=1;let i=z0[e]??ab(e),o=ob[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(h=>F0(n?.[h]??"")),u=cb(l).join(":");u&&c.push(u)}else n&&Object.values(n).some(l=>l)&&c.push(Object.values(n).filter(Boolean).map(l=>F0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function ab(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function F0(t){return t.replace(/[:_\s]+/g,"-")}function cb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Xt();ar();Ve();ne();Pe();import{execFileSync as db,spawnSync as lb}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 n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),lb("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var wd=new Set;function U0(t){typeof t=="number"&&t>0&&wd.add(t)}function G0(t){typeof t=="number"&&wd.delete(t)}function H0(){for(let t of wd)Ji(t,"SIGKILL")}var Fr="coze-bridge-daemon";function q0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return db("pgrep",["-U",String(o),"-f",Fr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
105
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function j0(t,e){if(t.length===0)return;let n=e?.killFn??Ji,i=e?.isAliveFn??Vi,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<c&&t.some(h=>i(h));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var ub=[{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 K0(t,e){if(!e)return null;for(let n of ub)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function W0(t,e){return K0(t,e)}function $0(t,e){return K0(t,e)}function zr(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 V0(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,m=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:zr(m,t.firstFrameSeen,e)}}let c=n-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:zr(c,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:zr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:zr(c,!1,e)}}var J0=Xe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),mb=200,gb=40,wb=Xe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),_b=Xe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),yb=Xe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),bb=Xe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Eb=Xe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),vb=Xe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Z0=500;function Sb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Z0?t:`${e.slice(0,Z0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ib(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 Y0(t){try{return fb(t)}catch{return}}function Ab(t,e){return{platform:process.platform,osRelease:hb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:pb(e.command)?Y0(e.command):void 0,cwd:e.cwd,cwdExists:Y0(e.cwd),envKeys:e.envKeys}}function kb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${xb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var gt=class{constructor(e){this.opts=e;this.log=K(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new To({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Br;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=Zf(process.env,this.opts.agentEnvFile??Y().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=at(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,U0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>mb&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,G0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,l=Ab(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(o),diag:l}),this.failAllPending(new k("AGENT_SPAWN_FAILED",kb(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 n=this.child,i=new Promise(c=>n.once("exit",()=>c()));Ji(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||Ji(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Eb,phase2GateMs:wb,livenessWindowMs:_b,absoluteMaxMs:yb,approvalMaxMs:vb,suspendThresholdMs:bb,...n};return this.call("session/prompt",e,J0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Nr("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(Mr(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(An(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=J0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=Ki(c,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let h=n.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let m={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),v={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:zr(0,!1,o),sessionId:u};m.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=V0(E,v.cfg,I),T=O=>{v.armedAt=I,v.expectedIntervalMs=O,m.timer=setTimeout(_,O)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,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(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,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:c,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(_,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new 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),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(B0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(ko(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new k("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:Sb(e.result)}),n.resolve(e.result));return}if(L0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(O0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(An(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(An(e.id,$i(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=N0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=$0(this.framework,Ib(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(gb).join(`
106
- `),o=W0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Tb(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 Ro=class extends gt{framework="claude-code";constructor(e){let{command:n,args:i}=ai("claude-code",e.command,e.args??[]),o={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return Tb(e)}};ln();import{mkdtempSync as Rb,rmSync as Pb}from"node:fs";import{tmpdir as Cb}from"node:os";import{join as Db}from"node:path";var X0=["default","acceptEdits","plan","auto","bypassPermissions"],Q0=["read-only","auto","full-access"];var eh=["default","accept_edits","dont_ask"];function Bt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return X0.includes(e);case"codex":return Q0.includes(e);case"hermes":return eh.includes(e);case"openclaw":return!1}}function Po(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function th(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function _d(t){switch(t){case"claude-code":return X0.join("/");case"codex":return Q0.join("/");case"hermes":return eh.join("/");case"openclaw":return""}}var Co=class extends gt{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:c}=ai("codex",e.command,i),l=e.isolateCodexHome?Rb(Db(Cb(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}:e.env,h={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=l}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}setSessionMode(e){let n=Bt("codex",e.modeId)?Po(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(Ob(n)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Pb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Ob(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=th(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var Lb=K("hermes-downstream"),Do=class extends gt{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){Lb.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}};Ve();var Nb=3e4,Ur=class extends gt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Nb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};jt();Ve();ne();Pe();function yd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}ln();var kn=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 Oo=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 kn,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)Zi(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 Zi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Qt(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Xt();ne();import{constants as nh}from"node:fs";import{access as Mb,readFile as Bb}from"node:fs/promises";import{delimiter as Fb,dirname as zb,join as rh}from"node:path";var rt=K("framework-detector"),ih={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Ub=[".exe",".cmd",".bat",".ps1"],Zn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??at,access:e.access??Mb,readFile:e.readFile??Bb}}async detect(e){let n=ih[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return rt.debug("framework binary not found",{framework:e,bin:n}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,l]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(ih).map(async i=>[i,await this.detect(i)])),n={};for(let[i,o]of e)o&&(n[i]=o);return n}async which(e){let n=this.env.pathEnv.split(Fb).filter(Boolean),i=this.env.platform==="win32"?["",...Ub]:[""];for(let o of n)for(let c of i){let l=rh(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?nh.F_OK:nh.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(l){return rt.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(l)}),null}let o=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return rt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let c=rh(zb(o),"hermes-acp");return await this.isExecutable(c)?(rt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:c}),c):(rt.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:c}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return rt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return rt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return rt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return rt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(rt.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}:(rt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return rt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return rt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||rt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},c=n.stdout.match(/\{[\s\S]*\}/);if(c)try{let l=JSON.parse(c[0]);typeof l.gateway?.port=="number"&&(o.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(o.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(o.detail=l.rpc.error)}catch(l){rt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(Hb(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",c=!1,l,u=h=>{c||(c=!0,l&&clearTimeout(l),i(h))};try{let h=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});l=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{o+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},Gb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Hb(t){return t.replace(Gb,"")}import{homedir as qb}from"node:os";import{join as jb}from"node:path";jt();Xt();ar();Ve();ne();async function ah(){let t=jb(qb(),".openclaw/openclaw.json");return ur(t)}async function ch(){return(await ah())?.gateway?.auth?.token??""}var sh=K("openclaw.config"),Kb=[0,5e3,5e3],Wb=Xe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),oh="models.providers.",Lo="agents.defaults.models",No=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Kb,this.cliTimeoutMs=e.cliTimeoutMs??Wb}async withRetry(e,n){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(l=>setTimeout(l,c));try{return await n()}catch(l){i=l,sh.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=at(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=x=>{l||(l=!0,clearTimeout(h),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let o=String(i);if(n.some(c=>o.includes(c)))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){sh.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",`${oh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${oh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Lo}[${e}]`,()=>this.runCli(["config","set",Lo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Lo}[${e}]`,`${Lo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await ah())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,c=[];for(let l of Object.keys(i))l.startsWith(o)&&c.push(l.slice(o.length));return c}ensureAgent(e,n,i){let o=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};import{readFile as $b,writeFile as Vb}from"node:fs/promises";import{join as Jb}from"node:path";var Zb=["```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(`
107
- `),Yb=["# 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(`
108
- `);function Xb(t){return t.length===0?t:`${(t.endsWith(`
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 Gp("schtasks",["/Create","/SC","ONLOGON","/TN",ba,"/TR",r,"/RU",t.userName,"/F"]),hl.info("task scheduler entry created",{task:ba,logFile:t.logFile})},async uninstall(t){await Gp("schtasks",["/Delete","/TN",ba,"/F"]).catch(e=>hl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),hl.info("task scheduler entry removed",{task:ba})}}});var jp={};Na(jp,{buildContext:()=>eA,getSupervisor:()=>XI,launchdSupervisor:()=>ul,systemdSupervisor:()=>fl,taskSchedulerSupervisor:()=>xl});import{homedir as JI,userInfo as ZI}from"node:os";function XI(t=process.platform){switch(t){case"darwin":return ul;case"linux":return fl;case"win32":return xl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function QI(){let t={};for(let e of YI){let r=process.env[e];r&&(t[e]=r)}return t}function eA(){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 YI,Wp=nt(()=>{"use strict";Te();ua();zp();Hp();qp();YI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});re();dn();var Wl=G("acp-installer-warmup"),wm=["claude-code","codex"];async function Kl(t={}){let e=t.ensure??hr,i=(await Promise.allSettled(wm.map(async o=>{let c=await e(o);Wl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.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(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}xn();re();import{readdir as Lm}from"node:fs/promises";import{mkdir as Zl,readFile as Pm,writeFile as Xl}from"node:fs/promises";import{join as Ga}from"node:path";var Om={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function xr(t,e,r){await Zl(t,{recursive:!0});let i=Om[e],o=Ga(t,i);return await Xl(o,r??"","utf8"),o}async function qa(t,e,r){let i=Ga(t,".claude");await Zl(i,{recursive:!0});let o=Ga(i,"settings.local.json"),c={};try{let u=await Pm(o,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(c=h)}catch{}let d=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=r)}return c.permissions=d,await Xl(o,JSON.stringify(c,null,2),"utf8"),o}var Qe=G("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(o){Qe.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Ce(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.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(o){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await Ce(e,this.opts.paths);if(!i){Qe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),m=x?Math.min(x.currentDelay*2,Mm):Nm;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(o.agentId&&o.agentId!==e){Qe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Qe.debug("detail sync: no diff",{agentId:e});return}await ze(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await xr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var xd=qt(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 xe,normalize as by,relative as hd,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 it from"fs";import{EventEmitter as qc}from"node:events";import hf from"node:stream";import{StringDecoder as sw}from"node:string_decoder";import gf from"node:path";import Ar 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 _r}from"node:path";import{basename as n_}from"node:path";import ro from"fs";import Dt from"fs";import qu from"path";import{win32 as p_}from"node:path";import Zu from"path";import Df from"node:fs";import P_ from"node:assert";import{randomBytes as Pf}from"node:crypto";import se from"node:fs";import Ne from"node:path";import Of from"fs";import ho from"node:fs";import Di from"node:path";import ct from"node:fs";import z_ from"node:fs/promises";import oo from"node:path";import{join as jf}from"node:path";import at 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})},Du=typeof process=="object"&&process?process:{stdout:null,stderr:null},ow=t=>!!t&&typeof t=="object"&&(t instanceof Jn||t instanceof hf||aw(t)||cw(t)),aw=t=>!!t&&typeof t=="object"&&t instanceof qc&&typeof t.pipe=="function"&&t.pipe!==hf.Writable.prototype.pipe,cw=t=>!!t&&typeof t=="object"&&t instanceof qc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),gn=Symbol("emittedEnd"),Rs=Symbol("emittingEnd"),hi=Symbol("emittedError"),Ds=Symbol("closed"),Pu=Symbol("read"),Ps=Symbol("flush"),Ou=Symbol("flushChunk"),_t=Symbol("encoding"),wr=Symbol("decoder"),Ue=Symbol("flowing"),xi=Symbol("paused"),vr=Symbol("resume"),He=Symbol("buffer"),et=Symbol("pipes"),Ge=Symbol("bufferLength"),Ja=Symbol("bufferPush"),Os=Symbol("bufferShift"),Ye=Symbol("objectMode"),Ie=Symbol("destroyed"),Za=Symbol("error"),Xa=Symbol("emitData"),Lu=Symbol("emitEnd"),Ya=Symbol("emitEnd2"),kt=Symbol("async"),Qa=Symbol("abort"),Ls=Symbol("aborted"),pi=Symbol("signal"),Bn=Symbol("dataListeners"),ot=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),xf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[vr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},hw=class extends xf{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)}},xw=t=>!!t.objectMode,pw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Jn=class extends qc{[Ue]=!1;[xi]=!1;[et]=[];[He]=[];[Ye];[_t];[kt];[wr];[jt]=!1;[gn]=!1;[Rs]=!1;[Ds]=!1;[hi]=null;[Ge]=0;[Ie]=!1;[pi];[Ls]=!1;[Bn]=0;[ot]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");xw(e)?(this[Ye]=!0,this[_t]=null):pw(e)?(this[_t]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[_t]=null),this[kt]=!!e.async,this[wr]=this[_t]?new sw(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal: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[Ye]}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[Ie])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[Ye]&&!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[Ye]?(this[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[Ja](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[wr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[wr].write(t)),this[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[Ja](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue])}read(t){if(this[Ie])return null;if(this[ot]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[Wt](),null;this[Ye]&&(t=null),this[He].length>1&&!this[Ye]&&(this[He]=[this[_t]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[Pu](t||null,this[He][0]);return this[Wt](),e}[Pu](t,e){if(this[Ye])this[Os]();else{let r=e;t===r.length||t===null?this[Os]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].length&&!this[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[Ue]||!this[xi])&&this[Wt](),this}[vr](){this[Ie]||(!this[Bn]&&!this[et].length&&(this[ot]=!0),this[xi]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[Ps]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[vr]()}pause(){this[Ue]=!1,this[xi]=!0,this[ot]=!1}get destroyed(){return this[Ie]}get flowing(){return this[Ue]}get paused(){return this[xi]}[Ja](t){this[Ye]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[Os](){return this[Ye]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[Ps](t=!1){do;while(this[Ou](this[Os]())&&this[He].length);!t&&!this[He].length&&!this[jt]&&this.emit("drain")}[Ou](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[Ie])return t;this[ot]=!1;let r=this[gn];return e=e||{},t===Du.stdout||t===Du.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[et].push(e.proxyErrors?new hw(this,t,e):new xf(this,t,e)),this[kt]?gi(()=>this[vr]()):this[vr]()),t}unpipe(t){let e=this[et].find(r=>r.dest===t);e&&(this[et].length===1?(this[Ue]&&this[Bn]===0&&(this[Ue]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[ot]=!1,this[Bn]++,!this[et].length&&!this[Ue]&&this[vr]();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[hi]){let i=e;this[kt]?gi(()=>i.call(this,this[hi])):i.call(this,this[hi])}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[ot]&&!this[et].length&&(this[Ue]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Bn]=0,!this[ot]&&!this[et].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[gn]}[Wt](){!this[Rs]&&!this[gn]&&!this[Ie]&&this[He].length===0&&this[jt]&&(this[Rs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ds]&&this.emit("close"),this[Rs]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ie&&this[Ie])return!1;if(t==="data")return!this[Ye]&&!r?!1:this[kt]?(gi(()=>this[Xa](r)),!0):this[Xa](r);if(t==="end")return this[Lu]();if(t==="close"){if(this[Ds]=!0,!this[gn]&&!this[Ie])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[hi]=r,super.emit(Za,r);let o=!this[pi]||this.listeners("error").length?super.emit("error",r):!1;return this[Wt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Wt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[Wt](),i}[Xa](t){for(let r of this[et])r.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Wt](),e}[Lu](){return this[gn]?!1:(this[gn]=!0,this.readable=!1,this[kt]?(gi(()=>this[Ya]()),!0):this[Ya]())}[Ya](){if(this[wr]){let e=this[wr].end();if(e){for(let r of this[et])r.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Ye]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ie,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ot]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[jt])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(Ie,h),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(Ie,h),this.pause(),i({value:x,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Ie,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,m)=>{o=m,i=x,this.once(Ie,h),this.once("error",c),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ot]=!1;let t=!1,e=()=>(this.pause(),this.off(Za,e),this.off(Ie,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(Ie,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ie])return t?this.emit("error",t):this.emit(Ie),this;this[Ie]=!0,this[ot]=!0,this[He].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Ds]&&e.close(),t?this.emit("error",t):this.emit(Ie),this}static get isStream(){return ow}},gw=it.writev,In=Symbol("_autoClose"),vt=Symbol("_close"),mi=Symbol("_ended"),de=Symbol("_fd"),ec=Symbol("_finished"),Jt=Symbol("_flags"),tc=Symbol("_flush"),Ec=Symbol("_handleChunk"),vc=Symbol("_makeBuf"),Ci=Symbol("_mode"),Ns=Symbol("_needDrain"),Tr=Symbol("_onerror"),Cr=Symbol("_onopen"),nc=Symbol("_onread"),Sr=Symbol("_onwrite"),An=Symbol("_open"),Et=Symbol("_path"),yn=Symbol("_pos"),Tt=Symbol("_queue"),Ir=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;[de];[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[de]=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[de]=="number"?this[Ir]():this[An]()}get fd(){return this[de]}get path(){return this[Et]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[An](){it.open(this[Et],"r",(t,e)=>this[Cr](t,e))}[Cr](t,e){t?this[Tr](t):(this[de]=e,this.emit("open",e),this[Ir]())}[vc](){return Buffer.allocUnsafe(Math.min(this[rc],this[wi]))}[Ir](){if(!this[Vt]){this[Vt]=!0;let t=this[vc]();if(t.length===0)return process.nextTick(()=>this[nc](null,0,t));it.read(this[de],t,0,t.length,null,(e,r,i)=>this[nc](e,r,i))}}[nc](t,e,r){this[Vt]=!1,t?this[Tr](t):this[Ec](e,r)&&this[Ir]()}[vt](){if(this[In]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Tr](t){this[Vt]=!0,this[vt](),this.emit("error",t)}[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[de]=="number"&&this[Ir](),!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[Cr](null,it.openSync(this[Et],"r")),t=!1}finally{t&&this[vt]()}}[Ir](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[vc](),r=e.length===0?0:it.readSync(this[de],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[de]=="number"){let t=this[de];this[de]=void 0,it.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];[de];[Ks];[Jt];[ec]=!1;[yn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[de]=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[de]===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[de]}get path(){return this[Et]}[Tr](t){this[vt](),this[Fn]=!0,this.emit("error",t)}[An](){it.open(this[Et],this[Jt],this[Ci],(t,e)=>this[Cr](t,e))}[Cr](t,e){this[Ks]&&this[Jt]==="r+"&&t&&t.code==="ENOENT"?(this[Jt]="w",this[An]()):t?this[Tr](t):(this[de]=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[de]=="number"&&this[Sr](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[de]===void 0||this[Fn]||this[Tt].length?(this[Tt].push(t),this[Ns]=!0,!1):(this[Fn]=!0,this[Ws](t),!0)}[Ws](t){it.write(this[de],t,0,t.length,this[yn],(e,r)=>this[Sr](e,r))}[Sr](t,e){t?this[Tr](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[Sr](null,0);else if(this[Tt].length===1)this[Ws](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],gw(this[de],t,this[yn],(e,r)=>this[Sr](e,r))}}[vt](){if(this[In]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.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=it.openSync(this[Et],this[Jt],this[Ci])}catch(e){if(e?.code==="ENOENT")return this[Jt]="w",this[An]();throw e}else t=it.openSync(this[Et],this[Jt],this[Ci]);this[Cr](null,t)}[vt](){if(this[In]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.closeSync(t),this.emit("close")}}[Ws](t){let e=!0;try{this[Sr](null,it.writeSync(this[de],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 o=Aw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Fi=(t,e,r,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=Wc(c);if(o?.(h,d),bw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(Ew(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(vw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(h,d)}else if(Sw(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:r,asyncNoFile:i,validate:o}),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"),Dw=t=>t,sc=Mu?.writable===!0||Mu?.set!==void 0?t=>{Kn.concat=t?Dw: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,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},sc(!0);let d;try{let h=typeof t[oc]=="number"?t[oc]:this.#r;d=this.#t._processChunk(t,h),sc(!1)}catch(h){sc(!1),this.#o(new Ms(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new Ms(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[$n](Kn.from(h));for(let x=1;x<d.length;x++)u=this[$n](d[x])}else u=this[$n](Kn.from(d));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,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},Pw=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 o=t&255;t=Math.floor(t/256),r?e[i-1]=yf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=bf(o))}},Hw=t=>{let e=t[0],r=e===128?qw(t.subarray(1,t.length)):e===255?Gw(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},Gw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=yf(c):c===0?d=c:(i=!0,d=bf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},qw=t=>{for(var e=t.length,r=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(r+=o*Math.pow(256,e-i-1))}return r},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 o=zn(t,e+156,1),c=Ef.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??zn(t,e,100),this.mode=d?.mode??u?.mode??bn(t,e+100,8),this.uid=d?.uid??u?.uid??bn(t,e+108,8),this.gid=d?.gid??u?.gid??bn(t,e+116,8),this.size=Kw(d?.size??u?.size??bn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??ac(t,e+136,12),this.cksum=bn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),$s(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=zn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??zn(t,e+265,32),this.gname=d?.gname??u?.gname??zn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??bn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??bn(t,e+337,8)??0,t[e+475]!==0){let x=zn(t,e+345,155);this.path=x+"/"+this.path}else{let x=zn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??ac(t,e+476,12),this.ctime=r?.ctime??i?.ctime??ac(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(([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),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Un(t,e,100,o)||this.needPax,this.needPax=En(t,e+100,8,this.mode)||this.needPax,this.needPax=En(t,e+108,8,this.uid)||this.needPax,this.needPax=En(t,e+116,8,this.gid)||this.needPax,this.needPax=En(t,e+124,12,this.size)||this.needPax,this.needPax=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 d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,En(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e: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="",o,c=_r.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=_r.dirname(r),r=_r.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=_r.join(_r.basename(i),r),i=_r.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},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)),Xw={12:8589934591,8:2097151},En=(t,e,r,i)=>i===void 0?!1:i>Xw[r]||i<0?(Fw(i,t.subarray(e,e+r)),!0):(Yw(t,e,r,i),!1),Yw=(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),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[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(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+o}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("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(c){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[c]=d;break;case"ctime":case"atime":case"mtime":t[c]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[c]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[c]=+d;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),ut=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"),ge=Symbol("buffer"),$t=Symbol("queue"),wn=Symbol("ended"),lc=Symbol("emittedEnd"),Gn=Symbol("emit"),Se=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"),yr=Symbol("writing"),Rt=Symbol("aborted"),Us=Symbol("onDone"),qn=Symbol("sawValidEntry"),Hs=Symbol("sawNullBlock"),Gs=Symbol("sawEOF"),Hu=Symbol("closeStream"),l_=1e3,bi=Symbol("compressedBytesRead"),hc=Symbol("decompressedBytesRead"),Gu=Symbol("checkDecompressionRatio"),u_=()=>!0,Bi=class extends kw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[$t]=[];[ge];[Kt];[Hn];[ut]="begin";[mn]="";[Ct];[_i];[wn]=!1;[Se];[Rt]=!1;[qn];[Hs]=!1;[Gs]=!1;[yr]=!1;[yi]=!1;[lc]=!1;[bi]=0;[hc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Us,()=>{(this[ut]==="begin"||this[qn]===!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[qn]===void 0&&(this[qn]=!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[Gs]=!0,this[ut]==="begin"&&(this[ut]="header"),this[Gn]("eof")):(this[Hs]=!0,this[Gn]("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 o=this[Hn]=new a_(r,this[Ct],this[_i]);if(!this[qn])if(o.remain){let c=()=>{o.invalid||(this[qn]=!0)};o.on("end",c)}else this[qn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Gn]("ignoredEntry",o),this[ut]="ignore",o.resume()):o.size>0&&(this[mn]="",o.on("data",c=>this[mn]+=c),this[ut]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Gn]("ignoredEntry",o),this[ut]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ut]="body":(this[ut]="header",o.end()),this[Kt]?this[$t].push(o):(this[$t].push(o),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[yr]||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,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[ut]="header",this[Hn]=void 0,r.end()),o.length}[zu](t,e){let r=this[Hn],i=this[uc](t,e);return!this[Hn]&&r&&this[Fu](r),i}[Gn](t,e,r){this[$t].length===0&&!this[Kt]?this.emit(t,e,r):this[$t].push([t,e,r])}[Fu](t){switch(this[Gn]("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[Se]){let e=this[Se];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})}}[Gu](t){this[hc]+=t.length;let e=this[hc]/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[Se]===void 0||this.brotli===void 0&&this[Se]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<d_)return this[ge]=t,r?.(),!0;for(let d=0;this[Se]===void 0&&d<Ic.length;d++)t[d]!==Ic[d]&&(this[Se]=!1);let o=!1;if(this[Se]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Ac.length;d++)if(t[d]!==Ac[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Se]===!1&&c)if(t.length<512)if(this[wn])this.brotli=!0;else return this[ge]=t,r?.(),!0;else try{new Vn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Se]===void 0||this[Se]===!1&&(this.brotli||o)){let d=this[wn];this[wn]=!1,this[Se]=this[Se]===void 0?new Ow({}):o?new Bw({}):new Nw({}),this[Se].on("data",h=>{this[Gu](h)&&this[Bs](h)}),this[Se].on("error",h=>{this[Rt]||this.abort(h)}),this[Se].on("end",()=>{this[wn]=!0,this[Bs]()}),this[yr]=!0,this[bi]+=t.length;let u=!!this[Se][d?"end":"write"](t);return this[yr]=!1,r?.(),u}}this[yr]=!0,this[Se]?(this[bi]+=t.length,this[Se].write(t)):this[Bs](t),this[yr]=!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[ge]=this[ge]?Buffer.concat([this[ge],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[ge]?this[ge].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ge]&&t.write(this[ge]),t.end()}this[Gn](Us)}}[Bs](t){if(this[yi]&&t)this[fc](t);else if(!t&&!this[ge])this[zs]();else if(t){if(this[yi]=!0,this[ge]){this[fc](t);let e=this[ge];this[ge]=void 0,this[Fs](e)}else this[Fs](t);for(;this[ge]&&this[ge]?.length>=512&&!this[Rt]&&!this[Gs];){let e=this[ge];this[ge]=void 0,this[Fs](e)}this[yi]=!1}(!this[ge]||this[wn])&&this[zs]()}[Fs](t){let e=0,r=t.length;for(;e+512<=r&&!this[Rt]&&!this[Gs];)switch(this[ut]){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[ut])}e<r&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):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[Se]?(t&&(this[bi]+=t.length,this[Se].write(t)),this[Se].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,o=(c,d="")=>{let u=d||_w(c).root||".",h;if(c===u)h=!1;else{let x=r.get(c);h=x!==void 0?x:o(ww(c),u)}return r.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&o(Ri(c)):c=>o(Ri(c))},h_=t=>{let e=new Bi(t),r=t.file,i;try{i=Ar.openSync(r,"r");let o=Ar.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Ar.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<o.size;){let h=Ar.readSync(i,u,0,c,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Ar.closeSync(i)}catch{}}},x_=(t,e)=>{let r=new Bi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Ar.stat(o,(u,h)=>{if(u)d(u);else{let x=new jc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Rr=Fi(h_,x_,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"),Dc=Symbol("openfile"),Pc=Symbol("onopenfile"),vn=Symbol("close"),io=Symbol("mode"),Oc=Symbol("awaitDrain"),xc=Symbol("ondrain"),Pt=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,d]=Vc(this.path);c&&typeof d=="string"&&(this.path=d,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||qu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[Js](o):this[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](){Dt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Js](e)})}[Js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=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)}[Pt](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[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](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[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[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](){Dt.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(qu.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[Dc]()}[Dc](){Dt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Pc](e)})}[Pc](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:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Dt.read(t,e,r,i,o,(c,d)=>{if(c)return this[vn](()=>this.emit("error",c));this[Cc](d)})}[vn](t=()=>{}){this.fd!==void 0&&Dt.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[xc]():this[Oc](()=>this[xc]())}[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)}[xc](){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](Dt.lstatSync(this.absolute))}[kc](){this[Rc](Dt.readlinkSync(this.absolute))}[Dc](){this[Pc](Dt.openSync(this.absolute,"r"))}[Vs](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let d=Dt.readSync(e,r,i,o,c);this[Cc](d),t=!1}finally{if(t)try{this[vn](()=>{})}catch{}}}[Oc](t){t()}[vn](t=()=>{}){this.fd!==void 0&&Dt.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 o=!1;if(!this.preservePaths){let[d,u]=Vc(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Vn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new 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[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Pt](t){return 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 kr{tail;head;length=0;static create(e=[]){return new kr(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,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new kr;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new kr;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new kr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new kr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<r;d++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=I_(this,o,d);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function I_(t,e,r){let i=e,o=e?e.next:t.head,c=new Zc(r,i,o,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}},Xu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Yu=Buffer.alloc(1024),Zs=Symbol("onStat"),vi=Symbol("ended"),yt=Symbol("queue"),Si=Symbol("pendingLinks"),_n=Symbol("current"),jn=Symbol("process"),Ii=Symbol("processing"),qs=Symbol("processJob"),bt=Symbol("jobs"),pc=Symbol("jobDone"),Xs=Symbol("addFSEntry"),Qu=Symbol("addTarEntry"),Lc=Symbol("stat"),Nc=Symbol("readdir"),Ys=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 Pw(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[Xs](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 Xu(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]()}[Xs](t){let e=Q(Zu.resolve(this.cwd,t));this[yt].push(new Xu(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[qs](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[Ys](t,r)})}[Ys](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[qs](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(Yu):(super.write(Yu),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 o of i)o.pending=!1,this[qs](o)}}this[jn]()}[qs](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[Ys](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 o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Xs](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)}},Xc=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[Ys](t,ro.readdirSync(t.absolute))}[Qs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Xs](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 Xc(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 o=new Promise((c,d)=>{i.on("error",d),i.on("close",c),r.on("error",d)});return Rf(r,e).catch(c=>r.emit("error",c)),o},Cf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Rr({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 Rr({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 Xc(t);return Cf(r,e),r},D_=(t,e)=>{let r=new fo(t);return Rf(r,e).catch(i=>r.emit("error",i)),r},M2=Fi(T_,C_,R_,D_,(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 ho.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},so=(t,e,r,i)=>{ho.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},B_=(t,e,r,i,o)=>{if(e.isDirectory())Uf(Di.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Di.resolve(t,e.name);so(d,r,i,o)});else{let c=Di.resolve(t,e.name);so(c,r,i,o)}},Uf=(t,e,r,i)=>{ho.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return so(t,e,r,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return so(t,e,r,i)}};for(let x of c)B_(t,x,e,r,h)})},F_=(t,e,r,i)=>{e.isDirectory()&&Hf(Di.resolve(t,e.name),r,i),Mc(Di.resolve(t,e.name),r,i)},Hf=(t,e,r)=>{let i;try{i=ho.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Mc(t,e,r);throw c}for(let o of i)F_(t,o,e,r);return Mc(t,e,r)},Gf=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"}},xo=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)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Gf(t,r?.code||"ENOTDIR")),e(r)})},H_=(t,e,r)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,m=e.unlink,w=Q(e.cwd),v=(E,S)=>{E?r(E):S&&h?Uf(S,d,u,I=>v(I)):c?ct.chmod(t,o,r):r()};if(t===w)return U_(t,v);if(x)return z_.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let _=Q(oo.relative(w,t)).split("/");Bc(w,_,o,m,w,void 0,v)},Bc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Q(oo.resolve(t+"/"+u));ct.mkdir(h,r,qf(h,e,r,i,o,c,d))},qf=(t,e,r,i,o,c,d)=>u=>{u?ct.lstat(t,(h,x)=>{if(h)h.path=h.path&&Q(h.path),d(h);else if(x.isDirectory())Bc(t,e,r,i,o,c,d);else if(i)ct.unlink(t,m=>{if(m)return d(m);ct.mkdir(t,r,qf(t,e,r,i,o,c,d))});else{if(x.isSymbolicLink())return d(new xo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Bc(t,e,r,i,o,c,d))},G_=t=>{let e=!1,r;try{e=ct.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Gf(t,r??"ENOTDIR")}},q_=(t,e)=>{t=Q(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,m=Q(e.cwd),w=E=>{E&&u&&Hf(E,c,d),o&&ct.chmodSync(t,i)};if(t===m)return G_(m),w();if(h)return w(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=Q(oo.relative(m,t)).split("/"),_;for(let E=v.shift(),S=m;E&&(S+="/"+E);E=v.shift()){S=Q(oo.resolve(S));try{ct.mkdirSync(S,i),_=_||S}catch{let I=ct.lstatSync(S);if(I.isDirectory())continue;if(x){ct.unlinkSync(S),ct.mkdirSync(S,i),_=_||S;continue}else if(I.isSymbolicLink())return new xo(S,S+"/"+v.join("/"))}}return w(_)},wc=Object.create(null),rf=1e4,br=new Set,j_=t=>{br.has(t)?br.delete(t):wc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),br.add(t);let e=wc[t],r=br.size-rf;if(r>rf/10){for(let i of br)if(br.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,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let h of u)o.add(h)}for(let c of i){let d=this.#e.get(c),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(c);continue}else if(u.size===1){d.shift();let h=d[0];typeof h=="function"&&o.add(h)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},J_=()=>process.umask(),sf=Symbol("onEntry"),Fc=Symbol("checkFs"),of=Symbol("checkFs2"),zc=Symbol("isReusable"),ft=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"),qe=Symbol("onError"),js=Symbol("pending"),uf=Symbol("pend"),Er=Symbol("unpend"),yc=Symbol("ended"),bc=Symbol("maybeClose"),Gc=Symbol("skip"),Pi=Symbol("doChown"),Oi=Symbol("uid"),Li=Symbol("gid"),Ni=Symbol("checkedCwd"),Z_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Mi=Z_==="win32",X_=1024,Y_=(t,e)=>{if(!Mi)return se.unlink(t,e);let r=t+".DELETE."+Pf(16).toString("hex");se.rename(t,r,i=>{if(i)return e(i);se.unlink(r,e)})},Q_=t=>{if(!Mi)return se.unlinkSync(t);let e=t+".DELETE."+Pf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},ff=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Yc=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:X_,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(Ne.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[o,c]=Vc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Mi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Ne.posix.dirname(t.path),h=Ne.posix.normalize(Ne.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[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=Ne.isAbsolute(t.path)?Q(Ne.resolve(t.path)):Q(Ne.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}=Ne.win32.parse(String(t.absolute));t.absolute=i+Wu(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Wu(t.path.slice(o.length))}return!0}[sf](t){if(!this[lf](t))return t.resume();switch(P_.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)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Er](),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)}[Pi](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&&se.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let o=1,c=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[qe](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,h=>{h?this[qe](h,t):this[Er](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,m=t.mtime;se.futimes(h,x,m,w=>w?se.utimes(u,x,m,v=>c(v&&w)):c())}if(typeof h=="number"&&this[Pi](t)){o++;let x=this[Oi](t),m=this[Li](t);typeof x=="number"&&typeof m=="number"&&se.fchown(h,x,m,w=>w?se.chown(u,x,m,v=>c(v&&w)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[qe](u,t),e()}),t.pipe(d)),d.pipe(i)}[Hc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Sn](String(t.absolute),r,i=>{if(i){this[qe](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[Er](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Pi](t)&&(o++,se.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(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ti](t,this.cwd,r,()=>this[to](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[cf](t,e){let r=Q(Ne.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ti](t,this.cwd,i,()=>this[to](t,r,"link",e),o=>{this[qe](o,t),e()})}[Ti](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Ne.resolve(e,c);se.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new xo(d,Ne.resolve(d,r.join("/"))));this[Ti](t,d,r,i,o)})}[uf](){this[js]++}[Er](){this[js]--,this[bc]()}[Gc](t){this[Er](),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=d=>{e(d)},i=()=>{this[Sn](this.cwd,this.dmode,d=>{if(d){this[qe](d,t),r();return}this[Ni]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Ne.dirname(String(t.absolute)));if(d!==this.cwd)return this[Sn](d,this.dmode,u=>{if(u){this[qe](u,t),r();return}c()})}c()},c=()=>{se.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Gc](t),r();return}if(d||this[zc](t,u))return this[ft](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[ft](m??null,t,r);return h?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),h=>this[ft](h??null,t,r))}if(t.absolute===this.cwd)return this[ft](null,t,r);Y_(String(t.absolute),h=>this[ft](h??null,t,r))})};this[Ni]?o():i()}[ft](t,e,r){if(t){this[qe](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){se[r](e,String(t.absolute),o=>{o?this[qe](o,t):(this[Er](),t.resume()),i()})}},Ai=t=>{try{return[null,t()]}catch(e){return[e,null]}},Wf=class extends Yc{sync=!0;[ft](t,e){return super[ft](t,e,()=>{})}[Fc](t){if(!this[Ni]){let o=this[Sn](this.cwd,this.dmode);if(o)return this[qe](o,t);this[Ni]=!0}if(t.absolute!==this.cwd){let o=Q(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[Sn](o,this.dmode);if(c)return this[qe](c,t)}}let[e,r]=Ai(()=>se.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Gc](t);if(e||this[zc](t,r))return this[ft](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?Ai(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ft](d,t)}let[o]=Ai(()=>se.rmdirSync(String(t.absolute)));this[ft](o,t)}let[i]=t.absolute===this.cwd?[]:Ai(()=>Q_(String(t.absolute)));this[ft](i,t)}[Uc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(o)}catch(h){u=h}(d||u)&&this[qe](d||u,t),e()},o;try{o=se.openSync(String(t.absolute),zf(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[qe](d,t)),t.pipe(c)),c.on("data",d=>{try{se.writeSync(o,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{se.futimesSync(o,u,h)}catch(x){try{se.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Pi](t)){let u=this[Oi](t),h=this[Li](t);try{se.fchownSync(o,Number(u),Number(h))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Hc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Sn](String(t.absolute),r);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Pi](t))try{se.chownSync(String(t.absolute),Number(this[Oi](t)),Number(this[Li](t)))}catch{}e(),t.resume()}[Sn](t,e){try{return q_(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,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Ne.resolve(c,d);let[u,h]=Ai(()=>se.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new xo(c,Ne.resolve(e,r.join("/"))))}i()}[to](t,e,r,i){let o=`${r}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[qe](c,t)}}},ey=t=>{let e=new Wf(t),r=t.file,i=Df.statSync(r),o=t.maxReadSize||16*1024*1024;new mw(r,{readSize:o,size:i.size}).pipe(e)},ty=(t,e)=>{let r=new Yc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),Df.stat(o,(u,h)=>{if(u)d(u);else{let x=new jc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Kf=Fi(ey,ty,t=>new Wf(t),t=>new Yc(t),(t,e)=>{e?.length&&Sf(t,e)}),ny=(t,e)=>{let r=new Xc(t),i=!0,o,c;try{try{o=at.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=at.openSync(t.file,"w+");else throw h}let d=at.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,w=0;m<512;m+=w){if(w=at.readSync(o,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 h=new Vn(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,ry(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},ry=(t,e,r,i,o)=>{let c=new pf(t.file,{fd:i,start:r});e.pipe(c),sy(e,o)},iy=(t,e)=>{e=Array.from(e);let r=new fo(t),i=(o,c,d)=>{let u=(v,_)=>{v?at.close(o,E=>d(v)):d(null,_)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),w=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return at.read(o,m,x,m.length-x,h+x,w);if(h===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let E=new Vn(m);if(!E.cksumValid)return u(null,h);let S=512*Math.ceil((E.size??0)/512);if(h+S+512>c||(h+=S+512,h>=c))return u(null,h);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,at.read(o,m,0,512,h,w)};at.read(o,m,0,512,h,w)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(h||!x)return c(h);at.fstat(x,(m,w)=>{if(m)return at.close(x,()=>c(m));i(x,w.size,(v,_)=>{if(v)return c(v);let E=new ao(t.file,{fd:x,start:_});r.pipe(E),E.on("error",c),E.on("close",o),oy(r,e)})})};at.open(t.file,d,u)})},sy=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Rr({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 Rr({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")}),X2=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))};xn();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 Xf(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();Ke();re();Te();Ke();function Dr(t,e){if(po(t)!=="cloud")throw new A("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function zi(t){return t.startsWith("http://")||t.startsWith("https://")}function Pr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as Gk}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-beta.3";Ke();re();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 Or(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=G("handshake");async function Qc(t){let e=Or(t.endpoint),r=t.timeoutMs??1e4,i=`${Pr(e)}${i0}?aid=${encodeURIComponent(mo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...kn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Ui.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.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 A("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${E.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${h}`);let w=m.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(m).slice(0,500);throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${E}`)}return Ui.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:v,deviceId:_}}catch(u){if(u instanceof A)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 A("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let h=u.cause;throw Ui.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 A("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}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 o={};if(t.modelToken?o.model=t.model||Nt:d0(t.model)||(o.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},d=rd(e,r,i);Object.keys(d).length>0&&(c.http_headers=d),o.model_providers={coze:c},o.model_context_window=t.modelInfo?.contextWindow??ed}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...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:o}=Hi(t),c={};return i&&(c["x-tt-env"]=i),o&&(c["x-use-ppe"]=o),e&&(c["x-mock-scenario"]=e),r&&(c["x-coze-request-scene"]=r),c}function h0(t,e,r,i){if(!t.modelToken)return{};let o=rd(e,r,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${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 x0(t,e,r,i,o){if(!t.modelToken)return null;let c=sd(t),d=rd(e,r,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let h=[a0(c,u,t.modelInfo?.contextWindow??ed,t.modelInfo?.maxOutput??o0)],x=new Set([c]);for(let w of i??[])!w||x.has(w)||(x.add(w),h.push(a0(w,["text"],ed,o0)));let m={baseUrl:`${td}/v1`,api:"openai-completions",apiKey:t.modelToken,models:h};return Object.keys(d).length>0&&(m.headers=d),m}var he=G("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=st("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=d=>{o||(o=!0,d?r(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var _o=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Zn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Fe(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=xe(o,h.relPath,"SKILL.md");await fd(x).then(w=>w.isFile()).catch(()=>!1)&&(d.push(Ly(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await k0(r,o,h),m=await T0(r,h);for(let w of[...x,...m])u.has(w.relPath)||(u.add(w.relPath),d.push(w.skill))}return{skills:d}}async addSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((h,x)=>[h.skillId,x])),u=[];for(let h of o){let x=await yo({agentId:r,workspace:i.workspace,framework:i.framework,skill:h});bo(c,d,x),u.push(h)}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),o=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!o.has(u.skillId)){d.push(u);continue}let h=xe(i.workspace,u.relPath);await cd(h,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await ui(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Zn(e._meta);if(!e.skillName)throw new A("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),o=i?.workspace??Fe(r).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await Dy(r,o,c,e.skillName,d);if(!u){let R=d?"global":"workspace";throw new A("SKILL_NOT_FOUND",`skill not found in ${R}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:m}=u,w=xe(h,"SKILL.md"),v=new xd.default;v.addLocalFolder(h,m);let _=v.toBuffer();if(_.length>m0)throw new A("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${m0}`);let E=await wo(w,{encoding:"utf8"}).then(R=>I0(R).description).catch(()=>{}),S={};this.opts.publishSkillToMarketplace?S=await this.opts.publishSkillToMarketplace({zip:_,...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 I=S.version??"v1.0",k=S.skillId??e.skillId??S0(r,x);if(i&&!d){let R=i.skills??[],b=R.find(D=>D.relPath===x);b?(b.version=I,b.skillId=k):R.push({skillId:k,skillName:e.skillName,relPath:x,version:I,installedAt:Date.now(),...E?{description:E}:{}}),await ui(r,R)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:k,version:I}),{ok:!0,skillId:k,version:I}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let h=c.downstream;c.downstream=void 0,he.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),h.stop(r).catch(x=>he.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return he.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Ce(r);if(!i)throw new A("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 xr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw he.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new A("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await ze(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 A("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Ce(r))throw new A("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&zi(e.registry)&&o.push(`--registry=${e.registry}`);let c=Ty(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Iy.test(d)&&o.push("--env",d);let u=await Cy(o);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 A("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Ce(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await ze(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 A("IPC_BAD_REQUEST",`${ht.DELETE}: missing agentId`);let i=await Ce(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let d=Fe(r);return c==="cloud"?await cd(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await ze(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 A("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=nd(e.model)??Nt,i=await Ce(e.agentId);if(!i)throw new A("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await ze(i),he.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return he.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>he.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,h]of o.allSessionQueues())d.push(h.enqueue(async()=>{let x=o.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${r}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),he.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Dr(e._meta,ht.RESET),!e.agentId)throw new A("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 o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await li(e,o)}async clearPersistedAcpSessionIds(e){let r=await Ce(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await ze(r)}async repairAgent(e){if(Dr(e._meta,ht.REPAIR),!e.agentId)throw new A("IPC_BAD_REQUEST",`${ht.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new A("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(o){he.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Dr(e._meta,"_agent/getFileTree");let r=e._meta,i=Zn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await od(d).catch(()=>null);if(!u)throw new A("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await di(d,o))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=Ky(e.depth);return u.isDirectory()?{tree:await Wy(o,d,c,h)}:{tree:[{name:$y(c),path:D0(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 A("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await od(o).catch(()=>null);if(!c||!c.isFile())throw new A("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await di(o,i))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>g0)throw new A("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${g0})`);let d=await wo(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:c.size}:{content:d.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await Ce(e).catch(()=>null))?.workspace??Fe(e).workspace}safeJoin(e,r){let i=ld(e,r||"."),o=hd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${_0}`))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Ce(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new A("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 A("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new A("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function pd(t){return t==="claude-code"?xe(".claude","skills"):xe(".agents","skills")}function v0(t){let e=_y();return t==="claude-code"?[xe(e,".claude","skills")]:t==="codex"?[xe(e,".agents","skills"),xe(e,".codex","skills")]:[xe(e,".agents","skills"),xe(e,".openclaw","skills")]}async function Ry(t,e,r,i){let o=async c=>fd(xe(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=xe(pd(e),r),d=xe(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of v0(e)){let d=xe(c,r);if(await o(d))return{absDir:d,relPath:d}}return null}async function Dy(t,e,r,i,o){let c=E0(i),d=await Ry(e,r,c,o);if(d)return{...d,dirName:c};let h=(o?await T0(t,r):await k0(t,e,r)).filter(w=>w.skill.skillName===i);if(h.length>1)throw new A("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(w=>p0(w.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=h[0];return x?{absDir:o?x.relPath:xe(e,x.relPath),relPath:x.relPath,dirName:p0(x.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 o of r.split(`
94
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function A0(t,e,r,i){let o=await w0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await fd(xe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=xe(r,h),m=xe(e,h,"SKILL.md"),w=await wo(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let v=I0(w);c.push({relPath:x,skill:{skillId:S0(t,x),skillName:v.name||h,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function k0(t,e,r){let i=pd(r);return A0(t,xe(e,i),i,!1)}async function T0(t,e){let r=[],i=new Set;for(let o of v0(e)){let c=await A0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var Py=3e4,Oy=50*1024*1024,m0=10*1024*1024,Lr=3e4;async function yo(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new A("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,d=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!d)throw new A("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=E0(o.skillName),h=pd(i),x=xe(h,u),m=xe(r,x);if(await ad(m,{recursive:!0}),c){let v=Buffer.from(o.content,"utf8");Gi(v.length),await dd(xe(m,"SKILL.md"),v,"utf8")}else{let v=await My(o.downloadUrl);Fy(v)?await Gy(v,m):zy(v)?await Uy(v,m):await dd(xe(m,"SKILL.md"),v.toString("utf8"),"utf8")}let w={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return he.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,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 Ce(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Lt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=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 ze(r,e),{status:"noop",count:0};let h=0,x=0;for(let m of u)try{await cd(xe(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,d,w),h+=1}catch(w){x+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(w)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await ze(r,e),he.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function My(t){if(!t)throw new A("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Gi(e);let r=By(t);return Gi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await wo(e);return Gi(r.length),r}if(zi(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Py);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new A("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Gi(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new A("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Gi(t){if(t>Oy)throw new A("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function By(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new A("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 xd.default(t),i=r.getEntries()}catch(d){throw new A("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||ud(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new A("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new A("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new A("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Hy(i),c=ld(e);for(let d of i){if(ud(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=ld(e,u),x=hd(c,h);if(x.startsWith("..")||x==="..")throw new A("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await ad(h,{recursive:!0});continue}await ad(yy(h),{recursive:!0});let m;try{m=d.getData()}catch(w){throw new A("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await dd(h,m)}}function Hy(t){let e;for(let r of t){let i=r.entryName;if(!i||ud(i))continue;let o=i.indexOf("/");if(o<=0)return;let c=i.slice(0,o+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function Gy(t,e){await qy(t);let r=Kf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new A("IPC_BAD_REQUEST",`tar extract timeout (${Lr}ms)`))},Lr);try{await b0(y0.from(t),r)}catch(c){throw c instanceof A?c:i?new A("IPC_BAD_REQUEST",`tar extract timeout (${Lr}ms)`):new A("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function qy(t){let e=[],r=Rr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new A("IPC_BAD_REQUEST",`tar list timeout (${Lr}ms)`))},Lr);try{await b0(y0.from(t),r)}catch(c){throw i?new A("IPC_BAD_REQUEST",`tar list timeout (${Lr}ms)`):new A("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new A("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,o){if(i<=0)return[];let c;try{c=await w0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(Sy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=jy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=xe(e,u.name),x=by(xe(r,u.name)),m=null;try{m=await od(h)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let w={name:u.name,path:D0(hd(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await R0(t,h,x,i-1,o)),d.push(w)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}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 D0(t){return t.split(_0).join("/")}re();var Tn=G("agent-health-reporter"),Vy=1e4,Jy=3,qi=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 d of this.opts.core.agents.values()){let u=Zy(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),r.push(h)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Tn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(Tn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){Tn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}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}xn();import{copyFile as hE,cp as xE,mkdir as Oo,readFile as pE,rm as gE,stat as Sd,writeFile as mE}from"node:fs/promises";import{homedir as fh}from"node:os";import{basename as wE,join as Yt}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 Nr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Mr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Cn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ke();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)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function P0(t){return"method"in t&&"id"in t&&t.id!==void 0}function O0(t){return"method"in t&&!("id"in t)}function vo(t){return!("method"in t)&&"id"in t}var Xy={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 Yy(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 A){let e=Yy(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:Xy[t.code]??X.INTERNAL_ERROR,message:Wi(t.message),data:r}}return{code:X.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,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new A(r,o,{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 o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${N0} bytes`)}),[]}let r=this.buffer.split(`
96
+ `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(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"},PT=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:[]},Br=class{seq=0;next(e,r){this.seq+=1;let i=F0[e]??nb(e),o=tb[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(h=>B0(r?.[h]??"")),u=rb(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>B0(String(d))).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)}hn();import{readFileSync as ib}from"node:fs";var sb=384;async function gd(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);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=o=>o){return{...i({...t,...$i(e)}),...r}}Zt();dr();Ke();re();Te();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 Fr="coze-bridge-daemon";function G0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return ob("pgrep",["-U",String(o),"-f",Fr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function q0(t,e){if(t.length===0)return;let r=e?.killFn??Ji,i=e?.isAliveFn??Vi,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(h=>i(h));u+=d)await o(Math.min(d,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 zr(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 o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,m=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:zr(m,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:zr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:zr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:zr(c,!1,e)}}var V0=Xe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),hb=200,xb=40,pb=Xe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),gb=Xe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),mb=Xe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),wb=Xe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),_b=Xe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),yb=Xe("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=G(`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 Br;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new A("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=Io(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=st(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",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>hb&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,U0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,d=vb(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new A("AGENT_SPAWN_FAILED",Sb(c,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Ji(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Ji(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:_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(Nr("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(Mr(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,o){if(!this.child||this.stopped)return Promise.reject(new A("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=ji(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let h=r.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let m={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),v={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:zr(0,!1,o),sessionId:u};m.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},S=this.now(),I=$0(E,v.cfg,S),k=R=>{v.armedAt=S,v.expectedIntervalMs=R,m.timer=setTimeout(_,R)};if(I.action==="suspend"){v.suspendedMs+=I.suspendedDeltaMs,v.lastActivityAt=S,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:I.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),k(I.rearmMs);return}if(I.action==="continue"){k(I.rearmMs);return}this.pending.delete(c),I.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:I.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(I.awaitingApproval?new A("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new A("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new A("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(_,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(w){m.timer&&clearTimeout(m.timer),this.pending.delete(c),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new A("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 A("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 o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(P0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="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 A(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 A("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(xb).join(`
98
+ `),o=W0(this.framework,i);return o?new A(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new A("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??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}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 nh,readSync as Db,readdirSync as Pb,rmSync as Ob,statSync as Lb}from"node:fs";import{homedir as Nb,tmpdir as Mb}from"node:os";import{join as Ur}from"node:path";var X0=["default","acceptEdits","plan","auto","bypassPermissions"],Y0=["read-only","auto","full-access"];function Bt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return X0.includes(e);case"codex":return Y0.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 X0.join("/");case"codex":return Y0.join("/");case"openclaw":return""}}Te();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 eh(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,o=Hb(e.env);return{command:r,timeoutMs:e.timeout_ms===void 0?zb(e.timeout):Ub(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function _d(t){if(Array.isArray(t))return t.flatMap(i=>_d(i));if(!t||typeof t!="object"){let i=eh(t);return i?[i]:[]}let e=t;if(e.hooks)return _d(e.hooks);let r=eh(e);return r?[r]:[]}function Gb(t){let e=Ur(t,"hooks.json");if(!yd(e))return[];let r=JSON.parse(nh(e,"utf8")),o=r.hooks&&typeof r.hooks=="object"?r.hooks:r;return _d(o.Stop??o.stop)}function qb(t,e){let r=Ur(t,"sessions");if(!yd(r))return;let i=[],o=c=>{let d;try{d=Pb(c,{withFileTypes:!0})}catch{return}for(let u of d){let h=Ur(c,u.name);if(u.isDirectory())o(h);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:h,mtimeMs:Lb(h).mtimeMs})}catch{}}};o(r),i.sort((c,d)=>d.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),o=Db(r,i,0,i.length,0),c=i.subarray(0,o).toString("utf8");return c.includes(JSON.stringify(e))||c.includes(e)}catch{return!1}finally{if(r!==void 0)try{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 o=i.startsWith("export ")?i.slice(7).trimStart():i,c=o.indexOf("=");if(c<=0)continue;let d=o.slice(0,c).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=Kb(o.slice(c+1)))}return e}function Vb(t){let e=Ur(t,"cozeloop.env");return yd(e)?$b(nh(e,"utf8")):{}}function th(t){let e=t?.trim();return e||void 0}function Jb(t){let e=Wb(t.agentEnvFile),r=th(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(r)return r;let i=th(t.env?.HOME??e.HOME??process.env.HOME)??Nb();return Ur(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:o,args:c}=ci("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Cb(Ur(Mb(),"coze-bridge-codex-home-")):Jb(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Tb(d,{recursive:!0});let h=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:c,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 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=Gb(r)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:r,err:String(d)});return}if(i.length===0)return;let o=qb(r,e),c=JSON.stringify({hook_event_name:"Stop",session_id:e,...o?{transcript_path:o}:{},trigger:"coze-bridge"});await Promise.all(i.map(async d=>{try{await this.runHookCommand(d,c)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:r,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,r){return new Promise((i,o)=>{let c=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=c?Vb(c):{},u=Io(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let h=Ab(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",m=setTimeout(()=>{h.kill("SIGTERM"),o(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(m),o(w)}),h.on("close",(w,v)=>{if(clearTimeout(m),w===0){i();return}o(new Error(`hook exited code=${w} signal=${v} stderr=${x.slice(-1e3)}`))}),h.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}}}Ke();var Xb=3e4,Hr=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 o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Xb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};hn();Ke();re();Te();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 Xt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Zt();re();import{constants as rh}from"node:fs";import{access as Yb}from"node:fs/promises";import{delimiter as Qb,join as eE}from"node:path";var St=G("framework-detector"),ih={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},tE=[".exe",".cmd",".bat",".ps1"],Xn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??Yb}}async detect(e){let r=ih[e],i=await this.which(r);if(!i)return St.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(ih).map(async i=>[i,await this.detect(i)])),r={};for(let[i,o]of e)o&&(r[i]=o);return r}async which(e){let r=this.env.pathEnv.split(Qb).filter(Boolean),i=this.env.platform==="win32"?["",...tE]:[""];for(let o of r)for(let c of i){let d=eE(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?rh.F_OK:rh.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 o=JSON.parse(i[0]);if(!Array.isArray(o))return St.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(St.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(St.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return St.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return 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 o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){St.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}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 o="",c=!1,d,u=h=>{c||(c=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{o+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},nE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function rE(t){return t.replace(nE,"")}import{homedir as oh}from"node:os";import{join as Do}from"node:path";hn();Zt();dr();Ke();re();async function ah(){let t=Do(oh(),".openclaw/openclaw.json");return ln(t)}async function ch(){return(await ah())?.gateway?.auth?.token??""}var Yn=G("openclaw.config"),iE=[0,5e3,5e3],sE=Xe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),sh="models.providers.",Ro="agents.defaults.models",oE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function qr(t,e){let r=Array.isArray(t)?[...t]:[],i=new Set(r);for(let o of e)i.has(o)||(i.add(o),r.push(o));return r}var Po=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??Do(oh(),".openclaw")}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(d=>setTimeout(d,c));try{return await r()}catch(d){i=d,Yn.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new A("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=st(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?r():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",r],["Config path not found","Nothing was changed"])))}catch(i){Yn.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${sh}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${sh}${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 ah())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,c=[];for(let d of Object.keys(i))d.startsWith(o)&&c.push(d.slice(o.length));return c}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}ensureAcpDeviceScopes(){return this.queue.enqueue(()=>this.ensureAcpDeviceScopesUnlocked())}async ensureAcpDeviceScopesUnlocked(){try{let e=Do(this.openclawDir,"identity","device.json"),i=(await ln(e))?.deviceId?.trim();if(!i)return Yn.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Do(this.openclawDir,"devices","paired.json"),c=await ln(o),d=c?.[i];if(!c||!d)return Yn.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,h=qr(qr(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(E=>E.startsWith("operator.")),x=qr([...oE],h),m=qr(d.scopes,x),w=qr(d.approvedScopes,x),v=u?qr(u.scopes,x):void 0;return m.length!==(d.scopes?.length??0)||w.length!==(d.approvedScopes?.length??0)||u!==void 0&&v?.length!==(u.scopes?.length??0)?(d.scopes=m,d.approvedScopes=w,u&&v&&(u.scopes=v),await fn(o,c,{mode:384}),Yn.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(Yn.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return Yn.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};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(`
109
103
  `)?t.slice(0,-1):t).split(`
110
104
  `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
111
105
  `)}
112
- `}async function dh(t){let e=Jb(t,"HEARTBEAT.md"),n=await $b(e,"utf8");return Xb(n)!==Zb?!1:(await Vb(e,Yb),!0)}var ae=K("agent-manager"),vd="acceptEdits",hh="full-access",xh="read-only";function nE(t){return{INITIAL_AGENT_MODE:Po(t)}}var rE=(t,e,n,i,o,c,l,u,h,x)=>{switch(t){case"claude-code":{let m={...o?{...o0(o),...d0(o,l,u)}:{},...h??{},IS_SANDBOX:"1"};return new Ro({cwd:n,env:m,agentId:i})}case"codex":{let m=hh;x!==void 0&&(Bt("codex",x)?m=x:ae.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let w=!!o,v={...o?{...c0(o),...a0(o,l,u)}:{},...nE(m),...w?{NO_BROWSER:"1"}:{},...h??{}};return new Co({cwd:n,agentId:i,...Object.keys(v).length>0?{env:v}:{},...w?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ur({command:e,cwd:n,agentId:i,...c?{sessionName:yd(c)}:{}});case"hermes":return new Do({command:e,cwd:n,agentId:i,...h&&Object.keys(h).length>0?{env:{...h}}:{},...o?.model?{modelId:o.model}:{}})}};function Ed(t){return t==="claude-code"||t==="codex"}var iE={path:"",version:"cloud-deployed"},uh="openclaw_gateway_unavailable",sE="openclaw_default_agent_missing";function fh(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 oE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},aE=6e4,Mo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??rE,this.createTimeoutMs=e.createTimeoutMs??aE,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new No({command:n})),this.openclawConfigDir=e.openclawConfigDir??lh(tE(),".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=>{ae.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=lh(e,".env");if(await eE(n).then(c=>c.isFile()).catch(()=>!1)){ae.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=zi({...process.env,...Fi(this.paths.agentEnvFile)});await ht(n,o,{mode:384}),ae.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ae.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 Se(e.agentId,this.paths).catch(()=>null),o=go(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")ae.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>ae.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")ae.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>ae.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ae.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await Se(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Ge(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ae.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await Se(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Ge(T,this.paths))}return ae.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework]){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=Ue(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",m;x&&!n?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=m??(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{o&&Ed(e.framework)&&await lr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await bd(u.root,{recursive:!0}),await bd(v,{recursive:!0}),await bd(u.logs,{recursive:!0}),T(),x||await hr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Ka(v,"cloud"):await Ka(v,"local",vd)),T();let O=i,b=i0({model:e.model??O?.model}),D=jf(e._meta)??O?.accountId,L=e.patToken??O?.patToken,G=h==="cloud"?e.modelInfo??O?.modelInfo:void 0;if(I=new Oo({agentId:e.agentId,framework:e.framework,workspace:v,model:b.model??kt,deployType:h,...D?{accountId:D}:{},...L?{patToken:L}:{},...G?{modelInfo:G}:{}}),I.status="ok",O?.sessions){let J=e.framework==="hermes"||h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,ce]of Object.entries(O.sessions)){let de={acpSessionId:ce.acpSessionId,modelToken:ce.modelToken,tokenGeneratedAt:ce.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};J?ce.permissionMode===void 0?(de.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ae.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Q,framework:e.framework,fallback:de.permissionMode})):Bt(e.framework,ce.permissionMode)?de.permissionMode=ce.permissionMode:ae.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:ce.permissionMode}):ce.permissionMode!==void 0&&ae.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:h}),ce.cozeGroupId&&(de.cozeGroupId=ce.cozeGroupId),I.sessions.set(Q,de)}let ie=Object.keys(O.sessions).length;ie>0&&ae.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(I),A=!0;let U={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"&&(U.deployType="cloud"),D&&(U.accountId=D),L&&(U.patToken=L),G&&(U.modelInfo=G),O?.skills&&(U.skills=O.skills),O?.agentName&&(U.agentName=O.agentName),O?.description&&(U.description=O.description),U.skillsRefreshedForVersion=O?.skillsRefreshedForVersion??Mt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ae.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await dh(v)&&ae.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(J){ae.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(J)})}}let Z=e.initialSkills??[];if(Z.length>0){let J=[...U.skills??[]],ie=new Map(J.map((de,P)=>[de.skillId,P])),Q=await Promise.allSettled(Z.map(de=>So({agentId:e.agentId,workspace:v,framework:e.framework,skill:de,paths:this.paths}))),ce=0;for(let[de,P]of Q.entries()){let H=Z[de];H&&(P.status==="fulfilled"?(Io(J,ie,P.value),ce++):ae.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:H.skillId,skillName:H.skillName,err:String(P.reason)}))}ce>0&&(U.skills=J,ae.info("initialSkills installed",{agentId:e.agentId,installed:ce,requested:Z.length}))}return await Ge(U,this.paths),ae.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 ae.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ae.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 Qb(u.root,{recursive:!0,force:!0}).catch(O=>ae.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,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&Ed(e.framework))u=iE;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`);Ed(e.framework)&&!vs(e.framework)&&(ae.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else if(e.framework==="hermes"){let m={...this.buildBinShimPathEnv()};h&&(await p0({paths:this.paths,agentId:e.agentId,modelConfig:h,cozeEnv:o,mockScenario:c}),m.HERMES_HOME=Jn(e.agentId,this.paths)),x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,c,m)}else{let m=e.sessions.get(i),w=Qt(e)?m?.permissionMode??hh:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,c,this.buildBinShimPathEnv(),w)}try{return await x.start(),await x.initialize(oE),x}catch(m){let w=x instanceof gt?x.getStderrTail():[];throw w.length>0&&ae.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof k?m.code:"unknown",recentStderr:w}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,m)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",fh(o),{cause:{reason:uh}})}catch(o){ae.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};ae.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 ae.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:sE}})}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",fh(n),{cause:{reason:uh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,h=yd(o);if(n.deployType==="local"){let w=await this.ensureOpenclawDefaultAgent();return new Ur({command:u,cwd:w.workspace,agentId:w.id,sessionName:h})}let x=await ch(),m;if(i?.modelToken){let w=id(o),v=sd(i),_=`${w}/${v}`;if(!this.ensuredProviders.has(_)){let E=this.getOpenclawConfig(),I=await E.getAllowlistModelsForProvider(w),A=l0(i,c,l,I);A&&(await E.ensureProvider(w,A),await E.addModelToAllowlist(_),this.ensuredProviders.add(_))}m=_}return new Ur({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:h,...x?{gatewayToken:x}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let c of e.sessions.keys()){let l=id(c),u=`${l}/${o}`,h=!0;try{await i.removeProvider(l)}catch(x){h=!1,ae.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:l,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,ae.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as _h}from"node:crypto";import{promises as xE}from"node:fs";import{basename as yh}from"node:path";Ve();ne();import{promises as cE}from"node:fs";import{basename as dE}from"node:path";var ph=K("file-upload"),lE="/api/coze_claw/file/agent_upload",uE=6e4;async function mh(t,e={}){let i=`${Cr(Dr(e.handshakeBase))}${lE}`,o=e.timeoutMs??uE,c=await cE.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",...Sn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);ph.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:h.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 v=await m.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 ph.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(m){throw m instanceof k?m:m.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${dE(t.path)}`):new k("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}Ve();ne();import{extname as fE}from"node:path";var hE={".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 gh(t){let e=fE(t).toLowerCase();return hE[e]??"application/octet-stream"}Pe();var Bo=K("agent-send"),wh=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 o=i.sessions.get(n);if(!o)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function Eh(t,e,n,i,o,c){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){u=x,h<2&&(Bo.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function vh(t,e){let{session:n,runtime:i}=bh(e.core,t.agentId,t.sessionId);if(!await ci(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await xE.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>wh)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${wh}`);let c=await gh(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??yh(t.path),u;try{u=await mh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:o.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Bo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:_h(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:l,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Bo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Sh(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 o=t.name??yh(t.path),c={sessionUpdate:"group_file",messageId:_h(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(e,n,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Bo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function Ih(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(n.length,i.length);for(let c=0;c<o;c++){let l=n[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}Xt();ne();ln();var Ft=K("coze-cli-installer"),Ah="@coze/cli@latest",pE="coze",kh="0.1.8",mE=5e3,gE=5e3,wE=9e4,Th=1e4,Yi=null,Fo=!1;async function Id(t,e={}){if(Fo)return;if(Yi)return Yi;let n=e.exec??Jf;return Yi=(async()=>{try{let i=await _E(pE,n),o=!1;if(i){let l=await yE(n);if(l===void 0)Ft.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Ih(l,kh))Ft.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:kh}),o=!0;else{Ft.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),Fo=!0;return}}let c=o?"upgrade-only":"full";Ft.info("coze-cli install start",{package:Ah,mode:c});try{await n("npm",["i","-g","--prefer-online",Ah],{timeout:wE,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(o){Fo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Th}),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 n("coze",["auth","login","--token",t.patToken],{timeout:Th}),Ft.info("coze auth login ok")}catch(l){Ft.warn("coze auth login failed",{err:String(l)});return}Fo=!0}finally{Yi=null}})(),Yi}async function _E(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:mE});return qa(i)}catch{return}}async function yE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:gE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Kt();jt();Pe();var bE=10*6e4;function Rh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?bE:e}function zo(t){return ur(t??Y().configFile)}function Xi(t,e){return fr(e??Y().configFile,t)}import{randomBytes as GE}from"node:crypto";ar();Ve();ne();import{createReadStream as EE}from"node:fs";import{mkdir as vE,readFile as SE,realpath as IE,stat as AE,writeFile as kE}from"node:fs/promises";import{basename as TE,dirname as Ad,isAbsolute as RE,join as PE,relative as CE,resolve as Ph,sep as DE}from"node:path";import{createInterface as OE}from"node:readline";var Dh=K("fs-rpc"),Qi=Xe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Oh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>Qi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${Qi} bytes`);let i=await Nh(t.path,e);return await vE(Ad(i),{recursive:!0}),await kE(i,t.content,"utf8"),Dh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Lh(t,e){let n=await Nh(t.path,e),i=await AE(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Qi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Qi} bytes`);let c;if(o&&i.size>Qi)c=await LE(n,t.line??1,t.limit);else{let l=await SE(n,"utf8");if(o){let u=l.split(`
106
+ `}async function dh(t){let e=dE(t,"HEARTBEAT.md"),r=await aE(e,"utf8");return fE(r)!==lE?!1:(await cE(e,uE),!0)}var ee=G("agent-manager"),_E=["hooks.json","cozeloop.env"],yE=["hooks"];async function bE(t,e){let r=Yt(Fe(t,e).root,"codex-home"),i=Yt(fh(),".codex");if(r!==i){await Oo(r,{recursive:!0});for(let o of yE){let c=Yt(i,o),d=Yt(r,o);try{await Sd(d);continue}catch{}try{await xE(c,d,{recursive:!0,errorOnExist:!0,filter:u=>{let h=wE(u);return!h.endsWith(".log")&&!h.includes(".bak")}}),ee.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ee.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of _E){let c=Yt(i,o),d=Yt(r,o);try{await Sd(d);continue}catch{}try{if(o==="cozeloop.env"){let h=(await pE(c,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
107
+ `);await mE(d,h,{mode:384})}else await hE(c,d);ee.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ee.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var Id="acceptEdits",hh="full-access",xh="read-only";function EE(t){return{INITIAL_AGENT_MODE:ko(t)}}var vE=(t,e,r,i,o,c,d,u,h,x,m,w)=>{switch(t){case"claude-code":{let v={...o?{...l0(o),...h0(o,d,u,w)}:{},...h??{},IS_SANDBOX:"1"};return new Ao({cwd:r,env:v,agentId:i})}case"codex":{let v=hh;x!==void 0&&(Bt("codex",x)?v=x:ee.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...o?{...f0(o),...u0(o,d,u,w)}:{},...EE(v),...o?{NO_BROWSER:"1"}:{},...h??{},...o?{COZELAB_ONBOARD_CLOUD:"true"}:{}},E=!!o;return new To({cwd:r,agentId:i,...Object.keys(_).length>0?{env:_}:{},...E?{authMethodId:"api-key",isolateCodexHome:!0,...m?{codexHomeDir:m}:{}}:{}})}case"openclaw":return new Hr({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 o=t[i];o!==void 0&&(IE(o)||e.push(`${i}=${o}`))}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"},lh="openclaw_gateway_unavailable",kE="openclaw_default_agent_missing";function uh(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 Xn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Po({command:r,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??Yt(fh(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{ee.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=Yt(e,".env");if(await Sd(r).then(c=>c.isFile()).catch(()=>!1)){ee.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=SE({...process.env,...$i(this.paths.agentEnvFile)});await un(r,o,{mode:384}),ee.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ee.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new A("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new A("IPC_BAD_REQUEST","framework required");let i=await Ce(e.agentId,this.paths).catch(()=>null),o=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 A("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(k=>ee.warn("dispose stale agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else if(o&&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(k=>ee.warn("dispose drifted agent failed (ignored)",{err:String(k)})),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 k=await Ce(e.agentId,this.paths).catch(()=>null);k&&(k.patToken=e.patToken,await ze(k,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ee.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let k=await Ce(e.agentId,this.paths).catch(()=>null);k&&(k.modelInfo=e.modelInfo,await ze(k,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(!o&&!this.config.frameworksCache?.[e.framework])throw new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Fe(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",m;x&&!r?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??w??u.workspace,_=new AbortController,E=setTimeout(()=>_.abort(new A("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),S,I=!1;try{o&&vd(e.framework)&&await hr(e.framework,_.signal);let k=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new A("AGENT_TIMEOUT","_agent/create aborted")};await Oo(u.root,{recursive:!0}),await Oo(v,{recursive:!0}),await Oo(u.logs,{recursive:!0}),k(),x||await xr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await qa(v,"cloud"):await qa(v,"local",Id)),k();let R=i,b=c0({model:e.model??R?.model}),D=Vf(e._meta)??R?.accountId,O=e.patToken??R?.patToken,F=h==="cloud"?e.modelInfo??R?.modelInfo:void 0;if(S=new Co({agentId:e.agentId,framework:e.framework,workspace:v,model:b.model??Nt,deployType:h,...D?{accountId:D}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),S.status="ok",R?.sessions){let K=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,te]of Object.entries(R.sessions)){let oe={acpSessionId:te.acpSessionId,modelToken:te.modelToken,tokenGeneratedAt:te.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?te.permissionMode===void 0?(oe.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:Y,framework:e.framework,fallback:oe.permissionMode})):Bt(e.framework,te.permissionMode)?oe.permissionMode=te.permissionMode:ee.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:te.permissionMode}):te.permissionMode!==void 0&&ee.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:h}),te.cozeGroupId&&(oe.cozeGroupId=te.cozeGroupId),te.tokenGroupId&&(oe.tokenGroupId=te.tokenGroupId),te.requestScene&&(oe.requestScene=te.requestScene),S.sessions.set(Y,oe)}let ie=Object.keys(R.sessions).length;ie>0&&ee.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(S),I=!0;let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:R?.createdAt??Date.now(),sessions:R?.sessions??{},model:b.model};if(h==="cloud"&&(M.deployType="cloud"),D&&(M.accountId=D),O&&(M.patToken=O),F&&(M.modelInfo=F),R?.skills&&(M.skills=R.skills),R?.agentName&&(M.agentName=R.agentName),R?.description&&(M.description=R.description),M.skillsRefreshedForVersion=R?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ee.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await dh(v)&&ee.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(K){ee.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(K)})}}let V=e.initialSkills??[];if(V.length>0){let K=[...M.skills??[]],ie=new Map(K.map((oe,P)=>[oe.skillId,P])),Y=await Promise.allSettled(V.map(oe=>yo({agentId:e.agentId,workspace:v,framework:e.framework,skill:oe}))),te=0;for(let[oe,P]of Y.entries()){let U=V[oe];U&&(P.status==="fulfilled"?(bo(K,ie,P.value),te++):ee.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(P.reason)}))}te>0&&(M.skills=K,ee.info("initialSkills installed",{agentId:e.agentId,installed:te,requested:V.length}))}return await ze(M,this.paths),ee.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(k){throw ee.error("agent create failed, rolling back",{agentId:e.agentId,err:String(k)}),I&&S&&(await S.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await gE(u.root,{recursive:!0,force:!0}).catch(R=>ee.warn("rm agent dir failed (ignored)",{err:String(R)})),k instanceof A?k:new A("AGENT_SPAWN_FAILED",String(k),{cause:k})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,r,i,o,c,d){let h=this.config.frameworksCache?.[e.framework];if(!h)if(e.deployType==="cloud"&&vd(e.framework))h=AE;else throw new A("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 x=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:x,cloudSessionId:i,cozeEnv:o,mockScenario:c,requestScene:d,command:h.path});else{let w=e.sessions.get(i),v=Xt(e)?w?.permissionMode??hh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await bE(e.agentId,this.paths),m=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),v,e.framework==="codex"&&e.deployType==="cloud"?Yt(Fe(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await m.start(),await m.initialize(TE),m}catch(w){let v=m instanceof Mt?m.getStderrTail():[];throw v.length>0&&ee.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof A?w.code:"unknown",recentStderr:v}),await m.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,h.path,w)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new A("AGENT_ENV_NOT_READY",uh(o),{cause:{reason:lh}})}catch(o){ee.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof A?i:new A("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};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 A("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:kE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new A("AGENT_ENV_NOT_READY",uh(r),{cause:{reason:lh}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,requestScene:u,command:h}=e,x=Ed(o);if(r.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Hr({command:h,cwd:v.workspace,agentId:v.id,sessionName:x})}let m=await ch();try{let v=this.getOpenclawConfig();await v.ensureAcpDeviceScopes()&&await v.restartGateway()}catch(v){ee.warn("acp device scope ensure failed (ignored)",{err:String(v)})}let w;if(i?.modelToken){let v=id(o),_=sd(i),E=`${v}/${_}`,S=JSON.stringify({modelConfig:i,cozeEnv:c,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(E)!==S){let I=this.getOpenclawConfig(),k=await I.getAllowlistModelsForProvider(v),R=x0(i,c,d,k,u);R&&(await I.ensureProvider(v,R),await I.addModelToAllowlist(E),this.ensuredProviders.set(E,S))}w=E}return new Hr({command:h,cwd:r.workspace,agentId:r.agentId,sessionName:x,...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,o=r??e.model;for(let c of e.sessions.keys()){let d=id(c),u=`${d}/${o}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,ee.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,ee.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as _h}from"node:crypto";import{promises as ME}from"node:fs";import{basename as yh}from"node:path";Ke();re();import{promises as RE}from"node:fs";import{basename as DE}from"node:path";var ph=G("file-upload"),PE="/api/coze_claw/file/agent_upload",OE=6e4;async function gh(t,e={}){let i=`${Pr(Or(e.handshakeBase))}${PE}`,o=e.timeoutMs??OE,c=await RE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);ph.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),w=m.headers.get("x-tt-logid")??"";if(!m.ok){let E=await m.text().catch(()=>"");throw new A("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${w}: ${E.slice(0,200)}`)}let v=await m.json();if(v.code!==void 0&&v.code!==0)throw new A("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${w}`);let _=v.data?.file?.file_url;if(!_)throw new A("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(v).slice(0,200)}`);return ph.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(m){throw m instanceof A?m:m.name==="AbortError"?new A("UPLOAD_FAILED",`upload timeout (${o}ms) for ${DE(t.path)}`):new A("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}Ke();re();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 mh(t){let e=LE(t).toLowerCase();return NE[e]??"application/octet-stream"}Te();var No=G("agent-send"),wh=50*1024*1024;function bh(t,e,r){let i=t.get(e);if(!i)throw new A("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new A("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new A("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function Eh(t,e,r,i,o,c){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,h<2&&(No.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new A("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function vh(t,e){let{session:r,runtime:i}=bh(e.core,t.agentId,t.sessionId);if(!await di(t.path,r.workspace))throw new A("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await ME.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new A("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>wh)throw new A("FILE_TOO_LARGE",`${o.size} bytes > limit ${wh}`);let c=await mh(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new A("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??yh(t.path),u;try{u=await gh({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw No.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof A?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:_h(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(e,r,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),No.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Sh(t,e){let{session:r,runtime:i}=bh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new A("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??yh(t.path),c={sessionUpdate:"group_file",messageId:_h(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(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:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function Ih(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let d=r[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}Zt();re();dn();var Ft=G("coze-cli-installer"),Ah="@coze/cli@latest",BE="coze",kh="0.1.8",FE=5e3,zE=5e3,UE=9e4,Th=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),o=!1;if(i){let d=await GE(r);if(d===void 0)Ft.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Ih(d,kh))Ft.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:kh}),o=!0;else{Ft.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Mo=!0;return}}let c=o?"upgrade-only":"full";Ft.info("coze-cli install start",{package:Ah,mode:c});try{await r("npm",["i","-g","--prefer-online",Ah],{timeout:UE,maxBuffer:10*1024*1024}),Ft.info("coze-cli install ok")}catch(d){Ft.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Mo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:Th}),Ft.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Ft.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:Th}),Ft.info("coze auth login ok")}catch(d){Ft.warn("coze auth login failed",{err:String(d)});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 GE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:zE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}hn();Te();var qE=10*6e4;function Ch(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?qE:e}function Bo(t){return ln(t??Z().configFile)}function Xi(t,e){return fn(e??Z().configFile,t)}import{randomBytes as dv}from"node:crypto";dr();Ke();re();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 XE,join as YE,relative as QE,resolve as Rh,sep as ev}from"node:path";import{createInterface as tv}from"node:readline";var Ph=G("fs-rpc"),Yi=Xe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Oh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Yi)throw new A("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Yi} bytes`);let i=await Nh(t.path,e);return await WE(Td(i),{recursive:!0}),await JE(i,t.content,"utf8"),Ph.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Lh(t,e){let r=await Nh(t.path,e),i=await VE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Yi&&!o)throw new A("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Yi} bytes`);let c;if(o&&i.size>Yi)c=await nv(r,t.line??1,t.limit);else{let d=await KE(r,"utf8");if(o){let u=d.split(`
113
111
  `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
114
- `)}else c=l}return Dh.info("fs/read_text_file ok",{path:n,size:c.length}),{content:c}}async function LE(t,e,n){let i=OE({input:EE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof n=="number"?o+n:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let h of i)if(u>=o&&u<c&&l.push(h),u++,u>=c)break}finally{i.close()}return l.join(`
115
- `)}async function Nh(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([Ch(Ph(e)),Ch(Ph(t))]),o=CE(n,i);if(NE(o,DE,RE(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function NE(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Ch(t){let e=[],n=t;for(;n!==Ad(n);)try{let i=await IE(n);return e.length?PE(i,...e.reverse()):i}catch{e.push(TE(n)),n=Ad(n)}return t}ne();var Mh=K("prompt-multimodal"),Bh=10*1024*1024,ME=15e3,BE=6;async function Fh(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let c=n++,l=t[c];l!==void 0&&(e[c]=await FE(l))}}let o=Array.from({length:Math.min(BE,t.length)},()=>i());return await Promise.all(o),e}function zh(t){return t.some(e=>e.type==="image")}async function FE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Bi(e.uri))return t;try{let{buf:n,contentType:i}=await UE(e.uri),o=e.mimeType||zE(i)||"application/octet-stream";return Mh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:o}),{type:"image",data:n.toString("base64"),mimeType:o}}catch(n){return Mh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function zE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function UE(t){let e=new AbortController,n=setTimeout(()=>e.abort(),ME);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>Bh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Bh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Kt();Ve();ne();var V=K("core"),HE=3e4,qE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,jE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",KE="\u5BA1\u6279\u5DF2\u8D85\u65F6",WE=3e4,Uo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Br;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Rh(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),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 o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,l)=>{V.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:c,signal:l}),Zi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){V.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(An(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(l=>V.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.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(ko(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&qE.test(i)?this.currentCozeEnv=i:i&&V.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){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 c=await o(e,this);n!==null&&await this.upstream.send(Mr(n,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Mr(n,o));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Mr(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(o){V.error("handleFrame failed",{method:e.method,err:String(o)}),n!==null&&await this.upstream.send(An(n,$i(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,n);if(e.method==="session/prompt"){let h=o.sessions.get(c);if(h?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,m=wo(n._meta);return V.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,jE,x,m)}}let l=Date.now(),u=!1;try{let h=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,h}finally{V.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=Wf(i);switch(n){case"session/new":{let c=$E();return V.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return V.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,l=c.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Qt(e)?Kf(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: ${_d(e.framework)}`);let h=await this.ensureRuntime(e,l);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,l,h),!h.downstream||!h.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&h.permissionMode!==void 0&&h.permissionMode!==u){let v=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(_){throw h.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),_}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(h.acpSessionId,x):e.activeTriggers.delete(h.acpSessionId);let m=wo(i._meta);if(m?e.activeGroupIds.set(h.acpSessionId,m):e.activeGroupIds.delete(h.acpSessionId),m&&h.cozeGroupId!==m&&(h.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&zh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await Fh(c.prompt);try{let v=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:w});return h.lastActiveAt=Date.now(),v}catch(v){if(v instanceof k&&v.code==="AGENT_APPROVAL_TIMEOUT"){let _=h.pendingPermission;_&&(_.downstream.respondAgentRequest(_.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(_.upstreamId),h.pendingPermission=void 0);let E=h.acpSessionId,I=E?e.activeTriggers.get(E):void 0,A=E?e.activeGroupIds.get(E):void 0;return V.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,h,l,KE,I,A)}throw v}finally{if(e.activeTriggers.delete(h.acpSessionId),e.activeGroupIds.delete(h.acpSessionId),h.pendingPermission=void 0,h.reloadAfterTurn){h.reloadAfterTurn=!1;let v=h.downstream;v&&(h.downstream=void 0,V.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:h.acpSessionId}),v.stop("reload-after-turn").catch(_=>V.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(_)})))}else h.downstream?.isAlive()&&this.armIdleTimer(e,l,h)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let h=e.getSessionQueue(l);h.size>0&&(V.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:h.size}),h.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,l=c.sessionId,u=c.modeId,h=wo(i._meta);if(!l)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Qt(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: ${_d(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(l)??await this.ensureRuntime(e,l);if(x.permissionMode===u)return{};let m=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),w}else V.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: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[l,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(o.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:o.length});for(let l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,h=l.runtime.acpSessionId;u?.isAlive()&&h&&c.push({downstream:u,acpSessionId:h,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 h of o)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n){let i=e.sessions.get(n);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Qt(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?f0:h0:c.permissionMode=e.framework==="claude-code"?vd:xh),e.sessions.set(n,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,n){let i={sessionId:n,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(mt.GEN_MODEL_TOKEN,i,WE);if(!o?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return o.modelToken}catch(o){throw o instanceof k&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new k("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,n,i){if(Zi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let h;try{h=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&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 m=await h.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw 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),Qt(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(Zi(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 o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>V.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let l=e.activeTriggers.get(n.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(n.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Nr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,n,i,o,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Nr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>V.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,o=this.reverseSessionId(e,i);if(!o){V.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){V.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(ZE(n)){V.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=n.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Qt(e)){let m=l.currentModeId;Bt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(w=>V.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof m=="string"&&!Bt(e.framework,m)&&V.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Nr("session/update",{...n,sessionId:o,_meta:u})).catch(m=>V.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}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 o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},l=await Oh(c,o);n.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await Lh(c,o);n.respondAgentRequest(i.id,l)}}catch(o){V.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,$i(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let m=u?e.activeGroupIds.get(u):void 0;m&&(x.cozeGroupId=m);let 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:o});let _={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),V.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,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(Ki(o,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(o),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 o=n.value;this.clearPendingPermissionFor(o),e.error?(V.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&VE(e.result,o),V.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Ao(e.error)):i.value.resolve(e.result);return}V.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let o=e.get(n);if(o)return{value:o,key:n};if(typeof n=="number"){let c=String(n),l=e.get(c);if(l)return V.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:c}),{value:l,key:c}}}sendRequest(e,n,i=HE){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(Ki(o,e,n)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),l(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Qt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),n.set(i,c)}await di(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,o]of e.sessions.entries())if(o.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(An(e,{code:n,message:i,data:{bridgeVersion:Mt}}))}};function $E(){return GE(16).toString("hex")}function VE(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 c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&V.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var JE=["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."],Uh="Warning: ";function ZE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let o=i.text.startsWith(Uh)?i.text.slice(Uh.length):i.text;return JE.some(c=>o.startsWith(c))}jt();ne();Pe();import{randomBytes as YE}from"node:crypto";import{createServer as XE}from"node:http";var QE=1e6,Gh=K("ipc"),Go=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??Y()}async start(){this.token=YE(32).toString("hex");let e=XE((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),Gh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(o=>o?i(o):n())}),this.server=null)}async persistAuthFiles(){await ht(this.paths.portFile,String(this.port)),await ht(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){es(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){es(n,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await ev(e)}catch(u){es(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);es(n,200,u??{ok:!0})}catch(u){Gh.error("IPC handler failed",{key:o,err:String(u)}),es(n,500,{error:u instanceof Error?u.message:String(u)})}}};function es(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function ev(t){let e=[],n=0;for await(let o of t){let c=o;if(n+=c.length,n>QE)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 bS=qt(Bx(),1),ES=qt(Zo(),1),vS=qt(qr(),1),SS=qt(Bd(),1),IS=qt(Ud(),1),AS=qt(Wd(),1),Wx=qt(ea(),1),kS=qt(Kx(),1);var $x=Wx.default;Ve();ne();var{FWS:qS}=ip(),Oe=K("upstream.frontier"),op="application/json",ap="none",jS=15e3;function KS(t){class e extends $x{constructor(i){super(i,Xf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Oe.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(Nl("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");Oe.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){Oe.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ds=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Oe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Qf,...Sn(this.opts.ppeOverride)},n=KS(e),i=t0(this.opts.urlOverride),o={url:i,ws:n,fpID:Yf,aID:_o,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 qS(o),l=!1,u=null,h,x,m=new Promise((_,E)=>{h=_,x=E}),w=_=>{l||(l=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Oe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&w();for(let E of this.connectHandlers)Promise.resolve(E({initial:_})).catch(I=>Oe.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,Oe.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{Oe.warn("frontier error",{code:_.code,msg:_.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let v=this.opts.openTimeoutMs??jS;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await m}catch(_){try{c.close(1e3,"open failed")}catch(E){Oe.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){Oe.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Oe.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Oe.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;cp(c)||Oe.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:op,payloadEncoding:ap})}catch(u){throw Oe.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 n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Oe.debug("drop non-adapter frontier frame",{service:n});return}let i=VS(e);if(!i){Oe.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Oe.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(l){Oe.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;cp(c)||Oe.info("frontier frame in",{logid:$S(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:WS(i)}),Promise.resolve(this.handler(o)).catch(l=>Oe.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 WS(t){return t.length<=dp?t:`${t.slice(0,dp)}...<truncated, total ${t.length} chars>`}function $S(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function VS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Ve();ne();var Zd=K("skill-publish"),JS="/api/marketplace/product/skill/publish_with_assets",ZS=15e4;async function lp(t,e={}){let i=`${Cr(Dr(e.handshakeBase))}${JS}`,o=e.timeoutMs??ZS,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",...Sn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);Zd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...l,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:l,body:c,signal:u.signal}),m=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=${m}: ${_.slice(0,200)}`)}let w=await x.json();if(Zd.info("skill publish response",{logid:m,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=${m}`);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),Zd.info("skill publish ok",{logid:m,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ne();var Yd=K("upstream.switchable"),da=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Yd.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw Yd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>Yd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var Xd=K("upstream"),Jr=class{handler=null;async start(){Xd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Xd.info("NoopUpstream stopped",{reason:e})}async send(e){Xd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ve();ne();jt();ne();Pe();import{promises as YS}from"node:fs";var up=K("pat-token-store");async function la(t=Y()){try{let n=(await YS.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(up.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"&&up.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ls(t,e=Y()){if(!t)throw new Error("writePatToken: empty patToken");await ht(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as ua}from"node:fs";import{join as XS}from"node:path";function QS(t,e){return`#!/bin/sh
112
+ `)}else c=d}return Ph.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}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=o&&u<c&&d.push(h),u++,u>=c)break}finally{i.close()}return d.join(`
113
+ `)}async function Nh(t,e){if(typeof t!="string"||t.length===0)throw new A("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([Dh(Rh(e)),Dh(Rh(t))]),o=QE(r,i);if(rv(o,ev,XE(o)))throw new A("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 Dh(t){let e=[],r=t;for(;r!==Td(r);)try{let i=await $E(r);return e.length?YE(i,...e.reverse()):i}catch{e.push(ZE(r)),r=Td(r)}return t}re();var Mh=G("prompt-multimodal"),Bh=10*1024*1024,iv=15e3,sv=6;async function Fh(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,d=t[c];d!==void 0&&(e[c]=await ov(d))}}let o=Array.from({length:Math.min(sv,t.length)},()=>i());return await Promise.all(o),e}function zh(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),o=e.mimeType||av(i)||"application/octet-stream";return Mh.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:o}),{type:"image",data:r.toString("base64"),mimeType:o}}catch(r){return Mh.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 o=await i.arrayBuffer();if(o.byteLength>Bh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Bh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}xn();Ke();re();var W=G("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",hv="\u5BA1\u6279\u5DF2\u8D85\u65F6",xv=3e4,Fo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Br;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=Ch(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(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Gr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(Cn(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:X.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new A("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&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,c=Jf(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);c&&u!==c?(this.requestSceneBySession.set(d,c),W.info("cached request_scene for session",{sessionId:d,requestScene:c})):!c&&u!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let h=await u(e,this);r!==null&&await this.upstream.send(Mr(r,h));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Mr(r,u));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Mr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(u){W.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 A("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new A("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new A("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new A("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let h=o.sessions.get(c);if(h?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,m=go(r._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,fv,x,m)}}let d=Date.now(),u=!1;try{let h=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,h}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Xf(i);switch(r){case"session/new":{let c=pv();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Xt(e)?Zf(i._meta):void 0;if(u!==void 0&&!Bt(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${wd(e.framework)}`);let h=go(i._meta),x=this.requestSceneBySession.get(d),m=await this.ensureRuntime(e,d,h,x);if(u!==void 0&&m.permissionMode===void 0&&(m.permissionMode=u,await this.persistSessionMapping(e)),m.replySeq=0,await this.ensureDownstream(e,d,m),!m.downstream||!m.acpSessionId)throw new A("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&m.permissionMode!==void 0&&m.permissionMode!==u){let _=m.permissionMode;m.permissionMode=u,await this.persistSessionMapping(e);try{await m.downstream.setSessionMode({sessionId:m.acpSessionId,modeId:u})}catch(E){throw m.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),E}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(m.acpSessionId,w):e.activeTriggers.delete(m.acpSessionId),h?e.activeGroupIds.set(m.acpSessionId,h):e.activeGroupIds.delete(m.acpSessionId),h&&m.cozeGroupId!==h&&(m.cozeGroupId=h,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&zh(c.prompt))throw new A("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let v=await Fh(c.prompt);try{let _=await m.downstream.sessionPrompt({...c,sessionId:m.acpSessionId,prompt:v});return m.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof A&&_.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 S=m.acpSessionId,I=S?e.activeTriggers.get(S):void 0,k=S?e.activeGroupIds.get(S):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,m,d,hv,I,k)}throw _}finally{if(e.activeTriggers.delete(m.acpSessionId),e.activeGroupIds.delete(m.acpSessionId),m.pendingPermission=void 0,m.reloadAfterTurn){m.reloadAfterTurn=!1;let _=m.downstream;_&&(m.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:m.acpSessionId}),_.stop("reload-after-turn").catch(E=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(E)})))}else m.downstream?.isAlive()&&this.armIdleTimer(e,d,m)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new A("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,h=go(i._meta);if(!d)throw new A("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Xt(e))throw e.framework==="openclaw"?new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new A("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Bt(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${wd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let m=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),w}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new A("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&c.push({downstream:u,acpSessionId:h,oldMode:d.oldMode,runtime:d.runtime})}for(let d of c)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let h of o)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r,i,o){let c=e.sessions.get(r);if(c){let h=c.cozeGroupId!==i,x=e.deployType==="cloud"&&c.tokenGroupId!==i,m=c.requestScene!==o;if(x&&(c.modelToken=await this.requestSessionToken(e.agentId,r,i),c.tokenGeneratedAt=Date.now(),c.tokenGroupId=i),x||m){Gr(c);let w=c.downstream;c.downstream=void 0,w&&await w.stop("request-context-changed")}return c.cozeGroupId=i,c.requestScene=o,(h||x||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}:{},...o?{requestScene:o}:{}};return Xt(e)&&(u.permissionMode=e.framework==="claude-code"?Id:xh),e.sessions.set(r,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,r,i){let o={sessionId:r,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let c=await this.sendRequest(ht.GEN_MODEL_TOKEN,o,xv);if(!c?.modelToken)throw new A("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return c.modelToken}catch(c){throw c instanceof A&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new A("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 A("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new A("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let h;try{let x=this.requestSceneBySession.get(r);x&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:r,requestScene:x}),h=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=h,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let m=await h.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Xt(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Gr(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let d=e.activeTriggers.get(r.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Nr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Nr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(wv(r)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=r.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Xt(e)){let m=d.currentModeId;Bt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(w=>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)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Nr("session/update",{...r,sessionId:o,_meta:u})).catch(m=>W.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}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Oh(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Lh(c,o);r.respondAgentRequest(i.id,d)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Ki(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let m=u?e.activeGroupIds.get(u):void 0;m&&(x.cozeGroupId=m);let w=u?this.reverseSessionId(e,u):void 0,v=w?e.sessions.get(w):void 0;v&&(v.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,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(o,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),r.respondAgentRequestError(i.id,{code:X.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 o=r.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&gv(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Eo(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),d=e.get(c);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=lv){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(ji(o,e,r)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Xt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),o.tokenGroupId&&(c.tokenGroupId=o.tokenGroupId),o.requestScene&&(c.requestScene=o.requestScene),r.set(i,c)}await li(e.agentId,r,this.paths)}catch(r){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(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"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var 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."],Uh="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 o=i.text.startsWith(Uh)?i.text.slice(Uh.length):i.text;return mv.some(c=>o.startsWith(c))}hn();re();Te();import{randomBytes as _v}from"node:crypto";import{createServer as yv}from"node:http";var bv=1e6,Hh=G("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,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),Hh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(o=>o?i(o):r())}),this.server=null)}async persistAuthFiles(){await 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 o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Qi(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Ev(e)}catch(u){Qi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Qi(r,200,u??{ok:!0})}catch(u){Hh.error("IPC handler failed",{key:o,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 o of t){let c=o;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 GS=qt(Bx(),1),qS=qt(Vo(),1),jS=qt(Kr(),1),WS=qt(zd(),1),KS=qt(Gd(),1),$S=qt(Vd(),1),Kx=qt(Yo(),1),VS=qt(Wx(),1);var $x=Kx.default;Ke();re();var{FWS:l1}=ip(),De=G("upstream.frontier"),op="application/json",ap="none",u1=15e3;function f1(t){class e extends $x{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,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){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 d=Buffer.from(c.slice(0,128)).toString("hex");De.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){De.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}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),o={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(o),d=!1,u=null,h,x,m=new Promise((_,E)=>{h=_,x=E}),w=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;De.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(S=>De.warn("onConnect handler threw (ignored)",{err:String(S)}))},c.onclose=_=>{this.opened=!1,De.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{De.warn("frontier error",{code:_.code,msg:_.message}),w(new A("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let v=this.opts.openTimeoutMs??u1;u=setTimeout(()=>{w(new A("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await m}catch(_){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,_}}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 A("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 A("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;cp(c)||De.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{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 A("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){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 o;try{o=JSON.parse(i)}catch(d){De.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;cp(c)||De.info("frontier frame in",{logid:x1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:h1(i)}),Promise.resolve(this.handler(o)).catch(d=>De.warn("frontier frame handler threw",{err:String(d)}))}};function cp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var dp=2e3;function h1(t){return t.length<=dp?t:`${t.slice(0,dp)}...<truncated, total ${t.length} chars>`}function x1(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}}Ke();re();var Yd=G("skill-publish"),g1="/api/marketplace/product/skill/publish_with_assets",m1=15e4;async function lp(t,e={}){let i=`${Pr(Or(e.handshakeBase))}${g1}`,o=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 d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);Yd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),m=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new A("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${_.slice(0,200)}`)}let w=await x.json();if(Yd.info("skill publish response",{logid:m,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 A("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${m}`);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),Yd.info("skill publish ok",{logid:m,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof A?x:x.name==="AbortError"?new A("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new A("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}re();var Qd=G("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 o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw Qd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Qd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};re();var el=G("upstream"),Yr=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)}};Ke();re();hn();re();Te();import{promises as w1}from"node:fs";var up=G("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})}Te();Te();import{promises as da}from"node:fs";import{join as _1}from"node:path";function y1(t,e){return`#!/bin/sh
116
114
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
117
- `}function e1(t,e){return`@echo off\r
115
+ `}function b1(t,e){return`@echo off\r
118
116
  "${e}" "${t}" %*\r
119
- `}async function fp(t,e=Y()){let n=e.binDir;await ua.mkdir(n,{recursive:!0});let i=XS(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?e1(t,o):QS(t,o);return await ua.readFile(i,"utf8").catch(()=>null)===c||(await ua.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ua.chmod(i,493)),n}ne();Pe();import{execSync as hp}from"node:child_process";import{readFileSync as xp,unlinkSync as t1}from"node:fs";import{mkdir as n1,open as r1,readFile as pp,unlink as Qd,writeFile as i1}from"node:fs/promises";import{dirname as s1}from"node:path";var o1=K("single-instance"),a1=t=>new Promise(e=>setTimeout(e,t)),fa=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Y().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Vi(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&&o1.warn("removing stale pid file",{stalePid:i}),await i1(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 pp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Qd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await pp(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 n1(s1(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await r1(n,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(n);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await a1(this.claimLockIntervalMs);continue}await Qd(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Qd(n).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${n} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=xp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Fr)||n.includes("lib/index.js"))}catch{}try{let n=hp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Fr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=hp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{xp(this.pidFile,"utf8").trim()===String(this.selfPid)&&t1(this.pidFile)}catch{}})}};ha();ne();var nr=K("daemon.upstream-watchdog"),p1=12e4,m1=9e5,g1=3e4;function tl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var xa=class{constructor(e){this.opts=e;this.softMs=e.softMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",p1),this.hardMs=e.hardMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",m1),this.intervalMs=e.intervalMs??tl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",g1),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),nr.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&nr.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&nr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,nr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){nr.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,nr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>nr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var $=K("daemon");async function wp(){let t=Y();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ol({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Ue(P,t).logs,listAgentIds:()=>Ss(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
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"),o=process.execPath,c=process.platform==="win32"?b1(t,o):y1(t,o);return await da.readFile(i,"utf8").catch(()=>null)===c||(await da.writeFile(i,c,"utf8"),process.platform!=="win32"&&await da.chmod(i,493)),r}re();Te();import{execSync as hp}from"node:child_process";import{readFileSync as xp,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=G("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 o;try{o=await S1(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(r);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await T1(this.claimLockIntervalMs);continue}await tl(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.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=xp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Fr)||r.includes("lib/index.js"))}catch{}try{let r=hp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Fr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=hp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{xp(this.pidFile,"utf8").trim()===String(this.selfPid)&&E1(this.pidFile)}catch{}})}};ua();re();var ir=G("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 q=G("daemon");async function wp(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ml({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Fe(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
120
118
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
121
119
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
122
- `)}catch{}}let e=new fa({processTitle:Fr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await zo(),o=i??{};bs({pid:process.pid}),$.info(i?"loaded bridge config":"initialized bridge config");let c=new da(new Jr),l=null,u=new Uo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,H,W,te)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(P,H,W,te)}}),h=new Mo({paths:t,config:o,registry:u});l=h;let x,m,w=null,v={},_,E=null,I=null,A=null,T=new kn;function O(P,H){return T.enqueue(()=>D(P,H))}function b(){I||(I=new xa({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>A?O(A,{force:!0}):void 0,onFatal:P=>{if(process.env[us]==="1"){$.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}$.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function D(P,H){let W=P,te=W?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Ze=Gi(W.env),me=W.handshake_url,ge=W.frontier_url,Rt=gp(W.env,me,ge);if(A=W,!H?.force&&x===te&&m===Rt){let ye=await w1(t);return u.agents.size===0&&ye?($.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ma(t,h).catch(Te=>$.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):$.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let yt=!!x&&x!==te,on=m!==void 0&&m!==Rt,Ht=yt||on,an=await td({privatecode:te,...me?{endpoint:me}:{},ppeOverride:Ze});if(Ht){$.warn("connect config switched, resetting agents",{pcChanged:yt,envChanged:on,previousPc:x?pa(x):"",nextPc:pa(te)});for(let ye of[...u.agents.values()])await ye.dispose("connect config switch").catch(()=>{}),u.agents.delete(ye.agentId);u.disconnectedAgents.size>0&&($.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"connect switch").catch(()=>{})}w=an.deviceId,bs({deviceId:w,pid:process.pid}),Id({patToken:te,env:W.env}).catch(ye=>$.warn("coze-cli setup error (ignored)",{err:String(ye)}));let ei=new ds({handshake:an,privatecode:te,...ge?{urlOverride:ge}:{},ppeOverride:Ze,getPatTokenForAgent:ye=>u.agents.get(ye)?.patToken});return await c.swap(ei,"connect"),x=te,m=Rt,v=Ze,_=me,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),$.info("mock scenario set",{scenario:W.mock_scenario})),E||(E=new ji({core:u,getDeviceId:()=>w??"",onTickEnd:()=>U.retryPending().catch(ye=>$.warn("detailSync.retryPending failed (ignored)",{err:String(ye)})),onAuthFailures:Z})),E.start(),b(),Ht&&ma(t,h).catch(ye=>$.warn("post-connect-switch auto-revive error (ignored)",{err:String(ye)})),ls(te,t).catch(ye=>$.warn("writePatToken after /connect failed (ignored)",{err:String(ye)})),$.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>h.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let L={},G=new vo({agents:u.agents,paths:t,publishSkillToMarketplace:async P=>{let H=u.agents.get(P.agentId)?.patToken??x;if(!H)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return lp({patToken:H,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:_,ppeOverride:v})},disposeAndMarkDisconnected:async(P,H)=>{let W=u.agents.get(P);if(W){await h.cleanupOpenclawSessionProviders(W).catch(Ze=>$.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Ze)})),W.framework==="hermes"&&W.deployType==="cloud"&&await cd(P,t).catch(Ze=>$.warn("cleanup hermes-home failed (ignored)",{agentId:P,err:String(Ze)}));let te=!0;try{await W.dispose(`disconnect: ${H}`)}catch(Ze){te=!1,$.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Ze)}),W.status="error"}te&&(W.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,H)=>{let W=u.agents.get(P);W&&(await h.cleanupOpenclawSessionProviders(W).catch(te=>$.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(te)})),W.framework==="hermes"&&W.deployType==="cloud"&&await cd(P,t).catch(te=>$.warn("cleanup hermes-home during delete failed (ignored)",{agentId:P,err:String(te)})),await W.dispose(`delete: ${H}`).catch(te=>$.warn("dispose during delete failed (ignored)",{agentId:P,err:String(te)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!L.ref)throw new Error("agent-detail-sync not initialized yet");await L.ref.syncOne(P)},cleanupOpenclawProviders:async(P,H)=>{await h.cleanupOpenclawSessionProviders(P,H)},openclawRepair:async(P,H)=>{await h.openclawRepair(P,H)},hermesReset:async(P,H)=>{let W=await Se(P).catch(()=>null);!W||W.framework!=="hermes"||W.deployType!=="cloud"||await x0({paths:t,agentId:P,model:W.model,modelInfo:W.modelInfo,cozeEnv:H,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>G.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>G.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>G.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>G.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>G.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>G.getFileContent(P.params)),u.registerExtension("_agent/update",P=>G.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>G.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>G.switchModel(P.params)),u.registerExtension("_agent/reset",P=>G.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>G.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>G.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>G.upgradeBridge(P.params));let U=new ks({paths:t,handlers:G,agentManager:h,sendDetail:P=>u.sendRequest("_agent/detail",P)});L.ref=U;let Z=async P=>{await Promise.allSettled(P.map(async H=>{try{await G.disconnectAgent({agentId:H.agentId,reason:`auth_failure: code=${H.code} ${H.message}`}),$.info("agent disconnected due to auth failure from heartbeat response",{agentId:H.agentId,code:H.code,message:H.message})}catch(W){$.warn("disconnect during authFailure handling failed (ignored)",{agentId:H.agentId,err:String(W)})}}))};c.onConnect(({initial:P})=>{$.info("frontier upstream connected, triggering detail sync",{initial:P}),U.syncAll(P?"initial-connect":"reconnect").catch(H=>$.warn("detail sync top-level error (ignored)",{err:String(H)}))});let J=new Go({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[us]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let H=P,W=H?.privatecode,te=H?.pairing_code;if(!W||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ze=Gi(H.env),me=H.handshake_url,ge=H.frontier_url,Rt=gp(H.env,me,ge),yt=!!x&&x!==W,on=m!==void 0&&m!==Rt,Ht=yt||on,an=await td({privatecode:W,...me?{endpoint:me}:{},ppeOverride:Ze});if(Ht){$.warn("pair config switched, resetting agents",{pcChanged:yt,envChanged:on,previousPc:x?pa(x):"",nextPc:pa(W),previousEnvKey:m??"",nextEnvKey:Rt});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.agentId);u.disconnectedAgents.size>0&&($.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"pair switch").catch(()=>{})}w=an.deviceId,bs({deviceId:w,pid:process.pid}),Id({patToken:W,env:H.env}).catch(Te=>$.warn("coze-cli setup error (ignored)",{err:String(Te)}));let ei=new ds({handshake:an,privatecode:W,...ge?{urlOverride:ge}:{},ppeOverride:Ze,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(ei,"pair");try{let Te=new Zn;o.frameworksCache=await Te.detectAll(),await Xi(o),$.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){$.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let ye=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:te,patToken:W,frameworks:ye,_meta:{cozeDeviceId:w}});$.info("_agent/pair ok",{pairResult:Te}),x=W,m=Rt,v=Ze,_=me,H.mock_scenario!==void 0&&(u.setMockScenario(H.mock_scenario),$.info("mock scenario set",{scenario:H.mock_scenario})),ls(W,t).catch(Ne=>$.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),E||(E=new ji({core:u,getDeviceId:()=>w??"",onTickEnd:()=>U.retryPending().catch(Ne=>$.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:Z})),E.start(),b(),Ht&&ma(t,h).catch(Ne=>$.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let rr;return H.agent_id&&(rr=await y1(H.agent_id,t,h,Ne=>u.sendRequest("_agent/detail",Ne),W).catch(Ne=>($.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(Ne)}),{ok:!1,agentId:H.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(Te){return $.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:P=>O(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let H=P;return{ok:!0,result:await h.createAgent(H)}}},{method:"POST",path:"/agent/send",handler:async P=>{let H=P;if(!H?.agentId||!H?.sessionId||!H?.kind||!H?.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=H;return await(W.groupFile?Sh:vh)(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 P=>{let H=P?.agent_id,W=await u.reloadAgents(H);return $.info("IPC /reload: recycled agent subprocesses",{agentId:H??"(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:ie,token:Q}=await J.start();try{await fp(t.libEntry,t)}catch(P){$.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),b1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Zn().detectAll(),await Xi(o),o.frameworksCache)}).catch(P=>$.warn("startup warmup error (ignored)",{err:String(P)})),ql().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(ln(),Gl));for(let H of["claude-code","codex"]){let W=await P(H);W&&$.info("acp wrapper version",{framework:H,version:W})}}).catch(P=>$.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let ce=null,de={port:ie,token:Q,core:u,ipc:J,shutdown(P){return ce||($.info("daemon shutdown",{reason:P}),ce=(async()=>{E?.stop(),I?.stop(),await u.stop(P),await J.stop(),await e.release()})(),ce)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{de.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>H0()),process.on("unhandledRejection",P=>{$.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{$.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}
123
- `)}catch{}process.exit(1)}),$.info("daemon ready",{port:ie,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),v1({cliSpawned:process.env[us]==="1",readPatToken:()=>la(t),connect:O}).catch(P=>$.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),de}async function w1(t){return Ss(t).length>0}function pa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function gp(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function _1(t,e){let n=Ss(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(Kt(),As));for(let c of n){await o(c,t).catch(l=>$.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),$.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),$.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){$.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function y1(t,e,n,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Kt(),As)),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`);$.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}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await n.createAgent(w),{ok:!0,agentId:t,note:l.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}:{},...o?{patToken:o}:{},...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 b1(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 _1(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await ma(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await E1(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function ma(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(Kt(),As));$.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let h;try{h=await o(u,t)}catch(x){$.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!h){l+=1;continue}if(h.deletedAt){$.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),l+=1;continue}if(h.disconnectedAt){$.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),l+=1;continue}try{$.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=_p(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){$.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),l+=1}}return $.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function E1(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let o of n)try{(await P0(o,t)).status==="refreshed"&&(i+=1)}catch(c){$.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&$.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function v1(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 _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}ha();Pe();import{readFile as yp}from"node:fs/promises";var sn=class{paths;constructor(e){this.paths=e??Y()}async probe(e=1e3){let n=await ga(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:I1(i)}}}async request(e){let n=await ga(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,l=setTimeout(()=>c.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:o,body:i?JSON.stringify(n.body):void 0,signal:c.signal}),h=await u.text();return{status:u.status,body:S1(h)}}finally{clearTimeout(l)}}};async function ga(t){try{let[e,n]=await Promise.all([yp(t.portFile,"utf8"),yp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=n.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function S1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function I1(t){return t instanceof Error?t.message:String(t)}Xt();ne();ar();import{spawn as A1}from"node:child_process";import{userInfo as Ep}from"node:os";var nl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",k1=new Set(["bash","zsh","sh","dash","ksh"]),bp=Xe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),T1=2e3;function R1(t,e=nl){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let o=t.slice(n+e.length,i),c={};for(let l of o.split(`
124
- `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function P1(){let t=(process.env.SHELL??"").trim()||(Ep().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return k1.has(e)?t:null}function C1(t){return new Promise(e=>{let n=`printf '%s' '${nl}'; env; printf '%s' '${nl}'`,i;try{i=A1(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Ep().homedir}})}catch{e(null);return}let o="",c=!1,l=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(h),clearTimeout(x),e(m))};i.stdout?.on("data",m=>{o+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let h=setTimeout(()=>l("SIGTERM"),bp),x=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},bp+T1)})}async function rl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=P1();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??C1)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=R1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Pe();function Pn(t,...e){let n=[],i;for(let o=0;o<t.length;o++){let c=t[o],l=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||n.push(c)}return{value:i,rest:n}}ln();import{chmod as D1,copyFile as vp,mkdir as Ip,readFile as hs,rename as Sp,rm as ol,stat as Ap,writeFile as O1}from"node:fs/promises";import{homedir as pO}from"node:os";import{dirname as L1,join as Le,resolve as al,sep as fs}from"node:path";import{fileURLToPath as N1}from"node:url";Xt();ne();Pe();function Zr(t,e,n,i){st(t.bridgeLogsDir,e,"dist-install",n,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 M1(){return{darwin:{arm64:Le("vendor","aarch64-apple-darwin","bin","codex"),x64:Le("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Le("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Le("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Le("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Le("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function B1(t){let e=N1(t),n=L1(e),i=`${fs}src${fs}`;if(n.includes(i)||n.endsWith(`${fs}src${fs}cli`))return null;let o=al(n,"index.js"),c=al(n,"..","package.json");return{dist:o,pkgJson:c}}async function cl(t={}){let e=t.paths??Y(),n=B1(import.meta.url),i=t.sourceDist??n?.dist,o=t.sourcePackageJson??n?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,l;try{let E=JSON.parse(await hs(o,"utf8"));c=E.version??"unknown",l=E.dependencies??{}}catch(E){throw Zr(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=Es.map(E=>({name:E,spec:l[E]??"latest"})),h=u.map(({name:E,spec:I})=>`${E}@${I}`),x=await zo(e.configFile)??{},m=x.libVersion,w=await hs(e.libEntry).then(()=>!0).catch(()=>!1),v=m===c,_=await Tp(e,u);if(v&&w&&_)return{kind:"already-current",libVersion:c};if(!v||!w){await Ip(e.libDir,{recursive:!0}),await vp(i,e.libEntry),await vp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=al(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
125
- `;await hs(E,"utf8").catch(()=>null)!==I&&await O1(E,I)}return _||(t.installWrappers?await t.installWrappers(e,h):await U1(e,h,u)),x.libVersion=c,await Xi(x,e.configFile),Zr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),v&&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 n of e){let i=Le(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await hs(i,"utf8"))}catch(l){return Zr(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(l)}),!1}let c=o.version;if(!c)return Zr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!F1(c,n.spec))return Zr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:c,expected:n.spec}),!1}return!!await Rp(Le(t.libDir,"node_modules"))}function F1(t,e){let n=il(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=il(i.slice(1));if(!c)return!0;if(sl(n,c)<0)return!1;let l=z1(c);return sl(n,l)<0}let o=il(i);return o?sl(n,o)===0:!0}function z1(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function il(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function sl(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 U1(t,e,n){await q1(t.installLock,async()=>{if(await Tp(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${fs}.staging-${process.pid}-${i}`,c=Le(o,"node_modules"),l=Le(t.libDir,"node_modules");try{await Ip(o,{recursive:!0}),await G1(e,o),await H1(c);let u=`${l}.trash-${i}`;await Sp(l,u).catch(()=>{}),await Sp(c,l),await ol(u,{recursive:!0,force:!0}).catch(()=>{}),Zr(t,"info","wrapper closure installed",{liveNm:l,specs:e})}finally{await ol(o,{recursive:!0,force:!0}).catch(()=>{})}})}function G1(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=at("npm",n,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",h=>{l.length<8192&&(l+=h.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",h=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(h)}`))}),c.once("close",h=>{clearTimeout(u),h===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${l.trim().slice(0,2e3)}`))})})}async function H1(t){for(let e of Es){let n=Le(t,...e.split("/")),i=JSON.parse(await hs(Le(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=Le(t,".bin",o),l=await Ap(c);process.platform!=="win32"&&!(l.mode&73)&&await D1(c,l.mode|73).catch(()=>{})}if(!await Rp(t)){let e=kp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Rp(t){let e=kp(),n=M1();if(!e||!n)return!0;let i=Le(t,"@openai","codex"),o=Le(t,...e.split("/")),c=[Le(i,"package.json"),Le(i,"bin","codex.js"),Le(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Le(o,"package.json"),Le(o,n)];return(await Promise.all(c.map(u=>Ap(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function q1(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await ol(t,{force:!0}).catch(()=>{})}}za();ne();Pe();import{closeSync as Cp,fstatSync as Dp,openSync as Op,readFileSync as j1,readSync as K1,readdirSync as W1,statSync as $1}from"node:fs";import{join as wa}from"node:path";var V1=new Set(["debug","info","warn","error"]);function Lp(t){let e=t,n=Pn(e,"--agent-id");e=n.rest;let i=Pn(e,"--date");e=i.rest;let o=Pn(e,"-n","--lines");e=o.rest;let c=Pn(e,"--level");e=c.rest;let l=Pn(e,"--grep");e=l.rest;let u=o.value===void 0?200:Number(o.value),h=Number.isInteger(u)&&u>=0?u:200,x=c.value&&V1.has(c.value)?c.value:void 0,m={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(m.agentId=n.value),i.value&&(m.date=i.value),x&&(m.level=x),l.value&&(m.grep=l.value),m}function J1(t,e){return t.agentId?wa(Ue(t.agentId,e).logs,cr("agent",t.date)):wa(e.bridgeLogsDir,cr("bridge",t.date))}function Z1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function Y1(t,e){let n;try{n=W1(t)}catch{return[]}let i=[];for(let o of n){let c=Fa(o,e);if(!c)continue;let l=0;try{l=$1(wa(t,o)).size}catch{}i.push({file:wa(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Np(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"&&!Ml(n,e.level))return!1}return!0}var Pp={debug:"90",info:"36",warn:"33",error:"31"},X1=new Set(["ts","level","module","msg"]);function Q1(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 n;try{n=JSON.parse(t)}catch{return t}let i=Q1(n.ts),o=typeof n.level=="string"?n.level:"",c=o.toUpperCase().padEnd(5);e.color&&Pp[o]&&(c=`\x1B[${Pp[o]}m${c}\x1B[0m`);let l=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",h=Object.entries(n).filter(([x])=>!X1.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${l} ${u}${h}`}function eI(t,e,n){let c=j1(t,"utf8").split(`
126
- `).filter(l=>l.length>0).filter(l=>Np(l,{level:e.level,grep:e.grep}));for(let l of Z1(c,e.lines))process.stdout.write(`${Mp(l,{raw:e.raw,color:n})}
127
- `)}async function Bp(t,e){let n=e.paths??Y(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Ue(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=Y1(l,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
120
+ `)}catch{}}let e=new la({processTitle:Fr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Bo(),o=i??{};ws({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new aa(new Yr),d=null,u=new Fo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,U,j,ne,Ve,le)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,U,j,ne,Ve,le)}}),h=new Lo({paths:t,config:o,registry:u});d=h;let x,m,w=null,v={},_,E=null,S=null,I=null,k=new Rn;function R(P,U){return k.enqueue(()=>D(P,U))}function b(){S||(S=new fa({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>I?R(I,{force:!0}):void 0,onFatal:P=>{if(process.env[ls]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),S.start()}async function D(P,U){let j=P,ne=j?.privatecode;if(!ne)throw new A("IPC_BAD_REQUEST","/connect requires privatecode");let Ve=Hi(j.env),le=j.handshake_url,pe=j.frontier_url,At=mp(j.env,le,pe);if(I=j,!U?.force&&x===ne&&m===At){let we=await z1(t);return u.agents.size===0&&we?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),xa(t,h).catch(Ae=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Ae)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let gt=!!x&&x!==ne,sn=m!==void 0&&m!==At,Gt=gt||sn,on=await Qc({privatecode:ne,...le?{endpoint:le}:{},ppeOverride:Ve});if(Gt){q.warn("connect config switched, resetting agents",{pcChanged:gt,envChanged:sn,previousPc:x?ha(x):"",nextPc:ha(ne)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Yr,"connect switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),kd({patToken:ne,env:j.env}).catch(we=>q.warn("coze-cli setup error (ignored)",{err:String(we)}));let ri=new cs({handshake:on,privatecode:ne,...pe?{urlOverride:pe}:{},ppeOverride:Ve,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await c.swap(ri,"connect"),x=ne,m=At,v=Ve,_=le,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),q.info("mock scenario set",{scenario:j.mock_scenario})),E||(E=new qi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(we=>q.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:V})),E.start(),b(),Gt&&xa(t,h).catch(we=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),ds(ne,t).catch(we=>q.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),q.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>h.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new _o({agents:u.agents,publishSkillToMarketplace:async P=>{let U=u.agents.get(P.agentId)?.patToken??x;if(!U)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return lp({patToken:U,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:_,ppeOverride:v})},disposeAndMarkDisconnected:async(P,U)=>{let j=u.agents.get(P);if(j){await h.cleanupOpenclawSessionProviders(j).catch(Ve=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Ve)}));let ne=!0;try{await j.dispose(`disconnect: ${U}`)}catch(Ve){ne=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Ve)}),j.status="error"}ne&&(j.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,U)=>{let j=u.agents.get(P);j&&(await h.cleanupOpenclawSessionProviders(j).catch(ne=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(ne)})),await j.dispose(`delete: ${U}`).catch(ne=>q.warn("dispose during delete failed (ignored)",{agentId:P,err:String(ne)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(P)},cleanupOpenclawProviders:async(P,U)=>{await h.cleanupOpenclawSessionProviders(P,U)},openclawRepair:async(P,U)=>{await h.openclawRepair(P,U)},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 M=new Is({paths:t,handlers:F,agentManager:h,sendDetail:P=>u.sendRequest("_agent/detail",P)});O.ref=M;let V=async P=>{await Promise.allSettled(P.map(async U=>{try{await F.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(j){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(j)})}}))};c.onConnect(({initial:P})=>{q.info("frontier upstream connected, triggering detail sync",{initial:P}),M.syncAll(P?"initial-connect":"reconnect").catch(U=>q.warn("detail sync top-level error (ignored)",{err:String(U)}))});let K=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:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let U=P,j=U?.privatecode,ne=U?.pairing_code;if(!j||!ne)throw new A("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ve=Hi(U.env),le=U.handshake_url,pe=U.frontier_url,At=mp(U.env,le,pe),gt=!!x&&x!==j,sn=m!==void 0&&m!==At,Gt=gt||sn,on=await Qc({privatecode:j,...le?{endpoint:le}:{},ppeOverride:Ve});if(Gt){q.warn("pair config switched, resetting agents",{pcChanged:gt,envChanged:sn,previousPc:x?ha(x):"",nextPc:ha(j),previousEnvKey:m??"",nextEnvKey:At});for(let Ae of[...u.agents.values()])await Ae.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ae.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Yr,"pair switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),kd({patToken:j,env:U.env}).catch(Ae=>q.warn("coze-cli setup error (ignored)",{err:String(Ae)}));let ri=new cs({handshake:on,privatecode:j,...pe?{urlOverride:pe}:{},ppeOverride:Ve,getPatTokenForAgent:Ae=>u.agents.get(Ae)?.patToken});await c.swap(ri,"pair");try{let Ae=new Xn;o.frameworksCache=await Ae.detectAll(),await Xi(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ae){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ae)})}let we=Object.keys(o.frameworksCache??{});try{let Ae=await u.sendRequest("_agent/pair",{pairCode:ne,patToken:j,frameworks:we,_meta:{cozeDeviceId:w}});q.info("_agent/pair ok",{pairResult:Ae}),x=j,m=At,v=Ve,_=le,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),q.info("mock scenario set",{scenario:U.mock_scenario})),ds(j,t).catch(Oe=>q.warn("writePatToken after /pair failed (ignored)",{err:String(Oe)})),E||(E=new qi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(Oe=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Oe)})),onAuthFailures:V})),E.start(),b(),Gt&&xa(t,h).catch(Oe=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(Oe)}));let sr;return U.agent_id&&(sr=await H1(U.agent_id,t,h,Oe=>u.sendRequest("_agent/detail",Oe),j).catch(Oe=>(q.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Oe)}),{ok:!1,agentId:U.agent_id??"",note:String(Oe)}))),{ok:!0,note:"paired with cloud",...sr?{agent:sr}:{}}}catch(Ae){return q.error("_agent/pair failed",{err:String(Ae)}),{ok:!1,note:`pair failed: ${String(Ae)}`}}}},{method:"POST",path:"/connect",handler:P=>R(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let U=P;return{ok:!0,result:await h.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async P=>{let U=P;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new A("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=U;return await(j.groupFile?Sh:vh)(j,{core:u,patToken:x,handshakeBase:_,ppeOverride:v})}catch(j){if(j instanceof A)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async P=>{let U=P?.agent_id,j=await u.reloadAgents(U);return q.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ie,token:Y}=await K.start();try{await fp(t.libEntry,t)}catch(P){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),G1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Xn().detectAll(),await Xi(o),o.frameworksCache)}).catch(P=>q.warn("startup warmup error (ignored)",{err:String(P)})),Kl().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(dn(),jl));for(let U of["claude-code","codex"]){let j=await P(U);j&&q.info("acp wrapper version",{framework:U,version:j})}}).catch(P=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let te=null,oe={port:ie,token:Y,core:u,ipc:K,shutdown(P){return te||(q.info("daemon shutdown",{reason:P}),te=(async()=>{E?.stop(),S?.stop(),await u.stop(P),await K.stop(),await e.release()})(),te)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{oe.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>H0()),process.on("unhandledRejection",P=>{q.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{q.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)}),q.info("daemon ready",{port:ie,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),j1({cliSpawned:process.env[ls]==="1",readPatToken:()=>ca(t),connect:R}).catch(P=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),oe}async function z1(t){return Es(t).length>0}function ha(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:o}=await Promise.resolve().then(()=>(xn(),Ss));for(let c of r){await o(c,t).catch(d=>q.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),q.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),q.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){q.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function H1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(xn(),Ss)),d=await c(t,e);if(d){if(d.deletedAt)throw new A("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let m=_p(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await r.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}q.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new A("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(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 G1(t){let e=t.logger??q;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 xa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await q1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function xa(t,e){let{readdir:r}=await import("node:fs/promises"),i;try{i=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(xn(),Ss));q.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let h;try{h=await o(u,t)}catch(x){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=_p(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return q.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function q1(t){let{readdir:e}=await import("node:fs/promises"),r;try{r=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(r.length===0)return{refreshed:0,total:0};let i=0;for(let o of r)try{(await C0(o,t)).status==="refreshed"&&(i+=1)}catch(c){q.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&q.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??q;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();Te();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,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),h=await u.text();return{status:u.status,body:W1(h)}}finally{clearTimeout(d)}}};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),o=r.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function 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();re();dr();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=Xe("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 o=t.slice(r+e.length,i),c={};for(let d of o.split(`
122
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function X1(){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 Y1(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 o="",c=!1,d=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(h),clearTimeout(x),e(m))};i.stdout?.on("data",m=>{o+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let h=setTimeout(()=>d("SIGTERM"),bp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},bp+J1)})}async function sl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=X1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??Y1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=Z1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Te();function On(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||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 g3}from"node:os";import{dirname as tI,join as Pe,resolve as dl,sep as us}from"node:path";import{fileURLToPath as nI}from"node:url";Zt();re();Te();function Qr(t,e,r,i){rt(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:Pe("vendor","aarch64-apple-darwin","bin","codex"),x64:Pe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Pe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Pe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Pe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Pe("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 o=dl(r,"index.js"),c=dl(r,"..","package.json");return{dist:o,pkgJson:c}}async function ll(t={}){let e=t.paths??Z(),r=iI(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let E=JSON.parse(await fs(o,"utf8"));c=E.version??"unknown",d=E.dependencies??{}}catch(E){throw Qr(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:d[E]??"latest"})),h=u.map(({name:E,spec:S})=>`${E}@${S}`),x=await Bo(e.configFile)??{},m=x.libVersion,w=await fs(e.libEntry).then(()=>!0).catch(()=>!1),v=m===c,_=await Tp(e,u);if(v&&w&&_)return{kind:"already-current",libVersion:c};if(!v||!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"),S=`${JSON.stringify({type:"module"},null,2)}
123
+ `;await fs(E,"utf8").catch(()=>null)!==S&&await eI(E,S)}return _||(t.installWrappers?await t.installWrappers(e,h):await aI(e,h,u)),x.libVersion=c,await Xi(x,e.configFile),Qr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),v&&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=Pe(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await fs(i,"utf8"))}catch(d){return Qr(t,"debug","wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(d)}),!1}let c=o.version;if(!c)return Qr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!sI(c,r.spec))return Qr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await Cp(Pe(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 d=oI(c);return al(r,d)<0}let o=ol(i);return o?al(r,o)===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),o=`${t.libDir}${us}.staging-${process.pid}-${i}`,c=Pe(o,"node_modules"),d=Pe(t.libDir,"node_modules");try{await Ip(o,{recursive:!0}),await cI(e,o),await dI(c);let u=`${d}.trash-${i}`;await Sp(d,u).catch(()=>{}),await Sp(c,d),await cl(u,{recursive:!0,force:!0}).catch(()=>{}),Qr(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await cl(o,{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,o)=>{let c=st("npm",r,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",h=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(h)}`))}),c.once("close",h=>{clearTimeout(u),h===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function dI(t){for(let e of ys){let r=Pe(t,...e.split("/")),i=JSON.parse(await fs(Pe(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=Pe(t,".bin",o),d=await Ap(c);process.platform!=="win32"&&!(d.mode&73)&&await Q1(c,d.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=Pe(t,"@openai","codex"),o=Pe(t,...e.split("/")),c=[Pe(i,"package.json"),Pe(i,"bin","codex.js"),Pe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Pe(o,"package.json"),Pe(o,r)];return(await Promise.all(c.map(u=>Ap(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function lI(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await cl(t,{force:!0}).catch(()=>{})}}Ba();re();Te();import{closeSync as Dp,fstatSync as Pp,openSync as Op,readFileSync as uI,readSync as fI,readdirSync as hI,statSync as xI}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 o=On(e,"-n","--lines");e=o.rest;let c=On(e,"--level");e=c.rest;let d=On(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),h=Number.isInteger(u)&&u>=0?u:200,x=c.value&&pI.has(c.value)?c.value:void 0,m={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(m.agentId=r.value),i.value&&(m.date=i.value),x&&(m.level=x),d.value&&(m.grep=d.value),m}function gI(t,e){return t.agentId?ga(Fe(t.agentId,e).logs,lr("agent",t.date)):ga(e.bridgeLogsDir,lr("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=hI(t)}catch{return[]}let i=[];for(let o of r){let c=Ma(o,e);if(!c)continue;let d=0;try{d=xI(ga(t,o)).size}catch{}i.push({file:ga(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.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),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Rp[o]&&(c=`\x1B[${Rp[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",h=Object.entries(r).filter(([x])=>!_I.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function bI(t,e,r){let c=uI(t,"utf8").split(`
124
+ `).filter(d=>d.length>0).filter(d=>Np(d,{level:e.level,grep:e.grep}));for(let d of mI(c,e.lines))process.stdout.write(`${Mp(d,{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 d=t.agentId?Fe(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=wI(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
128
126
  `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
129
- `);return 0}let o=t.date??Dn(new Date),c=J1({agentId:t.agentId,date:o},n);try{eI(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
127
+ `);return 0}let o=t.date??Nn(new Date),c=gI({agentId:t.agentId,date:o},r);try{bI(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
130
128
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
131
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
132
- `),1}return t.follow&&await rI(c,t,i),0}var tI=500;function nI(t){try{let e=Op(t,"r");try{return Dp(e).size}finally{Cp(e)}}catch{return 0}}async function rI(t,e,n){let i=nI(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let h=Op(t,"r");try{let x=Dp(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),w=K1(h,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{Cp(h)}}catch{}if(u){let h=(o+u).split(`
133
- `);o=h.pop()??"";for(let x of h)x.length>0&&Np(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Mp(x,{raw:e.raw,color:n})}
134
- `)}await new Promise(h=>setTimeout(h,tI))}}finally{process.off("SIGINT",l)}}import{basename as iI,resolve as sI}from"node:path";Pe();var oI=9e4,aI={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 aI[t]??1}async function Fp(t,e={}){let n=e.paths??Y();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
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 Pp(e).size}finally{Dp(e)}}catch{return 0}}async function SI(t,e,r){let i=vI(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=Op(t,"r");try{let x=Pp(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),w=fI(h,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{Dp(h)}}catch{}if(u){let h=(o+u).split(`
131
+ `);o=h.pop()??"";for(let x of h)x.length>0&&Np(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Mp(x,{raw:e.raw,color:r})}
132
+ `)}await new Promise(h=>setTimeout(h,EI))}}finally{process.off("SIGINT",d)}}import{basename as II,resolve as AI}from"node:path";Te();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>
135
133
  `),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.
136
- `),3;let i=await ga(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.
137
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:sI(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 dI(i,"/agent/send",o,oI)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
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 o={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",o,kI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
138
136
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
139
- `),cI(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
140
- `);else{let l=t.name??iI(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
141
- `)}else process.stdout.write(`Sent ${t.kind} ${l} (${lI(c.bytes)})
142
- `)}return 0}async function dI(t,e,n,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:o.signal}),u=await l.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=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function lI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Vp=K("cli");function $e(t,e){let{value:n,rest:i}=Pn(t,e);return{value:n,rest:i}}function Sa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
143
- `)}function LI(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}=$e(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 NI(e.slice(1));if(e[0]==="log")return{mode:"log",...Lp(e.slice(1))};if(e[0]==="connect")return MI(e.slice(1));if(e.includes("--status"))return Sa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Sa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Sa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Sa("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:o}=$e(n,"--pat-token");n=o;let{value:c,rest:l}=$e(n,"--pair-code");n=l;let{value:u,rest:h}=$e(n,"--env");n=h;let{value:x,rest:m}=$e(n,"--handshake-url");n=m;let{value:w,rest:v}=$e(n,"--frontier-url");n=v;let{value:_,rest:E}=$e(n,"--mock-scenario");n=E;let{value:I}=$e(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:c};return u&&(T.env=u),x&&(T.handshakeUrl=x),w&&(T.frontierUrl=w),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function NI(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=$e(i,"--caption");i=c;let{value:l,rest:u}=$e(i,"--name");i=u;let{value:h,rest:x}=$e(i,"--agent-id");i=x;let{value:m,rest:w}=$e(i,"--session-id");i=w;let{value:v,rest:_}=$e(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 o&&(A.caption=o),l&&(A.name=l),h&&(A.agentId=h),m&&(A.sessionId=m),E&&(A.groupFile=!0),v&&(A.mimeType=v),A}function MI(t){let e=t,{value:n,rest:i}=$e(e,"--pat-token");e=i;let{value:o,rest:c}=$e(e,"--env");e=c;let{value:l,rest:u}=$e(e,"--handshake-url");e=u;let{value:h,rest:x}=$e(e,"--frontier-url");e=x;let{value:m,rest:w}=$e(e,"--mock-scenario");e=w;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),l&&(_.handshakeUrl=l),h&&(_.frontierUrl=h),m&&(_.mockScenario=m),v&&(_.skipRebuildEnv=!0),_}var BI=`
137
+ `),CI(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
138
+ `);else{let d=t.name??II(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
139
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${DI(c.bytes)})
140
+ `)}return 0}async function RI(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function DI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Vp=G("cli");function We(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 tA(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:R}=We(e.slice(1),"--agent-id");return R?{mode:"reload",agentId:R}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return nA(e.slice(1));if(e[0]==="log")return{mode:"log",...Lp(e.slice(1))};if(e[0]==="connect")return rA(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:o}=We(r,"--pat-token");r=o;let{value:c,rest:d}=We(r,"--pair-code");r=d;let{value:u,rest:h}=We(r,"--env");r=h;let{value:x,rest:m}=We(r,"--handshake-url");r=m;let{value:w,rest:v}=We(r,"--frontier-url");r=v;let{value:_,rest:E}=We(r,"--mock-scenario");r=E;let{value:S}=We(r,"--agent-id"),I=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let k={mode:"pair",privatecode:i,pairingCode:c};return u&&(k.env=u),x&&(k.handshakeUrl=x),w&&(k.frontierUrl=w),_&&(k.mockScenario=_),S&&(k.agentId=S),I&&(k.skipRebuildEnv=!0),k}function nA(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=We(i,"--caption");i=c;let{value:d,rest:u}=We(i,"--name");i=u;let{value:h,rest:x}=We(i,"--agent-id");i=x;let{value:m,rest:w}=We(i,"--session-id");i=w;let{value:v,rest:_}=We(i,"--mime");i=_;let E=i.includes("--group-file");i=i.filter(k=>k!=="--group-file");let S=i.includes("--json"),I={mode:"send",kind:e,path:r,json:S};return o&&(I.caption=o),d&&(I.name=d),h&&(I.agentId=h),m&&(I.sessionId=m),E&&(I.groupFile=!0),v&&(I.mimeType=v),I}function rA(t){let e=t,{value:r,rest:i}=We(e,"--pat-token");e=i;let{value:o,rest:c}=We(e,"--env");e=c;let{value:d,rest:u}=We(e,"--handshake-url");e=u;let{value:h,rest:x}=We(e,"--frontier-url");e=x;let{value:m,rest:w}=We(e,"--mock-scenario");e=w;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),d&&(_.handshakeUrl=d),h&&(_.frontierUrl=h),m&&(_.mockScenario=m),v&&(_.skipRebuildEnv=!0),_}var iA=`
144
142
  coze-bridge - local bridge daemon for cloud Agent Service
145
143
 
146
144
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -221,57 +219,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
221
219
 
222
220
  Internal:
223
221
  <node> <entry> --daemon daemon mode (OS supervisor only)
224
- `.trimStart();async function Jp(t=process.argv,e={}){let n=LI(t);switch(n.mode){case"help":return process.stdout.write(BI),0;case"version":return process.stdout.write(`${Mt}
225
- `),0;case"daemon":{try{await wp()}catch(i){return Vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return FI(e);case"stop":return Yp(e);case"reload":return GI(n.agentId,e);case"log":return Bp(n,e);case"update":return zI(e);case"purge":return qI(e);case"service-install":return jI(e);case"service-uninstall":return KI(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),WI(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),$I(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Fp({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 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 FI(t){let e=t.paths??Y(),n=new sn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
222
+ `.trimStart();async function Jp(t=process.argv,e={}){let r=tA(t);switch(r.mode){case"help":return process.stdout.write(iA),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 sA(e);case"stop":return Xp(e);case"reload":return cA(r.agentId,e);case"log":return Bp(r,e);case"update":return oA(e);case"purge":return lA(e);case"service-install":return uA(e);case"service-uninstall":return fA(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),hA(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),xA(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 sA(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
226
224
  `),1;if(i.kind==="stale")return await Zp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
227
- `),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
225
+ `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
228
226
  ${JSON.stringify(o.body,null,2)}
229
- `),0}async function Yp(t){let e=t.paths??Y(),n=new sn(e),i=t.daemonSweep??(async()=>{let h=q0();return await j0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await ps(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
230
- `)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
227
+ `),0}async function Xp(t){let e=t.paths??Z(),r=new rn(e),i=t.daemonSweep??(async()=>{let h=G0();return await q0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await xs(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
228
+ `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
231
229
  `:`coze-bridge: not running
232
230
  `),0;if(u.kind==="stale")return await Zp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
233
- `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
234
- `),0}catch(h){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
231
+ `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
232
+ `),0}catch(h){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
235
233
  `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
236
- `),1)}}async function zI(t){return await Yp(t),(t.spawnNpx??UI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function UI(t){return new Promise(e=>{let n=at("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
237
- `),e(1)})})}async function GI(t,e){let n=new sn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
238
- `),1;try{let o=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
234
+ `),1)}}async function oA(t){return await Xp(t),(t.spawnNpx??aA)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function aA(t){return new Promise(e=>{let r=st("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 cA(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 o=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
239
237
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
240
238
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
241
239
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
242
- `),1}}async function ps(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:n}=await Promise.resolve().then(()=>(Kp(),jp)),i=e(),o=n();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Xp(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??VI,c=t.paths??Y();if(n.kind==="connected"){if(!HI(n.body))return n;st(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(h=>st(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await $p(c.pidFile,o)}let l=t.spawnDaemon??mp,u=await ps(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Wp(e,i,o);if(h.kind==="connected")return h;st(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){st(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}st(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,o)}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)}
240
+ `),1}}async function xs(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Wp(),jp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Yp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??pA,c=t.paths??Z();if(r.kind==="connected"){if(!dA(r.body))return r;rt(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(h=>rt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await $p(c.pidFile,o)}let d=t.spawnDaemon??gp,u=await xs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Kp(e,i,o);if(h.kind==="connected")return h;rt(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){rt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}rt(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,o)}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)}
243
241
  `));return process.stdout.write(`coze-bridge: starting daemon...
244
- `),await l({paths:t.paths}),Wp(e,i,o)}function HI(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 qI(t){let e=new sn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
245
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
246
- `)}await new Promise(l=>setTimeout(l,500))}let i=await ps(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
247
- `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
248
- `)}let o=t.paths??Y(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
249
- `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
242
+ `),await d({paths:t.paths}),Kp(e,i,o)}function dA(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 lA(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(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
244
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await xs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
245
+ `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
246
+ `)}let o=t.paths??Z(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
247
+ `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
250
248
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
251
- `),0}async function jI(t){let e=await ps(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
249
+ `),0}async function uA(t){let e=await xs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
252
250
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
253
- `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
254
- `),1}}async function KI(t){let e=await ps(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
255
- `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
256
- `),1}}async function Qp(t,e,n){if(e)return st(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
257
- `),st(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function WI(t,e,n,i={},o,c){let l=new sn(n.paths),u=n.paths??Y(),h=await Qp(u,c,n.reconstructEnv??rl);if(await ed(u,h).catch(w=>st(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!n.skipDistInstall){let w=await cl({paths:n.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
258
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
259
- `)}let x=await Xp(n,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
260
- `),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),o&&(m.agent_id=o);try{let w=await l.request({method:"POST",path:"/pair",body:m,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}
251
+ `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
252
+ `),1}}async function fA(t){let e=await xs(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 rt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(rt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(rt(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
+ `),rt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function hA(t,e,r,i={},o,c){let d=new rn(r.paths),u=r.paths??Z(),h=await Qp(u,c,r.reconstructEnv??sl);if(await gd(u,h).catch(w=>rt(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 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}
257
+ `)}let x=await Yp(r,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.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),o&&(m.agent_id=o);try{let w=await d.request({method:"POST",path:"/pair",body:m,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}
261
259
  `),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"
262
260
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
263
261
  `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
264
- `),1}}async function $I(t,e,n={},i){let o=e.paths??Y(),c=t??await la(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new sn(e.paths),u=await Qp(o,i,e.reconstructEnv??rl);if(await ed(o,u).catch(m=>st(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await cl({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
265
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
266
- `)}let h=await Xp(e,l);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
267
- `),1;let x={privatecode:c};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let m=await l.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
268
- `),t!==void 0&&await ls(c,o).catch(w=>Vp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
262
+ `),1}}async function xA(t,e,r={},i){let o=e.paths??Z(),c=t??await ca(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new rn(e.paths),u=await Qp(o,i,e.reconstructEnv??sl);if(await gd(o,u).catch(m=>rt(o.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 d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
264
+ `)}let h=await Yp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
265
+ `),1;let x={privatecode:c};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let m=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
266
+ `),t!==void 0&&await ds(c,o).catch(w=>Vp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
269
267
  `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
270
- `),1}}async function Wp(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await n(200)}return t.probe(500)}async function $p(t,e,n=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<n;c++){let l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Vi(u))return;await e(i)}}function VI(t){return new Promise(e=>setTimeout(e,t))}ne();function JI(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 em(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=JI(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
271
- `),n(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
268
+ `),1}}async function Kp(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await r(200)}return t.probe(500)}async function $p(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Vi(u))return;await e(i)}}function pA(t){return new Promise(e=>setTimeout(e,t))}re();function gA(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=gA(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
269
+ `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
272
270
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
273
271
  npx -y coze-bridge@latest stop
274
272
  npx -y coze-bridge@latest connect
275
273
 
276
- `)}em();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Ll("warn");Jp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
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)}
277
275
  `),process.exit(1)});