coze-bridge 0.2.7-alpha.10 → 0.2.7-alpha.101

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 +98 -95
  2. package/package.json +3 -7
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 Fg=Object.create;var Ra=Object.defineProperty;var zg=Object.getOwnPropertyDescriptor;var Ug=Object.getOwnPropertyNames;var Gg=Object.getPrototypeOf,Hg=Object.prototype.hasOwnProperty;var fe=(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 Xe=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ca=(t,e)=>{for(var n in e)Ra(t,n,{get:e[n],enumerable:!0})},Wg=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ug(e))!Hg.call(t,o)&&o!==n&&Ra(t,o,{get:()=>e[o],enumerable:!(i=zg(e,o))||i.enumerable});return t};var Ht=(t,e,n)=>(n=t!=null?Fg(Gg(t)):{},Wg(e||!t||!t.__esModule?Ra(n,"default",{value:t,enumerable:!0}):n,t));function $e(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ar=Xe(()=>{"use strict"});import{createWriteStream as qg,mkdirSync as jg,readdirSync as Kg,unlinkSync as $g}from"node:fs";import{join as Pl}from"node:path";function On(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 Pa(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Vg(t,e,n){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)>n}function us(t,e,n,i){let o;try{o=Kg(t)}catch{return}for(let c of o){let d=Pa(c,e);if(d&&Vg(d,n,i))try{$g(Pl(t,c))}catch{}}}var ni,Da=Xe(()=>{"use strict";ni=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>On(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{jg(this.dir,{recursive:!0});let n=qg(Pl(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&&us(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 Jg,mkdirSync as Zg}from"node:fs";import{join as Yg}from"node:path";function Ol(t){let e=t.retentionDays??em,n=t.clock??(()=>On(new Date));hs={bridgeSink:new ni(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new ni(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();us(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])us(t.agentLogsDir(o),"agent",i,e)}function tm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Ll(t){Oa=t}function Nl(t){return dr[Oa]<=dr[t]}function Ml(t,e){let n=dr[t];return n===void 0?!0:n>=dr[e]}function xs(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)),d=e(o%60);return`${On(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function ct(t,e,n,i,o){try{let c=`${JSON.stringify({ts:Bl(new Date),level:e,module:n,msg:i,...o})}
11
- `;Zg(t,{recursive:!0}),Jg(Yg(t,cr("bridge",On(new Date))),c)}catch{}}function nm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function fs(t,e,n,i,o){if(dr[t]<dr[Oa])return;let c=`${JSON.stringify({ts:Bl(new Date),level:t,module:e,msg:n,...Dl,...i})}
12
- `;if(hs){let d=nm(o,i),u=d?tm(hs,d):hs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Qg.write(c):Xg.write(c)}function G(t,e){return{debug:(n,i)=>fs("debug",t,n,i,e),info:(n,i)=>fs("info",t,n,i,e),warn:(n,i)=>fs("warn",t,n,i,e),error:(n,i)=>fs("error",t,n,i,e),child:n=>G(`${t}.${n}`,e),forAgent:n=>G(t,n)}}var dr,Oa,Xg,Qg,Dl,em,hs,ne=Xe(()=>{"use strict";ar();Da();dr={debug:10,info:20,warn:30,error:40},Oa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Xg=process.stdout,Qg=process.stderr,Dl={},em=$e("COZE_BRIDGE_LOG_RETENTION_DAYS",30),hs=null});var k,qe=Xe(()=>{"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={};Ca(Gl,{ACP_WRAPPER_NPM_PACKAGES:()=>gs,_resetAcpInstallerForTests:()=>cm,_setBinaryPathCacheForTests:()=>dm,buildAcpSpawn:()=>ri,ensureAcpInstalled:()=>ur,getAcpBinaryPath:()=>ms,pickWhichLine:()=>Ma,probeAcpVersion:()=>am,resolveAcpCommand:()=>Ul});import{readFileSync as Fl}from"node:fs";import{createRequire as rm}from"node:module";import{dirname as im,resolve as sm}from"node:path";function Na(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Ma(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 om(t){let e=zl.resolve(`${t.npmPackage}/package.json`),n=im(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 sm(n,o)}async function ur(t,e){let n=La[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=lr.get(t);if(i)return i;let o=Na(t);if(o)return lr.set(t,o),ps.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let c=om(n);return lr.set(t,c),ps.info("acp wrapper resolved",{framework:t,binary:n.binary,path:c}),c}catch(c){throw ps.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(c)}),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:c})}}async function am(t){let e=La[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){ps.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function ms(t){return lr.get(t)}function Ul(t,e){if(e)return e;let n=Na(t);if(n)return n;let i=ms(t);if(!i)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function ri(t,e,n){if(e)return{command:e,args:[...n]};let i=Na(t);if(i)return{command:i,args:[...n]};let o=Ul(t);return{command:process.execPath,args:[o,...n]}}function cm(){lr.clear()}function dm(t,e){lr.set(t,e)}var ps,La,gs,zl,lr,an=Xe(()=>{"use strict";qe();ne();ps=G("agents.acp-installer"),La={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},gs=Object.values(La).filter(t=>t!==void 0).map(t=>t.npmPackage),zl=rm(import.meta.url),lr=new Map});import{chmod as um,mkdir as fm,readFile as hm,rename as xm,rm as pm,writeFile as gm}from"node:fs/promises";import{dirname as mm}from"node:path";async function cn(t){try{let e=await hm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function dn(t,e,n){await fm(mm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await gm(i,e,{encoding:"utf8",mode:n?.mode}),await xm(i,t),n?.mode!==void 0&&await um(t,n.mode)}catch(o){throw await pm(i,{force:!0}).catch(()=>{}),o}}async function ln(t,e,n){await dn(t,`${JSON.stringify(e,null,2)}
14
- `,n)}var un=Xe(()=>{"use strict"});import{promises as ql,readdirSync as wm}from"node:fs";import{homedir as _m}from"node:os";import{sep as ym,join as Te,resolve as jl}from"node:path";function J(t){let e=t??_m(),n=Te(e,".coze"),i=Te(n,"bridge"),o=Te(i,"lib"),c=Te(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Te(o,"index.js"),binDir:Te(i,"bin"),pidFile:Te(i,"bridge.pid"),portFile:Te(i,"bridge.port"),tokenFile:Te(i,"bridge.token"),patTokenFile:Te(i,"pat-token"),agentEnvFile:Te(i,"agent-env.json"),logFile:Te(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Te(c,"daemon-stdio.log"),installLock:Te(i,"install.lock"),configFile:Te(i,"config.json"),agentsRoot:Te(n,"agents")}}function je(t,e=J()){let n=Te(e.agentsRoot,t);return{root:n,config:Te(n,"config.json"),workspace:Te(n,"workspace"),logs:Te(n,"logs")}}function ws(t=J()){try{return wm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ii(t,e){let n=await ql.realpath(jl(t)).catch(()=>null);if(!n)return!1;let i=await ql.realpath(jl(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+ym)}var Re=Xe(()=>{"use strict"});var ys={};Ca(ys,{AGENT_CONFIG_FILE_MODE:()=>_s,enforceAgentConfigMode:()=>vm,loadAgentConfig:()=>Ce,persistAgentSessions:()=>si,persistAgentSkills:()=>oi,saveAgentConfig:()=>Be});import{chmod as Em,stat as bm}from"node:fs/promises";function Ce(t,e){return cn(je(t,e).config)}function Be(t,e){return ln(je(t.agentId,e).config,t,{mode:_s})}async function vm(t,e){if(process.platform==="win32")return;let n=je(t,e).config;try{let i=await bm(n);if(!i.isFile())return;let o=i.mode&511;o!==_s&&(await Em(n,_s),Kl.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Kl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function si(t,e,n){let i=await Ce(t,n);i&&(i.sessions=Object.fromEntries(e),await Be(i,n))}async function oi(t,e,n){let i=await Ce(t,n);i&&(i.skills=e,await Be(i,n))}var Kl,_s,fn=Xe(()=>{"use strict";un();ne();Re();Kl=G("agent-config"),_s=384});var za=ae((N2,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 bs=ae(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 Rm(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]=Rm(Zl[t])});var nu=ae((B2,tu)=>{var Cm=fe("fs"),Le=fe("path"),Xl=za(),Pm=bs(),Dm=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 ve(t){this.sep=Le.sep,this.fs=Cm,Ql(t)&&Ql(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}tu.exports=ve;ve.prototype.makeDir=function(t){let e=this;function n(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(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 Pm.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};ve.prototype.writeFileTo=function(t,e,n,i){let o=this;if(o.fs.existsSync(t)){if(!n)return!1;var 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};ve.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!n)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(g,S){g?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,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)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};ve.prototype.findFiles=function(t){let e=this;function n(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(n(h,o,c)))}),d}return n(t,void 0,!0)};ve.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.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),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Le.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(m,g){if(m)return e(m);i=i.concat(g),--d||e(null,i)}):--d||e(null,i))})})})};ve.prototype.getAttributes=function(){};ve.prototype.setAttributes=function(){};ve.crc32update=function(t,e){return eu[(t^e)&255]^t>>>8};ve.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=ve.crc32update(n,t[i++]);return~n>>>0};ve.methodToString=function(t){switch(t){case Xl.STORED:return"STORED ("+t+")";case Xl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ve.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};ve.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.posix.join(".",e)};ve.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};ve.sanitize=function(t,e){t=Le.resolve(Le.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var c=Le.normalize(Le.join(t,n.slice(i,o).join(Le.sep)));if(c.indexOf(t)===0)return c}return Le.normalize(Le.join(t,Le.basename(e)))};ve.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};ve.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};ve.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ve.fromDate2DOS=function(t){let e=0,n=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),n=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|n};ve.isWin=Dm;ve.crcTable=eu});var iu=ae((F2,ru)=>{var Om=fe("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=Om.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=ae((z2,su)=>{su.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var xr=ae((U2,hr)=>{hr.exports=nu();hr.exports.Constants=za();hr.exports.Errors=bs();hr.exports.FileAttr=iu();hr.exports.decoder=ou()});var cu=ae((G2,au)=>{var hn=xr(),F=hn.Constants;au.exports=function(){var t=20,e=10,n=0,i=0,o=0,c=0,d=0,u=0,h=0,x=0,m=0,g=0,S=0,_=0,v=0;t|=hn.isWin?2560:768,n|=F.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,P=E=>Math.max(0,E)&255;return o=hn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&F.FLG_EFS)>0},set flags_efs(E){E?n|=F.FLG_EFS:n&=~F.FLG_EFS},get flags_desc(){return(n&F.FLG_DESC)>0},set flags_desc(E){E?n|=F.FLG_DESC:n&=~F.FLG_DESC},get method(){return i},set method(E){switch(E){case F.STORED:this.version=10;case F.DEFLATED:default:this.version=20}i=E},get time(){return hn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=hn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return P(o>>>8)},get crc(){return c},set crc(E){c=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return h},set fileNameLength(E){h=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return m},set commentLength(E){m=E},get diskNumStart(){return g},set diskNumStart(E){g=A(E)},get inAttr(){return S},set inAttr(E){S=A(E)},get attr(){return _},set attr(E){_=A(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(n&F.FLG_ENC)===F.FLG_ENC},get centralHeaderSize(){return F.CENHDR+h+x+m},get realDataOffset(){return v+F.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var R=E.slice(v,v+F.LOCHDR);if(R.readUInt32LE(0)!==F.LOCSIG)throw hn.Errors.INVALID_LOC();I.version=R.readUInt16LE(F.LOCVER),I.flags=R.readUInt16LE(F.LOCFLG),I.flags_desc=(I.flags&F.FLG_DESC)>0,I.method=R.readUInt16LE(F.LOCHOW),I.time=R.readUInt32LE(F.LOCTIM),I.crc=R.readUInt32LE(F.LOCCRC),I.compressedSize=R.readUInt32LE(F.LOCSIZ),I.size=R.readUInt32LE(F.LOCLEN),I.fnameLen=R.readUInt16LE(F.LOCNAM),I.extraLen=R.readUInt16LE(F.LOCEXT);let O=v+F.LOCHDR+I.fnameLen,B=O+I.extraLen;return E.slice(O,B)},loadFromBinary:function(E){if(E.length!==F.CENHDR||E.readUInt32LE(0)!==F.CENSIG)throw hn.Errors.INVALID_CEN();t=E.readUInt16LE(F.CENVEM),e=E.readUInt16LE(F.CENVER),n=E.readUInt16LE(F.CENFLG),i=E.readUInt16LE(F.CENHOW),o=E.readUInt32LE(F.CENTIM),c=E.readUInt32LE(F.CENCRC),d=E.readUInt32LE(F.CENSIZ),u=E.readUInt32LE(F.CENLEN),h=E.readUInt16LE(F.CENNAM),x=E.readUInt16LE(F.CENEXT),m=E.readUInt16LE(F.CENCOM),g=E.readUInt16LE(F.CENDSK),S=E.readUInt16LE(F.CENATT),_=E.readUInt32LE(F.CENATX),v=E.readUInt32LE(F.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(F.LOCHDR);return E.writeUInt32LE(F.LOCSIG,0),E.writeUInt16LE(e,F.LOCVER),E.writeUInt16LE(n,F.LOCFLG),E.writeUInt16LE(i,F.LOCHOW),E.writeUInt32LE(o,F.LOCTIM),E.writeUInt32LE(c,F.LOCCRC),E.writeUInt32LE(d,F.LOCSIZ),E.writeUInt32LE(u,F.LOCLEN),E.writeUInt16LE(h,F.LOCNAM),E.writeUInt16LE(I.extraLen,F.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(F.CENHDR+h+x+m);return E.writeUInt32LE(F.CENSIG,0),E.writeUInt16LE(t,F.CENVEM),E.writeUInt16LE(e,F.CENVER),E.writeUInt16LE(n,F.CENFLG),E.writeUInt16LE(i,F.CENHOW),E.writeUInt32LE(o,F.CENTIM),E.writeUInt32LE(c,F.CENCRC),E.writeUInt32LE(d,F.CENSIZ),E.writeUInt32LE(u,F.CENLEN),E.writeUInt16LE(h,F.CENNAM),E.writeUInt16LE(x,F.CENEXT),E.writeUInt16LE(m,F.CENCOM),E.writeUInt16LE(g,F.CENDSK),E.writeUInt16LE(S,F.CENATT),E.writeUInt32LE(_,F.CENATX),E.writeUInt32LE(v,F.CENOFF),E},toJSON:function(){let E=function(R){return R+" bytes"};return{made:t,version:e,flags:n,method:hn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(h),extraLength:E(x),commentLength:E(m),diskNumStart:g,inAttr:S,attr:_,offset:v,centralHeaderSize:E(F.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var lu=ae((H2,du)=>{var pr=xr(),ye=pr.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 ye.ENDHDR+o},loadFromBinary:function(c){if((c.length!==ye.ENDHDR||c.readUInt32LE(0)!==ye.ENDSIG)&&(c.length<ye.ZIP64HDR||c.readUInt32LE(0)!==ye.ZIP64SIG))throw pr.Errors.INVALID_END();c.readUInt32LE(0)===ye.ENDSIG?(t=c.readUInt16LE(ye.ENDSUB),e=c.readUInt16LE(ye.ENDTOT),n=c.readUInt32LE(ye.ENDSIZ),i=c.readUInt32LE(ye.ENDOFF),o=c.readUInt16LE(ye.ENDCOM)):(t=pr.readBigUInt64LE(c,ye.ZIP64SUB),e=pr.readBigUInt64LE(c,ye.ZIP64TOT),n=pr.readBigUInt64LE(c,ye.ZIP64SIZE),i=pr.readBigUInt64LE(c,ye.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(ye.ENDHDR+o);return c.writeUInt32LE(ye.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ye.ENDSUB),c.writeUInt16LE(e,ye.ENDTOT),c.writeUInt32LE(n,ye.ENDSIZ),c.writeUInt32LE(i,ye.ENDOFF),c.writeUInt16LE(o,ye.ENDCOM),c.fill(" ",ye.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:n+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ga=ae(Ua=>{Ua.EntryHeader=cu();Ua.MainHeader=lu()});var fu=ae((q2,uu)=>{uu.exports=function(t){var e=fe("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=[],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 xu=ae((j2,hu)=>{var Lm=+(process.versions?process.versions.node:"").split(".")[0]||0;hu.exports=function(t,e){var n=fe("zlib");let i=Lm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var c=n.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 g=d[m];g.copy(h,x),x+=g.length}o&&o(h)}),c.end(t)}}}});var _u=ae((K2,wu)=>{"use strict";var{randomFillSync:pu}=fe("crypto"),Nm=bs(),Mm=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}),mu=(t,e)=>Math.imul(t,e)>>>0,gu=(t,e)=>Mm[(t^e)&255]^t>>>8,ai=()=>typeof pu=="function"?pu(Buffer.alloc(12)):ai.node();ai.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let n=0;n<e;n++)t[n]=Math.random()*256&255;return t};var vs={genSalt:ai};function Ss(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])}Ss.prototype.updateKeys=function(t){let e=this.keys;return e[0]=gu(e[0],t),e[1]+=e[0]&255,e[1]=mu(e[1],134775813)+1,e[2]=gu(e[2],e[1]>>>24),t};Ss.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return mu(t,t^1)>>8&255};function Bm(t){let e=new Ss(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 Fm(t){let e=new Ss(t);return function(n,i,o=0){i||(i=Buffer.alloc(n.length));for(let c of n){let d=e.next();i[o++]=c^d,e.updateKeys(c)}return i}}function zm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Bm(n),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Nm.WRONG_PASSWORD();return i(t.slice(12))}function Um(t){Buffer.isBuffer(t)&&t.length>=12?vs.genSalt=function(){return t.slice(0,12)}:t==="node"?vs.genSalt=ai.node:vs.genSalt=ai}function Gm(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Fm(n),c=vs.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)}wu.exports={decrypt:zm,encrypt:Gm,_salter:Um}});var yu=ae(Is=>{Is.Deflater=fu();Is.Inflater=xu();Is.ZipCrypto=_u()});var Wa=ae((V2,Eu)=>{var ce=xr(),Hm=Ga(),Se=ce.Constants,Ha=yu();Eu.exports=function(t,e){var n=new Hm.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,g=typeof m.decoder=="object"?m.decoder:ce.decoder;x=g.hasOwnProperty("efs")?g.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ce.crc32(E)!==n.localHeader.crc)return!1}else{let R={},O=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(O)==Se.LOCSIG||e.readUInt32LE(O)==Se.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Se.EXTSIG)R.crc=e.readUInt32LE(O+Se.EXTCRC),R.compressedSize=e.readUInt32LE(O+Se.EXTSIZ),R.size=e.readUInt32LE(O+Se.EXTLEN);else if(e.readUInt16LE(O+12)===19280)R.crc=e.readUInt32LE(O+Se.EXTCRC-4),R.compressedSize=e.readUInt32LE(O+Se.EXTSIZ-4),R.size=e.readUInt32LE(O+Se.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==n.compressedSize||R.size!==n.size||R.crc!==n.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(E)!==R.crc)return!1}return!0}function v(E,R,O){if(typeof R>"u"&&typeof E=="string"&&(O=E,E=void 0),c)return E&&R&&R(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var B=S();if(B.length===0)return E&&R&&R(B),B;if(n.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();B=Ha.ZipCrypto.decrypt(B,n,O)}var N=Buffer.alloc(n.size);switch(n.method){case ce.Constants.STORED:if(B.copy(N),_(N))return E&&R&&R(N),N;throw E&&R&&R(N,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var $=new Ha.Inflater(B,n.size);if(E)$.inflateAsync(function(j){j.copy(j,0),R&&(_(j)?R(j):R(j,ce.Errors.BAD_CRC()))});else{if($.inflate(N).copy(N,0),!_(N))throw ce.Errors.BAD_CRC(`"${g.decode(i)}"`);return N}break;default:throw E&&R&&R(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(E,R){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&R&&R(S()),S();if(d.length&&!c){var O;switch(n.method){case ce.Constants.STORED:return n.compressedSize=n.size,O=Buffer.alloc(d.length),d.copy(O),E&&R&&R(O),O;default:case ce.Constants.DEFLATED:var B=new Ha.Deflater(d);if(E)B.deflateAsync(function($){O=Buffer.alloc($.length),n.compressedSize=$.length,$.copy(O),R&&R(O)});else{var N=B.deflate();return n.compressedSize=N.length,N}B=null;break}}else if(E&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,R){return ce.readBigUInt64LE(E,R)}function T(E){try{for(var R=0,O,B,N;R+4<E.length;)O=E.readUInt16LE(R),R+=2,B=E.readUInt16LE(R),R+=2,N=E.slice(R,R+B),R+=B,Se.ID_ZIP64===O&&P(N)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(E){var R,O,B,N;E.length>=Se.EF_ZIP64_SCOMP&&(R=A(E,Se.EF_ZIP64_SUNCOMP),n.size===Se.EF_ZIP64_OR_32&&(n.size=R)),E.length>=Se.EF_ZIP64_RHO&&(O=A(E,Se.EF_ZIP64_SCOMP),n.compressedSize===Se.EF_ZIP64_OR_32&&(n.compressedSize=O)),E.length>=Se.EF_ZIP64_DSN&&(B=A(E,Se.EF_ZIP64_RHO),n.offset===Se.EF_ZIP64_OR_32&&(n.offset=B)),E.length>=Se.EF_ZIP64_DSN+4&&(N=E.readUInt32LE(Se.EF_ZIP64_DSN),n.diskNumStart===Se.EF_ZIP64_OR_16&&(n.diskNumStart=N))}return{get entryName(){return g.decode(i)},get rawEntryName(){return i},set entryName(E){i=ce.toBuffer(E,g.encode);var R=i[i.length-1];c=R===47||R===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,T(E)},get comment(){return g.decode(o)},set comment(E){if(o=ce.toBuffer(E,g.encode),n.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var E=g.decode(i);return c?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=ce.toBuffer(E,ce.decoder.encode),!c&&d.length?(n.size=d.length,n.method=ce.Constants.DEFLATED,n.crc=ce.crc32(E),n.changed=!0):n.method=ce.Constants.STORED},getData:function(E){return n.changed?d:v(!1,null,E)},getDataAsync:function(E,R){n.changed?E(d):v(!0,E,R)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),R=ce.Constants.CENHDR;return i.copy(E,R),R+=i.length,u.copy(E,R),R+=n.extraLength,o.copy(E,R),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let R=n.localHeaderToBinary(),O=Buffer.alloc(R.length+i.length+n.extraLocalLength);return R.copy(O,E),E+=R.length,i.copy(O,E),E+=i.length,h.copy(O,E),E+=h.length,O},toJSON:function(){let E=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Su=ae((J2,vu)=>{var bu=Wa(),Wm=Ga(),Ke=xr();vu.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),c=new Wm.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:g}=x;t?v(x.readEntries):d=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let P=T.split("/");if(P.pop(),!!P.length)for(let E=0;E<P.length;E++){let R=P.slice(0,E+1).join("/")+"/";A.add(R)}}for(let T of A)if(!(T in i)){let P=new bu(x);P.entryName=T,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,h.add(P)}}function _(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/Ke.Constants.CENHDR)throw Ke.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(c.diskEntries);for(var A=c.offset,T=0;T<n.length;T++){var P=A,E=new bu(x,t);E.header=t.slice(P,P+=Ke.Constants.CENHDR),E.entryName=t.slice(P,P+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(P,P+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(P,P+E.header.commentLength)),A+=E.header.centralHeaderSize,n[T]=E,i[E.entryName]=E}h.clear(),S()}function v(A){var T=t.length-Ke.Constants.ENDHDR,P=Math.max(0,T-65535),E=P,R=t.length,O=-1,B=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ke.Constants.ENDSIG){O=T,B=T,R=T+Ke.Constants.ENDHDR,E=T-Ke.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ke.Constants.END64SIG){E=P;continue}if(t.readUInt32LE(T)===Ke.Constants.ZIP64SIG){O=T,R=T+Ke.readBigUInt64LE(t,T+Ke.Constants.ZIP64SIZE)+Ke.Constants.ZIP64LEAD;break}}if(O==-1)throw Ke.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,R)),c.commentLength&&(o=t.slice(B+Ke.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!m&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(A=>!h.has(A))},get comment(){return g.decode(o)},set comment(A){o=Ke.toBuffer(A,g.encode),c.commentLength=o.length},getEntryCount:function(){return d?n.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||_(),i[A]||null},setEntry:function(A){d||_(),n.push(A),i[A.entryName]=A,c.totalEntries=n.length},deleteFile:function(A,T=!0){d||_();let P=i[A];this.getEntryChildren(P,T).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||_();let T=i[A],P=n.indexOf(T);P>=0&&(n.splice(P,1),delete i[A],c.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(d||_(),typeof A=="object")if(A.isDirectory&&T){let P=[],E=A.entryName;for(let R of n)R.entryName.startsWith(E)&&P.push(R);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),I();let A=[],T=[],P=0,E=0;c.size=0,c.offset=0;let R=0;for(let N of this.entries){let $=N.getCompressedData();N.header.offset=E;let j=N.packLocalHeader(),re=j.length+$.length;E+=re,A.push(j),A.push($);let X=N.packCentralHeader();T.push(X),c.size+=X.length,P+=re+X.length,R++}P+=c.mainHeaderSize,c.offset=E,c.totalEntries=R,E=0;let O=Buffer.alloc(P);for(let N of A)N.copy(O,E),E+=N.length;for(let N of T)N.copy(O,E),E+=N.length;let B=c.toBinary();return o&&o.copy(B,Ke.Constants.ENDHDR),B.copy(O,E),t=O,d=!1,O},toAsyncBuffer:function(A,T,P,E){try{d||_(),I();let R=[],O=[],B=0,N=0,$=0;c.size=0,c.offset=0;let j=function(re){if(re.length>0){let X=re.shift(),se=X.entryName+X.extra.toString();P&&P(se),X.getCompressedDataAsync(function(oe){E&&E(se),X.header.offset=N;let C=X.packLocalHeader(),U=C.length+oe.length;N+=U,R.push(C),R.push(oe);let W=X.packCentralHeader();O.push(W),c.size+=W.length,B+=U+W.length,$++,j(re)})}else{B+=c.mainHeaderSize,c.offset=N,c.totalEntries=$,N=0;let X=Buffer.alloc(B);R.forEach(function(oe){oe.copy(X,N),N+=oe.length}),O.forEach(function(oe){oe.copy(X,N),N+=oe.length});let se=c.toBinary();o&&o.copy(se,Ke.Constants.ENDHDR),se.copy(X,N),t=X,d=!1,A(X)}};j(Array.from(this.entries))}catch(R){T(R)}}}}});var ku=ae((Z2,Au)=>{var be=xr(),Ee=fe("path"),qm=Wa(),jm=Su(),Ln=(...t)=>be.findLast(t,e=>typeof e=="boolean"),Iu=(...t)=>be.findLast(t,e=>typeof e=="string"),Km=(...t)=>be.findLast(t,e=>typeof e=="function"),$m={noSort:!1,readEntries:!1,method:be.Constants.NONE,fs:null};Au.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),$m);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=be.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new be(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=be.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=be.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw be.Errors.INVALID_FILENAME();let c=new jm(n,i),{canonical:d,sanitize:u,zipnamefix:h}=be;function x(_){if(_&&c){var v;if(typeof _=="string"&&(v=c.getEntry(Ee.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=c.getEntry(_.entryName)),v)return v}return null}function m(_){let{join:v,normalize:I,sep:A}=Ee.posix;return v(Ee.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function g(_){return _ instanceof RegExp?(function(v){return function(I){return v.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",Ee.relative(_,v)+I};return{readFile:function(_,v){var I=x(_);return I&&I.getData(v)||null},childCount:function(_){let v=x(_);if(v)return c.getChildCount(v)},readFileAsync:function(_,v){var I=x(_);I?I.getDataAsync(v):v(null,"getEntry failed for:"+_)},readAsText:function(_,v){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var A=x(_);A?A.getDataAsync(function(T,P){if(P){v(T,P);return}T&&T.length?v(T.toString(I||"utf8")):v("")}):v("")},deleteFile:function(_,v=!0){var I=x(_);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(_){var v=x(_);v&&c.deleteEntry(v.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,v){var I=x(_);I&&(I.comment=v)},getZipEntryComment:function(_){var v=x(_);return v&&v.comment||""},updateFile:function(_,v){var I=x(_);I&&I.setData(v)},addLocalFile:function(_,v,I,A){if(o.fs.existsSync(_)){v=v?m(v):"";let T=Ee.win32.basename(Ee.win32.normalize(_));v+=I||T;let P=o.fs.statSync(_),E=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(v+=o.sep),this.addFile(v,E,A,P)}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=Ee.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:P}=_,E=this;o.fs.stat(I,function(R,O){if(R)return v(R,!1);T=T?m(T):"";let B=Ee.win32.basename(Ee.win32.normalize(I));if(T+=P||B,O.isFile())o.fs.readFile(I,function(N,$){return N?v(N,!1):(E.addFile(T,$,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=g(I),v=v?m(v):"",_=Ee.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let P of A){let E=Ee.join(v,S(_,P));I(E)&&T.addLocalFile(P,Ee.dirname(E))}}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,A){A=g(A),I=I?m(I):"",_=Ee.normalize(_);var T=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")v(void 0,be.Errors.FILE_NOT_FOUND(_));else if(P)v(void 0,P);else{var E=o.findFiles(_),R=-1,O=function(){if(R+=1,R<E.length){var B=E[R],N=S(_,B).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(N)?o.fs.stat(B,function($,j){$&&v(void 0,$),j.isFile()?o.fs.readFile(B,function(re,X){re?v(void 0,re):(T.addFile(I+N,X,"",j),O())}):(T.addFile(I+N+"/",Buffer.alloc(0),"",j),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Ee.resolve(m(_.localPath));let{zipPath:A,filter:T,namefix:P}=_;T instanceof RegExp?T=(function(O){return function(B){return O.test(B)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?m(A):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let E=O=>Ee.join(A,P(S(localPath,O))),R=O=>Ee.win32.basename(Ee.win32.normalize(P(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,be.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):o.findFilesAsync(localPath,function(B,N){if(B)return v(B);N=N.filter($=>T(E($))),N.length||v(void 0,!1),setImmediate(N.reverse().reduce(function($,j){return function(re,X){if(re||X===!1)return setImmediate($,re,!1);I.addLocalFileAsync({localPath:j,zipPath:Ee.dirname(E(j)),zipName:R(j)},$)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(T,P)=>{T&&A(T),P&&I(this)})})},addFile:function(_,v,I,A){_=h(_);let T=x(_),P=T!=null;P||(T=new qm(i),T.entryName=_),T.comment=I||"";let E=typeof A=="object"&&A instanceof o.fs.Stats;E&&(T.header.time=A.mtime);var R=T.isDirectory?16:0;let O=T.isDirectory?16384:32768;return E?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=T.isDirectory?493:420,R=(R|O<<16)>>>0,T.attr=R,T.setData(v),P||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(_,v,I,A,T,P){A=Ln(!1,A),T=Ln(!1,T),I=Ln(!0,I),P=Iu(T,P);var E=x(_);if(!E)throw be.Errors.NO_ENTRY();var R=d(E.entryName),O=u(v,P&&!E.isDirectory?P:I?R:Ee.basename(R));if(E.isDirectory){var B=c.getEntryChildren(E);return B.forEach(function(j){if(j.isDirectory)return;var re=j.getData();if(!re)throw be.Errors.CANT_EXTRACT_FILE();var X=d(j.entryName),se=u(v,I?X:Ee.basename(X));let oe=T?j.header.fileAttr:void 0;o.writeFileTo(se,re,A,oe)}),!0}var N=E.getData(c.password);if(!N)throw be.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw be.Errors.CANT_OVERRIDE();let $=T?_.header.fileAttr:void 0;return o.writeFileTo(O,N,A,$),!0},test:function(_){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,v,I,A){if(I=Ln(!1,I),A=Iu(I,A),v=Ln(!1,v),!c)throw be.Errors.NO_ZIP();c.entries.forEach(function(T){var P=u(_,d(T.entryName));if(T.isDirectory){o.makeDir(P);return}var E=T.getData(A);if(!E)throw be.Errors.CANT_EXTRACT_FILE();let R=I?T.header.fileAttr:void 0;o.writeFileTo(P,E,v,R);try{o.fs.utimesSync(P,T.header.time,T.header.time)}catch{throw be.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,A){if(A=Km(v,I,A),I=Ln(!1,I),v=Ln(!1,v),!A)return new Promise((O,B)=>{this.extractAllToAsync(_,v,I,function(N){N?B(N):O(this)})});if(!c){A(be.Errors.NO_ZIP());return}_=Ee.resolve(_);let T=O=>u(_,Ee.normalize(d(O.entryName))),P=(O,B)=>new Error(O+': "'+B+'"'),E=[],R=[];c.entries.forEach(O=>{O.isDirectory?E.push(O):R.push(O)});for(let O of E){let B=T(O),N=I?O.header.fileAttr:void 0;try{o.makeDir(B),N&&o.fs.chmodSync(B,N),o.fs.utimesSync(B,O.header.time,O.header.time)}catch{A(P("Unable to create folder",B))}}R.reverse().reduce(function(O,B){return function(N){if(N)O(N);else{let $=Ee.normalize(d(B.entryName)),j=u(_,$);B.getDataAsync(function(re,X){if(X)O(X);else if(!re)O(be.Errors.CANT_EXTRACT_FILE());else{let se=I?B.header.fileAttr:void 0;o.writeFileToAsync(j,re,v,se,function(oe){oe||O(P("Unable to write file",j)),o.fs.utimes(j,B.header.time,B.header.time,function(C){C?O(P("Unable to set times",j)):O()})})}})}}},A)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((T,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let R=O=>O?T(O):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,E,I,A,R)},P)})},toBufferPromise:function(){return new Promise((_,v)=>{c.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,A){return typeof _=="function"?(c.toAsyncBuffer(_,v,I,A),null):c.compressToBuffer()}}}});import{execFile as ty,spawn as ny,spawnSync as xk}from"node:child_process";import{promisify as ry}from"node:util";function sy(t){if(process.platform!=="win32")return!1;if(Vf.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(Vf,"").toLowerCase();return iy.has(n)}function Jf(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return sy(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function et(t,e=[],n={}){return ny(t,e,Jf(t,n))}function Zf(t,e=[],n={}){return oy(t,e,Jf(t,n))}var iy,Vf,oy,Jt=Xe(()=>{"use strict";iy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Vf=/\.(cmd|bat|ps1)$/i;oy=ry(ty)});var Yt=ae((eP,Mh)=>{"use strict";var Lh=["nodebuffer","arraybuffer","fragments"],Nh=typeof Blob<"u";Nh&&Lh.push("blob");Mh.exports={BINARY_TYPES:Lh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Nh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Zi=ae((tP,No)=>{"use strict";var{EMPTY_BUFFER:iv}=Yt(),Sd=Buffer[Symbol.species];function sv(t,e){if(t.length===0)return iv;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 Sd(n.buffer,n.byteOffset,i):n}function Bh(t,e,n,i,o){for(let c=0;c<o;c++)n[i+c]=t[c]^e[c&3]}function Fh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function ov(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Id(t){if(Id.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Sd(t):ArrayBuffer.isView(t)?e=new Sd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Id.readOnly=!1),e}No.exports={concat:sv,mask:Bh,toArrayBuffer:ov,toBuffer:Id,unmask:Fh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=fe("bufferutil");No.exports.mask=function(e,n,i,o,c){c<48?Bh(e,n,i,o,c):t.mask(e,n,i,o,c)},No.exports.unmask=function(e,n){e.length<32?Fh(e,n):t.unmask(e,n)}}catch{}});var Gh=ae((nP,Uh)=>{"use strict";var zh=Symbol("kDone"),Ad=Symbol("kRun"),kd=class{constructor(e){this[zh]=()=>{this.pending--,this[Ad]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ad]()}[Ad](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[zh])}}};Uh.exports=kd});var Hr=ae((rP,jh)=>{"use strict";var Yi=fe("zlib"),Hh=Zi(),av=Gh(),{kStatusCode:Wh}=Yt(),cv=Buffer[Symbol.species],dv=Buffer.from([0,0,255,255]),Bo=Symbol("permessage-deflate"),Xt=Symbol("total-length"),Ur=Symbol("callback"),Rn=Symbol("buffers"),Gr=Symbol("error"),Mo,Td=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,!Mo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Mo=new av(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[Ur];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){Mo.add(o=>{this._decompress(e,n,(c,d)=>{o(),i(c,d)})})}compress(e,n,i){Mo.add(o=>{this._compress(e,n,(c,d)=>{o(),i(c,d)})})}_decompress(e,n,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Yi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Yi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Bo]=this,this._inflate[Xt]=0,this._inflate[Rn]=[],this._inflate.on("error",uv),this._inflate.on("data",qh)}this._inflate[Ur]=i,this._inflate.write(e),n&&this._inflate.write(dv),this._inflate.flush(()=>{let c=this._inflate[Gr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Hh.concat(this._inflate[Rn],this._inflate[Xt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Xt]=0,this._inflate[Rn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Yi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Yi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Xt]=0,this._deflate[Rn]=[],this._deflate.on("data",lv)}this._deflate[Ur]=i,this._deflate.write(e),this._deflate.flush(Yi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Hh.concat(this._deflate[Rn],this._deflate[Xt]);n&&(c=new cv(c.buffer,c.byteOffset,c.length-4)),this._deflate[Ur]=null,this._deflate[Xt]=0,this._deflate[Rn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};jh.exports=Td;function lv(t){this[Rn].push(t),this[Xt]+=t.length}function qh(t){if(this[Xt]+=t.length,this[Bo]._maxPayload<1||this[Xt]<=this[Bo]._maxPayload){this[Rn].push(t);return}this[Gr]=new RangeError("Max payload size exceeded"),this[Gr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gr][Wh]=1009,this.removeListener("data",qh),this.reset()}function uv(t){if(this[Bo]._inflate=null,this[Gr]){this[Ur](this[Gr]);return}t[Wh]=1007,this[Ur](t)}});var Wr=ae((iP,Fo)=>{"use strict";var{isUtf8:Kh}=fe("buffer"),{hasBlob:fv}=Yt(),hv=[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 xv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Rd(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 pv(t){return fv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Fo.exports={isBlob:pv,isValidStatusCode:xv,isValidUTF8:Rd,tokenChars:hv};if(Kh)Fo.exports.isValidUTF8=function(t){return t.length<24?Rd(t):Kh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=fe("utf-8-validate");Fo.exports.isValidUTF8=function(e){return e.length<32?Rd(e):t(e)}}catch{}});var Ld=ae((sP,Qh)=>{"use strict";var{Writable:gv}=fe("stream"),$h=Hr(),{BINARY_TYPES:mv,EMPTY_BUFFER:Vh,kStatusCode:wv,kWebSocket:_v}=Yt(),{concat:Cd,toArrayBuffer:yv,unmask:Ev}=Zi(),{isValidStatusCode:bv,isValidUTF8:Jh}=Wr(),zo=Buffer[Symbol.species],ft=0,Zh=1,Yh=2,Xh=3,Pd=4,Dd=5,Uo=6,Od=class extends gv{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[_v]=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=ft}_write(e,n,i){if(this._opcode===8&&this._state==ft)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new zo(i.buffer,i.byteOffset+e,i.length-e),new zo(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=n.length-e;e>=i.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new zo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ft:this.getInfo(e);break;case Zh:this.getPayloadLength16(e);break;case Yh:this.getPayloadLength64(e);break;case Xh:this.getMask();break;case Pd:this.getData(e);break;case Dd:case Uo: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[$h.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=Zh:this._payloadLength===127?this._state=Yh: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=Xh:this._state=Pd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Pd}getData(e){let n=Vh;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&&Ev(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Dd,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[$h.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 d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}this._fragments.push(c)}this.dataMessage(n),this._state===ft&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ft;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=Cd(i,n):this._binaryType==="arraybuffer"?o=yv(Cd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ft):(this._state=Uo,setImmediate(()=>{this.emit("message",o,!0),this._state=ft,this.startLoop(e)}))}else{let o=Cd(i,n);if(!this._skipUTF8Validation&&!Jh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Dd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ft):(this._state=Uo,setImmediate(()=>{this.emit("message",o,!1),this._state=ft,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Vh),this.end();else{let i=e.readUInt16BE(0);if(!bv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(c);return}let o=new zo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Jh(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=ft;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ft):(this._state=Uo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ft,this.startLoop(n)}))}createError(e,n,i,o,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=c,d[wv]=o,d}};Qh.exports=Od});var Bd=ae((aP,nx)=>{"use strict";var{Duplex:oP}=fe("stream"),{randomFillSync:vv}=fe("crypto"),ex=Hr(),{EMPTY_BUFFER:Sv,kWebSocket:Iv,NOOP:Av}=Yt(),{isBlob:qr,isValidStatusCode:kv}=Wr(),{mask:tx,toBuffer:Yn}=Zi(),ht=Symbol("kByteLength"),Tv=Buffer.alloc(4),Go=8*1024,Xn,jr=Go,bt=0,Rv=1,Cv=2,Nd=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=bt,this.onerror=Av,this[Iv]=void 0}static frame(e,n){let i,o=!1,c=2,d=!1;n.mask&&(i=n.maskBuffer||Tv,n.generateMask?n.generateMask(i):(jr===Go&&(Xn===void 0&&(Xn=Buffer.alloc(Go)),vv(Xn,0,Go),jr=0),i[0]=Xn[jr++],i[1]=Xn[jr++],i[2]=Xn[jr++],i[3]=Xn[jr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!n.mask||d)&&n[ht]!==void 0?u=n[ht]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.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]=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],d?[x,e]:o?(tx(e,i,x,c,u),[x]):(tx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let c;if(e===void 0)c=Sv;else{if(typeof e!="number"||!kv(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");c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof n=="string"?c.write(n,2):c.set(n,2)}}let d={[ht]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==bt?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):qr(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 d={[ht]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};qr(e)?this._state!==bt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==bt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):qr(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 d={[ht]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};qr(e)?this._state!==bt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==bt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[ex.extensionName],c=n.binary?2:1,d=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):qr(e)?(u=e.size,h=!1):(e=Yn(e),u=e.length,h=Yn.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),n.fin&&(this._firstFragment=!0);let x={[ht]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};qr(e)?this._state!==bt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==bt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[ht],this._state=Cv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Md,this,u,o);return}this._bufferedBytes-=i[ht];let d=Yn(c);n?this.dispatch(d,n,i,o):(this._state=bt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(Pv,this,c,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[ex.extensionName];this._bufferedBytes+=i[ht],this._state=Rv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");Md(this,h,o);return}this._bufferedBytes-=i[ht],this._state=bt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===bt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ht],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ht],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)}};nx.exports=Nd;function Md(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 Pv(t,e,n){Md(t,e,n),t.onerror(e)}});var ux=ae((cP,lx)=>{"use strict";var{kForOnEventAttribute:Xi,kListener:Fd}=Yt(),rx=Symbol("kCode"),ix=Symbol("kData"),sx=Symbol("kError"),ox=Symbol("kMessage"),ax=Symbol("kReason"),Kr=Symbol("kTarget"),cx=Symbol("kType"),dx=Symbol("kWasClean"),Qt=class{constructor(e){this[Kr]=null,this[cx]=e}get target(){return this[Kr]}get type(){return this[cx]}};Object.defineProperty(Qt.prototype,"target",{enumerable:!0});Object.defineProperty(Qt.prototype,"type",{enumerable:!0});var Qn=class extends Qt{constructor(e,n={}){super(e),this[rx]=n.code===void 0?0:n.code,this[ax]=n.reason===void 0?"":n.reason,this[dx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[rx]}get reason(){return this[ax]}get wasClean(){return this[dx]}};Object.defineProperty(Qn.prototype,"code",{enumerable:!0});Object.defineProperty(Qn.prototype,"reason",{enumerable:!0});Object.defineProperty(Qn.prototype,"wasClean",{enumerable:!0});var $r=class extends Qt{constructor(e,n={}){super(e),this[sx]=n.error===void 0?null:n.error,this[ox]=n.message===void 0?"":n.message}get error(){return this[sx]}get message(){return this[ox]}};Object.defineProperty($r.prototype,"error",{enumerable:!0});Object.defineProperty($r.prototype,"message",{enumerable:!0});var Qi=class extends Qt{constructor(e,n={}){super(e),this[ix]=n.data===void 0?null:n.data}get data(){return this[ix]}};Object.defineProperty(Qi.prototype,"data",{enumerable:!0});var Dv={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[Xi]&&o[Fd]===e&&!o[Xi])return;let i;if(t==="message")i=function(c,d){let u=new Qi("message",{data:d?c:c.toString()});u[Kr]=this,Ho(e,this,u)};else if(t==="close")i=function(c,d){let u=new Qn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Kr]=this,Ho(e,this,u)};else if(t==="error")i=function(c){let d=new $r("error",{error:c,message:c.message});d[Kr]=this,Ho(e,this,d)};else if(t==="open")i=function(){let c=new Qt("open");c[Kr]=this,Ho(e,this,c)};else return;i[Xi]=!!n[Xi],i[Fd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Fd]===e&&!n[Xi]){this.removeListener(t,n);break}}};lx.exports={CloseEvent:Qn,ErrorEvent:$r,Event:Qt,EventTarget:Dv,MessageEvent:Qi};function Ho(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Wo=ae((dP,fx)=>{"use strict";var{tokenChars:es}=Wr();function Bt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Ov(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,c=!1,d,u,h=-1,x=-1,m=-1,g=0;for(;g<t.length;g++)if(x=t.charCodeAt(g),d===void 0)if(m===-1&&es[x]===1)h===-1&&(h=g);else if(g!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=g);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${g}`);m===-1&&(m=g);let _=t.slice(h,m);x===44?(Bt(e,_,n),n=Object.create(null)):d=_,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);else if(u===void 0)if(m===-1&&es[x]===1)h===-1&&(h=g);else if(x===32||x===9)m===-1&&h!==-1&&(m=g);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${g}`);m===-1&&(m=g),Bt(n,t.slice(h,m),!0),x===44&&(Bt(e,d,n),n=Object.create(null),d=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,g),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(o){if(es[x]!==1)throw new SyntaxError(`Unexpected character at index ${g}`);h===-1?h=g:i||(i=!0),o=!1}else if(c)if(es[x]===1)h===-1&&(h=g);else if(x===34&&h!==-1)c=!1,m=g;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(x===34&&t.charCodeAt(g-1)===61)c=!0;else if(m===-1&&es[x]===1)h===-1&&(h=g);else if(h!==-1&&(x===32||x===9))m===-1&&(m=g);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${g}`);m===-1&&(m=g);let _=t.slice(h,m);i&&(_=_.replace(/\\/g,""),i=!1),Bt(n,u,_),x===44&&(Bt(e,d,n),n=Object.create(null),d=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=g);let S=t.slice(h,m);return d===void 0?Bt(e,S,n):(u===void 0?Bt(n,S,!0):i?Bt(n,u,S.replace(/\\/g,"")):Bt(n,u,S),Bt(e,d,n)),e}function Lv(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(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fx.exports={format:Lv,parse:Ov}});var $o=ae((fP,Ix)=>{"use strict";var Nv=fe("events"),Mv=fe("https"),Bv=fe("http"),px=fe("net"),Fv=fe("tls"),{randomBytes:zv,createHash:Uv}=fe("crypto"),{Duplex:lP,Readable:uP}=fe("stream"),{URL:zd}=fe("url"),Cn=Hr(),Gv=Ld(),Hv=Bd(),{isBlob:Wv}=Wr(),{BINARY_TYPES:hx,CLOSE_TIMEOUT:qv,EMPTY_BUFFER:qo,GUID:jv,kForOnEventAttribute:Ud,kListener:Kv,kStatusCode:$v,kWebSocket:He,NOOP:gx}=Yt(),{EventTarget:{addEventListener:Vv,removeEventListener:Jv}}=ux(),{format:Zv,parse:Yv}=Wo(),{toBuffer:Xv}=Zi(),mx=Symbol("kAborted"),Gd=[8,13],en=["CONNECTING","OPEN","CLOSING","CLOSED"],Qv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends Nv{constructor(e,n,i){super(),this._binaryType=hx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=qo,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]),_x(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){hx.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 Gv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new Hv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[He]=this,c[He]=this,e[He]=this,o.on("conclude",nS),o.on("drain",rS),o.on("error",iS),o.on("message",sS),o.on("ping",oS),o.on("pong",aS),c.onerror=cS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bx),e.on("data",Ko),e.on("end",vx),e.on("error",Sx),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[Cn.extensionName]&&this._extensions[Cn.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){ot(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())}),Ex(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){Hd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||qo,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){Hd(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||qo,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){Hd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Cn.extensionName]||(o.compress=!1),this._sender.send(e||qo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ot(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,"CONNECTING",{enumerable:!0,value:en.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:en.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:en.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:en.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ud])return e[Kv];return null},set(e){for(let n of this.listeners(t))if(n[Ud]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Ud]:!0})}})});we.prototype.addEventListener=Vv;we.prototype.removeEventListener=Jv;Ix.exports=we;function _x(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qv,protocolVersion:Gd[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,!Gd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Gd.join(", ")})`);let c;if(e instanceof zd)c=e;else try{c=new zd(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 I=new SyntaxError(h);if(t._redirects===0)throw I;jo(t,I);return}let x=d?443:80,m=zv(16).toString("base64"),g=d?Mv.request:Bv.request,S=new Set,_;if(o.createConnection=o.createConnection||(d?tS:eS),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 Cn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Zv({[Cn.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!Qv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(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 v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,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&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),v=t._req=g(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=g(o);o.timeout&&v.on("timeout",()=>{ot(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[mx]||(v=t._req=null,jo(t,I))}),v.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ot(t,v,"Maximum redirects exceeded");return}v.abort();let P;try{P=new zd(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);jo(t,R);return}_x(t,P,n,i)}else t.emit("unexpected-response",v,I)||ot(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==we.CONNECTING)return;v=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){ot(t,A,"Invalid Upgrade header");return}let E=Uv("sha1").update(m+jv).digest("base64");if(I.headers["sec-websocket-accept"]!==E){ot(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],O;if(R!==void 0?S.size?S.has(R)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){ot(t,A,O);return}R&&(t._protocol=R);let B=I.headers["sec-websocket-extensions"];if(B!==void 0){if(!_){ot(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=Yv(B)}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}let $=Object.keys(N);if($.length!==1||$[0]!==Cn.extensionName){ot(t,A,"Server indicated an extension that was not requested");return}try{_.accept(N[Cn.extensionName])}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cn.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function jo(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function eS(t){return t.path=t.socketPath,px.connect(t)}function tS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=px.isIP(t.host)?"":t.host),Fv.connect(t)}function ot(t,e,n){t._readyState=we.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ot),e.setHeader?(e[mx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(jo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Hd(t,e,n){if(e){let i=Wv(e)?e.size:Xv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${en[t.readyState]})`);process.nextTick(n,i)}}function nS(t,e){let n=this[He];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[He]!==void 0&&(n._socket.removeListener("data",Ko),process.nextTick(yx,n._socket),t===1005?n.close():n.close(t,e))}function rS(){let t=this[He];t.isPaused||t._socket.resume()}function iS(t){let e=this[He];e._socket[He]!==void 0&&(e._socket.removeListener("data",Ko),process.nextTick(yx,e._socket),e.close(t[$v])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function xx(){this[He].emitClose()}function sS(t,e){this[He].emit("message",t,e)}function oS(t){let e=this[He];e._autoPong&&e.pong(t,!this._isServer,gx),e.emit("ping",t)}function aS(t){this[He].emit("pong",t)}function yx(t){t.resume()}function cS(t){let e=this[He];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,Ex(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ex(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bx(){let t=this[He];if(this.removeListener("close",bx),this.removeListener("data",Ko),this.removeListener("end",vx),t._readyState=we.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[He]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",xx),t._receiver.on("finish",xx))}function Ko(t){this[He]._receiver.write(t)||this.pause()}function vx(){let t=this[He];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function Sx(){let t=this[He];this.removeListener("error",Sx),this.on("error",gx),t&&(t._readyState=we.CLOSING,this.destroy())}});var Rx=ae((xP,Tx)=>{"use strict";var hP=$o(),{Duplex:dS}=fe("stream");function Ax(t){t.emit("close")}function lS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function kx(t){this.removeListener("error",kx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function uS(t,e){let n=!0,i=new dS({...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||(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(Ax,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(o),process.nextTick(Ax,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,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,d)});return}t.send(o,d)},i.on("end",lS),i.on("error",kx),i}Tx.exports=uS});var Wd=ae((pP,Cx)=>{"use strict";var{tokenChars:fS}=Wr();function hS(t){let e=new Set,n=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&fS[d]===1)n===-1&&(n=o);else if(o!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=o);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(n,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Cx.exports={parse:hS}});var Bx=ae((mP,Mx)=>{"use strict";var xS=fe("events"),Vo=fe("http"),{Duplex:gP}=fe("stream"),{createHash:pS}=fe("crypto"),Px=Wo(),er=Hr(),gS=Wd(),mS=$o(),{CLOSE_TIMEOUT:wS,GUID:_S,kWebSocket:yS}=Yt(),ES=/^[+/0-9A-Za-z]{22}==$/,Dx=0,Ox=1,Nx=2,qd=class extends xS{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:wS,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=Vo.createServer((i,o)=>{let c=Vo.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=bS(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=Dx}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===Nx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ts,this);return}if(e&&this.once("close",e),this._state!==Ox)if(this._state=Ox,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(ts,this):process.nextTick(ts,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ts(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",Lx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){tr(this,e,n,400,"Invalid Upgrade header");return}if(c===void 0||!ES.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)){ns(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=gS.parse(h)}catch{tr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],g={};if(this.options.perMessageDeflate&&m!==void 0){let S=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Px.parse(m);_[er.extensionName]&&(S.accept(_[er.extensionName]),g[er.extensionName]=S)}catch{tr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(_,v,I,A)=>{if(!_)return ns(n,v||401,I,A);this.completeUpgrade(g,c,x,e,n,i,o)});return}if(!this.options.verifyClient(S))return ns(n,401)}this.completeUpgrade(g,c,x,e,n,i,o)}completeUpgrade(e,n,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[yS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Dx)return ns(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${pS("sha1").update(n+_S).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let g=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;g&&(x.push(`Sec-WebSocket-Protocol: ${g}`),m._protocol=g)}if(e[er.extensionName]){let g=e[er.extensionName].params,S=Px.format({[er.extensionName]:[g]});x.push(`Sec-WebSocket-Extensions: ${S}`),m._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
8
+ var qm=Object.create;var Oa=Object.defineProperty;var jm=Object.getOwnPropertyDescriptor;var Wm=Object.getOwnPropertyNames;var Km=Object.getPrototypeOf,$m=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),La=(t,e)=>{for(var r in e)Oa(t,r,{get:e[r],enumerable:!0})},Vm=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wm(e))!$m.call(t,o)&&o!==r&&Oa(t,o,{get:()=>e[o],enumerable:!(i=jm(e,o))||i.enumerable});return t};var qt=(t,e,r)=>(r=t!=null?qm(Km(t)):{},Vm(e||!t||!t.__esModule?Oa(r,"default",{value:t,enumerable:!0}):r,t));function Ze(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ar=nt(()=>{"use strict"});import{createWriteStream as Jm,mkdirSync as Zm,readdirSync as Ym,unlinkSync as Xm}from"node:fs";import{join as Tl}from"node:path";function Pn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function cr(t,e){return`${t}-${e}.log`}function Na(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function Qm(t,e,r){let i=c=>{let[d,u,f]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>r}function hs(t,e,r,i){let o;try{o=Ym(t)}catch{return}for(let c of o){let d=Na(c,e);if(d&&Qm(d,r,i))try{Xm(Tl(t,c))}catch{}}}var ri,Ma=nt(()=>{"use strict";ri=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Pn(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{Zm(this.dir,{recursive:!0});let r=Jm(Tl(this.dir,cr(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&&hs(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 eg,mkdirSync as tg}from"node:fs";import{join as ng}from"node:path";function Rl(t){let e=t.retentionDays??sg,r=t.clock??(()=>Pn(new Date));ms={bridgeSink:new ri(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ri(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();hs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])hs(t.agentLogsDir(o),"agent",i,e)}function og(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Dl(t){Ba=t}function Pl(t){return dr[Ba]<=dr[t]}function Ol(t,e){let r=dr[t];return r===void 0?!0:r>=dr[e]}function gs(t){Cl={...t}}function Ll(t){let e=(u,f=2)=>String(u).padStart(f,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),d=e(o%60);return`${Pn(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:Ll(new Date),level:e,module:r,msg:i,...o})}
11
+ `;tg(t,{recursive:!0}),eg(ng(t,cr("bridge",Pn(new Date))),c)}catch{}}function ag(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ps(t,e,r,i,o){if(dr[t]<dr[Ba])return;let c=`${JSON.stringify({ts:Ll(new Date),level:t,module:e,msg:r,...Cl,...i})}
12
+ `;if(ms){let d=ag(o,i),u=d?og(ms,d):ms.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?ig.write(c):rg.write(c)}function G(t,e){return{debug:(r,i)=>ps("debug",t,r,i,e),info:(r,i)=>ps("info",t,r,i,e),warn:(r,i)=>ps("warn",t,r,i,e),error:(r,i)=>ps("error",t,r,i,e),child:r=>G(`${t}.${r}`,e),forAgent:r=>G(t,r)}}var dr,Ba,rg,ig,Cl,sg,ms,te=nt(()=>{"use strict";ar();Ma();dr={debug:10,info:20,warn:30,error:40},Ba=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),rg=process.stdout,ig=process.stderr,Cl={},sg=Ze("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ms=null});var k,$e=nt(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Fl={};La(Fl,{ACP_WRAPPER_NPM_PACKAGES:()=>ws,_resetAcpInstallerForTests:()=>xg,_setBinaryPathCacheForTests:()=>hg,buildAcpSpawn:()=>si,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>_s,pickWhichLine:()=>Ua,probeAcpVersion:()=>fg,resolveAcpCommand:()=>Bl});import{readFileSync as Nl}from"node:fs";import{createRequire as cg}from"node:module";import{dirname as dg,resolve as lg}from"node:path";function Ua(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 ug(t){let e=Ml.resolve(`${t.npmPackage}/package.json`),r=dg(e),i=JSON.parse(Nl(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 lg(r,o)}async function lr(t,e){let r=za[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ii.get(t);if(i)return i;try{let o=ug(r);return ii.set(t,o),Fa.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Fa.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(o)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:o})}}async function fg(t){let e=za[t];if(e)try{let r=Ml.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Nl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Fa.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function _s(t){return ii.get(t)}function Bl(t,e){if(e)return e;let r=_s(t);if(!r)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function si(t,e,r){if(e)return{command:e,args:[...r]};let i=Bl(t);return{command:process.execPath,args:[i,...r]}}function xg(){ii.clear()}function hg(t,e){ii.set(t,e)}var Fa,za,ws,Ml,ii,ln=nt(()=>{"use strict";$e();te();Fa=G("agents.acp-installer"),za={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ws=Object.values(za).filter(t=>t!==void 0).map(t=>t.npmPackage),Ml=cg(import.meta.url),ii=new Map});import{chmod as mg,mkdir as gg,readFile as wg,rename as _g,rm as yg,writeFile as bg}from"node:fs/promises";import{dirname as Eg}from"node:path";async function ur(t){try{let e=await wg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ut(t,e,r){await gg(Eg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await bg(i,e,{encoding:"utf8",mode:r?.mode}),await _g(i,t),r?.mode!==void 0&&await mg(t,r.mode)}catch(o){throw await yg(i,{force:!0}).catch(()=>{}),o}}async function fr(t,e,r){await ut(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var jt=nt(()=>{"use strict"});import{promises as Gl,readdirSync as vg}from"node:fs";import{homedir as Sg}from"node:os";import{sep as Ig,join as Ce,resolve as Hl}from"node:path";function Z(t){let e=t??Sg(),r=Ce(e,".coze"),i=Ce(r,"bridge"),o=Ce(i,"lib"),c=Ce(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ce(o,"index.js"),binDir:Ce(i,"bin"),pidFile:Ce(i,"bridge.pid"),portFile:Ce(i,"bridge.port"),tokenFile:Ce(i,"bridge.token"),patTokenFile:Ce(i,"pat-token"),agentEnvFile:Ce(i,"agent-env.json"),logFile:Ce(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Ce(c,"daemon-stdio.log"),installLock:Ce(i,"install.lock"),configFile:Ce(i,"config.json"),agentsRoot:Ce(r,"agents")}}function ze(t,e=Z()){let r=Ce(e.agentsRoot,t);return{root:r,config:Ce(r,"config.json"),workspace:Ce(r,"workspace"),logs:Ce(r,"logs")}}function ys(t=Z()){try{return vg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function oi(t,e){let r=await Gl.realpath(Hl(t)).catch(()=>null);if(!r)return!1;let i=await Gl.realpath(Hl(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+Ig)}var Re=nt(()=>{"use strict"});var Es={};La(Es,{AGENT_CONFIG_FILE_MODE:()=>bs,enforceAgentConfigMode:()=>Tg,loadAgentConfig:()=>ve,persistAgentSessions:()=>ai,persistAgentSkills:()=>ci,saveAgentConfig:()=>Ue});import{chmod as Ag,stat as kg}from"node:fs/promises";function ve(t,e){return ur(ze(t,e).config)}function Ue(t,e){return fr(ze(t.agentId,e).config,t,{mode:bs})}async function Tg(t,e){if(process.platform==="win32")return;let r=ze(t,e).config;try{let i=await kg(r);if(!i.isFile())return;let o=i.mode&511;o!==bs&&(await Ag(r,bs),ql.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;ql.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ai(t,e,r){let i=await ve(t,r);i&&(i.sessions=Object.fromEntries(e),await Ue(i,r))}async function ci(t,e,r){let i=await ve(t,r);i&&(i.skills=e,await Ue(i,r))}var ql,bs,Wt=nt(()=>{"use strict";jt();te();Re();ql=G("agent-config"),bs=384});var qa=ae((AI,Kl)=>{Kl.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 Ss=ae(Vl=>{var $l={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 Lg(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($l))Vl[t]=Lg($l[t])});var Ql=ae((TI,Xl)=>{var Ng=fe("fs"),Me=fe("path"),Jl=qa(),Mg=Ss(),Bg=typeof process=="object"&&process.platform==="win32",Zl=t=>typeof t=="object"&&t!==null,Yl=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 Se(t){this.sep=Me.sep,this.fs=Ng,Zl(t)&&Zl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Xl.exports=Se;Se.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 Mg.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Se.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=Me.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,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,f){if(d&&f.isDirectory())return o(!1);var h=Me.dirname(t);c.fs.exists(h,function(g){g||c.makeDir(h),c.fs.open(t,"w",438,function(_,v){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){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)})})})})})};Se.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 f=Me.join(i,u),h=e.fs.statSync(f);(!o||o.test(f))&&d.push(Me.normalize(f)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&c&&(d=d.concat(r(f,o,c)))}),d}return r(t,void 0,!0)};Se.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=Me.join(t,u),r.fs.stat(u,function(f,h){if(f)return e(f);h&&(i.push(Me.normalize(u)+(h.isDirectory()?r.sep:"")),h.isDirectory()?r.findFilesAsync(u,function(g,_){if(g)return e(g);i=i.concat(_),--d||e(null,i)}):--d||e(null,i))})})})};Se.prototype.getAttributes=function(){};Se.prototype.setAttributes=function(){};Se.crc32update=function(t,e){return Yl[(t^e)&255]^t>>>8};Se.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Se.crc32update(r,t[i++]);return~r>>>0};Se.methodToString=function(t){switch(t){case Jl.STORED:return"STORED ("+t+")";case Jl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.posix.join(".",e)};Se.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]};Se.sanitize=function(t,e){t=Me.resolve(Me.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Me.normalize(Me.join(t,r.slice(i,o).join(Me.sep)));if(c.indexOf(t)===0)return c}return Me.normalize(Me.join(t,Me.basename(e)))};Se.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Se.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Se.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Se.fromDate2DOS=function(t){let e=0,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};Se.isWin=Bg;Se.crcTable=Yl});var tu=ae((CI,eu)=>{var Fg=fe("path");eu.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=Fg.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 ru=ae((RI,nu)=>{nu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=ae((DI,hr)=>{hr.exports=Ql();hr.exports.Constants=qa();hr.exports.Errors=Ss();hr.exports.FileAttr=tu();hr.exports.decoder=ru()});var su=ae((PI,iu)=>{var un=pr(),U=un.Constants;iu.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,f=0,h=0,g=0,_=0,v=0,y=0,E=0;t|=un.isWin?2560:768,r|=U.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,T=b=>Math.max(0,b)&65535,D=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 r},set flags(b){r=b},get flags_efs(){return(r&U.FLG_EFS)>0},set flags_efs(b){b?r|=U.FLG_EFS:r&=~U.FLG_EFS},get flags_desc(){return(r&U.FLG_DESC)>0},set flags_desc(b){b?r|=U.FLG_DESC:r&=~U.FLG_DESC},get method(){return i},set method(b){switch(b){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=b},get time(){return 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 D(o>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return d},set compressedSize(b){d=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return f},set fileNameLength(b){f=b},get extraLength(){return h},set extraLength(b){h=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return g},set commentLength(b){g=b},get diskNumStart(){return _},set diskNumStart(b){_=A(b)},get inAttr(){return v},set inAttr(b){v=A(b)},get attr(){return y},set attr(b){y=A(b)},get fileAttr(){return(y||0)>>16&4095},get offset(){return E},set offset(b){E=A(b)},get encrypted(){return(r&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+h+g},get realDataOffset(){return E+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var R=b.slice(E,E+U.LOCHDR);if(R.readUInt32LE(0)!==U.LOCSIG)throw un.Errors.INVALID_LOC();I.version=R.readUInt16LE(U.LOCVER),I.flags=R.readUInt16LE(U.LOCFLG),I.flags_desc=(I.flags&U.FLG_DESC)>0,I.method=R.readUInt16LE(U.LOCHOW),I.time=R.readUInt32LE(U.LOCTIM),I.crc=R.readUInt32LE(U.LOCCRC),I.compressedSize=R.readUInt32LE(U.LOCSIZ),I.size=R.readUInt32LE(U.LOCLEN),I.fnameLen=R.readUInt16LE(U.LOCNAM),I.extraLen=R.readUInt16LE(U.LOCEXT);let P=E+U.LOCHDR+I.fnameLen,B=P+I.extraLen;return b.slice(P,B)},loadFromBinary:function(b){if(b.length!==U.CENHDR||b.readUInt32LE(0)!==U.CENSIG)throw un.Errors.INVALID_CEN();t=b.readUInt16LE(U.CENVEM),e=b.readUInt16LE(U.CENVER),r=b.readUInt16LE(U.CENFLG),i=b.readUInt16LE(U.CENHOW),o=b.readUInt32LE(U.CENTIM),c=b.readUInt32LE(U.CENCRC),d=b.readUInt32LE(U.CENSIZ),u=b.readUInt32LE(U.CENLEN),f=b.readUInt16LE(U.CENNAM),h=b.readUInt16LE(U.CENEXT),g=b.readUInt16LE(U.CENCOM),_=b.readUInt16LE(U.CENDSK),v=b.readUInt16LE(U.CENATT),y=b.readUInt32LE(U.CENATX),E=b.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(U.LOCHDR);return b.writeUInt32LE(U.LOCSIG,0),b.writeUInt16LE(e,U.LOCVER),b.writeUInt16LE(r,U.LOCFLG),b.writeUInt16LE(i,U.LOCHOW),b.writeUInt32LE(o,U.LOCTIM),b.writeUInt32LE(c,U.LOCCRC),b.writeUInt32LE(d,U.LOCSIZ),b.writeUInt32LE(u,U.LOCLEN),b.writeUInt16LE(f,U.LOCNAM),b.writeUInt16LE(I.extraLen,U.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(U.CENHDR+f+h+g);return b.writeUInt32LE(U.CENSIG,0),b.writeUInt16LE(t,U.CENVEM),b.writeUInt16LE(e,U.CENVER),b.writeUInt16LE(r,U.CENFLG),b.writeUInt16LE(i,U.CENHOW),b.writeUInt32LE(o,U.CENTIM),b.writeUInt32LE(c,U.CENCRC),b.writeUInt32LE(d,U.CENSIZ),b.writeUInt32LE(u,U.CENLEN),b.writeUInt16LE(f,U.CENNAM),b.writeUInt16LE(h,U.CENEXT),b.writeUInt16LE(g,U.CENCOM),b.writeUInt16LE(_,U.CENDSK),b.writeUInt16LE(v,U.CENATT),b.writeUInt32LE(y,U.CENATX),b.writeUInt32LE(E,U.CENOFF),b},toJSON:function(){let b=function(R){return R+" bytes"};return{made:t,version:e,flags:r,method:un.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(f),extraLength:b(h),commentLength:b(g),diskNumStart:_,inAttr:v,attr:y,offset:E,centralHeaderSize:b(U.CENHDR+f+h+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var au=ae((OI,ou)=>{var mr=pr(),ye=mr.Constants;ou.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 ye.ENDHDR+o},loadFromBinary:function(c){if((c.length!==ye.ENDHDR||c.readUInt32LE(0)!==ye.ENDSIG)&&(c.length<ye.ZIP64HDR||c.readUInt32LE(0)!==ye.ZIP64SIG))throw mr.Errors.INVALID_END();c.readUInt32LE(0)===ye.ENDSIG?(t=c.readUInt16LE(ye.ENDSUB),e=c.readUInt16LE(ye.ENDTOT),r=c.readUInt32LE(ye.ENDSIZ),i=c.readUInt32LE(ye.ENDOFF),o=c.readUInt16LE(ye.ENDCOM)):(t=mr.readBigUInt64LE(c,ye.ZIP64SUB),e=mr.readBigUInt64LE(c,ye.ZIP64TOT),r=mr.readBigUInt64LE(c,ye.ZIP64SIZE),i=mr.readBigUInt64LE(c,ye.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(ye.ENDHDR+o);return c.writeUInt32LE(ye.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ye.ENDSUB),c.writeUInt16LE(e,ye.ENDTOT),c.writeUInt32LE(r,ye.ENDSIZ),c.writeUInt32LE(i,ye.ENDOFF),c.writeUInt16LE(o,ye.ENDCOM),c.fill(" ",ye.ENDHDR),c},toJSON:function(){let c=function(d,u){let f=d.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Wa=ae(ja=>{ja.EntryHeader=su();ja.MainHeader=au()});var du=ae((NI,cu)=>{cu.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),f=0;u.fill(0);for(var h=0;h<c.length;h++){var g=c[h];g.copy(u,f),f+=g.length}i&&i(u)}),o.end(t)}}}});var uu=ae((MI,lu)=>{var zg=+(process.versions?process.versions.node:"").split(".")[0]||0;lu.exports=function(t,e){var r=fe("zlib");let i=zg>=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(f){d.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),h=0;f.fill(0);for(var g=0;g<d.length;g++){var _=d[g];_.copy(f,h),h+=_.length}o&&o(f)}),c.end(t)}}}});var mu=ae((BI,pu)=>{"use strict";var{randomFillSync:fu}=fe("crypto"),Ug=Ss(),Gg=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}),hu=(t,e)=>Math.imul(t,e)>>>0,xu=(t,e)=>Gg[(t^e)&255]^t>>>8,di=()=>typeof fu=="function"?fu(Buffer.alloc(12)):di.node();di.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 Is={genSalt:di};function As(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])}As.prototype.updateKeys=function(t){let e=this.keys;return e[0]=xu(e[0],t),e[1]+=e[0]&255,e[1]=hu(e[1],134775813)+1,e[2]=xu(e[2],e[1]>>>24),t};As.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return hu(t,t^1)>>8&255};function Hg(t){let e=new As(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 qg(t){let e=new As(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 jg(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Hg(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Ug.WRONG_PASSWORD();return i(t.slice(12))}function Wg(t){Buffer.isBuffer(t)&&t.length>=12?Is.genSalt=function(){return t.slice(0,12)}:t==="node"?Is.genSalt=di.node:Is.genSalt=di}function Kg(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=qg(r),c=Is.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)}pu.exports={decrypt:jg,encrypt:Kg,_salter:Wg}});var gu=ae(ks=>{ks.Deflater=du();ks.Inflater=uu();ks.ZipCrypto=mu()});var $a=ae((zI,wu)=>{var ce=pr(),$g=Wa(),Ie=ce.Constants,Ka=gu();wu.exports=function(t,e){var r=new $g.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),h=!0;let g=t,_=typeof g.decoder=="object"?g.decoder:ce.decoder;h=_.hasOwnProperty("efs")?_.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function y(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let R={},P=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(P)==Ie.LOCSIG||e.readUInt32LE(P)==Ie.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(P)==Ie.EXTSIG)R.crc=e.readUInt32LE(P+Ie.EXTCRC),R.compressedSize=e.readUInt32LE(P+Ie.EXTSIZ),R.size=e.readUInt32LE(P+Ie.EXTLEN);else if(e.readUInt16LE(P+12)===19280)R.crc=e.readUInt32LE(P+Ie.EXTCRC-4),R.compressedSize=e.readUInt32LE(P+Ie.EXTSIZ-4),R.size=e.readUInt32LE(P+Ie.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==R.crc)return!1}return!0}function E(b,R,P){if(typeof R>"u"&&typeof b=="string"&&(P=b,b=void 0),c)return b&&R&&R(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var B=v();if(B.length===0)return b&&R&&R(B),B;if(r.encrypted){if(typeof P!="string"&&!Buffer.isBuffer(P))throw ce.Errors.INVALID_PASS_PARAM();B=Ka.ZipCrypto.decrypt(B,r,P)}var M=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(B.copy(M),y(M))return b&&R&&R(M),M;throw b&&R&&R(M,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var J=new Ka.Inflater(B,r.size);if(b)J.inflateAsync(function(V){V.copy(V,0),R&&(y(V)?R(V):R(V,ce.Errors.BAD_CRC()))});else{if(J.inflate(M).copy(M,0),!y(M))throw ce.Errors.BAD_CRC(`"${_.decode(i)}"`);return M}break;default:throw b&&R&&R(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(b,R){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&R&&R(v()),v();if(d.length&&!c){var P;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,P=Buffer.alloc(d.length),d.copy(P),b&&R&&R(P),P;default:case ce.Constants.DEFLATED:var B=new Ka.Deflater(d);if(b)B.deflateAsync(function(J){P=Buffer.alloc(J.length),r.compressedSize=J.length,J.copy(P),R&&R(P)});else{var M=B.deflate();return r.compressedSize=M.length,M}B=null;break}}else if(b&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,R){return ce.readBigUInt64LE(b,R)}function T(b){try{for(var R=0,P,B,M;R+4<b.length;)P=b.readUInt16LE(R),R+=2,B=b.readUInt16LE(R),R+=2,M=b.slice(R,R+B),R+=B,Ie.ID_ZIP64===P&&D(M)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(b){var R,P,B,M;b.length>=Ie.EF_ZIP64_SCOMP&&(R=A(b,Ie.EF_ZIP64_SUNCOMP),r.size===Ie.EF_ZIP64_OR_32&&(r.size=R)),b.length>=Ie.EF_ZIP64_RHO&&(P=A(b,Ie.EF_ZIP64_SCOMP),r.compressedSize===Ie.EF_ZIP64_OR_32&&(r.compressedSize=P)),b.length>=Ie.EF_ZIP64_DSN&&(B=A(b,Ie.EF_ZIP64_RHO),r.offset===Ie.EF_ZIP64_OR_32&&(r.offset=B)),b.length>=Ie.EF_ZIP64_DSN+4&&(M=b.readUInt32LE(Ie.EF_ZIP64_DSN),r.diskNumStart===Ie.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,_.encode);var R=i[i.length-1];c=R===47||R===92,r.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,T(b)},get comment(){return _.decode(o)},set comment(b){if(o=ce.toBuffer(b,_.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var b=_.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){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,R){r.changed?b(d):E(!0,b,R)},set attr(b){r.attr=b},get attr(){return r.attr},set header(b){r.loadFromBinary(b)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var b=r.centralHeaderToBinary(),R=ce.Constants.CENHDR;return i.copy(b,R),R+=i.length,u.copy(b,R),R+=r.extraLength,o.copy(b,R),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let R=r.localHeaderToBinary(),P=Buffer.alloc(R.length+i.length+r.extraLocalLength);return R.copy(P,b),b+=R.length,i.copy(P,b),b+=i.length,f.copy(P,b),b+=f.length,P},toJSON:function(){let b=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:b(e),data:b(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var bu=ae((UI,yu)=>{var _u=$a(),Vg=Wa(),Ve=pr();yu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Vg.MainHeader,d=!1,u=null;let f=new Set,h=e,{noSort:g,decoder:_}=h;t?E(h.readEntries):d=!0;function v(){let A=new Set;for(let T of Object.keys(i)){let D=T.split("/");if(D.pop(),!!D.length)for(let b=0;b<D.length;b++){let R=D.slice(0,b+1).join("/")+"/";A.add(R)}}for(let T of A)if(!(T in i)){let D=new _u(h);D.entryName=T,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,f.add(D)}}function y(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/Ve.Constants.CENHDR)throw Ve.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,T=0;T<r.length;T++){var D=A,b=new _u(h,t);b.header=t.slice(D,D+=Ve.Constants.CENHDR),b.entryName=t.slice(D,D+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(D,D+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(D,D+b.header.commentLength)),A+=b.header.centralHeaderSize,r[T]=b,i[b.entryName]=b}f.clear(),v()}function E(A){var T=t.length-Ve.Constants.ENDHDR,D=Math.max(0,T-65535),b=D,R=t.length,P=-1,B=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(D=0),T;T>=b;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ve.Constants.ENDSIG){P=T,B=T,R=T+Ve.Constants.ENDHDR,b=T-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ve.Constants.END64SIG){b=D;continue}if(t.readUInt32LE(T)===Ve.Constants.ZIP64SIG){P=T,R=T+Ve.readBigUInt64LE(t,T+Ve.Constants.ZIP64SIZE)+Ve.Constants.ZIP64LEAD;break}}if(P==-1)throw Ve.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(P,R)),c.commentLength&&(o=t.slice(B+Ve.Constants.ENDHDR)),A&&y()}function I(){r.length>1&&!g&&r.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||y(),r.filter(A=>!f.has(A))},get comment(){return _.decode(o)},set comment(A){o=Ve.toBuffer(A,_.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,T=!0){d||y();let D=i[A];this.getEntryChildren(D,T).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let T=i[A],D=r.indexOf(T);D>=0&&(r.splice(D,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,T=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&T){let D=[],b=A.entryName;for(let R of r)R.entryName.startsWith(b)&&D.push(R);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],T=[],D=0,b=0;c.size=0,c.offset=0;let R=0;for(let M of this.entries){let J=M.getCompressedData();M.header.offset=b;let V=M.packLocalHeader(),re=V.length+J.length;b+=re,A.push(V),A.push(J);let X=M.packCentralHeader();T.push(X),c.size+=X.length,D+=re+X.length,R++}D+=c.mainHeaderSize,c.offset=b,c.totalEntries=R,b=0;let P=Buffer.alloc(D);for(let M of A)M.copy(P,b),b+=M.length;for(let M of T)M.copy(P,b),b+=M.length;let B=c.toBinary();return o&&o.copy(B,Ve.Constants.ENDHDR),B.copy(P,b),t=P,d=!1,P},toAsyncBuffer:function(A,T,D,b){try{d||y(),I();let R=[],P=[],B=0,M=0,J=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let X=re.shift(),se=X.entryName+X.extra.toString();D&&D(se),X.getCompressedDataAsync(function(oe){b&&b(se),X.header.offset=M;let C=X.packLocalHeader(),z=C.length+oe.length;M+=z,R.push(C),R.push(oe);let H=X.packCentralHeader();P.push(H),c.size+=H.length,B+=z+H.length,J++,V(re)})}else{B+=c.mainHeaderSize,c.offset=M,c.totalEntries=J,M=0;let X=Buffer.alloc(B);R.forEach(function(oe){oe.copy(X,M),M+=oe.length}),P.forEach(function(oe){oe.copy(X,M),M+=oe.length});let se=c.toBinary();o&&o.copy(se,Ve.Constants.ENDHDR),se.copy(X,M),t=X,d=!1,A(X)}};V(Array.from(this.entries))}catch(R){T(R)}}}}});var Su=ae((GI,vu)=>{var Ee=pr(),be=fe("path"),Jg=$a(),Zg=bu(),On=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),Eu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Yg=(...t)=>Ee.findLast(t,e=>typeof e=="function"),Xg={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};vu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Xg);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Ee.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Ee(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ee.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Ee.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Ee.Errors.INVALID_FILENAME();let c=new Zg(r,i),{canonical:d,sanitize:u,zipnamefix:f}=Ee;function h(y){if(y&&c){var E;if(typeof y=="string"&&(E=c.getEntry(be.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(E=c.getEntry(y.entryName)),E)return E}return null}function g(y){let{join:E,normalize:I,sep:A}=be.posix;return E(be.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function _(y){return y instanceof RegExp?(function(E){return function(I){return E.test(I)}})(y):typeof y!="function"?()=>!0:y}let v=(y,E)=>{let I=E.slice(-1);return I=I===o.sep?o.sep:"",be.relative(y,E)+I};return{readFile:function(y,E){var I=h(y);return I&&I.getData(E)||null},childCount:function(y){let E=h(y);if(E)return c.getChildCount(E)},readFileAsync:function(y,E){var I=h(y);I?I.getDataAsync(E):E(null,"getEntry failed for:"+y)},readAsText:function(y,E){var I=h(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(y,E,I){var A=h(y);A?A.getDataAsync(function(T,D){if(D){E(T,D);return}T&&T.length?E(T.toString(I||"utf8")):E("")}):E("")},deleteFile:function(y,E=!0){var I=h(y);I&&c.deleteFile(I.entryName,E)},deleteEntry:function(y){var E=h(y);E&&c.deleteEntry(E.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,E){var I=h(y);I&&(I.comment=E)},getZipEntryComment:function(y){var E=h(y);return E&&E.comment||""},updateFile:function(y,E){var I=h(y);I&&I.setData(E)},addLocalFile:function(y,E,I,A){if(o.fs.existsSync(y)){E=E?g(E):"";let T=be.win32.basename(be.win32.normalize(y));E+=I||T;let D=o.fs.statSync(y),b=D.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);D.isDirectory()&&(E+=o.sep),this.addFile(E,b,A,D)}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,E){y=typeof y=="object"?y:{localPath:y};let I=be.resolve(y.localPath),{comment:A}=y,{zipPath:T,zipName:D}=y,b=this;o.fs.stat(I,function(R,P){if(R)return E(R,!1);T=T?g(T):"";let B=be.win32.basename(be.win32.normalize(I));if(T+=D||B,P.isFile())o.fs.readFile(I,function(M,J){return M?E(M,!1):(b.addFile(T,J,A,P),setImmediate(E,void 0,!0))});else if(P.isDirectory())return T+=o.sep,b.addFile(T,Buffer.alloc(0),A,P),setImmediate(E,void 0,!0)})},addLocalFolder:function(y,E,I){if(I=_(I),E=E?g(E):"",y=be.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),T=this;if(A.length)for(let D of A){let b=be.join(E,v(y,D));I(b)&&T.addLocalFile(D,be.dirname(b))}}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,E,I,A){A=_(A),I=I?g(I):"",y=be.normalize(y);var T=this;o.fs.open(y,"r",function(D){if(D&&D.code==="ENOENT")E(void 0,Ee.Errors.FILE_NOT_FOUND(y));else if(D)E(void 0,D);else{var b=o.findFiles(y),R=-1,P=function(){if(R+=1,R<b.length){var B=b[R],M=v(y,B).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(B,function(J,V){J&&E(void 0,J),V.isFile()?o.fs.readFile(B,function(re,X){re?E(void 0,re):(T.addFile(I+M,X,"",V),P())}):(T.addFile(I+M+"/",Buffer.alloc(0),"",V),P())}):process.nextTick(()=>{P()})}else E(!0,void 0)};P()}})},addLocalFolderAsync2:function(y,E){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=be.resolve(g(y.localPath));let{zipPath:A,filter:T,namefix:D}=y;T instanceof RegExp?T=(function(P){return function(B){return P.test(B)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=P=>P.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=P=>P);let b=P=>be.join(A,D(v(localPath,P))),R=P=>be.win32.basename(be.win32.normalize(D(P)));o.fs.open(localPath,"r",function(P){P&&P.code==="ENOENT"?E(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):P?E(void 0,P):o.findFilesAsync(localPath,function(B,M){if(B)return E(B);M=M.filter(J=>T(b(J))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(J,V){return function(re,X){if(re||X===!1)return setImmediate(J,re,!1);I.addLocalFileAsync({localPath:V,zipPath:be.dirname(b(V)),zipName:R(V)},J)}},E))})})},addLocalFolderPromise:function(y,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},E),(T,D)=>{T&&A(T),D&&I(this)})})},addFile:function(y,E,I,A){y=f(y);let T=h(y),D=T!=null;D||(T=new Jg(i),T.entryName=y),T.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(T.header.time=A.mtime);var R=T.isDirectory?16:0;let P=T.isDirectory?16384:32768;return b?P|=4095&A.mode:typeof A=="number"?P|=4095&A:P|=T.isDirectory?493:420,R=(R|P<<16)>>>0,T.attr=R,T.setData(E),D||c.setEntry(T),T},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return h(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,E,I,A,T,D){A=On(!1,A),T=On(!1,T),I=On(!0,I),D=Eu(T,D);var b=h(y);if(!b)throw Ee.Errors.NO_ENTRY();var R=d(b.entryName),P=u(E,D&&!b.isDirectory?D:I?R:be.basename(R));if(b.isDirectory){var B=c.getEntryChildren(b);return B.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw Ee.Errors.CANT_EXTRACT_FILE();var X=d(V.entryName),se=u(E,I?X:be.basename(X));let oe=T?V.header.fileAttr:void 0;o.writeFileTo(se,re,A,oe)}),!0}var M=b.getData(c.password);if(!M)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(P)&&!A)throw Ee.Errors.CANT_OVERRIDE();let J=T?y.header.fileAttr:void 0;return o.writeFileTo(P,M,A,J),!0},test:function(y){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,E,I,A){if(I=On(!1,I),A=Eu(I,A),E=On(!1,E),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(T){var D=u(y,d(T.entryName));if(T.isDirectory){o.makeDir(D);return}var b=T.getData(A);if(!b)throw Ee.Errors.CANT_EXTRACT_FILE();let R=I?T.header.fileAttr:void 0;o.writeFileTo(D,b,E,R);try{o.fs.utimesSync(D,T.header.time,T.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,E,I,A){if(A=Yg(E,I,A),I=On(!1,I),E=On(!1,E),!A)return new Promise((P,B)=>{this.extractAllToAsync(y,E,I,function(M){M?B(M):P(this)})});if(!c){A(Ee.Errors.NO_ZIP());return}y=be.resolve(y);let T=P=>u(y,be.normalize(d(P.entryName))),D=(P,B)=>new Error(P+': "'+B+'"'),b=[],R=[];c.entries.forEach(P=>{P.isDirectory?b.push(P):R.push(P)});for(let P of b){let B=T(P),M=I?P.header.fileAttr:void 0;try{o.makeDir(B),M&&o.fs.chmodSync(B,M),o.fs.utimesSync(B,P.header.time,P.header.time)}catch{A(D("Unable to create folder",B))}}R.reverse().reduce(function(P,B){return function(M){if(M)P(M);else{let J=be.normalize(d(B.entryName)),V=u(y,J);B.getDataAsync(function(re,X){if(X)P(X);else if(!re)P(Ee.Errors.CANT_EXTRACT_FILE());else{let se=I?B.header.fileAttr:void 0;o.writeFileToAsync(V,re,E,se,function(oe){oe||P(D("Unable to write file",V)),o.fs.utimes(V,B.header.time,B.header.time,function(C){C?P(D("Unable to set times",V)):P()})})}})}}},A)()},writeZip:function(y,E){if(arguments.length===1&&typeof y=="function"&&(E=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((T,D)=>{!y&&i.filename&&(y=i.filename),y||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let R=P=>P?T(P):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(y,b,I,A,R)},D)})},toBufferPromise:function(){return new Promise((y,E)=>{c.toAsyncBuffer(y,E)})},toBuffer:function(y,E,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,E,I,A),null):c.compressToBuffer()}}}});import{execFile as iy,spawn as sy,spawnSync as sk}from"node:child_process";import{promisify as oy}from"node:util";function cy(t){if(process.platform!=="win32")return!1;if(jf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(jf,"").toLowerCase();return ay.has(r)}function Wf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return cy(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function st(t,e=[],r={}){return sy(t,e,Wf(t,r))}function Kf(t,e=[],r={}){return dy(t,e,Wf(t,r))}var ay,jf,dy,Xt=nt(()=>{"use strict";ay=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),jf=/\.(cmd|bat|ps1)$/i;dy=oy(iy)});var en=ae((dR,Gx)=>{"use strict";var zx=["nodebuffer","arraybuffer","fragments"],Ux=typeof Blob<"u";Ux&&zx.push("blob");Gx.exports={BINARY_TYPES:zx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ux,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qi=ae((lR,zo)=>{"use strict";var{EMPTY_BUFFER:$E}=en(),vd=Buffer[Symbol.species];function VE(t,e){if(t.length===0)return $E;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 vd(r.buffer,r.byteOffset,i):r}function Hx(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function qx(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function JE(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Sd(t){if(Sd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vd(t):ArrayBuffer.isView(t)?e=new vd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Sd.readOnly=!1),e}zo.exports={concat:VE,mask:Hx,toArrayBuffer:JE,toBuffer:Sd,unmask:qx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=fe("bufferutil");zo.exports.mask=function(e,r,i,o,c){c<48?Hx(e,r,i,o,c):t.mask(e,r,i,o,c)},zo.exports.unmask=function(e,r){e.length<32?qx(e,r):t.unmask(e,r)}}catch{}});var Kx=ae((uR,Wx)=>{"use strict";var jx=Symbol("kDone"),Id=Symbol("kRun"),Ad=class{constructor(e){this[jx]=()=>{this.pending--,this[Id]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Id]()}[Id](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[jx])}}};Wx.exports=Ad});var qr=ae((fR,Zx)=>{"use strict";var es=fe("zlib"),$x=Qi(),ZE=Kx(),{kStatusCode:Vx}=en(),YE=Buffer[Symbol.species],XE=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),tn=Symbol("total-length"),Gr=Symbol("callback"),Tn=Symbol("buffers"),Hr=Symbol("error"),Uo,kd=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,!Uo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Uo=new ZE(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[Gr];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){Uo.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Uo.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"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=es.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Go]=this,this._inflate[tn]=0,this._inflate[Tn]=[],this._inflate.on("error",ev),this._inflate.on("data",Jx)}this._inflate[Gr]=i,this._inflate.write(e),r&&this._inflate.write(XE),this._inflate.flush(()=>{let c=this._inflate[Hr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=$x.concat(this._inflate[Tn],this._inflate[tn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[tn]=0,this._inflate[Tn]=[],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"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=es.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[tn]=0,this._deflate[Tn]=[],this._deflate.on("data",QE)}this._deflate[Gr]=i,this._deflate.write(e),this._deflate.flush(es.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=$x.concat(this._deflate[Tn],this._deflate[tn]);r&&(c=new YE(c.buffer,c.byteOffset,c.length-4)),this._deflate[Gr]=null,this._deflate[tn]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Zx.exports=kd;function QE(t){this[Tn].push(t),this[tn]+=t.length}function Jx(t){if(this[tn]+=t.length,this[Go]._maxPayload<1||this[tn]<=this[Go]._maxPayload){this[Tn].push(t);return}this[Hr]=new RangeError("Max payload size exceeded"),this[Hr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hr][Vx]=1009,this.removeListener("data",Jx),this.reset()}function ev(t){if(this[Go]._inflate=null,this[Hr]){this[Gr](this[Hr]);return}t[Vx]=1007,this[Gr](t)}});var jr=ae((xR,Ho)=>{"use strict";var{isUtf8:Yx}=fe("buffer"),{hasBlob:tv}=en(),nv=[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 rv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Td(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 iv(t){return tv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ho.exports={isBlob:iv,isValidStatusCode:rv,isValidUTF8:Td,tokenChars:nv};if(Yx)Ho.exports.isValidUTF8=function(t){return t.length<24?Td(t):Yx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=fe("utf-8-validate");Ho.exports.isValidUTF8=function(e){return e.length<32?Td(e):t(e)}}catch{}});var Od=ae((hR,ih)=>{"use strict";var{Writable:sv}=fe("stream"),Xx=qr(),{BINARY_TYPES:ov,EMPTY_BUFFER:Qx,kStatusCode:av,kWebSocket:cv}=en(),{concat:Cd,toArrayBuffer:dv,unmask:lv}=Qi(),{isValidStatusCode:uv,isValidUTF8:eh}=jr(),qo=Buffer[Symbol.species],mt=0,th=1,nh=2,rh=3,Rd=4,Dd=5,jo=6,Pd=class extends sv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ov[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[cv]=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=mt}_write(e,r,i){if(this._opcode===8&&this._state==mt)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 qo(i.buffer,i.byteOffset+e,i.length-e),new qo(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 qo(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 mt:this.getInfo(e);break;case th:this.getPayloadLength16(e);break;case nh:this.getPayloadLength64(e);break;case rh:this.getMask();break;case Rd:this.getData(e);break;case Dd:case jo: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[Xx.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=th:this._payloadLength===127?this._state=nh: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=rh:this._state=Rd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Rd}getData(e){let r=Qx;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&&lv(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Dd,this.decompress(r,e);return}if(r.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(r)}this.dataMessage(e)}decompress(e,r){this._extensions[Xx.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}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let d=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(d);return}this._fragments.push(c)}this.dataMessage(r),this._state===mt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=mt;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=Cd(i,r):this._binaryType==="arraybuffer"?o=dv(Cd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=mt):(this._state=jo,setImmediate(()=>{this.emit("message",o,!0),this._state=mt,this.startLoop(e)}))}else{let o=Cd(i,r);if(!this._skipUTF8Validation&&!eh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Dd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=mt):(this._state=jo,setImmediate(()=>{this.emit("message",o,!1),this._state=mt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Qx),this.end();else{let i=e.readUInt16BE(0);if(!uv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new qo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!eh(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=mt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=mt):(this._state=jo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=mt,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[av]=o,d}};ih.exports=Pd});var Md=ae((mR,ah)=>{"use strict";var{Duplex:pR}=fe("stream"),{randomFillSync:fv}=fe("crypto"),{types:{isUint8Array:xv}}=fe("util"),sh=qr(),{EMPTY_BUFFER:hv,kWebSocket:pv,NOOP:mv}=en(),{isBlob:Wr,isValidStatusCode:gv}=jr(),{mask:oh,toBuffer:Yn}=Qi(),gt=Symbol("kByteLength"),wv=Buffer.alloc(4),Wo=8*1024,Xn,Kr=Wo,kt=0,_v=1,yv=2,Ld=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=kt,this.onerror=mv,this[pv]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||wv,r.generateMask?r.generateMask(i):(Kr===Wo&&(Xn===void 0&&(Xn=Buffer.alloc(Wo)),fv(Xn,0,Wo),Kr=0),i[0]=Xn[Kr++],i[1]=Xn[Kr++],i[2]=Xn[Kr++],i[3]=Xn[Kr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[gt]!==void 0?u=r[gt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let f=u;u>=65536?(c+=8,f=127):u>125&&(c+=2,f=126);let h=Buffer.allocUnsafe(o?u+c:c);return h[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(h[0]|=64),h[1]=f,f===126?h.writeUInt16BE(u,2):f===127&&(h[2]=h[3]=0,h.writeUIntBE(u,4,6)),r.mask?(h[1]|=128,h[c-4]=i[0],h[c-3]=i[1],h[c-2]=i[2],h[c-1]=i[3],d?[h,e]:o?(oh(e,i,h,c,u),[h]):(oh(e,i,e,0,u),[h,e])):[h,e]}close(e,r,i,o){let c;if(e===void 0)c=hv;else{if(typeof e!="number"||!gv(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");if(c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string")c.write(r,2);else if(xv(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[gt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==kt?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):Wr(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 d={[gt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Wr(e)?this._state!==kt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==kt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Wr(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 d={[gt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Wr(e)?this._state!==kt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==kt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[sh.extensionName],c=r.binary?2:1,d=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Wr(e)?(u=e.size,f=!1):(e=Yn(e),u=e.length,f=Yn.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 h={[gt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:d};Wr(e)?this._state!==kt?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==kt?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[gt],this._state=yv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Nd,this,u,o);return}this._bufferedBytes-=i[gt];let d=Yn(c);r?this.dispatch(d,r,i,o):(this._state=kt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(bv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[sh.extensionName];this._bufferedBytes+=i[gt],this._state=_v,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Nd(this,f,o);return}this._bufferedBytes-=i[gt],this._state=kt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===kt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};ah.exports=Ld;function Nd(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 bv(t,e,r){Nd(t,e,r),t.onerror(e)}});var mh=ae((gR,ph)=>{"use strict";var{kForOnEventAttribute:ts,kListener:Bd}=en(),ch=Symbol("kCode"),dh=Symbol("kData"),lh=Symbol("kError"),uh=Symbol("kMessage"),fh=Symbol("kReason"),$r=Symbol("kTarget"),xh=Symbol("kType"),hh=Symbol("kWasClean"),nn=class{constructor(e){this[$r]=null,this[xh]=e}get target(){return this[$r]}get type(){return this[xh]}};Object.defineProperty(nn.prototype,"target",{enumerable:!0});Object.defineProperty(nn.prototype,"type",{enumerable:!0});var Qn=class extends nn{constructor(e,r={}){super(e),this[ch]=r.code===void 0?0:r.code,this[fh]=r.reason===void 0?"":r.reason,this[hh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[ch]}get reason(){return this[fh]}get wasClean(){return this[hh]}};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,r={}){super(e),this[lh]=r.error===void 0?null:r.error,this[uh]=r.message===void 0?"":r.message}get error(){return this[lh]}get message(){return this[uh]}};Object.defineProperty(Vr.prototype,"error",{enumerable:!0});Object.defineProperty(Vr.prototype,"message",{enumerable:!0});var ns=class extends nn{constructor(e,r={}){super(e),this[dh]=r.data===void 0?null:r.data}get data(){return this[dh]}};Object.defineProperty(ns.prototype,"data",{enumerable:!0});var Ev={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[ts]&&o[Bd]===e&&!o[ts])return;let i;if(t==="message")i=function(c,d){let u=new ns("message",{data:d?c:c.toString()});u[$r]=this,Ko(e,this,u)};else if(t==="close")i=function(c,d){let u=new Qn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[$r]=this,Ko(e,this,u)};else if(t==="error")i=function(c){let d=new Vr("error",{error:c,message:c.message});d[$r]=this,Ko(e,this,d)};else if(t==="open")i=function(){let c=new nn("open");c[$r]=this,Ko(e,this,c)};else return;i[ts]=!!r[ts],i[Bd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Bd]===e&&!r[ts]){this.removeListener(t,r);break}}};ph.exports={CloseEvent:Qn,ErrorEvent:Vr,Event:nn,EventTarget:Ev,MessageEvent:ns};function Ko(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var $o=ae((wR,gh)=>{"use strict";var{tokenChars:rs}=jr();function Ft(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function vv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,f=-1,h=-1,g=-1,_=0;for(;_<t.length;_++)if(h=t.charCodeAt(_),d===void 0)if(g===-1&&rs[h]===1)f===-1&&(f=_);else if(_!==0&&(h===32||h===9))g===-1&&f!==-1&&(g=_);else if(h===59||h===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_);let y=t.slice(f,g);h===44?(Ft(e,y,r),r=Object.create(null)):d=y,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(g===-1&&rs[h]===1)f===-1&&(f=_);else if(h===32||h===9)g===-1&&f!==-1&&(g=_);else if(h===59||h===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_),Ft(r,t.slice(f,g),!0),h===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),f=g=-1}else if(h===61&&f!==-1&&g===-1)u=t.slice(f,_),f=g=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(o){if(rs[h]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);f===-1?f=_:i||(i=!0),o=!1}else if(c)if(rs[h]===1)f===-1&&(f=_);else if(h===34&&f!==-1)c=!1,g=_;else if(h===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(h===34&&t.charCodeAt(_-1)===61)c=!0;else if(g===-1&&rs[h]===1)f===-1&&(f=_);else if(f!==-1&&(h===32||h===9))g===-1&&(g=_);else if(h===59||h===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_);let y=t.slice(f,g);i&&(y=y.replace(/\\/g,""),i=!1),Ft(r,u,y),h===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),u=void 0,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(f===-1||c||h===32||h===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=_);let v=t.slice(f,g);return d===void 0?Ft(e,v,r):(u===void 0?Ft(r,v,!0):i?Ft(r,u,v.replace(/\\/g,"")):Ft(r,u,v),Ft(e,d,r)),e}function Sv(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(", ")}gh.exports={format:Sv,parse:vv}});var Yo=ae((bR,Ch)=>{"use strict";var Iv=fe("events"),Av=fe("https"),kv=fe("http"),yh=fe("net"),Tv=fe("tls"),{randomBytes:Cv,createHash:Rv}=fe("crypto"),{Duplex:_R,Readable:yR}=fe("stream"),{URL:Fd}=fe("url"),Cn=qr(),Dv=Od(),Pv=Md(),{isBlob:Ov}=jr(),{BINARY_TYPES:wh,CLOSE_TIMEOUT:Lv,EMPTY_BUFFER:Vo,GUID:Nv,kForOnEventAttribute:zd,kListener:Mv,kStatusCode:Bv,kWebSocket:We,NOOP:bh}=en(),{EventTarget:{addEventListener:Fv,removeEventListener:zv}}=mh(),{format:Uv,parse:Gv}=$o(),{toBuffer:Hv}=Qi(),Eh=Symbol("kAborted"),Ud=[8,13],rn=["CONNECTING","OPEN","CLOSING","CLOSED"],qv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ge=class t extends Iv{constructor(e,r,i){super(),this._binaryType=wh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Vo,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]),vh(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wh.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 Dv({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 Pv(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",Kv),o.on("drain",$v),o.on("error",Vv),o.on("message",Jv),o.on("ping",Zv),o.on("pong",Yv),c.onerror=Xv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ah),e.on("data",Zo),e.on("end",kh),e.on("error",Th),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[Cn.extensionName]&&this._extensions[Cn.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())}),Ih(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){Gd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Vo,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){Gd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Vo,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){Gd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Cn.extensionName]||(o.compress=!1),this._sender.send(e||Vo,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(ge,"CONNECTING",{enumerable:!0,value:rn.indexOf("CONNECTING")});Object.defineProperty(ge.prototype,"CONNECTING",{enumerable:!0,value:rn.indexOf("CONNECTING")});Object.defineProperty(ge,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(ge.prototype,"OPEN",{enumerable:!0,value:rn.indexOf("OPEN")});Object.defineProperty(ge,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(ge.prototype,"CLOSING",{enumerable:!0,value:rn.indexOf("CLOSING")});Object.defineProperty(ge,"CLOSED",{enumerable:!0,value:rn.indexOf("CLOSED")});Object.defineProperty(ge.prototype,"CLOSED",{enumerable:!0,value:rn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ge.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ge.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[zd])return e[Mv];return null},set(e){for(let r of this.listeners(t))if(r[zd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[zd]:!0})}})});ge.prototype.addEventListener=Fv;ge.prototype.removeEventListener=zv;Ch.exports=ge;function vh(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Lv,protocolVersion:Ud[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,!Ud.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ud.join(", ")})`);let c;if(e instanceof Fd)c=e;else try{c=new Fd(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:",f;if(c.protocol!=="ws:"&&!d&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?f="The URL's pathname is empty":c.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;Jo(t,I);return}let h=d?443:80,g=Cv(16).toString("base64"),_=d?Av.request:kv.request,v=new Set,y;if(o.createConnection=o.createConnection||(d?Wv:jv),o.defaultPort=o.defaultPort||h,o.port=c.port||h,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(y=new Cn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Uv({[Cn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!qv.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}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 I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath: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&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=_(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=_(o);o.timeout&&E.on("timeout",()=>{dt(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Eh]||(E=t._req=null,Jo(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){dt(t,E,"Maximum redirects exceeded");return}E.abort();let D;try{D=new Fd(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);Jo(t,R);return}vh(t,D,r,i)}else t.emit("unexpected-response",E,I)||dt(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ge.CONNECTING)return;E=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){dt(t,A,"Invalid Upgrade header");return}let b=Rv("sha1").update(g+Nv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){dt(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],P;if(R!==void 0?v.size?v.has(R)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":v.size&&(P="Server sent no subprotocol"),P){dt(t,A,P);return}R&&(t._protocol=R);let B=I.headers["sec-websocket-extensions"];if(B!==void 0){if(!y){dt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=Gv(B)}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(M);if(J.length!==1||J[0]!==Cn.extensionName){dt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(M[Cn.extensionName])}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cn.extensionName]=y}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 Jo(t,e){t._readyState=ge.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function jv(t){return t.path=t.socketPath,yh.connect(t)}function Wv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=yh.isIP(t.host)?"":t.host),Tv.connect(t)}function dt(t,e,r){t._readyState=ge.CLOSING;let i=new Error(r);Error.captureStackTrace(i,dt),e.setHeader?(e[Eh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Jo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Gd(t,e,r){if(e){let i=Ov(e)?e.size:Hv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${rn[t.readyState]})`);process.nextTick(r,i)}}function Kv(t,e){let r=this[We];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[We]!==void 0&&(r._socket.removeListener("data",Zo),process.nextTick(Sh,r._socket),t===1005?r.close():r.close(t,e))}function $v(){let t=this[We];t.isPaused||t._socket.resume()}function Vv(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",Zo),process.nextTick(Sh,e._socket),e.close(t[Bv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function _h(){this[We].emitClose()}function Jv(t,e){this[We].emit("message",t,e)}function Zv(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,bh),e.emit("ping",t)}function Yv(t){this[We].emit("pong",t)}function Sh(t){t.resume()}function Xv(t){let e=this[We];e.readyState!==ge.CLOSED&&(e.readyState===ge.OPEN&&(e._readyState=ge.CLOSING,Ih(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ih(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ah(){let t=this[We];if(this.removeListener("close",Ah),this.removeListener("data",Zo),this.removeListener("end",kh),t._readyState=ge.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",_h),t._receiver.on("finish",_h))}function Zo(t){this[We]._receiver.write(t)||this.pause()}function kh(){let t=this[We];t._readyState=ge.CLOSING,t._receiver.end(),this.end()}function Th(){let t=this[We];this.removeListener("error",Th),this.on("error",bh),t&&(t._readyState=ge.CLOSING,this.destroy())}});var Oh=ae((vR,Ph)=>{"use strict";var ER=Yo(),{Duplex:Qv}=fe("stream");function Rh(t){t.emit("close")}function eS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Dh(t){this.removeListener("error",Dh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function tS(t,e){let r=!0,i=new Qv({...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(Rh,i);return}let d=!1;t.once("error",function(f){d=!0,c(f)}),t.once("close",function(){d||c(o),process.nextTick(Rh,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",eS),i.on("error",Dh),i}Ph.exports=tS});var Hd=ae((SR,Lh)=>{"use strict";var{tokenChars:nS}=jr();function rS(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&&nS[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}Lh.exports={parse:rS}});var Gh=ae((AR,Uh)=>{"use strict";var iS=fe("events"),Xo=fe("http"),{Duplex:IR}=fe("stream"),{createHash:sS}=fe("crypto"),Nh=$o(),er=qr(),oS=Hd(),aS=Yo(),{CLOSE_TIMEOUT:cS,GUID:dS,kWebSocket:lS}=en(),uS=/^[+/0-9A-Za-z]{22}==$/,Mh=0,Bh=1,zh=2,qd=class extends iS{constructor(e,r){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:cS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:aS,...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=Xo.createServer((i,o)=>{let c=Xo.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=fS(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=Mh}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===zh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(is,this);return}if(e&&this.once("close",e),this._state!==Bh)if(this._state=Bh,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(is,this):process.nextTick(is,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{is(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",Fh);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){tr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!uS.test(c)){tr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){tr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ss(r,400);return}let f=e.headers["sec-websocket-protocol"],h=new Set;if(f!==void 0)try{h=oS.parse(f)}catch{tr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&g!==void 0){let v=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Nh.parse(g);y[er.extensionName]&&(v.accept(y[er.extensionName]),_[er.extensionName]=v)}catch{tr(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,(y,E,I,A)=>{if(!y)return ss(r,E||401,I,A);this.completeUpgrade(_,c,h,e,r,i,o)});return}if(!this.options.verifyClient(v))return ss(r,401)}this.completeUpgrade(_,c,h,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[lS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Mh)return ss(c,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${sS("sha1").update(r+dS).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;_&&(h.push(`Sec-WebSocket-Protocol: ${_}`),g._protocol=_)}if(e[er.extensionName]){let _=e[er.extensionName].params,v=Nh.format({[er.extensionName]:[_]});h.push(`Sec-WebSocket-Extensions: ${v}`),g._extensions=e}this.emit("headers",h,o),c.write(h.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Lx),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(ts,this)})),u(m,o)}};Mx.exports=qd;function bS(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 ts(t){t._state=Nx,t.emit("close")}function Lx(){this.destroy()}function ns(t,e,n,i){n=n||Vo.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} ${Vo.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",Fh),g.setSocket(c,d,{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(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(is,this)})),u(g,o)}};Uh.exports=qd;function fS(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 is(t){t._state=zh,t.emit("close")}function Fh(){this.destroy()}function ss(t,e,r,i){r=r||Xo.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} ${Xo.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 d=new Error(o);Error.captureStackTrace(d,tr),t.emit("wsClientError",d,n,e)}else ns(n,i,o,c)}});var Zx=ae(Me=>{"use strict";var M=K;(function(t,e){let n=K,i=t();for(;;)try{if(parseInt(n(1281))/1*(parseInt(n(1718))/2)+-parseInt(n(1642))/3*(-parseInt(n(1767))/4)+-parseInt(n(1448))/5+parseInt(n(1297))/6+parseInt(n(1874))/7+-parseInt(n(1838))/8+-parseInt(n(1363))/9*(-parseInt(n(1345))/10)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ta,383989);var CS=Object[M(1418)+"operty"],PS=Object[M(1031)+M(1070)+M(1350)],jx=(t,e)=>function(){return t&&(e=(0,t[PS(t)[0]])(t=0)),e},DS=(t,e)=>{for(var n in e)CS(t,n,{get:e[n],enumerable:!0})};function OS(){return Ux||(Ux=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function LS(){let t=M;return Gx||(Gx=[IDBCursor[t(1528)+"e"][t(714)],IDBCursor.prototype.continue,IDBCursor.prototype[t(470)+t(1678)+"ey"]])}function NS(t){let e=M,n={XFGTq:e(436),OOLRX:e(1025),eFMhA:function(o,c){return o(c)},tMdWR:function(o){return o()},GZxci:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let d=e,u={qnOau:function(g,S){return g(S)},oeAwl:function(g){return n[K(1286)](g)}},h=()=>{let g=K;t[g(1512)+"entListe"+g(1275)](n.XFGTq,x),t["removeEventListe"+g(1275)](n[g(949)],m)},x=()=>{let g=K;o(n[g(1242)](zt,t[g(923)])),h()},m=()=>{let g=K;u[g(858)](c,t.error),u[g(631)](h)};t.addEventListener(n[d(448)],x),t[d(1564)+d(1626)](d(1025),m)});return i.then(o=>{n[e(887)](o,IDBCursor)&&Kd.set(o,t)})[e(1600)](()=>{}),Qo[e(1597)](i,t),i}function MS(t){let e=M,n={QvoZL:e(1762),TwvzP:e(1773),tRCbp:e(610)+"e_success",hctxU:function(o,c,d){return o(c,d)},iBYqB:e(1025),Iinzn:e(1694),nlVZP:function(o){return o()},CHNxf:e(1548)+"or",DgprZ:"abort"};if(Xo.has(t))return;let i=new Promise((o,c)=>{let d=e,u={JVpte:n[d(1481)],Aualf:n[d(1009)],NCkaT:n.tRCbp,xdVqM:d(436),mKBbj:function(g,S,_){return n[d(1412)](g,S,_)},KUseg:n.iBYqB,OvMeM:n.Iinzn,ImCjr:"abort",aeTYj:function(g){return n[d(1604)](g)},Evhua:function(g){return n[d(1604)](g)},qgNRB:function(g,S){return g(S)},ZLgmz:n[d(1610)],dYngv:function(g){return n.nlVZP(g)}},h=()=>{let g=d,S={YXgMh:function(_,v){return _===v},SXYiK:u[g(1285)],Otkde:u.Aualf,Hzrfj:u[g(627)],XORCd:u[g(655)],cyyao:function(_,v){return _===v},QYOeE:function(_,v,I){return u[g(1042)](_,v,I)},vpKcH:u[g(1701)]};if(g(723)==="wyoHg")t["removeEventListe"+g(1275)](u.OvMeM,x),t[g(1512)+"entListe"+g(1275)](u[g(1701)],m),t[g(1512)+"entListe"+g(1275)](u[g(1348)],m);else{let{pingInterval:_,pingFrequency:v}=this[g(591)];if((S.YXgMh("hi",_0x10f78c[g(971)])&&S[g(1671)](S[g(1725)],v)||S.YXgMh(S[g(903)],v))&&(this[g(1114)+g(604)](),this[g(396)](S[g(1043)],S[g(1192)]),this[g(440)+g(1598)+"Id"]=_0xacb9da(this[g(384)][g(583)](this),_)),S[g(915)]("hi",_0xdae052[g(971)]))return;try{_0x5dc14b(this,_0x2769ea,[_0x4650ae,_0x2f9c1d,_0x21e62b,_0x5e60ec,_0x1b89a8,_0x386119])}catch(I){let A=S[g(1756)](_0x4c73cf,S[g(796)],{message:I[g(1606)],code:_0x367eea["MESSAGE_"+g(1496)],error:I});this[g(1301)+g(492)+"ent"](A)}}},x=()=>{let g=d;u.aeTYj(o),u[g(1771)](h)},m=()=>{let g=d;u[g(1897)](c,t[g(1025)]||new DOMException(u.ZLgmz,u[g(459)])),u[g(1257)](h)};t[d(1564)+d(1626)](n[d(1445)],x),t[d(1564)+"Listener"](d(1025),m),t[d(1564)+d(1626)](n[d(1091)],m)});Xo[e(1597)](t,i)}function BS(t){ea=t(ea)}function FS(t){let e=M,n={bYYYT:function(i,o){return i(o)},hfIei:function(i,o){return i(o)},Xtaxj:function(i,o){return i===o},qgYvU:e(873)+e(1029),iyPRc:e(594),HTyRj:function(i){return i()}};if(n.Xtaxj(t,IDBDatabase.prototype[e(1582)+"ion"])&&!(n[e(916)]in IDBTransaction[e(1528)+"e"]))if(n[e(669)]!==n[e(669)]){let i=_0x337a14[e(1875)]();return i?(i[e(1652)]=i[e(1315)]=0,i):{bytes:new _0x4ddcd8(64),offset:0,limit:0}}else return function(i,...o){let c=e,d=t[c(1770)](n[c(1460)](rs,this),i,...o);return jd.set(d,i.sort?i[c(1616)]():[i]),n[c(1460)](zt,d)};return n[e(806)](LS)[e(425)](t)?function(...i){let o=e;return t[o(994)](n[o(1460)](rs,this),i),n[o(1460)](zt,Kd[o(1112)](this))}:function(...i){let o=e;return n.bYYYT(zt,t[o(994)](n[o(1646)](rs,this),i))}}function K(t,e){t=t-380;let n=ta(),i=n[t];if(K.jTxqKi===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",g="";for(let S=0,_,v,I=0;v=h.charAt(I++);~v&&(_=S%4?_*64+v:v,S++%4)?m+=String.fromCharCode(255&_>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,_=m.length;S<_;S++)g+="%"+("00"+m.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(g)};K.dKYqZm=o,K.OSmrIp={},K.jTxqKi=!0}let c=n[0],d=t+c,u=K.OSmrIp[d];return u?i=u:(i=K.dKYqZm(i),K.OSmrIp[d]=i),i}function zS(t){let e=M,n={pnfQU:function(i,o){return i===o},BhxrO:function(i,o){return i instanceof o},uOHuJ:function(i,o){return i(o)},cgznM:function(i,o,c){return i(o,c)}};return n[e(1802)](typeof t,e(859))?FS(t):(n[e(390)](t,IDBTransaction)&&n.uOHuJ(MS,t),n.cgznM(Kx,t,OS())?new Proxy(t,ea):t)}function zt(t){let e=M,n={yrHLN:function(o,c){return o instanceof c},VJscO:function(o,c){return o!==c}};if(n.yrHLN(t,IDBRequest))return NS(t);if(Zo[e(1092)](t))return Zo[e(1112)](t);let i=zS(t);return n[e(1631)](i,t)&&(Zo[e(1597)](t,i),Qo[e(1597)](i,t)),i}var Kx,Ux,Gx,Kd,Xo,jd,Zo,Qo,ea,rs,Hx=jx({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={SxxBb:function(n,i){return n|i},dAiCe:function(n,i){return n>>i},zkLZj:function(n,i){return n|i},LSUVk:function(n,i){return n&i},PWRQC:function(n,i){return n>>i},NXnHq:function(n,i){return n|i},CZiZW:function(n,i){return n instanceof i},DdQRo:t(566),LJgKT:function(n,i){return n===i},bqUti:t(1421),SXPhS:t(873)+"oreNames",QTNhZ:function(n,i){return n===i},yCKhw:t(1218),MQeXn:function(n,i){return n(i)},ocObc:function(n,i){return n===i},jXubF:"tqHMW",QvbuD:function(n,i){return n===i},tKtlu:function(n,i){return n===i},IdXvD:t(519),BFWkX:function(n,i){return n in i}};Kx=(n,i)=>i.some(o=>n instanceof o),Kd=new WeakMap,Xo=new WeakMap,jd=new WeakMap,Zo=new WeakMap,Qo=new WeakMap,ea={get(n,i,o){let c=t;if(e.CZiZW(n,IDBTransaction))if(e[c(1329)]==="zAyQy"){if(e[c(1912)](i,e[c(693)]))return Xo.get(n);if(e[c(1912)](i,e[c(1008)]))return e[c(968)]("fwuTN",c(1696))?n["objectSt"+c(1029)]||jd[c(1112)](n):!!_0x4ae1d3?.find(d=>d[c(661)]===_0x2fa380&&d[c(1151)]===_0x1f60c9);if(e.QTNhZ(i,e.yCKhw))return o[c(873)+c(1029)][1]?void 0:o[c(873)+c(759)](o[c(873)+c(1029)][0])}else _0x19af8d[_0x142d5a++]=e[c(991)](e[c(1339)](_0x2927da,12),224),_0x5705c7[_0x4c5b84++]=e[c(1095)](e[c(710)](e[c(1216)](_0x1719e7,6),63),128),_0x1723f9[_0xd56e07++]=e[c(1124)](63&_0x558a73,128);return e.MQeXn(zt,n[i])},set(n,i,o){let c=t;return e[c(761)](e[c(826)],"tqHMW")?(n[i]=o,!0):_0x3ef02c?_0x187482[c(1243)+"sLE"](_0x4eeb13,_0x6ca59e):_0x494fec[c(1243)+c(927)](_0x3d289a,_0x15d2f0)},has(n,i){let o=t;if(n instanceof IDBTransaction&&(e[o(769)](i,o(1421))||e.QvbuD(i,e.yCKhw))){if(e[o(1288)](e[o(1811)],e[o(1811)]))return!0;++_0x48fe71,_0x4cd276+=4}return e[o(433)](i,n)}},rs=n=>Qo[t(1112)](n)}}),$x={};DS($x,{deleteDB:()=>GS,openDB:()=>US,unwrap:()=>rs,wrap:()=>zt});function US(t,e,{blocked:n,upgrade:i,blocking:o,terminated:c}={}){let d=M,u={iUzPM:function(m,g){return m+g},oqIVA:function(m,g){return m!==g},hNpor:function(m,g){return m&g},GHUQj:function(m,g){return m|g},Ohvrv:function(m,g){return m<<g},QdKuc:function(m,g){return m|g},aYohO:function(m,g){return m|g},iBKRg:function(m,g){return m&g},HQQtv:function(m,g){return m<g},DuKdN:function(m,g){return m>g},qbPvR:function(m,g,S){return m(g,S)},iHWLV:d(497),qpgoZ:"dvvXD",UDpue:function(m,g,S,_,v){return m(g,S,_,v)},JOziL:function(m,g){return m(g)},WBEEw:function(m,g){return m(g)},vguXG:function(m,g){return m&g},nzGAg:function(m,g){return m<g},iRMAe:function(m,g){return m===g},mXrLn:d(1769),WFfzp:d(1195),wFClQ:d(1738)+d(892),ETpEX:function(m,g){return m!==g},pvNps:d(569),Ymgog:d(1177)+d(510)},h=indexedDB[d(1018)](t,e),x=u.WBEEw(zt,h);if(i)if(u[d(429)](u[d(1322)],d(647)))h.addEventListener(u[d(1098)],m=>{let g=d;u[g(1751)](u[g(1709)],u[g(1187)])?u[g(1225)](i,u[g(634)](zt,h.result),m[g(407)+"on"],m.newVersion,u.WBEEw(zt,h["transact"+g(587)])):(_0x27ded9=_0x2a5cc4[u[g(1148)](u.iUzPM(_0x367032,_0x4d62e2),1)],_0x279af4=_0x383766[u[g(1148)](_0x18f53f,_0x2d6f0d)+2],_0x199593=_0x39f6d7[u[g(1148)](_0x45c456,_0x14ce40)+3],u[g(1751)](u.hNpor(u[g(1115)](_0x5b2b57,_0x1b9d30<<8)|u.Ohvrv(_0xf4feae,16),12632256),8421504)?_0x3838ce+=_0x1a3c51:(_0x184378=u.QdKuc(u[g(1335)](u[g(536)](7&_0x39e399,18)|(63&_0xdd5bbb)<<12,(63&_0x17246c)<<6),u[g(1206)](63,_0xe94e9a)),u[g(849)](_0xd45ed4,65536)||u[g(1665)](_0x488615,1114111)?_0x10ce39+=_0x1ba182:(_0x3f599a-=65536,_0x2b2b3f+=u[g(494)](_0x49143e,u[g(1148)](_0x4c2f01>>10,55296),u[g(1148)](u.hNpor(1023,_0x5ef4f1),56320)),_0x31d7c8+=3)))});else{let m=u[d(494)](_0x47b695,_0x46b443,1);_0x13542f[d(1827)][m]=_0x344feb}return n&&h["addEvent"+d(1626)](d(1565),()=>n()),x[d(1893)](m=>{let g=d;u.iRMAe(g(1769),u[g(1613)])?(c&&m[g(1564)+g(1626)](u.WFfzp,()=>c()),o&&m[g(1564)+g(1626)](u.wFClQ,()=>o())):(_0x477721=u.Ohvrv(u.iBKRg(31,_0x5d46e2),6)|u.vguXG(63,_0xcb8b52),u[g(679)](_0x430914,128)?_0x1ad7b1+=_0x967b9f:(_0x2a152c+=_0x1c9666(_0xaa9a9f),_0xa0166d++))})[d(1600)](()=>{}),x}function GS(t,{blocked:e}={}){let n=M,i=indexedDB[n(741)+n(544)](t);return e&&i[n(1564)+n(1626)]("blocked",()=>e()),zt(i).then(()=>{})}function Wx(t,e){let n=M,i={izFnx:"readwrite",riMdv:n(1768),doiWn:function(h,x){return h in x},ZnnMN:function(h,x){return h===x},HlVIS:n(1594),GSxpp:function(h,x){return h!==x}};if(!(t instanceof IDBDatabase&&!i.doiWn(e,t)&&i[n(446)](typeof e,i[n(571)])))return;if(Yo.get(e))return Yo[n(1112)](e);let o=e[n(430)](/FromIndex$/,""),c=i[n(1455)](e,o),d=Jx.includes(o);if(!(o in(c?IDBIndex:IDBObjectStore)[n(1528)+"e"])||!(d||Vx.includes(o)))return;let u=async function(h,...x){let m=n,g=this[m(1582)+m(587)](h,d?i[m(1847)]:i[m(1731)]),S=g[m(1218)];return c&&(S=S.index(x[m(970)]())),(await Promise[m(1620)]([S[o](...x),d&&g[m(1421)]]))[0]};return Yo[n(1597)](e,u),u}var Vx,Jx,Yo,HS=jx({"node_modules/idb/build/index.js"(){let t=M,e={SfiEa:t(1112),kKSls:t(1439),shTeH:"getAll",MBdeG:t(1417),Gvfwq:function(o){return o()},AMDHG:t(850),BJxHl:t(1194),iFgcW:function(o){return o()},xDJMO:function(o,c){return o(c)}},n=(t(1258)+t(1191)).split("|"),i=0;for(;;){switch(n[i++]){case"0":Vx=[e[t(1819)],e[t(1416)],e.shTeH,t(1141)+"ys",e[t(1066)]];continue;case"1":e[t(1567)](Hx);continue;case"2":Jx=[t(611),e[t(879)],e[t(654)],t(653)];continue;case"3":e[t(458)](Hx);continue;case"4":Yo=new Map;continue;case"5":e[t(728)](BS,o=>({...o,get:(c,d,u)=>Wx(c,d)||o.get(c,d,u),has:(c,d)=>!!Wx(c,d)||o[t(1092)](c,d)}));continue}break}}}),WS={idb:function(t){let e=M;t[e(1217)]=Promise.resolve().then(()=>(HS(),$x))[e(1893)](function(n){return n})}},qx={};function ta(){let t=["AMTlEvm","A2nWDK0","x2LUDgvYDMe","Cg5Muvu","su1qvxu","Cwzqzgm","r1LlCNC","y3vYDMfSDwu","AMHmugO","vMDSDLu","zw5KCg9PBNq","x2LUAxrqCM8","swryDKq","mNWXFdb8nhW","CYbWyxjHBxm","uNHvq2i","u2Tjuvq","qwnovMe","BNLsCwu","C0XPC3rLBMu","u2zPrwe","uNbSD2u","zMX1C2HfEha","wuHpEuq","EhnjCg4","zcWGDw5RBM8","sNPXrfa","x2LZqNjVD3m","yNL0zxm","yxKSihrYEsa","zNDZxZeUmc4","B25ozxr3B3i","zM9YrwfJAa","yLzrAgK","tMPAvxe","qufcv28","q09oveLovuu","vefiCNC","ihzHBgLKigq","ndy4otCWneDftg1LCG","D2zeCwm","zgrjrcWGzgu","qxbqALG","wxf4vhu","AwDHDg9Yt24","EgneA1i","y2HLy2Tszwe","rLfXzfu","AxPgBNG","ueLcvLi","Bu96Eg4","yMrFzgLK","rwnVwKK","u3LsC2i","DMfS","AxjLza","vfHkD1q","zgLZCgf0y2G","u2LJuuy","Ae1LC3nHz2u","ALzPqxi","DxjS","rM1bvuW","C0Xf","DNnYCLe","Dg9cExrLC0i","qK91weC","BwLUzW","ze5jrvK","Cgf5Bg9Hzfq","B25TzxnZywC","DhDXDLu","zMvY","x2fKzfDZtgK","Bwf4uMv0CMK","mJyXmJy4CwHkr3zc","Cg9W","BIWGAg9ZDg4","Dxrjza","wgvKvuq","zgvS","zw50","y0X0yxe","ChvZAa","z2DZy1i","AM9PBG","igfYCMf5yNu","s2Hhzum","x2rLC3rYB3K","CNHjuvK","yM9L","CgfNzxnOB3C","B3nLrxzLBNq","CKL5y1i","DgHLBG","C3rYAw5NAwy","yMfSrxzLBNq","AMvJDfn0B3i","CwDouKi","wfDmww4","zMXVB3i","AwXK","uu5quNO","BMDLza","C2v0sxrLBq","reiGzMfPBgu","v2rUrgC","EMjmANq","txHSB3K","DxnLCKLW","yxbWzw5Kq2G","Ec1TC2CTCw8","y29UBMvJDgK","tePNs1q","y29UC3rYDwm","ug1Qswq","ChjVy2vZCW","tLvHDwm","D012DLa","CMvHzfvjBNq","swf3tLi","Bwf4twvZC2e","Dvfougq","x2rPC2nVBM4","t1DZq2G","x3bPBMC","EK9euxa","y3vYC29Yx24","BM5Ly3q","A0HzBxy","ExbL","qMH4CK8","AejOqLa","tKf1sMW","vuPpuvK","qNnpr1G","Fdn8n3W2FdG","zw1PDa","yxfbu1a","vhzJq2q","Cgf5Bg9Hza","v1zpA1O","y1nUCNO","uu1Ztee","rM9QwxO","yuL0zgW","zw5fDMvUDa","x2LZtwLUAvC","B2XKvMvYC2K","DLriAeK","v2DdwwG","D2HXuvy","ywDLrxzLBNq","yvbJCum","D3jfq2O","se9vDKG","y3jLyxrLt3a","Ae9YDKu","B3bLBKrc","u0vWr0i","Ec11C2uT","zMvJwKy","zMzMsLq","t2Tby3q","r1zUEg4","ENn5wKW","Aw5JBhvKzxm","s0P5ANq","r1Hcrei","y2XVC2veqG","rvrWrvG","CMvWBgfJzq","qw1VDw50","ywXSzwqGBxu","qKzxA1G","t1bftG","r1ndzNa","C3vJy2vZCW","BLnhCwe","yxDvALm","y1Ljt28","x3bPBMDqB24","BMDcqMC","zxj2AwnL","CMvJzwL2zwq","CgfNzwHPzgu","wuDbvKu","wM5Utu4","AefJA01LC3m","wezhvhe","BKXPBMu","Efvoq0G","vw5Oyw5KBgu","rM94BNG","B2fK","zM9sBgi","s1Dfrgi","C3nHz2vfDMu","tw1fBMu","AuzNy1C","wKXNBxO","u0nyEey","z2vzqMW","x2rYB3bhBg8","sffNtem","zsbHihn0CMK","Dg9tDhjPBMC","yNblCwm","BwHfCxG","zxjFDhrS","BML0AwfSAxO","y29UDgLUDwu","y1ftzLe","EvD4y20","t2jQzwn0","A3ziuhC","x3nVy2TLDa","C3rLBMvYCW","tujuqvO","CMvJB25Uzwm","BvzwDMe","uMPrwgC","r1PqBNq","zwrPyxrLBhK","swfwsNm","vxbLCfm","x2TLEvbHDgG","x3bYzwzPEa","wK1ytem","v1fXrgm","DhDVCMTdAge","C2XjzLu","zMLSzw5HBwu","AevYCM9Yrxy","yxbWBgLJyxq","CwjqDLi","uxj1wum","AeDzz20","De54Aui","rNjVBNrPzxi","AvD0Dwy","B2XHAfy","v2vRrMG","C0D2zMq","x2HHBMrSzvi","qw9LDxC","y1vpu2e","C2noAg0","B2zM","twPntwi","Cw9stNO","zwvKzwq","qvryDeC","Aw9UvgLTzw8","CNzHBfzHBhu","uKXhteC","DxrJq1K","BMnVzgLUzW","EsbJBg9Zzwq","wvvKt0S","vM5nB1K","ufHfsvK","uvrbzLG","ENzzBvC","wenLqwG","zvvYBa","Dhj1y3rVCIa","Bwf4tg9ZC0m","C1DsDfy","DgDzuuK","uw9OB2i","qNrLyvy","BNDnDeq","ELfwwvG","y2uGBM90igK","BwfW","AMvuzNa","t2H2CNy","Cgu6ia","v0rWExK","A05kq3q","zgL4zw4","C1rdq2O","qMrgt0C","A2v5CW","DgfIyxnL","z2v0sxrLBq","wNHiAgW","rePstem","rw5ADwW","EKvpv0O","x2LUAxq","DeL4B0u","CgrQu0y","Aw5RAfi","DhjPzxmGCMu","zNjVBNrPzxi","mNW2Fdn8ma","yuzqzve","EvfPv0W","y2HHCKnVzgu","vff5z3y","A0XrqwG","ign1CNnVCIa","tufyx1jfvfi","zeLizfy","z2v0u3rVCMe","EKf5uxK","wNzfC0K","yw5ZzM9YBvq","r3fTAe0","C2vYDMLJzq","sgXwsvm","B3HfDxC","vwHkr2y","x3DHAxq","ELrrzey","vxzJuxq","CNnVCKzPBgu","BMCGzMfPBgu","C2XPy2u","uKTWDum","A1PpzhC","BhrPCgXLihq","yMLUza","DeTAufG","DvzrChy","zevXqxm","Aw9U","CLzHBhvLCW","DxbIBvC","vuzvD00","x29WDgLVBNm","CvLnBwi","CgLUz09Uy2u","ExfUtgS","C2v0q3vYC28","ywnOzwq","zKTuEKu","yxHeuNu","tuvtu0fhrv8","Cg9Qz2O","zhDnt3O","yunmz1u","zhPHvge","BMDuAw1LCG","EuHfDuq","yMHxyNe","DcbVzIbYyw4","qLPVufu","ENbntKe","CgLUz19VBMm","Chv0","Bg9NsurozxC","mhW0Fdn8mxW","x2LZsw5PDa","B250r0C","ywDLu2HVDW","uvDlEvi","u1rkAgC","B2jxywS","EM15zhq","DgvVrLe","y3vYC29Yx2y","uevPtgG","zw50tgLZDgu","v1z1qNC","C1HxrMK","tKnRyvq","C3jJ","y29UBMvJDca","B25JBg9Zzq","B2vbD2W","zhbczLu","t0zNBKm","sK96AuW","ufnWsMW","A053Bfy","rg5rDK8","yMHRyuO","s2flr3i","rxjYB3jdB2q","ALzxu1u","DMzozei","s1jJwLa","EfLPC0O","y29UBMvJDa","BKLYBhe","v213sw8","Bw1Py3u","r2Lttgy","B2nRzxq","v0jszgG","BwvY","y2XLyxi","qKP4sgW","EgrwCu0","z3fmwwG","v2vPEgLUsLm","CLrPu2q","D3vXAKK","yxnL","A2v5","tePruu0","x2rLyNvN","x29Ut3bLBG","zgvJB2rLzey","CwTRy1q","txfoq2S","zMLSDgvY","AxLquMm","v1LRCM0","zxLQBvC","sLbzweC","uNnQyui","uNjrAK0","s0Xlt3O","vfHHywm","v3riDLm","CLjss0i","BNPhqwC","ywnOzwqSihC","B25SAw5L","yxrLq291BNq","CfLjsw0","D3m6lY8","DhjPzxm","C0rTDeC","BMv3vMvYC2K","tu10Awm","vw5PBxbSzw0","rgr0tNK","qvbtsvC","txPItMy","yNfvDgK","r3Pxzuq","s0TnwvO","mNW1","BMCGDxjSoIa","qvDVDvC","s0HYyKq","o2nOyxjZzxq","u0z2wNa","z1zAr1O","BePSu00","wfjxBee","x29UtwvZC2e","tMP4vgy","uxLzz0u","yuTXy3u","ywHTshy","tfnvvMS","DgHbrKS","Bxbhv04","CMvZzxrfBMq","ywr2yw5Jzq","EMXevwC","AffUwNy","sw9ouwC","sKD3vxi","z0TRy3a","BMrWB2LUDfq","BMXLsMu","t25oyLO","D3LVsgC","ywjVyMu","s3zbu0y","y2TPr1C","Bg93","Eerktu8","DcbSAw1PDa","B25mAw5L","CgvYC2LZDgu","zMzmAw5L","x29UvgLTzw8","v2vIu29JA2u","CMTLCKDSB2i","wgfWwuC","q1ruEva","AwXRwLe","zNjVBu51Bwi","AwXSihvZzsa","zgvSzxrLrge","zKTewgW","tg9JAW","vMj0zgK","EKPbv0e","twvZC2fNzuu","CMvHC29U","yw1L","ChDPBLm","AwXLx25HBwu","C3bSAxq","CM90D2i","D2z5CxK","sffvt2q","igzHAwWSig0","D3j3vvG","wufAwKK","zw5HyMXLqxu","B3jL","x2rItMfTzq","B2npyMm","BxnN","x2HHBMrSzu8","ihrPBwvVDxq","Afb1Avy","DfDZt1C","quXLuwS","Dg9oDw1Izxi","uxzIDuq","sNzuuMC","Fdv8mNWX","vvfAAxO","lcbTyxGGCMu","AxnmB25N","BMCGB3iGyw4","D2HvBfe","x2HHBMrSzva","uw5guNK","DuLJDhm","z0zzrKO","q3L2yMW","D2fZq2XLyw4","C3bSAwnL","Aw5KzxGGB3u","ywnRx2nVzgu","wxbItva","rfbAwee","EvvXEue","BfrPBwvVDxq","y2HnyxHdB3u","y3vMBvC","wxzWz0C","sKXTyLy","Dg9hzw5LCMe","y2XVC2uSihC","DNbly0G","A1vOr2y","x2LUAxrhBg8","vxbKyxrLq28","u3jjrLO","zw5NDgG","mNW0Fdn8mhW","BuXwA1C","y3jLyxrLtwu","tLjkq24","sfr5uMO","C3rpvui","EerxBLe","BgLUzq","AgvuqMC","uMfjtMm","C3rHCNq","AfjMD0O","Dg9cExrLC0W","x2LZv29YA2u","zwn0","B0XJCeK","EfvZzuvUDG","zxbkBvi","qwvTy2q","Euf3C2m","x19LC01Vzhu","zvb3ruu","x2n1CNnVCKy","wNjrwvG","ALH1yKy","EvjWB1G","DMfSDwvZ","rfD2uLK","uxbkCuu","z2jJENK","x2nSzwfYvgK","rwT0rfG","DeLUDgvYy2u","CMvZzxrdB3u","C2vYDMvYvgK","AwXLtMfTzq","rLDt","yK5UuMC","t1bftL9fuLi","BvzADNq","DKr6BMW","x3fVC0rc","EgrHuNO","zxf1ywXZ","Bfbxz0u","BMrqsK8","yxrZvwy","sffrDhy","ywrK","D1nrBfm","D1P2C24","tfHQzMe","sKDwtvG","aaaaaaaaaaa","AeLOzK0","rLjptLrjrvi","Cw5pyxu","zNvUy3rPB24","DxPrsgW","vgPirvq","zNDnteS","uuPcseS","igzPzwXKoIa","zw1LBNq","uxzfBvu","C3vIC3rYAw4","Aerjyxq","y29UBMvJDfm","CvzZt3m","BLfkCeW","nxW3Fdf8nhW","B2jQzwn0u3q","BMvJDa","q29Kzq","ruznvva","EKvjBM4","y29Kzq","qu1eseC","rMTXBee","twLZC2LUzYa","uu1ss0K","B2LUDfjLywm","DxrVuMvJB24","v2HRsKy","yxnZAwDU","r1P4y2K","r3DHs2e","AKz5rxi","B1nIqu0","yxKSig5LDhC","AgfUz2u","zKv4r1y","AwLbt0u","yw1LoIa","z3fkweK","u2Xcreu","Dw5ZAwDUzwq","y1Pqt1y","CYbPBNn0yw4","x3bPBMDmB3m","DeLK","t3rRzgu","Axzoug8","DffXvve","DMHcyLO","zv90Aw1LB3u","v052Auq","t1jjyuO","Cg9PBNrdB24","B3jRig9MzMW","EeL6wKG","DhbizwfKzxi","B2nRzxrgywK","y3L5yw8","CwDzDLu","BvPABhK","zMzMzG","BMv4DcGPigm","u2f6yKq","ChjVDg9JB2W","DND5u0S","CMvZDwX0","x2LZtwLUAvq","y2XIr1q","ww5kvNy","C0jf","Aw5N","tKDFrvjst1i","Dg9Y","ALzyDxa","B25tDgfYDfi","y09Wzw4","yKHPzuC","quDyDLC","vvLpvwC","Ahf3A2K","B25VCgvU","wufMv0q","x2DLDeLUDgu","u0Tkue0","yunevu0","CgvTy2G","BwvZC2fNztO","zhbXuK8","yKnqy2K","vg1Tvwm","mdaWmdaWmda","t09muLG","yMfSu2nVCgu","tgnQqMy","BeHbCLm","DxrMofDYAxq","v3vfzwe","Affkwxq","BhLkCLG","x2n1CNnVCK4","C1PluwW","nNWYFda","B3PtBNO","rgrgvfC","ywrKt25L","EM1qBhq","AxmGDw5Kzwy","DgHHBIbSB2m","B3bLBIa","Aw9Ul2PZB24","uvroAfO","x2zVCM1HDeu","C2HPzNq","zgf0yq","zvzhqxy","y3vYC29Y","EKvbrg4","y1ndrfq","uhfdyxu","q291BNq","CwfhBLK","y3jLyxrLuMu","CMvJzxzPzwq","u1z2sfK","mhWXFdn8nhW","CMvZB2X2zq","EwnqCfu","x21PBMLoyxy","B2zmyu4","wfrctxO","sLDTBui","DMvY","B25fCNjVCG","u3H4qMi","AenSB3nLrxy","uwfRyLm","yxbWBhK","D1HpzKS","uxvtCxi","BgLUzw5V","x1fVu01HBMe","y2HnyxHuCMK","m3WXFdr8mhW","Ae50zLm","x29UrxjYB3i","u3rYyxrLz3K","AhrLEuy","rw9OtKq","ChDAqKS","rKT0D28","u1HqAfm","vhD2ELa","qLHnvKi","ihzHBgLKihm","uvDjDg0","zNjVBuHHC2G","zMzLCG","uxL6CLG","mxWZFdr8nG","BKPODM8","B3bLBG","zhrqqum","DM9Rt2q","u2TzvLq","vu1JELC","C1fxD1q","uefksxu","zxjYB3i","uuvWvNq","sgT0tw4","z2u6ia","B3jLtMfTzxm","zhLzyNu","z2v0t3DUuhi","zNjHBwvuExa","BfbWB3u","v2rjA1e","twHWB04","A0DuCMS","BwrXD3G","qLr3qNK","whrSugS","BhD6D3e","z2v0q3vYC28","BuTcyMO","shPYzMO","z2v0qwXS","yw5Nzq","x29Uq2XVC2u","qxvZEfe","ELzAD2m","ihrVihjLDhi","yvH5Exq","q29UzMLN","tfnfvu8","sNjlsvC","swLsre4","zfDVCMTLCKC","BvrewuS","vu1JqwO","Aw50zwDLCIa","u0XLwuC","wLjxs3e","x3bHDgHlzxK","u2TPCcbWyxm","Axnby2TdBgu","CeHHteC","C3zUt3a","tujKzuC","yxDzzLO","ywWGy3vYC28","sMnfvKO","B3bLCNr5tMe","rg9MEgi","suvtx0vsuK8","C2vUzf9Hy2S","AgLNAa","CfnQqwu","yxf6veC","r0HUB0q","Avrxvhy","vLLNsfq","Dg9iyxnO","B3jpBMXPBMu","EgHTBe8","ywnRDxbfBMq","C2vYDMLJzs0","CMfTugfYyw0","z3jAAMu","BwvKAwf0zwW","wMXzvLi","seHqwMe","q0rdt1q","rgDWCLO","AgfZ","Dg9mB3DLCKm","mtf8mtb8ohW","EMTmwMO","tvjsCem","yNvrz2G","ww1NB2C","sgPHDha","AxnszwfKEq","Cw9Zx18","t0THsu4","B2nRzxrtDwm","zxvjt3O","EvPTz0e","Cw9Z","ywXsswm","tKLMA3C","Dg50ugO","EKvSse0","CePnEu0","z2v0","uKjrvuW","x2nSzwfYugK","r0HvuwO","zxH0zw5ZAw8","ywXty29Wzq","s1nxzKy","DgvZDa","EfvlsM8","A1jTB0m","rMLRvem","zgLZywjSzue","tLHUshe","y3jLyxrLrwW","Bg9N","EMXktNe","CNLpv0G","BgLZDgvUtMu","Dwr5wwu","rMjAt0G","vunhAM4","t3jMC24","ALvnyMu","BgrWC1u","ANzru1i","Ef9MCM9UDgK","zxjFCw9Z","Dw9AEeq","tKLlBMO","z2v0qwXSs2u","yw1Lu3bHy2u","rhf3BgO","ueDnAvC","wxjLDuO","uhbevve","AeXNzNi","Avv6ue0","CNnVCL9Uyw0","y2zlr3O","DMfSDwu","vKD5sM8","yMLUyxj5vhK","Dw5RBM93BIa","CLfKC2G","tgHcwhi","BK1eu2O","zK5ID24","Cg93","DuzzqLq","zufJAW","C2vUza","ze1kuKK","DK92Cwe","t3rlDMi","y3jLyxrLq2W","B25dBg9Zzq","DKPRufy","C09Lqwe","y3ruAw1LB3u","B25nzxnZywC","De5ZDfm","CMvHzhLtDge","CvPruM4","u2HhC1y","DMzcy0m","DxbNCMfKzw4","C1frDwO","wePfCfi","Cur3CfG","n3WZFdz8oxW","Ahr0Chm6","y2Tfs04","D3nZoI8V","yNLL","yNL0zuXLBMC","CxbNB1O","C0nVDw50zxi","zwXLu2G","x2jPBMfYEvq","nhW1","we9sq2q","uxvLDwu","zgvSzxrL","y2XVC2u","sNbQy0G","r2Pcrwy","y1vquum","DMLIrNG","CMfUzg9T","zgv2AwnLx2K","zxjFywnRx20","EMrgzgq","sNnWrNm","tKfusvzfx0u","AujluMC","r1rWs1e","B0jQy1e","q3vsrwK","BMfTzq","sNf2v3e","sMfrvxC","sLnptLa","zuDMA0i","wvjYz1y","ufDsuum","zxHWB3j0CW","C3rVCMu","CMvQzwn0","Cfb3z1G","z2vtEw5J","vwPTzLe","nhWXFdn8nxW","DNvhvLi","vurWDwu","EvjLy29UBMu","Dgv4Dc9Qyxy","rKLHtxi","B25LCNjVCG","DgLUzYbZzxi","BKXjrwi","uLjpuG","BerpChe","BeHHBMrSzxi","BwnQDeS","y29UBMvJDeu","AKPgwNe","CePUBuS","ueH4B0O","Cg9OzKC","zxjFAxnFywm","zuznAee","zNjVBuj5Dgu","C1vsz1e","DhLWzq","u256C2G","zNbgrva","B3nLza","vKDpDu8","sLbQsMO","wfrWr1e","y3vYCMvUDeu","q21nswy","id4G","q05REge","y2XLyxjtDg8","zfLUz3y","mxWZFdb8mNW","x21LC3nHz2u","D2vI","vvvTtMi","z2vjBMzVu3K","CuLYtwO","ywnRx2LK","v2fQAwi","BhferMq","B3bLCNr5","sxj3yK0","ysbTDxn0igi","v0TOAKG","zMLUza","wu5dywO","AgnozKS","C2fNzq","BMvY","Dwvtthy","v0fVALO","r2DoCMC","ywnRtxnNswq","rNDbthm","ndy5rLzMwMPj","rgfYy0q","CMvTB3zLq2G","u2vmrvG","sLzWDgu","De1Kv1i","EuLHCKe","DeT0Bhu","ru5AuMO","BM9Uzv9UB24","thboBvi","sLz5u3m","mNWZFdf8nhW","x3DZ","C2Dqy24","yxnJCMLWDa","mJyXmJC3ogPOwwDIBW","vMH2seu","C3vIyxjYyxK","AxnbCNjHEq","x2rPC3bHDgm","twfvsMi","yMX6Dxi","EhPqvwu","BvPmzw4","tMfTzq","q3bQugG","we9nAMO","vKf3B1y","A1DWshC","t3bLBKv2zw4","tg9Nsuq","CMfTzq","CMv0CNLdB3u","BgLTAxq","BuXTv1K","yxv0B21HDgK","t2Derum","CuLqt1m","v2XZExe","wMTSEfe","ChzoChm","sLros0W","CM92AwrLige","qvjbqNO","tLHhz0W","Ewf2v3G","Bwv0Ag9K","rgrruM8","Ew1ysNm","vwXnv2q","zK9hB20","v2zdBxa","t096yui","yvLVAe8","y29Uy2f0","Aw47y2HHCNm","CMvWBgfJzui","zefPq2u","uffNEhi","sKrhDLe","zxrxB3jRq2G","uMfSAfC","yxPHrw4","ndaZmdeWmezjzeLjqW","BMrLEa","EKDTt04","sw1dANi","CKPxqMK","BwvZ","Bhbksve","CgDmsKW","rw9RC0y","C1DOCKO","yxrZsvy","zNjVBunOyxi","EvvgveW","x3jLy29UBMu","C0zhDMO","BwLZzq","Bwu6ia","DML5zwG","ovfrDurzqG","Cefcuvi","s1HhDMO","B3vUDa","vejIt1O","y2rYvhq","Auvvtuy","sMPLrgG","Dw50","CM92AwrLihy","zw5JB2rLrNi","ueLNrfi","runuD1y","yw5Hz2vY","AgvKtwf4uMu","ywXPzcb1CMW","ihn1y2nLC3m","rxrJreO","wvjuv08","q0fowue","rhfmB00","BuLfEuC","zM9Yy2u","qvnbBKi","swHmv2S","AvLryve","BfPODxe","EhjZzwq","DNDjyvq","BLnvrhK","thvkBLq","Cu1sz1m","D2XWBxu","AxnAzxjV","CeHVrhq","zMHcww4","re9pyuO","su5OBMS","CMLLC0nVDw4","AKDduMq","BgXkt28","zeHSDgW","twHJDuW","uuDcCfu","q1vhr2m","x3nLCuLK","C3PsBw0","DhjPBq","A1fKEMC","Agn0Efu","BMvLzf9Hy2S","z2vrDwv1zuW","BMrWB2LUDca","A0TtBhm","y291BNq","zgvMAw5Luhi","Bw5iwhe","rM5dy3G","zg9Uzq","Bg9IywXty28","Bu93seu","DNPcrNi","y3jLyxrLrxi","sfvQruW","z3vzy24","C2XvwuC","uxjdEKe","Egfdt3a","Dev2zw50","y3jLyxrLt2i","zxH0ugf5Bg8","z3rfzKq","sejXCe8","sgriyKS","uhLwu1a","weLwDeG","z2v0s2v5","ihrPBwvZ","z01zq3G","zxjYtxnN","yMn0wNC","r0T2AgS","swLUEM4","lcbxzwjtB2m","DenqyM0","mJa2ndu4mfPdtfriyG","sw9oDu4","sxLztgO","ihrYEsbYzwm","rKfmyNu","zerMuLa","x29UugfNzu4","r1n4Cha","A3jMzKe","AvfZs1q","rNzpCMu","y3vZDg9Tshq","yLLzwvq","x3bYB3rVy28","C2XHteC","x3jLBw92zvC","CM9YrxzLBNq","uM9TB0C","D3fuzxm","tvreyMW","CeXmv24","ruPhswq","uMvJB25Uzwm","qKTpDLm","BgvUz3rO","v2jcv0u","t21PwwG","C2TozxK","CM9qB0O","Aw5KzxHpzG","CMvXDwLYzwq","CgfYC2u","z01REfC","uxzVwKW","DKfhwum","Dg9cExrLCW","zw5HyMXLvhi","y29UDgv4Da","DwX3EeO","Dw5kENu","rfvhtg0","t1fvwLO","DxDmvui","B1DMALC","BwLUAvbYB2C","rgniBfO","qKrkwxK","y3r4","rvjst1i","AxnrB1nby2S","zw5HyMXLuw8","yxrHlcbKyxq","u2P6wxO","s2zXwNm","Dgf0BLq","D01Nvva","y2vZC0HHBMq","x2LZtM9Kzq","vLjXAgi","AgvHzgvYCW","BvLSB3u","CMvKDwnL","AwrI","C2DPza","CMvTB3zLrxy","Aw5Lza","DNfvEM8","EhbWz1u","qM9ZBhm","AMHPDhO","DgfYz2v0","zNP1weq","mNWXFdb8m3W","Aw5L","C2vszK4","q0PSzLO","CvfVvg0","x3jLywr5q2W","t1L0wxK","v3fcAMC","ChjVDg90Exa","ALHwsum","Du5iuwW","sMjTCfK","ywnRpwzYB24","z2vY","C2v0u3rVCMe","mdaWma","v3PNzwS","B25szwnLAxy","Bhm6ia","BNrLCG","AxnFywnR","wM9wA2q","jMPZy2fSBgi","D24GCMvHC28","ugjgrhC","CvjrD08","DuHhDfG","ChnktMq","qwjVCNrfCNi","rfLVEwq","zMLN","zgPttxi","y29SBM8","yxjRANu","zxjYtM8","CNLPD0u","vhrhwLi","x3nLBMrby2S","D3jPDgu","ignVzgu6ia","tw9lu0q","v2LUzg93","EujevKG","x2n1CNnVCK0","ywrKrxzLBNq","yMXVy2TLza","BgvY","r3zMD3e","vM1kEw4","A3bduM4","Dgv4DfbHEwW","x2vUzhbVAw4","B2znAuC","AxvpzMO","Bxrpzxq","A1byEeC","AK5iCvC","zv9ZDwnJzxm","vMHvCgK","wgTuvfi","vuDeBg0","Eu5xBw4","DhjHBNnHy3q","q09otKvdveK","r3PnwKC","zxq9DxrMltG","DevWCe4","qxrXB2u","BuDdD3a","DwzvuLq","DeTHzhm","zhzLtg4","s01wruS","CIb0DhDjra","C3rYAw5N","ywrKq291BNq","CNjVCK1LC3m","C2v0","z1rPBwvVDxq","BM93","y2f0y2G","Cgf5Bg9Hzeu","Dw5KzwzPBMu","BwX0EKi","BMXwwLa","wgvdz24","BwvZC2fNzq","refsqKG","BezSDxnO","icSG","q0HoEgy","CgLUz0LUDgu","v0XXtvi","BvHYtg4","CMPUAxy","uvvbq0i","C29YDa","BurwEhy","zwnVBM5Ly3q","rgvKAwnHDgu","ywXS","r0f6yNi","EvHiz2K","zw5JB2rPBMC","BvHprgi","x3vYBa","tgLZDgvUzxi","x194x21Zz18","u2vYDMLJzvC","ywDLsgLKzq","x25HDMLNyxq","vKPZy08","ywDL","z2nKAgS","DhLLtwK","Ewvxv2O","r0zgCfi","te9Kq0y","AgvHzgvY","AKnmyKi","vgLuwgW","ChrVCG","nMLzEvHwAW","z2v0q3vYCMu","ALPgC00","wu1wz0S","AgzjzwK","A2v0ignVBNm","uhzfvwO","wejPwe4","Ec1TC2CTy3u","zNjVBujPDhm","B2zMC2v0","ANr4Axy","y3vYCMvUDeK","uNz3r24","D3fqAwS","x3DZsw5ZDge","Ae9Wzw5fDMu","De1HBMfNzxi","u2vXsuq","x2nYzwf0zvm","rMz0whu","D3jrC0G","C3bVz24","rhvlze4","sufbALG","DgLTzw91DcW","zw50zwqGDhK","vxD6rva","zMXRA1y","wvHNtwG","D3jPDgvvAw4","yxGGCMv0CMK","s0L6uLq","q3vZDg9Trxi","yNvMzMvY","C3rVCcbPBw0","uhjPBwfYEuS","C2v0y3vYC28","z29PBMCGyxC","t2jpqvq","BKzbEue","tM91Cfa","rvLUrg8","DKvTsMi","BNrbBMrvCgq","DxbKyxrLq3u","yMfJA3vWigu","sNrwCKu","r1LQzKG","r3biugu","CMfNzvn5BMm","rLn6rMO","y29TCgXLDgu","r2nws0y","zND1ve4","BMjWtLm","D2LSBfjLy28","EvLks2m","txvTz2G","s1vZzwC","rxnqy24","x2nVBM5Ly3q","BxzREfK","rNfnAMC","CMvZzxruCMK","CLDZre8","y1bhzLi","AuHxtfy","sg1UAeG","BNruCMLLC0m","sLrLzhO","yNvMzMvYzwq","sfHqBMG","u3flue4","CunwChm","t0T5B1m","otG2uw9urwTl","C2nYAxb0","vgfN","rufXvhq","z05tEKK","x2XPC3rLBMu","Dhr3Awq","u1HzAuS","CLPqEfa","y2HLy2TdDxi","sM5wsxa","AxnrB1nnzxm","B25tDg9Wsw0","CMLnzhy","x0rctMfTzq","DfvPufG","tKLoA3m","Aez4ugO","zcWG","zxjFBxnNAwq","DMvYC2LVBMm","Dgv4Dc9WBge","q3vZDg9Tq2W","BMnLq2XVC2u","rgnRtxK","Bg9Nsurhzw4","u0HVEg0","zfjmAMm","turPswm","y0nbvK0","q0Xpu0LorW","yNL0zu9MzNm","wgrbt0e","B3fjvKe","q0HlAhu","zxjFCw9Zx2e","CgjICdi","B0T0q1i","uvLpzuu","BgHRExK","nxWW","Dg9VigXHCMC","Eg9QDwy","sxbsAeq","ywX3yxLZ","rg9qEvm","CMvUDevUzha","AeH4sKO","zgvIDwC","ntuYmJa4wevSwgvu","CMvHzg9UBhK","re5cCKK","y2fSBa","rxzODwe","CgXLyxnLiha","yxv0BW","BwfrCeS","DMvUDa","zcbLCNjVCI4","EfHjAe8","AevHBMW","s0zNDum","ig1LC3nHz2u","ufH6Eeu","yM9KEq","tg9NsurozxC","uu9bBNu","A1n0yxr1C0m","qKvJtuO","BNrfBMrWB2K","u2PZwNq","DNfHv1i","BwvZC2fNzv8","rNLPBhO","rxzLBNq","B2zMBgLUzq","ChbL","CNzHBa","q0Xpu0ve","CM92AwrLigi","wevluve"];return ta=function(){return t},ta()}function Ft(t){let e=M,n={vEmJb:function(u,h){return u!==h}},i=(e(1293)+"0")[e(751)]("|"),o=0;for(;;){switch(i[o++]){case"0":return c[e(1217)];case"1":var c=qx[t]={exports:{}};continue;case"2":var d=qx[t];continue;case"3":if(n[e(1685)](void 0,d))return d[e(1217)];continue;case"4":WS[t](c,c[e(1217)],Ft);continue}break}}Ft.d=(t,e)=>{let n=K;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object[n(1418)+n(1267)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Ft.o=(e,n)=>Object[t(1528)+"e"]["hasOwnPr"+t(1267)][t(1770)](e,n)})(),(()=>{let t=M,e={mOzxn:function(n,i){return n!=i},tWsOW:t(1602)+"d",pohfG:"Module",viyeh:t(822)+"le"};Ft.r=n=>{let i=t;e[i(1849)](e[i(766)],typeof Symbol)&&Symbol.toStringTag&&Object["definePr"+i(1267)](n,Symbol[i(465)+"Tag"],{value:e[i(1240)]}),Object[i(1418)+i(1267)](n,e[i(1362)],{value:!0})}})();var Pe={};(()=>{let t=M,e={JTedz:function(a,r){return a(r)},Snzsh:function(a,r){return a+r},qfPdc:function(a,r){return a+r},tQqUQ:function(a,r){return a+r},xzPUe:function(a,r){return a*r},hLgfr:function(a,r){return a*r},JqvWq:function(a,r){return a(r)},XIVtH:function(a,r){return a+r},YAZZI:"0000",QTAfX:function(a,r){return a(r)},dHltl:t(948)+t(948)+t(948)+"00000000",HQUOd:t(1890),KKMYZ:function(a,r){return a>r},RsjaB:function(a,r){return a<r},vTHhI:function(a,r){return a<r},tUiPX:function(a,r){return a!==r},zsyZL:function(a,r){return a-r},UMcAj:function(a,r){return a!==r},aItdl:function(a,r){return a<r},atsUf:function(a,r){return a===r},nleJe:function(a,r){return a===r},kvHPw:t(975),eyjmW:function(a,r){return a-r},bctZw:function(a,r){return a>=r},BEcMJ:function(a,r,s){return a(r,s)},vOvqa:function(a,r){return a===r},iTWTv:"PpQZe",jJFZq:t(1573),TQygv:function(a,r,s){return a(r,s)},IpRhD:function(a,r,s){return a(r,s)},wfDqc:function(a,r){return a(r)},udyYe:function(a,r){return a>>>r},OWsCh:function(a,r){return a(r)},hWqao:function(a,r,s){return a(r,s)},hqwki:function(a,r){return a&r},OmiYh:function(a,r){return a===r},mvkxY:t(881)+"required"+t(864)+"key",kPXxG:t(881)+t(1478)+" field: "+t(1151),slIfU:function(a){return a()},KSWfF:function(a,r){return a!==r},uFYBT:function(a,r){return a!==r},JzqDP:t(648),zpMNA:function(a,r){return a!==r},ECTwV:function(a,r,s){return a(r,s)},hFxPj:function(a,r,s){return a(r,s)},yAwsc:function(a,r){return a!==r},XTpGQ:function(a,r,s){return a(r,s)},GFFpR:function(a,r){return a(r)},olahV:function(a){return a()},zQVYX:function(a,r){return a(r)},foRlb:function(a,r,s){return a(r,s)},BXMVB:function(a,r,s){return a(r,s)},fzuXD:function(a,r){return a!==r},vqUzo:t(1589),JGwUr:function(a,r,s){return a(r,s)},jNHqW:function(a,r,s){return a(r,s)},aPcqC:function(a,r,s){return a(r,s)},wfyqy:function(a,r,s){return a(r,s)},PIBVR:function(a,r){return a===r},GKvhk:t(963),KRcZP:t(931),tgYQI:function(a,r,s){return a(r,s)},GXBDB:function(a,r){return a!==r},XeCgn:function(a,r,s){return a(r,s)},cUPQC:function(a,r){return a(r)},sOeAa:function(a,r){return a(r)},lHArS:function(a,r,s){return a(r,s)},djSMr:function(a,r,s){return a(r,s)},NIKnj:function(a,r){return a(r)},EnZul:function(a,r){return a(r)},GIeyP:function(a,r){return a(r)},QMsLA:function(a,r,s){return a(r,s)},AusxQ:function(a,r,s){return a(r,s)},aFPeQ:function(a,r){return a&r},JiXlU:function(a,r){return a===r},DdFTW:function(a,r){return a===r},zKhgJ:t(881)+t(1478)+t(864)+t(1312),eXibj:t(881)+t(1478)+t(864)+t(1328),OuZRA:function(a,r){return a(r)},sWRtV:function(a,r,s){return a(r,s)},skNey:function(a,r,s){return a(r,s)},pwZBK:function(a,r){return a>=r},WfCmp:function(a,r){return a>r},iEUMF:function(a,r){return a>=r},GiSLf:function(a,r){return a+r},MTDbl:function(a,r){return a===r},ldpsU:function(a,r){return a<r},jtxiv:function(a,r){return a===r},lPpou:t(398),dRLjc:"Read pas"+t(729),jXVIC:function(a,r){return a+r},cCAVM:function(a,r){return a<r},CJlfZ:function(a,r){return a+r},zvYmW:function(a,r){return a&r},EYnDo:function(a,r){return a&r},ryiwE:function(a,r){return a+r},OOzaB:function(a,r){return a&r},WAojZ:function(a,r){return a!==r},FftXu:function(a,r){return a|r},scNhm:function(a,r){return a<<r},fNbwn:function(a,r){return a&r},DOOaJ:function(a,r){return a<r},FwfmT:function(a,r){return a===r},RvwGn:"sBdYG",qIPOS:function(a,r){return a(r)},MmEne:function(a,r){return a==r},TXJwT:function(a,r){return a+r},kGTrk:function(a,r){return a&r},gMYCx:function(a,r){return a|r},hBhBP:function(a,r){return a&r},YUdOK:function(a,r){return a<<r},UJOQY:function(a,r){return a&r},kpCRn:function(a,r){return a&r},AGXvW:function(a,r){return a>=r},UpepS:function(a,r){return a<=r},nLIEb:function(a,r){return a+r},mIEyG:function(a,r){return a+r},FSSfk:function(a,r){return a!==r},bKwqB:function(a,r){return a&r},Dofxb:function(a,r){return a|r},vwIaT:function(a,r){return a<<r},zEOWJ:function(a,r){return a|r},jFyEr:function(a,r){return a|r},xUNCH:function(a,r){return a<<r},hcNfK:function(a,r){return a&r},AWouW:function(a,r){return a&r},mcjtK:function(a,r){return a+r},WVuBw:function(a,r){return a<r},SLeYG:function(a,r){return a+r},VglvU:function(a,r){return a-r},inkhR:function(a,r){return a+r},Mxloy:function(a,r){return a<<r},Wajib:function(a,r){return a<r},lDOpq:function(a,r){return a+r},UjmfQ:function(a,r){return a+r},JLmbV:function(a,r){return a<<r},yXHgi:function(a,r){return a<r},UCGjn:function(a,r){return a>>r},YRTWO:function(a,r){return a|r},HHPZa:function(a,r){return a>>r},OYtYy:function(a,r){return a|r},yRpoX:function(a,r){return a>>r},YMVgK:function(a,r){return a|r},VMgSS:function(a,r){return a&r},zdFdd:function(a,r){return a|r},PSpJl:function(a,r){return a&r},ORIaJ:function(a,r,s){return a(r,s)},yUFTL:function(a,r,s){return a(r,s)},WBRdh:function(a,r){return a<r},WekFh:function(a,r){return a&r},qoRNz:function(a,r){return a&r},lyJrX:function(a,r){return a>=r},ATXtG:function(a,r){return a&r},WAWne:function(a,r,s){return a(r,s)},FkqlA:function(a,r){return a(r)},bhWbq:function(a,r){return a||r},GzWeD:function(a,r){return a!=r},FKtwo:t(1602)+"d",YGAVE:function(a,r){return a!==r},kNJCt:t(1592),jGCRd:function(a,r){return a(r)},YreuJ:function(a,r){return a&r},KJyjt:function(a,r){return a&r},lJlSM:function(a,r){return a<<r},stOUB:function(a,r){return a&r},EAqTt:t(621),QpJqE:t(1666),vFKBb:function(a,r){return a(r)},FIaMr:function(a,r){return a<<r},bhkaJ:function(a,r){return a&r},UUmNb:"mGGIx",FikTC:t(1102),QJBHK:function(a,r){return a<<r},WbBWE:function(a,r){return a&r},wXOfK:function(a,r){return a&r},wrECj:function(a,r){return a<<r},geYBl:function(a,r){return a|r},VGeJG:function(a,r){return a<<r},zEInn:function(a,r){return a>>>r},JspFs:function(a,r){return a<<r},CpjPh:function(a,r){return a>>>r},mOwHE:function(a,r){return a===r},ngBBg:function(a,r){return a<r},SicQF:function(a,r){return a<r},GHnoD:function(a,r){return a+r},whqQV:function(a,r){return a!==r},ozSnz:function(a,r){return a&r},bHieG:function(a,r){return a!==r},fExGV:function(a,r){return a>>>r},KhGeC:function(a,r){return a>>>r},SFvZp:function(a,r){return a+r},lhkyy:function(a,r){return a!==r},PmjId:function(a,r){return a>>>r},MDiIc:function(a,r){return a!==r},BOuXG:function(a,r){return a&r},OgDEC:function(a,r){return a>>>r},SKJPM:function(a,r){return a+r},EtcDJ:function(a,r){return a|r},flkkV:function(a,r){return a>>>r},vsrrQ:function(a,r){return a+r},oSbAM:function(a,r){return a+r},jvIVB:function(a,r){return a>>>r},AABWo:function(a,r){return a&r},dPIfd:function(a,r){return a!==r},QyzrX:function(a,r){return a|r},pJnmK:function(a,r){return a&r},CUGGc:function(a,r){return a(r)},gbczy:function(a,r){return a|r},kNwlV:function(a,r){return a<<r},ZklxQ:function(a,r){return a<<r},EohND:function(a,r){return a<<r},heTBg:function(a,r){return a|r},QyYgE:function(a,r){return a<<r},ZrQYX:function(a,r){return a<<r},BcsjX:function(a,r){return a|r},hEanl:function(a,r){return a|r},lJrtx:function(a,r){return a<<r},yBDVH:function(a,r){return a===r},LJQQM:function(a,r){return a>>>r},oqdWT:function(a,r){return a|r},wSQlS:function(a,r){return a<<r},TiTXl:function(a,r){return a|r},AcNVa:function(a,r){return a|r},EFMUP:function(a,r){return a&r},OnNbZ:function(a,r){return a&r},bCPci:function(a,r){return a>>>r},XapYG:function(a,r){return a>>>r},iiAOE:function(a,r){return a&r},dtPAC:function(a,r){return a>>>r},JPYXG:function(a,r){return a>>>r},dixen:"close",UYOUg:function(a,r){return a>=r},NXGgL:function(a,r){return a===r},PRWmG:t(752),yeWWj:function(a,r){return a/r},YvpgG:function(a,r){return a!==r},Hjatp:t(1270),fKDXl:function(a,r){return a>>>r},ObOAT:function(a,r){return a>>>r},RLGLG:function(a,r){return a===r},pwinS:function(a,r){return a===r},cPGfR:function(a,r){return a>>>r},PyVSP:function(a,r){return a>>>r},XkTTR:function(a,r){return a&r},GwaKa:function(a,r){return a&r},zmydt:function(a,r){return a+r},WLqMR:function(a,r){return a+r},WNviD:function(a,r){return a<<r},ENZRj:function(a,r){return a===r},Atqoe:function(a,r){return a>>>r},mVVva:function(a,r){return a===r},vJkPV:function(a,r){return a!==r},DqLoM:t(1426),qIrMj:t(678),twqvU:function(a,r){return a===r},wrwUX:function(a,r){return a+r},nyRqe:function(a,r){return a+r},LcjBf:function(a,r){return a&r},OkAct:function(a,r){return a&r},UlMWd:function(a,r){return a>>>r},LpNmR:function(a,r){return a&r},EcoZI:function(a,r){return a>>>r},yZmgA:function(a,r){return a&r},Cyvbl:function(a,r){return a&r},atsIV:function(a,r){return a>>>r},QUACB:t(1205)+t(1232),IiRDN:t(1583)+t(929),xUtEI:t(563)+t(1072)+"R",sGvfd:t(599)+"ERROR",EktDX:t(840)+"OR",Wlsyq:function(a,r){return a>r},gtEfD:"XtkvC",CHKhu:t(613)+"2",YpbMP:"Module",XdAOA:"wBxiN",WtHvS:t(617),GYjfH:function(a,r){return a(r)},SjzYz:function(a,r){return a===r},vkEwZ:t(1052),zlJNq:t(1449),DcHlZ:function(a,r){return a>=r},CTTyP:function(a,r){return a===r},lqDFd:function(a,r){return a==r},CmMIf:t(1025),EoksF:function(a,r){return a instanceof r},wnJws:function(a,r){return a+r},UQZiz:function(a,r){return a===r},ZoVkd:function(a,r){return a===r},BdFOG:function(a,r){return a instanceof r},pojgj:"done",IrwbM:function(a,r){return a in r},FSzFj:t(1822),mZZly:"wKFMM",jvQSR:"HHtVq",obWak:function(a,r){return a>=r},JVWYR:function(a,r){return a<=r},alRIc:function(a,r){return a+r},pPyRz:t(817),NzDTO:function(a,r,s){return a(r,s)},hHxJJ:t(1859),KWEDb:function(a,r,s){return a(r,s)},JPjJj:function(a,r){return a!==r},QEpVt:t(1056),TjHET:t(1395),JbmpY:function(a,r,s){return a(r,s)},DckMy:"message",XtlPk:function(a,r,s){return a(r,s)},WVOkZ:t(1018),SVvHY:function(a,r,s){return a(r,s)},TmmUc:"1|2|3|4|"+t(1758),zlDUg:function(a,r){return a(r)},RVpvq:function(a){return a()},ItpuH:t(1112),nbpNS:t(1044),SeLEX:t(1141)+"ys",WpUnz:"count",HQgLC:t(611),mGCwp:"add",FvOre:t(1194),GpHPe:t(653),TAHrw:function(a,r){return a instanceof r},GYKrw:function(a,r){return a===r},hPuiV:t(1522),QruYC:t(1065),vDznl:t(605),XJEpR:t(1302),SrIFZ:function(a,r){return a!=r},uVQpv:function(a,r){return a||r},PqCau:function(a,r){return a<=r},jUMbe:function(a,r){return a(r)},GlFZl:function(a,r){return a===r},krffA:function(a,r){return a&r},zGmON:"string",sDmtG:t(1739)+"in;chars"+t(1585),arkju:t(1393),ShGsV:function(a,r){return a-r},xUKJo:function(a,r){return a<<r},cfKGz:function(a,r){return a<<r},axDRu:function(a,r){return a&r},mpGWN:function(a,r){return a-r},yIarA:function(a,r){return a|r},ofLaN:function(a,r){return a&r},YorGu:function(a,r){return a+r},qVsOs:function(a,r){return a&r},mhEqx:t(872)+t(556),qcKCH:function(a,r){return a===r},jZFsM:t(795)+t(900)+t(533)+t(469)+"ed",nZcEP:function(a,r){return a===r},BTwBy:"FIGgP",Bosls:t(702),nSGqa:function(a,r){return a>>r},ePwEE:function(a,r){return a|r},htoVZ:function(a,r){return a&r},dIHdV:function(a,r){return a&r},OtKvb:function(a,r){return a===r},RomoG:function(a,r){return a&r},TCjOx:function(a,r){return a+r},XBiXN:t(613)+t(696),XOMjj:function(a,r){return a|r},MdeEu:function(a,r){return a&r},ivNPo:function(a,r){return a|r},nJhvo:function(a,r){return a>>r},Wbsig:function(a,r){return a|r},STJhg:function(a,r){return a(r)},cdrTt:function(a,r,s,l){return a(r,s,l)},fhBYn:"init QoS"+t(1904)+"d",cufmW:function(a,r){return a!==r},mYlou:t(573),ymXJs:"EtkIy",ocxkf:"XGXns",psJNd:function(a,r){return a instanceof r},jeTfp:t(708),xhmlO:t(1889),uJfec:function(a,r){return a===r},RdeUx:"rqrkp",uZfZx:function(a,r){return a>=r},dzaTa:t(1227)+t(1296),NjxTf:function(a,r){return a+r},sFGvj:"http",mLVkW:t(1542)+t(1532)+"tierJSONP",PvEUj:function(a,r){return a(r)},GYcqA:t(1510),RSbIm:function(a){return a()},ALeQk:t(436),Orfsn:function(a,r){return a!==r},VGyJo:"CoklP",YNCaj:function(a,r,s){return a(r,s)},cSnrz:"reconnect",cZPOV:t(812),MhpoN:function(a,r){return a===r},mnHXq:t(1309),zVZwc:function(a,r){return a+r},NoupP:t(1710),VSGWP:t(871),xrsed:function(a,r){return a instanceof r},gFYFJ:t(451)+t(1776),nFAyA:function(a,r){return a!==r},UFUwM:"UTTBr",WdIkQ:t(719),MjMMb:function(a,r){return a!==r},eVGAv:t(385),ZxHhl:function(a,r){return a||r},LOdCF:function(a,r,s){return a(r,s)},GVnxn:t(1316),jyXLl:function(a,r,s){return a(r,s)},tyeMi:function(a,r){return a===r},tCPbm:t(847),JWmmB:"RncWr",WgCYh:function(a,r){return a!==r},roPoJ:t(1700),grZje:function(a,r){return a||r},mXODb:function(a,r){return a===r},WuEea:"aLdke",rDNel:t(978),sQQuj:function(a,r){return a||r},hIhfM:function(a,r){return a||r},bdgnO:function(a,r){return a!=r},tNstS:function(a,r){return a!=r},mDVxv:function(a,r){return a===r},EOORv:t(1452),PGMiW:t(1790)+"id",QnFRy:function(a,r,s){return a(r,s)},rjniv:t(1184),MRRpC:"OHvET",BinmA:t(1517),VMRQR:function(a,r){return a(r)},wqPik:t(1137)+t(1138),eleSh:"x_fronti"+t(1241)+"k",clbGT:function(a,r,s){return a(r,s)},vwySK:t(1137)+t(1202)+t(1511),MoKSD:function(a,r,s,l){return a(r,s,l)},DYoyd:t(1413),VYgHT:function(a,r,s,l){return a(r,s,l)},sZKQl:function(a,r){return a&&r},fIrBQ:t(666),rxIQY:t(1540),INhnk:t(1264),vzBFr:t(785),kUhGf:function(a){return a()},yWxcm:t(443),azaEn:t(681),pLLWn:"offline",pABQR:function(a,r){return a instanceof r},JTNKL:function(a,r){return a instanceof r},QNPRz:t(493)+t(967)+t(700)+"=utf-8",WhkJF:t(1290)+"e",sURgQ:"binary",sWhrJ:function(a,r,s,l){return a(r,s,l)},FwALs:t(1763),vqaWR:function(a,r){return a>r},pSjAe:function(a,r){return a+r},rZPxP:function(a,r){return a+r},MiKLD:function(a,r){return a|r},dwMOz:function(a,r){return a>>>r},SqKPN:function(a,r){return a+r},BDJYy:t(784)+t(607)+t(1028),WYkrm:t(1609),xDWnQ:t(1254),SlBDE:t(1058)+t(1759)+"e",llJOo:function(a,r){return a&r},ofMiG:function(a,r,s){return a(r,s)},TtGZR:t(1520)+"4",JtVrE:function(a,r){return a+r},mtOet:function(a,r,s,l){return a(r,s,l)},RcUqY:function(a,r){return a+r},aCDUM:function(a,r,s){return a(r,s)},dNMic:function(a,r,s){return a(r,s)},dDfRP:t(1053),WdnDg:function(a,r){return a<<r},VGOuO:function(a,r){return a+r},qMRgS:function(a,r){return a+r},VhUpi:function(a,r){return a|r},MzbNf:function(a,r){return a+r},hQnZv:function(a,r){return a+r},yYJKc:function(a,r){return a&r},mltzB:function(a,r){return a>>>r},uNHQl:function(a,r){return a&r},dEqAs:function(a,r){return a+r},IhLWk:function(a,r){return a&r},ApPjX:function(a,r){return a&r},ZlYVR:function(a,r){return a>>>r},OOkEE:function(a,r){return a+r},DLPvn:function(a,r){return a&r},gNSzI:function(a,r){return a+r},spogn:function(a,r){return a+r},WdhIB:function(a,r){return a===r},iQsKT:t(1878),pHoDt:t(1812)+t(1094)+t(1181)+"5",yNWmn:function(a,r){return a|r},OFgnC:function(a,r){return a<r},IzOxk:function(a,r){return a&r},aXyyt:function(a,r){return a>>>r},MLkwv:function(a,r){return a|r},dveLn:function(a,r){return a>r},ckEKN:function(a,r){return a<r},oDsDC:function(a,r){return a|r},kWQyt:function(a,r){return a<<r},vhBbZ:"10|4|9|0"+t(395)+t(771),GSCfp:t(1806),QuSqr:t(570),CDCOT:t(1210),JDGvQ:function(a,r,s,l){return a(r,s,l)},SjsZt:t(1638),NAuJl:"cursor.s"+t(442),thAFK:function(a,r){return a|r},wMvvP:function(a,r){return a|r},ZRWKq:t(691),Qohob:t(504),rQdsh:function(a,r){return a(r)},pPwgX:t(622)+"ile_name",WqBjg:function(a,r,s,l){return a(r,s,l)},DnQvO:function(a,r){return a+r},QJdiU:function(a,r,s){return a(r,s)},FQqdU:"cursor_name",xojuf:function(a,r){return a(r)},GjBEf:function(a,r){return a&r},kLQAh:function(a,r){return a===r},fpFEP:t(575),fAGmx:"INSTANT",BsOGX:t(1835),SHoxm:t(608),vuGVR:"setdb",cxEox:function(a,r,s){return a(r,s)},eGfkB:t(1106),nhIuJ:"ncbjW",KIzRT:t(1388),dpBfU:function(a,r){return a!==r},Aemcd:t(1679)+"r",zEADn:function(a,r){return a===r},Dqwlj:function(a,r){return a===r},JvTRg:t(674),qCVps:function(a,r,s){return a(r,s)},TvYhp:t(878),JjeDh:function(a,r,s,l){return a(r,s,l)},iKTwk:function(a,r,s){return a(r,s)},epJmR:t(1137)+t(1737),DJRLC:function(a,r,s){return a(r,s)},PAJIu:t(1650)+"rsor_value",IaVJs:"FfWsf",HBqpO:function(a){return a()},pdjSF:function(a){return a()},DARBH:function(a,r){return a!==r},rGtbn:t(866),Suqnz:t(1489),fOGom:function(a,r){return a&&r},KfqZs:function(a){return a()},mdqwx:function(a,r){return a(r)},ZvEsI:function(a,r){return a!==r},NIfkw:"gjDpC",eAZuy:function(a,r){return a(r)},IlHpy:function(a,r,s,l){return a(r,s,l)},UaVkD:function(a,r){return a===r},hOrvE:"RRMTF",scqaW:t(1128),kHYmv:function(a){return a()},sbmEA:"ApEwH",SazbD:t(1276),LwIUK:function(a,r){return a!==r},xsIpn:function(a,r,s){return a(r,s)},HXPnh:function(a){return a()},QMRKI:function(a){return a()},buQgh:"dpJBC",xIzZH:t(1185),nwMtD:function(a,r,s){return a(r,s)},pYIIm:t(945),tiweK:t(1762),CYYNd:function(a,r){return a!==r},oWfjW:t(1310),bVQhi:t(982)+"2",QGBpU:"arraybuf"+t(1871),JnVIp:t(1754),iWtuf:"auto",RaINc:function(a,r){return a==r},mZLen:t(1772)+t(1372)+t(1378),RBQUL:function(a,r){return a(r)},yQiWL:"please provide w"+t(1813)+t(1446)+t(1647)+t(525)+t(964)+t(1513),lSBMH:t(1677)+t(482)+" reconnect",wuqjI:t(444),jpQKr:function(a,r){return a!==r},qZQRn:t(1850),RalhW:t(1724),HktMn:t(1201)+"d",jhLPj:function(a,r){return a||r},IawNR:"please p"+t(1797)+t(1840)+"viceID o"+t(1593),hRfwJ:t(859),urYbi:function(a){return a()},UvcQt:t(1260),sgPcn:function(a,r){return a>r},DarcD:"ping_once_timeout",KaKGr:"timeout",EJGId:"OUcoA",xppgU:"fCvJU",YAfWD:t(1207),xYisJ:t(1833),jCLbB:t(853),TBbOZ:"ZhpLJ",CXhmI:t(438),euIOz:function(a,r){return a||r},JWxUB:function(a,r,s){return a(r,s)},LBgcO:function(a,r){return a-r},FbZOH:function(a,r,s){return a(r,s)},upbmW:function(a,r,s){return a(r,s)},lPWgE:function(a,r){return a(r)},pgLJL:function(a,r,s){return a(r,s)},Foxnx:function(a,r,s){return a(r,s)},kZOdw:t(1667)+t(1451)+"onnecting",jkKyS:function(a,r,s){return a(r,s)},SEpGB:t(1420),FmAUL:t(1e3)+"2",wZvsn:t(1109),EsPcn:function(a,r){return a===r},XTBMz:t(1067),Qcnql:t(1298),hQJYt:function(a,r,s){return a(r,s)},utcCY:function(a,r){return a===r},tIxoE:"zkFpM",hteyF:"gBVaz",bNnRg:function(a,r,s){return a(r,s)},dNIEY:function(a,r,s){return a(r,s)},JcEVJ:t(1680)+t(891)+t(911)+t(1521),KFguC:"ack",dyYbu:function(a,r){return a!==r},tKZPX:function(a,r){return a-r},wCBIR:function(a,r){return a!==r},WQqDc:t(656),bpKqc:function(a,r){return a*r},PEiLh:t(688),QOAnu:function(a,r,s,l,f){return a(r,s,l,f)},IyYLj:t(1177)+"eeded",kRmoC:function(a,r){return a===r},NRJCn:t(1212),ontGG:t(1021),vAGYC:function(a,r){return a===r},Guakx:function(a,r){return a==r},vPuxd:t(1772)+t(1324)+t(1837)+t(1499)+t(1269)+t(464)+t(775)+t(1885)+t(1014),aXVJL:"number",VRqhb:function(a,r){return a!=r},UwzEP:function(a,r){return a(r)},KLKOz:function(a,r){return a||r},NUauc:t(1772)+t(1324)+t(1011)+t(442),bkrqH:function(a,r){return a instanceof r},KCoxZ:function(a,r){return a===r},VmJyn:"sent",jVWSU:function(a,r){return a(r)},slaLG:function(a,r){return a!==r},gqJXI:t(776),SyRsb:function(a,r){return a||r},yavWx:function(a,r){return a==r},vokOd:"ping_once_success",ZfGPy:t(855),ckiGW:function(a,r){return a/r},cLtaq:function(a,r){return a!=r},xXIhO:function(a,r){return a===r},QakbS:t(1561),fwMLK:function(a,r){return a===r},sQWwT:t(473),xcDkR:function(a,r){return a===r},DdtNy:t(1619)+t(1055)+t(1422)+"pe",xgIIu:function(a,r){return a===r},Fyilz:function(a,r){return a!=r},oKtCR:"SharedWo"+t(735)+t(1117),NINks:t(1628)+"orkerGlo"+t(950),YqxTu:function(a,r){return a===r},GzMZG:function(a,r){return a!=r},aCLgU:t(1627)+t(1101)};Ft.r(Pe),Ft.d(Pe,{FWS:()=>Lg,CustomErrorEvent:()=>hl,createCloseEvent:()=>pt,ReconnectEvent:()=>fl,createErrorEvent:()=>at,decodedFrame:()=>nn,createOpenEvent:()=>_l,CustomCloseEvent:()=>xl,createReconnectEvent:()=>wa,FrontierMessageEvent:()=>gl,encodeFrame:()=>Gt,createMessageEvent:()=>wl,OpenEvent:()=>ml,ErrorCode:()=>sn,Event:()=>ir,MessageEvent:()=>pl});let n="";function i(a=""){let r=t,s="02",l=""+Date.now(),f=n||(n=e[r(1712)](h,a)),w=Math.random().toString(16).slice(-6);return e.Snzsh(e.qfPdc(s+l,f),w)}function o(){let a=t;return e[a(905)](e[a(1304)](1e4,Date[a(1599)]()),Math[a(1899)](e[a(1147)](1e4,Math[a(1200)]())))}function c(a){let r=t;return(e.JqvWq(Array,8)[r(1884)]("0")+parseInt(a,10).toString(2))[r(579)](-8)}function d(a){let r=t;return e.qfPdc(Array(4).join("0"),parseInt(a,2)[r(465)](16))[r(579)](-4)}function u(a){let r=t,s=a[r(751)](/\./)[r(534)](w=>c(w)),l=[];return l[0]=d(s[0]+s[1]),l[1]=e[r(1712)](d,e[r(1438)](s[2],s[3])),["0000",e.YAZZI,e.YAZZI,e[r(757)],e.YAZZI,r(918),l[0],l[1]][r(1884)]("")}function h(a){let r=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(1119)](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]))/[r(1119)](a);return s?e[r(521)](u,a):l?e[r(1712)](x,a):e[r(1404)]}function x(a){let r=t,s={JWCgn:r(1793),WjBKi:e.HQUOd},l="",f=[],w=0,b=0,y=!0,p=e[r(757)];if(e[r(695)](a.indexOf("::"),-1)){let D=a[r(751)]("::");for(let z=0;e[r(673)](z,D[r(1472)]);z++){let V=D[z];if(e[r(695)](V[r(1477)](":"),0)){let te=V[r(751)](":");y&&(w=te[r(1472)]),b+=te[r(1472)];for(let Z=0;e[r(408)](Z,te[r(1472)]);Z++)if(e[r(1733)](4,te[Z].length)){let nt=p[r(867)+"g"](0,e.zsyZL(4,te[Z][r(1472)])),St=nt[r(1336)](te[Z]);f.push(St)}else f[r(1882)](te[Z]);y=!1}else{if(e[r(1057)](4,V[r(1472)])){let te=p.substring(0,4-V[r(1472)]),Z=te[r(1336)](V);f[r(1882)](Z)}else f.push(V);y&&(w+=1),b+=1,y=!1}}let L="";for(let z=0;z<e.zsyZL(8,b);z++)L=L.concat(p);for(let z=0;e[r(404)](z,f[r(1472)]);z++)e[r(848)](z,w)?e[r(721)](r(975),e[r(474)])?(l=l.concat(L),l=l[r(1336)](f[z])):(this[r(1826)+"er"]&&_0x39b56c[r(1512)+r(624)+r(1275)]("online",this[r(763)+"nLine"]),this[r(1826)+"er"]&&_0x51f7a6["removeEv"+r(624)+r(1275)](s.JWCgn,this._handleOffLine),this[r(1826)+"er"]&&_0x455b83[r(1512)+r(624)+r(1275)](r(444),this[r(777)+r(1629)]),this[r(1826)+"er"]&&_0x270479[r(1512)+r(624)+r(1275)](s.WjBKi,this["_handleP"+r(616)])):l=l.concat(f[z]);return l}{let D=a[r(751)](":");for(let L=0;L<D.length;L++){let z=D[L];if(D[L][r(1472)]!==4){let V=p[r(867)+"g"](0,e[r(671)](4,D[L][r(1472)])),te=V[r(1336)](z);l=l[r(1336)](te)}else l=l[r(1336)](z)}return l}}function m(a,r){let s=t,l={YKydu:function(b,y){return e[K(1443)](b,y)}},f=a.key;e[s(1733)](void 0,f)&&(pe(r,10),e.BEcMJ(U,r,f));let w=a[s(1151)];if(w!==void 0){if(e.vOvqa(e[s(1078)],e[s(1237)]))return l.YKydu(this[s(1417)],this[s(526)+s(1366)]);e[s(560)](pe,r,18),e[s(1761)](U,r,w)}}function g(a){let r=t,s={};e:for(;!e[r(1839)](j,a);){let l=xe(a);switch(e[r(1130)](l,3)){case 0:break e;case 1:s.key=C(a,e[r(383)](xe,a));break;case 2:s[r(1151)]=e.hWqao(C,a,e[r(1712)](xe,a));break;default:e.IpRhD(T,a,e[r(937)](7,l))}}if(e[r(1474)](void 0,s[r(661)]))throw new Error(e[r(1704)]);if(s.value===void 0)throw new Error(e[r(1575)]);return s}function S(a){let r=t,s=e[r(490)](R);return _(a,s),e[r(1712)](N,s)}function _(a,r){let s=t,l=a[s(1660)];if(e[s(1118)](void 0,l))if(e[s(1160)](e[s(1825)],e[s(1825)])){let nt=_0xe73100[s(1606)].payload;nt&&_0x1b4082[s(595)+"rs"](nt)}else pe(r,8),xt(r,l);let f=a[s(1312)];e[s(609)](void 0,f)&&(e[s(1375)](pe,r,16),e[s(1735)](xt,r,f));let w=a.service;e[s(821)](void 0,w)&&(e[s(1251)](pe,r,24),xt(r,e[s(1636)](P,w)));let b=a[s(1328)];e.KSWfF(void 0,b)&&(pe(r,32),e.ECTwV(xt,r,e[s(521)](P,b)));let y=a[s(1507)];if(e.uFYBT(void 0,y))for(let nt of y){pe(r,42);let St=e[s(500)](R);m(nt,St),e.BEcMJ(pe,r,St[s(1315)]),W(r,St),e.zQVYX(O,St)}let p=a[s(1601)+s(516)];e[s(1733)](void 0,p)&&(e[s(560)](pe,r,50),e.foRlb(U,r,p));let D=a[s(1868)+s(389)];e.UMcAj(void 0,D)&&(e[s(1010)](pe,r,58),e[s(1786)](U,r,D));let L=a.payload;if(e[s(1519)](void 0,L))if(s(1589)===e[s(1514)])e[s(1251)](pe,r,66),e[s(718)](pe,r,L.length),oe(r,L);else return this[s(1294)]?this[s(1294)][s(1116)+"ns"]:"";let z=a[s(1783)];e[s(1118)](void 0,z)&&(e[s(1576)](pe,r,74),e.aPcqC(U,r,z));let V=a[s(836)+s(1866)];e[s(1118)](void 0,V)&&(e[s(753)](pe,r,82),e.wfyqy(U,r,V));let te=a.msgID;e[s(1519)](void 0,te)&&(e[s(1848)](e[s(1444)],e[s(643)])?_0x41152c.log(_0x16967b):(pe(r,90),e.tgYQI(U,r,te)));let Z=a[s(1032)+"e"];e[s(427)](void 0,Z)&&(e[s(1605)](pe,r,96),xt(r,e[s(1636)](P,Z)))}function v(a){let r=t;return e[r(1198)](I,e[r(1712)](B,a))}function I(a){let r=t,s={};e:for(;!e[r(1169)](j,a);){let l=e[r(1712)](xe,a);switch(e[r(1130)](l,3)){case 0:break e;case 1:s[r(1660)]=e[r(952)](vt,a,!0);break;case 2:s.LogID=e[r(1551)](vt,a,!0);break;case 3:s[r(570)]=e[r(383)](xe,a);break;case 4:s[r(1328)]=e.NIKnj(xe,a);break;case 5:{let f=e.cUPQC(A,a);(s.headers||(s[r(1507)]=[])).push(e.sOeAa(g,a)),a.limit=f;break}case 6:s[r(1601)+r(516)]=e.BEcMJ(C,a,e[r(548)](xe,a));break;case 7:s.payloadType=C(a,e.GIeyP(xe,a));break;case 8:s[r(399)]=e[r(1761)](se,a,xe(a));break;case 9:s[r(1783)]=e[r(402)](C,a,xe(a));break;case 10:s.serverTiming=e[r(1047)](C,a,xe(a));break;case 11:s.msgID=e[r(952)](C,a,xe(a));break;case 12:s.frameType=e[r(383)](xe,a);break;default:e[r(412)](T,a,e[r(557)](7,l))}}if(e.JiXlU(void 0,s[r(1660)]))throw new Error(r(881)+"required field: "+r(1660));if(e[r(961)](void 0,s[r(1312)]))throw new Error(e.zKhgJ);if(e.PIBVR(void 0,s[r(570)]))throw new Error(r(881)+r(1478)+r(864)+"service");if(s[r(1328)]===void 0)throw new Error(e.eXibj);return s}function A(a){let r=t,s=xe(a),l=a[r(1315)];return a.limit=a.offset+s,l}function T(a,r){let s=t;switch(r){case 0:for(;128&e.OuZRA(ee,a););break;case 2:$(a,e[s(532)](xe,a));break;case 5:e[s(527)]($,a,4);break;case 1:e[s(1475)]($,a,8);break;default:throw new Error(e[s(1804)](s(689)+s(1668)+s(537),r))}}function P(a){let r=t;return a|=0,{low:a,high:a>>31,unsigned:e[r(1006)](a,0)}}let E=[];function R(){let a=t,r=E[a(1875)]();return r?(r.offset=r[a(1315)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){E.push(a)}function B(a){return{bytes:a,offset:0,limit:a[t(1472)]}}function N(a){let r=t,s=a[r(1827)],l=a[r(1315)];return s[r(1472)]===l?s:s[r(1299)](0,l)}function $(a,r){let s=t;if(e[s(1333)](a.offset+r,a.limit))throw new Error(s(1062)+s(729));a.offset+=r}function j(a){let r=t;return e.iEUMF(a.offset,a[r(1315)])}function re(a,r){let s=t,l=a[s(1827)],f=a.offset,w=a.limit,b=e[s(649)](f,r);if(e[s(695)](b,l[s(1472)])){let y=new Uint8Array(e[s(1304)](2,b));y[s(1597)](l),a[s(1827)]=y}return a[s(1652)]=b,e[s(1333)](b,w)&&(a[s(1315)]=b),f}function X(a,r){let s=t;if(s(520)!==e[s(1033)]){let l=a[s(1652)];if(e.KKMYZ(l+r,a[s(1315)]))throw new Error(e[s(1745)]);return a[s(1652)]+=r,l}else{if(_0x279ade===void 0)this[s(1723)+"rs"]={};else if(e[s(1467)](void 0,_0x27157))this._listeners[_0x401285]=null;else{let l=this[s(1723)+"rs"][_0x39a387];if(l)for(let f=0;e.ldpsU(f,l[s(1472)]);)e[s(1653)](l[f].fn,_0x174159)?l.splice(f,1):++f}return this}}function se(a,r){let s=t,l=e[s(1047)](X,a,r);return a[s(1827)][s(1299)](l,e[s(1529)](l,r))}function oe(a,r){let s=t,l=e[s(402)](re,a,r[s(1472)]);a[s(1827)][s(1597)](r,l)}function C(a,r){let s=t,l={CNkxa:function(D,L,z){return e[K(454)](D,L,z)},VccWP:s(1018)},f=e[s(952)](X,a,r),w=String[s(1356)+s(875)],b=a[s(1827)],y="\uFFFD",p="";for(let D=0;e.cCAVM(D,r);D++){let L=b[e[s(1523)](D,f)],z,V,te,Z;e[s(522)](128,L)===0?p+=e.QTAfX(w,L):e[s(961)](e[s(1684)](224,L),192)?D+1>=r?p+=y:(z=b[e.ryiwE(D+f,1)],e.OOzaB(192,z)!==128?p+=y:e[s(1277)]("pNyIK",s(1487))?(Z=e[s(1662)](e.scNhm(e[s(1158)](31,L),6),e[s(1158)](63,z)),e[s(1399)](Z,128)?p+=y:e.FwfmT(e[s(1655)],e[s(1655)])?(p+=e.qIPOS(w,Z),D++):(this[s(396)](s(1025),_0x426f48),this.onerror&&this[s(1229)](_0xaaa8d9))):this[s(396)](s(1018),l[s(1255)](_0x506156,l.VccWP,{..._0x38f2dc,data:_0x37c6a8[s(1442)]||""}))):e[s(457)](e[s(1334)](240,L),224)?e[s(1443)](D+2,r)?p+=y:(z=b[e.Snzsh(e[s(1804)](D,f),1)],V=b[e[s(1855)](D,f)+2],e.yAwsc(e[s(1036)](e.FftXu(z,e[s(506)](V,8)),49344),32896)?p+=y:(Z=e[s(1441)](e[s(391)](15,L)<<12|e[s(518)](e[s(393)](63,z),6),e.kpCRn(63,V)),Z<2048||e[s(935)](Z,55296)&&e[s(484)](Z,57343)?p+=y:(p+=w(Z),D+=2))):e.MmEne(248&L,240)?e[s(1443)](e.GiSLf(D,3),r)?p+=y:(z=b[e[s(1231)](e[s(1555)](D,f),1)],V=b[e[s(1529)](D+f,2)],te=b[e[s(1384)](D,f)+3],e.FSSfk(e.bKwqB(e[s(1071)](z|e.vwIaT(V,8),te<<16),12632256),8421504)?p+=y:(Z=e[s(1071)](e[s(549)](e.jFyEr(e[s(1036)](7,L)<<18,e[s(450)](e[s(1273)](63,z),12)),e.scNhm(e[s(698)](63,V),6)),63&te),e[s(408)](Z,65536)||e[s(695)](Z,1114111)?p+=y:(Z-=65536,p+=e[s(1475)](w,(Z>>10)+55296,e[s(1235)](1023&Z,56320)),D+=3))):p+=y}return p}function U(a,r){let s=t,l=r[s(1472)],f=0;for(let y=0;y<l;y++){let p=r[s(559)+"At"](y);p>=55296&&e[s(484)](p,56319)&&e[s(625)](e[s(1059)](y,1),l)&&(p=e[s(1808)](e[s(553)](e[s(1907)](p,10),r[s(559)+"At"](++y)),56613888)),f+=p<128?1:p<2048?2:e.WVuBw(p,65536)?3:4}e[s(1251)](pe,a,f);let w=re(a,f),b=a[s(1827)];for(let y=0;e[s(1265)](y,l);y++){let p=r[s(559)+"At"](y);e[s(1443)](p,55296)&&e.UpepS(p,56319)&&e[s(1265)](e[s(1233)](y,1),l)&&(p=e[s(1222)](e[s(793)](p,10),r[s(559)+"At"](++y))-56613888),e[s(1399)](p,128)?b[w++]=p:(e.yXHgi(p,2048)?b[w++]=e[s(1132)](p,6)&31|192:(p<65536?b[w++]=e[s(1381)](e[s(1684)](e[s(1089)](p,12),15),224):(b[w++]=e[s(1526)](e.AWouW(e[s(827)](p,18),7),240),b[w++]=e[s(1645)](e.VMgSS(e[s(1132)](p,12),63),128)),b[w++]=e[s(1203)](e[s(522)](p>>6,63),128)),b[w++]=e[s(635)](63,p)|128)}}function W(a,r){let s=t,l=e[s(909)](re,a,r[s(1315)]),f=a.bytes,w=r[s(1827)];for(let b=0,y=r[s(1315)];b<y;b++)f[e.jXVIC(b,l)]=w[b]}function ee(a){return a[t(1827)][e.TQygv(X,a,1)]}function Ye(a,r){let s=t,l=e[s(1357)](re,a,1);a[s(1827)][l]=r}function xe(a){let r=t,s=0,l=0,f;do f=e[r(1211)](ee,a),e[r(651)](s,32)&&(l|=e[r(1391)](e[r(501)](127,f),s)),s+=7;while(e.qoRNz(128,f));return l}function pe(a,r){let s=t;for(r>>>=0;e[s(956)](r,128);)e[s(528)](Ye,a,e[s(511)](127,r)|128),r>>>=7;e[s(1761)](Ye,a,r)}function vt(a,r){let s=t,l={kcpvM:function(f,w){return e[K(606)](f,w)},uwLUB:function(f,w){return e[K(694)](f,w)},tEppN:e[s(1007)]};if(e[s(445)](e[s(539)],e[s(539)])){if(_0x4d4f14)return new _0x3c6add(_0x38e30d[s(1860)],_0x17af55.protocol);if(l.kcpvM(_0x545e35,_0x3f1fe3))return new _0x4c5ce1(_0x47f19c.url,_0x848892[s(921)],_0x411b3f.headers);if(l[s(1800)](_0x503716,_0x1f4be2)&&l[s(1490)](l[s(1586)],typeof _0x3e5b6c)&&_0x541f40)return new _0x1b22d1(_0x2f4a64[s(1860)],_0x598174[s(921)+"s"])}else{let f=0,w=0,b=0,y;return y=e.jGCRd(ee,a),f=e[s(1145)](127,y),e.KJyjt(128,y)&&(y=ee(a),f|=e.lJlSM(e.AWouW(127,y),7),e[s(807)](128,y)&&(s(1349)===e[s(1721)]?(_0x4397f9.set(_0x54228e,_0xe477e6),_0x1ad03f[s(1597)](_0x9fffbf,_0x4827ec)):(y=e[s(1319)](ee,a),f|=e[s(1145)](127,y)<<14,e[s(1273)](128,y)&&(e.nleJe(e[s(830)],s(1803))?(e.sWRtV(_0x2e6f27,_0x364aa1,32),e.WAWne(_0x2fdded,_0x416bb6,e[s(880)](_0x18a80c,_0x51c501))):(y=e.vFKBb(ee,a),f|=e.FIaMr(e[s(937)](127,y),21),e.kGTrk(128,y)&&(y=e.JTedz(ee,a),w=e[s(638)](127,y),128&y&&(e[s(848)](e[s(1261)],e[s(1122)])?this[s(1872)+s(476)]():(y=ee(a),w|=e[s(863)](e.PSpJl(127,y),7),e[s(1036)](128,y)&&(y=e[s(880)](ee,a),w|=e[s(863)](127&y,14),e[s(1684)](128,y)&&(y=ee(a),w|=(127&y)<<21,e[s(1473)](128,y)&&(y=ee(a),b=127&y,e[s(995)](128,y)&&(y=e.EnZul(ee,a),b|=e[s(413)](e[s(522)](127,y),7))))))))))))),{low:e[s(461)](f,w<<28),high:e[s(889)](e[s(1130)](w,4),e.VGeJG(b,24)),unsigned:r}}}function xt(a,r){let s=t,l=e[s(877)](r[s(727)],0),f=e[s(1441)](r[s(727)]>>>28,e.JspFs(r[s(1074)],4))>>>0,w=e.CpjPh(r[s(1074)],24),b=w===0?e.mOwHE(0,f)?e[s(441)](l,16384)?e[s(1399)](l,128)?1:2:l<2097152?3:4:f<16384?e[s(1857)](f,128)?5:6:e[s(1622)](f,2097152)?7:8:e.DOOaJ(w,128)?9:10,y=re(a,b),p=a[s(1827)];switch(b){case 10:p[e.inkhR(y,9)]=e.ATXtG(e.zEInn(w,7),1);case 9:p[e.GHnoD(y,8)]=e[s(410)](9,b)?128|w:e[s(960)](127,w);case 8:p[e[s(553)](y,7)]=e[s(934)](8,b)?e[s(893)](f,21)|128:e[s(1569)](e[s(1886)](f,21),127);case 7:p[e[s(701)](y,6)]=e[s(1757)](7,b)?e[s(1526)](e[s(1307)](f,14),128):e[s(1914)](f,14)&127;case 6:p[y+5]=e[s(1746)](6,b)?e[s(877)](f,7)|128:e[s(1865)](e[s(1318)](f,7),127);case 5:p[e[s(941)](y,4)]=e[s(410)](5,b)?e.EtcDJ(128,f):127&f;case 4:p[y+3]=e[s(445)](4,b)?e[s(1203)](e[s(1670)](l,21),128):l>>>21&127;case 3:p[e[s(1863)](y,2)]=e[s(1519)](3,b)?e[s(893)](l,14)|128:e[s(638)](l>>>14,127);case 2:p[e[s(890)](y,1)]=e.GXBDB(2,b)?e.jvIVB(l,7)|128:e[s(1834)](e[s(893)](l,7),127);case 1:p[y]=e.dPIfd(1,b)?e.QyzrX(128,l):e[s(1238)](127,l)}}function nn(a){return v(a)}function Gt(a){return e[t(1407)](S,a)}let rn=65536,Qr=e.ZfGPy,_e=rn*rn,ke=_e*_e,rr=e[t(726)](ke,2),Oe=String[t(1528)+"e"][t(559)+"At"];class ue{constructor(r,s,l){let f=t;this.isLong=!0,this[f(727)]=e[f(889)](0,r),this[f(1074)]=0|s,this[f(898)]=!!l}static[t(774)](r){return r&&r.isLong===!0}static[t(1651)](r,s,l){return new ue(r,s,l)}static[t(1243)+"s"](r,s,l){let f=t;return l?ue[f(1243)+f(1862)](r,s):ue["fromByte"+f(927)](r,s)}static[t(1243)+t(1862)](r,s){let l=t;return new ue(e[l(889)](e[l(831)](r[0],e[l(636)](r[1],8))|r[2]<<16,e[l(1228)](r[3],24)),e[l(1662)](e[l(461)](e[l(1526)](r[4],e.ZklxQ(r[5],8)),e[l(1005)](r[6],16)),r[7]<<24),s)}static["fromByte"+t(927)](r,s){let l=t;return new ue(e.QyzrX(e[l(810)](r[4]<<24,e.QyYgE(r[5],16))|e[l(825)](r[6],8),r[7]),e.BcsjX(e.FftXu(e[l(1778)](e.lJrtx(r[0],24),e[l(450)](r[1],16)),e[l(1321)](r[2],8)),r[3]),s)}static[t(1013)](r){let s=t;return e[s(1562)](r,Qr)?ul:new ue(e.LJQQM(e[s(1015)](e.oqdWT(e[s(549)](Oe.call(r,0),e[s(851)](Oe[s(1770)](r,1),8)),e[s(793)](Oe.call(r,2),16)),e.lJlSM(Oe[s(1770)](r,3),24)),0),e[s(1640)](e[s(549)](e[s(1816)](Oe[s(1770)](r,4),e[s(636)](Oe[s(1770)](r,5),8)),Oe[s(1770)](r,6)<<16),e[s(707)](Oe[s(1770)](r,7),24))>>>0,!0)}[t(1080)](){let r=t;return String[r(1356)+"Code"](e[r(876)](255,this[r(727)]),e.OnNbZ(this.low>>>8,255),e[r(393)](e[r(946)](this[r(727)],16),255),e[r(736)](this[r(727)],24),255&this[r(1074)],e[r(1334)](this.high>>>8,255),e[r(894)](e[r(1019)](this[r(1074)],16),255),e[r(672)](this[r(1074)],24))}static[t(739)+"er"](r,s=!0){let l=t;if(e.EnZul(isNaN,r))return s?Kp:ul;if(s){if(e[l(936)](r,ke))return Vp}else if(e[l(1326)](l(420),e.PRWmG)){let f=this["_endpoin"+l(1659)]?.[l(1643)+l(1787)+"nt"](),w=this[l(591)]["reconnec"+l(834)+"ptor"](_0xdbe7d7[l(878)],_0x53e071[l(747)]);this[l(1301)+l(992)+"ent"](_0xb8684c(e.dixen,{code:1006,reason:_0x3b8661[l(747)]||l(1911)+l(578)+l(1824)+l(1543)+l(1876)+l(895)+f,willReconnect:w})),w&&this[l(1703)]();return}else{if(e[l(484)](r,-rr))return Jp;if(e[l(1369)](e.mcjtK(r,1),rr))return $p}return ue[l(1651)](r%_e|0,e[l(1640)](e.yeWWj(r,_e),0),s)}[t(768)](){let r=t;return e[r(792)](e[r(1099)],e[r(1099)])?this[r(843)]?.[r(1597)]({message_id:_0x297d2a,timestamp:_0x37a54d}):this.unsigned?e[r(1233)](e[r(1304)](e[r(662)](this.high,0),_e),e[r(742)](this.low,0)):e[r(890)](e[r(1304)](this.high,_e),e[r(1681)](this[r(727)],0))}[t(1396)](){let r=t;return e[r(514)](0,this[r(1074)])&&e[r(749)](0,this[r(727)])}[t(850)](r){let s=t;ue[s(774)](r)||(r=ue[s(739)+"er"](r));let l=e[s(1708)](this.high,16),f=65535&this[s(1074)],w=e[s(1437)](this.low,16),b=e[s(1579)](65535,this[s(727)]),y=e[s(662)](r[s(1074)],16),p=e[s(888)](65535,r[s(1074)]),D=e[s(1437)](r[s(727)],16),L=65535&r[s(727)],z=0,V=0,te=0,Z=0;return Z+=e[s(1863)](b,L),te+=Z>>>16,Z&=65535,te+=e[s(620)](w,D),V+=e[s(1708)](te,16),te&=65535,V+=e[s(1612)](f,p),z+=V>>>16,V&=65535,z+=e.vsrrQ(l,y),z&=65535,ue[s(1651)](e[s(636)](te,16)|Z,e.gbczy(e[s(908)](z,16),V),this[s(898)])}[t(845)](r){let s=t;return ue[s(774)](r)||(r=ue[s(739)+"er"](r)),this[s(898)]!==r[s(898)]&&e[s(1289)](e[s(1437)](this[s(1074)],31),1)&&e[s(1587)](r[s(1074)],31)===1?!1:this[s(1074)]===r[s(1074)]&&e[s(479)](this[s(727)],r.low)}[t(962)](){let r=t;return e[r(1168)](e[r(1383)],e[r(1263)])?this.low===-1&&e[r(1870)](-1,this[r(1074)])?ue[r(1651)](0,0,this[r(898)]):e[r(479)](-1,this[r(727)])?ue[r(1651)](0,e[r(756)](this.high,1),this.unsigned):ue.fromBits(e.nyRqe(this.low,1),this[r(1074)],this[r(898)]):_0x2d41e7[r(983)]()}[t(1483)](r){return r?this.toBytesLE():this.toBytesBE()}[t(814)+"E"](){let r=t,s=this[r(1074)],l=this.low;return[e[r(426)](255,l),e.XapYG(l,8)&255,e.LcjBf(l>>>16,255),l>>>24,e[r(422)](255,s),s>>>8&255,e.AABWo(e[r(1670)](s,16),255),e[r(1331)](s,24)]}[t(1864)+"E"](){let r=t,s=this.high,l=this[r(727)];return[s>>>24,e[r(1291)](e[r(1851)](s,16),255),e[r(1105)](e[r(1851)](s,8),255),255&s,e[r(1437)](l,24),e[r(781)](e[r(1019)](l,16),255),e[r(807)](e[r(1355)](l,8),255),e[r(876)](255,l)]}}let ul=new ue(0,0,!1),Kp=new ue(0,0,!0),$p=ue.fromBits(-1,2147483647,!1),Vp=ue.fromBits(-1,-1,!0),Jp=ue[t(1651)](0,-2147483648,!1);var sn=(function(a){let r=t;return a[a[r(1205)+r(1232)]=5001]=e[r(1615)],a[a[e[r(1054)]]=5002]=e[r(1054)],a[a[r(563)+"IES_ERROR"]=5003]=e.xUtEI,a[a[e[r(502)]]=5004]=e[r(502)],a[a[e[r(833)]]=5005]=e.EktDX,a})({});class ir{constructor(r){let s=t;this.type=r,this[s(1518)]=null}}class fl extends ir{constructor(r,s){let l=t;super(r),this[l(1606)]=s&&s[l(1606)]||null}}class hl extends ir{constructor(r,s){let l=t,f=(l(1223)+l(959))[l(751)]("|"),w=0;for(;;){switch(f[w++]){case"0":this[l(878)]=s&&s[l(878)]||5001;continue;case"1":this[l(1025)]=s&&s.error||null;continue;case"2":this[l(1606)]=s&&s[l(1606)]||"";continue;case"3":this[l(1552)]=s&&s[l(1552)]||0;continue;case"4":super(r);continue;case"5":this[l(491)]=s&&s[l(491)]||"";continue;case"6":this.lineno=s&&s[l(997)]||0;continue}break}}}class xl extends ir{constructor(r,s){let l=t,f={pHaLG:function(w,b){return e[K(457)](w,b)},sTCCj:function(w,b){return e[K(1320)](w,b)}};if(e[l(1733)](l(1325),e[l(1434)])){let w=e[l(1752)][l(751)]("|"),b=0;for(;;){switch(w[b++]){case"0":super(r);continue;case"1":this[l(782)]=s&&s.wasClean||!1;continue;case"2":this["willReco"+l(387)]=s&&s[l(1698)+"nnect"]||!1;continue;case"3":this[l(747)]=s&&s[l(747)]||"";continue;case"4":this[l(878)]=s&&s[l(878)]||0;continue}break}}else return f[l(1064)](this[l(1654)+"ndex"],this[l(1809)+"s"].length)?!0:f[l(541)](this[l(1252)+l(720)+l(1401)+"t"],this[l(1873)+"es"])}}class pl extends ir{constructor(r,s){let l=t;super(r),this.data=s&&s[l(971)]||null}}class gl extends pl{constructor(r,s){let l=t;super(r),this.data=s&&s.data||null,this[l(1606)]=s&&s[l(1606)]||null}}class ml extends ir{constructor(r,s){let l=t;super(r),this[l(971)]=s&&s[l(971)]||null}}function at(a,{message:r,code:s,error:l}){return new hl(a,{message:r,code:s,error:l})}function pt(a,{code:r,reason:s,wasClean:l,willReconnect:f}){return new xl(a,{code:r,reason:s,wasClean:l,willReconnect:f})}function wl(a,{data:r,message:s}){return new gl(a,{data:r,message:s})}function _l(a,{data:r}){let s=t,l={KXGvj:function(f,w){return e[K(694)](f,w)},JpjcH:e[s(1007)],XCeAh:e[s(786)]};if(e[s(1750)]===e[s(677)])WFjWhl[s(1365)](WFjWhl[s(1196)],typeof _0x4d4a29)&&_0x8012ee[s(465)+s(1720)]&&_0x32ca05[s(1418)+s(1267)](_0x22ffe9,_0x4fec5f[s(465)+s(1720)],{value:WFjWhl[s(523)]}),_0x524f4f[s(1418)+s(1267)](_0x36f3ad,s(822)+"le",{value:!0});else return new ml(a,{data:r})}function wa(a,{message:r}){return new fl(a,{message:r})}class yl{constructor(r,s){let l=t;this[l(1809)+"s"]=r,this[l(1873)+"es"]=s,this[l(1654)+"ndex"]=0,this[l(1252)+l(720)+l(1401)+"t"]=0}[t(713)+"pointCon"+t(1550)](){let r=t;this[r(1654)+"ndex"]=0,this[r(1252)+r(720)+"riesCount"]=0}[t(1706)+"es"](){let r=t;this[r(1252)+r(720)+r(1401)+"t"]=0}[t(1643)+"ntEndpoint"](){let r=t;if(e.SjzYz(e.vkEwZ,e[r(1127)])){let s=_0x186884[r(751)](/\./)[r(534)](w=>_0x787263(w)),l=[];return l[0]=e[r(1690)](_0x4f259b,e[r(1438)](s[0],s[1])),l[1]=_0x3407b8(e.mIEyG(s[2],s[3])),[e[r(757)],r(1535),e[r(757)],e[r(757)],e.YAZZI,r(918),l[0],l[1]][r(1884)]("")}else return this.endpoints[this[r(1654)+r(1346)]]}[t(1643)+t(1787)+t(1711)+t(1366)](){let r=t;return this[r(1252)+"ndpointT"+r(1401)+"t"]}[t(1845)+"chMaxTries"](){let r=t;return!!(e[r(1493)](this[r(1654)+r(1346)],this[r(1809)+"s"][r(1472)])||e[r(737)](this[r(1654)+r(1346)],this[r(1809)+"s"][r(1472)]-1)&&this["currentE"+r(720)+r(1401)+"t"]===this[r(1873)+"es"])}[t(1727)+"rentEndp"+t(883)+t(1377)+t(685)](){let r=t;return e[r(1266)](this[r(1654)+r(1346)],this[r(1809)+"s"][r(1472)])?!0:e[r(1333)](this[r(1252)+"ndpointTriesCount"],this[r(1873)+"es"])}[t(1338)+"ackupEndpointAnd"+t(799)+t(1371)](){let r=t;return this["currentE"+r(720)+r(1401)+"t"]=1,this["currentI"+r(1346)]++,this.endpoints[this[r(1654)+r(1346)]]}[t(1643)+t(1787)+"ntAndUpd"+t(682)](){let r=t;return this[r(1252)+"ndpointTriesCount"]++,this[r(1643)+r(1787)+"nt"]()}}let sr=(e[t(1881)](t(1602)+"d",typeof globalThis)&&e[t(1777)](e.QakbS,globalThis[t(1913)+t(930)].name)||e[t(800)](e[t(1007)],typeof window)&&e[t(993)]===window[t(1913)+t(930)].name)&&e[t(1506)](e[t(1007)],typeof document),Dn=e[t(1007)]!=typeof globalThis&&(e[t(862)](e[t(1023)],globalThis[t(1913)+t(930)].name)||e[t(1844)](e[t(690)],globalThis[t(1913)+t(930)][t(1210)]))&&e.VRqhb(e[t(1007)],typeof tt),ei=(e[t(694)](e[t(1007)],typeof globalThis)&&e.xgIIu(e[t(1023)],globalThis[t(1913)+t(930)][t(1210)])||e[t(457)](e[t(1007)],typeof globalThis)||e.Fyilz(e[t(1007)],typeof globalThis)&&!!globalThis[t(657)+"Bridge"])&&e[t(1791)](e[t(1007)],typeof wx),ti=t(1602)+"d"!=typeof globalThis&&(e[t(690)]===globalThis[t(1913)+t(930)][t(1210)]||e.ENZRj(e[t(1755)],globalThis[t(1913)+t(930)][t(1210)])||e[t(1617)](e[t(1734)],globalThis[t(1913)+"tor"][t(1210)]))&&e[t(1506)](e.FKtwo,typeof self),Zp=e[t(1506)](e.FKtwo,typeof globalThis)&&e.sQWwT===globalThis[t(1913)+t(930)].name&&e.FKtwo!=typeof global&&e[t(1842)](e.sQWwT,global[t(1913)+t(930)][t(1210)])&&e[t(1791)](e[t(1007)],typeof process)&&!!process.version;class _a{constructor(){let r=t;this[r(1723)+"rs"]={}}emit(r,...s){let l=t,f=this._listeners[r];if(f)f.slice()[l(1831)](w=>w.fn.apply(w[l(1495)],s));else if(e[l(721)](e[l(1253)],r)&&!this[l(1229)]){let w=s[l(1472)]&&s[0];if(e[l(1353)](w,Error))throw w;let b=new Error(l(451)+"d error."+(w?e.vsrrQ(e.wnJws(" (",w[l(1606)]),")"):""));throw b[l(1485)]=w,w}return this}[t(507)](r,s){let l=t;if(e[l(772)](void 0,r))this[l(1723)+"rs"]={};else if(e[l(1541)](void 0,s))this._listeners[r]=null;else{let f=this._listeners[r];if(f)for(let w=0;e[l(441)](w,f[l(1472)]);)e[l(737)](f[w].fn,s)?f[l(783)](w,1):++w}return this}on(r,s,l){let f=t;return(this[f(1723)+"rs"][r]||(this[f(1723)+"rs"][r]=[]))[f(1882)]({fn:s,ctx:l||this}),this}}class Yp extends _a{[t(969)+t(1596)+t(1632)](r){let s=t;return e[s(1500)](e[s(1693)],e[s(917)])?PhWpWS[s(542)](_0x42161e,_0x5e15d3)&&(PhWpWS.twqvU(_0x39675a,PhWpWS[s(600)])||PhWpWS[s(1164)](_0x377d23,s(1218)))?!0:PhWpWS[s(1268)](_0x2609be,_0x4901bd):r.errMsg||r[s(1554)]?(s(944)+" "+(r.errMsg||"")+s(1559)+(r[s(1554)]||""))[s(1410)]():JSON[s(1894)+"y"](r)}constructor(r,s,l){let f=t;super(),this._socket=null,ei&&wx["connectS"+f(650)]&&(this[f(475)]=wx["connectS"+f(650)]({url:r,protocols:s,header:l,fail:this["_createS"+f(914)+"lHandler"][f(583)](this),success:this["_createS"+f(1103)+f(1504)+f(1566)][f(583)](this)})),Dn&&tt[f(869)+f(650)]&&(this[f(475)]=tt[f(869)+"ocket"]({url:r,protocols:s,header:l,fail:this[f(1661)+"ocketFai"+f(1234)].bind(this),success:this[f(1661)+"ocketSuc"+f(1504)+"ler"][f(583)](this)}))}[t(1661)+t(1103)+t(1504)+"ler"](){let r=t,s={GgNrg:function(l,f){return e[K(619)](l,f)},OKyoS:function(l,f){return e.JVWYR(l,f)},SCXxF:function(l,f){return e[K(424)](l,f)},Vbtdi:function(l,f){return l+f},PXzxE:function(l,f){return e[K(863)](l,f)},qQoTm:function(l,f){return e[K(625)](l,f)}};Promise[r(983)]()[r(1893)](()=>{let l=r;if(e[l(821)](e.jvQSR,e[l(1136)])){let f=_0x28aede[l(559)+"At"](_0xa2c4d6);loKVOx[l(1278)](f,55296)&&loKVOx[l(1717)](f,56319)&&_0x5284ba+1<_0x253c6f&&(f=loKVOx[l(460)](loKVOx[l(744)](loKVOx[l(1781)](f,10),_0x42e968[l(559)+"At"](++_0x4230a8)),56613888)),_0xe5a72c+=loKVOx[l(1524)](f,128)?1:loKVOx[l(1524)](f,2048)?2:f<65536?3:4}else this["_addWsLi"+l(476)]()})}[t(1661)+"ocketFai"+t(1234)](r){let s=t,l={ZMXLC:function(f,w){return f===w},uHGtX:e[s(1253)],oBjcQ:function(f,w){return f instanceof w},Rplwe:function(f,w){return e[s(1107)](f,w)},TXaac:"Unhandle"+s(1776),tOBZT:e.pPyRz,PHxoJ:s(1663),IoNQg:function(f,w,b){return e.NzDTO(f,w,b)},CuREi:e[s(540)]};if(e.lhkyy("YKUCf",e[s(1765)]))Promise[s(983)]()[s(1893)](()=>{let f=s,w={qDwpX:function(b,y){return l.ZMXLC(b,y)},QrCzA:l[f(1546)],UGDlm:function(b,y){return l[f(1208)](b,y)},PQgxr:function(b,y){return l[f(1820)](b,y)},WDpyy:l[f(676)],QWItm:function(b,y){return l[f(1820)](b,y)}};if(l[f(487)](l.tOBZT,l[f(1239)])){let b=this[f(1723)+"rs"][_0x1b519e];if(b)b[f(579)]()[f(1831)](y=>y.fn[f(994)](y.ctx,_0xafbc8d));else if(uPimOR[f(1180)](uPimOR[f(1429)],_0x55c6ea)&&!this[f(1229)]){let y=_0x2b1604[f(1472)]&&_0x330b95[0];if(uPimOR[f(1580)](y,_0xf901d))throw y;let p=new _0x5c4f47(uPimOR[f(1340)](uPimOR[f(538)],y?uPimOR[f(1012)](uPimOR[f(1340)](" (",y[f(1606)]),")"):""));throw p.context=y,y}return this}else{let b=at(l[f(1546)],{message:this[f(969)+f(1596)+f(1632)](r)});this[f(396)](l[f(1546)],b);let y=l[f(717)](pt,l[f(1209)],{reason:this[f(969)+f(1596)+f(1632)](r)});this[f(396)](l.CuREi,y)}});else return s(555)+"_"+this[s(1732)]}[t(1872)+"steners"](){let r=t,s={wqTes:e.WVOkZ,mcYOE:function(l,f,w){return e[K(981)](l,f,w)}};this[r(475)].onOpen(l=>{let f=r;this[f(396)](s[f(1466)],s.mcYOE(_l,s[f(1466)],{...l,data:l[f(1442)]||""}))}),this[r(475)][r(1167)](l=>{let f=r;this[f(396)](f(1195),pt(f(1195),{...l}))}),this._socket[r(1171)+"e"](l=>{let f=r,w={XWLYn:function(b,y,p){return e[K(1786)](b,y,p)},RjQXg:e[f(540)],RxUCb:function(b,y,p){return e[f(455)](b,y,p)}};if(e[f(1250)](e[f(1026)],e[f(861)]))this.emit(f(1606),e[f(1531)](wl,e[f(1742)],{...l}));else{if(this[f(1114)+f(604)](),this[f(832)+"mer"](),this[f(1463)+f(1818)+"rs"](),this[f(1657)+f(1741)](1e3,_0x166639),this[f(1703)+f(743)]=!1,_0x1d6431&&this[f(1630)+f(1081)]()&&!this[f(1525)+"osed"]){if(this[f(1571)+"tManager"]?.[f(1845)+f(999)+"es"]()){let y=this["_endpoin"+f(1659)]?.[f(1643)+f(1787)+"nt"]();this["_dispatchCloseEv"+f(1880)](w[f(1898)](_0x9e80c5,w.RjQXg,{code:1006,reason:"connect "+y+(f(764)+f(773)+f(554)+f(596)),wasClean:!0}))}else{let y=this[f(591)][f(478)+"tInterce"+f(1641)](_0x5584c0,_0x8deea4);this[f(1301)+f(992)+f(1880)](w[f(1898)](_0x2e7c94,f(1195),{code:_0x5ed7c9,reason:_0x53897f,wasClean:!0,willReconnect:y})),y&&this[f(1703)]()}return}this._navigatorOnline()||this[f(1525)+f(1248)]?this[f(1301)+f(992)+"ent"](w[f(1898)](_0x12fbf6,w[f(480)],{code:_0x1cbafa,reason:f(1185)})):this["_dispatc"+f(992)+f(1880)](w[f(1814)](_0x136fb6,w[f(480)],{code:1006,reason:f(1680)+f(891)+"ork offl"+f(1521)})),this._ws=null,this[f(1571)+f(1659)]?.[f(713)+"pointCon"+f(1550)](),this[f(901)+f(1188)]?.[f(835)+"nter"]()}}),this[r(475)][r(990)](l=>{let f=r;this.emit(f(1025),e[f(1039)](at,e.CmMIf,{...l,message:l[f(1442)]||""}))})}[t(1162)](r){let s=t,l={aqzTG:function(f,w,b){return e[K(1761)](f,w,b)}};if(e[s(1836)](r,Uint8Array))if(e[s(1805)](e[s(765)],e[s(495)])){let f=e[s(947)].split("|"),w=0;for(;;){switch(f[w++]){case"0":PhWpWS[s(715)](_0x3e5229,b=>({...b,get:(y,p,D)=>_0x38099c(y,p)||b[s(1112)](y,p,D),has:(y,p)=>!!_0x423349(y,p)||b[s(1092)](y,p)}));continue;case"1":PhWpWS.RVpvq(_0x4ba674);continue;case"2":PhWpWS[s(490)](_0x53f7c2);continue;case"3":_0x409921=[PhWpWS.ItpuH,"getKey",PhWpWS[s(1697)],PhWpWS[s(1284)],PhWpWS.WpUnz];continue;case"4":_0x5c0fae=[PhWpWS[s(463)],PhWpWS[s(1588)],PhWpWS[s(1458)],PhWpWS[s(1691)]];continue;case"5":_0x2d0993=new _0x38b9c7;continue}break}}else{let f=r[s(1676)][s(579)](r[s(1749)+"et"],e[s(941)](r[s(1186)+"th"],r[s(1749)+"et"]));this._socket&&this[s(475)][s(1162)]({data:f,fail:w=>{let b=s;this[b(396)](e[b(1253)],e[b(1576)](at,b(1025),{message:this[b(969)+b(1596)+b(1632)](w)}))}})}else this[s(475)]&&this._socket[s(1162)]({data:r,fail:f=>{let w=s;this[w(396)](w(1025),l[w(1076)](at,w(1025),{message:this["_formatErrorMess"+w(1632)](f)}))}})}[t(1195)](r,s){let l=t;this[l(475)]&&this._socket[l(1195)]({code:r,reason:s})}[t(1564)+t(1626)](r,s){this.on(r,s)}[t(1512)+t(624)+t(1275)](r,s){this[t(507)](r,s)}get readyState(){let r=t;return this._socket[r(1173)+"te"]}get[t(1153)+"pe"](){let r=t;return this._socket[r(1153)+"pe"]}set[t(1153)+"pe"](r){}get[t(1860)](){let r=t;return this[r(475)][r(1860)]}get[t(921)](){return this[t(475)].protocol}get[t(1116)+"ns"](){let r=t;if(e[r(842)]!==e[r(1179)])return this._socket[r(1116)+"ns"];_0x22f38a.log(_0x3072f6)}get["buffered"+t(431)](){return 0}}function Xp(a,r){let s=t;if(r)return new r(a[s(1860)],a[s(921)]);if(ei||Dn)return new Yp(a.url,a[s(921)],a[s(1507)]);if((sr||ti)&&e[s(800)](e[s(1007)],typeof WebSocket)&&WebSocket)return new WebSocket(a[s(1860)],a[s(921)+"s"])}function Qp(a){let r=t;return!!(a||ei&&wx[r(869)+"ocket"]||Dn&&tt[r(869)+"ocket"]||e[r(585)](sr,ti)&&e[r(1007)]!=typeof WebSocket&&WebSocket)}function El(a,r,s){let l=t,f={hGYgm:function(y,p){return e[K(976)](y,p)},MhcuL:l(919)+l(432)+l(582)+"imes in "+l(1915),uzQHl:function(y,p){return e.vOvqa(y,p)},fffJT:function(y,p){return e.SFvZp(y,p)}},w=-1;async function b(y){let p=l;return f[p(496)](y,w)?Promise[p(1219)](new Error(f[p(1405)])):(w=y,f[p(860)](y,s[p(1472)])?Promise[p(983)]():s[y][p(583)](a)(r,b[p(583)](null,f[p(421)](y,1))))}e.jUMbe(b,0)}function bl(a){let r=t,s=0,l=0;for(let f=0;f<a[r(1472)];++f)l=a[r(559)+"At"](f),e[r(408)](l,128)?s+=1:e[r(625)](l,2048)?s+=2:e.GlFZl(64512&l,55296)&&e.GlFZl(e[r(1456)](64512,a[r(559)+"At"](e[r(1612)](f,1))),56320)?(++f,s+=4):s+=3;return s}function vl(a,r,s){let l=t,f={xaCOp:function(w,b){return w!=b},qYMmb:e.zGmON,kQdzg:function(w,b){return e[K(542)](w,b)},FojYz:function(w,b){return w==b},vfBcC:e.sDmtG};if(e[l(1553)]!==e.arkju)try{return f[l(1430)](f[l(592)],typeof _0x4db8d)&&(f[l(1411)](_0x43497c,_0x18ca1d)||_0x28add1[l(1676)]&&f[l(1411)](_0x1fd2ff[l(1676)],_0x2c2e9a))||f[l(1430)](f[l(592)],typeof _0x2858e9)?"":(_0x4f1984.parse(_0x1153a3),l(493)+"ion/json")}catch{return f[l(403)](f.qYMmb,typeof _0x30ec9b)?f[l(1176)]:""}else{if(e[l(1747)](e[l(1175)](s,r),1))return"";let w="";for(let b=r;e[l(1135)](b,s);){let y=a[b++];if(y<=127)w+=String[l(1356)+"Code"](y);else if(e[l(1369)](y,192)&&e[l(651)](y,224))w+=String[l(1356)+l(875)](e[l(1120)](31&y,6)|e.bhkaJ(63,a[b++]));else if(y>=224&&y<240)w+=String[l(1356)+l(875)](e[l(1150)](e[l(598)](15,y),12)|(63&a[b++])<<6|e[l(393)](63,a[b++]));else if(e[l(1493)](y,240)){let p=e[l(712)](e.oqdWT(e[l(1287)](e[l(636)](e[l(522)](7,y),18),(63&a[b++])<<12)|e[l(391)](63,a[b++])<<6,e[l(986)](63,a[b++])),65536);w+=String[l(1356)+l(875)](e.YorGu(55296,e[l(1089)](p,10))),w+=String[l(1356)+l(875)](56320+e[l(870)](1023,p))}}return w}}function ya(a,r,s){let l=t,f={UMczW:e[l(467)],WtXbP:function(p,D){return e.qcKCH(p,D)},CqfVG:l(795)+"s alread"+l(517),uQNPd:e.jZFsM},w=s,b,y;for(let p=0;e[l(408)](p,a[l(1472)]);++p)if(e.nZcEP(e[l(1038)],e[l(1516)])){let D=f[l(1022)][l(751)]("|"),L=0;for(;;){switch(D[L++]){case"0":this[l(1887)+"WebSocket"](_0x89d355,_0x351f7d);continue;case"1":this[l(1114)+"ngTimer"]();continue;case"2":this[l(998)+l(1533)]?.[l(428)]();continue;case"3":if(f.WtXbP(this._ws.readyState,this[l(1796)])||this[l(1294)][l(1173)+"te"]===this[l(1748)])return void this[l(663)](f.CqfVG);continue;case"4":this[l(462)+"balEvent"+l(1626)]();continue;case"5":this[l(1525)+l(1248)]=!0;continue;case"6":if(!this[l(1294)])return void this[l(663)](f[l(381)]);continue;case"7":this[l(832)+l(652)]();continue}break}}else if(b=a[l(559)+"At"](p),b<128)r[s++]=b;else if(e.RsjaB(b,2048))r[s++]=e[l(437)](b,6)|192,r[s++]=e[l(823)](e.htoVZ(63,b),128);else if(e[l(564)](64512,b)===55296&&e[l(1165)](e.RomoG(64512,y=a[l(559)+"At"](e.TCjOx(p,1))),56320)){let D=e[l(1649)][l(751)]("|"),L=0;for(;;){switch(D[L++]){case"0":b=e[l(1863)](e[l(1231)](65536,e[l(703)](1023&b,10)),e[l(1465)](1023,y));continue;case"1":r[s++]=e[l(1308)](b>>12&63,128);continue;case"2":r[s++]=e.MdeEu(b>>6,63)|128;continue;case"3":r[s++]=e[l(904)](b>>18,240);continue;case"4":++p;continue;case"5":r[s++]=63&b|128;continue}break}}else r[s++]=b>>12|224,r[s++]=e[l(781)](e[l(1017)](b,6),63)|128,r[s++]=e.Wbsig(e[l(951)](63,b),128);return s-w}async function Sl(a){let r=t;if(e[r(1347)]==typeof a){let s=new Uint8Array(e.STJhg(bl,a));return e[r(1368)](ya,a,s,0),s}return e[r(1353)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[r(1676)],a[r(1749)+"et"],a[r(1186)+"th"])}function eg(a){let r=t,s={MqNCk:function(l,f){return l||f},XEKQQ:function(l,f){return e[K(606)](l,f)},lpJIQ:function(l,f){return e[K(694)](l,f)},mVZvt:e.FKtwo,DPZXA:e.fhBYn};if(e[r(791)](e[r(1508)],e[r(1330)]))try{if(e.ocxkf===e.ocxkf)return e[r(800)](r(1594),typeof a)&&(e[r(1836)](a,ArrayBuffer)||a.buffer&&e[r(1547)](a[r(1676)],ArrayBuffer))||e[r(1347)]!=typeof a?"":(JSON[r(1479)](a),"applicat"+r(967));this[r(1732)]=_0x403b70,this[r(1061)]=_0x40b26a,this._qosDB=_0x5e4301?_0x1e9c79:_0x325799?_0x4c3da5:null}catch{return e[r(1266)]("string",typeof a)?e[r(686)]:""}else{if(s[r(667)](_0x278b71,_0x177ddb))return new _0x64ff9b(_0x2a1ffc,_0x185554);if(s[r(1798)](_0x38be66,_0x37af51)&&s[r(1351)](s[r(841)],typeof _0x2e53c0))return new _0x5d84f6(_0x2cc853,_0x58febb);if(s[r(1798)](_0x58141d,_0x1f71c2)&&s[r(841)]!=typeof _0x25b52e)return new _0x5cafb5(_0x47aa43,_0x54883c);throw new _0x431049(s[r(787)])}}let tg=(a,r)=>{let s=t;if(e.qcKCH(e[s(535)],s(1139)))return!0;switch(a){case e[s(1082)]:case s(1794):return{[s(419)+a]:1,"x-tt-env":r};default:return{}}};class ng{constructor(r){let s=t;this[s(526)+s(1366)]=r,this[s(1417)]=0}[t(1595)](){let r=t;if(e.uJfec(e.RdeUx,e.RdeUx))this[r(1417)]++;else return e.SrIFZ(e.zGmON,typeof _0x1c9b9b)&&(e[r(1547)](_0xd71ca1,_0x1a762c)||_0x117ded[r(1676)]&&_0x18a1cb.buffer instanceof _0x44b4c6)||e.SrIFZ(e[r(1347)],typeof _0x4242d7)?"":(_0x432f16[r(1479)](_0xcca44c),r(493)+"ion/json")}["checkRea"+t(790)+"nt"](){let r=t;return e.uZfZx(this[r(1417)],this[r(526)+"ount"])}[t(835)+t(1539)](r=0){let s=t;this[s(526)+s(1366)]=r,this[s(1417)]=0}}async function rg(a){let r=t,s={JGVMX:"unknown "+r(747),tptfm:e[r(603)],HOUvH:function(l,f){return e[r(706)](l,f)},BteaV:e[r(1359)],MBTAZ:e[r(803)],vibFx:function(l,f){return e[r(1648)](l,f)}};return new Promise(l=>{let f=r,w={wMgUP:s.JGVMX};if(!sr)return l(s[f(854)]);try{let b=document[f(1125)+f(865)](f(1719));window[f(555)+"JSONP"]=y=>{let p=f;document[p(1782)][p(1283)+p(1900)](b),window["frontier"+p(1213)]=void 0,l(y&&y[p(762)]||w[p(1503)])},b[f(1245)]=s.tptfm,b[f(628)]=s[f(414)](a.replace(/^ws/,s[f(530)]),s[f(477)]);try{document.body[f(1909)+"ild"](b)}catch{document[f(1782)]["removeCh"+f(1900)](b)}}catch{window[f(555)+f(1213)]=void 0,s[f(1199)](l,f(1154)+"reason")}})}function on(a,r,s){let l=t;return!!a?.find(f=>f[l(661)]===r&&f[l(1151)]===s)}function or(a,r){let s=t;return a?.[s(1271)](l=>l[s(661)]===r)?.[s(1151)]}let Ea=null;async function ig(){let a=t;return Ea||(Ea=Promise[a(983)]()[a(1893)](Ft.bind(Ft,e.GYcqA))),Ea}class sg extends _a{constructor(r,s){let l=t;super(),this[l(760)]=r,this[l(485)]=s,this[l(843)]=void 0,this["_initPro"+l(1360)]=null}async openDB(){await this[t(550)]()}async[t(550)](){let r=t;if(!this[r(843)]){if(this[r(1810)+r(1360)])return this["_initPro"+r(1360)];try{let s=this[r(760)],l=this[r(485)];this[r(1810)+r(1360)]=(async()=>{let f=r,w={LhBXr:f(1025),yUqyA:function(b,y){return e.CUGGc(b,y)},slUYG:function(b){return e.RSbIm(b)},szRmm:e[f(767)]};if(e[f(1133)](e[f(1152)],e[f(1152)])){let b=()=>{let D=f;_0x4d6ec8["removeEv"+D(624)+D(1275)](D(436),y),_0x24d9f7[D(1512)+D(624)+D(1275)](uvWuIU[D(1156)],p)},y=()=>{let D=f;uvWuIU[D(788)](_0x8739b9,_0x4411af(_0x12f4fd.result)),uvWuIU[D(1428)](b)},p=()=>{let D=f;_0x4849cb(_0x5e8c33.error),uvWuIU[D(1428)](b)};_0x3a345a.addEventListener(uvWuIU[f(1409)],y),_0x70f029[f(1564)+f(1626)](uvWuIU.LhBXr,p)}else{let{openDB:b}=await e.slIfU(ig);this[f(843)]=await e.cdrTt(b,f(555)+"_"+s,1,{upgrade(y){let p=f;y[p(1432)+p(1896)+"e"](s,{keyPath:l})}})}})(),await this[r(1810)+"mise"]}catch(s){console[r(1126)](s)}finally{this[r(1810)+r(1360)]=null}}}async get(r){let s=t,l={vfNdB:function(f,w,b){return e[K(1272)](f,w,b)},ASAnB:e[s(401)],cYIOo:e[s(899)]};if(e[s(1035)](s(1374),e[s(1419)])){let f=l[s(642)](_0x3f2df4,l[s(1386)],{message:l[s(439)]});this[s(932)+s(1618)]&&this[s(932)+s(1618)](f)}else try{return await this._init(),this[s(843)]?.[s(1112)](this[s(760)],r)}catch(f){console.log(f)}}async set(r,s){let l=t;return await this[l(550)](),this[l(843)]?.[l(611)](this[l(760)],r)}async[t(1879)](r){let s=t;try{return await this[s(550)](),this._qosDB?.[s(1194)](this[s(760)],r)}catch(l){console[s(1126)](l)}}async[t(653)](){let r=t,s={KJbwT:function(l,f){return e[K(1048)](l,f)},zJAWA:function(l,f){return e.STJhg(l,f)},nSUDy:function(l,f,w){return e.foRlb(l,f,w)}};try{return e[r(737)](e[r(1683)],e.VSGWP)?LcXkSM.KJbwT(LcXkSM[r(745)](_0x277f0d,4)[r(1884)]("0"),LcXkSM[r(1392)](_0x4b058a,_0x32445f,2)[r(465)](16))[r(579)](-4):(await this._init(),this._qosDB?.[r(653)](this[r(760)]))}catch(l){console.log(l)}}async[t(543)](){let r=t;if(e[r(1682)](e[r(590)],e[r(1034)]))return await this._init(),this[r(843)]?.[r(1141)+"ys"](this[r(760)]);{let s=_0x203688.length&&_0x27b745[0];if(e[r(1390)](s,_0x28bffc))throw s;let l=new _0x19f5fd(e[r(1246)](e[r(780)],s?e[r(905)](" (",s[r(1606)])+")":""));throw l[r(1485)]=s,s}}async[t(1044)](){let r=t;return await this[r(550)](),this[r(843)]?.[r(1044)](this[r(760)])}async[t(428)](){let r=t;try{this[r(843)]?.[r(1195)](),this[r(843)]=void 0}catch(s){console[r(1126)](s)}}get isReady(){let r=t;try{return e[r(508)](r(1303),e[r(972)])?!!this._qosDB:this[r(475)][r(1116)+"ns"]}catch(s){return console.log(s),!1}}}class og{constructor(r,s){let l=t;this[l(1732)]=r,this[l(1061)]=s,this[l(843)]=localStorage}async openDB(){}get[t(486)](){let r=t;return r(555)+"_"+this[r(1732)]}async get(r){let s=t,l=this[s(843)][s(545)](this[s(486)]);return JSON[s(1479)](e[s(585)](l,"{}"))[r]}async[t(1597)](r,s){let l=t,f=this[l(843)].getItem(this[l(486)]),w=JSON[l(1479)](e[l(585)](f,"{}"));return w[s||r[this._pathKey]]=r,this[l(843)][l(1903)](this._prefix,JSON.stringify(w)),s||r[this[l(1061)]]}async del(r){let s=t,l=this[s(843)][s(545)](this[s(486)]),f=JSON[s(1479)](e[s(546)](l,"{}"));return f[r]=void 0,this[s(843)][s(1903)](this._prefix,JSON[s(1894)+"y"](f))}async[t(653)](){let r=t;return this._qosDB[r(653)]()}async[t(543)](){let r=t,s=this[r(843)][r(545)](this._prefix),l=JSON[r(1479)](e[r(546)](s,"{}"));return Object[r(543)](l)}async[t(1044)](){let r=t,s=this[r(843)].getItem(this[r(486)]),l=JSON[r(1479)](e[r(585)](s,"{}"));return Object[r(828)](l)}closeDB(){return Promise[t(983)]()}get isReady(){let r=t;if(e[r(1474)](r(1633),e[r(423)]))try{e[r(1368)](_0x53b945,this,_0x3ae7e6,[_0xe695d4,_0x287d33,_0x19184e])}catch(s){let l=e.LOdCF(_0x296598,e[r(1253)],{message:s[r(1606)],code:_0x3b3e8f[r(840)+"OR"],error:s});this[r(1301)+r(492)+r(1880)](l)}else return!!this[r(843)]}}class ag{constructor(r,s){let l=t;this._DBName=r,this[l(1061)]=s,this[l(843)]=Dn?tt:ei?wx:null}async[t(417)](){}get _prefix(){let r=t,s={KHrbD:function(l,f,w){return e.jyXLl(l,f,w)}};if(e[r(1634)](e[r(1447)],e[r(988)]))dtLHNB[r(699)](_0x5246e5,_0x3af04f,74),dtLHNB[r(699)](_0x56e4b2,_0x1d4c2e,_0x44d805);else return r(555)+"_"+this[r(1732)]}async get(r){let s=t;if(e[s(409)](e[s(1476)],s(926))){let l=this[s(843)][s(565)+s(1221)](this[s(486)]);return JSON[s(1479)](e[s(546)](l,"{}"))[r]}else _0x4db02e[s(1126)](_0xe04b29)}async[t(1597)](r,s){let l=t,f=this[l(843)][l(565)+l(1221)](this[l(486)]),w=JSON.parse(e.grZje(f,"{}"));return w[s||r[this[l(1061)]]]=r,this[l(843)][l(1534)+l(1221)](this._prefix,JSON[l(1894)+"y"](w)),s||r[this[l(1061)]]}async[t(1879)](r){let s=t;if(e[s(1624)](e[s(954)],e.rDNel))return _0x145fdb||(_0x212880=[_0x2f13d9,_0x5338c0,_0x3c17db,_0xa60311,_0x32ac30]);{let l=this[s(843)].getStorageSync(this[s(486)]),f=JSON[s(1479)](l||"{}");return f[r]=void 0,this[s(843)]["setStora"+s(1221)](this._prefix,JSON[s(1894)+"y"](f))}}async clear(){let r=t;return this._qosDB[r(1256)+r(1692)]()}async keys(){let r=t,s=this[r(843)][r(565)+r(1262)+"nc"](this[r(486)]),l=JSON[r(1479)](e[r(1178)](s,"{}"));return Object[r(543)](l)}async[t(1044)](){let r=t,s=this[r(843)][r(565)+r(1262)+"nc"](this._prefix),l=JSON[r(1479)](e.bhWbq(s,"{}"));return Object.values(l)}[t(428)](){return Promise[t(983)]()}get isReady(){return!!this[t(843)]}}function Il(a,r){let s=t;if(e[s(606)](Dn,Dn))return new ag(a,r);if(e[s(856)](sr,ti)&&e.bdgnO(e[s(1007)],typeof indexedDB))return new sg(a,r);if(e[s(1086)](sr,ti)&&e[s(1172)](e[s(1007)],typeof localStorage))return new og(a,r);throw new Error(e[s(1398)])}class cg{constructor(){let r=t;if(e.mDVxv(r(1452),e.EOORv))this._intervalTimeoutId=null,this[r(1801)+"l"]=36e5,this[r(843)]=Il(r(1106),e[r(1144)]);else{let s=this[r(1571)+"tManager"]?.[r(1643)+r(1787)+"nt"]();this["_dispatc"+r(992)+r(1880)](_0xe6cb42(e[r(540)],{code:_0x5420e4.code,reason:r(1911)+r(578)+r(1824)+r(1543)+r(1876)+r(895)+s})),this["_endpoin"+r(1659)]?.[r(713)+r(910)+r(1550)](),this[r(901)+r(1188)]?.["resetCou"+r(1539)]();return}}async[t(1801)+t(1608)](){let r=t;e[r(383)](clearInterval,this["_interva"+r(789)+"Id"]),this[r(1801)+"lTimeoutId"]=e[r(778)](setInterval,()=>{this.flushExpired()},this[r(1801)+"l"])}async[t(417)](){let r=t;await this[r(843)][r(417)]()[r(1893)](()=>{let s=r;this[s(1801)+s(1608)]()})}async[t(1821)+t(1854)](){let r=t;(await this[r(843)]?.[r(1044)]()||[])[r(668)](({timestamp:f})=>f<Date[r(1599)]())[r(1831)](f=>{let w=r;this._qosDB?.[w(1879)](f[w(1790)+"id"])})}async del(r){let s=t;return this[s(843)]?.[s(1879)](r)}async set(r,s){let l=t;return this[l(843)]?.[l(1597)]({message_id:r,timestamp:s})}async[t(1112)](r){let s=t;if(e[s(1423)](e[s(1096)],e.BinmA))_0xf11b8b=e.rjniv,_0x392a52=_0x389ef5[s(430)](/(^http)((?:[s]*:\/\/))/,""),_0x41c56b=/(^ws)((?:[s]*:\/\/))/[s(1119)](_0x2c7841)?_0x259467:""+_0x30280a+_0x4e9575;else return this._qosDB?.[s(1112)](r)}async[t(428)](){let r=t;e.VMRQR(clearInterval,this[r(1801)+r(789)+"Id"]),await this[r(843)]?.[r(428)]()}get isReady(){let r=t;return this[r(843)]?.[r(1100)]}}function ba(a){let r=t,s=!!this[r(591)][r(1498)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(1368)](on,a[r(1606)][r(1507)],e[r(1656)],"2"),f=l&&on(a.message[r(1507)],r(1137)+r(1753)+"ck","1"),w=l&&on(a[r(1606)][r(1507)],e[r(1189)],"1"),b=w?e[r(925)](or,a[r(1606)][r(1507)],e[r(922)])?.split(",").filter(Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:w,ackMsgIds:b}}async function Al(){let a=t;return this[a(998)+a(1533)]||(this["_QoSMana"+a(1533)]=new cg),this[a(998)+a(1533)][a(1100)]||await this[a(998)+"ger"].openDB(),this[a(998)+a(1533)]}async function dg(a,r){let s=t,{enableAutoAck:l}=this[s(591)],f=e.MoKSD(on,a[s(1606)].headers,e[s(1549)],"1"),w=e[s(1079)](on,a[s(1606)][s(1507)],s(1540),"1"),b=ba.call(this,a);if(e[s(958)](l,f)){if(s(572)===e.fIrBQ)return this[s(843)]?.[s(1112)](_0x50a23b);{let{SeqID:y,LogID:p,service:D,LogIDNew:L,method:z}=a.message;this[s(1557)]({SeqID:y,LogID:p,LogIDNew:L,service:D,method:z,headers:[{key:e[s(1888)],value:"1"},{key:e[s(1400)],value:L||""},{key:e[s(1424)],value:"0"}]})}}w&&!b[s(1497)]&&this[s(1301)+s(447)+s(411)](a),e.kUhGf(r)}async function lg(a,r){let s=t;this[s(663)](e[s(472)],a[s(1606)]),r()}async function ug(a,r){let s=t,l=e[s(1712)](nn,await e[s(1211)](Sl,a[s(971)]));try{if(e[s(1364)](l[s(399)],Uint8Array)){let f=e[s(1836)](this[s(591)][s(1601)+s(516)],Object)?{force:!!this[s(591)][s(1601)+"ncoding"][s(1385)],encoding:this[s(591)][s(1601)+s(516)][s(1623)]?this[s(591)][s(1601)+s(516)].encoding.replace(/\s/g,"")[s(1093)+"ase"]():""}:{force:!1,encoding:this[s(591)][s(1601)+s(516)]?this._options[s(1601)+s(516)][s(430)](/\s/g,"")[s(1093)+"ase"]():""},w=l[s(1601)+s(516)]?l[s(1601)+"ncoding"][s(430)](/\s/g,"")[s(1093)+s(660)]():"",b=e[s(1323)](this[s(591)]["payloadT"+s(389)],Object)?{force:!!this[s(591)][s(1868)+s(389)][s(1385)],type:this[s(591)][s(1868)+s(389)].type?this[s(591)][s(1868)+"ype"].type[s(430)](/\s/g,"")["toLowerC"+s(660)]():""}:{force:!1,type:this[s(591)][s(1868)+s(389)]?this[s(591)][s(1868)+s(389)][s(430)](/\s/g,"")["toLowerC"+s(660)]():""},y=l[s(1868)+"ype"]?l.payloadType.replace(/\s/g,"")[s(1093)+s(660)]():"",p=b[s(1385)]?b[s(1245)]:y||b[s(1245)],D=f[s(1385)]?f.encoding:w||f[s(1623)],L=[s(1739)+s(1337)+"et=utf-8",s(493)+s(967),e[s(1901)],s(1594)],z=[e[s(885)],e[s(1244)]];this[s(591)][s(1484)+s(568)+s(1433)+"ad"]&&L[s(425)](p)&&(!D||z.includes(D))?l[s(1570)+s(453)]=e[s(1354)](vl,l[s(399)],0,l[s(399)][s(1186)+"th"]):l[s(1570)+"oad"]=""}else l.textPayload=""}catch(f){e[s(1280)]===e[s(1280)]?(l[s(1570)+s(453)]="",console.log(f)):(!_0x457d03[s(731)+"d"]&&(this[s(1826)+"er"]&&_0x47ff9b["removeEv"+s(624)+s(1275)](s(444),this[s(777)+s(1629)]),this[s(1826)+"er"]&&_0x15fd1f[s(1512)+s(624)+s(1275)](e[s(754)],this[s(777)+s(616)]),this[s(1195)]()),this[s(1826)+"er"]&&_0x100869[s(1512)+s(624)+s(1275)](e.azaEn,this[s(763)+s(449)]),this[s(1826)+"er"]&&_0x1f0937[s(1512)+s(624)+"ner"](e[s(1468)],this[s(763)+s(732)]))}a[s(1606)]=l,r()}function fg(a,r,s){let l=t,f=s||8192,w=e[l(601)](f,1),b=null,y=f;return function(p){let D=l;if(e[D(651)](p,1)||e[D(1789)](p,w))return e[D(548)](a,p);e[D(1075)](y,p)>f&&(b=a(f),y=0);let L=r.call(b,y,y+=p);return e[D(876)](7,y)&&(y=e[D(1726)](e.MiKLD(7,y),1)),L}}let hg=4294967295;function xg(a,r,s){let l=t;return RangeError(e[l(701)](e[l(756)](e[l(701)](e[l(1715)](e[l(1494)]+a,e[l(670)]),r||1),e[l(808)]),s))}function pg(a,r,s){let l=t;if(e.WfCmp(s,hg))throw new Error(e[l(897)]);let f=3;for(;e[l(1369)](f,0);){let w=e[l(1403)](255,s);Sa(w,a,e.GiSLf(r,f)),s>>>=8,f--}return e[l(1529)](r,4)}function gg(a,r){let s=t,l=0,f=r,w=e.vsrrQ(r,4);for(;e.aItdl(f,w);){let{value:b,offset:y}=e[s(1572)](va,a,f);f=y,l=e[s(1914)](e[s(1204)](l,8),0),l+=b}return{value:l,offset:w}}function mg(a,r,s){let l=t,f=e[l(1556)].split("|"),w=0;for(;;){switch(f[w++]){case"0":if(r[l(953)+"e"])return e[l(1689)](r.utf8Write(a,s),s);continue;case"1":if(a.length<40)return e[l(1574)](ya,a,r,s)+s;continue;case"2":if(!a)return s;continue;case"3":if(r[l(1558)])return e.RcUqY(r[l(1558)](a,s),s);continue;case"4":return e.WLqMR(ya(a,r,s),s)}break}}function wg(a,r){let s=t,l={iAmBp:function(f,w,b){return e[K(942)](f,w,b)},lwzwq:"error",guYcn:function(f,w,b){return e.dNMic(f,w,b)},zbLjt:function(f,w){return f+w}};if(e[s(721)](e[s(1453)],s(1695)))if(_0x4cf165 instanceof _0x1ed9d3){let f=_0x41ffd8[s(1676)].slice(_0x2144a1[s(1749)+"et"],YLNQHE[s(1906)](_0x460b14[s(1186)+"th"],_0x2f01ad.byteOffset));this[s(475)]&&this[s(475)].send({data:f,fail:w=>{let b=s;this[b(396)](b(1025),YLNQHE.iAmBp(_0x3f0f5d,YLNQHE[b(1040)],{message:this["_formatErrorMess"+b(1632)](w)}))}})}else this._socket&&this[s(475)].send({data:_0x9cc065,fail:f=>{let w=s;this[w(396)](YLNQHE[w(1040)],YLNQHE[w(1427)](_0x49f815,YLNQHE.lwzwq,{message:this[w(969)+"rrorMess"+w(1632)](f)}))}});else{let f=new ue(e[s(1381)](e[s(1203)](e[s(1526)](a[e.pSjAe(r,4)]<<24,e[s(1905)](a[e[s(1249)](r,5)],16)),a[e[s(1394)](r,6)]<<8),a[e[s(1231)](r,7)]),e[s(1578)](e[s(1380)](e.TiTXl(a[e[s(905)](r,0)]<<24,e.YUdOK(a[e[s(1059)](r,1)],16)),e[s(851)](a[r+2],8)),a[r+3]),!0);return r+=8,{value:f,offset:e[s(692)](r,8)}}}function _g(a,r,s){let l=t,f=a[l(727)],w=a[l(1074)];return r[s]=e[l(1307)](w,24),r[e[l(716)](s,1)]=e[l(1699)](e[l(1603)](w,16),255),r[s+2]=e.PSpJl(w>>>8,255),r[e[l(1235)](s,3)]=e[l(1530)](255,w),r[e[l(586)](s,4)]=e[l(1914)](f,24),r[s+5]=e[l(1387)](f>>>16,255),r[e[l(1077)](s,6)]=e[l(1841)](e[l(1088)](f,8),255),r[e.OOkEE(s,7)]=e.DLPvn(255,f),s+=8,s}function va(a,r){let s=t;return a[s(1918)+"8"]?{value:a[s(1918)+"8"](r),offset:e[s(1529)](r,1)}:{value:e[s(722)](255,a[r]),offset:e[s(1722)](r,1)}}function Sa(a,r,s){let l=t;return r.writeUint8?r[l(1672)+"t8"](a,s):r[s]=e[l(509)](255,a),e[l(1664)](s,1)}let yg=function(a){return new Uint8Array(a)},Eg=e[t(1584)](e.FKtwo,typeof Buffer)?Buffer.allocUnsafe:fg(yg,Uint8Array[t(1528)+"e"][t(1299)]),bg=16,Ia=32;function vg(a){let r=t,s=0,l={};for(let f=0;e[r(1183)](f,a[r(1472)]);f++)l[a[f][r(386)+r(748)]]=e[r(1134)](bl,a[f][r(386)+"ame"]),s+=e[r(1246)](14,l[a[f]["cursor_n"+r(748)]]);return[s,l]}function kl(a,r,s){let l=t,f={gMkxW:e[l(906)],DUGLm:function(w,b,y,p){return w(b,y,p)},ilkZQ:e[l(435)],cUOSa:e[l(996)],ApGXg:e[l(1090)],abobe:function(w,b,y,p){return e[l(1341)](w,b,y,p)},SDjFx:e[l(1788)],ycPpU:e[l(392)],pJMyM:function(w,b){return e.DdFTW(w,b)},pemch:function(w,b){return e[l(711)](w,b)},tKads:function(w,b){return e[l(1917)](w,b)},mYDJF:function(w,b){return e[l(1307)](w,b)},lZhuq:function(w,b){return w|b},HdHbK:function(w,b){return w<<b}};if(e[l(1060)]!==e[l(529)]){let[w,b]=e[l(618)](vg,a),y=e[l(1155)](Eg,w),p=0;return a[l(1831)](D=>{let L=l,z=f[L(1480)][L(751)]("|"),V=0;for(;;){switch(z[V++]){case"0":p=f[L(1488)](pg,y,p,D[L(570)]||0);continue;case"1":console[L(1126)](f[L(738)],p);continue;case"2":p=f[L(1488)](_g,ue[L(739)+"er"](D.cursor||r),y,p);continue;case"3":console[L(1126)](f[L(505)],p);continue;case"4":p=Sa(0,y,p);continue;case"5":console[L(1126)](f.ApGXg,p);continue;case"6":console[L(1126)](L(1084)+L(1210),p);continue;case"7":p=f[L(724)](Sa,b[D[L(386)+"ame"]],y,p);continue;case"8":p=f[L(1488)](mg,D[L(386)+L(748)],y,p);continue;case"9":console[L(1126)](f.SDjFx,p);continue;case"10":console[L(1126)](f[L(984)],D,D[L(570)]);continue}break}}),{frameType:Ia,headers:[{key:e[l(1220)],value:s}],payload:y}}else return WVooQc[l(1111)](_0x52a4ec,_0x56ae52)?_0x1b8972:new _0x33784f((WVooQc[l(943)](WVooQc[l(1590)](_0x2f4cae[l(1770)](_0x26a185,0),_0x1746fa.call(_0x4a9d7d,1)<<8),_0x43ee68[l(1770)](_0x353b78,2)<<16)|_0x2d62a8[l(1770)](_0xa1a221,3)<<24)>>>0,WVooQc.mYDJF(WVooQc[l(1389)](_0x5c1944[l(1770)](_0x25a72b,4),WVooQc[l(1436)](_0x1b67cc.call(_0x4ff045,5),8))|WVooQc[l(1436)](_0x564dcf[l(1770)](_0x443a0e,6),16)|_0x981c7e[l(1770)](_0x953181,7)<<24,0),!0)}function Sg(a){let r=t,s=0,l=[];for(;s<a[r(1186)+"th"];){let{offset:f}=e[r(952)](va,a,s);s=f;let w={cursor_name:"",cursor:0,service:0},{value:b,offset:y}=gg(a,s);w[r(570)]=b,s=y;let{value:p,offset:D}=va(a,s);s=D,w[r(386)+r(748)]=e[r(1527)](vl,a,s,e[r(637)](s,p)),s+=p;let{value:L,offset:z}=e[r(1375)](wg,a,s);w[r(973)]=L[r(768)](),s=z,l[r(1882)](w)}return l}function Ig(){let a=t;return{frameType:Ia,headers:[{key:a(622)+a(750),value:"FILE_NOT_EXIST"}],payload:void 0}}class Ag{constructor(r,s,l){let f=t;this[f(957)+f(1142)]=r,this[f(824)+f(837)]=s,this["_message"+f(1003)]=l,this[f(843)]=e.QJdiU(Il,this[f(957)+f(1142)],e.FQqdU)}async openDB(){let r=t;e[r(561)](e[r(1247)],r(575))?await this._qosDB[r(417)]():(_0x5d9250=_0x1c1c48(_0x44dc4c),_0x12e011=127&_0x1b6a12,e.RomoG(128,_0x44ba20)&&(_0x79a71b=e[r(1760)](_0xbd18ec,_0x20f195),_0x261d41|=e.Mxloy(e[r(1197)](127,_0xd199fb),7)))}async[t(1041)+"rs"](){let r=t;if(!this[r(843)].isReady)return;let s=this[r(1259)+r(1003)],l=await this[r(843)][r(1044)]();switch(console[r(1126)]("allCurso"+r(588),l),s){case"ALL":return l&&l[r(1472)]?kl(l,0,this[r(824)+r(837)]):void 0;case e.fAGmx:return;case e[r(394)]:return l&&l[r(1472)]?e.cdrTt(kl,l,0,this[r(824)+r(837)]):Ig()}}async[t(1597)](r,s,l){let f=t;if(e[f(1757)](e[f(1744)],f(608)))this[f(1294)]&&this[f(1294)][f(1162)](_0x57bac8),this[f(1259)+f(1193)][_0x572b12]=null;else return console[f(1126)](e[f(1224)],r,s,l),this._qosDB.set({cursor_name:r,cursor:s,service:l})}async setCursors(r){let s=t,l={rTiSd:function(f,w,b){return e.cxEox(f,w,b)},GZPnt:e[s(1214)],XRWlA:e[s(1144)]};if(e.nhIuJ!==e[s(1674)]){let f=e[s(532)](Sg,r);for(let w of f)e[s(632)](s(1382),s(1382))?(this[s(1801)+"lTimeoutId"]=null,this[s(1801)+"l"]=36e5,this[s(843)]=OiTZEC[s(658)](_0x3c8464,OiTZEC[s(481)],OiTZEC[s(704)])):(console[s(1126)](e[s(820)],f),await this._qosDB[s(1597)](w))}else return 0}async[t(1112)](r){let s=t,l={bSAsD:function(f,w){return e[K(1547)](f,w)},Estvx:function(f,w){return e[K(974)](f,w)},rWsDO:e.pojgj,SkIQT:function(f,w){return e[K(1143)](f,w)},KvASF:s(873)+s(1029),sXWFi:function(f,w){return e[s(1402)](f,w)}};if(e[s(609)](e[s(770)],"dAGIb"))return(await this[s(843)][s(1112)](r))?.cursor;if(ivVYca.bSAsD(_0x12f66b,_0x22f686)){if(ivVYca.Estvx(_0x4e5916,ivVYca[s(1707)]))return _0x1f978f.get(_0x38bbc6);if(ivVYca[s(1815)](_0x382c82,ivVYca[s(725)]))return _0x5a901d["objectSt"+s(1029)]||_0x53f522[s(1112)](_0x2bcb11);if(_0x2b485e===s(1218))return _0x474d95[s(873)+"oreNames"][1]?void 0:_0x26e8e9[s(873)+s(759)](_0x4a2d95[s(873)+"oreNames"][0])}return ivVYca[s(626)](_0x1fbfc6,_0x113cf9[_0x1a78f1])}async[t(428)](){let r=t;await this._qosDB[r(428)]()}[t(1687)+"rsorFile"+t(1306)](r){let s=t;this["_cursorF"+s(837)]=r}get[t(1100)](){let r=t;return this[r(843)][r(1100)]}}let kg=e[t(602)];async function Tl(a){let r=t;if(!this[r(591)].enableQoS)return null;let{aID:s,fpID:l,messageStrategy:f}=this[r(591)],w=a||kg;try{return this[r(1563)+r(1376)]?a&&this[r(1563)+r(1376)][r(1687)+r(577)+"Name"](a):this[r(1563)+"anager"]=new Ag(l+"_"+s+"_"+w,w,f),this["_cursorM"+r(1376)][r(1100)]||await this[r(1563)+r(1376)].openDB(),this[r(1563)+r(1376)]}catch{return null}}async function Tg(a,r){let s=t,l=e[s(1527)](on,a[s(1606)][s(1507)],e.TvYhp,"-1"),f=e[s(1370)](on,a[s(1606)][s(1507)],e[s(1888)],"1"),w=e.iKTwk(or,a[s(1606)][s(1507)],e[s(819)]),b=Number(e[s(1272)](or,a[s(1606)][s(1507)],"x_fronti"+s(468)))||0,y=ba.call(this,a),p=e[s(1368)](on,a.message[s(1507)],s(1910)+"s","2"),D=e[s(547)](or,a[s(1606)][s(1507)],s(1650)+s(1149)+"e"),L=e.CUGGc(Number,e[s(454)](or,a[s(1606)][s(1507)],e[s(1024)]));if(y[s(1497)])return e[s(490)](r);let z=y[s(1729)+"sage"]?await Al[s(1770)](this):null;if(e.WfCmp(a.message[s(570)],0)&&f&&!l||a[s(1606)].service>0){if(w&&y[s(1729)+"sage"]&&z){if(e[s(821)](e[s(483)],s(646)))return!!!await z[s(1112)](w)&&(this["_dispatc"+s(1858)+s(1792)](a),await z.set(w,Date[s(1599)]()+b)),e[s(1435)](r);this.emit(e[s(1253)],e[s(1716)](_0xb7003a,"error",{..._0x503d53,message:_0x159b8a[s(1442)]||""}))}if(p){let V=await Tl[s(1770)](this);if(!V)return this[s(1301)+s(1858)+s(1792)](a),e[s(552)](r);let te=await V[s(1112)](D)??-1;if(te<L)this[s(1301)+s(1858)+"Event"](a),V[s(1597)](D,L,a.message[s(570)]);else throw new Error(s(980)+s(1780)+s(562)+L+(" larger "+s(965)+s(1068)+"r ")+te);return r()}return this["_dispatc"+s(1858)+s(1792)](a),r()}}async function Rg(a,r){let s=t,l=ba[s(1770)](this,a);if(!l[s(1729)+s(1274)])return e.pdjSF(r);let f=await Al[s(1770)](this);if(l[s(1063)+"anupMess"+s(1632)]&&l[s(1279)+"s"].length)for(let w of l.ackMsgIds)await f[s(1879)](w);r()}async function Cg(a,r){let s=t;if(e[s(1607)](e.rGtbn,e.Suqnz)){let l=a[s(1606)].frameType===bg,f=e[s(1562)](a[s(1606)][s(1032)+"e"],Ia);if(e[s(1332)](!l,!f))return e[s(490)](r);let w=or(a.message[s(1507)],"cursor_f"+s(750));if(!w)return r();let b=await Tl.call(this,w);if(!b)return e[s(1501)](r);if(l){let y=await b[s(1041)+"rs"](),p={frameType:y?.[s(1032)+"e"],SeqID:ue[s(739)+"er"](this[s(1408)]++),LogID:ue[s(739)+"er"](this[s(591)].logIDGenerator()),service:9e3,method:5,headers:y?.[s(1507)],payload:y?.[s(399)]},D=e[s(1037)](S,p);this[s(1294)]&&this._ws[s(1173)+"te"]&&this[s(1294)][s(1162)](D)}if(f){if(e[s(567)](e[s(1108)],e[s(1108)]))return _0x52dd29[s(1126)](_0x442248),!1;{let y=a[s(1606)].payload;y&&b[s(595)+"rs"](y)}}}else this[s(614)]=!0,this[s(1703)]()}let Pg=async function(a,r){let s=t;this._isInit=!1,e.eAZuy(clearTimeout,this[s(1703)+s(512)+s(1877)]),e[s(797)](r)},Dg=async function(a,r){let s=t,l={Wzgek:function(f,w,b,y){return e.IlHpy(f,w,b,y)}};if(e.UaVkD(e[s(416)],e.scqaW))_0x4dd4e6(_0x3e26f7,8),e[s(1572)](_0x13dd84,_0x525ef7,_0x2df8ac);else{if(!this[s(1294)]||this[s(1294)][s(1173)+"te"]!==this.OPEN)return e[s(388)](r);let{pingInterval:f}=this[s(591)];this[s(1571)+s(1659)]?.["resetEndpointCon"+s(1550)]();for(let b=0;e.yXHgi(b,this[s(1259)+s(1193)][s(1472)]);b++)if(e[s(1165)](e.sbmEA,e[s(920)]))l[s(1536)](_0x203cd7,this,_0x306464,[_0x4fa146,_0x42533a,_0x3c11f9,_0x1c5bb6,_0x5d131b,_0x321884]);else{let y=this["_message"+s(1193)][b];if(e[s(1805)](this[s(1294)][s(1173)+"te"],this[s(434)])&&e.LwIUK(null,y))this[s(1294)]&&this[s(1294)][s(1162)](y),this[s(1259)+s(1193)][b]=null;else break}this._messageQueue=this[s(1259)+s(1193)][s(668)](b=>!!b),this["_pingPon"+s(1598)+"Id"]=e[s(1823)](setTimeout,()=>this._ping(),f),this[s(1301)+s(1658)+"nt"](a),this[s(1826)+"er"]&&this._ws&&(this[s(1294)].binaryType=this[s(1190)+"ype"]);let w=this[s(1571)+s(1659)]?.[s(1643)+s(1787)+"nt"]();this[s(663)]("open "+w+s(1379)),e[s(1714)](r)}},Og=async function(a,r){let s=t,l=this[s(1571)+s(1659)]?.[s(1643)+s(1787)+"nt"]();this[s(663)](s(966)+l),e[s(882)](r)};class Lg extends _a{constructor(r){let s=t,l={qRQwO:function(y,p,D,L){return y(p,D,L)},dMJRI:function(y,p,D){return e[K(753)](y,p,D)},fKTzE:e.CmMIf,PpDUQ:function(y,p){return e[K(1682)](y,p)},MGdGd:e[s(683)],maQpK:function(y,p){return y===p},zElHM:e.tiweK,aKXCA:s(1773),LhQKc:function(y,p){return e.CYYNd(y,p)},ahmHv:e[s(1491)],aqASP:function(y,p,D,L){return e.cdrTt(y,p,D,L)},BKOvS:function(y,p){return e[s(1870)](y,p)},hDIat:e[s(1832)],cQSfQ:e[s(400)],mFwOR:e.dixen,tatnT:e[s(1742)]};super(),this["_miniNavigatorOn"+s(809)]=!0,this._isBrowser=sr,this[s(1505)]=Zp,this[s(924)+"T"]=Dn,this[s(406)+"X"]=ei,this[s(815)+"r"]=ti,this["_message"+s(1193)]=[],this[s(1571)+s(1659)]=null,this[s(1525)+"osed"]=!1,this[s(1190)+s(389)]=e[s(1406)],this[s(1703)+"Lock"]=!1,this[s(1703)+s(512)+s(1877)]=null,this[s(1358)+s(1170)+s(902)]=null,this[s(440)+s(1598)+"Id"]=null,this[s(1408)]=0,this[s(614)]=!1,this[s(1625)]="",this[s(998)+"ger"]=null,this["_cursorM"+s(1376)]=null,this[s(901)+s(1188)]=null,this[s(1461)+"ls"]=e[s(1728)],this.CLOSED=3,this[s(1583)+"NG"]=0,this[s(434)]=1,this[s(1748)]=2,this[s(664)]=y=>{let p=s;try{l[p(1545)](El,this,y,[Pg,Dg,Og])}catch(D){let L=l[p(1163)](at,l[p(597)],{message:D[p(1606)],code:sn.OPEN_ERROR,error:D});this[p(1301)+p(492)+p(1880)](L)}},this[s(705)+"ge"]=async y=>{let p=s;if(l[p(1146)](p(1883),l.MGdGd)){let{pingInterval:D,pingFrequency:L}=this[p(591)];if((l[p(1774)]("hi",y[p(971)])&&l[p(1774)](l[p(1110)],L)||l.aKXCA===L)&&(l[p(1146)](p(779),p(1486))?(this[p(1114)+p(604)](),this[p(396)](p(610)+p(1577)+"s",p(436)),this[p(440)+"gTimeoutId"]=l.dMJRI(setTimeout,this._ping.bind(this),D)):(_0x4fec40=_0x5b8ba0[p(1336)](_0x59f94f),_0x291125=_0x17617a.concat(_0x5390b9[_0x11606c]))),l[p(1774)]("hi",y[p(971)]))return;try{l.LhQKc(l[p(709)],l[p(709)])?(this[p(1732)]=_0x432e3d,this[p(1061)]=_0x3daf11,this[p(843)]=_0x40843b):l[p(397)](El,this,y,[ug,dg,Rg,Cg,Tg,lg])}catch(z){let V=at(l[p(597)],{message:z[p(1606)],code:sn[p(599)+p(1496)],error:z});this[p(1301)+p(492)+p(1880)](V)}}else this[p(1654)+p(1346)]=0,this[p(1252)+p(720)+p(1401)+"t"]=0},this[s(1002)]=y=>{let p=s,D=this[p(1571)+p(1659)]?.[p(1845)+p(999)+"es"](),L=this[p(1571)+p(1659)]?.[p(1643)+p(1787)+"nt"]();if(D&&!y[p(1606)]){let z=p(629)+L+(p(755)+p(1673)+"es reached");this["_dispatc"+p(492)+p(1880)](at(l.fKTzE,{message:z,code:sn["MAX_RETR"+p(1072)+"R"],error:y}));return}this._ws&&l[p(1471)](this[p(1294)][p(1173)+"te"],this[p(434)])&&this._disconnect(),this[p(1301)+p(492)+p(1880)](l[p(1163)](at,l[p(597)],{message:y.message,code:sn[p(1205)+p(1232)],error:y}))},this[s(1046)]=async y=>{let p=s;if(e[p(1474)](e.buQgh,e[p(1097)])){this[p(832)+p(652)](),this._clearPingTimer(),this["_removeW"+p(1818)+"rs"](),this[p(1294)]=null,this[p(1703)+"Lock"]=!1;let D=this._endpointManager?.["checkRea"+p(999)+"es"]();if(!D&&this[p(1630)+p(1081)]()&&!this[p(1525)+p(1248)]){let L=this[p(1571)+p(1659)]?.[p(1643)+"ntEndpoint"](),z=this[p(591)][p(478)+p(834)+p(1641)](y[p(878)],y[p(747)]);this[p(1301)+p(992)+p(1880)](e[p(942)](pt,e[p(540)],{code:1006,reason:y[p(747)]||"connecti"+p(578)+p(1824)+p(1543)+p(1876)+p(895)+L,willReconnect:z})),z&&this[p(1703)]();return}if(e[p(609)](1e3,y[p(878)])&&this[p(1525)+p(1248)]){this[p(1301)+p(992)+p(1880)](e.iKTwk(pt,e[p(540)],{code:1e3,reason:e[p(912)]})),this[p(1571)+p(1659)]?.[p(713)+"pointCon"+p(1550)](),this[p(901)+p(1188)]?.[p(835)+p(1539)]();return}if(e[p(1168)](1e3,y.code)&&D){let L=this["_endpoin"+p(1659)]?.[p(1643)+p(1787)+"nt"](),z=y[p(747)];z||(z=await e[p(1690)](rg,this[p(1625)])),z=p(1911)+p(578)+p(1736)+z+(", hostna"+p(1361))+L+(p(773)+"tries re"+p(596)),this[p(1301)+p(992)+p(1880)](e[p(778)](pt,e.dixen,{code:y[p(878)],reason:z}));let V=p(629)+L+" fail, max retries reached";this._dispatchErrorEvent(e[p(531)](at,p(1025),{message:V,code:sn[p(563)+p(1072)+"R"]})),this[p(1571)+p(1659)]?.[p(713)+p(910)+p(1550)](),this[p(901)+p(1188)]?.[p(835)+"nter"]();return}if(y[p(878)]!==1e3&&!y[p(747)]){let L=this[p(1571)+p(1659)]?.[p(1643)+p(1787)+"nt"]();this[p(1301)+p(992)+"ent"](pt(e[p(540)],{code:y[p(878)],reason:p(1911)+"ng failed, unkno"+p(1543)+"n, hostn"+p(895)+L})),this[p(1571)+p(1659)]?.[p(713)+p(910)+p(1550)](),this[p(901)+"sCounter"]?.[p(835)+p(1539)]();return}this[p(1301)+p(992)+p(1880)](y),this["_endpoin"+p(1659)]?.[p(713)+p(910)+"fig"](),this[p(901)+p(1188)]?.["resetCou"+p(1539)]()}else{let D=l[p(868)][p(751)]("|"),L=0;for(;;){switch(D[L++]){case"0":if(!this[p(1294)])return;continue;case"1":this._ws[p(1564)+p(1626)](l[p(471)],this[p(664)]);continue;case"2":this[p(1294)][p(1564)+p(1626)](l[p(597)],this[p(1002)]);continue;case"3":this[p(1294)][p(1564)+p(1626)](l.mFwOR,this[p(1046)]);continue;case"4":this[p(1294)]["addEvent"+p(1626)](l[p(1502)],this[p(705)+"ge"]);continue}break}}},this[s(630)]=null,this.onerror=null,this[s(1869)+"e"]=null,this[s(938)]=null,this[s(932)+s(1618)]=null,this[s(1537)+s(1161)]=null,this[s(1730)+s(1087)+s(1226)+"ct"]=null,this[s(763)+s(449)]=this[s(763)+s(449)][s(583)](this),this[s(763)+s(732)]=this[s(763)+s(732)][s(583)](this),this[s(777)+s(1629)]=this[s(777)+s(1629)][s(583)](this),this[s(777)+s(616)]=this[s(777)+s(616)][s(583)](this),this[s(591)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1635)](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(499)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:s(1835),env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:w}=r,b=Array[s(1300)](f)?f:e[s(811)](e[s(1347)],typeof f)?[f]:[];if(!b||e[s(974)](0,b[s(1472)]))throw new Error(e[s(1305)]);if(!e[s(1113)](Qp,w))throw new Error(e[s(558)]);Object[s(886)](this._options,r),this["_endpoin"+s(1659)]=new yl(b,this[s(591)][s(1873)+"es"]),this[s(901)+s(1188)]=new ng(this._options["pingLoss"+s(977)]),this[s(591)][s(1317)+s(933)]&&(this[s(614)]=!0,this[s(1703)]()),this[s(591)][s(1129)+s(489)+s(1902)]&&(this[s(924)+"T"]||this[s(406)+"X"]?this[s(1454)+s(1342)+s(1045)]():this[s(1826)+"er"]&&this[s(798)+s(1895)+s(1626)]())}[t(763)+t(449)](){let r=t;this[r(591)][r(1123)+r(884)+r(874)]||this[r(1525)+r(1248)]||this["_handleR"+r(1618)]()}[t(763)+t(732)](){let r=t;this[r(1887)+"WebSocket"]();let s=e[r(531)](wa,e[r(401)],{message:e.lSBMH});this[r(1730)+r(1087)+"yReconnect"]&&this["onStopImmediatel"+r(1226)+"ct"](s)}[t(798)+"balEvent"+t(1626)](){let r=t;this[r(1826)+"er"]&&window[r(1564)+r(1626)](e[r(1344)],this[r(763)+"nLine"]),this[r(1826)+"er"]&&window["addEvent"+r(1626)](e[r(1468)],this[r(763)+r(732)]),this[r(1826)+"er"]&&window[r(1564)+r(1626)](e[r(659)],this["_handleP"+r(1629)]),this[r(1826)+"er"]&&window["addEvent"+r(1626)](r(1890),this[r(777)+"ageShow"])}[t(462)+t(1895)+"Listener"](){let r=t;this[r(1826)+"er"]&&window[r(1512)+"entListe"+r(1275)](r(681),this["_handleO"+r(449)]),this[r(1826)+"er"]&&window["removeEventListe"+r(1275)](e.pLLWn,this["_handleO"+r(732)]),this._isBrowser&&window[r(1512)+"entListener"](e[r(659)],this[r(777)+r(1629)]),this[r(1826)+"er"]&&window[r(1512)+r(624)+"ner"](e.HQUOd,this[r(777)+r(616)])}[t(777)+t(1629)](r){let s=t;!r[s(731)+"d"]&&(this[s(1826)+"er"]&&window[s(1512)+s(624)+s(1275)](e[s(659)],this[s(777)+"ageHide"]),this[s(1826)+"er"]&&window[s(1512)+s(624)+"ner"](s(1890),this[s(777)+"ageShow"]),this[s(1195)]()),this[s(1826)+"er"]&&window[s(1512)+"entListener"](e[s(1344)],this["_handleO"+s(449)]),this[s(1826)+"er"]&&window[s(1512)+s(624)+s(1275)](e[s(1468)],this._handleOffLine)}[t(777)+t(616)](r){let s=t;r[s(731)+"d"]&&(this[s(1630)+s(1081)]()&&(!this[s(1294)]||e.jpQKr(this[s(1294)][s(1173)+"te"],this.OPEN)||e[s(1160)](this[s(1294)][s(1173)+"te"],this.CONNECTING))&&this["_handleO"+s(449)](),this[s(1826)+"er"]&&window[s(1564)+"Listener"](e.azaEn,this[s(763)+s(449)]),this._isBrowser&&window[s(1564)+s(1626)](e[s(1468)],this[s(763)+s(732)]))}async["_generat"+t(524)](r){let s=t,{fpID:l,deviceID:f,bddID:w,ttwID:b,accessKey:y,aID:p,customParams:D={},enableAutoAck:L,enableQoS:z,QoSLevel:V,env:te}=this[s(591)],Z,nt,St;this[s(1826)+"er"]||this[s(406)+"X"]||this[s(924)+"T"]?(Z=location&&s(1182)==location[s(921)]?e[s(1614)]:s(684),nt=r[s(430)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),St=/^wss(.*:\/\/)/.test(r)?r:""+Z+nt):(Z=s(1184),nt=r[s(430)](/(^http)((?:[s]*:\/\/))/,""),St=/(^ws)((?:[s]*:\/\/))/.test(nt)?nt:""+Z+nt);let Rl=w?e[s(1174)]:b?e[s(1343)]:e[s(1027)],Cl=w||b||f;if(e[s(1807)](!Cl,!Rl))throw new Error(e[s(1919)]);let Ng=e[s(457)](e[s(813)],typeof D)?await e.urYbi(D):D,Mg=te?e.JbmpY(tg,te[s(818)],te.xTTEnv):{},Aa=Object[s(886)]({device_platform:e[s(576)],version_code:s(1829)+"0",access_key:y,fpid:l,aid:p,[Rl]:Cl,xsack:L?1:0,xaack:L?1:0,xsqos:z?1:0,qos_level:z?V:void 0,qos_sdk_version:2,...Mg},Ng),Bg=Object.keys(Aa).reduce((ka,Ta)=>Aa[Ta]!==void 0?""+ka+(ka?"&":"?")+Ta+"="+Aa[Ta]:ka,"");return St+"/ws/v2"+Bg}async _connect(){let r=t;if(!(this[r(1703)+r(743)]||this[r(1525)+r(1248)])){this["_connect"+r(743)]=!0;try{if(e[r(1469)]===e[r(1515)])_0x59ae9b.textPayload="",_0x4d09fd[r(1126)](_0x16ebbd);else{let s=this[r(1571)+r(1659)]?.["checkCur"+r(1764)+r(883)+r(1377)+r(685)](),{timeoutInterval:l}=this[r(591)];if(s){let w=this[r(1571)+r(1659)]?.[r(1643)+r(1787)+"nt"](),b=this[r(1571)+r(1659)]?.[r(1338)+r(1083)+"pointAnd"+r(799)+r(1371)](),y=this[r(1571)+r(1659)]?.["getCurre"+r(1787)+"ntTriesC"+r(1366)]();if(b)if(e[r(479)](e[r(939)],e[r(644)]))_0x57506c[r(1126)](_0x2687c9);else{let p=r(629)+w+(r(764)+r(773)+r(554)+r(680)+r(740)+r(1688)+r(1415))+b+(r(1049)+"y"),D=e[r(942)](at,e[r(1253)],{message:p,code:sn[r(563)+"IES_ERROR"]});this._debug(p),this["_dispatc"+r(492)+r(1880)](D),this._url=await this["_generat"+r(524)](b),this._debug("connect "+b+" "+y+r(1440)),this[r(1463)+r(1818)+"rs"]()}else if(e[r(1639)]!==e[r(1367)]){let p=r(629)+w+(r(764)+r(773)+r(554)+r(596));this[r(663)](p),this["_dispatchErrorEv"+r(1880)](at(r(1025),{message:p,code:sn["MAX_RETR"+r(1072)+"R"]}));return}else{if(e.sgPcn(_0x2db613,_0x354794))throw new _0x4a749a(e.SlBDE);let p=3;for(;p>=0;){let D=255&_0x52c9c8;e[r(1354)](_0x575253,D,_0x5e761b,e[r(1059)](_0x5b6315,p)),_0x2ac947>>>=8,p--}return e[r(1817)](_0x2546cc,4)}}else if(r(438)!==e.CXhmI)this[r(901)+r(1188)]?.[r(1595)](),this[r(396)](e[r(1282)],e[r(639)]),this["_pingLos"+r(1188)]?.["checkRea"+r(790)+"nt"]()?this["_handleR"+r(1618)]():this[r(384)]();else{let w=this[r(1571)+r(1659)]?.["getCurrentEndpoi"+r(1686)+r(682)](),b=this[r(1571)+r(1659)]?.[r(1643)+r(1787)+"ntTriesC"+r(1366)]();this[r(1625)]=await this["_generat"+r(524)](e[r(1104)](w,"")),this[r(663)](r(629)+w+" "+b+r(1440)),this[r(1463)+r(1818)+"rs"]()}if(this[r(614)])this._isInit=!1;else{let w=e.JWxUB(wa,e[r(401)],{message:r(812)});this[r(932)+"econnect"]&&this["onStartR"+r(1618)](w)}let f=this[r(1571)+"tManager"]?.[r(1643)+"ntEndpoi"+r(1711)+r(1366)]()||0;e[r(1333)](f,1)&&await this[r(574)](e.LBgcO(f,1)),this[r(663)](r(1911)+r(697)+this[r(1625)]+(" protoco"+r(1538))+this[r(1461)+"ls"]),this[r(1294)]=e[r(1131)](Xp,{url:this[r(1625)],protocols:[this._protocols],headers:this[r(591)][r(1492)+r(1085)+"s"][r(1459)+r(913)]},this[r(591)].ws),(this[r(1826)+"er"]||this._isWorker)&&this[r(1294)]&&(this[r(1294)][r(1153)+"pe"]=this["_binaryT"+r(389)]),this[r(1872)+r(476)](),this[r(1703)+r(512)+r(1877)]=e[r(589)](setTimeout,this._onTimeout[r(583)](this),l)}}catch(s){throw this[r(1703)+"Lock"]=!1,s}}}[t(832)+t(652)](){let r=t;clearTimeout(this[r(1703)+r(512)+r(1877)]),this[r(1703)+r(512)+r(1877)]=null}[t(1114)+t(604)](){let r=t;e.rQdsh(clearTimeout,this["_pingPon"+r(1598)+"Id"]),e[r(846)](clearTimeout,this["_reconne"+r(1170)+"tId"]),this[r(440)+r(1598)+"Id"]=null,this[r(1358)+r(1170)+"tId"]=null}[t(663)](...r){let s=t;this[s(591)][s(1766)]&&console[s(1126)][s(994)](console,[s(857)+">",...r])}[t(940)+t(513)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:w}=this._options,b=e[s(1147)](l,Math[s(1159)](w,e[s(1175)](r,1)));return e[s(1295)](b,f)?f:b}[t(384)](){let r=t;if(this._ws&&e.DdFTW(this._ws[r(1173)+"te"],this.CONNECTING)){this[r(1114)+r(604)](),this["_pingPon"+r(1598)+"Id"]=setTimeout(this._ping.bind(this),this[r(591)].pingInterval);return}if(!this._ws||e[r(1746)](this._ws[r(1173)+"te"],this[r(434)]))return void this[r(503)+"econnect"]();this._ws&&this._ws[r(1162)]("hi"),this["_reconne"+r(1170)+r(902)]=e[r(1352)](setTimeout,this["_handleR"+r(1618)+"Timeout"][r(583)](this),this[r(591)]["pingTimeoutInter"+r(1853)])}["_handleR"+t(1618)+"Timeout"](){let r=t;this[r(901)+"sCounter"]?.[r(1595)](),this.emit(e[r(1282)],e[r(639)]),this[r(901)+r(1188)]?.[r(1845)+r(790)+"nt"]()?this[r(503)+r(1618)]():this[r(384)]()}[t(1630)+t(1081)](){let r=t;return this[r(924)+"T"]||this[r(406)+"X"]?this["_miniNav"+r(1843)+r(809)]:(this[r(1826)+"er"]||this._isWorker)&&this[r(591)]["listenNe"+r(489)+r(1902)]?navigator[r(730)]:!0}[t(503)+t(1618)](){let r=t;!this[r(1630)+"orOnline"]()||this["_readyCl"+r(1248)]||(this[r(1571)+"tManager"]?.[r(713)+r(910)+"fig"](),this[r(901)+r(1188)]?.[r(835)+r(1539)](),this._ws?this[r(382)+r(816)](1001,r(1680)+r(1828)+r(478)+r(1230)+r(989),!0):this[r(1703)]())}[t(1454)+t(1342)+"ange"](){let r=t;this[r(924)+"T"]?tt[r(1830)+r(1785)+r(892)](({isConnected:s})=>{let l=r;this[l(985)+l(1843)+l(809)]=s,s?this["_handleO"+l(449)]():this[l(763)+"ffLine"]()}):this[r(406)+"X"]&&wx[r(1830)+r(1785)+r(892)](({isConnected:s})=>{let l=r;this[l(985)+l(1843)+l(809)]=s,s?this[l(763)+l(449)]():this[l(763)+l(732)]()})}[t(574)](r){return new Promise(s=>{let l=K;e[l(452)](setTimeout,s,this[l(940)+"rvalValue"](r))})}[t(382)+t(816)](r=1e3,s="",l=!1){let f=t;this._ws&&this[f(1887)+f(734)+"t"](r,s,l)}[t(733)+"ut"](){let r=t,s=this[r(1571)+"tManager"]?.[r(1643)+r(1787)+"nt"]();this._debug(r(629)+s+r(764)),this[r(382)+r(816)](1001,e[r(581)],!0)}[t(1557)](r){let s=t;if(e[s(1057)](e[s(418)],"hndHR")){let l=e[s(1140)](Gt,r);this[s(1294)]&&e.SjzYz(this[s(1294)][s(1173)+"te"],this[s(434)])&&(this[s(1294)]&&this[s(1294)].send(l),this._debug(s(1073),r))}else e.jyXLl(_0x46dc7c,_0x1d87eb,24),e[s(1799)](_0x2df74b,_0x38d48a,_0x5c5784(_0x2c04f0))}[t(1463)+t(1818)+"rs"](){let r=t,s=e[r(1861)][r(751)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1294)][r(1512)+r(624)+r(1275)](e[r(1742)],this[r(705)+"ge"]);continue;case"1":this[r(1294)][r(1512)+r(624)+r(1275)](e[r(400)],this[r(664)]);continue;case"2":this._ws[r(1512)+r(624)+r(1275)](r(1025),this._onError);continue;case"3":if(!this[r(1294)])return;continue;case"4":this._ws["removeEventListe"+r(1275)](e.dixen,this[r(1046)]);continue}break}}[t(1872)+t(476)](){let r=t,s=(r(802)+"1")[r(751)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1294)][r(1564)+r(1626)](e[r(1742)],this[r(705)+"ge"]);continue;case"1":this._ws[r(1564)+"Listener"]("error",this._onError);continue;case"2":if(!this._ws)return;continue;case"3":this[r(1294)][r(1564)+"Listener"](e.dixen,this[r(1046)]);continue;case"4":this[r(1294)]["addEvent"+r(1626)](r(1018),this[r(664)]);continue}break}}[t(1657)+t(1741)](r=1e3,s=""){let l=t;try{if(e[l(852)]===e[l(852)])this[l(1294)]&&this._ws[l(1195)](r,s);else return this[l(843)]?.[l(1100)]}catch{}}[t(1887)+t(734)+"t"](r=1e3,s="",l=!1){let f=t,w={FqMjg:e[f(1846)]};if(this[f(1114)+f(604)](),this[f(832)+f(652)](),this[f(1463)+f(1818)+"rs"](),this[f(1657)+f(1741)](1e3,s),this[f(1703)+f(743)]=!1,l&&this[f(1630)+"orOnline"]()&&!this[f(1525)+f(1248)]){if(e[f(1702)](e[f(987)],e.Qcnql))return this[f(924)+"T"]||this[f(406)+"X"]?this[f(985)+f(1843)+f(809)]:(this._isBrowser||this[f(815)+"r"])&&this._options[f(1129)+f(489)+f(1902)]?_0x1e88ff.onLine:!0;if(this[f(1571)+f(1659)]?.checkReachMaxTries()){let y=this[f(1571)+f(1659)]?.["getCurre"+f(1787)+"nt"]();this["_dispatchCloseEv"+f(1880)](e[f(955)](pt,e[f(540)],{code:1006,reason:f(629)+y+(f(764)+f(773)+f(554)+f(596)),wasClean:!0}))}else if(e[f(515)](e[f(551)],e[f(1004)]))this[f(957)+f(1142)]=_0x265579,this[f(824)+f(837)]=_0x4beff7,this[f(1259)+f(1003)]=_0x4af751,this[f(843)]=_0x372fa9(this["_cursorN"+f(1142)],QbOSys[f(1705)]);else{let y=this[f(591)][f(478)+f(834)+f(1641)](r,s);this[f(1301)+f(992)+f(1880)](e[f(839)](pt,e[f(540)],{code:r,reason:s,wasClean:!0,willReconnect:y})),y&&this[f(1703)]()}return}this[f(1630)+f(1081)]()||this[f(1525)+"osed"]?this[f(1301)+f(992)+f(1880)](e[f(1867)](pt,e[f(540)],{code:r,reason:e[f(912)]})):this[f(1301)+f(992)+"ent"](pt(f(1195),{code:1006,reason:e[f(1069)]})),this[f(1294)]=null,this[f(1571)+f(1659)]?.[f(713)+f(910)+f(1550)](),this["_pingLos"+f(1188)]?.[f(835)+f(1539)]()}[t(1301)+"hOpenEvent"](r){let s=t;this[s(396)](s(1018),r),this[s(938)]&&this[s(938)](r)}["_dispatc"+t(1858)+"Event"](r){let s=t;this[s(396)](e.DckMy,r),this[s(1869)+"e"]&&this[s(1869)+"e"](r)}[t(1301)+t(447)+t(411)](r){let s=t;this[s(396)](e[s(1779)],r),this[s(1537)+s(1161)]&&this[s(1537)+s(1161)](r)}[t(1301)+"hErrorEv"+t(1880)](r){let s=t;this.emit(s(1025),r),this[s(1229)]&&this[s(1229)](r)}[t(1301)+t(992)+t(1880)](r){let s=t;this[s(396)](e[s(540)],r),this.onclose&&this[s(630)](r)}get[t(1153)+"pe"](){let r=t;if(e.wCBIR(e[r(488)],r(656))){let s=_0x30f71a[_0xe8ed6f];if(e[r(1030)](4,_0x88dd75[_0x4114ee][r(1472)])){let l=_0x11b079[r(867)+"g"](0,e[r(584)](4,_0x152691[_0x21a095].length)),f=l[r(1336)](s);_0x37a52d=_0x5f5c7d.concat(f)}else _0xc65d8c=_0x19ee6c[r(1336)](s)}else return this[r(1294)]?this[r(1294)].binaryType:this[r(1190)+r(389)]}set binaryType(r){let s=t;this[s(1190)+"ype"]=r,this[s(1294)]&&(this[s(1294)][s(1153)+"pe"]=r)}get[t(1314)+"nt"](){let r=t;return this[r(1571)+r(1659)]?.["getCurre"+r(1787)+r(1711)+r(1366)]()||0}get[t(1713)+t(431)](){let r=t;return this[r(1259)+r(1193)][r(1509)]((l,f)=>{let w=r,b={VwvqZ:function(y,p){return y+p},dwZzd:function(y,p){return y*p},KUEpo:function(y,p){return e[K(466)](y,p)}};return e[w(623)]!=="yIAOG"?(l+=f&&f[w(1186)+"th"]||0,l):jtDVsA.VwvqZ(jtDVsA.dwZzd(1e4,_0x113ea1[w(1599)]()),_0x2b1fb3[w(1899)](jtDVsA.KUEpo(1e4,_0x5568ea.random())))},0)+(this[r(1294)]?this._ws[r(1713)+r(431)]:0)}get[t(1116)+"ns"](){let r=t;return this._ws?this[r(1294)][r(1116)+"ns"]:""}get protocol(){let r=t;return this[r(1294)]?this._ws[r(921)]:""}get readyState(){let r=t;return this._ws?this[r(1294)].readyState:this[r(591)].automaticOpen?this[r(1583)+"NG"]:this[r(1796)]}get url(){let r=t;if(e[r(1121)](e[r(805)],e[r(615)])){let s={YRrgV:function(l,f,w,b,y){let p=r;return PhWpWS[p(1784)](l,f,w,b,y)}};_0x1f116c[r(1564)+r(1626)](PhWpWS[r(1450)],l=>{let f=r;s[f(1215)](_0x37f072,_0x4cd39f(_0xf0ac63.result),l[f(407)+"on"],l[f(687)+"on"],_0xc3980f(_0x131e29[f(1582)+f(587)]))})}else return this[r(1294)]?this[r(1294)][r(1860)]:this[r(1625)]}[t(1195)](r=1e3,s){let l=t,f=("2|5|0|7|"+l(1016))[l(751)]("|"),w=0;for(;;){switch(f[w++]){case"0":this[l(1114)+l(604)]();continue;case"1":this[l(998)+l(1533)]?.[l(428)]();continue;case"2":this[l(1525)+l(1248)]=!0;continue;case"3":if(!this._ws)return void this[l(663)](e[l(1644)]);continue;case"4":if(this[l(1294)][l(1173)+"te"]===this.CLOSED||e[l(1482)](this[l(1294)][l(1173)+"te"],this[l(1748)]))return void this._debug(l(795)+"s alread"+l(517));continue;case"5":this[l(832)+"mer"]();continue;case"6":this["_destroy"+l(734)+"t"](r,s);continue;case"7":this[l(462)+l(1895)+"Listener"]();continue}break}}async[t(1162)](r,s){let l=t;if(e.Guakx(null,r))throw new Error(e.vPuxd);e.aXVJL==typeof r&&(r=JSON[l(1894)+"y"](r)),e[l(1506)](e[l(1347)],typeof r)&&!(r instanceof ArrayBuffer)&&!(r[l(1676)]&&e.JTNKL(r[l(1676)],ArrayBuffer))&&(r=JSON.stringify(r));let f=await e[l(521)](Sl,r),w=e.EnZul(eg,r),{method:b=0,service:y=this[l(591)][l(570)],logID:p=this[l(591)][l(1743)+"erator"](),headers:D=this[l(591)][l(1507)],payloadEncoding:L=this[l(591)].payloadEncoding,payloadType:z=this[l(591)][l(1868)+l(389)],logIDNew:V=this[l(591)][l(612)+l(1051)][l(758)+l(794)+"teLogIDNew"]?e[l(1669)](i,this[l(591)]["logIDNew"+l(1051)][l(1908)]):""}=e[l(675)](s,{});if(!y)throw new Error(e[l(1916)]);let te={SeqID:ue[l(739)+"er"](this[l(1408)]++),LogID:ue[l(739)+"er"](p),service:y,method:b,headers:D,payloadEncoding:e[l(1547)](L,Object)?L[l(1623)]?L[l(1623)]:"":L,payloadType:e.bkrqH(z,Object)?z.type?z.type:w:z||w,payload:f,LogIDNew:V},Z=Gt(te);return this[l(1294)]&&e.KCoxZ(this[l(1294)][l(1173)+"te"],this.OPEN)?(this[l(1294)]&&this[l(1294)][l(1162)](Z),this[l(663)](e[l(1568)],te)):this["_message"+l(1193)].length<this[l(591)][l(380)+l(1414)+l(801)]?(this[l(1259)+l(1193)][l(1882)](Z),this._debug("enqueue",te)):(this[l(1259)+l(1193)].shift(),this["_message"+l(1193)].push(Z)),{seqID:this[l(1408)],logID:p,logIDNew:V}}async reconnect(r){let s=t,l={JVySs:function(f,w){return e[K(641)](f,w)}};if(e[s(1462)](e[s(896)],e[s(896)]))return _0x4f17b8&&(_0x469568=(0,_0x127a3d[hcIcWj[s(1292)](_0x2d8ac9,_0x3e2d35)[0]])(_0x16b792=0)),_0x2977f1;{let{url:f}=e[s(1852)](r,{}),w=Array[s(1300)](f)?f:e[s(1327)](e.zGmON,typeof f)?[f]:[];r&&Object[s(886)](this[s(591)],r),w&&w.length?this[s(1571)+s(1659)]=new yl(w,this[s(591)][s(1873)+"es"]):this[s(1571)+s(1659)]?.[s(713)+s(910)+"fig"](),this[s(901)+s(1188)]?.[s(835)+s(1539)](this[s(591)]["pingLoss"+s(977)]),this[s(1525)+s(1248)]=!1,this[s(1294)]&&this[s(1294)][s(1173)+"te"]!==this[s(1796)]?this["_disconn"+s(816)](1e3,"manual reconnect"+s(928),!0):(this[s(614)]=!0,this._connect())}}async[t(645)](){let r=t;if(!this[r(1703)+"Lock"]){let s=(r(1812)+"3").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1525)+r(1248)]=!1;continue;case"1":this[r(901)+"sCounter"]?.["resetCou"+r(1539)]();continue;case"2":this[r(1571)+r(1659)]?.[r(713)+r(910)+r(1550)]();continue;case"3":this[r(1703)]();continue;case"4":this[r(614)]=!0;continue}break}}}[t(1564)+"Listener"](r,s){this.on(r,s)}[t(1856)+t(1792)](r){let{type:s}=r;this.emit(s,r)}["removeEventListe"+t(1275)](r,s){this[t(507)](r,s)}[t(593)](){let r=t,s={RKpuC:function(l,f){return l(f)},nMDSj:e[r(767)],fMMRK:e.KaKGr,xdaRz:function(l,f,w){return e[r(1637)](l,f,w)},vSMmL:e[r(1020)],owiaO:e[r(1282)]};return new Promise((l,f)=>{let w=r,b={KbNCQ:function(D,L){return s[K(580)](D,L)},PbFDw:s.fMMRK,hNtfS:"ping_onc"+w(1577)+"s",rIycR:w(610)+"e_timeout"};this[w(1114)+w(604)](),this[w(440)+"gTimeoutId"]=s[w(844)](setTimeout,this[w(384)][w(583)](this),this._options[w(1611)+w(1795)]);let y=()=>{let D=w;s[D(580)](l,s[D(1157)]),this[D(507)](D(610)+D(1577)+"s",y),this[D(507)](D(610)+D(907)+"t",p)},p=()=>{let D=w;b.KbNCQ(f,b[D(1544)]),this[D(507)](b[D(1001)],y),this.off(b[D(1892)],p)};this.on(s.vSMmL,y),this.on(s.owiaO,p),this._ping()})}}})(),Me["CustomCl"+M(1891)]=Pe[M(1740)+M(1891)],Me[M(1675)+M(1464)]=Pe.CustomErrorEvent,Me[M(640)+"e"]=Pe[M(640)+"e"],Me.Event=Pe.Event,Me.FWS=Pe.FWS,Me[M(498)+M(746)+M(1775)]=Pe["Frontier"+M(746)+M(1775)],Me[M(746)+M(1775)]=Pe[M(746)+M(1775)],Me[M(1311)+"t"]=Pe.OpenEvent,Me[M(1470)+M(1431)]=Pe[M(1470)+M(1431)],Me[M(1166)+M(1891)]=Pe[M(1166)+M(1891)],Me["createEr"+M(1464)]=Pe[M(1425)+M(1464)],Me[M(804)+M(456)+"nt"]=Pe[M(804)+M(456)+"nt"],Me["createOp"+M(405)]=Pe.createOpenEvent,Me[M(979)+M(1236)+"vent"]=Pe[M(979)+M(1236)+"vent"],Me["decodedF"+M(1313)]=Pe[M(665)+M(1313)],Me["encodeFr"+M(748)]=Pe[M(1373)+M(748)];for(Jo in Pe)["CustomCl"+M(1891),M(1675)+"rorEvent",M(640)+"e",M(1792),M(838),M(498)+"MessageEvent","MessageE"+M(1775),"OpenEvent",M(1470)+M(1431),M(1166)+M(1891),"createEr"+M(1464),M(804)+"ssageEvent",M(415)+M(405),M(979)+M(1236)+M(1775),M(665)+"rame",M(1373)+"ame"][M(1477)](Jo)===-1&&(Me[Jo]=Pe[Jo]);var Jo;Object[M(1418)+"operty"](Me,M(822)+"le",{value:!0})});import{existsSync as l1,openSync as u1}from"node:fs";import{mkdir as f1}from"node:fs/promises";import{dirname as h1}from"node:path";import{fileURLToPath as x1}from"node:url";function g1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Yd(t=J()){return l1(t.libEntry)?t.libEntry:x1(new URL("../index.ts",import.meta.url))}async function cp(t={}){let e=t.paths??J(),n=t.entryOverride??Yd(e),i=g1(e,process.env.COZE_BRIDGE_LOG_MODE);await f1(h1(i),{recursive:!0});let o=u1(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=et(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[os]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return p1.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var p1,os,oa=Xe(()=>{"use strict";Jt();ne();Re();p1=G("spawn-daemon"),os="COZE_BRIDGE_DAEMON"});import{spawn as fI}from"node:child_process";import{mkdir as hI,unlink as xI,writeFile as pI}from"node:fs/promises";import{dirname as gI,join as mI}from"node:path";function Yr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function wI(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${Yr(n)}</key>
21
- <string>${Yr(i)}</string>`).join(`
20
+ `+r)}function tr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,tr),t.emit("wsClientError",d,r,e)}else ss(r,i,o,c)}});var ep=ae(Ae=>{"use strict";var N=j;(function(t,e){let r=j,i=t();for(;;)try{if(parseInt(r(888))/1*(-parseInt(r(1354))/2)+-parseInt(r(1034))/3*(parseInt(r(423))/4)+parseInt(r(935))/5*(parseInt(r(1053))/6)+-parseInt(r(1208))/7*(parseInt(r(1012))/8)+-parseInt(r(1187))/9*(-parseInt(r(1099))/10)+parseInt(r(1308))/11*(parseInt(r(1043))/12)+parseInt(r(364))/13*(-parseInt(r(1829))/14)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(sa,670870);var yS=Object["definePr"+N(1536)],bS=Object["getOwnPr"+N(1806)+N(1526)],Jh=(t,e)=>function(){return t&&(e=(0,t[{TkRak:function(c,d){return c(d)}}[N(1020)](bS,t)[0]])(t=0)),e},ES=(t,e)=>{let r=N,i={wzKLD:function(c,d,u,f){return c(d,u,f)}};for(var o in e)i[r(1002)](yS,t,o,{get:e[o],enumerable:!0})};function vS(){return jh||(jh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function SS(){let t=N;return Wh||(Wh=[IDBCursor[t(870)+"e"][t(1320)],IDBCursor[t(870)+"e"][t(1324)],IDBCursor.prototype[t(1324)+"PrimaryKey"]])}function IS(t){let e=N,r={gSFWZ:function(o){return o()},nGgxE:function(o,c){return o(c)},tOWRb:e(1682),GXdpr:e(1459),OMUNS:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let d=e,u={GIWSn:r[d(1668)],GiXyK:r.GXdpr},f=()=>{let _=d;t[_(1181)+_(564)+_(398)](u[_(741)],h),t[_(1181)+_(564)+_(398)](u[_(651)],g)},h=()=>{let _=d;o(Ut(t.result)),r[_(1033)](f)},g=()=>{let _=d;r[_(1813)](c,t[_(1459)]),r.gSFWZ(f)};t[d(765)+"Listener"](r[d(1668)],h),t[d(765)+d(1865)](r[d(1052)],g)});return i[e(607)](o=>{let c=e;r[c(1219)](o,IDBCursor)&&Wd[c(808)](o,t)})[e(1436)](()=>{}),ra[e(808)](i,t),i}function AS(t){let e=N,r={qCJxK:e(1453),NsoAp:e(1459),vwKFc:"abort",OnYJN:function(o,c){return o-c},MbJcr:function(o,c){return o===c},RaLCp:e(457),ArHjs:function(o){return o()},krbxj:function(o,c){return o(c)},nyecE:e(308)+"or",azWSm:function(o){return o()}};if(na[e(1721)](t))return;let i=new Promise((o,c)=>{let d=e,u={duEly:function(_,v){return r.krbxj(_,v)},YTmUE:r.nyecE,jgHXy:function(_){return r.azWSm(_)}},f=()=>{let _=j;t[_(1181)+_(564)+_(398)](r[_(1258)],h),t[_(1181)+"entListe"+_(398)](r[_(1500)],g),t[_(1181)+_(564)+_(398)](r[_(809)],g)},h=()=>{let _=j,v={ONBCW:function(y,E){return y*E},dagyR:function(y,E){return r[j(849)](y,E)}};if(r[_(1797)](r[_(1673)],r[_(1673)]))r[_(859)](o),f();else{let{initReconnectInterval:y,maxReconnectInterval:E,reconnectIntervalGrowFactor:I}=this[_(1696)],A=v.ONBCW(y,_0x544413.pow(I,v[_(1658)](_0x4e933e,1)));return A>E?E:A}},g=()=>{let _=j;u[_(1518)](c,t[_(1459)]||new DOMException(u[_(753)],u.YTmUE)),u.jgHXy(f)};t["addEvent"+d(1865)](r[d(1258)],h),t[d(765)+"Listener"](r[d(1500)],g),t[d(765)+d(1865)](r[d(809)],g)});na.set(t,i)}function kS(t){ia={ocmcF:function(i,o){return i(o)}}[N(887)](t,ia)}function TS(t){let e=N,r={qGuzW:function(i,o){return i(o)},vPooF:function(i,o){return i(o)},hzODJ:function(i,o){return i(o)},WQEzj:function(i,o){return i(o)},egXFY:function(i,o){return i<<o},pDeIX:function(i,o){return i&o},mbvSC:e(1423),ZaPyB:function(i,o){return i(o)},Zacwi:function(i,o){return i in o},jYsTq:e(990)+"oreNames",YaxfJ:function(i){return i()}};return t===IDBDatabase[e(870)+"e"][e(641)+e(1041)]&&!r[e(1242)](r.jYsTq,IDBTransaction[e(870)+"e"])?function(i,...o){let c=e,d=t.call(r[c(725)](os,this),i,...o);return jd.set(d,i[c(1572)]?i[c(1572)]():[i]),r[c(1549)](Ut,d)}:r.YaxfJ(SS)[e(1477)](t)?function(...i){let o=e;return t.apply(r.hzODJ(os,this),i),r[o(725)](Ut,Wd[o(1548)](this))}:function(...i){let o=e,c={pzPud:function(d,u){return r[j(1332)](d,u)},xfgGo:function(d,u){return d<u},hosWj:function(d,u){return r[j(1274)](d,u)},aAkmv:function(d,u){return r[j(1115)](d,u)}};if(o(1423)===r[o(643)])return Ut(t[o(800)](r[o(1830)](os,this),i));_0x52607f=c[o(763)](_0x4b0509,_0x2ff250),c[o(813)](_0x3bbc4b,32)&&(_0x2ae62a|=c.hosWj(c[o(1338)](127,_0x1be0e2),_0x2fb8ea)),_0x429195+=7}}function CS(t){let e=N,r={RmCrZ:e(890),Yracy:function(i,o){return i(o)},pmJIF:function(i,o){return i instanceof o},ZmwCY:function(i,o,c){return i(o,c)},yUxkB:function(i){return i()}};return typeof t===r[e(449)]?r[e(1151)](TS,t):(r[e(1800)](t,IDBTransaction)&&r[e(1151)](AS,t),r[e(1352)](Zh,t,r[e(1038)](vS))?new Proxy(t,ia):t)}function Ut(t){let e=N,r={ZuriD:function(o,c){return o!==c}};if(t instanceof IDBRequest)return IS(t);if(ea[e(1721)](t))return ea.get(t);let i=CS(t);return r[e(1849)](i,t)&&(ea.set(t,i),ra.set(i,t)),i}function j(t,e){t=t-292;let r=sa(),i=r[t];if(j.yTwVEE===void 0){var o=function(f){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",_="";for(let v=0,y,E,I=0;E=f.charAt(I++);~E&&(y=v%4?y*64+E:E,v++%4)?g+=String.fromCharCode(255&y>>(-2*v&6)):0)E=h.indexOf(E);for(let v=0,y=g.length;v<y;v++)_+="%"+("00"+g.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(_)};j.pnVSkh=o,j.pWQsvd={},j.yTwVEE=!0}let c=r[0],d=t+c,u=j.pWQsvd[d];return u?i=u:(i=j.pnVSkh(i),j.pWQsvd[d]=i),i}var Zh,jh,Wh,Wd,na,jd,ea,ra,ia,os,Kh=Jh({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={akWnd:function(r,i,o){return r(i,o)},VdBIa:t(1461),LFVLU:function(r,i){return r>>i},EgkSz:function(r,i){return r&i},MSCGy:function(r,i){return r!==i},DOHJp:t(1619),MSTmK:function(r,i){return r instanceof i},mRuPz:function(r,i){return r===i},hpOgy:"done",bTsNk:function(r,i){return r===i},zHeNx:t(990)+t(894),qLAvf:t(1382),VZagm:function(r,i){return r(i)},OVXEQ:function(r,i){return r!==i},KPViB:t(300),mAOcS:function(r,i){return r===i},XLdeE:"store"};Zh=(r,i)=>i.some(o=>r instanceof o),Wd=new WeakMap,na=new WeakMap,jd=new WeakMap,ea=new WeakMap,ra=new WeakMap,ia={get(r,i,o){let c=t,d={mhsDx:function(u,f,h){return e[j(458)](u,f,h)},gLNZT:e[c(994)],kIBcf:function(u,f){return u|f},XyIjI:function(u,f){return u&f},pCLUG:function(u,f){return e[c(755)](u,f)},WzMLa:function(u,f){return e[c(1653)](u,f)}};if(e.MSCGy(e.DOHJp,e[c(863)])){let u=this[c(816)+c(1051)]?.[c(1795)+"ntEndpoint"]();this["_dispatc"+c(1256)+"ent"](d.mhsDx(_0x47cd92,d.gLNZT,{code:_0x550f3a.code,reason:"connecti"+c(1328)+c(1419)+"wn reaso"+c(1645)+c(786)+u})),this[c(816)+c(1051)]?.[c(608)+"pointConfig"](),this[c(1770)+c(610)]?.["resetCou"+c(1870)]();return}else{if(e[c(1040)](r,IDBTransaction)){if(e.mRuPz(i,e.hpOgy))return na[c(1548)](r);if(e[c(395)](i,e[c(529)]))return r[c(990)+c(894)]||jd.get(r);if(i===c(602))if(e[c(1728)]!==e[c(1728)])_0x2b07ba[_0x577605++]=d.kIBcf(d.XyIjI(d.pCLUG(_0x1d91eb,18),7),240),_0x4c5da9[_0x1437cf++]=d.WzMLa(_0x2b709e>>12,63)|128;else return o[c(990)+c(894)][1]?void 0:o["objectSt"+c(549)](o["objectSt"+c(894)][0])}return e[c(764)](Ut,r[i])}},set(r,i,o){let c=t;if(e[c(781)](c(1689),e.KPViB))return r[i]=o,!0;this[c(540)+"s"]=_0x16e729,this[c(1734)+"es"]=_0x1dab2e,this[c(473)+c(1679)]=0,this["currentE"+c(591)+c(1823)+"t"]=0},has(r,i){let o=t;return r instanceof IDBTransaction&&(e[o(907)](i,e.hpOgy)||e[o(1532)](i,e[o(371)]))?!0:i in r}},os=r=>ra[t(1548)](r)}}),Yh={};ES(Yh,{deleteDB:()=>DS,openDB:()=>RS,unwrap:()=>os,wrap:()=>Ut});function RS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=N,u={QQuWY:function(g,_){return g(_)},cVjZB:d(1461),Oocos:d(847)+"hange",mQzrz:function(g,_){return g(_)},WNExe:d(1112)+"eeded",QKSWP:"blocked"},f=indexedDB[d(1576)](t,e),h=u[d(774)](Ut,f);return i&&f[d(765)+d(1865)](u.WNExe,g=>{let _=d;i(Ut(f[_(877)]),g[_(696)+"on"],g[_(1415)+"on"],u[_(902)](Ut,f[_(641)+_(1041)]))}),r&&f[d(765)+"Listener"](u.QKSWP,()=>r()),h[d(607)](g=>{let _=d;c&&g[_(765)+"Listener"](u[_(723)],()=>c()),o&&g[_(765)+"Listener"](u[_(571)],()=>o())})[d(1436)](()=>{}),h}function DS(t,{blocked:e}={}){let r=N,i={AehNU:r(1230),MOwyY:function(c,d){return c(d)}},o=indexedDB["deleteDa"+r(716)](t);return e&&o[r(765)+r(1865)](i.AehNU,()=>e()),i[r(677)](Ut,o).then(()=>{})}function $h(t,e){let r=N,i={oaXNP:function(f,h){return f!==h},lwbwZ:"nZwFZ",HsFRM:r(1457)+"e",DMBXJ:r(471),vPiag:function(f,h){return f instanceof h},FijQL:function(f,h){return f in h},eAihk:function(f,h){return f===h},IyPmP:function(f,h){return f!==h}};if(!(i[r(1179)](t,IDBDatabase)&&!i[r(663)](e,t)&&i.eAihk(typeof e,r(882))))return;if(ta.get(e))return ta[r(1548)](e);let o=e.replace(/FromIndex$/,""),c=i[r(1238)](e,o),d=Qh.includes(o);if(!i[r(663)](o,(c?IDBIndex:IDBObjectStore)[r(870)+"e"])||!(d||Xh.includes(o)))return;let u=async function(f,...h){let g=r;if(i[g(1301)](i[g(1269)],g(807))){if(!this[g(1839)])return;this[g(500)+g(1473)+"t"](_0x3bc7b4,_0xc38b1,_0x2e77c6)}else{let _=this[g(641)+g(1041)](f,d?i[g(1142)]:i[g(1550)]),v=_[g(602)];return c&&(v=v[g(803)](h[g(1189)]())),(await Promise[g(704)]([v[o](...h),d&&_[g(603)]]))[0]}};return ta[r(808)](e,u),u}var Xh,Qh,ta,PS=Jh({"node_modules/idb/build/index.js"(){let t=N,e={jOiUm:function(r){return r()},YbOVG:t(1548),BGPwd:"getKey",PcQSU:t(1194),Cccpr:t(1837)+"ys",jRBmV:t(1123),MoCFB:t(1009),jwxcN:t(1866)};e[t(788)](Kh),e.jOiUm(Kh),Xh=[e.YbOVG,e.BGPwd,e[t(1646)],e[t(1285)],t(757)],Qh=[t(1754),e[t(1330)],e.MoCFB,e[t(960)]],ta=new Map,kS(r=>({...r,get:(i,o,c)=>$h(i,o)||r[t(1548)](i,o,c),has:(i,o)=>!!$h(i,o)||r[t(1721)](i,o)}))}}),OS={idb:function(t){let e=N,r={xtNiu:function(i,o){return i<o},zxwxD:function(i,o){return i&o},oUoml:function(i,o){return i>=o},XyuTM:function(i,o){return i<o},NJnTP:function(i,o){return i<<o},CxyAH:function(i,o){return i-o},weCZA:function(i,o){return i|o},dfRWu:function(i,o){return i<<o},ToGZY:function(i,o){return i+o},jJweZ:function(i,o){return i!==o},SyRvT:e(776),wLlIS:e(1174)};t.exports=Promise[e(1877)]()[e(607)](()=>(PS(),Yh))[e(607)](function(i){let o=e,c={pPTMt:function(d,u){return r.xtNiu(d,u)},NGgPq:function(d,u){return d|u},FBdZi:function(d,u){return d<<u},WIFFY:function(d,u){return d&u},MSKdK:function(d,u){return r[j(719)](d,u)},xlScu:function(d,u){return r[j(1092)](d,u)},pOazI:function(d,u){return r.XyuTM(d,u)},IgwNy:function(d,u){return d|u},Fxokh:function(d,u){return r[j(1437)](d,u)},fIvCf:function(d,u){return d>=u},phKXi:function(d,u){return r[j(1827)](d,u)},xFxTR:function(d,u){return r.weCZA(d,u)},rULjv:function(d,u){return r[j(719)](d,u)},OzjuF:function(d,u){return r.dfRWu(d,u)},HGwQG:function(d,u){return r[j(1322)](d,u)},reaeO:function(d,u){return r[j(875)](d,u)}};if(r[o(1821)](r.SyRvT,r[o(1214)]))return i;{let d=_0x34a0d8[_0x35c04f++];if(d<=127)_0x589002+=_0x315332["fromChar"+o(404)](d);else if(d>=192&&c[o(553)](d,224))_0x25f90a+=_0x5d74f7["fromChar"+o(404)](c.NGgPq(c[o(534)](c[o(1758)](31,d),6),c[o(1398)](63,_0x47cebc[_0x4f58e3++])));else if(c[o(599)](d,224)&&c.pOazI(d,240))_0x53f2b8+=_0x3d2173[o(455)+o(404)](c[o(511)](c[o(534)](c[o(1758)](15,d),12),c[o(1812)](c[o(1398)](63,_0x2bc950[_0x331ef6++]),6))|c[o(1398)](63,_0xdf7dd5[_0x21e27c++]));else if(c.fIvCf(d,240)){let u=c[o(792)](c.xFxTR(c.xFxTR(c[o(575)](c[o(1812)](c[o(720)](7,d),18),c[o(488)](63&_0x5e9852[_0x1054a2++],12)),c.HGwQG(c.WIFFY(63,_0x1dd0d7[_0x14d26d++]),6)),c[o(1758)](63,_0x2b9788[_0x164bec++])),65536);_0x27c9ba+=_0x37e746[o(455)+o(404)](55296+(u>>10)),_0x47d4f2+=_0x3150db[o(455)+o(404)](c.reaeO(56320,1023&u))}}})}},Vh={};function sa(){let t=["yMfJA3vWigu","C3bSAwnL","z25yvw4","yxnZAwDU","yM93rhm","D2LSBfjLy28","C2v0sxrLBq","DfnQrxO","CurvzuG","qNntDw4","qNPdEu0","r0Xnt0O","DuH1Dfa","Axnby2TdBgu","ywfjDNi","Dev2zw50","z2v0q3vYCMu","DwnABwu","twjky3i","Dgv4Dc9Qyxy","BwfW","Cg1ksuy","x2rYB3bhBg8","u2Putfm","EM1kz3a","x2nSzwfYvgK","C3jtAwK","B3bLCNr5tMe","u2vYDMLJzvC","igzPzwXKoIa","CMfNzvn5BMm","wLLcBxG","lcbTyxGGCMu","rNHVA2G","BKDNEeu","uNHtsLq","rNnnqvG","yLnctK4","wvrHqvK","vMPAu1K","BwzUt1q","ywnRDxbfBMq","AKP3zvO","qufOwKC","CMLLC0nVDw4","o2nOyxjZzxq","Bwv0Ag9K","C3nHz2vfDMu","q3H5quG","y1bIuM8","mZCZmtGXmK5Zq3njwa","wMfqEui","x2fKzfDZtgK","qNjPzgDL","Bg9Wre4","vfPotwW","ALPIA04","DMX4uhC","z2v0qwXSs2u","zxjFCw9Zx2e","x3DZ","yNHOCMO","yxbuv3i","r1DKtKG","mhWZ","suXgEwO","sw5qCwS","DgfftuK","BwzQyui","x29UrxjYB3i","wNvYAuq","zxH0ugf5Bg8","B3nLrxzLBNq","mNWXFdn8ohW","DxrVuMvJB24","CM92AwrLihC","Dg9cExrLC0W","uu1ruNG","zhrZtwm","vLv2tMK","wwjdzLi","q3jADwe","mNW3Fdr8mq","vuL1rwq","AMDSzKe","tu1lr0K","tgLZDgvUzxi","y2XLyxi","vxPXv28","y3jLyxrLrwW","zgfgBwq","BNrLCG","v25dDwG","ELnABNm","C1nSu2m","igfYCMf5yNu","BgLTAxq","CMvJB25Uzwm","CMvZB2X2zq","zxPcCgi","zgvJB2rLzey","x29UvgLTzw8","B2D1Duy","zgvIDwC","ve1YC3K","EujYwxK","r21eCeq","u1HPuNC","Cgf5Bg9Hzfq","v3jMt00","z1rPBwvVDxq","uwXbyvi","Ef9MCM9UDgK","D25wzgW","AgTdweS","y3ruAw1LB3u","BMvLzf9Hy2S","BuflANa","wgzjsxu","sxn0u2K","Evfxuem","CgXLyxnLiha","qwjVCNrfCNi","ywnRtxnNswq","DhfVwhq","DgLLCKPtt04","vhrSu3m","zwLHwfC","CMvUDevUzha","zgrjrcWGzgu","qufLD0W","v0fnrgC","ywDguey","DK9uuhy","uKzfC2m","EKHwy0G","Bg9IywXty28","igXHCMDLCIa","BNruCMLLC0m","wgHUuMm","wKnmENC","B3fxDei","uuTfruy","s3H5BKW","CMvJzwL2zwq","y2HLy2TdDxi","ENLyAhq","AxzwB3e","CgfYC2u","EvPVC2K","y2uGBM90igK","uKDlEMG","whbwrfa","AgvHzgvY","Ae1crhy","vxbjCMq","x3vYBa","z2vrDwv1zuW","Cu9uB3e","DLPpzg8","rfHdyvy","B2fK","zKvVqwq","y3bjv3K","tfbpCgi","zNjVBuHHC2G","zgPNrxG","y0DSuvm","CM92AwrLige","r0rICMq","uMXTCwG","s3HvqM0","zeXmvfC","Ew9lDee","s0HotMO","qvHOr2u","AwrI","yNPxCvy","mtnytuLVwei","v2Dxs2y","DgLTzw91DcW","tLnYtve","CgLUz0LUDgu","CxfXDhi","v1HuBeW","weXKzuu","tNndtKu","x2XPC3rLBMu","rejWwhK","yw5ZzM9YBvq","AevYCM9Yrxy","u0vjr1y","wfrmufC","v2Xctvi","CLvjvMy","r054Dfy","EK5UqLC","yMfSu2nVCgu","AuzmDKK","u0fdwNK","ue9NsKW","BfbIAgS","B0PRww8","u3jvteq","z0LAy2e","zxjFBxnNAwq","CenWue4","reiGzMfPBgu","u1HvzvC","yLrZtMS","tK9yAvC","AuzeuLK","BMvY","qLf5EgC","uvHwqNK","ruX0uMq","tvvrBvu","r2PUD3i","q29Kzq","ELjvrMS","weDju0u","vvLHteC","ywDLsgLKzq","zw1LBNq","Bg9fy1y","yu9LyLC","shzqEhC","BwrjD3u","CMvKDwnL","x2LUAxq","y29UC3rYDwm","yxv0B21HDgK","B3rwDNi","EgTAEg8","ywX3yxLZ","y1n3vxm","CYbWyxjHBxm","mtq0mJm2vKjTrxnJ","BxnNsuq","x2LZqNjVD3m","BMnVzgLUzW","zK5kB3u","x21LC3nHz2u","ywDL","x25HDMLNyxq","y09Wzw4","svvgwgG","uLLHsvi","B2TVz1G","refYEuC","tun0vwm","CuPpAve","BML0AwfSAxO","DMLJzuLeig8","Cfnvve4","D24GCMvHC28","AKr3qNe","weD1vgm","txrZyxC","vxnPsLu","qMTRtfO","CfbiEfK","v2rWuKW","uM1dCLO","y056zfe","wNHqu0S","seviB2O","ExvVzhu","D05IDeW","zNjVBunOyxi","A29SvKu","tNjfDwq","ywTxBMq","y29UBMvJDfm","BMfTzq","BwvY","z1DSC1i","BfjvrLy","CNnVCKzPBgu","u21OreS","BgPrtgW","u2XWCxy","wvDeqKO","v2TRA0C","twvZC2fNzuu","CMvHzg9UBhK","CMfTugfYyw0","y3vYCMvUDeK","rwfrCwS","CM9YrxzLBNq","CgLUz1rPBwu","tgnwC3O","sgvczwm","Dg9mB3DLCKm","EMPTz0W","ywD1vLi","tu9pEwW","u2vXsuq","DwrzD2e","q0v3rKC","x1fVu01HBMe","wNnpCM4","t3PQDuy","DxPvAvG","ywzL","CMvQzwn0","AxnAzxjV","ywDLu2HVDW","zMXVB3i","zgHIswW","zw5hCgG","zKDlAva","z3nuAuu","r3LrBMK","x2rLC3rYB3K","qu5VuwC","BNrbBMrvCgq","zMDtAwW","y29Uy2f0","AxL0yuO","uxvzuvi","nNWWFdv8m3W","tuvtu0fhrv8","t01yCfa","v1DRvLe","swD3tNK","B25SAw5L","DhjiCLu","q0f1r3u","Cxvct3q","BM5Ly3q","Aw5Lza","zurhwe8","y2LnqKu","wNzJyNO","uejjvvm","Dw5ZAwDUzwq","x2n1CNnVCKy","zKHVBfi","BNbztKq","yKDUB0i","rerwBM4","AgfUz2u","EKHLtNG","DMTfq1i","sfriu0y","rfH3AKC","yMLUyxj5vhK","rKjKwMK","DeD4BgS","zenzAhq","B25pCgvU","u0HsD3e","vvzXDfO","zw5KCg9PBNq","zw1PDa","s1nHz1G","EKrUBg0","BgnHDhC","BgXYrKe","CLzHBhvLCW","yuvLueq","DfDUtfK","B3jL","wKvdvLm","BwvZC2fNzq","yxbWzw5Kq2G","Cfbutxq","y3vYC29Yx24","uePMz1i","D2noCMW","u2XuAei","y0XHEKe","wuTqqLa","EKDbCfa","zxH0zw5ZAw8","y1HpAxi","zgHLzfq","zw50tgLZDgu","whnPEuG","wujMwwS","ihrYEsbYzwm","BwLUzW","Bxr3uLy","x2LZsw5PDa","t29JB3m","yw1rB20","B25LCNjVCG","ywXPzcb1CMW","tKDNuhe","AKnsv2W","zuXZvfO","ywXSB2nvBNm","Bwu6ia","z2vjBMzVu3K","r0fTtLm","zvfvAxy","s0PND08","C2nwv1C","rfPfD3q","Ee1MuLi","zxjYtxnN","v3zeAgK","DxzbA2m","C0rIvLK","BMrWB2LUDfq","x2n1CNnVCK0","wg1mD3m","qvrluNa","z2v0q3vYC28","vLHWCwG","weTMENe","v2vPEgLUsLm","EgXty3u","BMzku3C","D2vI","C3rVCMu","zg9Uzq","q3PbDK4","BgvY","zv9ZDwnJzxm","DgHLBG","CMvZzxrfBMq","Aw91AeO","C0nVDw50zxi","x3nLCuLK","mNW0Fdf8m3W","rvfkq2C","ExfZtM8","ChrVCG","DgLTzw91Da","zxjFAxnFywm","wgv5tgy","zfDVCMTLCKC","v2LjuM0","yMLUyxj5","sgPOsuq","zM5hwM8","Aw1LCYbPBIa","B2rvEwy","v0rqCLi","s21Wwu0","AwLhB0K","rKLmrv9ot1q","zwXwDwS","Eufiuw4","rxjYB3jdB2q","wgLJEMC","tg5PvxG","CKPeELq","v29gyxG","zxPnrfO","B3jRig9MzMW","s0XKt0W","tLr5sMm","DhjHBNnHy3q","vwrsrNy","Bwj2u0m","A1nvB3O","pxv0zI04","C2fNzq","x2HHBMrSzva","tvDnsvG","BMrWB2LUDca","Cgzcshy","r2LyEuS","DxbKyxrLq3u","rw9sy2S","aaaaaaaaaaa","EwD0vNu","uxzHDvO","D3jPDgvvAw4","twLZC2LUzYa","t0PeDgK","Dg9tDhjPBMC","B2fOExe","q09oveLovuu","rMLQuuW","x2zVCM1HDeu","u3rYyxrLz3K","CvHcs2K","BNrfBMrWB2K","CNjVCK1LC3m","AwrPtxm","BhHiv2C","y29UBMvJDa","CxHSqNq","yw5Nzq","CMvHzfvjBNq","C3L3BeK","ruDIEvy","tu93EvK","D3jPDgu","CM92AwrLigi","C3vcEwe","y29SBM8","sLnTr2C","CNrOs0K","BeHHBMrSzxi","AgvHzgvYCW","ugX3wLK","vxvlu1u","Ae9Wzw5fDMu","C1HtC1K","C3vIyxjYyxK","Bg9NsurozxC","Bwf4tg9ZC0m","Bw1QuMy","zM9oCKq","r2nrtNa","B2XKvMvYC2K","zNjVBu51Bwi","zw5XDwv1zq","wvzRvuC","BuDfDfe","vKfrr1q","AxnbCNjHEq","C2vYDMLJzs0","ywXS","u0L3B2u","DMfS","AxDbEKG","BLjuy0m","yLv3tui","qurdvg0","wfjgtxG","Ahr0Chm6","uer3BKy","rNbluvy","BfrPBwvVDxq","DgfIyxnL","tMvTvLu","ufj2wNm","ENH3Eeq","CLvmANy","CLvTwvO","Aw5N","y1zQwKi","zxj2AwnL","CuD1ELC","DgLUzYbZzxi","ywzbuha","wNj5tvC","y3jLyxrLt3a","yxnL","EwncB1y","z2v0sxrLBq","BwvZC2fNzv8","q2TKA2i","Dg9cExrLC0i","AMnmwNq","thLUtMe","tMfTzq","uK1YsMC","CeL5Cfm","r0Lxu24","ihrPBwvVDxq","igzHAwWSig0","vurdyvC","Ec1TC2CTy3u","r21mC1i","q2PYBfi","qMfeq2y","CwD5A1q","y2HnyxHdB3u","zNLjwMK","zw5JB2rPBMC","wvrTvuu","u2TPCcbWyxm","tezwtfu","ywnRx2nVzgu","y291BNq","ihrVihjLDhi","AwDHDg9Yt24","x2rItMfTzq","DwfvD1e","AuvJEMe","ChPqDwq","vLPHz20","ywrKrxzLBNq","qKLHC2S","BMvJDa","rMrly2e","AfjXwfm","yxKSihrYEsa","BwTrDKW","CMvWBgfJzq","CgLUz09Uy2u","Bvf6CNO","tw5Ztu0","BhP6ExG","zfbgufq","A0DIzuS","x2TLEvbHDgG","ihn1y2nLC3m","t1zyrve","zwn0","yKn3q0W","yNbcuhy","wKfQtuO","yw1LoIa","AxzfA0q","AK9Pvw0","zcWG","Dgv4DfbHEwW","whjpB00","CgHlwgK","DhDVCMTdAge","z25RvLa","sfzqEK4","tg9NsurozxC","q29UzMLN","y29UBMvJDca","ChbLteG","yxbWBhK","s0zdzM8","CvDLsuW","Aw5KzxG","zw50zwqGDhK","CNLXCNC","y3jLyxrLuMu","BLP3rLO","C2v0","DNDlrMm","u25ss2q","teDJA2C","AxnmB25N","EgzNr28","qKv3B0W","yMLUza","x2vUzhbVAw4","DKLOsg4","twzivKq","DMLbt2W","vMP2uNa","vw5kvMS","whHIrwe","nhWXFdj8mhW","vgn2uNG","EvrotLG","reDSt0W","EwT1D1K","v1DYC1m","wKz3BwG","D0PVCw8","CNzHBfzHBhu","ywnur2O","v1LRqvC","x3bYzwzPEa","tfnIEhy","C2vYDMvYvgK","Ahr0Ca","wKTJA2y","EMvdC2y","y2fSBa","DxbAr2S","vwPwu3y","C3rHCNq","AvvIuha","Dg9Y","s2XvuhG","DMvYC2LVBMm","z2v0u3rVCMe","t25zsK4","vKjUseq","B3v0sw50zxi","wLn1A0S","s2ziD1G","CMjKtxy","EhntEMK","thzjCNe","CgvYC2LZDgu","Aw5ewKm","qxjiANm","zw5HyMXLvhi","vxjtDgS","x2LZtwLUAvC","re9isNa","rwTuwwC","y2HLy2Tszwe","zxmGCMvHy2G","A2v5sKC","yKPtte8","zMLN","ChjVDg90Exa","Cw9Z","zw5fDMvUDa","wKD1vvG","y3jLyxrLt2i","vg9hwLK","y2HnyxHuCMK","CMvZDwX0","z2nOs0O","AxnTBhK","t29lu0e","C1rlrKC","C3rYAw5N","wMjivuu","x2DLBMvYyxq","x3jLywr5q2W","wMXWBxK","B2nTy0y","mZjhufHLDva","A2v5CW","zNvUy3rPB24","venSDxO","l3DZl3yY","y3vYC29Y","B3jLtMfTzxm","tuDez2e","DgvZDa","Duj1Cu8","r0fitem","v05ky2i","s3PLEgS","EhLKsKq","uvf1v1K","C1Hlq2m","AgvKtwf4uMu","qwD2vKq","DMjrCem","Bvj1uhO","Evv4z3i","Egrzruq","sKLrs00","rvjst1i","uvfHBg4","DwDArM0","y2XVC2veqG","sNbbs0q","ANLAv0S","CeP4B2K","te92vMG","z2vtEw5J","sKjwru8","wufQuLu","DxL5Aum","s3juDhG","EhDzEw0","BMv4DcGPigm","x2jPBMfYEvq","B2zMC2v0","yKTYBMK","DvDbAKu","CNzsC3K","u3fYDhm","x2LUDgvYDMe","rxzLBNq","uLfHz0i","nuDjC2nVEa","x29UtwvZC2e","CMvXDwLYzwq","qK1Zr00","q09otKvdveK","x0vysvnu","A2vmEve","shrmquS","B3nLza","ywXSq3vYC28","yM9L","x3DZsw5ZDge","tgLXyMy","C2vUza","zv90Aw1LB3u","Efrurw52","zwvSt1i","BvDItgu","ywHXD2O","z25VugW","AMnNCgy","Cgf5Bg9Hzeu","uvfKsey","ywnOzwq","wNz0seO","AND4y04","A0fvCLu","x2DLDeLUDgu","Cg9qC0G","ywrKq291BNq","AwXLtMfTzq","zK1yBMS","x2nSzwfYugK","C2vUzf9Hy2S","DhbSte4","rvHcAe4","zwrhAvi","x2rPC2nVBM4","zM9YrwfJAa","z3nosgm","yNfpqLm","yLvpruW","rKzlt00","r1P6CeC","B25dBg9Zzq","z2u6ia","Bg93","tMnXtfy","zMLSzw5HBwu","Dxrjza","vgfN","r0jJveu","v2LUzg93","ENjry3y","q2rIthy","B2jQzwn0u3q","r0TVzfC","AfHhyve","BgfotLG","vMrcswe","renfvMe","Au9PD0y","x29Uq2XVC2u","C2XPy2u","A2v5","uuD1CfG","tMz2r3e","D3Plteq","AKnszhC","BMDLza","rxvZvNe","x29UugfNzu4","DhLWzq","BgjNBuC","zgvSzxrL","yxrLq291BNq","B25nzxnZywC","oda5nZzgtgvouLy","sgrdExm","BMjqCeO","sufNBNy","EMH2Eum","D2Txt28","CxDQsfi","tujhuvm","vgTsywS","zxrxB3jRq2G","CMfUzg9T","zgvMAw5Luhi","tufyx1jfvfi","wMn4tvi","Bvviqu4","q2DYDKe","DLDOvKu","B25VCgvU","rM5Wsvi","sxbRwNO","r1LwyLC","z1ngv1O","mZLMEM55tfu","A3fMwLe","DxrMofDYAxq","Exjeuee","Evv4A0i","CurYs28","tvnuBuS","Aw9U","uufRuxC","mtuZotGZndbNAxrnt2C","Agfoy3C","ywnRpwzYB24","EerUAeW","mdaWma","CIb0DhDjra","A0L2D0e","Eujyse8","De1HBMfNzxi","r1HKChi","mZy0mZG1nezUshveuG","uMvHzcbWyxm","DhD2qxe","r3nVvxa","DM56CLG","DgrnsfO","yxbWBgLJyxq","v1bAuwy","yNLL","B25tDg9Wsw0","zvHXD1a","Cw9Zx18","x2HHBMrSzvi","x2LZtM9Kzq","uLjpuG","yxv0BW","ihbYB3rVy28","AvzKtvm","vefrDxq","BwLAyuq","vgPhCgm","x2LUAxrhBg8","r1vtALO","zNjVBujPDhm","x2LZtwLUAvq","CM1QEhC","C3vIC3rYAw4","vMrNAuC","Dw5RBM93BIa","wwzhsNO","zMX1C2HfEha","zw5JB2rLrNi","zNjHBwvuExa","BM9Uzv9UB24","DMvUDa","s29uveq","zgnMueO","C2vYDMLJzq","EufTwMe","B1vVBwW","DujPCuu","ugjvvwO","AxnrB1nnzxm","BMLAC2m","wLn0seO","zwfXA0y","mte5mty4mtbpzxLUCMu","CYbHBhjLywq","sLfutu0","ze1iBwG","C2DPza","C2v0u3rVCMe","Ewvvq2u","DhbizwfKzxi","ww9RC0K","s1fKB3e","x3bPBMC","A1n0yxr1C0m","zM9Yy2u","DxbNCMfKzw4","B2zMBgLUzq","CgTTtNG","CerLsvG","DgHHBIbSB2m","yNL0zuXLBMC","qw1VDw50","C2v0y3vYC28","vgDjq0G","zufJAW","y3jLyxrLq2W","ywrK","EgDJwM8","zw5HyMXLuw8","C3rYAw5NAwy","sg1bA24","yMfSrxzLBNq","D1HiCLy","AgHtvuG","x2n1CNnVCK4","Cg93","tw9gA0W","DxjS","CKDVqw0","z0fQAu8","Aw47y2HHCNm","AxnrB1nby2S","CxDiu3C","uhntrKm","tKDFrvjst1i","shnguK0","BK1mq0m","zgvS","Dgfzq2q","nhW2FdL8nxW","zur0rgO","quXm","u2f2zuK","zKPdzMu","wxjHy3K","t2PLrha","ALvMtMS","DMzWqxa","q0Xpu0ve","AgvIywG","twrSsei","t1bftG","z25wswy","tu1dB2O","q291BNq","BxnNtw0","AgvJu3q","CKnWu0y","De5Uq0u","B2zM","ihjLy29UBMu","Dw50","AM9PBG","yxrHlcbKyxq","EwvXAMm","u1LZv1i","C2v0q3vYC28","rgv0EwS","EKjVs3K","CMvHC29U","uMnMDxG","ChjVy2vZCW","DLbPywC","yw5Hz2vY","CMvTB3zLrxy","rwXhy3m","x3nVy2TLDa","zMzmAw5L","BwXWuvi","B3bLBKrc","owvgsuvoCG","icSG","C2HPzNq","zwrPyxrLBhK","Ewzusfe","tg9Nsuq","wuHxree","z2v0qwXS","DhfdzKm","B25ozxr3B3i","zgf0yq","x194x21Zz18","sM9LC1q","x3jLy29UBMu","v1jRDxm","vgrtDeS","sLf6rwq","wMv6Dfi","Aw11q08","yw9yqNK","C2DKseW","ntuZB3bWDeHP","x29Ut3bLBG","vMnNyvG","CgDPzuW","x19LC01Vzhu","vfj5AwS","D0XSsvm","BMDuAw1LCG","AgnUvuq","AMvJDfn0B3i","zsbHihn0CMK","t01vtLm","yxjNBLm","q3vZDg9Trxi","Ce95vvK","ywDLrxzLBNq","y2flC28","t1bftL9fuLi","AeziugK","u1fgBem","BfjUsgW","suvtx0vsuK8","yMXVy2TLza","wxnnvuW","seHkCM8","sufpAMm","C2nYAxb0","D3vrrgm","ywrdEva","tgT1tw0","sxLqBva","DMvHyu8","wejsvgG","CMvHzhLtDge","wMfJD2K","zxjYtM8","zwPSwxC","DhjPzxm","uez2uuS","CvrTBfG","CvPhDvy","y2XVC2uSihC","ExzTBuy","yLLeBe4","mdaWmdaWmda","x2LUAxrqCM8","qMvMB1q","Cg9PBNrdB24","AenSB3nLrxy","zgv2AwnLx2K","CunkEeS","wwPqy08","CvrXq3i","Dfntv2C","EfHoB0q","vhbtsfK","y3jLyxrLtwu","uMvJB25Uzwm","zxnrzNu","DwLxsfi","zgzWsKO","BhDID1O","AfHyzve","t3LmrLG","sNnHAe4","D1bSvxe","zwDyrLK","C0Xf","C2vUDa","qvH4Cei","rKrxCxy","vLLPA1G","zwHms0u","EfPwAee","CgLUz19VBMm","q3vZDg9Tq2W","B09ougu","q2nJChi","twnOz1K","BgLUzq","tLfRquK","z2vY","A01Hrei","Au5WuMi","rfzUC3C","ufHWr0W","r1HlD20","Ew1UvK0","BKXPBMu","zxjFCw9Z","v0v3ANG","Den4y1u","vMLlsgO","B2fytLa","DMfSDwu","vgLTzw91Da","B2nRzxq","ywjmwM8","zw5HyMXLqxu","yujovfi","mtfuwxnntuW","EuvQz1a","vKPLCu0","r0veswq","quv4Cui","AufnyuS","BhLIswe","x3jLBw92zvC","tM1uv3O","zMvY","A0zVuhO","EhLABMO","ywr2yw5Jzq","y3vYC29Yx2y","zgzsv3u","tMPLwLi","y29UDgLUDwu","rLrQtLq","sLLhBfC","B25tDgfYDfi","BMCGzMfPBgu","rfPuu2K","ALjcBvy","zMzLCG","v1ffEMO","twnZuKi","AxnFywnR","BNfjtfG","rwHuywu","Aw1oEhG","yufRBxy","v1j0ywS","BwTZr24","ywnOzwqSihC","wfvdz0y","zw50","z3rsB0K","zw5UwfO","x21PBMLoyxy","uKXItK0","zMjryvu","AxDOB2e","Dw1hshG","DNDJu0C","wM13q1K","ExzNALG","ntq3nZjct1Dzv1a","B2HIvvq","thrmv00","zwP2uLG","zwnVBM5Ly3q","CMXrAMW","zgLZCgf0y2G","s25Yzu4","yxn6Bhy","AgfZt3DUuhi","ruTRuwq","zxHWB3j0CW","DhjPBq","vwr6twS","x3bHDgHlzxK","Ae1LC3nHz2u","zxjHDg9Y","x2rPC3bHDgm","sKjXvNG","ze90z3y","uuHsqwK","x3nLBMrby2S","B25mAw5L","zMLUza","BwHtD1G","z3LYruq","CvvuuwC","CfbpCKi","vgXuDe0","zKHNCKS","t0HQqK0","uwzfAgK","AefJA01LC3m","vgLPCwe","rMvcAg4","yxDQAe8","BgvUz3rO","B3jpBMXPBMu","yNL0zu9MzNm","zgrzAhm","zwDLuNy","Curkqxi","yujhz1u","ihzHBgLKigq","tvnlzeS","u3rpueC","Aw5PDcbrB1m","DgvmB2Djre4","rMvnA0O","D3jQy0G","t3bdDKq","Ee9ttw4","A3rQzLC","C2PsvuK","shP3Eg4","y3jLyxrLrxi","vKL0whG","AxjLza","DgjUz3O","vfzMDhC","AejPCxO","BMv3vMvYC2K","C0jf","D0zkAhC","rNjVBNrPzxi","zcWGDw5RBM8","y3vYCMvUDeu","ywXty29Wzq","BeTOvfa","qwT5twK","x3DHAxq","s0Xgr3u","DMfSDwvZ","qxvQBNC","A1beEMW","Dw5KzwzPBMu","uKjPCva","ywWGy3vYC28","DxP4v2i","BuPurhe","CM92AwrLihy","AwXSihvZzsa","y2f0y2G","tKPUvfa","runOAvi","rwHuvuK","ChDbrvO","vxDYrfO","y29UDgv4Da","zvvYBa","uvnWyKK","BgLUzw5V","D3viz1K","teLlvLy","y29UBMvJDeu","BM93","ELverhC","qvLlsuC","CMvWBgfJzui","y29TCgXLDgu","vurcEMC","D1bgsNK","C0LdC0S","CMvHzhDYAxq","B3vUDa","zxjYB3i","sMrxEM4","y2XVC2u","ww9Mv1C","rLjptLrjrvi","swvezwS","vefnD2m","CNzHBa","BgnOte0","yw1Lu3bHy2u","q1P4D1q","CgfNzwHPzgu","zKTksMS","A1HfwwO","v2vIu29JA2u","quvcuhq","AhfyDvC","wvDPz2m","Aw5JBhvKzxm","DNrtvKu","EwXZquW","Cg9W","zMT2Cu4","B25JBg9Zzq","x3bPBMDqB24","zMnLD3i","u3bpEfm","C1vJzMy","y29UBMvJDgK","x3fVC0rc","ChvZAa","yxGGCMv0CMK","Cgu6ia","vMXdrfm","Bwf4twvZC2e","Cfrxuhu","Bhbnq2W","DLDhvxO","uwPLAfi","jMPZy2fSBgi","q0PyDxm","tNnVqxa","B3zJswO","BezSDxnO","Dg9hzw5LCMe","whDXzgG","BwvKAwf0zwW","zwf6Du8","y1rwt1K","rMH4qxC","B1jAuNq","ENPwtNu","Aw9Ul2PZB24","sfLJyKq","BhrmDhG","A1jhqLm","t1HjveG","ugLxBwS","zgfhs0q","zhvfBhK","DxDzr2S","DeLUDgvYy2u","lcbOB3n0BMe","EgzAqu4","t3bLBKv2zw4","wLLzs0i","C1D0uuO","BwvZ","DwDvrKS","BMCGDxjSoIa","y3vYC29YlNm","teHdBw4","C1fRDgq","Bufpy1m","C3rLBMvYCW","y29Kzq","t212Deu","B3bLCNr5","u1v0ALm","BMnmtNK","uePtufC","yNLLEum","zNjVBuj5Dgu","x2nYzwf0zvm","DKTOz1C","DvrUr0G","yw1L","zLbyr00","wwLnyvO","z2v0","DLbVB0y","re1cweO","twfZt2q","uM9KCuy","zNbWtK4","uKfmA04","BgLZDgvUtMu","sg5owg0","Aw5SvhK","y2Dvt0W","A2XLzNa","C0XPC3rLBMu","nhWXFdj8m3W","A3HXEvK","v2zZvgi","CgLUz0XVC3m","ihzHBgLKihm","ChfJD1G","t0T5qxO","u0PSDfC","y2vZC0HHBMq","y1jYt04","B3bQDhO","C29YDa","vKvZwMm","ChnUDfG","q0Xpu0LorW","B3bLBG","BhvXALq","AxnszwfKEq","vfr0CK8","BwLZzq","z3njwvm","CgfNzxnOB3C","DevWDw8","Bg9N","q1nnAM0","svPrv2q","wMX2rNO","DufVAge","uK1uvM8","zKzMr3m","BhrPCgXLihq","AKXLruS","yM5AEei","wLLWExi","Awnmtge","ExbL","y3vZDg9Tshq","C3bSAxq","BxzNug8","x2nVBM5Ly3q","yu1HteG","rMf0A0C","yMrFzgLK","qMT6B3y","EMnOCLm","EsbJBg9Zzwq","Cgf5Bg9Hza","zNjVBNrPzxi","AxmGDw5Kzwy","t3PTAfO","x2rLyNvN","r2vquwG","t2jQzwn0","Bxnmtwe","sLHSsui","AwzJENi","Aw50zwDLCIa","Bxzes0e","ENL2vue","ChD1z1e","vxbKyxrLq28","sfHut1C","ExHvBw0","D25zshy","BwvZC2fNztO","EhnUvxC","DgfYz2v0","tffxy0m","ANDsAvK","DhjRAMG","rMvmEei","tufMDKm","ELHSq3C","whfTt2G","zKvsv1y","zxjFywnRx20","Dxf5Axa","CfrvsfK","C2v0zgi","DwH3CNe","C3Lxrem","DeLK","x0rctMfTzq","zhHPCuO","BIWGAg9ZDg4","ugnru1u","A3znEvO","rLDt","BxnN","rKTQsMK","v1LbuLK","AwXLx25HBwu","rwDRu3O","CvjgCNy","DePguLu","yNvMzMvY","ihrPBwvZ","zgfNEvi","zxbXq0y","BMnLq2XVC2u","Exzkr0u","s0nQCuW","yNvMzMvYzwq","u2HHCMvKv28","wgTIAhO","r0Pjv3q","A2vKC2S","De9xuMi","tKfusvzfx0u","B0rjCKC","sLnptLa","BxjytKS","uMfmq3a","zMr0BhO","revoqK4","A2vYsha","z2Pzv08","tMDAEwu","BMrLEa","x3bYB3rVy28","B25szwnLAxy","C3vJy2vZCW","wNbJsfu","mhWZFdr8mxW","sfnnv2m","z29PBMCGyxC","BNvTyMvY","wuPAENG","q3HuAMW","CezKzK8","DfDqB1a","yvrqy0K","yMjKA1i","Ec11C2uT","Dg9iyxnO","x29WDgLVBNm","sKXbAgy","vMLyBxO","x2HHBMrSzu8","vxvZt1K","DNztBgW","uw53rhG","y2HHCKnVzgu","B2nRzxrtDwm","Aw5KzxHpzG","CMvZzxrdB3u","wgntz24","ruvQu3a","tgXyCKu","ChzXyuq","C3HKwg4","q0rizMq","vu1Iweq","AgLNAa","zwTpve8","tvfrA0u","BNv2ugO","ChjVDg9JB2W","CfPTBMG","y2XLyxjtDg8","AgfZ","vLvvEvy","ExL3ru4","Cg9PBNrbBMq","Aw9UvgLTzw8","Dhj1y3rVCIa","s3D4C3y","CuXbDMy","EgPdsxO","DhjPzxmGCMu","uxvLDwu","x2LZv29YA2u","z0fjs1u","Bwf4uMv0CMK","B25TzxnZywC","tg9JAW","zfLwwKG","vLjjqvG","vuP4zvO","yNL0zxm","Ehz1vwS","CMvZzxruCMK","zKPNrNi","quHcr3e","z0PMz3e","ywnRx2LK","suXtwxC","Aw54BhC","rLHgCNe","uxv2DMm","EwPAD2q","u1vPALK","Bhv5vwS","Chv0","yM9KEq","swL5s3q","B2LUDfjLywm","v0LgrLK","Ec1TC2CTCw8","yMnJC28","D3m6lY8","DMvY","wuXyrNC","EvjLy29UBMu","vwnVBuq","DMvsy0W","AM5fC3e","Bg9Nsurhzw4","rfDAwgS","x3bPBMDmB3m","Aw5L","B3jNs00","C2vVtNq","B3jRzxjhBg8","u3jtueu","vfHXqLq","EwfOvw0","B2nRzxrgywK"];return sa=function(){return t},sa()}function zt(t){let e=N,r={BEwoL:e(612)+"0",uwYGk:function(u,f){return u!==f}},i=r[e(814)][e(1598)]("|"),o=0;for(;;){switch(i[o++]){case"0":return c[e(1365)];case"1":var c=Vh[t]={exports:{}};continue;case"2":var d=Vh[t];continue;case"3":OS[t](c,c[e(1365)],zt);continue;case"4":if(r[e(1519)](void 0,d))return d[e(1365)];continue}break}}zt.d=(t,e)=>{let r=j;for(var i in e)zt.o(e,i)&&!zt.o(t,i)&&Object["definePr"+r(1536)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;zt.o=(e,r)=>Object[t(870)+"e"][t(1363)+t(1536)][t(840)](e,r)})(),(()=>{let t=N,e={kerHp:function(r,i){return r===i},dxiqJ:t(1336),fjEMx:t(450),QjehR:function(r,i){return r!=i},fppNN:t(1429)+"d",DDVnn:"Module",nfJSw:t(1212)+"le"};zt.r=r=>{let i=t;e[i(1676)](e[i(1644)],e.fjEMx)?(Ae[i(1346)+"igatorOn"+i(1287)]=_0xc5496,_0x3700ce?Ae["_handleO"+i(1296)]():Ae["_handleO"+i(1184)]()):(e[i(1497)](e[i(1553)],typeof Symbol)&&Symbol[i(660)+i(985)]&&Object[i(1023)+i(1536)](r,Symbol[i(660)+i(985)],{value:e[i(527)]}),Object[i(1023)+i(1536)](r,e[i(600)],{value:!0}))}})();var Pe={};(()=>{let t=N,e={FKjJi:function(a,n){return a(n)},fKJJk:function(a,n){return a+n},oqWtB:"GWnqZ",fcewr:function(a,n){return a+n},taEMI:function(a,n){return a*n},ILFyj:function(a,n,s){return a(n,s)},NmTWz:function(a,n){return a(n)},WYARY:function(a,n){return a(n)},NsCNE:t(1047),Acptf:"ffff",ZCLzw:function(a,n){return a(n)},xDQqm:function(a,n){return a(n)},uWAjE:t(1252)+t(1252)+t(1252)+t(1252),UMbXD:function(a,n){return a<n},pJxoi:function(a,n){return a+n},ZYBmx:t(1463)+">",kqfZQ:function(a,n){return a<n},zHVcH:t(1494),rJDzT:function(a,n){return a>n},xOSMn:function(a,n){return a!==n},qTqCr:"tDrGw",VyRnX:"lDjea",yoKtA:function(a,n){return a!==n},iAMaK:function(a,n){return a-n},bqOBS:function(a,n){return a===n},cLazA:function(a,n){return a-n},FpKQV:function(a,n){return a>=n},IAgnv:function(a,n){return a<=n},mlpQR:function(a,n){return a|n},OjGIa:function(a,n){return a/n},iiGoI:function(a,n){return a!==n},WnCuh:t(1464),AgvVD:"ftvOh",jLeEK:function(a,n){return a>>>n},ZeztR:function(a,n,s){return a(n,s)},xvuUk:function(a,n){return a(n)},tWPoP:function(a,n,s){return a(n,s)},SrULD:function(a,n){return a(n)},XGISE:function(a,n,s){return a(n,s)},LPOpb:function(a,n){return a&n},lpMCl:t(658)+t(937)+" field: key",PsSFC:function(a,n){return a===n},HYcbD:t(658)+t(937)+t(1808)+"value",dMHmh:function(a){return a()},HEHoj:function(a,n,s){return a(n,s)},dfpJJ:function(a,n){return a(n)},aTPcI:t(1617)+"too large",YKPBP:function(a,n,s,l){return a(n,s,l)},GcQNp:function(a,n){return a+n},UVqtZ:function(a,n){return a==n},ZYYKB:"wss://",hebah:"close",JQzEd:function(a,n,s){return a(n,s)},tKGSF:function(a,n){return a!==n},VEsZc:t(1120),gIZca:function(a,n){return a!==n},uhwrq:function(a,n,s){return a(n,s)},iwAzH:function(a,n,s){return a(n,s)},mJTDq:function(a,n){return a!==n},vZOdo:function(a,n,s){return a(n,s)},HUBLk:function(a,n,s){return a(n,s)},lRUFV:function(a,n,s){return a(n,s)},uBuqO:function(a,n){return a(n)},sQktd:t(1860),uAoha:"cfOKV",JIQKM:t(1345),lRnHl:function(a,n,s){return a(n,s)},yBXHO:function(a,n){return a!==n},LlXrE:function(a,n,s){return a(n,s)},KQdoq:function(a,n,s){return a(n,s)},TpSHY:function(a,n,s){return a(n,s)},UJxeZ:function(a,n){return a!==n},EKkQd:function(a,n){return a!==n},TcvRx:function(a,n){return a!==n},cYOgI:t(310),EGbyV:function(a,n){return a!==n},KCjqL:function(a,n){return a!==n},SEIGV:function(a,n,s){return a(n,s)},zeCsf:function(a,n){return a===n},VlCDS:t(1776),DCEVa:t(411),aoXBy:function(a,n){return a(n)},Ngglw:function(a,n){return a>>>n},xgcZo:function(a,n){return a(n)},pCpPN:function(a,n,s){return a(n,s)},lHeZt:function(a,n){return a(n)},GAmNS:function(a,n){return a(n)},VjvRp:function(a,n){return a(n)},ltLtx:t(658)+t(937)+t(1808)+"SeqID",lybIa:function(a,n){return a===n},foNrD:t(658)+t(937)+t(1808)+"LogID",caKso:t(658)+t(937)+t(1808)+t(1090),ygtVu:function(a,n){return a===n},fHolR:function(a,n,s){return a(n,s)},OHjBM:function(a,n,s){return a(n,s)},MchgY:function(a,n){return a!==n},veRcL:t(992),GZzpG:function(a,n){return a(n)},fEoAd:function(a,n){return a(n)},daGKD:function(a,n){return a+n},GYVbW:"Unimplem"+t(804)+t(1491),bccso:function(a,n){return a>>n},abLZo:function(a,n){return a>=n},MdlHB:function(a,n){return a===n},XqxVG:t(1396),DZEwt:"OlZSP",eaqkF:function(a,n){return a+n},iQXta:"ajiYP",rmYeG:"TeNCz",ZxPSK:function(a,n){return a+n},GKmdK:function(a,n){return a===n},eazuO:t(700),tNnCE:function(a,n){return a+n},UuKSU:function(a,n){return a>n},LOvVh:t(1054)+"t limit",ymnVM:function(a,n,s){return a(n,s)},iMYDD:function(a,n){return a+n},KmpYM:function(a,n){return a>n},zyXht:function(a,n){return a===n},pgieL:t(299),VcgaX:function(a,n){return a(n)},iFLvI:function(a,n){return a|n},XfIIu:function(a,n){return a<<n},gJfgq:function(a,n){return a&n},BIask:function(a,n){return a<n},fgSil:function(a,n){return a(n)},qwjHR:function(a,n){return a==n},xsnUw:function(a,n){return a+n},AAewL:function(a,n){return a+n},inlTy:function(a,n){return a&n},rCpSF:function(a,n){return a<<n},sjRUI:function(a,n){return a<<n},bYDlN:function(a,n){return a&n},GEDId:function(a,n){return a(n)},dsBnU:function(a,n){return a>=n},WAMDg:function(a,n){return a+n},viAOl:function(a,n){return a<<n},qiDsb:function(a,n){return a&n},mkQvL:function(a,n){return a&n},LSbxv:function(a,n){return a>n},KJgwO:function(a,n,s){return a(n,s)},jCRdw:function(a,n){return a+n},YWDBJ:function(a,n){return a>>n},GmLsR:function(a,n){return a&n},vnzrX:function(a,n){return a===n},BkkLZ:t(543),pfBHv:function(a,n){return a!==n},KLdOL:t(1666),BefoT:function(a,n){return a<n},SIwoe:function(a,n){return a+n},tGxlk:function(a,n){return a<<n},KoTTD:function(a,n){return a<n},qxlBt:function(a,n){return a<=n},XGuTc:function(a,n){return a<n},XKfzq:function(a,n){return a<n},TCluz:function(a,n){return a|n},vKhgW:function(a,n){return a|n},Xkbhz:function(a,n){return a>>n},kFoPz:function(a,n){return a|n},qOToq:function(a,n){return a>>n},ANoQg:function(a,n){return a|n},QXVBy:t(945),YJZzx:function(a,n){return a+n},ZSukK:function(a,n){return a!==n},gnXUn:t(1599),TtlSs:t(1247),DGlOL:function(a,n){return a<n},mhSwX:function(a,n,s){return a(n,s)},hChXj:function(a,n,s){return a(n,s)},iouhJ:"CZxwT",qJOiQ:function(a,n){return a<<n},msLMa:function(a,n){return a&n},LvIrq:function(a,n){return a<<n},GUSjZ:function(a,n){return a&n},yywEN:function(a,n){return a&n},OpCvD:function(a,n){return a&n},qqqtr:function(a,n){return a<<n},wXHrV:function(a,n){return a&n},OKyAz:function(a,n){return a(n)},jcgpf:function(a,n){return a<<n},HVPzN:function(a,n){return a&n},bJSLO:function(a,n){return a<<n},WEwjx:function(a,n){return a&n},jnEsq:function(a,n){return a|n},YjkWE:function(a,n){return a<<n},yEjgP:function(a,n){return a|n},ljQLl:function(a,n){return a>>>n},PFvQK:function(a,n){return a<<n},epqCF:function(a,n){return a>>>n},bugRe:function(a,n){return a===n},Zlpmy:function(a,n){return a===n},wrjcH:function(a,n){return a<n},ppeLH:function(a,n){return a<n},UusOY:function(a,n){return a<n},fNJou:function(a,n){return a!==n},YVkUG:function(a,n){return a&n},AXxpB:function(a,n){return a|n},rbdMv:function(a,n){return a+n},CzAvN:function(a,n){return a|n},mIKBt:function(a,n){return a&n},kedsk:function(a,n){return a>>>n},qwHSw:function(a,n){return a!==n},ELtRd:function(a,n){return a|n},VRIAX:function(a,n){return a+n},HjhID:function(a,n){return a!==n},Sqrts:function(a,n){return a|n},tCxcU:function(a,n){return a>>>n},WkkkG:function(a,n){return a!==n},aguVR:function(a,n){return a|n},WJUqL:function(a,n){return a>>>n},kvMyZ:function(a,n){return a&n},QlAaR:function(a,n){return a>>>n},KxynL:function(a,n){return a!==n},CAuGu:function(a,n){return a(n)},sisBA:function(a,n){return a<<n},OyLFX:function(a,n){return a<<n},wNQnf:"eLsTZ",PRvZs:function(a,n){return a!==n},ILSYw:t(582),DVnsw:function(a,n){return a|n},JYGlW:function(a,n){return a|n},bGnoB:function(a,n){return a<<n},TVftw:function(a,n){return a|n},NQkAI:function(a,n){return a>=n},FpEHm:function(a,n){return a+n},pqcwX:function(a,n){return a<<n},bUOEL:function(a,n){return a<n},OjeDp:t(565),ZlvFz:function(a,n){return a<<n},bnZxB:function(a,n){return a<<n},GXKwm:function(a,n){return a|n},HLGsp:function(a,n){return a|n},bowDs:function(a,n){return a<<n},iUbPp:function(a,n){return a<<n},UdRFv:function(a,n){return a===n},QGupX:function(a,n){return a<<n},bCwCL:function(a,n){return a<<n},FatkG:function(a,n){return a|n},fbQaU:function(a,n){return a|n},mtwRV:function(a,n){return a|n},DZPib:function(a,n){return a<<n},vfpAp:function(a,n){return a<<n},odUyf:t(626),tbngz:function(a,n){return a&n},JSmGg:function(a,n){return a&n},keLyQ:function(a,n){return a>>>n},syWDC:function(a,n){return a&n},NSrMQ:function(a,n){return a===n},yxUmm:function(a,n){return a!==n},qgykT:t(1568),uBiqE:function(a,n){return a>=n},lKhTP:function(a,n){return a>=n},WYkAW:function(a,n){return a+n},StOPG:function(a,n){return a%n},mdIwu:function(a,n){return a+n},Rlmqh:function(a,n){return a>>>n},fPXGM:function(a,n){return a>>>n},miZaD:function(a,n){return a+n},RQagB:function(a,n){return a>>>n},vKQFZ:function(a,n){return a===n},CEwFG:function(a,n){return a&n},kGbeK:function(a,n){return a>>>n},HXTOW:function(a,n){return a&n},xydJD:function(a,n){return a>>>n},jcLZt:function(a,n){return a&n},TTtrO:function(a,n){return a+n},xMfRR:function(a,n){return a+n},SnRKd:function(a,n){return a+n},RFEsc:function(a,n){return a+n},SXUeW:function(a,n){return a|n},YfGJz:function(a,n){return a>>>n},KHNNj:function(a,n){return a===n},gqcof:function(a,n){return a===n},DXCaV:function(a,n){return a&n},PBIUS:function(a,n){return a&n},Slpqv:function(a,n){return a&n},qDUeH:function(a,n){return a>>>n},RqbvC:function(a,n){return a+n},eiaXW:function(a,n){return a+n},MUQmU:function(a,n){return a<<n},pwAEZ:function(a,n){return a&n},DXwjG:function(a,n){return a<=n},XUCgF:function(a,n){return a(n)},gnoPl:t(319),yAHQn:function(a,n){return a&n},dhedT:function(a,n){return a>>>n},GBcTE:"NATIVE_E"+t(1067),QnwDx:t(939)+t(1141),DRakH:t(1225)+"OR",qSgJO:t(508)+"ERROR",DENBN:"MAX_RETR"+t(1229)+"R",qDJAr:function(a,n,s){return a(n,s)},fERWV:"error",daFmd:function(a,n){return a!==n},QvauZ:"QtNuu",IHjgM:t(1191),ahqwj:t(1684)+"2",nMLCC:t(1814),XxbEa:"PKmRZ",YoksI:function(a,n){return a===n},llrFA:function(a,n){return a===n},yZosi:function(a,n){return a===n},yApbv:"UgNIE",LkuMm:"ezsiO",jUfNk:t(1159),edGiR:function(a,n){return a+n},lPbhk:function(a,n){return a>>>n},sxdXn:function(a,n){return a>>>n},wuHgY:t(1661),zBoKy:function(a,n){return a(n)},Rcfux:t(991),ivEkD:function(a,n){return a(n)},ohbUT:t(433),veaaO:t(1872),UdzMk:function(a,n){return a instanceof n},gsNHc:function(a,n){return a+n},dLLTW:function(a,n){return a+n},ycBoV:function(a,n){return a===n},hRqXS:function(a,n){return a<n},gAIKU:function(a,n){return a===n},pPOrB:t(1455),QKEEF:t(1385),AEBPt:t(1576),ktjfW:function(a,n,s){return a(n,s)},EChiR:t(405),iwhoa:function(a,n){return a!==n},wkWOo:t(1540),GLMOJ:function(a,n){return a+n},ElGcs:function(a,n,s){return a(n,s)},GNxtV:function(a,n){return a!==n},ErVMM:t(1716),pOyUY:t(1270),oONPe:function(a,n){return a!==n},WiIRm:function(a,n){return a===n},Quvvc:t(1481),WoHjA:"SlRFu",yBrYy:t(1250),poPsH:"jZqCk",xjCIz:function(a,n){return a!=n},ncLNy:t(1429)+"d",pIypS:function(a,n){return a(n)},NjeZR:"success",kSUoz:t(903),VwmBn:t(1561)+"0",SpOxS:function(a,n){return a||n},dPFPT:t(925)+"alled mu"+t(1591)+t(624)+t(1178),uvAkc:function(a,n){return a===n},tEpuo:t(1816),mrXNK:t(951),WrfOM:function(a,n){return a<n},TAQut:function(a,n){return a<n},bKrni:function(a,n){return a===n},tWnLY:function(a,n){return a&n},luyUk:function(a,n){return a-n},ifczr:function(a,n){return a<<n},vlxPw:function(a,n){return a&n},dYVZH:function(a,n){return a|n},ovcIj:function(a,n){return a&n},NvbLS:function(a,n){return a&n},NgZye:function(a,n){return a>=n},spwAE:function(a,n){return a-n},ZGuUX:function(a,n){return a|n},rlQjl:function(a,n){return a|n},amQom:function(a,n){return a<<n},KrTtx:function(a,n){return a&n},tUwAk:function(a,n){return a<<n},FXFrq:function(a,n){return a&n},HtLAK:function(a,n){return a+n},yrDPA:function(a,n){return a<n},laNNX:function(a,n){return a|n},RGKzh:function(a,n){return a===n},cRrON:function(a,n){return a+n},NCnMR:"2|3|1|5|4|0",qRXvW:function(a,n){return a&n},SACZy:function(a,n){return a&n},srSii:function(a,n){return a|n},dtsMc:function(a,n){return a<n},UrStk:function(a,n){return a&n},iOiwF:t(882),ZxiWx:t(1878),hxUxY:t(550),gtRoI:function(a,n){return a instanceof n},bbdkR:function(a,n){return a!=n},JXlIB:function(a,n){return a instanceof n},loEcV:function(a,n){return a!=n},imNxx:t(1454),xfZAN:"text/pla"+t(1137)+"et=utf-8",orgKM:"ppe",umGHx:t(603),rFDGc:"LeHnj",YofWW:function(a,n,s){return a(n,s)},lbgmG:function(a,n){return a(n)},qXBKi:t(1234),vWGUz:t(829),mmjRf:t(1244),UIuEd:t(1081)+t(1176),UcomD:function(a,n){return a===n},CSMjm:t(977),Hzwxn:t(1339),keyJG:function(a,n){return a===n},lxHWg:t(453),YLXFw:"nMdJn",WNJcb:function(a,n,s){return a(n,s)},UDCaW:function(a,n,s){return a(n,s)},IUFXh:t(1136),maTLz:function(a,n){return a(n)},xyZnj:function(a,n){return a&n},AXhGe:function(a,n){return a&n},pEWuV:function(a,n){return a&n},yjZwd:function(a,n){return a===n},jZbkN:function(a,n){return a||n},wfOkl:function(a,n){return a||n},DGpbe:function(a,n){return a||n},wuQDc:t(330),xmYue:"mGFVe",UsiJU:function(a,n,s,l){return a(n,s,l)},QcHaD:t(302),jCRWl:t(1334),PaBmJ:t(1818),ZryMW:function(a,n){return a||n},sSlSc:function(a,n,s){return a(n,s)},iNpRb:function(a){return a()},ATKRp:function(a,n,s){return a(n,s)},haNcw:"PVTPv",SUtjS:t(556),ismly:function(a,n){return a||n},oJkYo:function(a,n){return a||n},yuBmj:t(733)+"id",aMaLH:function(a,n){return a(n)},EzELo:function(a,n){return a===n},vvSll:t(1207),WXTlL:function(a,n){return a!==n},zzVNu:"RRDXp",kXEYj:t(785),imuCO:t(298)+t(1297),psntX:t(298)+t(1838)+"ck",cSwUs:"x_fronti"+t(617)+"k",mvarc:function(a,n,s){return a(n,s)},MOOyl:t(298)+t(1636)+t(1103),yeqjc:t(1530),PJfgR:function(a,n,s,l){return a(n,s,l)},Xwqdh:function(a,n){return a!==n},SrSPE:t(988),ycstZ:"fPXLn",cGlQS:t(1746),nqILX:t(756),SlThB:t(1261),mksGn:function(a,n){return a(n)},kVkpO:"KyOtW",PJSPW:"YRElm",JsahN:function(a,n){return a instanceof n},uzxWb:function(a,n){return a instanceof n},Mtsaw:t(1059)+t(1511),FsMAX:t(1059)+t(1511)+t(1824)+t(645),QAkQw:t(1086)+"e",MnsMM:function(a){return a()},NcqLV:function(a,n){return a>n},KFCfo:function(a,n){return a+n},WWrsS:function(a,n){return a(n)},mJAJG:t(659),jyBwS:function(a,n){return a+n},WRkus:"index out of ran"+t(980),fdtlz:t(1188),KSagX:" > ",FDWqv:function(a,n){return a>n},GiUpr:function(a,n){return a+n},JBqVx:function(a,n){return a>>>n},Buqpt:function(a,n){return a+n},IZQWd:function(a,n){return a+n},FeMkJ:function(a,n){return a|n},VUvNi:function(a,n){return a+n},trHrU:function(a,n){return a+n},NhIWV:function(a,n){return a+n},dhbIl:function(a,n){return a+n},pwugQ:function(a,n){return a instanceof n},pSUTN:function(a,n){return a(n)},PWoma:function(a,n){return a===n},XBcKu:t(1259),kVpMG:t(519),yahUm:function(a,n){return a&n},HoDbP:function(a,n){return a&n},ViXmz:function(a,n){return a+n},WdpRL:function(a,n){return a>>>n},ZbHUE:function(a,n){return a&n},IiyKt:function(a,n){return a+n},SHRwq:function(a,n){return a&n},vzzzT:function(a,n){return a+n},kAUrU:"YBkvs",zXlCw:function(a,n){return a>>>n},KfHwX:function(a,n){return a<<n},JBebq:function(a,n){return a&n},sUcff:function(a,n){return a|n},KxUBm:function(a,n){return a<<n},Bkzov:function(a,n){return a|n},UwrDZ:function(a,n){return a<<n},zhvyC:function(a,n){return a>>>n},xPqdY:function(a,n){return a|n},ryqrw:function(a,n){return a>n},lchLM:function(a,n){return a!==n},UjVSv:"YWigc",EoRck:function(a,n){return a|n},zmQIM:"SpXnG",mfnOT:function(a,n){return a<n},HmAkn:function(a,n){return a(n)},fufzc:t(1090),UCYFv:t(1529)+t(724),scVWW:"curvalue",XhnRc:t(339),BQyxg:"name",BsSun:function(a,n){return a(n)},kolVE:t(1321)+t(1652),kMaDB:function(a,n,s,l){return a(n,s,l)},ugZFm:t(629)+t(940),hMBDv:function(a,n,s){return a(n,s)},vwcSG:t(944)+t(546),AHBGq:t(1148),LcVsz:function(a,n,s,l){return a(n,s,l)},Aujnw:t(662),SmhDK:t(1119)+"r",GveQr:t(1388),xZVhA:t(1073),ucZme:function(a,n){return a===n},ZsOrn:function(a,n){return a===n},kRGBS:t(990)+t(894),CdbLv:function(a,n){return a===n},hhSUH:t(602),bzWqV:t(1195),VYikX:function(a,n,s,l){return a(n,s,l)},fJgFr:t(1534),uqyip:t(298)+t(391),NOXiW:t(298)+"er_ttl",QMQRx:t(1759)+"s",ykuwY:t(745)+"rsor_name",bpBPv:t(745)+"rsor_value",MMKGI:function(a){return a()},aszlv:function(a,n){return a>n},xjYWu:function(a,n){return a!==n},MMCoj:t(489),bxhrj:function(a,n){return a<n},cpIWy:t(1162),GVfzh:t(1135),dSAjx:t(1231),fFfGs:function(a,n,s){return a(n,s)},MfHVD:function(a,n){return a&&n},LqrDk:function(a){return a()},ogYDv:t(618),niZsc:function(a,n){return a&n},xyaBF:function(a,n){return a&n},OmvtE:function(a,n){return a|n},GWdNH:function(a,n){return a|n},ZIiKE:function(a,n){return a&n},yUxgr:function(a,n){return a|n},vIhHn:function(a,n){return a&n},GyQni:function(a,n){return a|n},vAhHZ:function(a,n){return a>>n},TfsWE:function(a,n){return a|n},RMTVo:function(a,n){return a&n},wnYHv:function(a,n){return a>>n},wFJhw:function(a,n){return a&n},ZvtHJ:"xMdkz",iFDRY:function(a,n){return a(n)},SYsWR:function(a,n){return a(n)},nRTcC:function(a,n){return a<n},VItXx:function(a,n){return a!==n},tdMHZ:"GWJQI",KlUPx:function(a,n){return a===n},Ntqpq:function(a){return a()},qWbSn:function(a){return a()},fjUPf:function(a,n,s){return a(n,s)},YHWDA:function(a,n,s){return a(n,s)},aBNTR:function(a,n){return a!==n},DBCJC:function(a,n){return a!==n},kxqyY:t(1101),aaIvr:t(1220),XpVDP:function(a,n,s,l){return a(n,s,l)},WfsTb:t(952),gsTiE:"iEjAi",PObTs:t(420),xdYED:function(a,n){return a===n},cgUOL:t(1068),GsoUp:t(1282)+t(606)+"s",QQaln:function(a,n,s){return a(n,s)},iVdMS:function(a,n){return a===n},EkTYg:t(751),HvPxw:function(a,n,s){return a(n,s)},ooOre:t(761),GmDpD:"SeVpV",QQdHF:"fYhBw",Gjnwr:function(a,n,s){return a(n,s)},gchKJ:function(a,n){return a!==n},MoFkL:t(1061),icLLa:function(a,n){return a!==n},ZKckf:t(680),gjYWO:function(a,n){return a(n)},nQqcu:function(a,n){return a(n)},CgrvA:t(1282)+t(949)+"t",klefp:function(a,n){return a||n},sWtQJ:"init QoS"+t(393)+"d",nIlNE:"arraybuf"+t(1317),djgEx:"pbbp2",Xiczg:function(a,n){return a/n},ezMDZ:function(a,n){return a==n},bNgTb:function(a,n){return a===n},qEVjD:function(a,n){return a(n)},inxlw:"please p"+t(1854)+t(422)+", WebSocket cons"+t(1726)+t(1609)+t(517),WlBMR:function(a,n,s){return a(n,s)},UYaLG:t(1876)+"t",VBnHD:"stop imm"+t(1190)+t(1167)+"ct",SUijY:t(512),xDnhL:t(1582),inDZC:function(a,n){return a!==n},JoesT:t(382),VAQGT:t(1690),mqkkY:t(1113),ADCTm:t(1470),uHutP:t(510),DBpXy:function(a,n){return a!==n},lySPm:"https:",TAMwc:t(1761),BaDCf:t(1603),DxCcE:function(a){return a()},Ckdkb:t(601),NMvWw:"fws_1.0.0",rthKI:function(a,n,s){return a(n,s)},jyZWK:t(843),fQczt:function(a,n){return a<<n},ylsAL:function(a,n){return a<n},YAjRU:function(a,n){return a<n},EusVq:function(a,n){return a<n},InPqk:function(a,n,s){return a(n,s)},clBjf:function(a,n){return a+n},EaQqk:function(a,n){return a+n},fJCfe:function(a,n){return a!==n},rUmYZ:function(a,n){return a|n},trkjh:function(a,n){return a+n},weFtJ:function(a,n){return a|n},AExqB:function(a,n){return a&n},egeRv:function(a,n){return a>>>n},YBfYk:function(a,n){return a|n},QFHrz:function(a,n){return a>>>n},vPkNm:function(a,n){return a>>>n},OMXpP:function(a,n){return a+n},luqjT:function(a,n){return a!==n},jDwBq:function(a,n){return a>>>n},hFHPi:function(a,n){return a+n},ASUGj:function(a,n){return a!==n},oRZRt:function(a,n){return a>>>n},bUwMB:function(a,n){return a|n},QHRAi:function(a,n){return a>>>n},adCyP:function(a,n){return a+n},idiMs:function(a,n){return a>>>n},kPDzl:"uSZAU",MCtUc:function(a,n){return a(n)},cESGp:function(a,n){return a*n},sICsK:function(a,n){return a*n},XBRTh:t(648),SjTLS:function(a,n){return a(n)},PDwnF:function(a,n){return a-n},cPbRo:t(616),hhtTY:function(a,n){return a===n},gWlsR:t(1612),XTLPW:t(1094),qWeIL:t(1686)+t(770)+t(1876)+t(726)+t(1762),zjmgL:function(a,n,s){return a(n,s)},ZYpyr:function(a,n,s,l){return a(n,s,l)},iEcza:t(1833),RALkN:t(366)+t(567)+"onnecting",XqmOh:"message",xsSzi:function(a,n){return a!=n},MGDga:t(333),lcatw:t(1686)+"ay, network offl"+t(1771),SaveI:"ack",HdCys:"axfxL",DAryG:t(1019),gsIYS:t(1439),sDbVY:"lIlKo",sywlI:function(a,n){return a===n},tSjEz:"close, w"+t(1100)+t(1606),FeLxB:t(1249)+"s instan"+t(336)+t(438)+"ed",WWDCr:function(a,n){return a==n},sXSsY:function(a,n){return a==n},kgNSe:t(1687),HeBec:function(a,n){return a instanceof n},LfmaP:function(a,n){return a(n)},IAOjc:function(a,n){return a||n},uOntp:function(a,n){return a instanceof n},BzCyM:function(a,n){return a(n)},rmjxw:function(a,n){return a===n},zchrS:function(a,n){return a<n},WStYC:t(698),pZmnh:function(a,n){return a===n},WoFax:t(1444),TZNMl:function(a,n){return a!==n},hBiqz:"manual r"+t(1358)+t(722),taYCd:t(596),fGKiP:t(1049),LGckg:t(898),dCYht:function(a,n){return a<<n},NfvGq:function(a,n){return a+n},hqXuW:function(a,n){return a<<n},oPOIe:t(593),uiWHR:t(484),seoNt:t(630),Dxakf:t(518),KnreN:"rtNKT",ugUFK:t(930),IstSi:t(419),OXITH:t(654),vWhVE:function(a,n){return a!=n},RLbNM:function(a,n){return a===n},WOWVT:t(987),EQJCg:function(a,n){return a!=n},vbQpC:t(1613),mUHAN:function(a,n){return a===n},TMrsy:"Dedicate"+t(619)+"lobalScope",wNbtL:function(a,n){return a!=n},Kzexk:function(a,n){return a!=n},hcnUD:function(a,n){return a===n},xXNoD:t(1664)+"rkerGlob"+t(1421),hWoUc:function(a,n){return a!=n},ddYhs:t(1198)+t(1064)};zt.r(Pe),zt.d(Pe,{FWS:()=>zm,CustomErrorEvent:()=>ul,createCloseEvent:()=>_t,ReconnectEvent:()=>ll,createErrorEvent:()=>lt,decodedFrame:()=>on,createOpenEvent:()=>gl,CustomCloseEvent:()=>fl,createReconnectEvent:()=>Ea,FrontierMessageEvent:()=>hl,encodeFrame:()=>Gt,createMessageEvent:()=>ml,OpenEvent:()=>pl,ErrorCode:()=>cn,Event:()=>ir,MessageEvent:()=>xl});let r="";function i(a=""){let n=t,s="02",l=""+Date[n(1449)](),x=r||(r=e[n(1650)](f,a)),m=Math[n(1022)]()[n(660)](16)[n(998)](-6);return e[n(1471)](e[n(1471)](s,l),x)+m}function o(){let a=t;return e[a(327)]!==e[a(327)]?_0x3dc51a[a(1877)]():e[a(1484)](1e4*Date[a(1449)](),Math[a(494)](e[a(1846)](1e4,Math[a(1022)]())))}function c(a){let n=t;return e.fKJJk(e[n(1650)](Array,8)[n(1169)]("0"),e[n(1844)](parseInt,a,10)[n(660)](2))[n(998)](-8)}function d(a){let n=t;return e[n(1471)](e[n(1316)](Array,4)[n(1169)]("0"),parseInt(a,2)[n(660)](16))[n(998)](-4)}function u(a){let n=t,s=a[n(1598)](/\./)[n(1799)](m=>c(m)),l=[];return l[0]=e[n(1651)](d,s[0]+s[1]),l[1]=d(e[n(1471)](s[2],s[3])),[n(1047),e.NsCNE,e[n(372)],e[n(372)],e.NsCNE,e.Acptf,l[0],l[1]][n(1169)]("")}function f(a){let n=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(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]))/[n(896)](a);return s?e[n(326)](u,a):l?e.xDQqm(h,a):e[n(929)]}function h(a){let n=t,s="",l=[],x=0,m=0,w=!0,S="0000";if(a[n(1705)]("::")>-1){let p=a[n(1598)]("::");for(let L=0;e[n(1035)](L,p[n(1390)]);L++)if(e[n(321)]===e[n(321)]){let F=p[L];if(e[n(635)](F[n(1705)](":"),0)){let W=F[n(1598)](":");w&&(x=W[n(1390)]),m+=W.length;for(let K=0;e.kqfZQ(K,W.length);K++)if(e.xOSMn(4,W[K][n(1390)])){let _e=S.substring(0,4-W[K][n(1390)]),Fe=_e[n(504)](W[K]);l[n(1489)](Fe)}else l.push(W[K]);w=!1}else if(e.xOSMn(e[n(1260)],e.VyRnX)){if(e[n(359)](4,F[n(1390)])){let W=S[n(1079)+"g"](0,e[n(1313)](4,F[n(1390)])),K=W.concat(F);l[n(1489)](K)}else l[n(1489)](F);w&&(x+=1),m+=1,w=!1}else{let W=e.ILFyj(_0x12676e,_0x4c6ba0,_0x4ce866[n(1875)]),K=_0xdd9325[n(1740)],_e=_0x351ae0[n(1740)];for(let Fe=0,yt=_0x5cd8cf[n(1875)];e[n(1713)](Fe,yt);Fe++)K[e[n(917)](Fe,W)]=_e[Fe]}}else this._options[n(1882)]&&_0x5687c9.log[n(800)](_0x3e6fd8,[e[n(1810)],..._0x479096]);let O="";for(let L=0;L<e[n(1313)](8,m);L++)O=O[n(504)](S);for(let L=0;L<l.length;L++)e[n(975)](L,x)&&(s=s[n(504)](O)),s=s[n(504)](l[L]);return s}{let p=a[n(1598)](":");for(let O=0;e[n(1035)](O,p[n(1390)]);O++){let L=p[O];if(e[n(359)](4,p[O][n(1390)])){let F=S[n(1079)+"g"](0,e[n(558)](4,p[O][n(1390)])),W=F[n(504)](L);s=s.concat(W)}else s=s[n(504)](L)}return s}}function g(a,n){let s=t;if(e.iiGoI(e[s(1871)],e[s(905)])){let l=a[s(999)];e[s(628)](void 0,l)&&(e[s(1844)](pe,n,10),e[s(1844)](z,n,l));let x=a[s(1302)];x!==void 0&&(pe(n,18),z(n,x))}else{if(_0x2a130b(_0x2a1044))return _0x407305?_0xef4fbe:_0x1cf5ca;if(_0x5c1741){if(e[s(714)](_0x59bfab,_0xad6f61))return _0x45327d}else{if(e.IAgnv(_0x5f07da,-_0x1a621b))return _0x538db5;if(e[s(1471)](_0x48f428,1)>=_0x120688)return _0x55538c}return _0x2afd84[s(1076)](e[s(1185)](_0x1977f0%_0x160d81,0),e[s(1185)](e.OjGIa(_0x58eb38,_0x136a4b),0),_0x1a3c2b)}}function _(a){let n=t,s={};e:for(;!e[n(326)](V,a);){let l=he(a);switch(e[n(1592)](l,3)){case 0:break e;case 1:s[n(999)]=e[n(1204)](C,a,e[n(1741)](he,a));break;case 2:s[n(1302)]=e[n(1691)](C,a,e[n(389)](he,a));break;default:e[n(406)](T,a,e[n(350)](7,l))}}if(s[n(999)]===void 0)throw new Error(e[n(1495)]);if(e[n(1140)](void 0,s[n(1302)]))throw new Error(e[n(1512)]);return s}function v(a){let n=t,s=e.dMHmh(R);return e[n(452)](y,a,s),e[n(1268)](M,s)}function y(a,n){let s=t,l={WvDhi:e.hebah,SQFlC:function(x,m,w){return e[j(1203)](x,m,w)},fahvE:function(x,m,w){return e.ILFyj(x,m,w)}};if(e.tKGSF(s(915),s(915))){if(e[s(635)](_0x40d1d1,_0x39929a))throw new _0x33bf03(e[s(1692)]);let x=3;for(;x>=0;){let m=e[s(350)](255,_0x19395d);e.YKPBP(_0x32edb4,m,_0x17a524,e.fKJJk(_0x5c5f06,x)),_0x99a491>>>=8,x--}return e.GcQNp(_0xb4af8d,4)}else{let x=a[s(483)];if(e[s(359)](void 0,x))if(e[s(1573)]===e[s(1573)])e[s(452)](pe,n,8),e.JQzEd(wt,n,x);else{if(_0x418017[s(1390)]!==4){let yt=_0x538442[s(1079)+"g"](0,e.iAMaK(4,_0x4a46ed[s(1390)])),Ht=yt.concat(_0x48fede);_0x1a1c2d[s(1489)](Ht)}else _0x28b6d6[s(1489)](_0x2b0600);_0x52ada1&&(_0x298ac1+=1),_0x1ccca0+=1,_0x121a8e=!1}let m=a.LogID;e[s(390)](void 0,m)&&(e[s(1640)](pe,n,16),e[s(1691)](wt,n,m));let w=a[s(1090)];e[s(390)](void 0,w)&&(e.JQzEd(pe,n,24),e[s(707)](wt,n,D(w)));let S=a[s(1825)];e[s(1433)](void 0,S)&&(e[s(345)](pe,n,32),wt(n,e[s(1316)](D,S)));let p=a[s(685)];if(p!==void 0)for(let yt of p){e.tWPoP(pe,n,42);let Ht=e[s(1102)](R);e[s(345)](g,yt,Ht),e.HUBLk(pe,n,Ht[s(1875)]),e[s(463)](H,n,Ht),e[s(897)](P,Ht)}let O=a.payloadEncoding;e.xOSMn(void 0,O)&&(e[s(1433)](e[s(1531)],e[s(1588)])?(pe(n,50),e[s(707)](z,n,O)):this[s(541)](l[s(588)],l[s(1227)](_0x1d5339,s(1461),{..._0x51c15c})));let L=a[s(294)+s(1596)];e.xOSMn(void 0,L)&&(e[s(1140)](e[s(910)],s(1383))?(l.fahvE(_0xab3680,_0x5202d6,90),l[s(1227)](_0x47e537,_0x179e02,_0x2c6515)):(e[s(1204)](pe,n,58),e[s(1228)](z,n,L)));let F=a[s(1607)];e[s(1050)](void 0,F)&&(e[s(1709)](pe,n,66),e.KQdoq(pe,n,F[s(1390)]),e.TpSHY(oe,n,F));let W=a[s(796)];e[s(1739)](void 0,W)&&(e.JQzEd(pe,n,74),e.vZOdo(z,n,W));let K=a[s(836)+s(568)];e[s(1364)](void 0,K)&&(e[s(824)](e.cYOgI,"UEtWa")?(pe(n,82),z(n,K)):(_0xfc28c2=_0x5ef7db&&e.UVqtZ(s(712),_0x18e750.protocol)?e[s(1524)]:s(1761),_0x3ac978=_0x2cc7d3[s(772)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x342e77=/^wss(.*:\/\/)/.test(_0xdbab50)?_0x5aaa2b:""+_0x229783+_0x3a2f04));let _e=a[s(424)];e[s(676)](void 0,_e)&&(e[s(463)](pe,n,90),z(n,_e));let Fe=a[s(1085)+"e"];e[s(1662)](void 0,Fe)&&(e[s(1108)](pe,n,96),wt(n,e[s(1268)](D,Fe)))}}function E(a){let n=t,s={FTjNT:function(l,x,m){return e[j(377)](l,x,m)}};if(e.zeCsf(e[n(1492)],e[n(1492)]))return I(B(a));eYyhzF[n(1325)](_0x339bcc,_0x8e8d97,50),eYyhzF[n(1325)](_0x97d27,_0x2903d0,_0x338973)}function I(a){let n=t,s={LniUx:function(l,x,m,w){return e.YKPBP(l,x,m,w)}};if(e[n(1050)](e[n(995)],n(623))){let l={};e:for(;!e[n(1206)](V,a);){let x=he(a);switch(e.Ngglw(x,3)){case 0:break e;case 1:l[n(483)]=Tt(a,!0);break;case 2:l[n(1192)]=e.lRUFV(Tt,a,!0);break;case 3:l.service=e.xDQqm(he,a);break;case 4:l[n(1825)]=he(a);break;case 5:{let m=e[n(1650)](A,a);(l.headers||(l[n(685)]=[]))[n(1489)](e[n(1741)](_,a)),a[n(1875)]=m;break}case 6:l[n(956)+"ncoding"]=e[n(345)](C,a,e.xgcZo(he,a));break;case 7:l[n(294)+"ype"]=C(a,e[n(326)](he,a));break;case 8:l[n(1607)]=e[n(392)](se,a,e[n(326)](he,a));break;case 9:l.LogIDNew=C(a,e.lHeZt(he,a));break;case 10:l[n(836)+"ming"]=C(a,e[n(581)](he,a));break;case 11:l[n(424)]=e[n(1691)](C,a,he(a));break;case 12:l[n(1085)+"e"]=e[n(820)](he,a);break;default:T(a,7&x)}}if(e.bqOBS(void 0,l[n(483)]))throw new Error(e[n(1513)]);if(e.lybIa(void 0,l[n(1192)]))throw new Error(e[n(694)]);if(e[n(1140)](void 0,l[n(1090)]))throw new Error(e[n(1224)]);if(e[n(655)](void 0,l.method))throw new Error(n(658)+n(937)+n(1808)+n(1825));return l}else throw _0x44ec4e=_0x7131ef[n(1390)],s[n(634)](_0x49ebbb,_0x58fe92,10,_0x275fa8[n(1390)])}function A(a){let n=t;if(e[n(1286)](n(1632),e[n(1766)])){let s=e[n(978)](he,a),l=a[n(1875)];return a[n(1875)]=e.fcewr(a[n(927)],s),l}else e[n(524)](_0x2f3817,_0x23548e,82),e[n(1384)](_0x2f2b30,_0x4246f5,_0x2563b9)}function T(a,n){let s=t;switch(n){case 0:for(;e[s(350)](128,ee(a)););break;case 2:e[s(524)](J,a,e[s(348)](he,a));break;case 5:e.uhwrq(J,a,4);break;case 1:J(a,8);break;default:throw new Error(e[s(1517)](e[s(1032)],n))}}function D(a){let n=t;return a|=0,{low:a,high:e.bccso(a,31),unsigned:e[n(1305)](a,0)}}let b=[];function R(){let a=t,n=b[a(1480)]();return n?(n.offset=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function P(a){b[t(1489)](a)}function B(a){let n=t;if(e[n(1157)](e.XqxVG,e[n(585)])){let s=this[n(1488)][n(848)+n(919)](this[n(834)]),l=_0x10bd10[n(334)](s||"{}");return l[_0x155e73||_0xfafbe0[this[n(1368)]]]=_0x3e4533,this[n(1488)][n(1104)+n(919)](this[n(834)],_0x1f864f.stringify(l)),_0x229eb7||_0x20513b[this[n(1368)]]}else return{bytes:a,offset:0,limit:a.length}}function M(a){let n=t,s={vtSVE:function(l,x){return l instanceof x},qRFrv:function(l,x){return e[j(1098)](l,x)}};if(e.iQXta===e.rmYeG){let l=_0x51a4c1[n(1390)]&&_0x4e8887[0];if(s[n(1478)](l,_0x194637))throw l;let x=new _0x36c719("Unhandled error."+(l?s[n(1654)](s[n(1654)](" (",l[n(551)]),")"):""));throw x[n(1442)]=l,l}else{let l=a[n(1740)],x=a.limit;return l[n(1390)]===x?l:l[n(690)](0,x)}}function J(a,n){let s=t;if(e[s(451)](a[s(927)],n)>a[s(1875)])throw new Error(s(754)+"t limit");a[s(927)]+=n}function V(a){let n=t;return e.GKmdK(e[n(1506)],e[n(1506)])?e[n(714)](a.offset,a[n(1875)]):null}function re(a,n){let s=t,l=a.bytes,x=a[s(927)],m=a[s(1875)],w=e[s(1165)](x,n);if(e[s(687)](w,l[s(1390)])){let S=new Uint8Array(2*w);S.set(l),a[s(1740)]=S}return a.offset=w,e.UuKSU(w,m)&&(a[s(1875)]=w),x}function X(a,n){let s=t,l=a[s(927)];if(e[s(635)](l+n,a.limit))throw new Error(e[s(918)]);return a[s(927)]+=n,l}function se(a,n){let s=t,l=e[s(1295)](X,a,n);return a[s(1740)][s(690)](l,e.iMYDD(l,n))}function oe(a,n){let s=t,l=re(a,n[s(1390)]);a[s(1740)].set(n,l)}function C(a,n){let s=t;if(e[s(332)](s(299),e[s(1211)])){let l=X(a,n),x=String[s(455)+"Code"],m=a[s(1740)],w="\uFFFD",S="";for(let p=0;e[s(1713)](p,n);p++){let O=m[p+l],L,F,W,K;e[s(350)](128,O)===0?S+=e[s(1210)](x,O):(224&O)===192?e[s(1305)](p+1,n)?S+=w:(L=m[e[s(451)](p,l)+1],e[s(1050)](e[s(350)](192,L),128)?S+=w:(K=e.iFLvI(e.XfIIu(31&O,6),e[s(1745)](63,L)),e[s(766)](K,128)?S+=w:(S+=e[s(503)](x,K),p++))):e.qwjHR(e[s(350)](240,O),224)?e[s(1626)](p,2)>=n?S+=w:(L=m[e[s(316)](e[s(1517)](p,l),1)],F=m[e[s(1471)](e[s(1471)](p,l),2)],e.xOSMn(e[s(1557)](e[s(1185)](L,e.rCpSF(F,8)),49344),32896)?S+=w:(K=e[s(1164)](15&O,12)|e[s(1407)](e[s(1251)](63,L),6)|63&F,e.BIask(K,2048)||e[s(1305)](K,55296)&&e[s(1015)](K,57343)?S+=w:(S+=e[s(1311)](x,K),p+=2))):e[s(1018)](e.bYDlN(248,O),240)?e.dsBnU(p+3,n)?S+=w:(L=m[e[s(917)](p,l)+1],F=m[e.fcewr(e[s(1517)](p,l),2)],W=m[e[s(695)](e[s(317)](p,l),3)],e[s(824)](e[s(350)](e[s(1185)](e[s(1185)](L,F<<8),e[s(1164)](W,16)),12632256),8421504)?S+=w:(K=e[s(1185)]((7&O)<<18,e[s(819)](e.qiDsb(63,L),12))|e[s(1407)](63&F,6)|e[s(771)](63,W),e[s(1713)](K,65536)||e[s(835)](K,1114111)?S+=w:(K-=65536,S+=e[s(583)](x,e.jCRdw(e.YWDBJ(K,10),55296),e[s(917)](e[s(746)](1023,K),56320)),p+=3))):S+=w}return S}else return e[s(539)](this[s(473)+s(1679)],this[s(540)+"s"].length)?!0:e[s(627)](this[s(1420)+s(591)+s(1823)+"t"],this[s(1734)+"es"])}function z(a,n){let s=t,l={izhzH:function(x,m){return e.kqfZQ(x,m)},OzmhZ:function(x,m){return e[j(1057)](x,m)}};if(e[s(839)](e[s(446)],e[s(446)])){let x=n[s(1390)],m=0;for(let p=0;p<x;p++)if(e[s(650)](s(739),e[s(639)])){let O=n[s(1703)+"At"](p);e[s(1305)](O,55296)&&e[s(1015)](O,56319)&&e[s(1254)](e[s(1471)](p,1),x)&&(O=e.SIwoe(e[s(535)](O,10),n[s(1703)+"At"](++p))-56613888),m+=e[s(1088)](O,128)?1:O<2048?2:e[s(1254)](O,65536)?3:4}else{let O=this[s(373)+"rs"][_0x985c69];if(O)for(let L=0;l.izhzH(L,O[s(1390)]);)l[s(1610)](O[L].fn,_0x5dd150)?O[s(1780)](L,1):++L}e.LlXrE(pe,a,m);let w=e.pCpPN(re,a,m),S=a[s(1740)];for(let p=0;p<x;p++){let O=n[s(1703)+"At"](p);O>=55296&&e[s(672)](O,56319)&&e[s(443)](e[s(1098)](p,1),x)&&(O=e[s(558)](e[s(1165)](e[s(819)](O,10),n[s(1703)+"At"](++p)),56613888)),e[s(597)](O,128)?S[w++]=O:(e[s(1035)](O,2048)?S[w++]=e.TCluz(O>>6&31,192):(O<65536?S[w++]=e[s(1760)](O,12)&15|224:(S[w++]=e.vKhgW(e[s(1745)](e[s(1665)](O,18),7),240),S[w++]=e.iFLvI(e[s(1251)](O>>12,63),128)),S[w++]=e.kFoPz(e[s(344)](O,6)&63,128)),S[w++]=e.ANoQg(63&O,128))}}else{let x=_0x40ec01.substring(0,e[s(558)](4,_0x3cd684[s(1390)])),m=x[s(504)](_0x21c921);_0x3f0ee2.push(m)}}function H(a,n){let s=t;if(e.bqOBS(s(1248),s(1039)))switch(_0x994251){case e[s(400)]:case"ppe":return{[s(1694)+_0x405ac1]:1,"x-tt-env":_0x128e9f};default:return{}}else{let l=e[s(1263)](re,a,n[s(1875)]),x=a.bytes,m=n[s(1740)];for(let w=0,S=n[s(1875)];e[s(1035)](w,S);w++)x[e[s(1688)](w,l)]=m[w]}}function ee(a){let n=t;if(e[n(852)](e.gnXUn,e[n(1781)])){let s={oahyq:function(l,x,m){return l(x,m)}};return new _0x3b6234(l=>{let x=n;s[x(661)](_0x598263,l,this[x(962)+x(831)+"e"](_0x2515b1))})}else return a.bytes[X(a,1)]}function Je(a,n){let s=t;if(e[s(1405)](e[s(312)],e[s(312)]))return e.VjvRp(_0xc70d66,e[s(1316)](_0x108243,_0x373ae8));{let l=e.JQzEd(re,a,1);a[s(1740)][l]=n}}function he(a){let n=t,s=0,l=0,x;do x=e[n(820)](ee,a),e[n(826)](s,32)&&(l|=e[n(304)](e[n(1745)](127,x),s)),s+=7;while(128&x);return l}function pe(a,n){let s=t;for(n>>>=0;e[s(714)](n,128);)e[s(1378)](Je,a,e[s(891)](e[s(746)](127,n),128)),n>>>=7;e.hChXj(Je,a,n)}function Tt(a,n){let s=t;if(e[s(650)](s(1469),e[s(609)]))this["flushExp"+s(1411)]();else{let l=0,x=0,m=0,w;return w=ee(a),l=e.gJfgq(127,w),e[s(771)](128,w)&&(w=e.GAmNS(ee,a),l|=e[s(437)](127&w,7),e[s(1614)](128,w)&&(w=e[s(389)](ee,a),l|=e[s(437)](e[s(1557)](127,w),14),e[s(1745)](128,w)&&(w=ee(a),l|=e[s(856)](e.GUSjZ(127,w),21),e[s(1745)](128,w)&&(w=e[s(1206)](ee,a),x=e[s(1723)](127,w),e.yywEN(128,w)&&(w=ee(a),x|=e[s(1164)](127&w,7),e.OpCvD(128,w)&&(w=e.VcgaX(ee,a),x|=e[s(369)](e[s(1129)](127,w),14),128&w&&(w=e[s(1567)](ee,a),x|=e[s(955)](e.mkQvL(127,w),21),e[s(1129)](128,w)&&(w=e[s(978)](ee,a),m=e[s(771)](127,w),e.HVPzN(128,w)&&(w=ee(a),m|=e[s(868)](e[s(1298)](127,w),7)))))))))),{low:e[s(1767)](l,e.YjkWE(x,28)),high:e.yEjgP(e[s(466)](x,4),e[s(1246)](m,24)),unsigned:n}}}function wt(a,n){let s=t,l=e[s(1659)](n[s(981)],0),x=e.epqCF(e.mlpQR(e.ljQLl(n.low,28),e[s(1246)](n.high,4)),0),m=n.high>>>24,w=e.bugRe(0,m)?e[s(886)](0,x)?e[s(1254)](l,16384)?e[s(1403)](l,128)?1:2:e[s(1035)](l,2097152)?3:4:e[s(799)](x,16384)?e[s(1035)](x,128)?5:6:e[s(1254)](x,2097152)?7:8:e[s(1700)](m,128)?9:10,S=re(a,w),p=a[s(1740)];switch(w){case 10:p[e[s(1626)](S,9)]=e[s(771)](m>>>7,1);case 9:p[S+8]=e[s(427)](9,w)?128|m:e.YVkUG(127,m);case 8:p[e[s(695)](S,7)]=e.tKGSF(8,w)?e.Ngglw(x,21)|128:e[s(746)](e[s(1592)](x,21),127);case 7:p[e[s(695)](S,6)]=w!==7?e[s(1277)](x>>>14,128):e.LPOpb(e.jLeEK(x,14),127);case 6:p[e[s(854)](S,5)]=e[s(359)](6,w)?e[s(604)](e.epqCF(x,7),128):e.mIKBt(e[s(1667)](x,7),127);case 5:p[S+4]=e[s(1139)](5,w)?e[s(401)](128,x):127&x;case 4:p[e[s(1738)](S,3)]=e[s(622)](4,w)?e.Sqrts(l>>>21,128):e[s(1404)](e[s(1299)](l,21),127);case 3:p[e[s(695)](S,2)]=w!==3?e[s(1667)](l,14)|128:e[s(1557)](l>>>14,127);case 2:p[S+1]=e[s(469)](2,w)?e[s(481)](e.WJUqL(l,7),128):e.kvMyZ(e[s(297)](l,7),127);case 1:p[S]=e[s(329)](1,w)?128|l:127&l}}function on(a){let n=t;if(e.wNQnf===n(577))return e[n(1124)](E,a);_0x19d544=e[n(514)](_0x2a39df,_0x1e6f59),_0x52bd28|=e.sisBA(e[n(350)](127,_0x2a2400),21),e[n(795)](128,_0x26b1bb)&&(_0x4462d4=_0x2d06df(_0x454be9),_0x39aff1=127&_0x47bd77,e.msLMa(128,_0x254a1c)&&(_0x2499ca=_0x3b8eef(_0x42ae27),_0x584b68|=e[n(1271)](127&_0x5d3c47,7)))}function Gt(a){let n=t;if(e[n(718)]("eQUiv",e[n(1747)]))_0x2be8e5[n(1584)](_0x544ec);else return v(a)}let an=65536,ei=e[t(1515)],we=e[t(1846)](an,an),Te=e[t(1456)](we,we),rr=Te/2,Ne=String[t(870)+"e"].charCodeAt;class xe{constructor(n,s,l){let x=t;this[x(812)]=!0,this[x(981)]=e[x(1318)](0,n),this.high=0|s,this.unsigned=!!l}static[t(812)](n){return n&&e.bugRe(!0,n.isLong)}static[t(1076)](n,s,l){return new xe(n,s,l)}static[t(1541)+"s"](n,s,l){let x=t;return l?xe[x(1541)+x(1275)](n,s):xe["fromByte"+x(1416)](n,s)}static["fromByte"+t(1275)](n,s){let l=t;return new xe(e[l(1292)](e.JYGlW(n[0],e[l(1271)](n[1],8)),e[l(526)](n[2],16))|n[3]<<24,e[l(1326)](e[l(401)](e[l(1413)](n[4],e[l(868)](n[5],8)),e.XfIIu(n[6],16)),e[l(437)](n[7],24)),s)}static[t(1541)+t(1416)](n,s){let l=t,x={BTZYe:function(m,w){return e[j(1288)](m,w)},xwYym:function(m,w){return m<=w},pPHxY:function(m,w){return m<w},ViKHj:function(m,w){return e.FpEHm(m,w)},Zvcbz:function(m,w){return e[j(1566)](m,w)},yeUCe:function(m,w){return e[j(976)](m,w)}};if(l(565)===e[l(1152)])return new xe(e.aguVR(e[l(1277)](e[l(1587)](n[4],24),e[l(1593)](n[5],16))|e[l(955)](n[6],8),n[7]),e.GXKwm(e.HLGsp(e[l(1783)](n[0],24),e.rCpSF(n[1],16))|e[l(844)](n[2],8),n[3]),s);{let m=_0x1c7fd9[l(1703)+"At"](_0x2204ff);KOzmCL.BTZYe(m,55296)&&KOzmCL[l(924)](m,56319)&&KOzmCL[l(447)](KOzmCL[l(1300)](_0x398465,1),_0x283f2b)&&(m=KOzmCL[l(520)](m,10)+_0xfd8b19[l(1703)+"At"](++_0x362ee3)-56613888),_0xa12765+=m<128?1:m<2048?2:KOzmCL[l(1105)](m,65536)?3:4}}static[t(351)](n){let s=t;return e[s(642)](n,ei)?dl:new xe(e[s(1592)](e[s(931)](e[s(384)](Ne.call(n,0),e[s(1e3)](Ne[s(840)](n,1),8)),e[s(1407)](Ne[s(840)](n,2),16))|e[s(783)](Ne[s(840)](n,3),24),0),e[s(1602)](e[s(1348)](e[s(569)](Ne[s(840)](n,4),e.DZPib(Ne[s(840)](n,5),8)),e[s(1154)](Ne[s(840)](n,6),16)),Ne[s(840)](n,7)<<24)>>>0,!0)}[t(1695)](){let n=t;if(e.PRvZs(e[n(625)],"WDPrR")){let s=_0x1060a0[n(1480)]();return s?(s[n(927)]=s[n(1875)]=0,s):{bytes:new _0x5bf874(64),offset:0,limit:0}}else return String[n(455)+n(404)](e[n(1412)](255,this.low),this[n(981)]>>>8&255,e[n(682)](e.keLyQ(this[n(981)],16),255),this[n(981)]>>>24,255&this[n(1714)],e[n(1723)](this[n(1714)]>>>8,255),e.syWDC(this[n(1714)]>>>16,255),this[n(1714)]>>>24)}static fromNumber(n,s=!0){let l=t;if(e[l(1623)](l(547),e[l(749)])){if(isNaN(n))return s?Yp:dl;if(s){if(e[l(1093)](n,Te))return Qp}else{if(e[l(672)](n,-rr))return em;if(e[l(1422)](e[l(833)](n,1),rr))return Xp}return xe[l(1076)](e[l(1399)](n,we)|0,e[l(501)](n/we,0),s)}else return _0x535c44[l(812)](_0x4de7a0)||(_0x3f4a01=_0x2ae489[l(697)+"er"](_0x34f21e)),this[l(522)]!==_0x48a374[l(522)]&&e.vnzrX(e[l(297)](this[l(1714)],31),1)&&e.lybIa(e[l(297)](_0x4e875a[l(1714)],31),1)?!1:e[l(367)](this.high,_0x50b23c[l(1714)])&&this[l(981)]===_0xbe21b6.low}toNumber(){let n=t;return this.unsigned?e[n(413)](e[n(1846)](e.Rlmqh(this[n(1714)],0),we),e.fPXGM(this[n(981)],0)):e[n(1072)](e[n(1846)](this[n(1714)],we),e[n(934)](this.low,0))}[t(492)](){return this[t(1714)]===0&&e.vKQFZ(0,this.low)}[t(1123)](n){let s=t;xe[s(812)](n)||(n=xe[s(697)+"er"](n));let l=e[s(1659)](this[s(1714)],16),x=e[s(485)](65535,this[s(1714)]),m=e.kGbeK(this[s(981)],16),w=e.HXTOW(65535,this[s(981)]),S=e.xydJD(n.high,16),p=e[s(736)](65535,n[s(1714)]),O=e[s(941)](n[s(981)],16),L=e[s(699)](65535,n[s(981)]),F=0,W=0,K=0,_e=0;return _e+=e[s(1579)](w,L),K+=e[s(356)](_e,16),_e&=65535,K+=e[s(586)](m,O),W+=e[s(356)](K,16),K&=65535,W+=e[s(810)](x,p),F+=e[s(356)](W,16),W&=65535,F+=e[s(320)](l,S),F&=65535,xe.fromBits(e[s(394)](K<<16,_e),e[s(1413)](e[s(304)](F,16),W),this[s(522)])}equals(n){let s=t;return xe.isLong(n)||(n=xe[s(697)+"er"](n)),e[s(1623)](this[s(522)],n[s(522)])&&e[s(1314)](e[s(1082)](this[s(1714)],31),1)&&e[s(360)](e[s(1299)](n.high,31),1)?!1:e[s(1057)](this.high,n[s(1714)])&&this[s(981)]===n[s(981)]}addOne(){let n=t;return this[n(981)]===-1&&e.gqcof(-1,this[n(1714)])?xe[n(1076)](0,0,this[n(522)]):e[n(367)](-1,this[n(981)])?xe[n(1076)](0,this.high+1,this[n(522)]):xe.fromBits(e.xMfRR(this[n(981)],1),this.high,this[n(522)])}toBytes(n){let s=t;return n?this[s(1855)+"E"]():this[s(735)+"E"]()}[t(1855)+"E"](){let n=t,s=this[n(1714)],l=this[n(981)];return[e[n(346)](255,l),e.PBIUS(e[n(901)](l,8),255),e[n(1412)](e[n(356)](l,16),255),l>>>24,e[n(521)](255,s),e.Slpqv(e.qDUeH(s,8),255),e.xydJD(s,16)&255,e.Rlmqh(s,24)]}toBytesBE(){let n=t,s={pGesu:function(l,x){return e.RqbvC(l,x)},exkUj:function(l,x){return e[j(451)](l,x)},HHJro:function(l,x){return e[j(313)](l,x)},lUSAx:function(l,x){return e[j(1623)](l,x)},oDIrG:function(l,x){return e[j(467)](l,x)},JBVEO:function(l,x){return e[j(402)](l,x)},nuvPj:function(l,x){return l|x},MNWcD:function(l,x){return e[j(844)](l,x)},NTyJc:function(l,x){return e.bCwCL(l,x)},Jpxeq:function(l,x){return e[j(1440)](l,x)},EJuQX:function(l,x){return e.NQkAI(l,x)},qUTQg:function(l,x){return e[j(532)](l,x)},MasOd:function(l,x){return e[j(1342)](l,x)}};if(e[n(332)](e[n(954)],n(319))){let l=this[n(1714)],x=this[n(981)];return[l>>>24,e[n(1641)](l>>>16,255),e.yAHQn(e[n(563)](l,8),255),255&l,e.WJUqL(x,24),e.syWDC(e[n(1659)](x,16),255),x>>>8&255,255&x]}else _0x1657a6=_0x53a169[nMyvkE.pGesu(nMyvkE.exkUj(_0xa0f5cc,_0x52ca40),1)],_0x2749ad=_0xe540a4[nMyvkE[n(1232)](nMyvkE.HHJro(_0x345149,_0x5f1e35),2)],nMyvkE.lUSAx(nMyvkE[n(1670)](_0x5b4520|nMyvkE[n(920)](_0x3faadb,8),49344),32896)?_0x298e53+=_0x169289:(_0x44ccef=nMyvkE[n(1717)](nMyvkE.MNWcD(15&_0x464d5a,12)|nMyvkE[n(640)](nMyvkE.Jpxeq(63,_0x3a6985),6),nMyvkE.Jpxeq(63,_0x326a98)),_0xd19d37<2048||nMyvkE.EJuQX(_0x21108d,55296)&&nMyvkE[n(1380)](_0x311b87,57343)?_0x468c54+=_0x211a72:(_0x552648+=nMyvkE[n(1551)](_0x3cff92,_0x3dadbc),_0x2d318e+=2))}}let dl=new xe(0,0,!1),Yp=new xe(0,0,!0),Xp=xe[t(1076)](-1,2147483647,!1),Qp=xe[t(1076)](-1,-1,!0),em=xe[t(1076)](0,-2147483648,!1);var cn=(function(a){let n=t,s="0|1|5|4|3|2".split("|"),l=0;for(;;){switch(s[l++]){case"0":a[a[e.GBcTE]=5001]=e[n(986)];continue;case"1":a[a[e[n(1702)]]=5002]=e[n(1702)];continue;case"2":return a;case"3":a[a[n(1225)+"OR"]=5005]=e.DRakH;continue;case"4":a[a[e.qSgJO]=5004]=e.qSgJO;continue;case"5":a[a[e[n(1675)]]=5003]=e[n(1675)];continue}break}})({});class ir{constructor(n){let s=t;this[s(1007)]=n,this[s(1627)]=null}}class ll extends ir{constructor(n,s){super(n),this.message=s&&s.message||null}}class ul extends ir{constructor(n,s){let l=t;if(e[l(1869)](e[l(656)],e.IHjgM))super(n),this[l(1459)]=s&&s[l(1459)]||null,this[l(681)]=s&&s[l(681)]||0,this[l(983)]=s&&s[l(983)]||"",this[l(1445)]=s&&s[l(1445)]||0,this[l(551)]=s&&s[l(551)]||"",this[l(1534)]=s&&s[l(1534)]||5001;else{let x=this[l(816)+l(1051)]?.[l(865)+l(876)+"es"](),m=this[l(816)+l(1051)]?.["getCurre"+l(667)+"nt"]();if(x&&!_0x5338a6[l(551)]){let w="connect "+m+(" fail, m"+l(1490)+"es reached");this[l(1371)+l(376)+"ent"](e[l(1395)](_0x2ae0e5,e.fERWV,{message:w,code:_0x513e55[l(1024)+l(1229)+"R"],error:_0x40eeec}));return}this[l(1839)]&&e[l(1157)](this[l(1839)][l(1241)+"te"],this[l(1158)])&&this[l(972)+l(782)](),this[l(1371)+l(376)+l(1343)](_0x50e70d(l(1459),{message:_0x1af507[l(551)],code:_0x282f3d[l(1669)+"RROR"],error:_0x46d25a}))}}}class fl extends ir{constructor(n,s){let l=t,x=e[l(953)].split("|"),m=0;for(;;){switch(x[m++]){case"0":super(n);continue;case"1":this.wasClean=s&&s.wasClean||!1;continue;case"2":this.willReconnect=s&&s[l(1784)+l(516)]||!1;continue;case"3":this.code=s&&s[l(1534)]||0;continue;case"4":this[l(1176)]=s&&s[l(1176)]||"";continue}break}}}class xl extends ir{constructor(n,s){let l=t;super(n),this[l(1197)]=s&&s[l(1197)]||null}}class hl extends xl{constructor(n,s){let l=t;super(n),this[l(1197)]=s&&s.data||null,this[l(551)]=s&&s[l(551)]||null}}class pl extends ir{constructor(n,s){let l=t;e[l(1286)](e[l(1143)],e[l(822)])?(super(n),this[l(1197)]=s&&s[l(1197)]||null):_0x2895b4[l(1489)](_0x279bab)}}function lt(a,{message:n,code:s,error:l}){return new ul(a,{message:n,code:s,error:l})}function _t(a,{code:n,reason:s,wasClean:l,willReconnect:x}){return new fl(a,{code:n,reason:s,wasClean:l,willReconnect:x})}function ml(a,{data:n,message:s}){return new hl(a,{data:n,message:s})}function gl(a,{data:n}){return new pl(a,{data:n})}function Ea(a,{message:n}){return new ll(a,{message:n})}class wl{constructor(n,s){let l=t;if(e[l(335)](e.yApbv,e[l(1237)]))return e[l(1107)](0,this[l(1714)])&&e.llrFA(0,this[l(981)]);this[l(540)+"s"]=n,this.maxRetries=s,this.currentIndex=0,this[l(1420)+l(591)+"riesCount"]=0}resetEndpointConfig(){let n=t;if(e[n(1153)]!==n(1618))this[n(473)+n(1679)]=0,this["currentEndpointT"+n(1823)+"t"]=0;else return this[n(540)+"s"][this[n(473)+n(1679)]]}[t(1742)+"es"](){let n=t;this["currentE"+n(591)+"riesCount"]=0}[t(1795)+t(667)+"nt"](){let n=t;return this[n(540)+"s"][this[n(473)+n(1679)]]}["getCurre"+t(667)+"ntTriesC"+t(1458)](){let n=t;return this[n(1420)+n(591)+n(1823)+"t"]}[t(865)+t(876)+"es"](){let n=t;return!!(this[n(473)+n(1679)]>=this[n(540)+"s"].length||e.bqOBS(this[n(473)+n(1679)],e[n(558)](this[n(540)+"s"][n(1390)],1))&&e.Zlpmy(this[n(1420)+"ndpointT"+n(1823)+"t"],this.maxRetries))}[t(331)+t(314)+t(1757)+t(904)+t(1245)](){let n=t;return e[n(1405)](e[n(1446)],n(1147))?e[n(1018)](this["currentI"+n(1679)],this[n(540)+"s"].length)?!0:e.KmpYM(this[n(1420)+n(591)+n(1823)+"t"],this[n(1734)+"es"]):this[n(522)]?e[n(971)](e[n(387)](this[n(1714)],0)*_0x23a4fe,this.low>>>0):e[n(1165)](e.taEMI(this[n(1714)],_0x1b96dd),e[n(1711)](this[n(981)],0))}[t(1452)+t(1820)+t(1724)+t(1621)+t(1168)](){let n=t;if(e[n(359)](e[n(1177)],e[n(1177)]))_0x31722d+=e[n(1175)](_0x39b68f,_0x56b2e6),_0x1a1bfb++;else return this[n(1420)+n(591)+n(1823)+"t"]=1,this["currentI"+n(1679)]++,this[n(540)+"s"][this[n(473)+n(1679)]]}[t(1795)+t(667)+t(502)+t(1010)](){let n=t;return this[n(1420)+"ndpointT"+n(1823)+"t"]++,this["getCurre"+n(667)+"nt"]()}}let sr=(e[t(1028)](t(1429)+"d",typeof globalThis)&&e[t(975)]("Window",globalThis[t(416)+"tor"].name)||e.ncLNy!=typeof window&&e[t(1347)](e.WOWVT,window[t(416)+t(845)][t(460)]))&&e[t(613)](e[t(1538)],typeof document),Dn=e[t(1729)]("undefined",typeof globalThis)&&(e[t(906)]===globalThis[t(416)+t(845)][t(460)]||e[t(1026)](e[t(1883)],globalThis[t(416)+t(845)][t(460)]))&&e[t(1729)](t(1429)+"d",typeof tt),ti=(e[t(1028)](e[t(1538)],typeof globalThis)&&e[t(675)](t(1613),globalThis[t(416)+"tor"][t(460)])||e[t(1538)]==typeof globalThis||e[t(454)](t(1429)+"d",typeof globalThis)&&!!globalThis[t(598)+t(1832)])&&e[t(855)](e[t(1538)],typeof wx),ni=e[t(900)](e[t(1538)],typeof globalThis)&&("Dedicate"+t(619)+t(322)+"pe"===globalThis[t(416)+t(845)][t(460)]||e[t(1216)](e[t(1262)],globalThis[t(416)+"tor"][t(460)])||t(1807)+t(1774)+t(383)===globalThis[t(416)+t(845)][t(460)])&&e[t(1538)]!=typeof self,tm=e[t(1538)]!=typeof globalThis&&e[t(906)]===globalThis.constructor.name&&e.hWoUc(e[t(1538)],typeof global)&&e.vbQpC===global[t(416)+t(845)][t(460)]&&e.hWoUc(e[t(1538)],typeof process)&&!!process.version;class va{constructor(){let n=t;if(e[n(1355)]!==e[n(1239)])this[n(373)+"rs"]={};else return e[n(787)](_0x368580,_0x3802e7)}[t(541)](n,...s){let l=t,x=this[l(373)+"rs"][n];if(x)x[l(998)]()[l(973)](m=>m.fn[l(800)](m.ctx,s));else if(e[l(1635)]===n&&!this[l(573)]){let m=s.length&&s[0];if(e[l(1367)](m,Error))throw m;let w=new Error(e[l(451)]("Unhandled error.",m?e[l(974)](e[l(358)](" (",m[l(551)]),")"):""));throw w[l(1442)]=m,m}return this}[t(1166)](n,s){let l=t;if(n===void 0)this[l(373)+"rs"]={};else if(e[l(731)](void 0,s))this[l(373)+"rs"][n]=null;else{let x=this[l(373)+"rs"][n];if(x)for(let m=0;e[l(769)](m,x[l(1390)]);)e[l(1733)](x[m].fn,s)?x[l(1780)](m,1):++m}return this}on(n,s,l){let x=t;return(this._listeners[n]||(this[x(373)+"rs"][n]=[]))[x(1489)]({fn:s,ctx:l||this}),this}}class nm extends va{[t(664)+"rrorMess"+t(429)](n){let s=t;return n[s(587)]||n.errNo?(s(1625)+" "+(n[s(587)]||"")+" code: "+(n[s(1243)]||""))[s(1366)]():JSON[s(1126)+"y"](n)}constructor(n,s,l){let x=t;if(e[x(469)](e[x(1381)],e[x(1381)]))return this._socket.protocol;super(),this[x(1183)]=null,ti&&wx[x(459)+x(1304)]&&(this._socket=wx[x(459)+x(1304)]({url:n,protocols:s,header:l,fail:this[x(1542)+x(1778)+x(684)][x(815)](this),success:this[x(1542)+x(1704)+x(1569)+x(605)].bind(this)})),Dn&&tt[x(459)+"ocket"]&&(this[x(1183)]=tt[x(459)+x(1304)]({url:n,protocols:s,header:l,fail:this[x(1542)+"ocketFailHandler"][x(815)](this),success:this[x(1542)+x(1704)+x(1569)+x(605)].bind(this)}))}[t(1542)+t(1704)+"cessHand"+t(605)](){let n=t;e[n(975)](e.QKEEF,e[n(328)])?Promise[n(1877)]()[n(607)](()=>{let s=n;this[s(1831)+s(1533)]()}):this.on(_0x44c593,_0x4f6bcc)}["_createS"+t(1778)+t(684)](n){let s=t;Promise[s(1877)]()[s(607)](()=>{let l=s,x=e.KQdoq(lt,e[l(1635)],{message:this["_formatErrorMess"+l(429)](n)});this[l(541)](l(1459),x);let m=_t(l(1461),{reason:this[l(664)+l(668)+l(429)](n)});this[l(541)](e[l(1156)],m)})}[t(1831)+t(1533)](){let n=t,s={hCtOR:e[n(1474)],Kwxsv:function(l,x,m){return e[n(1406)](l,x,m)},uyyiC:n(551)};n(405)!==e[n(1438)]?(this["currentI"+n(1679)]=0,this["currentE"+n(591)+n(1823)+"t"]=0):(this._socket[n(537)](l=>{let x=n;this.emit(s.hCtOR,s[x(1727)](gl,s.hCtOR,{...l,data:l.errMsg||""}))}),this[n(1183)][n(979)](l=>{let x=n;this.emit(e[x(1156)],_t("close",{...l}))}),this[n(1183)][n(1011)+"e"](l=>{let x=n;this[x(541)](x(551),ml(s[x(922)],{...l}))}),this[n(1183)].onError(l=>{let x=n;this[x(541)](x(1459),lt(e.fERWV,{...l,message:l[x(587)]||""}))}))}[t(948)](n){let s=t,l={zmJgp:function(x,m,w){return e[j(524)](x,m,w)},AAhZG:e.fERWV};if(e[s(1367)](n,Uint8Array))if(e[s(1349)](e[s(1017)],e[s(1017)])){let x=this._qosDB[s(732)](this._prefix);return _0x5abc0b[s(334)](x||"{}")[_0x4e489f]}else{let x=n[s(1656)][s(998)](n.byteOffset,e[s(1790)](n.byteLength,n[s(1392)+"et"]));this[s(1183)]&&this[s(1183)][s(948)]({data:x,fail:m=>{let w=s;this[w(541)](w(1459),l[w(1803)](lt,l[w(1822)],{message:this["_formatE"+w(668)+"age"](m)}))}})}else this[s(1183)]&&this[s(1183)][s(948)]({data:n,fail:x=>{let m=s;this[m(541)](e[m(1635)],lt(e[m(1635)],{message:this[m(664)+m(668)+m(429)](x)}))}})}[t(1461)](n,s){let l=t;this[l(1183)]&&this[l(1183)][l(1461)]({code:n,reason:s})}[t(765)+t(1865)](n,s){let l=t;e[l(381)](e.ErVMM,l(1716))?this[l(541)](l(1459),e[l(1182)](_0x4880d5,l(1459),{message:this[l(664)+"rrorMessage"](_0x2b0e8c)})):this.on(n,s)}["removeEv"+t(564)+"ner"](n,s){let l=t;e.TcvRx(e[l(1222)],l(727))?this[l(1166)](n,s):this["_addWsLi"+l(1533)]()}get[t(1241)+"te"](){let n=t,s={ehLKE:function(l,x){return e.GLMOJ(l,x)},CDHfd:function(l,x){return e[j(1284)](l,x)},pkmNx:function(l,x){return e[j(1647)](l,x)},FnpIR:function(l,x){return l|x},PiWmk:function(l,x){return l<<x},acTGj:function(l,x){return l&x},LIKVV:function(l,x){return e[j(443)](l,x)},dOtgv:function(l,x){return l(x)}};if(e[n(620)](e[n(1750)],e.WoHjA))_0x2b98f3=_0x5d6b30[eTtBcS[n(1280)](_0x2e362e+_0x14dae8,1)],eTtBcS[n(1712)](eTtBcS[n(1114)](192,_0x5765cb),128)?_0x6aa093+=_0x42aa91:(_0xa3612f=eTtBcS[n(1030)](eTtBcS[n(1516)](eTtBcS[n(832)](31,_0x2f7ada),6),eTtBcS[n(1114)](63,_0x2a9d0a)),eTtBcS[n(1447)](_0x1d9d9a,128)?_0x1e1d77+=_0x2195a6:(_0x51f071+=eTtBcS[n(1373)](_0x27c33c,_0x12f02b),_0x5bc2b1++));else return this[n(1183)].readyState}get[t(533)+"pe"](){return this._socket.binaryType}set[t(533)+"pe"](n){}get[t(1134)](){return this._socket.url}get protocol(){let n=t;return this[n(1183)][n(1718)]}get[t(561)+"ns"](){let n=t;return e[n(1884)]===e[n(963)]?!0:this[n(1183)].extensions}get[t(1663)+t(1118)](){return 0}}function rm(a,n){let s=t;if(n)return new n(a[s(1134)],a.protocol);if(ti||Dn)return new nm(a.url,a.protocol,a[s(685)]);if((sr||ni)&&e[s(1729)](e[s(1538)],typeof WebSocket)&&WebSocket)return new WebSocket(a[s(1134)],a[s(1718)+"s"])}function im(a){let n=t,s={YbCfR:e[n(1635)],pTUHY:function(l,x){return e[n(740)](l,x)},SXiRw:function(l){return e[n(1102)](l)},wJoqo:function(l,x){return l(x)},zUDDw:e[n(1323)]};if(e[n(332)](n(903),e[n(644)])){let l=e.VwmBn[n(1598)]("|"),x=0;for(;;){switch(l[x++]){case"0":return!1;case"1":if(ti&&wx[n(459)+n(1304)])return!0;continue;case"2":if(Dn&&tt["connectS"+n(1304)])return!0;continue;case"3":if(e.SpOxS(sr,ni)&&e[n(1538)]!=typeof WebSocket&&WebSocket)return!0;continue;case"4":if(a)return!0;continue}break}}else{let l=()=>{let w=n;_0x5a666f[w(1181)+w(564)+w(398)](w(1682),x),_0x1d0ea9[w(1181)+w(564)+w(398)](medted.YbCfR,m)},x=()=>{let w=n;medted[w(1638)](_0xab2b9a,medted[w(1638)](_0x239ce8,_0x6adcbd.result)),medted[w(293)](l)},m=()=>{let w=n;medted[w(830)](_0x21fd92,_0x22c062[w(1459)]),l()};_0xad7282[n(765)+n(1865)](medted[n(1450)],x),_0x172b16[n(765)+n(1865)](medted[n(1859)],m)}}function _l(a,n,s){let l=t,x={tJFRU:function(m,w){return e[j(672)](m,w)},WPXhs:e[l(777)],ejvRX:function(m,w){return e[l(854)](m,w)}};if(e[l(589)](e[l(1583)],e[l(1672)])){let m=this._qosDB[l(848)+"geInfoSync"](this[l(834)]),w=_0x3c13a1[l(334)](e[l(1485)](m,"{}"));return _0x1ea9d3[l(1426)](w)}else{let m=-1;async function w(S){let p=l;return x[p(1655)](S,m)?Promise[p(491)](new Error(x.WPXhs)):(m=S,S===s[p(1390)]?Promise[p(1877)]():s[S][p(815)](a)(n,w[p(815)](null,x[p(1357)](S,1))))}w(0)}}function yl(a){let n=t,s=0,l=0;for(let x=0;e.WrfOM(x,a[n(1390)]);++x)l=a.charCodeAt(x),e[n(826)](l,128)?s+=1:e[n(1071)](l,2048)?s+=2:e.KHNNj(e[n(1641)](64512,l),55296)&&e[n(928)](e[n(548)](64512,a[n(1703)+"At"](e[n(358)](x,1))),56320)?(++x,s+=4):s+=3;return s}function bl(a,n,s){let l=t;if(e.ppeLH(e[l(1753)](s,n),1))return"";let x="";for(let m=n;e[l(769)](m,s);){let w=a[m++];if(e.DXwjG(w,127))x+=String[l(455)+l(404)](w);else if(w>=192&&w<224)x+=String[l(455)+l(404)](e[l(394)](e.ifczr(e[l(1836)](31,w),6),e[l(1075)](63,a[m++])));else if(e.FpKQV(w,224)&&e[l(1713)](w,240))x+=String[l(455)+l(404)](e[l(1737)](e[l(1501)](15,w)<<12,e[l(1622)](63,a[m++])<<6)|e.NvbLS(63,a[m++]));else if(e[l(1678)](w,240)){let S=e.spwAE(e[l(873)](e[l(1359)](e[l(572)](e[l(923)](7,w),18),e.tUwAk(e.kvMyZ(63,a[m++]),12)),e[l(1593)](e[l(1749)](63,a[m++]),6))|63&a[m++],65536);x+=String["fromChar"+l(404)](e.daGKD(55296,e[l(1665)](S,10))),x+=String[l(455)+l(404)](e[l(942)](56320,e.GmLsR(1023,S)))}}return x}function Sa(a,n,s){let l=t,x=s,m,w;for(let S=0;e[l(443)](S,a[l(1390)]);++S)if(m=a.charCodeAt(S),e[l(1037)](m,128))n[s++]=m;else if(m<2048)n[s++]=e.qOToq(m,6)|192,n[s++]=e[l(993)](e.Slpqv(63,m),128);else if(e[l(337)](e[l(699)](64512,m),55296)&&e[l(928)](e[l(350)](64512,w=a.charCodeAt(e[l(1570)](S,1))),56320)){let p=e.NCnMR[l(1598)]("|"),O=0;for(;;){switch(p[O++]){case"0":n[s++]=e.qRXvW(63,m)|128;continue;case"1":n[s++]=e.aguVR(m>>18,240);continue;case"2":m=65536+e[l(819)](e[l(385)](1023,m),10)+e[l(631)](1023,w);continue;case"3":++S;continue;case"4":n[s++]=e[l(1805)](e[l(468)](m,6)&63,128);continue;case"5":n[s++]=e.HLGsp(e[l(1665)](m,12)&63,128);continue}break}}else n[s++]=m>>12|224,n[s++]=e[l(1326)](e[l(350)](e[l(468)](m,6),63),128),n[s++]=e[l(795)](63,m)|128;return s-x}async function El(a){let n=t;if(e[n(539)](e.iOiwF,typeof a))if(e.ZxiWx===e.hxUxY){let s=0,l=0,x;do x=_0x23484a(_0x1a24dc),e[n(1857)](s,32)&&(l|=e[n(955)](e[n(1614)](127,x),s)),s+=7;while(e[n(861)](128,x));return l}else{let s=new Uint8Array(yl(a));return e[n(559)](Sa,a,s,0),s}return e.gtRoI(a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(1656)],a[n(1392)+"et"],a[n(1117)+"th"])}function sm(a){let n=t;try{return e.bbdkR(e[n(996)],typeof a)&&(e[n(1344)](a,ArrayBuffer)||a[n(1656)]&&e[n(1615)](a[n(1656)],ArrayBuffer))||e[n(410)](e[n(996)],typeof a)?"":(JSON[n(334)](a),n(1059)+n(1511))}catch{return e[n(1337)]===n(318)?(this[n(1420)+n(591)+n(1823)+"t"]=1,this[n(473)+n(1679)]++,this.endpoints[this[n(473)+"ndex"]]):e[n(539)](e.iOiwF,typeof a)?e[n(1522)]:""}}let om=(a,n)=>{let s=t;switch(a){case e.QXVBy:case e[s(1772)]:return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class am{constructor(n){let s=t,l={UpIrd:function(x,m){return x===m},PlwZY:e[s(1350)]};if(e[s(650)](e.rFDGc,s(1060)))this[s(692)+s(1458)]=n,this[s(757)]=0;else return _0x568dfa instanceof _0x35d6d2&&(lAOtZy[s(341)](_0x49fad2,lAOtZy[s(686)])||lAOtZy[s(341)](_0x122998,"store"))?!0:_0x5210e0 in _0xbe0b7d}[t(964)](){let n=t;this[n(757)]++}[t(865)+"chMaxCount"](){let n=t;return e[n(1288)](this[n(757)],this[n(692)+n(1458)])}[t(1706)+t(1870)](n=0){let s=t;this[s(692)+s(1458)]=n,this[s(757)]=0}}async function cm(a){let n=t,s={WocjU:e[n(1156)],awjhO:function(l,x,m){return e[n(1462)](l,x,m)},wBUBq:function(l,x){return e[n(1008)](l,x)},PrCMp:e[n(666)],pvqaD:n(1798)+"ascript",TRyik:function(l,x){return e[n(1869)](l,x)},EXBhN:e[n(1496)],uQgGX:e[n(693)],UKlKs:e[n(1862)]};return new Promise(l=>{let x=n,m={FdKca:s.WocjU,HnNXm:x(1061),FhxAw:function(w,S,p){return s[x(1389)](w,S,p)},CjrlR:x(1686)+"ay, netw"+x(638)+x(1771)};if(!sr)return s.wBUBq(l,x(1081)+"reason");try{let w=document[x(1868)+x(409)](s.PrCMp);window[x(1608)+x(1671)]=S=>{let p=x;document.body.removeChild(w),window[p(1608)+p(1671)]=void 0,l(S&&S[p(1649)]||p(1081)+p(1176))},w[x(1007)]=s[x(1710)],w.src=a.replace(/^ws/,x(837))+(x(1498)+x(1045)+x(311)+"P");try{if(s[x(1213)](s[x(970)],s.uQgGX))document[x(1755)][x(552)+"ild"](w);else{if(this[x(967)+x(1215)](),this[x(1804)+x(461)](),this["_removeW"+x(1560)+"rs"](),this["_wsInsta"+x(1660)](1e3,_0x581f18),this["_connect"+x(1736)]=!1,_0x397d90&&this["_navigat"+x(1391)]()&&!this[x(885)+"osed"]){if(this[x(816)+"tManager"]?.[x(865)+x(876)+"es"]()){let p=this[x(816)+x(1051)]?.["getCurre"+x(667)+"nt"]();this[x(1371)+x(1256)+x(1343)](_0x3e965b(m[x(768)],{code:1006,reason:x(798)+p+(x(742)+x(1811)+x(1730)+"ached"),wasClean:!0}))}else{let p=this[x(1696)][x(1876)+x(1520)+x(615)](_0x59ee0f,_0x371400);this[x(1371)+x(1256)+x(1343)](_0xe8b7c4(m[x(768)],{code:_0x3703ee,reason:_0x306f84,wasClean:!0,willReconnect:p})),p&&this._connect()}return}this[x(430)+x(1391)]()||this["_readyCl"+x(943)]?this[x(1371)+x(1256)+x(1343)](_0x568571(m[x(768)],{code:_0x1f4d62,reason:m[x(1556)]})):this["_dispatc"+x(1256)+x(1343)](m[x(1508)](_0x41bbc0,x(1461),{code:1006,reason:m[x(747)]})),this[x(1839)]=null,this["_endpoin"+x(1051)]?.[x(608)+x(1255)+x(869)](),this[x(1770)+x(610)]?.[x(1706)+"nter"]()}}catch{document.body.removeChild(w)}}catch{window[x(1608)+x(1671)]=void 0,s.wBUBq(l,s.UKlKs)}})}function dn(a,n,s){let l=t;return!!a?.[l(1377)](x=>x[l(999)]===n&&x[l(1302)]===s)}function or(a,n){let s=t;return a?.[s(1377)](l=>l[s(999)]===n)?.value}let Ia=null;async function dm(){let a=t;return Ia||(Ia=Promise.resolve().then(zt[a(815)](zt,a(362)))),Ia}class lm extends va{constructor(n,s){let l=t;e[l(1765)](e[l(1585)],e[l(1408)])?_0x4a60e1.log(_0x547312):(super(),this[l(760)]=n,this[l(779)]=s,this[l(1488)]=void 0,this[l(1253)+l(1580)]=null)}async openDB(){await this[t(415)]()}async[t(415)](){let n=t;if(!this._qosDB){if(this[n(1253)+n(1580)])return this[n(1253)+n(1580)];try{let s=this._dbName,l=this[n(779)];this[n(1253)+n(1580)]=(async()=>{let x=n,{openDB:m}=await dm();this._qosDB=await e[x(559)](m,x(1608)+"_"+s,1,{upgrade(w){let S=x;w[S(874)+S(1217)+"e"](s,{keyPath:l})}})})(),await this["_initPro"+n(1580)]}catch(s){console[n(1584)](s)}finally{this[n(1253)+n(1580)]=null}}}async[t(1548)](n){let s=t;try{return e.keyJG(e[s(670)],e[s(1763)])?_0x39f34a||(_0xb39757=[_0x484789,_0x3b104c,_0x2bf141,_0x5e2f57,_0x384e77]):(await this[s(415)](),this[s(1488)]?.get(this[s(760)],n))}catch(l){console[s(1584)](l)}}async[t(808)](n,s){let l=t;return await this[l(415)](),this[l(1488)]?.[l(1754)](this[l(760)],n)}async[t(1144)](n){let s=t;try{return await this[s(415)](),this[s(1488)]?.[s(1009)](this[s(760)],n)}catch(l){console.log(l)}}async[t(1866)](){let n=t;try{return await this._init(),this[n(1488)]?.[n(1866)](this[n(760)])}catch(s){console[n(1584)](s)}}async[t(889)](){let n=t;return await this._init(),this[n(1488)]?.getAllKeys(this[n(760)])}async[t(1194)](){let n=t;return await this[n(415)](),this[n(1488)]?.[n(1194)](this[n(760)])}async closeDB(){let n=t;try{this._qosDB?.close(),this[n(1488)]=void 0}catch(s){console[n(1584)](s)}}get[t(1578)](){let n=t;try{if(e[n(359)](e[n(432)],e.IUFXh))e[n(899)](_0x14fefb,_0x3a193d,24),e[n(744)](_0x449704,_0x161b8d,e.fEoAd(_0x3cc0e7,_0x3b4015));else return!!this._qosDB}catch(s){return console.log(s),!1}}}class um{constructor(n,s){let l=t,x={zcZag:function(m,w){return e.maTLz(m,w)},jwRiY:function(m,w){return e[j(1319)](m,w)},DWZXk:function(m,w){return e[j(361)](m,w)},NemVU:function(m,w){return m(w)},CThcS:function(m,w){return m<<w},mPaIf:function(m,w){return e.qiDsb(m,w)},Tiiqa:function(m,w){return e[j(485)](m,w)},nbPpJ:function(m,w){return e.pEWuV(m,w)},YTaAY:function(m,w){return m<<w}};e[l(1751)](l(530),l(505))?(_0x5a2735=uBKqeP.zcZag(_0x82ba6e,_0x2b7515),_0x2a65f0|=uBKqeP[l(1629)](127,_0x397ba9)<<14,uBKqeP[l(1769)](128,_0x4d8018)&&(_0xaa3001=uBKqeP.NemVU(_0x2f1c33,_0x27523a),_0xb2d4e1|=uBKqeP.CThcS(127&_0x91987a,21),uBKqeP.mPaIf(128,_0xe3ce12)&&(_0x36ddc6=uBKqeP[l(717)](_0x314229,_0x51658e),_0x5e5b33=uBKqeP[l(1387)](127,_0x5c101f),uBKqeP[l(1014)](128,_0x5bf347)&&(_0x50e3ca=uBKqeP[l(717)](_0x4e3e99,_0x57c1e9),_0x49483a|=uBKqeP[l(1817)](uBKqeP[l(1629)](127,_0x46c14f),7))))):(this[l(1643)]=n,this[l(1368)]=s,this._qosDB=localStorage)}async openDB(){}get[t(834)](){let n=t;return n(1608)+"_"+this[n(1643)]}async[t(1548)](n){let s=t,l=this[s(1488)][s(732)](this[s(834)]);return JSON[s(334)](e.jZbkN(l,"{}"))[n]}async[t(808)](n,s){let l=t,x=this[l(1488)][l(732)](this[l(834)]),m=JSON[l(334)](e[l(1835)](x,"{}"));return m[s||n[this[l(1368)]]]=n,this[l(1488)][l(1785)](this._prefix,JSON[l(1126)+"y"](m)),s||n[this[l(1368)]]}async del(n){let s=t,l=this._qosDB[s(732)](this[s(834)]),x=JSON[s(334)](e.wfOkl(l,"{}"));return x[n]=void 0,this._qosDB.setItem(this[s(834)],JSON[s(1126)+"y"](x))}async[t(1866)](){let n=t;return this._qosDB[n(1866)]()}async[t(889)](){let n=t,s=this._qosDB.getItem(this._prefix),l=JSON.parse(s||"{}");return Object[n(889)](l)}async getAll(){let n=t,s=this[n(1488)].getItem(this[n(834)]),l=JSON[n(334)](e.DGpbe(s,"{}"));return Object[n(1426)](l)}[t(914)](){let n=t,s={ekOTO:e[n(1235)]};if(e[n(867)]("mGFVe",e.xmYue))return Promise[n(1877)]();this[n(1611)](s[n(1715)],_0x2c9850[n(551)]),_0x359565()}get[t(1578)](){return!!this._qosDB}}class fm{constructor(n,s){let l=t;this[l(1643)]=n,this[l(1368)]=s,this[l(1488)]=Dn?tt:ti?wx:null}async openDB(){}get[t(834)](){let n=t;return n(1608)+"_"+this[n(1643)]}async get(n){let s=t,l=this[s(1488)][s(848)+"geSync"](this[s(834)]);return JSON[s(334)](e.wfOkl(l,"{}"))[n]}async[t(808)](n,s){let l=t,x={yqsNo:function(m,w,S,p){return e[j(445)](m,w,S,p)},mfjaB:e.QcHaD,TdStK:e.jCRWl,LQWcC:l(1746),quBOt:function(m,w){return e.DGpbe(m,w)}};if(e[l(1364)](e.PaBmJ,l(1818))){let{enableAutoAck:m}=this[l(1696)],w=x[l(614)](_0x52a6c9,_0x3c8609[l(551)][l(685)],x[l(1847)],"1"),S=x.yqsNo(_0x538d20,_0x187a7f[l(551)][l(685)],l(1334),"1"),p=_0x13330c.call(this,_0x1bee76);if(m&&w){let{SeqID:O,LogID:L,service:F,LogIDNew:W,method:K}=_0x4752b2[l(551)];this[l(1375)]({SeqID:O,LogID:L,LogIDNew:W,service:F,method:K,headers:[{key:x[l(1202)],value:"1"},{key:x[l(1628)],value:x[l(515)](W,"")},{key:l(756),value:"0"}]})}S&&!p[l(1138)]&&this["_dispatc"+l(1386)+l(1223)](_0x407aa8),_0x44426d()}else{let m=this[l(1488)][l(848)+"geSync"](this[l(834)]),w=JSON[l(334)](m||"{}");return w[s||n[this[l(1368)]]]=n,this[l(1488)][l(1104)+"geSync"](this[l(834)],JSON[l(1126)+"y"](w)),s||n[this[l(1368)]]}}async[t(1144)](n){let s=t,l=this[s(1488)][s(848)+s(919)](this[s(834)]),x=JSON[s(334)](l||"{}");return x[n]=void 0,this._qosDB[s(1104)+s(919)](this._prefix,JSON.stringify(x))}async[t(1866)](){let n=t;return this[n(1488)][n(1720)+n(1809)]()}async keys(){let n=t,s=this[n(1488)]["getStora"+n(580)+"nc"](this._prefix),l=JSON[n(334)](e[n(728)](s,"{}"));return Object[n(889)](l)}async getAll(){let n=t,s=this._qosDB[n(848)+"geInfoSync"](this._prefix),l=JSON[n(334)](s||"{}");return Object[n(1426)](l)}[t(914)](){return Promise.resolve()}get[t(1578)](){return!!this[t(1488)]}}function vl(a,n){let s=t;if(e.KCjqL(e[s(1044)],e[s(1537)])){if(e[s(879)](Dn,Dn))return new fm(a,n);if(e[s(1835)](sr,ni)&&e[s(1729)](e[s(1538)],typeof indexedDB))return new lm(a,n);if(e[s(388)](sr,ni)&&e[s(1693)](e[s(1538)],typeof localStorage))return new um(a,n);throw new Error(s(1400)+s(393)+"d")}else{e[s(1873)](_0x2b30b8,_0x5c9f85,42);let l=e[s(1291)](_0x414798);e[s(345)](_0xaefb65,_0x655a4a,l),e[s(594)](_0x2caafe,_0x1928dc,l.limit),_0x3b9db8(_0x459993,l),e.lbgmG(_0x248b77,l)}}class xm{constructor(){let n=t;this[n(932)+n(715)+"Id"]=null,this[n(932)+"l"]=36e5,this._qosDB=e.hChXj(vl,n(871),e.yuBmj)}async[t(932)+t(1502)](){let n=t;e[n(1601)](clearInterval,this[n(932)+n(715)+"Id"]),this[n(932)+"lTimeoutId"]=setInterval(()=>{let s=n;this[s(1083)+s(1411)]()},this[n(932)+"l"])}async[t(1186)](){let n=t;await this[n(1488)][n(1186)]().then(()=>{let s=n;this[s(932)+s(1502)]()})}async flushExpired(){let n=t,s={upZGk:function(m,w){return e[j(897)](m,w)},mAKjp:function(m,w){return e.EzELo(m,w)},opjtz:e[n(1701)]};(await this[n(1488)]?.[n(1194)]()||[]).filter(({timestamp:m})=>m<Date[n(1449)]())[n(973)](m=>{let w=n;s[w(303)](s[w(1571)],w(1333))?(s[w(841)](_0x1c5d58,this[w(1483)+w(296)+"Id"]),_0x1a8d8e(this["_reconne"+w(301)+w(1642)]),this._pingPongTimeoutId=null,this["_reconnectTimeou"+w(1642)]=null):this._qosDB?.[w(1144)](m[w(733)+"id"])})}async[t(1144)](n){let s=t;return this[s(1488)]?.[s(1144)](n)}async[t(808)](n,s){let l=t;return this[l(1488)]?.[l(808)]({message_id:n,timestamp:s})}async[t(1548)](n){let s=t;return this[s(1488)]?.[s(1548)](n)}async[t(914)](){let n=t;if(e[n(370)](e[n(1510)],e[n(1472)]))e.VjvRp(clearInterval,this["_interva"+n(715)+"Id"]),await this._qosDB?.closeDB();else return this._ws?this[n(1839)][n(533)+"pe"]:this._binaryType}get[t(1578)](){let n=t;return this._qosDB?.[n(1578)]}}function Aa(a){let n=t,s=!!this[n(1696)][n(1125)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(445)](dn,a.message[n(685)],e[n(1205)],"2"),x=l&&e[n(445)](dn,a.message[n(685)],e[n(1574)],"1"),m=l&&dn(a[n(551)][n(685)],e[n(421)],"1"),w=m?e.mvarc(or,a.message.headers,e[n(482)])?.[n(1598)](",").filter(Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:x,isAckCleanupMessage:m,ackMsgIds:w}}async function Sl(){let a=t;return this["_QoSMana"+a(1289)]||(this[a(486)+"ger"]=new xm),this[a(486)+a(1289)][a(1578)]||await this[a(486)+a(1289)].openDB(),this["_QoSMana"+a(1289)]}async function hm(a,n){let s=t;if(e[s(1364)](e[s(1171)],e[s(1171)]))return new _0x503368(_0x4a1a80);{let{enableAutoAck:l}=this._options,x=e[s(555)](dn,a.message[s(685)],e.QcHaD,"1"),m=e[s(559)](dn,a.message[s(685)],e[s(576)],"1"),w=Aa[s(840)](this,a);if(l&&x)if(e[s(1504)](e[s(1775)],e.ycstZ)){let{SeqID:S,LogID:p,service:O,LogIDNew:L,method:F}=a.message;this[s(1375)]({SeqID:S,LogID:p,LogIDNew:L,service:O,method:F,headers:[{key:e[s(576)],value:"1"},{key:e[s(353)],value:L||""},{key:e[s(1335)],value:"0"}]})}else _0x4f2cf2(_0x34381b.error),RcTvpN[s(1102)](_0x4b40aa);m&&!w[s(1138)]&&this[s(1371)+s(1386)+s(1223)](a),e.iNpRb(n)}}async function pm(a,n){let s=t;this[s(1611)](e.wuQDc,a[s(551)]),n()}async function mm(a,n){let s=t;if(e[s(557)]!==s(1356)){let l=e[s(1340)](on,await El(a[s(1197)]));try{if(e.gtRoI(l.payload,Uint8Array))if(e.kVkpO===e[s(1539)])this[s(1839)]&&this[s(1839)].close(_0x144b68,_0x18d22a);else{let x=e.JsahN(this[s(1696)][s(956)+s(426)],Object)?{force:!!this[s(1696)][s(956)+s(426)].force,encoding:this[s(1696)][s(956)+s(426)][s(752)]?this[s(1696)].payloadEncoding[s(752)][s(772)](/\s/g,"")["toLowerC"+s(730)]():""}:{force:!1,encoding:this[s(1696)][s(956)+s(426)]?this[s(1696)].payloadEncoding[s(772)](/\s/g,"")[s(479)+"ase"]():""},m=l[s(956)+"ncoding"]?l[s(956)+"ncoding"].replace(/\s/g,"")[s(479)+s(730)]():"",w=e[s(1432)](this._options["payloadT"+s(1596)],Object)?{force:!!this[s(1696)][s(294)+s(1596)].force,type:this[s(1696)]["payloadT"+s(1596)][s(1007)]?this[s(1696)]["payloadT"+s(1596)][s(1007)][s(772)](/\s/g,"")["toLowerC"+s(730)]():""}:{force:!1,type:this[s(1696)][s(294)+"ype"]?this[s(1696)][s(294)+s(1596)][s(772)](/\s/g,"")["toLowerC"+s(730)]():""},S=l[s(294)+s(1596)]?l[s(294)+s(1596)][s(772)](/\s/g,"")[s(479)+s(730)]():"",p=w[s(1111)]?w.type:S||w[s(1007)],O=x[s(1111)]?x[s(752)]:m||x.encoding,L=[e[s(1522)],e.Mtsaw,e[s(1815)],e[s(996)]],F=[e[s(1042)],s(621)];this[s(1696)]["enableTr"+s(375)+s(1850)+"ad"]&&L.includes(p)&&(!O||F[s(1477)](O))?l[s(790)+s(347)]=bl(l[s(1607)],0,l[s(1607)][s(1117)+"th"]):l[s(790)+"oad"]=""}else l.textPayload=""}catch(x){l[s(790)+s(347)]="",console[s(1584)](x)}a[s(551)]=l,e.MnsMM(n)}else return!!this._qosDB}function gm(a,n,s){let l=t;if(e.mJAJG!=="gPmOs"){let x=e[l(879)](s,8192),m=x>>>1,w=null,S=x;return function(p){let O=l;if(e[O(826)](p,1)||e[O(835)](p,m))return e[O(1311)](a,p);e[O(982)](e[O(801)](S,p),x)&&(w=e[O(828)](a,x),S=0);let L=n[O(840)](w,S,S+=p);return e[O(548)](7,S)&&(S=e[O(801)](e.CzAvN(7,S),1)),L}}else return(this[l(373)+"rs"][_0x1f4b0e]||(this[l(373)+"rs"][_0x437634]=[]))[l(1489)]({fn:_0x489b2a,ctx:_0x2d54e2||this}),this}let wm=4294967295;function _m(a,n,s){let l=t;return RangeError(e[l(1688)](e.pJxoi(e.jyBwS(e[l(1201)],a),e[l(1674)])+e.oJkYo(n,1)+e[l(542)],s))}function ym(a,n,s){let l=t;if(e[l(1278)](s,wm))throw new Error(e.aTPcI);let x=3;for(;e.FpKQV(x,0);){let m=e.PBIUS(255,s);e[l(559)](Ta,m,a,e[l(1471)](n,x)),s>>>=8,x--}return n+4}function bm(a,n){let s=t,l=0,x=n,m=e.GiUpr(n,4);for(;e[s(976)](x,m);){let{value:w,offset:S}=e.tWPoP(ka,a,x);x=S,l=e[s(1372)](l<<8,0),l+=w}return{value:l,offset:m}}function Em(a,n,s){let l=t;return a?e[l(1037)](a[l(1390)],40)?e[l(1003)](Sa(a,n,s),s):n[l(1036)+"e"]?e[l(801)](n[l(1036)+"e"](a,s),s):n[l(678)]?e.Buqpt(n[l(678)](a,s),s):e[l(1586)](Sa(a,n,s),s):s}function vm(a,n){let s=t,l=new xe(e.ANoQg(e[s(1402)](e[s(384)](e[s(535)](a[e[s(1858)](n,4)],24),e[s(955)](a[e[s(513)](n,5)],16)),a[e.TTtrO(n,6)]<<8),a[n+7]),e[s(1402)](a[e.NhIWV(n,0)]<<24|e[s(1e3)](a[e.dhbIl(n,1)],16),a[e[s(358)](n,2)]<<8)|a[e[s(942)](n,3)],!0);return n+=8,{value:l,offset:n+8}}function Sm(a,n,s){let l=t,x={eXqwP:function(m,w){return e.pwugQ(m,w)},CnCyg:function(m,w){return e[j(440)](m,w)}};if(e.PWoma(e.XBcKu,e.kVpMG)){if(QBpvat[l(1063)](_0x15c2db,_0x5d64ed))return _0x354ea2(_0x516e6b);if(_0x1bf76d[l(1721)](_0x1226cc))return _0x410d33[l(1548)](_0x37372d);let m=QBpvat.CnCyg(_0x396bf9,_0x11a667);return m!==_0x55c4f2&&(_0x6ce594[l(808)](_0xe3fb2c,m),_0x5aed83[l(808)](m,_0x316562)),m}else{let m=a.low,w=a[l(1714)];return n[s]=e[l(466)](w,24),n[e[l(974)](s,1)]=e[l(548)](w>>>16,255),n[e[l(974)](s,2)]=e[l(1777)](e.WJUqL(w,8),255),n[s+3]=e.HoDbP(255,w),n[e[l(833)](s,4)]=e[l(387)](m,24),n[e[l(1698)](s,5)]=e.LPOpb(e[l(448)](m,16),255),n[e.SIwoe(s,6)]=e[l(883)](e[l(1787)](m,8),255),n[e[l(1756)](s,7)]=e[l(538)](255,m),s+=8,s}}function ka(a,n){let s=t;return a[s(674)+"8"]?{value:a[s(674)+"8"](n),offset:e.vzzzT(n,1)}:{value:255&a[n],offset:n+1}}function Ta(a,n,s){let l=t;return e.gIZca(e.kAUrU,e[l(961)])?!!(_0x5e6179||_0x58e47d&&_0x2245d4[l(459)+l(1304)]||_0xe88176&&_0x393025["connectS"+l(1304)]||e[l(388)](_0x5b88b0,_0x26379a)&&e[l(1693)](e[l(1538)],typeof _0x29620)&&_0x1f36b5):(n[l(657)+"t8"]?n[l(657)+"t8"](a,s):n[s]=255&a,e[l(971)](s,1))}let Im=function(a){return new Uint8Array(a)},Am=typeof Buffer<"u"?Buffer[t(578)+t(490)]:e[t(899)](gm,Im,Uint8Array[t(870)+"e"].subarray);(()=>{let a=t;if(e.zmQIM!=="SpXnG")return _0x13adad?_0x49a8be[a(1541)+a(1275)](_0x37b4b9,_0x1df1cf):_0x1811d3[a(1541)+"sBE"](_0x37b481,_0x2c4639);{let n=4294967295;return function(s,l,x=!0){let m=a;if(n=e[m(1633)](127&s[l],0),s[l++]<128)return{value:x?n:e[m(1277)](0,n),offset:l};if(n=e[m(356)](e[m(1294)](n,e[m(853)](e.JBebq(127,s[l]),7)),0),e[m(976)](s[l++],128))return{value:x?n:e[m(1185)](0,n),offset:l};if(n=e[m(1486)](n,e[m(357)](e.PBIUS(127,s[l]),14))>>>0,e[m(769)](s[l++],128))return{value:x?n:e[m(1348)](0,n),offset:l};if(n=e[m(778)](e[m(1604)](n,e[m(1441)](e.qiDsb(127,s[l]),21)),0),e.WrfOM(s[l++],128))return{value:x?n:0|n,offset:l};if(n=e[m(1016)](e.xPqdY(n,e[m(1616)](e[m(883)](15,s[l]),28)),0),s[l++]<128)return{value:x?n:0|n,offset:l};if(e[m(805)](l+=5,s[m(1390)])){if(e[m(1467)](e[m(842)],m(1476)))return new _0x1908e4(_0x1ec0e9,_0x294d71,_0x25e7ab);throw l=s.length,e[m(445)](_m,l,10,s[m(1390)])}return{value:x?n:e[m(653)](0,n),offset:l}}}})();let km=16,Ca=32;function Tm(a){let n=t,s=0,l={};for(let x=0;e[n(1819)](x,a[n(1390)]);x++)l[a[x][n(554)+"ame"]]=e[n(1127)](yl,a[x][n(554)+"ame"]),s+=14+l[a[x][n(554)+n(1545)]];return[s,l]}function Il(a,n,s){let l=t,x={UzqWo:l(1146)+l(1852)+"10|0|7",QuYQR:function(O,L,F,W){return e[l(445)](O,L,F,W)},CmjcF:e.fufzc,WgWKf:e.UCYFv,mqdre:e[l(584)],Liqbf:e[l(325)],uTnGH:e[l(399)]},[m,w]=e[l(1788)](Tm,a),S=Am(m),p=0;return a[l(973)](O=>{let L=l,F=x[L(1867)].split("|"),W=0;for(;;){switch(F[W++]){case"0":p=x[L(506)](Sm,xe[L(697)+"er"](O[L(893)]||n),S,p);continue;case"1":p=x[L(506)](Ta,w[O[L(554)+"ame"]],S,p);continue;case"2":console[L(1584)](x.CmjcF,p);continue;case"3":console[L(1584)](L(703)+"name",p);continue;case"4":console[L(1584)](x[L(365)],O,O[L(1090)]);continue;case"5":p=x[L(506)](ym,S,p,O[L(1090)]||0);continue;case"6":p=Ta(0,S,p);continue;case"7":console.log(x.mqdre,p);continue;case"8":p=Em(O[L(554)+"ame"],S,p);continue;case"9":console[L(1584)](x[L(947)],p);continue;case"10":console[L(1584)](x[L(1544)],p);continue}break}}),{frameType:Ca,headers:[{key:e.kolVE,value:s}],payload:S}}function Cm(a){let n=t,s=0,l=[];for(;e[n(295)](s,a[n(1117)+"th"]);){let{offset:x}=e[n(583)](ka,a,s);s=x;let m={cursor_name:"",cursor:0,service:0},{value:w,offset:S}=bm(a,s);m.service=w,s=S;let{value:p,offset:O}=e[n(1640)](ka,a,s);s=O,m[n(554)+n(1545)]=e[n(1290)](bl,a,s,e[n(495)](s,p)),s+=p;let{value:L,offset:F}=e[n(1844)](vm,a,s);m[n(893)]=L.toNumber(),s=F,l[n(1489)](m)}return l}function Rm(){let a=t;return{frameType:Ca,headers:[{key:e[a(456)],value:e[a(913)]}],payload:void 0}}class Dm{constructor(n,s,l){let x=t;this[x(1131)+x(1468)]=n,this["_cursorF"+x(965)]=s,this[x(428)+x(665)]=l,this[x(1488)]=e[x(340)](vl,this["_cursorN"+x(1468)],x(554)+"ame")}async[t(1186)](){let n=t;await this[n(1488)][n(1186)]()}async[t(595)+"rs"](){let n=t;if(!this[n(1488)][n(1578)])return;let s=this["_message"+n(665)],l=await this[n(1488)][n(1194)]();switch(console[n(1584)](e[n(1351)],l),s){case e[n(1744)]:return l&&l[n(1390)]?e[n(477)](Il,l,0,this["_cursorF"+n(965)]):void 0;case"INSTANT":return;case e[n(1427)]:return l&&l.length?Il(l,0,this[n(523)+"ileName"]):Rm()}}async set(n,s,l){let x=t;return console.log(x(1639),n,s,l),this[x(1488)][x(808)]({cursor_name:n,cursor:s,service:l})}async[t(1173)+"rs"](n){let s=t,l=Cm(n);for(let x of l)console[s(1584)](e[s(465)],l),await this._qosDB[s(808)](x)}async[t(1548)](n){let s=t;return(await this[s(1488)].get(n))?.[s(893)]}async[t(914)](){let n=t;await this[n(1488)][n(914)]()}[t(652)+t(464)+t(738)](n){let s=t;this[s(523)+s(965)]=n}get isReady(){let n=t,s={CGNtP:function(l,x,m){return l(x,m)},VycBE:e[n(1635)]};if(e[n(367)](n(1460),e.GveQr)){let l="connect "+_0x96f59e+(" timeout"+n(1811)+n(1730)+n(958));this[n(1611)](l),this[n(1371)+n(376)+n(1343)](s.CGNtP(_0x59f7ae,s.VycBE,{message:l,code:_0xb8e388["MAX_RETR"+n(1229)+"R"]}));return}else return this[n(1488)][n(1578)]}}let Pm=e[t(1393)];async function Al(a){let n=t;if(!this._options[n(1125)+"S"])return null;let{aID:s,fpID:l,messageStrategy:x}=this._options,m=a||Pm;try{if(e.NSrMQ(e[n(1281)],n(1073)))return this[n(592)+n(1180)]?a&&this[n(592)+n(1180)][n(652)+n(464)+n(738)](a):this[n(592)+n(1180)]=new Dm(l+"_"+s+"_"+m,m,x),this["_cursorM"+n(1180)][n(1578)]||await this["_cursorM"+n(1180)][n(1186)](),this["_cursorM"+n(1180)];_0x11bf5a[n(808)](_0xb94988,_0x5ca926),_0x4d89b9.set(_0xe4a8cb,_0x1eeb8a)}catch{return null}}async function Om(a,n){let s=t,l={gyrED:s(629)+s(940)};if(e[s(1057)](s(938),e[s(363)]))return this._qosDB?.[s(1144)](_0x2f8d55);{let x=e[s(1279)](dn,a[s(551)][s(685)],e[s(1743)],"-1"),m=dn(a[s(551)][s(685)],e.jCRWl,"1"),w=e[s(1395)](or,a.message.headers,e[s(1637)]),S=e.VjvRp(Number,or(a.message.headers,e[s(396)]))||0,p=Aa[s(840)](this,a),O=e[s(555)](dn,a.message[s(685)],e[s(1856)],"2"),L=or(a[s(551)][s(685)],e[s(827)]),F=e.NmTWz(Number,e[s(1295)](or,a[s(551)][s(685)],e[s(784)]));if(p[s(1138)])return e[s(1864)](n);let W=p[s(1095)+s(646)]?await Sl[s(840)](this):null;if(e[s(805)](a[s(551)].service,0)&&m&&!x||e[s(1362)](a.message.service,0)){if(w&&p["isQoSMes"+s(646)]&&W)return!!!await W.get(w)&&(this["_dispatc"+s(1369)+s(933)](a),await W[s(808)](w,Date[s(1449)]()+S)),n();if(O){let K=await Al[s(840)](this);if(!K)return e.xjYWu(s(489),e[s(1160)])?{frameType:_0x3314bc,headers:[{key:s(1321)+s(1652),value:BoyYYt[s(1379)]}],payload:void 0}:(this["_dispatc"+s(1369)+s(933)](a),n());let _e=await K.get(L)??-1;if(e[s(1840)](_e,F))if(e[s(349)]===e[s(349)])this["_dispatc"+s(1369)+s(933)](a),K.set(L,F,a[s(551)][s(1090)]);else{if(RcTvpN[s(1796)](_0x5667db,RcTvpN[s(1350)]))return _0x2c1b7f[s(1548)](_0x2399f6);if(RcTvpN.ZsOrn(_0x146c68,RcTvpN[s(1514)]))return _0x33f431[s(990)+s(894)]||_0x5b11e8[s(1548)](_0x452ec9);if(RcTvpN.CdbLv(_0x23560f,RcTvpN[s(1130)]))return _0x16b02c[s(990)+"oreNames"][1]?void 0:_0x52bf43[s(990)+s(549)](_0x565ae6[s(990)+s(894)][0])}else throw new Error("recevied message cursor "+F+(s(323)+s(1116)+s(1431)+"r ")+_e);return n()}return this[s(1371)+s(1369)+"Event"](a),e[s(1102)](n)}}}async function Lm(a,n){let s=t;if(e.RGKzh(e.GVfzh,e.dSAjx)){let l=this[s(428)+s(1731)].reduce((x,m)=>(x+=m&&m[s(1117)+"th"]||0,x),0);return e[s(705)](l,this._ws?this[s(1839)]["buffered"+s(1118)]:0)}else{let l=Aa.call(this,a);if(!l[s(1095)+s(646)])return e[s(775)](n);let x=await Sl[s(840)](this);if(l[s(1792)+"anupMess"+s(429)]&&l[s(309)+"s"][s(1390)])for(let m of l[s(309)+"s"])await x[s(1144)](m);e[s(1291)](n)}}async function Nm(a,n){let s=t,l=e[s(1751)](a[s(551)].frameType,km),x=a[s(551)][s(1085)+"e"]===Ca;if(e[s(818)](!l,!x))return e[s(1291)](n);let m=or(a.message.headers,e[s(456)]);if(!m)return e.MnsMM(n);let w=await Al[s(840)](this,m);if(!w)return e.LqrDk(n);if(l){let S=await w.getCursors(),p={frameType:S?.[s(1085)+"e"],SeqID:xe[s(697)+"er"](this._seqId++),LogID:xe.fromNumber(this._options[s(1768)+"erator"]()),service:9e3,method:5,headers:S?.[s(685)],payload:S?.[s(1607)]},O=e[s(1567)](v,p);this[s(1839)]&&this[s(1839)][s(1241)+"te"]&&this[s(1839)][s(948)](O)}if(x)if(e.fNJou("yEUmp",e.ogYDv)){let S=a[s(551)][s(1607)];S&&w[s(1173)+"rs"](S)}else e[s(1384)](_0x2c8787,_0x12200e,58),e[s(1590)](_0x540766,_0x2f39b4,_0x3a9a25)}let Mm=async function(a,n){let s=t;if(s(1273)===e[s(959)])if(_0x2c2e05=_0x412465[s(1703)+"At"](_0x49a37f),e[s(597)](_0x545d8b,128))_0x489e89[_0x285752++]=_0x13f28c;else if(e.BIask(_0x21d102,2048))_0x4c1be5[_0x5e39f4++]=_0x3abe0b>>6|192,_0x44ed6b[_0x2682d6++]=e[s(1486)](63&_0x12d174,128);else if(e[s(361)](64512,_0x2a88fc)===55296&&e[s(1096)](64512,_0x41e372=_0x4aebda[s(1703)+"At"](_0x638c57+1))===56320){let l=("4|5|1|2|"+s(1843))[s(1598)]("|"),x=0;for(;;){switch(l[x++]){case"0":_0x391f76[_0x54867d++]=e[s(891)](e.xyaBF(_0x20f254>>6,63),128);continue;case"1":_0x1bd357[_0x72c632++]=e[s(1535)](e[s(1665)](_0x509206,18),240);continue;case"2":_0x48146e[_0xc8a2bb++]=e[s(1842)](e.ZIiKE(e.YWDBJ(_0x3929c7,12),63),128);continue;case"3":_0x254e22[_0x300ebb++]=e[s(908)](e.niZsc(63,_0x4c61e7),128);continue;case"4":_0x3b9e53=65536+(e[s(817)](1023,_0x3d3056)<<10)+(1023&_0x19b836);continue;case"5":++_0x24ba0b;continue}break}}else _0x463c54[_0x384dad++]=e[s(499)](e.vAhHZ(_0x34be73,12),224),_0x3a3739[_0x4354a8++]=e.TfsWE(e[s(1589)](e[s(1624)](_0x48bdbb,6),63),128),_0x6193c[_0x45d862++]=e.mlpQR(e[s(1417)](63,_0x52bdc2),128);else this[s(570)]=!1,e[s(397)](clearTimeout,this[s(1600)+s(1725)+s(984)]),e[s(1864)](n)},Bm=async function(a,n){let s=t,l={ybBcS:function(w,S){return w==S},LynNa:function(w,S){return e[j(1172)](w,S)},UnJVk:function(w,S){return e.uzxWb(w,S)}};if(!this[s(1839)]||this[s(1839)][s(1241)+"te"]!==this[s(1158)])return e[s(1102)](n);let{pingInterval:x}=this[s(1696)];this[s(816)+s(1051)]?.[s(608)+s(1255)+s(869)]();for(let w=0;e[s(708)](w,this[s(428)+s(1731)].length);w++)if(e[s(1410)](e[s(1058)],s(1707))){let S=this["_message"+s(1731)][w];if(e[s(846)](this[s(1839)].readyState,this.OPEN)&&S!==null)this._ws&&this[s(1839)][s(948)](S),this[s(428)+s(1731)][w]=null;else break}else{if(ceHclc.ybBcS("string",typeof _0x156173)){let S=new _0xe81c85(ceHclc[s(737)](_0x90a7aa,_0x4882c0));return _0x4cc3c4(_0x3b400e,S,0),S}return ceHclc[s(821)](_0x3ab75c,_0x7a3b10)?new _0x23643f(_0x578852):new _0x4e6ba4(_0x3d12fc.buffer,_0x47a856[s(1392)+"et"],_0x3a5fa9[s(1117)+"th"])}this[s(428)+s(1731)]=this[s(428)+s(1731)].filter(w=>!!w),this["_pingPon"+s(296)+"Id"]=setTimeout(()=>this._ping(),x),this[s(1371)+s(688)+"nt"](a),this[s(425)+"er"]&&this._ws&&(this[s(1839)][s(533)+"pe"]=this[s(926)+"ype"]);let m=this["_endpoin"+s(1051)]?.[s(1795)+s(667)+"nt"]();this._debug("open "+m+s(780)),e.Ntqpq(n)},Fm=async function(a,n){let s=t,l=this["_endpoin"+s(1051)]?.["getCurre"+s(667)+"nt"]();this._debug("open "+l),e.qWbSn(n)};class zm extends va{constructor(n){let s=t,l={sTKFG:"4|0|3|2|1",twvAq:function(S,p){return e.nQqcu(S,p)},tplLN:function(S,p,O){return S(p,O)},VJeqM:function(S,p){return S===p},cdkKB:e[s(1635)],JLAhf:function(S,p){return e[s(897)](S,p)},otVvr:e[s(1323)],dcfPJ:s(1282)+s(606)+"s",hecSt:e[s(1027)],KjSNC:function(S,p){return e[s(1559)](S,p)},jglfA:function(S,p){return e[s(410)](S,p)},VdgiG:e[s(1538)],XrOoM:e[s(1525)]};super(),this[s(1346)+s(759)+"line"]=!0,this[s(425)+"er"]=sr,this[s(1066)]=tm,this[s(1077)+"T"]=Dn,this[s(862)+"X"]=ti,this._isWorker=ni,this["_message"+s(1731)]=[],this[s(816)+s(1051)]=null,this[s(885)+s(943)]=!1,this[s(926)+s(1596)]=e.nIlNE,this["_connect"+s(1736)]=!1,this["_connect"+s(1725)+"utId"]=null,this[s(1200)+"ctTimeou"+s(1642)]=null,this["_pingPon"+s(296)+"Id"]=null,this._seqId=0,this[s(570)]=!1,this._url="",this[s(486)+s(1289)]=null,this[s(592)+s(1180)]=null,this[s(1770)+s(610)]=null,this._protocols=e[s(352)],this[s(1155)]=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this[s(1209)]=S=>{let p=s,O={apTWr:function(L,F,W){return e.fjUPf(L,F,W)},IpkZz:function(L,F,W){return e[j(1193)](L,F,W)}};if(e[p(1307)]("XQsTl",p(1293)))try{if(e.DBCJC(e[p(1562)],e[p(1793)]))e[p(338)](_l,this,S,[Mm,Bm,Fm]);else{let L=l[p(881)][p(1598)]("|"),F=0;for(;;){switch(L[F++]){case"0":this[p(1770)+"sCounter"]?.[p(1706)+"nter"]();continue;case"1":this[p(1600)]();continue;case"2":this[p(570)]=!0;continue;case"3":this["_readyCl"+p(943)]=!1;continue;case"4":this[p(816)+p(1051)]?.[p(608)+p(1255)+p(869)]();continue}break}}}catch(L){if(e[p(381)]("BQFla","GARUZ")){let F=e[p(1640)](lt,e[p(1635)],{message:L[p(551)],code:cn.OPEN_ERROR,error:L});this[p(1371)+p(376)+"ent"](F)}else kyIUQw[p(1055)](_0x7517e6,this[p(932)+p(715)+"Id"]),this[p(932)+p(715)+"Id"]=kyIUQw[p(969)](_0x2d95de,()=>{this[p(1083)+"ired"]()},this[p(932)+"l"])}else zWhUyv[p(1841)](_0x20e52b,_0x25c4ba,74),zWhUyv[p(1031)](_0x4b861d,_0x1bcb75,_0x5d6452)},this._onMessage=async S=>{let p=s,O={rUIVf:function(L,F){return L<F},XRFMx:function(L,F){return e[j(317)](L,F)}};if(e[p(989)](e[p(1563)],e[p(498)])){let L=0,F={};for(let W=0;akSwAI[p(380)](W,_0xe77bd3[p(1390)]);W++)F[_0x4e76e3[W][p(554)+p(1545)]]=_0x368e54(_0x153efd[W][p(554)+p(1545)]),L+=akSwAI[p(711)](14,F[_0x28c8d0[W]["cursor_n"+p(1545)]]);return[L,F]}else{let{pingInterval:L,pingFrequency:F}=this[p(1696)];if((e[p(1796)]("hi",S[p(1197)])&&e.PObTs===F||e[p(909)](e[p(1558)],F))&&(this[p(967)+p(1215)](),this[p(541)](e[p(1056)],e[p(1323)]),this[p(1483)+"gTimeoutId"]=e[p(912)](setTimeout,this[p(1109)].bind(this),L)),e[p(1070)]("hi",S[p(1197)]))return;try{if(e[p(864)]!==e[p(864)])return this[p(1183)][p(561)+"ns"];_l(this,S,[mm,hm,Lm,Nm,Om,pm])}catch(W){let K=e[p(412)](lt,"error",{message:W[p(551)],code:cn[p(508)+p(911)],error:W});this[p(1371)+p(376)+p(1343)](K)}}},this._onError=S=>{let p=s,O=this[p(816)+p(1051)]?.[p(865)+p(876)+"es"](),L=this[p(816)+p(1051)]?.[p(1795)+p(667)+"nt"]();if(O&&!S.message){let F=p(798)+L+(p(743)+p(1490)+"es reached");this[p(1371)+"hErrorEvent"](lt(p(1459),{message:F,code:cn[p(1024)+p(1229)+"R"],error:S}));return}this._ws&&l[p(1310)](this[p(1839)][p(1241)+"te"],this[p(1158)])&&this[p(972)+p(782)](),this["_dispatc"+p(376)+p(1343)](l[p(969)](lt,l.cdkKB,{message:S[p(551)],code:cn[p(1669)+"RROR"],error:S}))},this[s(997)]=async S=>{let p=s;if(e[p(1739)](e.ooOre,"uaUwQ"))try{return!!this[p(1488)]}catch(O){return _0x454dca[p(1584)](O),!1}else{this[p(1804)+p(461)](),this["_clearPi"+p(1215)](),this[p(1315)+p(1560)+"rs"](),this._ws=null,this["_connect"+p(1736)]=!1;let O=this[p(816)+p(1051)]?.[p(865)+p(876)+"es"]();if(!O&&this[p(430)+p(1391)]()&&!this[p(885)+p(943)])if(e[p(718)](e[p(292)],e[p(957)])){let L=this[p(816)+p(1051)]?.[p(1795)+"ntEndpoint"](),F=this[p(1696)][p(1876)+p(1520)+p(615)](S[p(1534)],S[p(1176)]);this[p(1371)+"hCloseEv"+p(1343)](e.Gjnwr(_t,e[p(1156)],{code:1006,reason:S[p(1176)]||"connecti"+p(1328)+p(1419)+p(441)+p(1645)+p(786)+L,willReconnect:F})),F&&this[p(1600)]();return}else l[p(1697)](_0x2665d8,l[p(418)]),this[p(1166)](l[p(1089)],_0x5b7470),this[p(1166)](l[p(1163)],_0x3769ce);if(e[p(878)](1e3,S[p(1534)])&&this[p(885)+"osed"]){this[p(1371)+p(1256)+p(1343)](e[p(452)](_t,p(1461),{code:1e3,reason:e.MoFkL})),this[p(816)+p(1051)]?.["resetEndpointCon"+p(869)](),this[p(1770)+p(610)]?.[p(1706)+p(1870)]();return}if(e[p(1595)](1e3,S[p(1534)])&&O)if(e[p(1433)](p(680),e[p(838)])){if(kyIUQw.KjSNC(_0x2d5f8f,_0x18b38e))return new _0xbeb7a9(_0x1c9279,_0x2de44d);if((_0x4d0aca||_0x594c77)&&kyIUQw[p(1863)](kyIUQw[p(1080)],typeof _0x17773f))return new _0x24fa4f(_0x40c54c,_0x59f916);if(kyIUQw.KjSNC(_0x4fc8cc,_0x2ff735)&&kyIUQw[p(1080)]!=typeof _0x34e497)return new _0x3e7451(_0x2ff292,_0x4af6a5);throw new _0x1772df(kyIUQw[p(791)])}else{let L=this[p(816)+"tManager"]?.[p(1795)+p(667)+"nt"](),F=S[p(1176)];F||(F=await e[p(1677)](cm,this[p(342)])),F=p(1487)+p(1328)+p(789)+F+(p(1521)+p(579))+L+(p(1811)+"tries re"+p(958)),this[p(1371)+p(1256)+p(1343)](e.SEIGV(_t,e[p(1156)],{code:S[p(1534)],reason:F}));let W=p(798)+L+(p(743)+p(1490)+p(866)+"ed");this[p(1371)+p(376)+p(1343)](e[p(403)](lt,e[p(1635)],{message:W,code:cn["MAX_RETR"+p(1229)+"R"]})),this[p(816)+p(1051)]?.["resetEnd"+p(1255)+p(869)](),this[p(1770)+p(610)]?.[p(1706)+p(1870)]();return}if(S[p(1534)]!==1e3&&!S[p(1176)]){let L=this._endpointManager?.[p(1795)+p(667)+"nt"]();this[p(1371)+p(1256)+"ent"](e[p(452)](_t,e[p(1156)],{code:S.code,reason:p(1487)+p(1328)+p(1419)+p(441)+p(1645)+"ame: "+L})),this["_endpoin"+p(1051)]?.[p(608)+"pointConfig"](),this["_pingLos"+p(610)]?.[p(1706)+p(1870)]();return}this[p(1371)+p(1256)+p(1343)](S),this[p(816)+p(1051)]?.[p(608)+"pointCon"+p(869)](),this[p(1770)+"sCounter"]?.["resetCou"+p(1870)]()}},this[s(1482)]=null,this.onerror=null,this[s(1735)+"e"]=null,this[s(1029)]=null,this["onStartR"+s(1358)]=null,this[s(1681)+"eAck"]=null,this[s(1062)+s(1505)+s(1764)+"ct"]=null,this[s(1699)+"nLine"]=this[s(1699)+s(1296)][s(815)](this),this[s(1699)+"ffLine"]=this[s(1699)+s(1184)][s(815)](this),this[s(647)+"ageHide"]=this[s(647)+s(408)][s(815)](this),this._handlePageShow=this._handlePageShow.bind(this),this[s(1696)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(633)](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(1558)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1427)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:x,ws:m}=n,w=Array.isArray(x)?x:e[s(637)](e[s(996)],typeof x)?[x]:[];if(!w||e.bNgTb(0,w.length))throw new Error("please p"+s(1434)+s(574));if(!e.qEVjD(im,m))throw new Error(e[s(1748)]);Object.assign(this._options,n),this[s(816)+s(1051)]=new wl(w,this[s(1696)][s(1734)+"es"]),this._pingLossCounter=new am(this[s(1696)][s(1564)+"Count"]),this[s(1696)][s(417)+s(431)]&&(this[s(570)]=!0,this[s(1600)]()),this[s(1696)]["listenNe"+s(793)+s(1004)]&&(this._isMiniTT||this[s(862)+"X"]?this["_onPageN"+s(1021)+s(673)]():this._isBrowser&&this[s(1074)+s(1128)+"Listener"]())}[t(1699)+"nLine"](){let n=t;this[n(1696)]["disableA"+n(1853)+n(767)]||this["_readyCl"+n(943)]||this[n(1065)+"econnect"]()}[t(1699)+"ffLine"](){let n=t;this[n(500)+n(1473)+"t"]();let s=e[n(379)](Ea,e[n(407)],{message:e[n(850)]});this[n(1062)+n(1505)+n(1764)+"ct"]&&this["onStopIm"+n(1505)+n(1764)+"ct"](s)}[t(1074)+"balEvent"+t(1865)](){let n=t;this[n(425)+"er"]&&window[n(765)+n(1865)](e.SUijY,this[n(1699)+n(1296)]),this._isBrowser&&window[n(765)+n(1865)](n(1113),this[n(1699)+n(1184)]),this[n(425)+"er"]&&window[n(765)+n(1865)](n(1470),this[n(647)+n(408)]),this[n(425)+"er"]&&window[n(765)+n(1865)](e[n(1046)],this[n(647)+"ageShow"])}[t(1801)+t(1128)+t(1865)](){let n=t;e[n(858)](e[n(1199)],e[n(701)])?(this._isBrowser&&window[n(1181)+n(564)+n(398)](e[n(1752)],this[n(1699)+"nLine"]),this._isBrowser&&window[n(1181)+n(564)+n(398)](e.mqkkY,this[n(1699)+n(1184)]),this._isBrowser&&window[n(1181)+n(564)+n(398)](e[n(710)],this[n(647)+n(408)]),this[n(425)+"er"]&&window[n(1181)+n(564)+"ner"](e[n(1046)],this[n(647)+"ageShow"])):this._qosDB?.del(_0x2aac82[n(733)+"id"])}[t(647)+"ageHide"](n){let s=t;if(s(510)===e[s(1791)])!n[s(857)+"d"]&&(this[s(425)+"er"]&&window["removeEventListe"+s(398)](e[s(710)],this._handlePageHide),this._isBrowser&&window[s(1181)+s(564)+s(398)](e.xDnhL,this[s(647)+"ageShow"]),this[s(1461)]()),this._isBrowser&&window[s(1181)+"entListener"](e.SUijY,this[s(1699)+s(1296)]),this[s(425)+"er"]&&window[s(1181)+s(564)+s(398)](e.mqkkY,this[s(1699)+s(1184)]);else return{bytes:_0x17b8a4,offset:0,limit:_0x1acab1[s(1390)]}}[t(647)+t(493)](n){let s=t;n[s(857)+"d"]&&(this[s(430)+"orOnline"]()&&(!this[s(1839)]||e[s(359)](this[s(1839)][s(1241)+"te"],this[s(1158)])||e[s(374)](this._ws[s(1241)+"te"],this.CONNECTING))&&this[s(1699)+s(1296)](),this[s(425)+"er"]&&window[s(765)+s(1865)]("online",this[s(1699)+s(1296)]),this[s(425)+"er"]&&window.addEventListener(s(1113),this[s(1699)+s(1184)]))}async[t(884)+t(1443)](n){let s=t,{fpID:l,deviceID:x,bddID:m,ttwID:w,accessKey:S,aID:p,customParams:O={},enableAutoAck:L,enableQoS:F,QoSLevel:W,env:K}=this._options,_e,Fe,yt;this._isBrowser||this[s(862)+"X"]||this[s(1077)+"T"]?(_e=location&&e.qwjHR(e.lySPm,location[s(1718)])?"wss://":e[s(1465)],Fe=n[s(772)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),yt=/^wss(.*:\/\/)/[s(896)](n)?n:""+_e+Fe):(_e=e[s(1524)],Fe=n[s(772)](/(^http)((?:[s]*:\/\/))/,""),yt=/(^ws)((?:[s]*:\/\/))/[s(896)](Fe)?Fe:""+_e+Fe);let Ht=m?e[s(748)]:w?"ttwid":s(1257)+"d",kl=m||w||x;if(e[s(879)](!kl,!Ht))throw new Error("please p"+s(679)+s(315)+s(439)+s(1048));let Um=typeof O=="function"?await e.DxCcE(O):O,Gm=K?e[s(1182)](om,K.xUseEnv,K[s(950)]):{},Ra=Object[s(1782)]({device_platform:e[s(734)],version_code:e.NMvWw,access_key:S,fpid:l,aid:p,[Ht]:kl,xsack:L?1:0,xaack:L?1:0,xsqos:F?1:0,qos_level:F?W:void 0,qos_sdk_version:2,...Gm},Um),Hm=Object.keys(Ra)[s(414)]((Da,Pa)=>Ra[Pa]!==void 0?""+Da+(Da?"&":"?")+Pa+"="+Ra[Pa]:Da,"");return yt+s(892)+Hm}async[t(1600)](){let n=t;if(!(this["_connect"+n(1736)]||this["_readyCl"+n(943)])){this._connectLock=!0;try{let s=this[n(816)+"tManager"]?.[n(331)+n(314)+n(1757)+n(904)+"tries"](),{timeoutInterval:l}=this[n(1696)];if(s){let m=this["_endpoin"+n(1051)]?.["getCurre"+n(667)+"nt"](),w=this[n(816)+n(1051)]?.[n(1452)+n(1820)+n(1724)+n(1621)+n(1168)](),S=this[n(816)+n(1051)]?.[n(1795)+n(667)+n(324)+n(1458)]();if(w){let p=n(798)+m+(n(742)+n(1811)+n(1730)+n(1341)+n(1435)+n(1779)+n(649))+w+(n(758)+"y"),O=lt(e[n(1635)],{message:p,code:cn[n(1024)+"IES_ERROR"]});this[n(1611)](p),this[n(1371)+n(376)+"ent"](O),this[n(342)]=await this["_generat"+n(1443)](w),this[n(1611)]("connect "+w+" "+S+n(1657)),this[n(1315)+n(1560)+"rs"]()}else{let p=n(798)+m+(n(742)+", max re"+n(1730)+n(958));this[n(1611)](p),this[n(1371)+"hErrorEvent"](e[n(683)](lt,e.fERWV,{message:p,code:cn[n(1024)+n(1229)+"R"]}));return}}else{let m=this[n(816)+n(1051)]?.[n(1795)+n(667)+"ntAndUpd"+n(1010)](),w=this["_endpoin"+n(1051)]?.[n(1795)+n(667)+n(324)+n(1458)]();this._url=await this[n(884)+n(1443)](e[n(1835)](m,"")),this[n(1611)](n(798)+m+" "+w+n(1657)),this[n(1315)+n(1560)+"rs"]()}if(this[n(570)])this[n(570)]=!1;else{let m=Ea(e.UYaLG,{message:e[n(916)]});this["onStartR"+n(1358)]&&this[n(1327)+n(1358)](m)}let x=this[n(816)+n(1051)]?.[n(1795)+n(667)+n(324)+n(1458)]()||0;e[n(1278)](x,1)&&await this[n(1424)](e[n(1753)](x,1)),this[n(1611)](n(1487)+n(1528)+this[n(342)]+(n(1069)+"ls: ")+this[n(1680)+"ls"]),this._ws=rm({url:this[n(342)],protocols:[this._protocols],headers:this[n(1696)]["miniProg"+n(472)+"s"][n(1597)+n(1106)]},this[n(1696)].ws),(this._isBrowser||this[n(1732)+"r"])&&this[n(1839)]&&(this._ws[n(533)+"pe"]=this._binaryType),this[n(1831)+n(1533)](),this[n(1600)+n(1725)+"utId"]=e.XGISE(setTimeout,this[n(1880)+"ut"].bind(this),l)}catch(s){throw this["_connect"+n(1736)]=!1,s}}}[t(1804)+t(461)](){let n=t;if(e[n(1433)](e[n(1428)],n(825)))e[n(436)](clearTimeout,this[n(1600)+"ionTimeo"+n(984)]),this[n(1600)+"ionTimeo"+n(984)]=null;else{let s=_0x5af683[n(981)]>>>0,l=e.RQagB(e[n(1543)](e[n(1546)](_0x18dbf5.low,28),e.fQczt(_0x2d9ece[n(1714)],4)),0),x=e.JBqVx(_0xed482c[n(1714)],24),m=e[n(545)](0,x)?l===0?e[n(1479)](s,16384)?e[n(826)](s,128)?1:2:s<2097152?3:4:l<16384?e.ylsAL(l,128)?5:6:e[n(921)](l,2097152)?7:8:e[n(1005)](x,128)?9:10,w=e[n(1845)](_0x39803c,_0x2930e1,m),S=_0x4cb60c[n(1740)];switch(m){case 10:S[e.clBjf(w,9)]=x>>>7&1;case 9:S[e[n(474)](w,8)]=e[n(1150)](9,m)?e[n(721)](128,x):e[n(1641)](127,x);case 8:S[e[n(1630)](w,7)]=e[n(1623)](8,m)?e.weFtJ(l>>>21,128):e[n(1312)](e[n(1394)](l,21),127);case 7:S[e.IiyKt(w,6)]=e[n(1595)](7,m)?e[n(566)](e.QFHrz(l,14),128):e.vPkNm(l,14)&127;case 6:S[e[n(509)](w,5)]=e[n(1577)](6,m)?e[n(1309)](e.jDwBq(l,7),128):e[n(699)](l>>>7,127);case 5:S[e[n(1226)](w,4)]=e.WXTlL(5,m)?e.JYGlW(128,l):e[n(1129)](127,l);case 4:S[e[n(1471)](w,3)]=e.ASUGj(4,m)?e[n(993)](s>>>21,128):e[n(1319)](e[n(1509)](s,21),127);case 3:S[w+2]=m!==3?e[n(709)](e[n(1374)](s,14),128):e[n(1647)](e[n(1394)](s,14),127);case 2:S[e[n(1236)](w,1)]=e[n(329)](2,m)?e.weFtJ(e[n(442)](s,7),128):e[n(485)](e[n(669)](s,7),127);case 1:S[w]=m!==1?128|s:e[n(1412)](127,s)}}}["_clearPi"+t(1215)](){let n=t,s={mrDzJ:function(l,x){return e.cESGp(l,x)},KGmWh:function(l,x){return e[j(1456)](l,x)}};if(e[n(1240)]!==n(434))e[n(1802)](clearTimeout,this[n(1483)+n(296)+"Id"]),clearTimeout(this[n(1200)+n(301)+n(1642)]),this[n(1483)+n(296)+"Id"]=null,this["_reconne"+n(301)+n(1642)]=null;else return jUIQJm.mrDzJ(1e4,_0x47afed.now())+_0x37d970[n(494)](jUIQJm.KGmWh(1e4,_0x55ed53[n(1022)]()))}[t(1611)](...n){let s=t;this[s(1696)][s(1882)]&&console[s(1584)][s(800)](console,[e[s(1810)],...n])}[t(962)+t(831)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:x,reconnectIntervalGrowFactor:m}=this[s(1696)],w=e.sICsK(l,Math[s(1132)](m,e[s(713)](n,1)));return e.UuKSU(w,x)?x:w}[t(1109)](){let n=t;if(this._ws&&this._ws[n(1241)+"te"]===this[n(939)+"NG"]){this[n(967)+n(1215)](),this[n(1483)+n(296)+"Id"]=setTimeout(this[n(1109)][n(815)](this),this[n(1696)][n(368)+n(1466)]);return}if(!this[n(1839)]||this[n(1839)][n(1241)+"te"]!==this[n(1158)])return void this[n(1065)+n(1358)]();this[n(1839)]&&this._ws[n(948)]("hi"),this[n(1200)+"ctTimeoutId"]=e[n(1640)](setTimeout,this[n(1065)+n(1358)+n(1303)][n(815)](this),this._options[n(476)+n(851)+n(706)])}[t(1065)+t(1358)+t(1303)](){let n=t;this[n(1770)+n(610)]?.addCount(),this[n(541)](e[n(1027)],e[n(1828)]),this[n(1770)+n(610)]?.[n(865)+n(750)+"nt"]()?this[n(1065)+"econnect"]():this[n(1109)]()}_navigatorOnline(){let n=t;if(e.hhtTY(e[n(462)],e[n(378)]))this[n(932)+"lTimeoutId"]=null,this._interval=36e5,this[n(1488)]=e[n(583)](_0x4a1070,"qos",n(733)+"id");else return this[n(1077)+"T"]||this._isMiniWX?this[n(1346)+n(759)+n(1287)]:(this[n(425)+"er"]||this._isWorker)&&this[n(1696)][n(1555)+n(793)+n(1004)]?navigator[n(1376)]:!0}[t(1065)+t(1358)](){let n=t;!this["_navigat"+n(1391)]()||this["_readyCl"+n(943)]||(this[n(816)+n(1051)]?.[n(608)+n(1255)+"fig"](),this[n(1770)+"sCounter"]?.["resetCou"+n(1870)](),this[n(1839)]?this[n(972)+"ect"](1001,e[n(802)],!0):this[n(1600)]())}[t(1006)+t(1021)+"ange"](){let n=t;this[n(1077)+"T"]?tt[n(1196)+n(1110)+n(528)](({isConnected:s})=>{let l=n;this[l(1346)+"igatorOn"+l(1287)]=s,s?this[l(1699)+l(1296)]():this["_handleO"+l(1184)]()}):this[n(862)+"X"]&&wx[n(1196)+"kStatusChange"](({isConnected:s})=>{let l=n;this[l(1346)+l(759)+l(1287)]=s,s?this[l(1699)+l(1296)]():this["_handleO"+l(1184)]()})}_wait(n){let s=t,l={cXOir:function(x,m){return e[j(1272)](x,m)},EEjSp:function(x,m){return e[j(1620)](x,m)},VUUyV:function(x,m){return e.uzxWb(x,m)},vjXWp:e[s(1522)],npYND:e.Mtsaw,CJXus:e[s(1042)],HTHSF:s(621),ZcxMR:function(x,m,w,S){return e[s(1594)](x,m,w,S)}};if(e.RGKzh(e[s(762)],e[s(762)]))return new Promise(x=>{let m=s;e[m(480)](setTimeout,x,this[m(962)+m(831)+"e"](n))});if(JJDLBZ[s(562)](_0x3f34f9[s(1607)],_0x1c734b)){let x=JJDLBZ[s(1708)](this[s(1696)][s(956)+s(426)],_0x1fe6ac)?{force:!!this[s(1696)][s(956)+s(426)][s(1111)],encoding:this[s(1696)][s(956)+s(426)][s(752)]?this[s(1696)][s(956)+s(426)].encoding[s(772)](/\s/g,"")[s(479)+s(730)]():""}:{force:!1,encoding:this._options["payloadE"+s(426)]?this._options[s(956)+s(426)][s(772)](/\s/g,"")[s(479)+s(730)]():""},m=_0x48856c[s(956)+"ncoding"]?_0x43ddbe[s(956)+s(426)].replace(/\s/g,"")[s(479)+s(730)]():"",w=JJDLBZ[s(1722)](this[s(1696)][s(294)+s(1596)],_0x22c487)?{force:!!this[s(1696)][s(294)+s(1596)].force,type:this[s(1696)]["payloadT"+s(1596)][s(1007)]?this[s(1696)][s(294)+s(1596)][s(1007)].replace(/\s/g,"")["toLowerC"+s(730)]():""}:{force:!1,type:this[s(1696)][s(294)+s(1596)]?this[s(1696)][s(294)+"ype"][s(772)](/\s/g,"")[s(479)+s(730)]():""},S=_0x5ca146["payloadT"+s(1596)]?_0x41a2d5[s(294)+s(1596)][s(772)](/\s/g,"")[s(479)+s(730)]():"",p=w.force?w[s(1007)]:S||w.type,O=x.force?x[s(752)]:m||x[s(752)],L=[JJDLBZ.vjXWp,JJDLBZ[s(525)],s(1059)+"ion/json"+s(1824)+s(645),s(882)],F=[JJDLBZ[s(1499)],JJDLBZ[s(531)]];this._options[s(860)+s(375)+s(1850)+"ad"]&&L[s(1477)](p)&&(!O||F[s(1477)](O))?_0x316515[s(790)+"oad"]=JJDLBZ[s(1025)](_0xdc7ff,_0x5cca0f.payload,0,_0x32f816[s(1607)][s(1117)+"th"]):_0x2aa4d2.textPayload=""}else _0x237fc0[s(790)+s(347)]=""}[t(972)+t(782)](n=1e3,s="",l=!1){let x=t;this[x(1839)]&&this["_destroy"+x(1473)+"t"](n,s,l)}[t(1880)+"ut"](){let n=t,s=this[n(816)+n(1051)]?.["getCurre"+n(667)+"nt"]();this[n(1611)](n(798)+s+n(742)),this[n(972)+n(782)](1001,e[n(1554)],!0)}_sendAck(n){let s=t,l=e[s(1127)](Gt,n);this._ws&&this[s(1839)][s(1241)+"te"]===this[s(1158)]&&(this._ws&&this[s(1839)].send(l),this._debug(s(968),n))}[t(1315)+t(1560)+"rs"](){let n=t;this[n(1839)]&&(this._ws["removeEv"+n(564)+n(398)](n(1576),this[n(1209)]),this[n(1839)]["removeEv"+n(564)+n(398)](e[n(1156)],this[n(997)]),this[n(1839)][n(1181)+"entListe"+n(398)](e[n(1634)],this[n(936)+"ge"]),this._ws[n(1181)+n(564)+"ner"](e[n(1635)],this[n(1848)]))}["_addWsLi"+t(1533)](){let n=t,s="4|1|3|2|0".split("|"),l=0;for(;;){switch(s[l++]){case"0":this._ws[n(765)+n(1865)](e[n(1635)],this[n(1848)]);continue;case"1":this[n(1839)][n(765)+n(1865)](e.AEBPt,this[n(1209)]);continue;case"2":this[n(1839)][n(765)+n(1865)](e[n(1634)],this[n(936)+"ge"]);continue;case"3":this[n(1839)][n(765)+n(1865)](e[n(1156)],this._onClose);continue;case"4":if(!this[n(1839)])return;continue}break}}[t(946)+t(1660)](n=1e3,s=""){let l=t,x={KcOOe:function(m,w){return m!=w},RodqF:e[l(996)],ZStHJ:function(m,w){return e[l(1344)](m,w)},HSMWc:function(m,w){return e[l(855)](m,w)},OoKSA:e[l(444)],HfOZM:function(m,w){return e.ezMDZ(m,w)},yQWPC:e[l(1522)]};try{if(e.MGDga!==e[l(895)])try{return fcaQax.KcOOe(fcaQax[l(1552)],typeof _0x55cd30)&&(_0x1e3633 instanceof _0xf822ad||_0x503294[l(1656)]&&fcaQax[l(1097)](_0x27cdf4[l(1656)],_0x41b9cd))||fcaQax[l(1685)](l(882),typeof _0x4d2131)?"":(_0x4109c1[l(334)](_0x4d681c),fcaQax[l(880)])}catch{return fcaQax.HfOZM(fcaQax[l(1552)],typeof _0x56e4a9)?fcaQax[l(306)]:""}else this[l(1839)]&&this[l(1839)][l(1461)](n,s)}catch{}}[t(500)+"WebSocket"](n=1e3,s="",l=!1){let x=t;if(this[x(967)+x(1215)](),this["_clearTi"+x(461)](),this[x(1315)+x(1560)+"rs"](),this[x(946)+"nceClose"](1e3,s),this["_connect"+x(1736)]=!1,l&&this[x(430)+x(1391)]()&&!this["_readyCl"+x(943)]){if(this[x(816)+"tManager"]?.["checkRea"+x(876)+"es"]()){let w=this[x(816)+x(1051)]?.[x(1795)+x(667)+"nt"]();this[x(1371)+"hCloseEv"+x(1343)](e[x(899)](_t,e[x(1156)],{code:1006,reason:x(798)+w+(x(742)+", max retries re"+x(958)),wasClean:!0}))}else{let w=this[x(1696)][x(1876)+x(1520)+x(615)](n,s);this[x(1371)+x(1256)+x(1343)](_t(e.hebah,{code:n,reason:s,wasClean:!0,willReconnect:w})),w&&this[x(1600)]()}return}this[x(430)+x(1391)]()||this["_readyCl"+x(943)]?this[x(1371)+x(1256)+x(1343)](e[x(707)](_t,x(1461),{code:n,reason:e[x(1133)]})):this[x(1371)+"hCloseEv"+x(1343)](e.fHolR(_t,e[x(1156)],{code:1006,reason:e[x(544)]})),this._ws=null,this["_endpoin"+x(1051)]?.[x(608)+x(1255)+x(869)](),this[x(1770)+x(610)]?.resetCounter()}[t(1371)+"hOpenEvent"](n){let s=t;this[s(541)](e[s(1474)],n),this[s(1029)]&&this.onopen(n)}["_dispatchMessage"+t(933)](n){let s=t;this.emit(s(551),n),this.onmessage&&this.onmessage(n)}[t(1371)+t(1386)+t(1223)](n){let s=t;this.emit(e[s(1149)],n),this["onReceiv"+s(1121)]&&this[s(1681)+"eAck"](n)}["_dispatc"+t(376)+t(1343)](n){let s=t;this[s(541)](s(1459),n),this[s(573)]&&this[s(573)](n)}[t(1371)+t(1256)+t(1343)](n){let s=t;e[s(1467)](e[s(1013)],e[s(435)])?(this.emit(s(1461),n),this.onclose&&this[s(1482)](n)):(this._DBName=_0x3a6ce9,this[s(1368)]=_0x111a0e,this[s(1488)]=_0xfa755?_0x38779a:_0x5c8dc5?_0x2b254d:null)}get binaryType(){let n=t;return this[n(1839)]?this[n(1839)][n(533)+"pe"]:this[n(926)+n(1596)]}set[t(533)+"pe"](n){let s=t;this[s(926)+s(1596)]=n,this._ws&&(this[s(1839)].binaryType=n)}get retryCount(){let n=t;return this[n(816)+"tManager"]?.["getCurrentEndpointTriesC"+n(1458)]()||0}get[t(1663)+t(1118)](){let n=t,s={DYAOz:e[n(1474)],cTVOY:e[n(1156)]};return this[n(428)+"Queue"][n(414)]((x,m)=>{let w=n;if(e[w(1581)]!==e[w(1581)]){let S=(w(823)+"3")[w(1598)]("|"),p=0;for(;;){switch(S[p++]){case"0":this[w(1839)][w(1181)+w(564)+"ner"](w(551),this[w(936)+"ge"]);continue;case"1":this[w(1839)][w(1181)+w(564)+w(398)](nxudId.DYAOz,this[w(1209)]);continue;case"2":this[w(1839)].removeEventListener(nxudId[w(1507)],this[w(997)]);continue;case"3":this._ws[w(1181)+w(564)+w(398)](w(1459),this[w(1848)]);continue;case"4":if(!this._ws)return;continue}break}}else return x+=m&&m[w(1117)+"th"]||0,x},0)+(this._ws?this[n(1839)][n(1663)+n(1118)]:0)}get extensions(){let n=t;return this[n(1839)]?this[n(1839)][n(561)+"ns"]:""}get[t(1718)](){let n=t;return this._ws?this[n(1839)][n(1718)]:""}get[t(1241)+"te"](){let n=t,s={POgJL:function(l){return l()}};if(e[n(487)](e.sDbVY,e[n(590)]))return this[n(1839)]?this[n(1839)][n(1241)+"te"]:this[n(1696)][n(417)+n(431)]?this[n(939)+"NG"]:this.CLOSED;_0x437502(),qRmUGx[n(386)](_0x421bd2)}get[t(1134)](){let n=t;return this[n(1839)]?this[n(1839)][n(1134)]:this._url}[t(1461)](n=1e3,s){let l=t,x=(l(507)+l(1861))[l(1598)]("|"),m=0;for(;;){switch(x[m++]){case"0":this[l(1804)+l(461)]();continue;case"1":this[l(500)+"WebSocket"](n,s);continue;case"2":this[l(486)+"ger"]?.[l(914)]();continue;case"3":this[l(1801)+l(1128)+l(1865)]();continue;case"4":if(e.xdYED(this[l(1839)][l(1241)+"te"],this[l(1155)])||e[l(675)](this[l(1839)][l(1241)+"te"],this[l(1575)]))return void this[l(1611)](e[l(1786)]);continue;case"5":this[l(967)+"ngTimer"]();continue;case"6":this[l(885)+l(943)]=!0;continue;case"7":if(!this[l(1839)])return void this[l(1611)](e[l(1631)]);continue}break}}async[t(948)](n,s){let l=t;if(e.WWDCr(null,n))throw new Error(l(307)+l(354)+l(1397)+l(1170)+"a must b"+l(1218)+"ng or an"+l(1874)+l(1331));e[l(689)](e.kgNSe,typeof n)&&(n=JSON.stringify(n)),e[l(1729)](e[l(996)],typeof n)&&!e[l(1432)](n,ArrayBuffer)&&!(n[l(1656)]&&e[l(478)](n[l(1656)],ArrayBuffer))&&(n=JSON[l(1126)+"y"](n));let x=await e.LfmaP(El,n),m=e[l(1316)](sm,n),{method:w=0,service:S=this[l(1696)][l(1090)],logID:p=this._options["logIDGen"+l(1370)](),headers:O=this[l(1696)][l(685)],payloadEncoding:L=this[l(1696)][l(956)+l(426)],payloadType:F=this._options["payloadT"+l(1596)],logIDNew:W=this[l(1696)][l(691)+"Config"][l(1306)+l(1503)+l(1401)+"ew"]?i(this[l(1696)]["logIDNew"+l(797)].userIp):""}=e[l(1233)](s,{});if(!S)throw new Error(l(307)+l(354)+l(1565)+l(724));let K={SeqID:xe[l(697)+"er"](this[l(611)]++),LogID:xe.fromNumber(p),service:S,method:w,headers:O,payloadEncoding:e.HeBec(L,Object)?L[l(752)]?L[l(752)]:"":L,payloadType:e.uOntp(F,Object)?F[l(1007)]?F[l(1007)]:m:F||m,payload:x,LogIDNew:W},_e=e[l(1789)](Gt,K);if(this[l(1839)]&&e[l(1078)](this[l(1839)].readyState,this[l(1158)]))this[l(1839)]&&this._ws.send(_e),this._debug(l(1276),K);else if(e[l(1605)](this["_message"+l(1731)][l(1390)],this[l(1696)][l(1493)+l(343)+"ength"]))this[l(428)+l(1731)][l(1489)](_e),this[l(1611)](e.WStYC,K);else if(e[l(1719)](e[l(636)],e[l(636)]))this[l(428)+l(1731)][l(1189)](),this[l(428)+"Queue"][l(1489)](_e);else{let Fe=_0x38e597[l(1079)+"g"](0,e[l(1753)](4,_0x54049e[_0x4acdda][l(1390)])),yt=Fe[l(504)](_0x333d58[_0x4d7af1]);_0x4b844b.push(yt)}return{seqID:this[l(611)],logID:p,logIDNew:W}}async[t(1876)+"t"](n){let s=t,{url:l}=n||{},x=Array[s(702)](l)?l:e[s(996)]==typeof l?[l]:[];n&&Object[s(1782)](this[s(1696)],n),x&&x[s(1390)]?this["_endpoin"+s(1051)]=new wl(x,this[s(1696)][s(1734)+"es"]):this[s(816)+"tManager"]?.[s(608)+s(1255)+s(869)](),this[s(1770)+s(610)]?.[s(1706)+s(1870)](this[s(1696)][s(1564)+s(1161)]),this._readyClosed=!1,this[s(1839)]&&e[s(1834)](this[s(1839)][s(1241)+"te"],this[s(1155)])?this[s(972)+s(782)](1e3,e[s(1414)],!0):s(596)!==e[s(1145)]?(this[s(541)](e[s(1474)],_0x7da20d),this[s(1029)]&&this[s(1029)](_0x5eaa79)):(this._isInit=!0,this[s(1600)]())}async[t(671)](){let n=t,s={esQfu:function(l,x){return e.uBiqE(l,x)}};if(e[n(497)]===e[n(811)])return BenLoU[n(1266)](_0x3c62ee.offset,_0x3c9e07.limit);!this[n(1600)+n(1736)]&&(this[n(816)+n(1051)]?.[n(608)+n(1255)+n(869)](),this[n(1770)+"sCounter"]?.resetCounter(),this["_readyCl"+n(943)]=!1,this[n(570)]=!0,this._connect())}[t(765)+t(1865)](n,s){this.on(n,s)}[t(1360)+t(933)](n){let s=t,l={AYKIG:function(x,m){return e[j(653)](x,m)},YiMaZ:function(x,m){return e[j(1294)](x,m)},OCrPd:function(x,m){return e[j(536)](x,m)},gnkVP:function(x,m){return e[j(1001)](x,m)},GDbrd:function(x,m){return e[j(1475)](x,m)},enGph:function(x,m){return x|m},fMXnk:function(x,m){return x+m}};if(e[s(622)](e.oPOIe,e[s(1267)])){let{type:x}=n;this[s(541)](x,n)}else{let x=new _0xd58edc(NnLuYF[s(1451)](NnLuYF[s(1547)](_0x5d3b56[_0x590c51+4]<<24,NnLuYF.OCrPd(_0x3e98e2[NnLuYF.gnkVP(_0x8db9ae,5)],16))|NnLuYF.GDbrd(_0xb49dc1[NnLuYF.gnkVP(_0x593df1,6)],8),_0x2f7d24[NnLuYF.gnkVP(_0x2958ec,7)]),NnLuYF[s(1451)](NnLuYF[s(496)](NnLuYF[s(355)](_0x286b6e[NnLuYF[s(794)](_0x2faa5e,0)],24)|NnLuYF[s(355)](_0x1f8dd1[NnLuYF[s(966)](_0x3c0325,1)],16),NnLuYF.OCrPd(_0x3adc2d[_0x19b942+2],8)),_0x3460dd[NnLuYF[s(794)](_0x488c2a,3)]),!0);return _0x3fccc1+=8,{value:x,offset:NnLuYF[s(966)](_0x4a4de8,8)}}}[t(1181)+t(564)+t(398)](n,s){this[t(1166)](n,s)}[t(773)](){let n=t,s={owPuC:e[n(1323)],DZTSi:e[n(1056)],yvgjX:"ping_onc"+n(949)+"t",RBiqP:function(l,x){return e[n(1765)](l,x)},KLFGu:e[n(1773)],oguuF:e.Dxakf,zGApP:function(l,x){return l(x)},IihJU:e[n(1361)],yAmZa:e[n(1527)],dpcgO:function(l,x,m){return e[n(480)](l,x,m)}};if(e.icLLa(e[n(305)],n(1683)))return new Promise((l,x)=>{let m=n;if(s[m(1430)](s.IihJU,s[m(1091)])){let w=_0x384304(_0x4597ad,1);_0x34bd66[m(1740)][w]=_0x568ca3}else{this[m(967)+"ngTimer"](),this[m(1483)+m(296)+"Id"]=s.dpcgO(setTimeout,this._ping[m(815)](this),this[m(1696)][m(368)+m(1466)]);let w=()=>{let p=m;l(s.owPuC),this.off(s[p(1329)],w),this[p(1166)](s[p(1353)],S)},S=()=>{let p=m;if(s[p(1430)](s[p(1425)],s[p(1881)])){this[p(967)+p(1215)](),this[p(1483)+p(296)+"Id"]=_0x2a0324(this._ping[p(815)](this),this[p(1696)].pingInterval);return}else s[p(560)](x,"timeout"),this.off(s.DZTSi,w),this[p(1166)](s[p(1353)],S)};this.on(s[m(1329)],w),this.on(s[m(1353)],S),this._ping()}});++_0x2231c5,_0x5413a3+=4}}})(),Ae[N(1283)+N(1851)]=Pe[N(1283)+N(1851)],Ae[N(1221)+N(475)]=Pe[N(1221)+N(475)],Ae[N(632)+"e"]=Pe.ErrorCode,Ae[N(933)]=Pe[N(933)],Ae[N(1648)]=Pe[N(1648)],Ae[N(1418)+N(470)+N(1087)]=Pe[N(1418)+"MessageEvent"],Ae[N(470)+"vent"]=Pe[N(470)+N(1087)],Ae[N(1523)+"t"]=Pe[N(1523)+"t"],Ae[N(1265)+N(1794)]=Pe[N(1265)+N(1794)],Ae[N(1122)+N(1851)]=Pe[N(1122)+N(1851)],Ae[N(1409)+"rorEvent"]=Pe[N(1409)+"rorEvent"],Ae[N(1264)+N(1826)+"nt"]=Pe[N(1264)+"ssageEvent"],Ae[N(729)+"enEvent"]=Pe[N(729)+"enEvent"],Ae[N(806)+N(1448)+N(1087)]=Pe[N(806)+"connectE"+N(1087)],Ae[N(1879)+"rame"]=Pe[N(1879)+"rame"],Ae[N(1084)+N(1545)]=Pe["encodeFr"+N(1545)];for(Qo in Pe)["CustomCl"+N(1851),N(1221)+N(475),"ErrorCode",N(933),"FWS","Frontier"+N(470)+"vent",N(470)+N(1087),N(1523)+"t",N(1265)+N(1794),"createCl"+N(1851),N(1409)+"rorEvent",N(1264)+N(1826)+"nt",N(729)+N(872),N(806)+"connectE"+N(1087),N(1879)+"rame","encodeFr"+N(1545)][N(1705)](Qo)===-1&&(Ae[Qo]=Pe[Qo]);var Qo;Object[N(1023)+N(1536)](Ae,N(1212)+"le",{value:!0})});import{existsSync as e1,openSync as t1}from"node:fs";import{mkdir as n1}from"node:fs/promises";import{dirname as r1}from"node:path";import{fileURLToPath as i1}from"node:url";function o1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Zd(t=Z()){return e1(t.libEntry)?t.libEntry:i1(new URL("../index.ts",import.meta.url))}async function fp(t={}){let e=t.paths??Z(),r=t.entryOverride??Zd(e),i=o1(e,process.env.COZE_BRIDGE_LOG_MODE);await n1(r1(i),{recursive:!0});let o=t1(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,[ds]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return s1.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var s1,ds,la=nt(()=>{"use strict";Xt();te();Re();s1=G("spawn-daemon"),ds="COZE_BRIDGE_DAEMON"});import{spawn as r2}from"node:child_process";import{mkdir as i2,unlink as s2,writeFile as o2}from"node:fs/promises";import{dirname as a2,join as c2}from"node:path";function Xr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function d2(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Xr(r)}</key>
21
+ <string>${Xr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function _I(t,e){return new Promise((n,i)=>{let o=fI(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?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Zr,ds,fa,al,Cp=Xe(()=>{"use strict";ne();Zr=G("supervisor.launchd"),ds="ai.coze.bridge",fa=_I,al={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function l2(t,e){return new Promise((r,i)=>{let o=r2(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 Yr,fs,ma,sl,Np=nt(()=>{"use strict";te();Yr=G("supervisor.launchd"),fs="ai.coze.bridge",ma=l2,sl={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>${ds}</string>
31
+ <string>${fs}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Yr(t.nodeBin)}</string>
35
- <string>${Yr(t.entry)}</string>
34
+ <string>${Xr(t.nodeBin)}</string>
35
+ <string>${Xr(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>${Yr(t.logFile)}</string>
45
+ <string>${Xr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Yr(t.logFile)}</string>${wI(t.env)}
47
+ <string>${Xr(t.logFile)}</string>${d2(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return mI(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await hI(gI(i),{recursive:!0}),await pI(i,this.renderConfig(t),"utf8"),Zr.info("plist written",{plistPath:i,activate:n}),!n)return;await fa("launchctl",["unload","-w",i]).catch(c=>Zr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await fa("launchctl",["load","-w",i]),Zr.info("launchd job loaded",{label:ds});let o=process.getuid?.()??0;await fa("launchctl",["kickstart","-k",`gui/${o}/${ds}`]),Zr.info("launchd job kickstarted",{label:ds,uid:o})},async uninstall(t){let e=this.configPath(t);await fa("launchctl",["unload","-w",e]).catch(n=>Zr.warn("launchctl unload failed (ignored)",{err:String(n)})),await xI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Zr.info("launchd job removed",{plistPath:e})}}});import{spawn as yI}from"node:child_process";import{mkdir as EI,unlink as bI,writeFile as vI}from"node:fs/promises";import{dirname as SI,join as Pp}from"node:path";function xa(t,e){return t.isRoot?e:["--user",...e]}function AI(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function pa(t,e){return new Promise((n,i)=>{let o=yI(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?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ha,Xr,II,cl,Dp=Xe(()=>{"use strict";ne();ha=G("supervisor.systemd"),Xr="coze-bridge.service",II="/etc/systemd/system";cl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return c2(t.homeDir,"Library","LaunchAgents",`${fs}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await i2(a2(i),{recursive:!0}),await o2(i,this.renderConfig(t),"utf8"),Yr.info("plist written",{plistPath:i,activate:r}),!r)return;await ma("launchctl",["unload","-w",i]).catch(c=>Yr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ma("launchctl",["load","-w",i]),Yr.info("launchd job loaded",{label:fs});let o=process.getuid?.()??0;await ma("launchctl",["kickstart","-k",`gui/${o}/${fs}`]),Yr.info("launchd job kickstarted",{label:fs,uid:o})},async uninstall(t){let e=this.configPath(t);await ma("launchctl",["unload","-w",e]).catch(r=>Yr.warn("launchctl unload failed (ignored)",{err:String(r)})),await s2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Yr.info("launchd job removed",{plistPath:e})}}});import{spawn as u2}from"node:child_process";import{mkdir as f2,unlink as x2,writeFile as h2}from"node:fs/promises";import{dirname as p2,join as Mp}from"node:path";function wa(t,e){return t.isRoot?e:["--user",...e]}function g2(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function _a(t,e){return new Promise((r,i)=>{let o=u2(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 ga,Qr,m2,ol,Bp=nt(()=>{"use strict";te();ga=G("supervisor.systemd"),Qr="coze-bridge.service",m2="/etc/systemd/system";ol={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
- ${AI(t.env)}
62
+ ${g2(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Pp(II,Xr):Pp(t.homeDir,".config","systemd","user",Xr)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await EI(SI(i),{recursive:!0}),await vI(i,this.renderConfig(t),"utf8"),ha.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await pa("systemctl",xa(t,["daemon-reload"])),await pa("systemctl",xa(t,n?["enable","--now",Xr]:["enable",Xr])),ha.info("systemd unit enabled",{unitName:Xr,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await pa("systemctl",xa(t,["disable","--now",Xr])).catch(n=>ha.warn("systemctl disable failed (ignored)",{err:String(n)})),await bI(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await pa("systemctl",xa(t,["daemon-reload"])).catch(()=>{}),ha.info("systemd unit removed",{unitPath:e})}}});import{spawn as kI}from"node:child_process";import{join as TI}from"node:path";function Op(t,e){return new Promise((n,i)=>{let o=kI(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?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var dl,ga,ll,Lp=Xe(()=>{"use strict";ne();dl=G("supervisor.taskscheduler"),ga="CozeBridge",ll={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Mp(m2,Qr):Mp(t.homeDir,".config","systemd","user",Qr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await f2(p2(i),{recursive:!0}),await h2(i,this.renderConfig(t),"utf8"),ga.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await _a("systemctl",wa(t,["daemon-reload"])),await _a("systemctl",wa(t,r?["enable","--now",Qr]:["enable",Qr])),ga.info("systemd unit enabled",{unitName:Qr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await _a("systemctl",wa(t,["disable","--now",Qr])).catch(r=>ga.warn("systemctl disable failed (ignored)",{err:String(r)})),await x2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await _a("systemctl",wa(t,["daemon-reload"])).catch(()=>{}),ga.info("systemd unit removed",{unitPath:e})}}});import{spawn as w2}from"node:child_process";import{join as _2}from"node:path";function Fp(t,e){return new Promise((r,i)=>{let o=w2(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 al,ya,cl,zp=nt(()=>{"use strict";te();al=G("supervisor.taskscheduler"),ya="CozeBridge",cl={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,52 +86,55 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return TI(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 Op("schtasks",["/Create","/SC","ONLOGON","/TN",ga,"/TR",n,"/RU",t.userName,"/F"]),dl.info("task scheduler entry created",{task:ga,logFile:t.logFile})},async uninstall(t){await Op("schtasks",["/Delete","/TN",ga,"/F"]).catch(e=>dl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),dl.info("task scheduler entry removed",{task:ga})}}});var Np={};Ca(Np,{buildContext:()=>LI,getSupervisor:()=>PI,launchdSupervisor:()=>al,systemdSupervisor:()=>cl,taskSchedulerSupervisor:()=>ll});import{homedir as RI,userInfo as CI}from"node:os";function PI(t=process.platform){switch(t){case"darwin":return al;case"linux":return cl;case"win32":return ll;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function OI(){let t={};for(let e of DI){let n=process.env[e];n&&(t[e]=n)}return t}function LI(){let t=J();return{nodeBin:process.execPath,entry:Yd(t),logFile:t.logFile,homeDir:RI(),userName:CI().username,isRoot:process.getuid?.()===0,env:OI()}}var DI,Mp=Xe(()=>{"use strict";Re();oa();Cp();Dp();Lp();DI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();an();var Hl=G("acp-installer-warmup"),lm=["claude-code","codex"];async function Wl(t={}){let e=t.ensure??ur,i=(await Promise.allSettled(lm.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))})}fn();ne();import{readdir as Am}from"node:fs/promises";import{mkdir as $l,readFile as Sm,writeFile as Vl}from"node:fs/promises";import{join as Ba}from"node:path";var Im={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function fr(t,e,n){await $l(t,{recursive:!0});let i=Im[e],o=Ba(t,i);return await Vl(o,n??"","utf8"),o}async function Fa(t,e,n){let i=Ba(t,".claude");await $l(i,{recursive:!0});let o=Ba(i,"settings.local.json"),c={};try{let u=await Sm(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(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return c.permissions=d,await Vl(o,JSON.stringify(c,null,2),"utf8"),o}var Je=G("agent-detail-sync"),km=6e4,Tm=5*6e4,Es=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Am(n)}catch(o){Je.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}Je.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){Je.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Je.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Je.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){Je.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){Je.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await Ce(e,this.opts.paths);if(!i){Je.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){Je.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,Tm):km;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(o.agentId&&o.agentId!==e){Je.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"?(Je.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Je.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Je.debug("detail sync: no diff",{agentId:e});return}await Be(i,this.opts.paths),Je.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}),Je.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await fr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var ad=Ht(ku(),1);import{createHash as ly}from"node:crypto";import{lstat as ed,mkdir as td,readFile as po,readdir as h0,rm as nd,stat as x0,writeFile as rd}from"node:fs/promises";import{homedir as uy}from"node:os";import{dirname as fy,join as me,normalize as hy,relative as od,resolve as id,sep as p0}from"node:path";import{Readable as g0}from"node:stream";import{pipeline as m0}from"node:stream/promises";import Zm from"events";import Qe from"fs";import{EventEmitter as Fc}from"node:events";import lf from"node:stream";import{StringDecoder as Ym}from"node:string_decoder";import hf from"node:path";import Sr from"node:fs";import{dirname as lw,parse as uw}from"path";import{EventEmitter as _w}from"events";import _c from"assert";import{Buffer as qn}from"buffer";import*as Du from"zlib";import yw from"zlib";import{posix as mr}from"node:path";import{basename as Vw}from"node:path";import Qs from"fs";import Rt from"fs";import Uu from"path";import{win32 as a_}from"node:path";import $u from"path";import Tf from"node:fs";import S_ from"node:assert";import{randomBytes as Rf}from"node:crypto";import ie from"node:fs";import Ne from"node:path";import Cf from"fs";import co from"node:fs";import Ai from"node:path";import st from"node:fs";import P_ from"node:fs/promises";import no from"node:path";import{join as Gf}from"node:path";import it from"node:fs";import qf from"node:path";var Vm=Object.defineProperty,Jm=(t,e)=>{for(var n in e)Vm(t,n,{get:e[n],enumerable:!0})},Tu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Xm=t=>!!t&&typeof t=="object"&&(t instanceof $n||t instanceof lf||Qm(t)||ew(t)),Qm=t=>!!t&&typeof t=="object"&&t instanceof Fc&&typeof t.pipe=="function"&&t.pipe!==lf.Writable.prototype.pipe,ew=t=>!!t&&typeof t=="object"&&t instanceof Fc&&typeof t.write=="function"&&typeof t.end=="function",Wt=Symbol("EOF"),qt=Symbol("maybeEmitEnd"),xn=Symbol("emittedEnd"),As=Symbol("emittingEnd"),ci=Symbol("emittedError"),ks=Symbol("closed"),Ru=Symbol("read"),Ts=Symbol("flush"),Cu=Symbol("flushChunk"),gt=Symbol("encoding"),gr=Symbol("decoder"),Fe=Symbol("flowing"),di=Symbol("paused"),Er=Symbol("resume"),ze=Symbol("buffer"),Ze=Symbol("pipes"),Ue=Symbol("bufferLength"),qa=Symbol("bufferPush"),Rs=Symbol("bufferShift"),Ve=Symbol("objectMode"),Ae=Symbol("destroyed"),ja=Symbol("error"),Ka=Symbol("emitData"),Pu=Symbol("emitEnd"),$a=Symbol("emitEnd2"),It=Symbol("async"),Va=Symbol("abort"),Cs=Symbol("aborted"),li=Symbol("signal"),Nn=Symbol("dataListeners"),rt=Symbol("discarded"),ui=t=>Promise.resolve().then(t),tw=t=>t(),nw=t=>t==="end"||t==="finish"||t==="prefinish",rw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,iw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),uf=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()}},sw=class extends uf{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)}},ow=t=>!!t.objectMode,aw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",$n=class extends Fc{[Fe]=!1;[di]=!1;[Ze]=[];[ze]=[];[Ve];[gt];[It];[gr];[Wt]=!1;[xn]=!1;[As]=!1;[ks]=!1;[ci]=null;[Ue]=0;[Ae]=!1;[li];[Cs]=!1;[Nn]=0;[rt]=!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");ow(e)?(this[Ve]=!0,this[gt]=null):aw(e)?(this[gt]=e.encoding,this[Ve]=!1):(this[Ve]=!1,this[gt]=null),this[It]=!!e.async,this[gr]=this[gt]?new Ym(this[gt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[ze]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ze]});let{signal:n}=e;n&&(this[li]=n,n.aborted?this[Va]():n.addEventListener("abort",()=>this[Va]()))}get bufferLength(){return this[Ue]}get encoding(){return this[gt]}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[Ve]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[It]}set async(t){this[It]=this[It]||!!t}[Va](){this[Cs]=!0,this.emit("abort",this[li]?.reason),this.destroy(this[li]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,n){if(this[Cs])return!1;if(this[Wt])throw new Error("write after end");if(this[Ae])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[It]?ui:tw;if(!this[Ve]&&!Buffer.isBuffer(t)){if(iw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(rw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ve]?(this[Fe]&&this[Ue]!==0&&this[Ts](!0),this[Fe]?this.emit("data",t):this[qa](t),this[Ue]!==0&&this.emit("readable"),n&&i(n),this[Fe]):t.length?(typeof t=="string"&&!(e===this[gt]&&!this[gr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[gt]&&(t=this[gr].write(t)),this[Fe]&&this[Ue]!==0&&this[Ts](!0),this[Fe]?this.emit("data",t):this[qa](t),this[Ue]!==0&&this.emit("readable"),n&&i(n),this[Fe]):(this[Ue]!==0&&this.emit("readable"),n&&i(n),this[Fe])}read(t){if(this[Ae])return null;if(this[rt]=!1,this[Ue]===0||t===0||t&&t>this[Ue])return this[qt](),null;this[Ve]&&(t=null),this[ze].length>1&&!this[Ve]&&(this[ze]=[this[gt]?this[ze].join(""):Buffer.concat(this[ze],this[Ue])]);let e=this[Ru](t||null,this[ze][0]);return this[qt](),e}[Ru](t,e){if(this[Ve])this[Rs]();else{let n=e;t===n.length||t===null?this[Rs]():typeof n=="string"?(this[ze][0]=n.slice(t),e=n.slice(0,t),this[Ue]-=t):(this[ze][0]=n.subarray(t),e=n.subarray(0,t),this[Ue]-=t)}return this.emit("data",e),!this[ze].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[Fe]||!this[di])&&this[qt](),this}[Er](){this[Ae]||(!this[Nn]&&!this[Ze].length&&(this[rt]=!0),this[di]=!1,this[Fe]=!0,this.emit("resume"),this[ze].length?this[Ts]():this[Wt]?this[qt]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[Fe]=!1,this[di]=!0,this[rt]=!1}get destroyed(){return this[Ae]}get flowing(){return this[Fe]}get paused(){return this[di]}[qa](t){this[Ve]?this[Ue]+=1:this[Ue]+=t.length,this[ze].push(t)}[Rs](){return this[Ve]?this[Ue]-=1:this[Ue]-=this[ze][0].length,this[ze].shift()}[Ts](t=!1){do;while(this[Cu](this[Rs]())&&this[ze].length);!t&&!this[ze].length&&!this[Wt]&&this.emit("drain")}[Cu](t){return this.emit("data",t),this[Fe]}pipe(t,e){if(this[Ae])return t;this[rt]=!1;let n=this[xn];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[Ze].push(e.proxyErrors?new sw(this,t,e):new uf(this,t,e)),this[It]?ui(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[Ze].find(n=>n.dest===t);e&&(this[Ze].length===1?(this[Fe]&&this[Nn]===0&&(this[Fe]=!1),this[Ze]=[]):this[Ze].splice(this[Ze].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[rt]=!1,this[Nn]++,!this[Ze].length&&!this[Fe]&&this[Er]();else if(t==="readable"&&this[Ue]!==0)super.emit("readable");else if(nw(t)&&this[xn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ci]){let i=e;this[It]?ui(()=>i.call(this,this[ci])):i.call(this,this[ci])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Nn]=this.listeners("data").length,this[Nn]===0&&!this[rt]&&!this[Ze].length&&(this[Fe]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Nn]=0,!this[rt]&&!this[Ze].length&&(this[Fe]=!1)),e}get emittedEnd(){return this[xn]}[qt](){!this[As]&&!this[xn]&&!this[Ae]&&this[ze].length===0&&this[Wt]&&(this[As]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ks]&&this.emit("close"),this[As]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Ae&&this[Ae])return!1;if(t==="data")return!this[Ve]&&!n?!1:this[It]?(ui(()=>this[Ka](n)),!0):this[Ka](n);if(t==="end")return this[Pu]();if(t==="close"){if(this[ks]=!0,!this[xn]&&!this[Ae])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ci]=n,super.emit(ja,n);let o=!this[li]||this.listeners("error").length?super.emit("error",n):!1;return this[qt](),o}else if(t==="resume"){let o=super.emit("resume");return this[qt](),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[qt](),i}[Ka](t){for(let n of this[Ze])n.dest.write(t)===!1&&this.pause();let e=this[rt]?!1:super.emit("data",t);return this[qt](),e}[Pu](){return this[xn]?!1:(this[xn]=!0,this.readable=!1,this[It]?(ui(()=>this[$a]()),!0):this[$a]())}[$a](){if(this[gr]){let e=this[gr].end();if(e){for(let n of this[Ze])n.dest.write(e);this[rt]||super.emit("data",e)}}for(let e of this[Ze])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ve]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Ve]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Ve])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[gt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ae,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[rt]=!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",d),this.off("end",u),this.off(Ae,h),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(Ae,h),this.pause(),i({value:x,done:!!this[Wt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Ae,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(Ae,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[rt]=!1;let t=!1,e=()=>(this.pause(),this.off(ja,e),this.off(Ae,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(ja,e),this.once(Ae,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ae])return t?this.emit("error",t):this.emit(Ae),this;this[Ae]=!0,this[rt]=!0,this[ze].length=0,this[Ue]=0;let e=this;return typeof e.close=="function"&&!this[ks]&&e.close(),t?this.emit("error",t):this.emit(Ae),this}static get isStream(){return Xm}},cw=Qe.writev,vn=Symbol("_autoClose"),yt=Symbol("_close"),fi=Symbol("_ended"),de=Symbol("_fd"),Ja=Symbol("_finished"),Vt=Symbol("_flags"),Za=Symbol("_flush"),mc=Symbol("_handleChunk"),wc=Symbol("_makeBuf"),Si=Symbol("_mode"),Ps=Symbol("_needDrain"),Ar=Symbol("_onerror"),kr=Symbol("_onopen"),Ya=Symbol("_onread"),br=Symbol("_onwrite"),Sn=Symbol("_open"),_t=Symbol("_path"),wn=Symbol("_pos"),At=Symbol("_queue"),vr=Symbol("_read"),Xa=Symbol("_readSize"),$t=Symbol("_reading"),hi=Symbol("_remain"),Qa=Symbol("_size"),Gs=Symbol("_write"),Mn=Symbol("_writing"),Hs=Symbol("_defaultFlag"),Wn=Symbol("_errored"),zc=class extends $n{[Wn]=!1;[de];[_t];[Xa];[$t]=!1;[Qa];[hi];[vn];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[_t]=t,this[Xa]=e.readSize||16*1024*1024,this[$t]=!1,this[Qa]=typeof e.size=="number"?e.size:1/0,this[hi]=this[Qa],this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[vr]():this[Sn]()}get fd(){return this[de]}get path(){return this[_t]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Sn](){Qe.open(this[_t],"r",(t,e)=>this[kr](t,e))}[kr](t,e){t?this[Ar](t):(this[de]=e,this.emit("open",e),this[vr]())}[wc](){return Buffer.allocUnsafe(Math.min(this[Xa],this[hi]))}[vr](){if(!this[$t]){this[$t]=!0;let t=this[wc]();if(t.length===0)return process.nextTick(()=>this[Ya](null,0,t));Qe.read(this[de],t,0,t.length,null,(e,n,i)=>this[Ya](e,n,i))}}[Ya](t,e,n){this[$t]=!1,t?this[Ar](t):this[mc](e,n)&&this[vr]()}[yt](){if(this[vn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ar](t){this[$t]=!0,this[yt](),this.emit("error",t)}[mc](t,e){let n=!1;return this[hi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[hi]<=0)&&(n=!1,this[yt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[vr](),!1;case"error":return this[Wn]?!1:(this[Wn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},dw=class extends zc{[Sn](){let t=!0;try{this[kr](null,Qe.openSync(this[_t],"r")),t=!1}finally{t&&this[yt]()}}[vr](){let t=!0;try{if(!this[$t]){this[$t]=!0;do{let e=this[wc](),n=e.length===0?0:Qe.readSync(this[de],e,0,e.length,null);if(!this[mc](n,e))break}while(!0);this[$t]=!1}t=!1}finally{t&&this[yt]()}}[yt](){if(this[vn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.closeSync(t),this.emit("close")}}},ro=class extends Zm{readable=!1;writable=!0;[Wn]=!1;[Mn]=!1;[fi]=!1;[At]=[];[Ps]=!1;[_t];[Si];[vn];[de];[Hs];[Vt];[Ja]=!1;[wn];constructor(t,e){e=e||{},super(e),this[_t]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Si]=e.mode===void 0?438:e.mode,this[wn]=typeof e.start=="number"?e.start:void 0,this[vn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[wn]!==void 0?"r+":"w";this[Hs]=e.flags===void 0,this[Vt]=e.flags===void 0?n:e.flags,this[de]===void 0&&this[Sn]()}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[_t]}[Ar](t){this[yt](),this[Mn]=!0,this.emit("error",t)}[Sn](){Qe.open(this[_t],this[Vt],this[Si],(t,e)=>this[kr](t,e))}[kr](t,e){this[Hs]&&this[Vt]==="r+"&&t&&t.code==="ENOENT"?(this[Vt]="w",this[Sn]()):t?this[Ar](t):(this[de]=e,this.emit("open",e),this[Mn]||this[Za]())}end(t,e){return t&&this.write(t,e),this[fi]=!0,!this[Mn]&&!this[At].length&&typeof this[de]=="number"&&this[br](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[fi]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[Mn]||this[At].length?(this[At].push(t),this[Ps]=!0,!1):(this[Mn]=!0,this[Gs](t),!0)}[Gs](t){Qe.write(this[de],t,0,t.length,this[wn],(e,n)=>this[br](e,n))}[br](t,e){t?this[Ar](t):(this[wn]!==void 0&&typeof e=="number"&&(this[wn]+=e),this[At].length?this[Za]():(this[Mn]=!1,this[fi]&&!this[Ja]?(this[Ja]=!0,this[yt](),this.emit("finish")):this[Ps]&&(this[Ps]=!1,this.emit("drain"))))}[Za](){if(this[At].length===0)this[fi]&&this[br](null,0);else if(this[At].length===1)this[Gs](this[At].pop());else{let t=this[At];this[At]=[],cw(this[de],t,this[wn],(e,n)=>this[br](e,n))}}[yt](){if(this[vn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},ff=class extends ro{[Sn](){let t;if(this[Hs]&&this[Vt]==="r+")try{t=Qe.openSync(this[_t],this[Vt],this[Si])}catch(e){if(e?.code==="ENOENT")return this[Vt]="w",this[Sn]();throw e}else t=Qe.openSync(this[_t],this[Vt],this[Si]);this[kr](null,t)}[yt](){if(this[vn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.closeSync(t),this.emit("close")}}[Gs](t){let e=!0;try{this[br](null,Qe.writeSync(this[de],t,0,t.length,this[wn])),e=!1}finally{if(e)try{this[yt]()}catch{}}}},fw=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"]]),hw=t=>!!t.sync&&!!t.file,xw=t=>!t.sync&&!!t.file,pw=t=>!!t.sync&&!t.file,gw=t=>!t.sync&&!t.file,mw=t=>!!t.file,ww=t=>fw.get(t)||t,Uc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=ww(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Oi=(t,e,n,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=Uc(c);if(o?.(h,d),hw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(xw(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(pw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,d)}else if(gw(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),Ew=yw.constants||{ZLIB_VERNUM:4736},Pt=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},Ew)),bw=qn.concat,Ou=Object.getOwnPropertyDescriptor(qn,"concat"),vw=t=>t,ec=Ou?.writable===!0||Ou?.set!==void 0?t=>{qn.concat=t?vw:bw}:t=>{},jn=Symbol("_superWrite"),Ds=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"}},tc=Symbol("flushFlag"),Gc=class extends $n{#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 Ds(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 Ds(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return _c(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),{[tc]: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;_c(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},ec(!0);let d;try{let h=typeof t[tc]=="number"?t[tc]:this.#r;d=this.#t._processChunk(t,h),ec(!1)}catch(h){ec(!1),this.#o(new Ds(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 Ds(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[jn](qn.from(h));for(let x=1;x<d.length;x++)u=this[jn](d[x])}else u=this[jn](qn.from(d));return n&&n(),u}},xf=class extends Gc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Pt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Pt.Z_FINISH,t.fullFlushFlag=Pt.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(Pt.Z_SYNC_FLUSH),_c(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)}}}},Sw=class extends xf{#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)}},Iw=class extends xf{constructor(t){super(t,"Unzip")}},pf=class extends Gc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Pt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Pt.BROTLI_OPERATION_FLUSH,super(t,e)}},Aw=class extends pf{constructor(t){super(t,"BrotliCompress")}},kw=class extends pf{constructor(t){super(t,"BrotliDecompress")}},gf=class extends Gc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Pt.ZSTD_e_end,t.fullFlushFlag=Pt.ZSTD_e_flush,super(t,e)}},Tw=class extends gf{constructor(t){super(t,"ZstdCompress")}},Rw=class extends gf{constructor(t){super(t,"ZstdDecompress")}},Cw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Dw(t,e):Pw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Pw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},Dw=(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]=wf(o))}},Ow=t=>{let e=t[0],n=e===128?Nw(t.subarray(1,t.length)):e===255?Lw(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},Lw=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=mf(c):c===0?d=c:(i=!0,d=wf(c)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},Nw=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,wf=t=>(255^t)+1&255,Mw={};Jm(Mw,{code:()=>Hc,isCode:()=>Ws,isName:()=>Bw,name:()=>io,normalFsTypes:()=>_f});var Ws=t=>io.has(t),Bw=t=>Hc.has(t),_f=new Set(["0","","1","2","3","4","5","6","7","D"]),io=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Hc=new Map(Array.from(io).map(t=>[t[1],t[0]])),Fw=t=>t===void 0||t<0?void 0:t,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=Bn(t,e+156,1),c=_f.has(o),d=c?n:void 0,u=c?i:void 0;if(this.path=d?.path??Bn(t,e,100),this.mode=d?.mode??u?.mode??_n(t,e+100,8),this.uid=d?.uid??u?.uid??_n(t,e+108,8),this.gid=d?.gid??u?.gid??_n(t,e+116,8),this.size=Fw(d?.size??u?.size??_n(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??nc(t,e+136,12),this.cksum=_n(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Ws(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Bn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Bn(t,e+265,32),this.gname=d?.gname??u?.gname??Bn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??_n(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??_n(t,e+337,8)??0,t[e+475]!==0){let x=Bn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Bn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??nc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??nc(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="size"&&Number(i)<0||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=zw(this.path||"",n),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Fn(t,e,100,o)||this.needPax,this.needPax=yn(t,e+100,8,this.mode)||this.needPax,this.needPax=yn(t,e+108,8,this.uid)||this.needPax,this.needPax=yn(t,e+116,8,this.gid)||this.needPax,this.needPax=yn(t,e+124,12,this.size)||this.needPax,this.needPax=rc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Fn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Fn(t,e+265,32,this.uname)||this.needPax,this.needPax=Fn(t,e+297,32,this.gname)||this.needPax,this.needPax=yn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=yn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Fn(t,e+345,n,c)||this.needPax,t[e+475]!==0?this.needPax=Fn(t,e+345,155,c)||this.needPax:(this.needPax=Fn(t,e+345,130,c)||this.needPax,this.needPax=rc(t,e+476,12,this.atime)||this.needPax,this.needPax=rc(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,yn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:io.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Hc.get(t));if(Ws(e)||e==="Unsupported")this.#e=e;else if(Ws(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},zw=(t,e)=>{let n=t,i="",o,c=mr.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=mr.dirname(n),n=mr.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=mr.join(mr.basename(i),n),i=mr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Bn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),nc=(t,e,n)=>Uw(_n(t,e,n)),Uw=t=>t===void 0?void 0:new Date(t*1e3),_n=(t,e,n)=>Number(t[e])&128?Ow(t.subarray(e,e+n)):Hw(t,e,n),Gw=t=>isNaN(t)?void 0:t,Hw=(t,e,n)=>Gw(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Ww={12:8589934591,8:2097151},yn=(t,e,n,i)=>i===void 0?!1:i>Ww[n]||i<0?(Cw(i,t.subarray(e,e+n)),!0):(qw(t,e,n,i),!1),qw=(t,e,n,i)=>t.write(jw(i,n),e,n,"ascii"),jw=(t,e)=>Kw(Math.floor(t).toString(8),e),Kw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",rc=(t,e,n,i)=>i===void 0?!1:yn(t,e,n,i.getTime()/1e3),$w=new Array(156).join("\0"),Fn=(t,e,n,i)=>i===void 0?!1:(t.write(i+$w,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),Xs=class yf{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/"+Vw(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),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,n,i=!1){return new yf(Jw(Zw(e),n),i)}},Jw=(t,e)=>e?Object.assign({},e,t):t,Zw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(Yw,Object.create(null)),Yw=(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"),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},Xw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Xw!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),Qw=class extends $n{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,i=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},so=(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))},e_=1024*1024,yc=Buffer.from([31,139]),Ec=Buffer.from([40,181,47,253]),t_=Math.max(yc.length,Ec.length),dt=Symbol("state"),zn=Symbol("writeEntry"),jt=Symbol("readEntry"),ic=Symbol("nextEntry"),Lu=Symbol("processEntry"),kt=Symbol("extendedHeader"),xi=Symbol("globalExtendedHeader"),pn=Symbol("meta"),Nu=Symbol("emitMeta"),ge=Symbol("buffer"),Kt=Symbol("queue"),gn=Symbol("ended"),sc=Symbol("emittedEnd"),Un=Symbol("emit"),Ie=Symbol("unzip"),Os=Symbol("consumeChunk"),Ls=Symbol("consumeChunkSub"),oc=Symbol("consumeBody"),Mu=Symbol("consumeMeta"),Bu=Symbol("consumeHeader"),pi=Symbol("consuming"),ac=Symbol("bufferConcat"),Ns=Symbol("maybeEnd"),wr=Symbol("writing"),Tt=Symbol("aborted"),Ms=Symbol("onDone"),Gn=Symbol("sawValidEntry"),Bs=Symbol("sawNullBlock"),Fs=Symbol("sawEOF"),Fu=Symbol("closeStream"),n_=1e3,gi=Symbol("compressedBytesRead"),cc=Symbol("decompressedBytesRead"),zu=Symbol("checkDecompressionRatio"),r_=()=>!0,Di=class extends _w{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[Kt]=[];[ge];[jt];[zn];[dt]="begin";[pn]="";[kt];[xi];[gn]=!1;[Ie];[Tt]=!1;[Gn];[Bs]=!1;[Fs]=!1;[wr]=!1;[pi]=!1;[sc]=!1;[gi]=0;[cc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Ms,()=>{(this[dt]==="begin"||this[Gn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ms,t.ondone):this.on(Ms,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:n_,this.maxMetaEntrySize=t.maxMetaEntrySize||e_,this.filter=typeof t.filter=="function"?t.filter:r_;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={}){so(this,t,e,n)}[Bu](t,e){this[Gn]===void 0&&(this[Gn]=!1);let n;try{n=new Kn(t,e,this[kt],this[xi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Bs]?(this[Fs]=!0,this[dt]==="begin"&&(this[dt]="header"),this[Un]("eof")):(this[Bs]=!0,this[Un]("nullBlock"));else if(this[Bs]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let o=this[zn]=new Qw(n,this[kt],this[xi]);if(!this[Gn])if(o.remain){let c=()=>{o.invalid||(this[Gn]=!0)};o.on("end",c)}else this[Gn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Un]("ignoredEntry",o),this[dt]="ignore",o.resume()):o.size>0&&(this[pn]="",o.on("data",c=>this[pn]+=c),this[dt]="meta"):(this[kt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Un]("ignoredEntry",o),this[dt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[dt]="body":(this[dt]="header",o.end()),this[jt]?this[Kt].push(o):(this[Kt].push(o),this[ic]())))}}}[Fu](){queueMicrotask(()=>this.emit("close"))}[Lu](t){let e=!0;if(!t)this[jt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ic]()),e=!1);return e}[ic](){do;while(this[Lu](this[Kt].shift()));if(this[Kt].length===0){let t=this[jt];!t||t.flowing||t.size===t.remain?this[wr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[oc](t,e){let n=this[zn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(o),n.blockRemain||(this[dt]="header",this[zn]=void 0,n.end()),o.length}[Mu](t,e){let n=this[zn],i=this[oc](t,e);return!this[zn]&&n&&this[Nu](n),i}[Un](t,e,n){this[Kt].length===0&&!this[jt]?this.emit(t,e,n):this[Kt].push([t,e,n])}[Nu](t){switch(this[Un]("meta",this[pn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[kt]=Xs.parse(this[pn],this[kt],!1);break;case"GlobalExtendedHeader":this[xi]=Xs.parse(this[pn],this[xi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[kt]??Object.create(null);this[kt]=e,e.path=this[pn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[kt]||Object.create(null);this[kt]=e,e.linkpath=this[pn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Tt]){if(this[Ie]){let e=this[Ie];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Tt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[zu](t){this[cc]+=t.length;let e=this[cc]/this[gi];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Tt])return n?.(),!1;if((this[Ie]===void 0||this.brotli===void 0&&this[Ie]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<t_)return this[ge]=t,n?.(),!0;for(let d=0;this[Ie]===void 0&&d<yc.length;d++)t[d]!==yc[d]&&(this[Ie]=!1);let o=!1;if(this[Ie]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Ec.length;d++)if(t[d]!==Ec[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Ie]===!1&&c)if(t.length<512)if(this[gn])this.brotli=!0;else return this[ge]=t,n?.(),!0;else try{new Kn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ie]===void 0||this[Ie]===!1&&(this.brotli||o)){let d=this[gn];this[gn]=!1,this[Ie]=this[Ie]===void 0?new Iw({}):o?new Rw({}):new kw({}),this[Ie].on("data",h=>{this[zu](h)&&this[Os](h)}),this[Ie].on("error",h=>{this[Tt]||this.abort(h)}),this[Ie].on("end",()=>{this[gn]=!0,this[Os]()}),this[wr]=!0,this[gi]+=t.length;let u=!!this[Ie][d?"end":"write"](t);return this[wr]=!1,n?.(),u}}this[wr]=!0,this[Ie]?(this[gi]+=t.length,this[Ie].write(t)):this[Os](t),this[wr]=!1;let i=this[Kt].length>0?!1:this[jt]?this[jt].flowing:!0;return!i&&this[Kt].length===0&&this[jt]?.once("drain",()=>this.emit("drain")),n?.(),i}[ac](t){t&&!this[Tt]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Ns](){if(this[gn]&&!this[sc]&&!this[Tt]&&!this[pi]){this[sc]=!0;let t=this[zn];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[Un](Ms)}}[Os](t){if(this[pi]&&t)this[ac](t);else if(!t&&!this[ge])this[Ns]();else if(t){if(this[pi]=!0,this[ge]){this[ac](t);let e=this[ge];this[ge]=void 0,this[Ls](e)}else this[Ls](t);for(;this[ge]&&this[ge]?.length>=512&&!this[Tt]&&!this[Fs];){let e=this[ge];this[ge]=void 0,this[Ls](e)}this[pi]=!1}(!this[ge]||this[gn])&&this[Ns]()}[Ls](t){let e=0,n=t.length;for(;e+512<=n&&!this[Tt]&&!this[Fs];)switch(this[dt]){case"begin":case"header":this[Bu](t,e),e+=512;break;case"ignore":case"body":e+=this[oc](t,e);break;case"meta":e+=this[Mu](t,e);break;default:throw new Error("invalid state: "+this[dt])}e<n&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Tt]||(this[Ie]?(t&&(this[gi]+=t.length,this[Ie].write(t)),this[Ie].end()):(this[gn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ns]())),this}},Ii=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)},i_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Ef=(t,e)=>{let n=new Map(e.map(c=>[Ii(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||uw(c).root||".",h;if(c===u)h=!1;else{let x=n.get(c);h=x!==void 0?x:o(lw(c),u)}return n.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&o(Ii(c)):c=>o(Ii(c))},s_=t=>{let e=new Di(t),n=t.file,i;try{i=Sr.openSync(n,"r");let o=Sr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Sr.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=Sr.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{Sr.closeSync(i)}catch{}}},o_=(t,e)=>{let n=new Di(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("end",c),Sr.stat(o,(u,h)=>{if(u)d(u);else{let x=new zc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Tr=Oi(s_,o_,t=>new Di(t),t=>new Di(t),(t,e)=>{e?.length&&Ef(t,e),t.noResume||i_(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:c_,parse:Gu}=a_,Wc=t=>{let e="",n=Gu(t);for(;c_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Gu(t)}return[e,t]},oo=["|","<",">","?",":"],qc=oo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),d_=new Map(oo.map((t,e)=>[t,qc[e]])),l_=new Map(qc.map((t,e)=>[t,oo[e]])),Hu=t=>oo.reduce((e,n)=>e.split(n).join(d_.get(n)),t),u_=t=>qc.reduce((e,n)=>e.split(n).join(l_.get(n)),t),vf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ii(e)+"/"+t):Q(t),f_=16*1024*1024,Wu=Symbol("process"),qu=Symbol("file"),ju=Symbol("directory"),bc=Symbol("symlink"),Ku=Symbol("hardlink"),mi=Symbol("header"),qs=Symbol("read"),vc=Symbol("lstat"),js=Symbol("onlstat"),Sc=Symbol("onread"),Ic=Symbol("onreadlink"),Ac=Symbol("openfile"),kc=Symbol("onopenfile"),En=Symbol("close"),eo=Symbol("mode"),Tc=Symbol("awaitDrain"),dc=Symbol("ondrain"),Ct=Symbol("prefix"),Sf=class extends $n{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=Uc(e);super(),this.path=Q(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||f_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Q(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Q(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Wc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=u_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(n.absolute||Uu.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[vc]()}warn(t,e,n={}){return so(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[vc](){Rt.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=p_(t),this.emit("stat",t),this[Wu]()}[Wu](){switch(this.type){case"File":return this[qu]();case"Directory":return this[ju]();case"SymbolicLink":return this[bc]();default:return this.end()}}[eo](t){return bf(t,this.type==="Directory",this.portable)}[Ct](t){return vf(t,this.prefix)}[mi](){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[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](this.linkpath):this.linkpath,mode:this[eo](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Xs({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[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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[mi](),this.end()}[bc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ic](e)})}[Ic](t){this.linkpath=Q(t),this[mi](),this.end()}[Ku](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Uu.relative(this.cwd,t)),this.stat.size=0,this[mi](),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[mi](),this.stat.size===0)return this.end();this[Ac]()}[Ac](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[kc](e)})}[kc](t){if(this.fd=t,this.#e)return this[En]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[qs]()}[qs](){let{fd:t,buf:e,offset:n,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Rt.read(t,e,n,i,o,(c,d)=>{if(c)return this[En](()=>this.emit("error",c));this[Sc](d)})}[En](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[Sc](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[En](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[En](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[dc]():this[Tc](()=>this[dc]())}[Tc](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)}[dc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[En](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[qs]()}},h_=class extends Sf{sync=!0;[vc](){this[js](Rt.lstatSync(this.absolute))}[bc](){this[Ic](Rt.readlinkSync(this.absolute))}[Ac](){this[kc](Rt.openSync(this.absolute,"r"))}[qs](){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 d=Rt.readSync(e,n,i,o,c);this[Sc](d),t=!1}finally{if(t)try{this[En](()=>{})}catch{}}}[Tc](t){t()}[En](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},x_=class extends $n{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 so(this,t,e,n)}constructor(t,e={}){let n=Uc(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[eo](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:n.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Wc(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 Kn({path:this[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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 Xs({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[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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)}[Ct](t){return vf(t,this.prefix)}[eo](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}},p_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",g_=class Ir{tail;head;length=0;static create(e=[]){return new Ir(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++)w_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)__(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 Ir;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 Ir;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 Ir;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 Ir;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 d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<n;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=m_(this,o,d);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 m_(t,e,n){let i=e,o=e?e.next:t.head,c=new jc(n,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function w_(t,e){t.tail=new jc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function __(t,e){t.head=new jc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var jc=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}},Vu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Ju=Buffer.alloc(1024),Ks=Symbol("onStat"),wi=Symbol("ended"),mt=Symbol("queue"),_i=Symbol("pendingLinks"),mn=Symbol("current"),Hn=Symbol("process"),yi=Symbol("processing"),zs=Symbol("processJob"),wt=Symbol("jobs"),lc=Symbol("jobDone"),$s=Symbol("addFSEntry"),Zu=Symbol("addTarEntry"),Rc=Symbol("stat"),Cc=Symbol("readdir"),Vs=Symbol("onreaddir"),Js=Symbol("pipe"),Yu=Symbol("entry"),uc=Symbol("entryOpt"),Zs=Symbol("writeEntryClass"),If=Symbol("write"),fc=Symbol("ondrain"),ao=class extends $n{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Zs];onWriteEntry;[mt];[_i]=new Map;[wt]=0;[yi]=!1;[wi]=!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[Zs]=Sf,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 Sw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Aw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Tw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[fc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[fc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[mt]=new g_,this[wt]=0,this.jobs=Number(t.jobs)||4,this[yi]=!1,this[wi]=!1}[If](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[wi]=!0,this[Hn](),n&&n(),this}write(t){if(this[wi])throw new Error("write after end");return typeof t=="string"?this[$s](t):this[Zu](t),this.flowing}[Zu](t){let e=Q($u.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new Vu(t.path,e);n.entry=new x_(t,this[uc](n)),n.entry.on("end",()=>this[lc](n)),this[wt]+=1,this[mt].push(n)}this[Hn]()}[$s](t){let e=Q($u.resolve(this.cwd,t));this[mt].push(new Vu(t,e)),this[Hn]()}[Rc](t){t.pending=!0,this[wt]+=1;let e=this.follow?"stat":"lstat";Qs[e](t.absolute,(n,i)=>{t.pending=!1,this[wt]-=1,n?this.emit("error",n):this[Ks](t,i)})}[Ks](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[zs](t);else{let n=`${e.dev}:${e.ino}`,i=this[_i].get(n);i?i.push(t):this[_i].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Hn]()}[Cc](t){t.pending=!0,this[wt]+=1,Qs.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[wt]-=1,e)return this.emit("error",e);this[Vs](t,n)})}[Vs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Hn]()}[Hn](){if(!this[yi]){this[yi]=!0;for(let t=this[mt].head;t&&this[wt]<this.jobs;t=t.next)if(this[zs](t.value),t.value.ignore){let e=t.next;this[mt].removeNode(t),t.next=e}this[yi]=!1,this[wi]&&this[mt].length===0&&this[wt]===0&&(this.zip?this.zip.end(Ju):(super.write(Ju),super.end()))}}get[mn](){return this[mt]&&this[mt].head&&this[mt].head.value}[lc](t){this[mt].shift(),this[wt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[_i].get(n);if(i){this[_i].delete(n);for(let o of i)o.pending=!1,this[zs](o)}}this[Hn]()}[zs](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[Js](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ks](t,e):this[Rc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Vs](t,e):this[Cc](t),!t.readdir)return}if(t.entry=this[Yu](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[Js](t)}}}[uc](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}}[Yu](t){this[wt]+=1;try{return new this[Zs](t.path,this[uc](t)).on("end",()=>this[lc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[fc](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[Js](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[$s](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={}){so(this,t,e,n)}},Kc=class extends ao{sync=!0;constructor(t){super(t),this[Zs]=h_}pause(){}resume(){}[Rc](t){let e=this.follow?"statSync":"lstatSync";this[Ks](t,Qs[e](t.absolute))}[Cc](t){this[Vs](t,Qs.readdirSync(t.absolute))}[Js](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[$s](c+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[If](i)})}},y_=(t,e)=>{let n=new Kc(t),i=new ff(t.file,{mode:t.mode||438});n.pipe(i),Af(n,e)},E_=(t,e)=>{let n=new ao(t),i=new ro(t.file,{mode:t.mode||438});n.pipe(i);let o=new Promise((c,d)=>{i.on("error",d),i.on("close",c),n.on("error",d)});return kf(n,e).catch(c=>n.emit("error",c)),o},Af=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Tr({file:hf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},kf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Tr({file:hf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},b_=(t,e)=>{let n=new Kc(t);return Af(n,e),n},v_=(t,e)=>{let n=new ao(t);return kf(n,e).catch(i=>n.emit("error",i)),n},gA=Oi(y_,E_,b_,v_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),I_=process.env.__FAKE_PLATFORM__||process.platform,Pf=I_==="win32",{O_CREAT:Df,O_NOFOLLOW:Xu,O_TRUNC:Of,O_WRONLY:Lf}=Cf.constants,Nf=Number(process.env.__FAKE_FS_O_FILENAME__)||Cf.constants.UV_FS_O_FILEMAP||0,A_=Pf&&!!Nf,k_=512*1024,T_=Nf|Of|Df|Lf,Qu=!Pf&&typeof Xu=="number"?Xu|Of|Df|Lf:null,Mf=Qu!==null?()=>Qu:A_?t=>t<k_?T_:"w":()=>"w",Pc=(t,e,n)=>{try{return co.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},to=(t,e,n,i)=>{co.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},R_=(t,e,n,i,o)=>{if(e.isDirectory())Bf(Ai.resolve(t,e.name),n,i,c=>{if(c)return o(c);let d=Ai.resolve(t,e.name);to(d,n,i,o)});else{let c=Ai.resolve(t,e.name);to(c,n,i,o)}},Bf=(t,e,n,i)=>{co.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 to(t,e,n,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return to(t,e,n,i)}};for(let x of c)R_(t,x,e,n,h)})},C_=(t,e,n,i)=>{e.isDirectory()&&Ff(Ai.resolve(t,e.name),n,i),Pc(Ai.resolve(t,e.name),n,i)},Ff=(t,e,n)=>{let i;try{i=co.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Pc(t,e,n);throw c}for(let o of i)C_(t,o,e,n);return Pc(t,e,n)},zf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},lo=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"}},D_=(t,e)=>{st.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new zf(t,n?.code||"ENOTDIR")),e(n)})},O_=(t,e,n)=>{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,g=Q(e.cwd),S=(v,I)=>{v?n(v):I&&h?Bf(I,d,u,A=>S(A)):c?st.chmod(t,o,n):n()};if(t===g)return D_(t,S);if(x)return P_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let _=Q(no.relative(g,t)).split("/");Dc(g,_,o,m,g,void 0,S)},Dc=(t,e,n,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Q(no.resolve(t+"/"+u));st.mkdir(h,n,Uf(h,e,n,i,o,c,d))},Uf=(t,e,n,i,o,c,d)=>u=>{u?st.lstat(t,(h,x)=>{if(h)h.path=h.path&&Q(h.path),d(h);else if(x.isDirectory())Dc(t,e,n,i,o,c,d);else if(i)st.unlink(t,m=>{if(m)return d(m);st.mkdir(t,n,Uf(t,e,n,i,o,c,d))});else{if(x.isSymbolicLink())return d(new lo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Dc(t,e,n,i,o,c,d))},L_=t=>{let e=!1,n;try{e=st.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new zf(t,n??"ENOTDIR")}},N_=(t,e)=>{t=Q(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==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),g=v=>{v&&u&&Ff(v,c,d),o&&st.chmodSync(t,i)};if(t===m)return L_(m),g();if(h)return g(st.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(no.relative(m,t)).split("/"),_;for(let v=S.shift(),I=m;v&&(I+="/"+v);v=S.shift()){I=Q(no.resolve(I));try{st.mkdirSync(I,i),_=_||I}catch{let A=st.lstatSync(I);if(A.isDirectory())continue;if(x){st.unlinkSync(I),st.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new lo(I,I+"/"+S.join("/"))}}return g(_)},hc=Object.create(null),ef=1e4,_r=new Set,M_=t=>{_r.has(t)?_r.delete(t):hc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),_r.add(t);let e=hc[t],n=_r.size-ef;if(n>ef/10){for(let i of _r)if(_r.delete(i),delete hc[i],--n<=0)break}return e},B_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,F_=B_==="win32",z_=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Gf(i,n)),e.push(n||"/"),e},[]),U_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=F_?["win32 parallelization disabled"]:t.map(i=>Ii(Gf(M_(i))));let n=new Set(t.map(i=>z_(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 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}},G_=()=>process.umask(),tf=Symbol("onEntry"),Oc=Symbol("checkFs"),nf=Symbol("checkFs2"),Lc=Symbol("isReusable"),lt=Symbol("makeFs"),Nc=Symbol("file"),Mc=Symbol("directory"),Ys=Symbol("link"),rf=Symbol("symlink"),sf=Symbol("hardlink"),vi=Symbol("ensureNoSymlink"),of=Symbol("unsupported"),af=Symbol("checkPath"),xc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),Ge=Symbol("onError"),Us=Symbol("pending"),cf=Symbol("pend"),yr=Symbol("unpend"),pc=Symbol("ended"),gc=Symbol("maybeClose"),Bc=Symbol("skip"),ki=Symbol("doChown"),Ti=Symbol("uid"),Ri=Symbol("gid"),Ci=Symbol("checkedCwd"),H_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pi=H_==="win32",W_=1024,q_=(t,e)=>{if(!Pi)return ie.unlink(t,e);let n=t+".DELETE."+Rf(16).toString("hex");ie.rename(t,n,i=>{if(i)return e(i);ie.unlink(n,e)})},j_=t=>{if(!Pi)return ie.unlinkSync(t);let e=t+".DELETE."+Rf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},df=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,$c=class extends Di{[pc]=!1;[Ci]=!1;[Us]=0;reservations=new U_;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[pc]=!0,this[gc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:W_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Pi,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:G_():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[tf](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[gc](){this[pc]&&this[Us]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[xc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,c]=Wc(n),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Pi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=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]:n}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:n})),!0}[af](t){let e=Q(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[xc](t,"path")||!this[xc](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+Hu(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Hu(t.path.slice(o.length))}return!0}[tf](t){if(!this[af](t))return t.resume();switch(S_.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[Oc](t);default:return this[of](t)}}[Ge](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[yr](),e.resume())}[bn](t,e,n){O_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[ki](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ti](t){return df(this.uid,t.uid,this.processUid)}[Ri](t){return df(this.gid,t.gid,this.processGid)}[Nc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new ro(String(t.absolute),{flags:Mf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[Ge](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[Ge](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,h=>{h?this[Ge](h,t):this[yr](),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;ie.futimes(h,x,m,g=>g?ie.utimes(u,x,m,S=>c(S&&g)):c())}if(typeof h=="number"&&this[ki](t)){o++;let x=this[Ti](t),m=this[Ri](t);typeof x=="number"&&typeof m=="number"&&ie.fchown(h,x,m,g=>g?ie.chown(u,x,m,S=>c(S&&g)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[Ge](u,t),e()}),t.pipe(d)),d.pipe(i)}[Mc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),n,i=>{if(i){this[Ge](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[yr](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[ki](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ti](t)),Number(this[Ri](t)),c)),c()})}[of](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[rf](t,e){let n=Q(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[vi](t,this.cwd,n,()=>this[Ys](t,String(t.linkpath),"symlink",e),i=>{this[Ge](i,t),e()})}[sf](t,e){let n=Q(Ne.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[vi](t,this.cwd,i,()=>this[Ys](t,n,"link",e),o=>{this[Ge](o,t),e()})}[vi](t,e,n,i,o){let c=n.shift();if(this.preservePaths||c===void 0)return i();let d=Ne.resolve(e,c);ie.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new lo(d,Ne.resolve(d,n.join("/"))));this[vi](t,d,n,i,o)})}[cf](){this[Us]++}[yr](){this[Us]--,this[gc]()}[Bc](t){this[yr](),t.resume()}[Lc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Pi}[Oc](t){this[cf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[nf](t,n))}[nf](t,e){let n=d=>{e(d)},i=()=>{this[bn](this.cwd,this.dmode,d=>{if(d){this[Ge](d,t),n();return}this[Ci]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Ne.dirname(String(t.absolute)));if(d!==this.cwd)return this[bn](d,this.dmode,u=>{if(u){this[Ge](u,t),n();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Bc](t),n();return}if(d||this[Lc](t,u))return this[lt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[lt](m??null,t,n);return h?ie.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),h=>this[lt](h??null,t,n))}if(t.absolute===this.cwd)return this[lt](null,t,n);q_(String(t.absolute),h=>this[lt](h??null,t,n))})};this[Ci]?o():i()}[lt](t,e,n){if(t){this[Ge](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Nc](e,n);case"Link":return this[sf](e,n);case"SymbolicLink":return this[rf](e,n);case"Directory":case"GNUDumpDir":return this[Mc](e,n)}}[Ys](t,e,n,i){ie[n](e,String(t.absolute),o=>{o?this[Ge](o,t):(this[yr](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Hf=class extends $c{sync=!0;[lt](t,e){return super[lt](t,e,()=>{})}[Oc](t){if(!this[Ci]){let o=this[bn](this.cwd,this.dmode);if(o)return this[Ge](o,t);this[Ci]=!0}if(t.absolute!==this.cwd){let o=Q(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[Ge](c,t)}}let[e,n]=Ei(()=>ie.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Bc](t);if(e||this[Lc](t,n))return this[lt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=c?Ei(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[lt](d,t)}let[o]=Ei(()=>ie.rmdirSync(String(t.absolute)));this[lt](o,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>j_(String(t.absolute)));this[lt](i,t)}[Nc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ie.closeSync(o)}catch(h){u=h}(d||u)&&this[Ge](d||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Mf(t.size),n)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[Ge](d,t)),t.pipe(c)),c.on("data",d=>{try{ie.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{ie.futimesSync(o,u,h)}catch(x){try{ie.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[ki](t)){let u=this[Ti](t),h=this[Ri](t);try{ie.fchownSync(o,Number(u),Number(h))}catch(x){try{ie.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Mc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),n);if(i){this[Ge](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ki](t))try{ie.chownSync(String(t.absolute),Number(this[Ti](t)),Number(this[Ri](t)))}catch{}e(),t.resume()}[bn](t,e){try{return N_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[vi](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let c=e;for(let d of n){c=Ne.resolve(c,d);let[u,h]=Ei(()=>ie.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new lo(c,Ne.resolve(e,n.join("/"))))}i()}[Ys](t,e,n,i){let o=`${n}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ge](c,t)}}},K_=t=>{let e=new Hf(t),n=t.file,i=Tf.statSync(n),o=t.maxReadSize||16*1024*1024;new dw(n,{readSize:o,size:i.size}).pipe(e)},$_=(t,e)=>{let n=new $c(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{n.on("error",d),n.on("close",c),Tf.stat(o,(u,h)=>{if(u)d(u);else{let x=new zc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Wf=Oi(K_,$_,t=>new Hf(t),t=>new $c(t),(t,e)=>{e?.length&&Ef(t,e)}),V_=(t,e)=>{let n=new Kc(t),i=!0,o,c;try{try{o=it.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=it.openSync(t.file,"w+");else throw h}let d=it.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,g=0;m<512;m+=g){if(g=it.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(!g)break e}let h=new Kn(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,J_(t,n,c,o,e)}finally{if(i)try{it.closeSync(o)}catch{}}},J_=(t,e,n,i,o)=>{let c=new ff(t.file,{fd:i,start:n});e.pipe(c),Y_(e,o)},Z_=(t,e)=>{e=Array.from(e);let n=new ao(t),i=(o,c,d)=>{let u=(S,_)=>{S?it.close(o,v=>d(S)):d(null,_)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),g=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return it.read(o,m,x,m.length-x,h+x,g);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 v=new Kn(m);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,it.read(o,m,0,512,h,g)};it.read(o,m,0,512,h,g)};return new Promise((o,c)=>{n.on("error",c);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",it.open(t.file,d,u);if(h||!x)return c(h);it.fstat(x,(m,g)=>{if(m)return it.close(x,()=>c(m));i(x,g.size,(S,_)=>{if(S)return c(S);let v=new ro(t.file,{fd:x,start:_});n.pipe(v),v.on("error",c),v.on("close",o),X_(n,e)})})};it.open(t.file,d,u)})},Y_=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Tr({file:qf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},X_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Tr({file:qf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},bi=Oi(V_,Z_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!mw(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=Oi(bi.syncFile,bi.asyncFile,bi.syncNoFile,bi.asyncNoFile,(t,e=[])=>{bi.validate?.(t,e),Q_(t)}),Q_=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))};fn();var ut={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 uo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function jf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function fo(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 $f(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function Vn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Jt();qe();ne();Re();qe();function Rr(t,e){if(uo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Li(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 Sk,join as Ik}from"node:path";import{fileURLToPath as kk}from"node:url";var Dt="0.2.7-alpha.10";qe();ne();var ho="1008033",Yf="1289";var Xf="pbbp2",Qf="https://www.coze.cn",e0="/api/coze_claw/resource/get_frontier_key",ay="https://www.coze.cn",cy="wss://frontier.coze.cn";function Pr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??ay}function t0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??cy}function In(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 Mi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Ni=G("handshake");async function Vc(t){let e=Pr(t.endpoint),n=t.timeoutMs??1e4,i=`${Cr(e)}${e0}?aid=${encodeURIComponent(ho)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...In(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),n);Ni.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 v=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${v.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 g=m.data??{},S=typeof g.access_key=="string"&&g.access_key||typeof g.accessKey=="string"&&g.accessKey||void 0,_=typeof g.device_id=="string"&&g.device_id||typeof g.deviceId=="string"&&g.deviceId||void 0;if(!S||!_){let v=JSON.stringify(m).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${v}`)}return Ni.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:S,deviceId:_}}catch(u){if(u instanceof k)throw Ni.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Ni.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw Ni.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Jc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ot="auto",xo=15e4;function r0(t){return{model:Zc(t.model)??Ot,...t.modelToken?{modelToken:t.modelToken}:{}}}function i0(t){return!t||t===Ot}var dy=new Set(["auto","\u81EA\u52A8"]);function Zc(t){let e=t?.trim();if(e)return dy.has(e.toLowerCase())?Ot:e}function s0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Jc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Ot;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else i0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function o0(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Ot}"`):i0(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${Jc}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let n=t.modelInfo?.contextWindow??xo;e.push("-c",`model_context_window=${n}`)}return e}function a0(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Yc(t,e){let{ttEnv:n,usePpe:i}=Mi(t),o={};return n&&(o["x-tt-env"]=n),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function c0(t,e,n){if(!t.modelToken)return{};let i=Yc(e,n);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
- `)}}function Xc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Qc(t){return t.model||Ot}function n0(t,e,n){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:8192,api:"openai-completions"}}function d0(t,e,n,i){if(!t.modelToken)return null;let o=Qc(t),c=Yc(e,n),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[n0(o,d,t.modelInfo?.contextWindow??xo)],h=new Set([o]);for(let m of i??[])!m||h.has(m)||(h.add(m),u.push(n0(m,["text"],xo)));let x={baseUrl:`${Jc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:o,name:o,reasoning:!1,input:d,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??xo,maxTokens:32e3,api:"openai-completions"}]};return Object.keys(c).length>0&&(x.headers=c),x}function l0(t,e,n){if(!t.modelToken)return[];let i=Yc(e,n),o=[];for(let[c,d]of Object.entries(i))o.push("-c",`model_providers.coze.http_headers.${c}="${d}"`);return o}var he=G("agent-handlers"),u0=5*1024*1024,xy=1,py=6,gy=new Set(["node_modules",".git",".coze","dist","build",".next"]),my=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,wy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,_y=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function yy(t){let e=t?.trim();return e?_y.test(e)||wy.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Ey(t){return new Promise((e,n)=>{let i=et("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=d=>{o||(o=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var go=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let n=Vn(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??je(n).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=me(o,h.relPath,"SKILL.md");await x0(x).then(g=>g.isFile()).catch(()=>!1)&&(d.push(ky(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await vy(n,o,h),m=await Sy(n,h);for(let g of[...x,...m])u.has(g.relPath)||(u.add(g.relPath),d.push(g.skill))}return{skills:d}}async addSkills(e){e._meta;let n=Vn(e._meta),i=await this.requireAgentCfg(n),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 mo({agentId:n,workspace:i.workspace,framework:i.framework,skill:h});wo(c,d,x),u.push(h)}return await oi(n,c),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=Vn(e._meta),i=await this.requireAgentCfg(n),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=me(i.workspace,u.relPath);await nd(h,{recursive:!0,force:!0}),he.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await oi(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=Vn(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");he.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??je(n).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=w0(e.skillName),h=await by(o,c,u,d);if(!h){let P=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${P}: ${e.skillName} (${u})`)}let{absDir:x,relPath:m}=h,g=me(x,"SKILL.md"),S=new ad.default;S.addLocalFolder(x,u);let _=S.toBuffer();if(_.length>f0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${f0}`);let v=await po(g,{encoding:"utf8"}).then(P=>E0(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):he.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??y0(n,m);if(i&&!d){let P=i.skills??[],E=P.find(R=>R.relPath===m);E?(E.version=A,E.skillId=T):P.push({skillId:T,skillName:e.skillName,relPath:m,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await oi(n,P)}return he.info("skill published",{agentId:n,skillName:e.skillName,relPath:m,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 d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:n,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:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),h.stop(n).catch(x=>he.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 he.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Ce(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return he.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await fr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw he.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 Be(i),he.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 Ce(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Li(e.registry)&&o.push(`--registry=${e.registry}`);let c=yy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&my.test(d)&&o.push("--env",d);let u=await Ey(o);return he.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 Ce(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Be(i),he.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}):(he.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",`${ut.DELETE}: missing agentId`);let i=await Ce(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 d=je(n);return c==="cloud"?await nd(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Be(i)),he.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Rr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Zc(e.model)??Ot,i=await Ce(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 Be(i),he.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,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=n,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: ${n}`).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:n,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Rr(e._meta,ut.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ut.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ut.RESET),await this.runDetailSync(e.agentId,ut.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){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(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,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await si(e,o)}async clearPersistedAcpSessionIds(e){let n=await Ce(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 Be(n)}async repairAgent(e){if(Rr(e._meta,ut.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ut.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ut.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.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,ut.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){he.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){he.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Rr(e._meta,"_agent/getFileTree");let n=e._meta,i=Vn(n),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await ed(d).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 ii(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=zy(e.depth);return u.isDirectory()?{tree:await Fy(o,d,c,h)}:{tree:[{name:Uy(c),path:I0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Rr(e._meta,"_agent/getFileContent");let n=Vn(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 ed(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 ii(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>u0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${u0})`);let d=await po(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 n=this.opts.agents.get(e);return n?n.workspace:(await Ce(e).catch(()=>null))?.workspace??je(e).workspace}safeJoin(e,n){let i=id(e,n||"."),o=od(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${p0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Ce(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 w0(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 cd(t){return t==="claude-code"?me(".claude","skills"):me(".agents","skills")}function _0(t){let e=uy();return t==="claude-code"?[me(e,".claude","skills")]:t==="codex"?[me(e,".agents","skills"),me(e,".codex","skills")]:[me(e,".agents","skills"),me(e,".openclaw","skills")]}async function by(t,e,n,i){let o=async c=>x0(me(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=me(cd(e),n),d=me(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of _0(e)){let d=me(c,n);if(await o(d))return{absDir:d,relPath:d}}return null}function y0(t,e){return(ly("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function E0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
- ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.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 b0(t,e,n,i){let o=await h0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let d of o){if(!d.isDirectory())continue;let u=d.name,h=me(n,u),x=me(e,u,"SKILL.md"),m=await po(x,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let g=E0(m);c.push({relPath:h,skill:{skillId:y0(t,h),skillName:g.name||u,...g.description?{description:g.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function vy(t,e,n){let i=cd(n);return b0(t,me(e,i),i,!1)}async function Sy(t,e){let n=[],i=new Set;for(let o of _0(e)){let c=await b0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var Iy=3e4,Ay=50*1024*1024,f0=10*1024*1024,Dr=3e4;async function mo(t){let{agentId:e,workspace:n,framework:i,skill:o}=t;if(!o.skillName)throw new k("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 k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=w0(o.skillName),h=cd(i),x=me(h,u),m=me(n,x);if(await td(m,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Bi(S.length),await rd(me(m,"SKILL.md"),S,"utf8")}else{let S=await Ry(o.downloadUrl);Py(S)?await Ny(S,m):Dy(S)?await Oy(S,m):await rd(me(m,"SKILL.md"),S.toString("utf8"),"utf8")}let g={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"}),g}function wo(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 ky(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 Ty(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 v0(t,e){let n=await Ce(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Dt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Be(n,e),{status:"seeded",count:0};let c=[...n.skills??[]],d=new Map(c.map((m,g)=>[m.skillId,g])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Be(n,e),{status:"noop",count:0};let h=0,x=0;for(let m of u)try{await nd(me(n.workspace,m.relPath),{recursive:!0,force:!0});let g=await mo({agentId:t,workspace:n.workspace,framework:n.framework,skill:Ty(m)});wo(c,d,g),h+=1}catch(g){x+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(g)})}return n.skills=c,x===0&&(n.skillsRefreshedForVersion=i),await Be(n,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 Ry(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Bi(e);let n=Cy(t);return Bi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await po(e);return Bi(n.length),n}if(Li(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Iy);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 Bi(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 Bi(t){if(t>Ay)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Cy(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 Py(t){return t.length>=2&&t[0]===31&&t[1]===139}function Dy(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 sd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Oy(t,e){let n,i;try{n=new ad.default(t),i=n.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||sd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Ly(i),c=id(e);for(let d of i){if(sd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=id(e,u),x=od(c,h);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await td(h,{recursive:!0});continue}await td(fy(h),{recursive:!0});let m;try{m=d.getData()}catch(g){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${g.message}`,{cause:g})}await rd(h,m)}}function Ly(t){let e;for(let n of t){let i=n.entryName;if(!i||sd(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 Ny(t,e){await My(t);let n=Wf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Dr}ms)`))},Dr);try{await m0(g0.from(t),n)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Dr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function My(t){let e=[],n=Tr({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,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Dr}ms)`))},Dr);try{await m0(g0.from(t),n)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Dr}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 By=5e3;async function Fy(t,e,n,i){return S0(t,e,n,i,{count:0})}async function S0(t,e,n,i,o){if(i<=0)return[];let c;try{c=await h0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(gy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=By){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=me(e,u.name),x=hy(me(n,u.name)),m=null;try{m=await ed(h)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let g={name:u.name,path:I0(od(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(g.children=await S0(t,h,x,i-1,o)),d.push(g)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function zy(t){return!t||t<=0?xy:Math.min(t,py)}function Uy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function I0(t){return t.split(p0).join("/")}ne();var An=G("agent-health-reporter"),Gy=1e4,Hy=3,Fi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Gy,this.livenessFailureThreshold=e.livenessFailureThreshold??Hy}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),An.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),An.info("heartbeat stopped"))}async tick(){if(this.inFlight){An.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,An.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=Wy(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),n.push(h)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Dt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,An.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(An.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){An.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){An.warn("onTickEnd hook failed",{err:String(n)})}}};function Wy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}fn();import{mkdir as md,rm as eb,stat as tb}from"node:fs/promises";import{homedir as nb}from"node:os";import{join as wd}from"node:path";an();import{existsSync as nE}from"node:fs";import{release as rE}from"node:os";import{basename as iE,isAbsolute as sE}from"node:path";function zi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Or(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Lr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function kn(t,e){return{jsonrpc:"2.0",id:t,error:e}}qe();var _o=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function A0(t){return"method"in t&&"id"in t&&t.id!==void 0}function k0(t){return"method"in t&&!("id"in t)}function yo(t){return!("method"in t)&&"id"in t}var qy={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function jy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ui(t.message)}:typeof t=="string"?Ui(t):typeof t=="object"?$y(t):t}var Ky=[[/\/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 Ui(t){let e=t;for(let[n,i]of Ky)e=e.replace(n,i);return e}function $y(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Ui(i):e[n]=i;return e}function Gi(t){if(t instanceof k){let e=jy(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:qy[t.code]??Y.INTERNAL_ERROR,message:Ui(t.message),data:n}}return{code:Y.INTERNAL_ERROR,message:Ui(t instanceof Error?t.message:String(t))}}function T0(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:d,...u}=e;c=u}return new k(n,o,{retriable:e?.retriable??!1,cause:c})}function C0(t){return`${JSON.stringify(t)}
95
- `}var R0=10*1024*1024,Eo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>R0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${R0} bytes`)}),[]}let n=this.buffer.split(`
96
- `);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(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(n){return this.onError?.({line:e,error:n}),[]}}};var D0={"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"},fT=Object.fromEntries(Object.entries(D0).map(([t,e])=>[e,t])),Vy={"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:[]},Nr=class{seq=0;next(e,n){this.seq+=1;let i=D0[e]??Jy(e),o=Vy[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(h=>P0(n?.[h]??"")),u=Zy(d).join(":");u&&c.push(u)}else n&&Object.values(n).some(d=>d)&&c.push(Object.values(n).filter(Boolean).map(d=>P0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Jy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function P0(t){return t.replace(/[:_\s]+/g,"-")}function Zy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}un();import{readFileSync as Yy}from"node:fs";var Xy=384;async function dd(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await ln(t.agentEnvFile,n,{mode:Xy})}function Hi(t){try{let e=JSON.parse(Yy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function bo(t,e,n={},i=o=>o){return{...i({...t,...Hi(e)}),...n}}Jt();ar();qe();ne();Re();import{execFileSync as Qy,spawnSync as eE}from"node:child_process";function Wi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function qi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),eE("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ld=new Set;function O0(t){typeof t=="number"&&t>0&&ld.add(t)}function L0(t){typeof t=="number"&&ld.delete(t)}function N0(){for(let t of ld)qi(t,"SIGKILL")}var Mr="coze-bridge-daemon";function M0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Qy("pgrep",["-U",String(o),"-f",Mr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
97
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function B0(t,e){if(t.length===0)return;let n=e?.killFn??qi,i=e?.isAliveFn??Wi,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(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)&&n(u,"SIGKILL")}var tE=[{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[^\n]*node_modules[\\/]@(agentclientprotocol[\\/]claude-agent-acp|zed-industries[\\/]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 F0(t,e){if(!e)return null;for(let n of tE)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function z0(t,e){return F0(t,e)}function U0(t,e){return F0(t,e)}function Br(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 G0(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:Br(m,t.firstFrameSeen,e)}}let c=n-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:Br(c,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Br(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Br(c,!1,e)}}var H0=$e("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),oE=200,aE=40,cE=$e("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),dE=$e("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),lE=$e("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),uE=$e("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),fE=$e("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),hE=$e("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),W0=500;function xE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=W0?t:`${e.slice(0,W0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function pE(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 q0(t){try{return nE(t)}catch{return}}function gE(t,e){return{platform:process.platform,osRelease:rE(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:sE(e.command)?q0(e.command):void 0,cwd:e.cwd,cwdExists:q0(e.cwd),envKeys:e.envKeys}}function mE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${iE(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Lt=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Eo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Nr;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=bo(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=et(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,O0(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>oE&&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,L0(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=gE(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",mE(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 n=this.child,i=new Promise(c=>n.once("exit",()=>c()));qi(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||qi(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:fE,phase2GateMs:cE,livenessWindowMs:dE,absoluteMaxMs:lE,approvalMaxMs:hE,suspendThresholdMs:uE,...n};return this.call("session/prompt",e,H0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Or("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,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Lr(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(kn(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=H0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=zi(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 g=this.now(),S={cfg:o,startedAt:g,lastActivityAt:g,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:g,expectedIntervalMs:Br(0,!1,o),sessionId:u};m.promptTimeout=S;let _=()=>{let v={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),A=G0(v,S.cfg,I),T=P=>{S.armedAt=I,S.expectedIntervalMs=P,m.timer=setTimeout(_,P)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(_,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(g){m.timer&&clearTimeout(m.timer),this.pending.delete(c),x(g)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(C0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(yo(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:xE(e.result)}),n.resolve(e.result));return}if(k0(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(A0(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 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(kn(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(kn(e.id,Gi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=T0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=U0(this.framework,pE(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(aE).join(`
98
- `),o=z0(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 wE(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=i));return e}var vo=class extends Lt{framework="claude-code";constructor(e){let{command:n,args:i}=ri("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 wE(e)}};an();import{spawn as _E}from"node:child_process";import{closeSync as yE,existsSync as hd,mkdirSync as EE,mkdtempSync as bE,openSync as vE,readFileSync as Y0,readSync as SE,readdirSync as IE,rmSync as AE,statSync as kE}from"node:fs";import{homedir as TE,tmpdir as RE}from"node:os";import{join as Fr}from"node:path";var j0=["default","acceptEdits","plan","auto","bypassPermissions"],K0=["read-only","auto","full-access"];function Nt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return j0.includes(e);case"codex":return K0.includes(e);case"openclaw":return!1}}function $0(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function V0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function ud(t){switch(t){case"claude-code":return j0.join("/");case"codex":return K0.join("/");case"openclaw":return""}}Re();var xd=9e4,CE=64*1024,PE=100;function DE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?xd:Math.max(1,Math.floor(e*1e3))}function OE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?xd:Math.max(1,Math.floor(e))}function LE(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return Object.keys(e).length>0?e:void 0}function J0(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:xd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let n=typeof e.command=="string"?e.command.trim():"";if(!n)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,o=LE(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?DE(e.timeout):OE(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function fd(t){if(Array.isArray(t))return t.flatMap(i=>fd(i));if(!t||typeof t!="object"){let i=J0(t);return i?[i]:[]}let e=t;if(e.hooks)return fd(e.hooks);let n=J0(e);return n?[n]:[]}function NE(t){let e=Fr(t,"hooks.json");if(!hd(e))return[];let n=JSON.parse(Y0(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return fd(o.Stop??o.stop)}function ME(t,e){let n=Fr(t,"sessions");if(!hd(n))return;let i=[],o=c=>{let d;try{d=IE(c,{withFileTypes:!0})}catch{return}for(let u of d){let h=Fr(c,u.name);if(u.isDirectory())o(h);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:h,mtimeMs:kE(h).mtimeMs})}catch{}}};o(n),i.sort((c,d)=>d.mtimeMs-c.mtimeMs);for(let c of i.slice(0,PE))if(BE(c.path,e))return c.path;return i[0]?.path}function BE(t,e){let n;try{n=vE(t,"r");let i=Buffer.alloc(CE),o=SE(n,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(n!==void 0)try{yE(n)}catch{}}}function FE(t){return Hi(t??J().agentEnvFile)}function zE(t){let e=t.trim();if(e.length>=2){let n=e[0];if((n==='"'||n==="'")&&e.endsWith(n)){let i=e.slice(1,-1);return n==='"'?i.replace(/\\n/g,`
99
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function UE(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.startsWith("export ")?i.slice(7).trimStart():i,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]=zE(o.slice(c+1)))}return e}function GE(t){let e=Fr(t,"cozeloop.env");return hd(e)?UE(Y0(e,"utf8")):{}}function Z0(t){let e=t?.trim();return e||void 0}function HE(t){let e=FE(t.agentEnvFile),n=Z0(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=Z0(t.env?.HOME??e.HOME??process.env.HOME)??TE();return Fr(i,".codex")}var So=class extends Lt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:c}=ri("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??bE(Fr(RE(),"coze-bridge-codex-home-")):HE(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&EE(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 n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=Nt("codex",e.modeId)?$0(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(WE(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=NE(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let o=ME(n,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:n,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,n){return new Promise((i,o)=>{let c=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=c?GE(c):{},u=_E(e.command,{cwd:e.cwd??this.opts.cwd,env:bo(process.env,this.opts.agentEnvFile??J().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}}),shell:!0,stdio:["pipe","ignore","pipe"]}),h="",x=setTimeout(()=>{u.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);u.stderr?.setEncoding("utf8"),u.stderr?.on("data",m=>{h+=m,h.length>4e3&&(h=h.slice(-4e3))}),u.on("error",m=>{clearTimeout(x),o(m)}),u.on("close",(m,g)=>{if(clearTimeout(x),m===0){i();return}o(new Error(`hook exited code=${m} signal=${g} stderr=${h.slice(-1e3)}`))}),u.stdin.end(`${n}
100
- `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{AE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function WE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=V0(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}qe();var qE=3e4,zr=class extends Lt{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}`}]},qE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};un();qe();ne();Re();function pd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}an();var Tn=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 Io=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 Tn,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)ji(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 ji(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Zt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Jt();ne();import{constants as X0}from"node:fs";import{access as jE}from"node:fs/promises";import{delimiter as KE,join as $E}from"node:path";var Et=G("framework-detector"),Q0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},VE=[".exe",".cmd",".bat",".ps1"],Jn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??et,access:e.access??jE}}async detect(e){let n=Q0[e],i=await this.which(n);if(!i)return Et.debug("framework binary not found",{framework:e,bin:n}),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(Q0).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(KE).filter(Boolean),i=this.env.platform==="win32"?["",...VE]:[""];for(let o of n)for(let c of i){let d=$E(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?X0.F_OK:X0.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return Et.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return Et.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return Et.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return Et.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(Et.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}:(Et.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return Et.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return Et.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||Et.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},c=n.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){Et.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(ZE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){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,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{o+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},JE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function ZE(t){return t.replace(JE,"")}import{homedir as th}from"node:os";import{join as ko}from"node:path";un();Jt();ar();qe();ne();async function nh(){let t=ko(th(),".openclaw/openclaw.json");return cn(t)}async function rh(){return(await nh())?.gateway?.auth?.token??""}var Zn=G("openclaw.config"),YE=[0,5e3,5e3],XE=$e("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),eh="models.providers.",Ao="agents.defaults.models",QE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function gd(t,e){if(!Array.isArray(t))return!1;let n=new Set(t);return e.every(i=>n.has(i))}var To=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Tn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??YE,this.cliTimeoutMs=e.cliTimeoutMs??XE,this.openclawDir=e.openclawDir??ko(th(),".openclaw")}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(d=>setTimeout(d,c));try{return await n()}catch(d){i=d,Zn.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=et(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?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.runCli(["config","unset",n])))}catch(i){Zn.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",`${eh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${eh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ao}[${e}]`,()=>this.runCli(["config","set",Ao,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ao}[${e}]`,`${Ao}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await nh())?.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,n,i){let o=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}async ensureAcpDeviceScopes(){try{let e=ko(this.openclawDir,"identity","device.json"),i=(await cn(e))?.deviceId?.trim();if(!i)return Zn.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=ko(this.openclawDir,"devices","paired.json"),c=await cn(o),d=c?.[i];if(!c||!d)return Zn.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=[...QE],h=d.tokens?.operator;return gd(d.scopes,u)&&gd(d.approvedScopes,u)&&gd(h?.scopes,u)?(Zn.debug("acp device already has full operator scopes",{deviceId:i}),!1):(d.scopes=[...u],d.approvedScopes=[...u],h&&(h.scopes=[...u]),await ln(o,c,{mode:384}),Zn.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:u}),!0)}catch(e){return Zn.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};var le=G("agent-manager"),yd="acceptEdits",oh="full-access",ah="read-only";function rb(t){switch(t){case"read-only":return["-c",'sandbox_mode="read-only"',"-c",'approval_policy="on-request"'];case"auto":return["-c",'sandbox_mode="workspace-write"',"-c",'approval_policy="on-failure"'];case"full-access":return["-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"']}}var ib=(t,e,n,i,o,c,d,u,h,x,m)=>{switch(t){case"claude-code":{let g={...o?{...s0(o),...c0(o,d,u)}:{},...h??{},IS_SANDBOX:"1"};return new vo({cwd:n,env:g,agentId:i})}case"codex":{let g=o?[...o0(o),...l0(o,d,u)]:[],S=oh;x!==void 0&&(Nt("codex",x)?S=x:le.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _=[...g,...rb(S)],v={...o?a0(o):{},...h??{}},I=!!o;return new So({cwd:n,agentId:i,..._.length>0?{extraArgs:_}:{},...Object.keys(v).length>0?{env:v}:{},...I?{authMethodId:"openai-api-key",isolateCodexHome:!0,...m?{codexHomeDir:m}:{}}:{}})}case"openclaw":return new zr({command:e,cwd:n,agentId:i,...c?{sessionName:pd(c)}:{}})}};function _d(t){return t==="claude-code"||t==="codex"}function sb(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(ob(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return _2(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 Fp("schtasks",["/Create","/SC","ONLOGON","/TN",ya,"/TR",r,"/RU",t.userName,"/F"]),al.info("task scheduler entry created",{task:ya,logFile:t.logFile})},async uninstall(t){await Fp("schtasks",["/Delete","/TN",ya,"/F"]).catch(e=>al.warn("schtasks /Delete failed (ignored)",{err:String(e)})),al.info("task scheduler entry removed",{task:ya})}}});var Up={};La(Up,{buildContext:()=>I2,getSupervisor:()=>E2,launchdSupervisor:()=>sl,systemdSupervisor:()=>ol,taskSchedulerSupervisor:()=>cl});import{homedir as y2,userInfo as b2}from"node:os";function E2(t=process.platform){switch(t){case"darwin":return sl;case"linux":return ol;case"win32":return cl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function S2(){let t={};for(let e of v2){let r=process.env[e];r&&(t[e]=r)}return t}function I2(){let t=Z();return{nodeBin:process.execPath,entry:Zd(t),logFile:t.logFile,homeDir:y2(),userName:b2().username,isRoot:process.getuid?.()===0,env:S2()}}var v2,Gp=nt(()=>{"use strict";Re();la();Np();Bp();zp();v2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();ln();var zl=G("acp-installer-warmup"),pg=["claude-code","codex"];async function Ul(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(pg.map(async o=>{let c=await e(o);zl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&zl.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))})}Wt();te();import{readdir as Dg}from"node:fs/promises";import{mkdir as jl,readFile as Cg,writeFile as Wl}from"node:fs/promises";import{join as Ga}from"node:path";var Rg={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function xr(t,e,r){await jl(t,{recursive:!0});let i=Rg[e],o=Ga(t,i);return await Wl(o,r??"","utf8"),o}async function Ha(t,e,r){let i=Ga(t,".claude");await jl(i,{recursive:!0});let o=Ga(i,"settings.local.json"),c={};try{let u=await Cg(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}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 Wl(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=G("agent-detail-sync"),Pg=6e4,Og=5*6e4,vs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Dg(r)}catch(o){Xe.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Xe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await ve(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Xe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Xe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Xe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Xe.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Xe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await ve(e,this.opts.paths);if(!i){Xe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let h=this.retryQueue.get(e),g=h?Math.min(h.currentDelay*2,Og):Pg;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(o.agentId&&o.agentId!==e){Xe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let 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"?(Xe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Xe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Xe.debug("detail sync: no diff",{agentId:e});return}await Ue(i,this.opts.paths),Xe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Xe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await xr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var xd=qt(Su(),1);import{createHash as by}from"node:crypto";import{lstat as sd,mkdir as od,readFile as _o,readdir as m0,rm as ad,stat as ud,writeFile as cd}from"node:fs/promises";import{homedir as Ey}from"node:os";import{basename as x0,dirname as vy,join as le,normalize as Sy,relative as fd,resolve as dd,sep as g0}from"node:path";import{Readable as w0}from"node:stream";import{pipeline as _0}from"node:stream/promises";import tw from"events";import it from"fs";import{EventEmitter as Gc}from"node:events";import of from"node:stream";import{StringDecoder as nw}from"node:string_decoder";import df from"node:path";import Ir from"node:fs";import{dirname as pw,parse as mw}from"path";import{EventEmitter as Sw}from"events";import Ec from"assert";import{Buffer as qn}from"buffer";import*as Cu from"zlib";import Iw from"zlib";import{posix as wr}from"node:path";import{basename as Xw}from"node:path";import to from"fs";import Pt from"fs";import Mu from"path";import{win32 as l_}from"node:path";import qu from"path";import Sf from"node:fs";import k_ from"node:assert";import{randomBytes as If}from"node:crypto";import ie from"node:fs";import Be from"node:path";import Af from"fs";import uo from"node:fs";import ki from"node:path";import ct from"node:fs";import L_ from"node:fs/promises";import io from"node:path";import{join as Bf}from"node:path";import at from"node:fs";import Uf from"node:path";var Qg=Object.defineProperty,ew=(t,e)=>{for(var r in e)Qg(t,r,{get:e[r],enumerable:!0})},Iu=typeof process=="object"&&process?process:{stdout:null,stderr:null},rw=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof of||iw(t)||sw(t)),iw=t=>!!t&&typeof t=="object"&&t instanceof Gc&&typeof t.pipe=="function"&&t.pipe!==of.Writable.prototype.pipe,sw=t=>!!t&&typeof t=="object"&&t instanceof Gc&&typeof t.write=="function"&&typeof t.end=="function",Kt=Symbol("EOF"),$t=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),Ts=Symbol("emittingEnd"),li=Symbol("emittedError"),Cs=Symbol("closed"),Au=Symbol("read"),Rs=Symbol("flush"),ku=Symbol("flushChunk"),bt=Symbol("encoding"),gr=Symbol("decoder"),Ge=Symbol("flowing"),ui=Symbol("paused"),Er=Symbol("resume"),He=Symbol("buffer"),Qe=Symbol("pipes"),qe=Symbol("bufferLength"),Va=Symbol("bufferPush"),Ds=Symbol("bufferShift"),Ye=Symbol("objectMode"),ke=Symbol("destroyed"),Ja=Symbol("error"),Za=Symbol("emitData"),Tu=Symbol("emitEnd"),Ya=Symbol("emitEnd2"),Ct=Symbol("async"),Xa=Symbol("abort"),Ps=Symbol("aborted"),fi=Symbol("signal"),Ln=Symbol("dataListeners"),ot=Symbol("discarded"),xi=t=>Promise.resolve().then(t),ow=t=>t(),aw=t=>t==="end"||t==="finish"||t==="prefinish",cw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,dw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),af=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,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()}},lw=class extends af{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)}},uw=t=>!!t.objectMode,fw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Gc{[Ge]=!1;[ui]=!1;[Qe]=[];[He]=[];[Ye];[bt];[Ct];[gr];[Kt]=!1;[fn]=!1;[Ts]=!1;[Cs]=!1;[li]=null;[qe]=0;[ke]=!1;[fi];[Ps]=!1;[Ln]=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");uw(e)?(this[Ye]=!0,this[bt]=null):fw(e)?(this[bt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[bt]=null),this[Ct]=!!e.async,this[gr]=this[bt]?new nw(this[bt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:r}=e;r&&(this[fi]=r,r.aborted?this[Xa]():r.addEventListener("abort",()=>this[Xa]()))}get bufferLength(){return this[qe]}get encoding(){return this[bt]}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[Ct]}set async(t){this[Ct]=this[Ct]||!!t}[Xa](){this[Ps]=!0,this.emit("abort",this[fi]?.reason),this.destroy(this[fi]?.reason)}get aborted(){return this[Ps]}set aborted(t){}write(t,e,r){if(this[Ps])return!1;if(this[Kt])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"&&(r=e,e="utf8"),e||(e="utf8");let i=this[Ct]?xi:ow;if(!this[Ye]&&!Buffer.isBuffer(t)){if(dw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(cw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[Ge]&&this[qe]!==0&&this[Rs](!0),this[Ge]?this.emit("data",t):this[Va](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[Ge]):t.length?(typeof t=="string"&&!(e===this[bt]&&!this[gr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[bt]&&(t=this[gr].write(t)),this[Ge]&&this[qe]!==0&&this[Rs](!0),this[Ge]?this.emit("data",t):this[Va](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[Ge]):(this[qe]!==0&&this.emit("readable"),r&&i(r),this[Ge])}read(t){if(this[ke])return null;if(this[ot]=!1,this[qe]===0||t===0||t&&t>this[qe])return this[$t](),null;this[Ye]&&(t=null),this[He].length>1&&!this[Ye]&&(this[He]=[this[bt]?this[He].join(""):Buffer.concat(this[He],this[qe])]);let e=this[Au](t||null,this[He][0]);return this[$t](),e}[Au](t,e){if(this[Ye])this[Ds]();else{let r=e;t===r.length||t===null?this[Ds]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[qe]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[qe]-=t)}return this.emit("data",e),!this[He].length&&!this[Kt]&&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[Kt]=!0,this.writable=!1,(this[Ge]||!this[ui])&&this[$t](),this}[Er](){this[ke]||(!this[Ln]&&!this[Qe].length&&(this[ot]=!0),this[ui]=!1,this[Ge]=!0,this.emit("resume"),this[He].length?this[Rs]():this[Kt]?this[$t]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[Ge]=!1,this[ui]=!0,this[ot]=!1}get destroyed(){return this[ke]}get flowing(){return this[Ge]}get paused(){return this[ui]}[Va](t){this[Ye]?this[qe]+=1:this[qe]+=t.length,this[He].push(t)}[Ds](){return this[Ye]?this[qe]-=1:this[qe]-=this[He][0].length,this[He].shift()}[Rs](t=!1){do;while(this[ku](this[Ds]())&&this[He].length);!t&&!this[He].length&&!this[Kt]&&this.emit("drain")}[ku](t){return this.emit("data",t),this[Ge]}pipe(t,e){if(this[ke])return t;this[ot]=!1;let r=this[fn];return e=e||{},t===Iu.stdout||t===Iu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Qe].push(e.proxyErrors?new lw(this,t,e):new af(this,t,e)),this[Ct]?xi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[Qe].find(r=>r.dest===t);e&&(this[Qe].length===1?(this[Ge]&&this[Ln]===0&&(this[Ge]=!1),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[ot]=!1,this[Ln]++,!this[Qe].length&&!this[Ge]&&this[Er]();else if(t==="readable"&&this[qe]!==0)super.emit("readable");else if(aw(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[li]){let i=e;this[Ct]?xi(()=>i.call(this,this[li])):i.call(this,this[li])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[ot]&&!this[Qe].length&&(this[Ge]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[ot]&&!this[Qe].length&&(this[Ge]=!1)),e}get emittedEnd(){return this[fn]}[$t](){!this[Ts]&&!this[fn]&&!this[ke]&&this[He].length===0&&this[Kt]&&(this[Ts]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Cs]&&this.emit("close"),this[Ts]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==ke&&this[ke])return!1;if(t==="data")return!this[Ye]&&!r?!1:this[Ct]?(xi(()=>this[Za](r)),!0):this[Za](r);if(t==="end")return this[Tu]();if(t==="close"){if(this[Cs]=!0,!this[fn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[li]=r,super.emit(Ja,r);let o=!this[fi]||this.listeners("error").length?super.emit("error",r):!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}[Za](t){for(let r of this[Qe])r.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[$t](),e}[Tu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[Ct]?(xi(()=>this[Ya]()),!0):this[Ya]())}[Ya](){if(this[gr]){let e=this[gr].end();if(e){for(let r of this[Qe])r.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[Qe])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",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[bt]?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",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[Kt])return e();let i,o,c=h=>{this.off("data",d),this.off("end",u),this.off(ke,f),e(),o(h)},d=h=>{this.off("error",c),this.off("end",u),this.off(ke,f),this.pause(),i({value:h,done:!!this[Kt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(ke,f),e(),i({done:!0,value:void 0})},f=()=>c(new Error("stream destroyed"));return new Promise((h,g)=>{o=g,i=h,this.once(ke,f),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(Ja,e),this.off(ke,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(Ja,e),this.once(ke,e),{next:r,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[ot]=!0,this[He].length=0,this[qe]=0;let e=this;return typeof e.close=="function"&&!this[Cs]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return rw}},xw=it.writev,En=Symbol("_autoClose"),It=Symbol("_close"),hi=Symbol("_ended"),de=Symbol("_fd"),Qa=Symbol("_finished"),Yt=Symbol("_flags"),ec=Symbol("_flush"),yc=Symbol("_handleChunk"),bc=Symbol("_makeBuf"),Ii=Symbol("_mode"),Os=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),tc=Symbol("_onread"),vr=Symbol("_onwrite"),vn=Symbol("_open"),St=Symbol("_path"),gn=Symbol("_pos"),Rt=Symbol("_queue"),Sr=Symbol("_read"),nc=Symbol("_readSize"),Zt=Symbol("_reading"),pi=Symbol("_remain"),rc=Symbol("_size"),qs=Symbol("_write"),Nn=Symbol("_writing"),js=Symbol("_defaultFlag"),Hn=Symbol("_errored"),Hc=class extends Kn{[Hn]=!1;[de];[St];[nc];[Zt]=!1;[rc];[pi];[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[de]=typeof e.fd=="number"?e.fd:void 0,this[St]=t,this[nc]=e.readSize||16*1024*1024,this[Zt]=!1,this[rc]=typeof e.size=="number"?e.size:1/0,this[pi]=this[rc],this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[Sr]():this[vn]()}get fd(){return this[de]}get path(){return this[St]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){it.open(this[St],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[de]=e,this.emit("open",e),this[Sr]())}[bc](){return Buffer.allocUnsafe(Math.min(this[nc],this[pi]))}[Sr](){if(!this[Zt]){this[Zt]=!0;let t=this[bc]();if(t.length===0)return process.nextTick(()=>this[tc](null,0,t));it.read(this[de],t,0,t.length,null,(e,r,i)=>this[tc](e,r,i))}}[tc](t,e,r){this[Zt]=!1,t?this[kr](t):this[yc](e,r)&&this[Sr]()}[It](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Zt]=!0,this[It](),this.emit("error",t)}[yc](t,e){let r=!1;return this[pi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[pi]<=0)&&(r=!1,this[It](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[Sr](),!1;case"error":return this[Hn]?!1:(this[Hn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},hw=class extends Hc{[vn](){let t=!0;try{this[Tr](null,it.openSync(this[St],"r")),t=!1}finally{t&&this[It]()}}[Sr](){let t=!0;try{if(!this[Zt]){this[Zt]=!0;do{let e=this[bc](),r=e.length===0?0:it.readSync(this[de],e,0,e.length,null);if(!this[yc](r,e))break}while(!0);this[Zt]=!1}t=!1}finally{t&&this[It]()}}[It](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.closeSync(t),this.emit("close")}}},so=class extends tw{readable=!1;writable=!0;[Hn]=!1;[Nn]=!1;[hi]=!1;[Rt]=[];[Os]=!1;[St];[Ii];[En];[de];[js];[Yt];[Qa]=!1;[gn];constructor(t,e){e=e||{},super(e),this[St]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Ii]=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 r=this[gn]!==void 0?"r+":"w";this[js]=e.flags===void 0,this[Yt]=e.flags===void 0?r:e.flags,this[de]===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[de]}get path(){return this[St]}[kr](t){this[It](),this[Nn]=!0,this.emit("error",t)}[vn](){it.open(this[St],this[Yt],this[Ii],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[js]&&this[Yt]==="r+"&&t&&t.code==="ENOENT"?(this[Yt]="w",this[vn]()):t?this[kr](t):(this[de]=e,this.emit("open",e),this[Nn]||this[ec]())}end(t,e){return t&&this.write(t,e),this[hi]=!0,!this[Nn]&&!this[Rt].length&&typeof this[de]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[hi]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[Nn]||this[Rt].length?(this[Rt].push(t),this[Os]=!0,!1):(this[Nn]=!0,this[qs](t),!0)}[qs](t){it.write(this[de],t,0,t.length,this[gn],(e,r)=>this[vr](e,r))}[vr](t,e){t?this[kr](t):(this[gn]!==void 0&&typeof e=="number"&&(this[gn]+=e),this[Rt].length?this[ec]():(this[Nn]=!1,this[hi]&&!this[Qa]?(this[Qa]=!0,this[It](),this.emit("finish")):this[Os]&&(this[Os]=!1,this.emit("drain"))))}[ec](){if(this[Rt].length===0)this[hi]&&this[vr](null,0);else if(this[Rt].length===1)this[qs](this[Rt].pop());else{let t=this[Rt];this[Rt]=[],xw(this[de],t,this[gn],(e,r)=>this[vr](e,r))}}[It](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},cf=class extends so{[vn](){let t;if(this[js]&&this[Yt]==="r+")try{t=it.openSync(this[St],this[Yt],this[Ii])}catch(e){if(e?.code==="ENOENT")return this[Yt]="w",this[vn]();throw e}else t=it.openSync(this[St],this[Yt],this[Ii]);this[Tr](null,t)}[It](){if(this[En]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.closeSync(t),this.emit("close")}}[qs](t){let e=!0;try{this[vr](null,it.writeSync(this[de],t,0,t.length,this[gn])),e=!1}finally{if(e)try{this[It]()}catch{}}}},gw=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"]]),ww=t=>!!t.sync&&!!t.file,_w=t=>!t.sync&&!!t.file,yw=t=>!!t.sync&&!t.file,bw=t=>!t.sync&&!t.file,Ew=t=>!!t.file,vw=t=>gw.get(t)||t,qc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=vw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Li=(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 f=qc(c);if(o?.(f,d),ww(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(_w(f)){let h=e(f,d);return u?h.then(()=>u(),u):h}else if(yw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(f,d)}else if(bw(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),Aw=Iw.constants||{ZLIB_VERNUM:4736},Lt=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},Aw)),kw=qn.concat,Ru=Object.getOwnPropertyDescriptor(qn,"concat"),Tw=t=>t,ic=Ru?.writable===!0||Ru?.set!==void 0?t=>{qn.concat=t?Tw:kw}:t=>{},jn=Symbol("_superWrite"),Ls=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"}},sc=Symbol("flushFlag"),jc=class extends Kn{#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 Cu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Cu[e](t)}catch(r){throw new Ls(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 Ls(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Ec(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),{[sc]: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}[jn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=qn.from(t,e)),this.#e)return;Ec(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},ic(!0);let d;try{let f=typeof t[sc]=="number"?t[sc]:this.#r;d=this.#t._processChunk(t,f),ic(!1)}catch(f){ic(!1),this.#o(new Ls(f,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",f=>this.#o(new Ls(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[jn](qn.from(f));for(let h=1;h<d.length;h++)u=this[jn](d[h])}else u=this[jn](qn.from(d));return r&&r(),u}},lf=class extends jc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Lt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Lt.Z_FINISH,t.fullFlushFlag=Lt.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(Lt.Z_SYNC_FLUSH),Ec(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)}}}},Cw=class extends lf{#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)}},Rw=class extends lf{constructor(t){super(t,"Unzip")}},uf=class extends jc{constructor(t,e){t=t||{},t.flush=t.flush||Lt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Lt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Lt.BROTLI_OPERATION_FLUSH,super(t,e)}},Dw=class extends uf{constructor(t){super(t,"BrotliCompress")}},Pw=class extends uf{constructor(t){super(t,"BrotliDecompress")}},ff=class extends jc{constructor(t,e){t=t||{},t.flush=t.flush||Lt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Lt.ZSTD_e_end,t.fullFlushFlag=Lt.ZSTD_e_flush,super(t,e)}},Ow=class extends ff{constructor(t){super(t,"ZstdCompress")}},Lw=class extends ff{constructor(t){super(t,"ZstdDecompress")}},Nw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Bw(t,e):Mw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Mw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Bw=(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]=xf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=hf(o))}},Fw=t=>{let e=t[0],r=e===128?Uw(t.subarray(1,t.length)):e===255?zw(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},zw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=xf(c):c===0?d=c:(i=!0,d=hf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Uw=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},xf=t=>(255^t)&255,hf=t=>(255^t)+1&255,Gw={};ew(Gw,{code:()=>Wc,isCode:()=>Ws,isName:()=>Hw,name:()=>oo,normalFsTypes:()=>pf});var Ws=t=>oo.has(t),Hw=t=>Wc.has(t),pf=new Set(["0","","1","2","3","4","5","6","7","D"]),oo=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"]]),Wc=new Map(Array.from(oo).map(t=>[t[1],t[0]])),Wn=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=Mn(t,e+156,1),c=pf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Mn(t,e,100),this.mode=d?.mode??u?.mode??wn(t,e+100,8),this.uid=d?.uid??u?.uid??wn(t,e+108,8),this.gid=d?.gid??u?.gid??wn(t,e+116,8),this.size=d?.size??u?.size??wn(t,e+124,12),this.mtime=d?.mtime??u?.mtime??oc(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Ws(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=d?.uname??u?.uname??Mn(t,e+265,32),this.gname=d?.gname??u?.gname??Mn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??wn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??wn(t,e+337,8)??0,t[e+475]!==0){let h=Mn(t,e+345,155);this.path=h+"/"+this.path}else{let h=Mn(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=r?.atime??i?.atime??oc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??oc(t,e+488,12)}let f=256;for(let h=e;h<e+148;h++)f+=t[h];for(let h=e+156;h<e+512;h++)f+=t[h];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||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=qw(this.path||"",r),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=ac(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,r,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=ac(t,e+476,12,this.atime)||this.needPax,this.needPax=ac(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,_n(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:oo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Wc.get(t));if(Ws(e)||e==="Unsupported")this.#e=e;else if(Ws(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},qw=(t,e)=>{let r=t,i="",o,c=wr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=wr.dirname(r),r=wr.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=wr.join(wr.basename(i),r),i=wr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Mn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),oc=(t,e,r)=>jw(wn(t,e,r)),jw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,r)=>Number(t[e])&128?Fw(t.subarray(e,e+r)):Kw(t,e,r),Ww=t=>isNaN(t)?void 0:t,Kw=(t,e,r)=>Ww(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),$w={12:8589934591,8:2097151},_n=(t,e,r,i)=>i===void 0?!1:i>$w[r]||i<0?(Nw(i,t.subarray(e,e+r)),!0):(Vw(t,e,r,i),!1),Vw=(t,e,r,i)=>t.write(Jw(i,r),e,r,"ascii"),Jw=(t,e)=>Zw(Math.floor(t).toString(8),e),Zw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",ac=(t,e,r,i)=>i===void 0?!1:_n(t,e,r,i.getTime()/1e3),Yw=new Array(156).join("\0"),Bn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Yw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),eo=class mf{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 Wn({path:("PaxHeader/"+Xw(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 mf(Qw(e_(e),r),i)}},Qw=(t,e)=>e?Object.assign({},e,t):t,e_=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(t_,Object.create(null)),t_=(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("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(d)*1e3):/^[0-9]+$/.test(d)?+d:d,t},n_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=n_!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),r_=class extends Kn{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))))}},ao=(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))},i_=1024*1024,vc=Buffer.from([31,139]),Sc=Buffer.from([40,181,47,253]),s_=Math.max(vc.length,Sc.length),ft=Symbol("state"),Fn=Symbol("writeEntry"),Vt=Symbol("readEntry"),cc=Symbol("nextEntry"),Du=Symbol("processEntry"),Dt=Symbol("extendedHeader"),mi=Symbol("globalExtendedHeader"),xn=Symbol("meta"),Pu=Symbol("emitMeta"),me=Symbol("buffer"),Jt=Symbol("queue"),hn=Symbol("ended"),dc=Symbol("emittedEnd"),zn=Symbol("emit"),De=Symbol("unzip"),Ns=Symbol("consumeChunk"),Ms=Symbol("consumeChunkSub"),lc=Symbol("consumeBody"),Ou=Symbol("consumeMeta"),Lu=Symbol("consumeHeader"),gi=Symbol("consuming"),uc=Symbol("bufferConcat"),Bs=Symbol("maybeEnd"),_r=Symbol("writing"),pn=Symbol("aborted"),Fs=Symbol("onDone"),Un=Symbol("sawValidEntry"),zs=Symbol("sawNullBlock"),Us=Symbol("sawEOF"),Nu=Symbol("closeStream"),o_=()=>!0,Oi=class extends Sw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Jt]=[];[me];[Vt];[Fn];[ft]="begin";[xn]="";[Dt];[mi];[hn]=!1;[De];[pn]=!1;[Un];[zs]=!1;[Us]=!1;[_r]=!1;[gi]=!1;[dc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Fs,()=>{(this[ft]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Fs,t.ondone):this.on(Fs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||i_,this.filter=typeof t.filter=="function"?t.filter:o_;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[Nu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){ao(this,t,e,r)}[Lu](t,e){this[Un]===void 0&&(this[Un]=!1);let r;try{r=new Wn(t,e,this[Dt],this[mi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[zs]?(this[Us]=!0,this[ft]==="begin"&&(this[ft]="header"),this[zn]("eof")):(this[zs]=!0,this[zn]("nullBlock"));else if(this[zs]=!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[Fn]=new r_(r,this[Dt],this[mi]);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[ft]="ignore",o.resume()):o.size>0&&(this[xn]="",o.on("data",c=>this[xn]+=c),this[ft]="meta"):(this[Dt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[ft]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ft]="body":(this[ft]="header",o.end()),this[Vt]?this[Jt].push(o):(this[Jt].push(o),this[cc]())))}}}[Nu](){queueMicrotask(()=>this.emit("close"))}[Du](t){let e=!0;if(!t)this[Vt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Vt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[cc]()),e=!1);return e}[cc](){do;while(this[Du](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"))}}[lc](t,e){let r=this[Fn];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[ft]="header",this[Fn]=void 0,r.end()),o.length}[Ou](t,e){let r=this[Fn],i=this[lc](t,e);return!this[Fn]&&r&&this[Pu](r),i}[zn](t,e,r){this[Jt].length===0&&!this[Vt]?this.emit(t,e,r):this[Jt].push([t,e,r])}[Pu](t){switch(this[zn]("meta",this[xn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Dt]=eo.parse(this[xn],this[Dt],!1);break;case"GlobalExtendedHeader":this[mi]=eo.parse(this[xn],this[mi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Dt]??Object.create(null);this[Dt]=e,e.path=this[xn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Dt]||Object.create(null);this[Dt]=e,e.linkpath=this[xn].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,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[pn])return r?.(),!1;if((this[De]===void 0||this.brotli===void 0&&this[De]===!1)&&t){if(this[me]&&(t=Buffer.concat([this[me],t]),this[me]=void 0),t.length<s_)return this[me]=t,r?.(),!0;for(let d=0;this[De]===void 0&&d<vc.length;d++)t[d]!==vc[d]&&(this[De]=!1);let o=!1;if(this[De]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Sc.length;d++)if(t[d]!==Sc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[De]===!1&&c)if(t.length<512)if(this[hn])this.brotli=!0;else return this[me]=t,r?.(),!0;else try{new Wn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[De]===void 0||this[De]===!1&&(this.brotli||o)){let d=this[hn];this[hn]=!1,this[De]=this[De]===void 0?new Rw({}):o?new Lw({}):new Pw({}),this[De].on("data",f=>this[Ns](f)),this[De].on("error",f=>this.abort(f)),this[De].on("end",()=>{this[hn]=!0,this[Ns]()}),this[_r]=!0;let u=!!this[De][d?"end":"write"](t);return this[_r]=!1,r?.(),u}}this[_r]=!0,this[De]?this[De].write(t):this[Ns](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")),r?.(),i}[uc](t){t&&!this[pn]&&(this[me]=this[me]?Buffer.concat([this[me],t]):t)}[Bs](){if(this[hn]&&!this[dc]&&!this[pn]&&!this[gi]){this[dc]=!0;let t=this[Fn];if(t&&t.blockRemain){let e=this[me]?this[me].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[me]&&t.write(this[me]),t.end()}this[zn](Fs)}}[Ns](t){if(this[gi]&&t)this[uc](t);else if(!t&&!this[me])this[Bs]();else if(t){if(this[gi]=!0,this[me]){this[uc](t);let e=this[me];this[me]=void 0,this[Ms](e)}else this[Ms](t);for(;this[me]&&this[me]?.length>=512&&!this[pn]&&!this[Us];){let e=this[me];this[me]=void 0,this[Ms](e)}this[gi]=!1}(!this[me]||this[hn])&&this[Bs]()}[Ms](t){let e=0,r=t.length;for(;e+512<=r&&!this[pn]&&!this[Us];)switch(this[ft]){case"begin":case"header":this[Lu](t,e),e+=512;break;case"ignore":case"body":e+=this[lc](t,e);break;case"meta":e+=this[Ou](t,e);break;default:throw new Error("invalid state: "+this[ft])}e<r&&(this[me]=this[me]?Buffer.concat([t.subarray(e),this[me]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[pn]||(this[De]?(t&&this[De].write(t),this[De].end()):(this[hn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Bs]())),this}},Ai=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)},a_=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},gf=(t,e)=>{let r=new Map(e.map(c=>[Ai(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||mw(c).root||".",f;if(c===u)f=!1;else{let h=r.get(c);f=h!==void 0?h:o(pw(c),u)}return r.set(c,f),f};t.filter=i?(c,d)=>i(c,d)&&o(Ai(c)):c=>o(Ai(c))},c_=t=>{let e=new Oi(t),r=t.file,i;try{i=Ir.openSync(r,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Ir.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 f=Ir.readSync(i,u,0,c,d);if(f===0)break;d+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},d_=(t,e)=>{let r=new Oi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Ir.stat(o,(u,f)=>{if(u)d(u);else{let h=new Hc(o,{readSize:i,size:f.size});h.on("error",d),h.pipe(r)}})})},Cr=Li(c_,d_,t=>new Oi(t),t=>new Oi(t),(t,e)=>{e?.length&&gf(t,e),t.noResume||a_(t)}),wf=(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:u_,parse:Bu}=l_,Kc=t=>{let e="",r=Bu(t);for(;u_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Bu(t)}return[e,t]},co=["|","<",">","?",":"],$c=co.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),f_=new Map(co.map((t,e)=>[t,$c[e]])),x_=new Map($c.map((t,e)=>[t,co[e]])),Fu=t=>co.reduce((e,r)=>e.split(r).join(f_.get(r)),t),h_=t=>$c.reduce((e,r)=>e.split(r).join(x_.get(r)),t),_f=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ai(e)+"/"+t):Q(t),p_=16*1024*1024,zu=Symbol("process"),Uu=Symbol("file"),Gu=Symbol("directory"),Ic=Symbol("symlink"),Hu=Symbol("hardlink"),wi=Symbol("header"),Ks=Symbol("read"),Ac=Symbol("lstat"),$s=Symbol("onlstat"),kc=Symbol("onread"),Tc=Symbol("onreadlink"),Cc=Symbol("openfile"),Rc=Symbol("onopenfile"),yn=Symbol("close"),no=Symbol("mode"),Dc=Symbol("awaitDrain"),fc=Symbol("ondrain"),Ot=Symbol("prefix"),yf=class extends Kn{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=qc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||p_,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]=Kc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=h_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Mu.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[$s](o):this[Ac]()}warn(t,e,r={}){return ao(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Ac](){Pt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[$s](e)})}[$s](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=w_(t),this.emit("stat",t),this[zu]()}[zu](){switch(this.type){case"File":return this[Uu]();case"Directory":return this[Gu]();case"SymbolicLink":return this[Ic]();default:return this.end()}}[no](t){return wf(t,this.type==="Directory",this.portable)}[Ot](t){return _f(t,this.prefix)}[wi](){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 Wn({path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,mode:this[no](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new eo({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Gu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[wi](),this.end()}[Ic](){Pt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Tc](e)})}[Tc](t){this.linkpath=Q(t),this[wi](),this.end()}[Hu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Mu.relative(this.cwd,t)),this.stat.size=0,this[wi](),this.end()}[Uu](){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[Hu](e);this.linkCache.set(t,this.absolute)}if(this[wi](),this.stat.size===0)return this.end();this[Cc]()}[Cc](){Pt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Rc](e)})}[Rc](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[Ks]()}[Ks](){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");Pt.read(t,e,r,i,o,(c,d)=>{if(c)return this[yn](()=>this.emit("error",c));this[kc](d)})}[yn](t=()=>{}){this.fd!==void 0&&Pt.close(this.fd,t)}[kc](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[yn](()=>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[yn](()=>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[fc]():this[Dc](()=>this[fc]())}[Dc](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)}[fc](){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[Ks]()}},m_=class extends yf{sync=!0;[Ac](){this[$s](Pt.lstatSync(this.absolute))}[Ic](){this[Tc](Pt.readlinkSync(this.absolute))}[Cc](){this[Rc](Pt.openSync(this.absolute,"r"))}[Ks](){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=Pt.readSync(e,r,i,o,c);this[kc](d),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[Dc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Pt.closeSync(this.fd),t()}},g_=class extends Kn{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 ao(this,t,e,r)}constructor(t,e={}){let r=qc(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[no](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]=Kc(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 Wn({path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new eo({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Ot](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ot](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Ot](t){return _f(t,this.prefix)}[no](t){return wf(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}},w_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",__=class Ar{tail;head;length=0;static create(e=[]){return new Ar(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++)b_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)E_(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 Ar;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 Ar;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 Ar;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 Ar;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=y_(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 y_(t,e,r){let i=e,o=e?e.next:t.head,c=new Vc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function b_(t,e){t.tail=new Vc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function E_(t,e){t.head=new Vc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Vc=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}},ju=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Wu=Buffer.alloc(1024),Vs=Symbol("onStat"),_i=Symbol("ended"),Et=Symbol("queue"),yi=Symbol("pendingLinks"),mn=Symbol("current"),Gn=Symbol("process"),bi=Symbol("processing"),Gs=Symbol("processJob"),vt=Symbol("jobs"),xc=Symbol("jobDone"),Js=Symbol("addFSEntry"),Ku=Symbol("addTarEntry"),Pc=Symbol("stat"),Oc=Symbol("readdir"),Zs=Symbol("onreaddir"),Ys=Symbol("pipe"),$u=Symbol("entry"),hc=Symbol("entryOpt"),Xs=Symbol("writeEntryClass"),bf=Symbol("write"),pc=Symbol("ondrain"),lo=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Xs];onWriteEntry;[Et];[yi]=new Map;[vt]=0;[bi]=!1;[_i]=!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[Xs]=yf,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 Cw(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 Ow(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[pc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[pc]);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[Et]=new __,this[vt]=0,this.jobs=Number(t.jobs)||4,this[bi]=!1,this[_i]=!1}[bf](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[_i]=!0,this[Gn](),r&&r(),this}write(t){if(this[_i])throw new Error("write after end");return typeof t=="string"?this[Js](t):this[Ku](t),this.flowing}[Ku](t){let e=Q(qu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new ju(t.path,e);r.entry=new g_(t,this[hc](r)),r.entry.on("end",()=>this[xc](r)),this[vt]+=1,this[Et].push(r)}this[Gn]()}[Js](t){let e=Q(qu.resolve(this.cwd,t));this[Et].push(new ju(t,e)),this[Gn]()}[Pc](t){t.pending=!0,this[vt]+=1;let e=this.follow?"stat":"lstat";to[e](t.absolute,(r,i)=>{t.pending=!1,this[vt]-=1,r?this.emit("error",r):this[Vs](t,i)})}[Vs](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[Gs](t);else{let r=`${e.dev}:${e.ino}`,i=this[yi].get(r);i?i.push(t):this[yi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[Gn]()}[Oc](t){t.pending=!0,this[vt]+=1,to.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[vt]-=1,e)return this.emit("error",e);this[Zs](t,r)})}[Zs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Gn]()}[Gn](){if(!this[bi]){this[bi]=!0;for(let t=this[Et].head;t&&this[vt]<this.jobs;t=t.next)if(this[Gs](t.value),t.value.ignore){let e=t.next;this[Et].removeNode(t),t.next=e}this[bi]=!1,this[_i]&&this[Et].length===0&&this[vt]===0&&(this.zip?this.zip.end(Wu):(super.write(Wu),super.end()))}}get[mn](){return this[Et]&&this[Et].head&&this[Et].head.value}[xc](t){this[Et].shift(),this[vt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[yi].get(r);if(i){this[yi].delete(r);for(let o of i)o.pending=!1,this[Gs](o)}}this[Gn]()}[Gs](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[Ys](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Vs](t,e):this[Pc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Zs](t,e):this[Oc](t),!t.readdir)return}if(t.entry=this[$u](t),!t.entry){t.ignore=!0;return}t===this[mn]&&!t.piped&&this[Ys](t)}}}[hc](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}}[$u](t){this[vt]+=1;try{return new this[Xs](t.path,this[hc](t)).on("end",()=>this[xc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[pc](){this[mn]&&this[mn].entry&&this[mn].entry.resume()}[Ys](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Js](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={}){ao(this,t,e,r)}},Jc=class extends lo{sync=!0;constructor(t){super(t),this[Xs]=m_}pause(){}resume(){}[Pc](t){let e=this.follow?"statSync":"lstatSync";this[Vs](t,to[e](t.absolute))}[Oc](t){this[Zs](t,to.readdirSync(t.absolute))}[Ys](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Js](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[bf](i)})}},v_=(t,e)=>{let r=new Jc(t),i=new cf(t.file,{mode:t.mode||438});r.pipe(i),Ef(r,e)},S_=(t,e)=>{let r=new lo(t),i=new so(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 vf(r,e).catch(c=>r.emit("error",c)),o},Ef=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:df.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},vf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:df.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},I_=(t,e)=>{let r=new Jc(t);return Ef(r,e),r},A_=(t,e)=>{let r=new lo(t);return vf(r,e).catch(i=>r.emit("error",i)),r},aA=Li(v_,S_,I_,A_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),T_=process.env.__FAKE_PLATFORM__||process.platform,kf=T_==="win32",{O_CREAT:Tf,O_NOFOLLOW:Vu,O_TRUNC:Cf,O_WRONLY:Rf}=Af.constants,Df=Number(process.env.__FAKE_FS_O_FILENAME__)||Af.constants.UV_FS_O_FILEMAP||0,C_=kf&&!!Df,R_=512*1024,D_=Df|Cf|Tf|Rf,Ju=!kf&&typeof Vu=="number"?Vu|Cf|Tf|Rf:null,Pf=Ju!==null?()=>Ju:C_?t=>t<R_?D_:"w":()=>"w",Lc=(t,e,r)=>{try{return uo.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},ro=(t,e,r,i)=>{uo.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},P_=(t,e,r,i,o)=>{if(e.isDirectory())Of(ki.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=ki.resolve(t,e.name);ro(d,r,i,o)});else{let c=ki.resolve(t,e.name);ro(c,r,i,o)}},Of=(t,e,r,i)=>{uo.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 ro(t,e,r,i);let d=c.length,u=null,f=h=>{if(!u){if(h)return i(u=h);if(--d===0)return ro(t,e,r,i)}};for(let h of c)P_(t,h,e,r,f)})},O_=(t,e,r,i)=>{e.isDirectory()&&Lf(ki.resolve(t,e.name),r,i),Lc(ki.resolve(t,e.name),r,i)},Lf=(t,e,r)=>{let i;try{i=uo.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Lc(t,e,r);throw c}for(let o of i)O_(t,o,e,r);return Lc(t,e,r)},Nf=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"}},fo=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"}},N_=(t,e)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Nf(t,r?.code||"ENOTDIR")),e(r)})},M_=(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,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),h=e.preserve,g=e.unlink,_=Q(e.cwd),v=(E,I)=>{E?r(E):I&&f?Of(I,d,u,A=>v(A)):c?ct.chmod(t,o,r):r()};if(t===_)return N_(t,v);if(h)return L_.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let y=Q(io.relative(_,t)).split("/");Nc(_,y,o,g,_,void 0,v)},Nc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),f=Q(io.resolve(t+"/"+u));ct.mkdir(f,r,Mf(f,e,r,i,o,c,d))},Mf=(t,e,r,i,o,c,d)=>u=>{u?ct.lstat(t,(f,h)=>{if(f)f.path=f.path&&Q(f.path),d(f);else if(h.isDirectory())Nc(t,e,r,i,o,c,d);else if(i)ct.unlink(t,g=>{if(g)return d(g);ct.mkdir(t,r,Mf(t,e,r,i,o,c,d))});else{if(h.isSymbolicLink())return d(new fo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Nc(t,e,r,i,o,c,d))},B_=t=>{let e=!1,r;try{e=ct.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Nf(t,r??"ENOTDIR")}},F_=(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),f=e.preserve,h=e.unlink,g=Q(e.cwd),_=E=>{E&&u&&Lf(E,c,d),o&&ct.chmodSync(t,i)};if(t===g)return B_(g),_();if(f)return _(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=Q(io.relative(g,t)).split("/"),y;for(let E=v.shift(),I=g;E&&(I+="/"+E);E=v.shift()){I=Q(io.resolve(I));try{ct.mkdirSync(I,i),y=y||I}catch{let A=ct.lstatSync(I);if(A.isDirectory())continue;if(h){ct.unlinkSync(I),ct.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new fo(I,I+"/"+v.join("/"))}}return _(y)},mc=Object.create(null),Zu=1e4,yr=new Set,z_=t=>{yr.has(t)?yr.delete(t):mc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=mc[t],r=yr.size-Zu;if(r>Zu/10){for(let i of yr)if(yr.delete(i),delete mc[i],--r<=0)break}return e},U_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,G_=U_==="win32",H_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Bf(i,r)),e.push(r||"/"),e},[]),q_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=G_?["win32 parallelization disabled"]:t.map(i=>Ai(Bf(z_(i))));let r=new Set(t.map(i=>H_(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 f of u)o.add(f)}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 f=d[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},j_=()=>process.umask(),Yu=Symbol("onEntry"),Mc=Symbol("checkFs"),Xu=Symbol("checkFs2"),Bc=Symbol("isReusable"),xt=Symbol("makeFs"),Fc=Symbol("file"),zc=Symbol("directory"),Qs=Symbol("link"),Qu=Symbol("symlink"),ef=Symbol("hardlink"),Si=Symbol("ensureNoSymlink"),tf=Symbol("unsupported"),nf=Symbol("checkPath"),gc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),je=Symbol("onError"),Hs=Symbol("pending"),rf=Symbol("pend"),br=Symbol("unpend"),wc=Symbol("ended"),_c=Symbol("maybeClose"),Uc=Symbol("skip"),Ti=Symbol("doChown"),Ci=Symbol("uid"),Ri=Symbol("gid"),Di=Symbol("checkedCwd"),W_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Pi=W_==="win32",K_=1024,$_=(t,e)=>{if(!Pi)return ie.unlink(t,e);let r=t+".DELETE."+If(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},V_=t=>{if(!Pi)return ie.unlinkSync(t);let e=t+".DELETE."+If(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},sf=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Zc=class extends Oi{[wc]=!1;[Di]=!1;[Hs]=0;reservations=new q_;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[wc]=!0,this[_c]()},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:K_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Pi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Be.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[Yu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[_c](){this[wc]&&this[Hs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[gc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Kc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Pi&&/^[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=Be.posix.dirname(t.path),f=Be.posix.normalize(Be.posix.join(u,d.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[nf](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[gc](t,"path")||!this[gc](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?Q(Be.resolve(t.path)):Q(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: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}=Be.win32.parse(String(t.absolute));t.absolute=i+Fu(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+Fu(t.path.slice(o.length))}return!0}[Yu](t){if(!this[nf](t))return t.resume();switch(k_.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[Mc](t);default:return this[tf](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[bn](t,e,r){M_(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)}[Ti](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 sf(this.uid,t.uid,this.processUid)}[Ri](t){return sf(this.gid,t.gid,this.processGid)}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new so(String(t.absolute),{flags:Pf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[je](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[je](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,f=>{f?this[je](f,t):this[br](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let h=t.atime||new Date,g=t.mtime;ie.futimes(f,h,g,_=>_?ie.utimes(u,h,g,v=>c(v&&_)):c())}if(typeof f=="number"&&this[Ti](t)){o++;let h=this[Ci](t),g=this[Ri](t);typeof h=="number"&&typeof g=="number"&&ie.fchown(f,h,g,_=>_?ie.chown(u,h,g,v=>c(v&&_)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[je](u,t),e()}),t.pipe(d)),d.pipe(i)}[zc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),r,i=>{if(i){this[je](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ti](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ci](t)),Number(this[Ri](t)),c)),c()})}[tf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Qu](t,e){let r=Q(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Si](t,this.cwd,r,()=>this[Qs](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[ef](t,e){let r=Q(Be.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Si](t,this.cwd,i,()=>this[Qs](t,r,"link",e),o=>{this[je](o,t),e()})}[Si](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Be.resolve(e,c);ie.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new fo(d,Be.resolve(d,r.join("/"))));this[Si](t,d,r,i,o)})}[rf](){this[Hs]++}[br](){this[Hs]--,this[_c]()}[Uc](t){this[br](),t.resume()}[Bc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Pi}[Mc](t){this[rf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Xu](t,r))}[Xu](t,e){let r=d=>{e(d)},i=()=>{this[bn](this.cwd,this.dmode,d=>{if(d){this[je](d,t),r();return}this[Di]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Be.dirname(String(t.absolute)));if(d!==this.cwd)return this[bn](d,this.dmode,u=>{if(u){this[je](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Uc](t),r();return}if(d||this[Bc](t,u))return this[xt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=g=>this[xt](g??null,t,r);return f?ie.chmod(String(t.absolute),Number(t.mode),h):h()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),f=>this[xt](f??null,t,r))}if(t.absolute===this.cwd)return this[xt](null,t,r);$_(String(t.absolute),f=>this[xt](f??null,t,r))})};this[Di]?o():i()}[xt](t,e,r){if(t){this[je](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Fc](e,r);case"Link":return this[ef](e,r);case"SymbolicLink":return this[Qu](e,r);case"Directory":case"GNUDumpDir":return this[zc](e,r)}}[Qs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[je](o,t):(this[br](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Ff=class extends Zc{sync=!0;[xt](t,e){return super[xt](t,e,()=>{})}[Mc](t){if(!this[Di]){let o=this[bn](this.cwd,this.dmode);if(o)return this[je](o,t);this[Di]=!0}if(t.absolute!==this.cwd){let o=Q(Be.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[je](c,t)}}let[e,r]=Ei(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Uc](t);if(e||this[Bc](t,r))return this[xt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?Ei(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[xt](d,t)}let[o]=Ei(()=>ie.rmdirSync(String(t.absolute)));this[xt](o,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>V_(String(t.absolute)));this[xt](i,t)}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ie.closeSync(o)}catch(f){u=f}(d||u)&&this[je](d||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Pf(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[je](d,t)),t.pipe(c)),c.on("data",d=>{try{ie.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,f=t.mtime;try{ie.futimesSync(o,u,f)}catch(h){try{ie.utimesSync(String(t.absolute),u,f)}catch{d=h}}}if(this[Ti](t)){let u=this[Ci](t),f=this[Ri](t);try{ie.fchownSync(o,Number(u),Number(f))}catch(h){try{ie.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||h}}}i(d)})}[zc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),r);if(i){this[je](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ti](t))try{ie.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Ri](t)))}catch{}e(),t.resume()}[bn](t,e){try{return F_(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}}[Si](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Be.resolve(c,d);let[u,f]=Ei(()=>ie.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new fo(c,Be.resolve(e,r.join("/"))))}i()}[Qs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[je](c,t)}}},J_=t=>{let e=new Ff(t),r=t.file,i=Sf.statSync(r),o=t.maxReadSize||16*1024*1024;new hw(r,{readSize:o,size:i.size}).pipe(e)},Z_=(t,e)=>{let r=new Zc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),Sf.stat(o,(u,f)=>{if(u)d(u);else{let h=new Hc(o,{readSize:i,size:f.size});h.on("error",d),h.pipe(r)}})})},zf=Li(J_,Z_,t=>new Ff(t),t=>new Zc(t),(t,e)=>{e?.length&&gf(t,e)}),Y_=(t,e)=>{let r=new Jc(t),i=!0,o,c;try{try{o=at.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=at.openSync(t.file,"w+");else throw f}let d=at.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let g=0,_=0;g<512;g+=_){if(_=at.readSync(o,u,g,u.length-g,c+g),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!_)break e}let f=new Wn(u);if(!f.cksumValid)break;let h=512*Math.ceil((f.size||0)/512);if(c+h+512>d.size)break;c+=h,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,X_(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},X_=(t,e,r,i,o)=>{let c=new cf(t.file,{fd:i,start:r});e.pipe(c),ey(e,o)},Q_=(t,e)=>{e=Array.from(e);let r=new lo(t),i=(o,c,d)=>{let u=(v,y)=>{v?at.close(o,E=>d(v)):d(null,y)},f=0;if(c===0)return u(null,0);let h=0,g=Buffer.alloc(512),_=(v,y)=>{if(v||y===void 0)return u(v);if(h+=y,h<512&&y)return at.read(o,g,h,g.length-h,f+h,_);if(f===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(h<512)return u(null,f);let E=new Wn(g);if(!E.cksumValid)return u(null,f);let I=512*Math.ceil((E.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),h=0,at.read(o,g,0,512,f,_)};at.read(o,g,0,512,f,_)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(f,h)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(f||!h)return c(f);at.fstat(h,(g,_)=>{if(g)return at.close(h,()=>c(g));i(h,_.size,(v,y)=>{if(v)return c(v);let E=new so(t.file,{fd:h,start:y});r.pipe(E),E.on("error",c),E.on("close",o),ty(r,e)})})};at.open(t.file,d,u)})},ey=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:Uf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},ty=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:Uf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},vi=Li(Y_,Q_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Ew(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")}),EA=Li(vi.syncFile,vi.asyncFile,vi.syncNoFile,vi.asyncNoFile,(t,e=[])=>{vi.validate?.(t,e),ny(t)}),ny=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))};Wt();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 xo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Gf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ho(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Hf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function qf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function $n(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Xt();$e();te();Re();$e();function Rr(t,e){if(xo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ni(t){return t.startsWith("http://")||t.startsWith("https://")}function Dr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as xk}from"node:fs";import{dirname as pk,join as mk}from"node:path";import{fileURLToPath as wk}from"node:url";var Nt="0.2.7-alpha.101";import{mkdir as _y,rm as c0}from"node:fs/promises";import{join as Ui}from"node:path";jt();import{readFileSync as ly}from"node:fs";var uy=384;async function Yc(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await fr(t.agentEnvFile,r,{mode:uy})}function Mi(t){try{let e=JSON.parse(ly(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function $f(t,e,r={},i=o=>o){return{...i({...t,...Mi(e)}),...r}}jt();function Bi(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(fy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
101
92
  `)}
102
- `}function ob(t){if(t.includes(`
103
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var ab={path:"",version:"cloud-deployed"},ih="openclaw_gateway_unavailable",cb="openclaw_default_agent_missing";function sh(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 db={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},lb=6e4,Ro=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??ib,this.createTimeoutMs=e.createTimeoutMs??lb,this.detectorFactory=e.detectorFactory??(()=>new Jn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new To({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??wd(nb(),".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=>{le.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=wd(e,".env");if(await tb(n).then(c=>c.isFile()).catch(()=>!1)){le.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=sb({...process.env,...Hi(this.paths.agentEnvFile)});await dn(n,o,{mode:384}),le.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),le.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 Ce(e.agentId,this.paths).catch(()=>null),o=uo(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")le.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>le.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")le.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>le.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){le.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await Ce(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Be(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){le.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await Ce(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Be(T,this.paths))}return le.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 k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=je(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 g=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??g??u.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&_d(e.framework)&&await ur(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await md(u.root,{recursive:!0}),await md(S,{recursive:!0}),await md(u.logs,{recursive:!0}),T(),x||await fr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Fa(S,"cloud"):await Fa(S,"local",yd)),T();let P=i,E=r0({model:e.model??P?.model}),R=jf(e._meta)??P?.accountId,O=e.patToken??P?.patToken,B=h==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Io({agentId:e.agentId,framework:e.framework,workspace:S,model:E.model??Ot,deployType:h,...R?{accountId:R}:{},...O?{patToken:O}:{},...B?{modelInfo:B}:{}}),I.status="ok",P?.sessions){let j=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,se]of Object.entries(P.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};j?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",le.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:oe.permissionMode})):Nt(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:le.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&le.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:h}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(X,oe)}let re=Object.keys(P.sessions).length;re>0&&le.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),A=!0;let N={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:E.model};h==="cloud"&&(N.deployType="cloud"),R&&(N.accountId=R),O&&(N.patToken=O),B&&(N.modelInfo=B),P?.skills&&(N.skills=P.skills),P?.agentName&&(N.agentName=P.agentName),P?.description&&(N.description=P.description),N.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Dt,e.framework==="openclaw"&&h==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):le.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let $=e.initialSkills??[];if($.length>0){let j=[...N.skills??[]],re=new Map(j.map((oe,C)=>[oe.skillId,C])),X=await Promise.allSettled($.map(oe=>mo({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe}))),se=0;for(let[oe,C]of X.entries()){let U=$[oe];U&&(C.status==="fulfilled"?(wo(j,re,C.value),se++):le.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(C.reason)}))}se>0&&(N.skills=j,le.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:$.length}))}return await Be(N,this.paths),le.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(T){throw le.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await eb(u.root,{recursive:!0,force:!0}).catch(P=>le.warn("rm agent dir failed (ignored)",{err:String(P)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&_d(e.framework))u=ab;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);_d(e.framework)&&!ms(e.framework)&&(le.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await ur(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{let m=e.sessions.get(i),g=Zt(e)?m?.permissionMode??oh:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,c,this.buildBinShimPathEnv(),g,e.framework==="codex"&&e.deployType==="cloud"?wd(je(e.agentId,this.paths).root,"codex-home"):void 0)}try{return await x.start(),await x.initialize(db),x}catch(m){let g=x instanceof Lt?x.getStderrTail():[];throw g.length>0&&le.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof k?m.code:"unknown",recentStderr:g}),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",sh(o),{cause:{reason:ih}})}catch(o){le.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};le.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 le.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:cb}})}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",sh(n),{cause:{reason:ih}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,h=pd(o);if(n.deployType==="local"){let g=await this.ensureOpenclawDefaultAgent();return new zr({command:u,cwd:g.workspace,agentId:g.id,sessionName:h})}let x=await rh();try{await this.getOpenclawConfig().ensureAcpDeviceScopes()}catch(g){le.warn("acp device scope ensure failed (ignored)",{err:String(g)})}let m;if(i?.modelToken){let g=Xc(o),S=Qc(i),_=`${g}/${S}`;if(!this.ensuredProviders.has(_)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(g),A=d0(i,c,d,I);A&&(await v.ensureProvider(g,A),await v.addModelToAllowlist(_),this.ensuredProviders.add(_))}m=_}return new zr({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 d=Xc(c),u=`${d}/${o}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,le.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,le.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as fh}from"node:crypto";import{promises as mb}from"node:fs";import{basename as hh}from"node:path";qe();ne();import{promises as ub}from"node:fs";import{basename as fb}from"node:path";var ch=G("file-upload"),hb="/api/coze_claw/file/agent_upload",xb=6e4;async function dh(t,e={}){let i=`${Cr(Pr(e.handshakeBase))}${hb}`,o=e.timeoutMs??xb,c=await ub.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",...In(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);ch.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),g=m.headers.get("x-tt-logid")??"";if(!m.ok){let v=await m.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${g}: ${v.slice(0,200)}`)}let S=await m.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${g}`);let _=S.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${g}: ${JSON.stringify(S).slice(0,200)}`);return ch.info("file upload ok",{uri:_,logid:g}),{uri:_}}catch(m){throw m instanceof k?m:m.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${fb(t.path)}`):new k("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}qe();ne();import{extname as pb}from"node:path";var gb={".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 lh(t){let e=pb(t).toLowerCase();return gb[e]??"application/octet-stream"}Re();var Co=G("agent-send"),uh=50*1024*1024;function xh(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 ph(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&&(Co.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 gh(t,e){let{session:n,runtime:i}=xh(e.core,t.agentId,t.sessionId);if(!await ii(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await mb.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>uh)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${uh}`);let c=await lh(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 d=t.name??hh(t.path),u;try{u=await dh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Co.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:fh(),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 ph(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Co.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 mh(t,e){let{session:n,runtime:i}=xh(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??hh(t.path),c={sessionUpdate:"group_file",messageId:fh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ph(e,n,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Co.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 wh(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 d=n[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}an();Jt();ne();var Mt=G("coze-cli-installer"),_h="@coze/cli@latest",wb="coze",yh="0.1.8",_b=5e3,yb=5e3,Eb=9e4,Eh=1e4,Ki=null,Po=!1;async function bd(t,e={}){if(Po)return;if(Ki)return Ki;let n=e.exec??Zf;return Ki=(async()=>{try{let i=await bb(wb,n),o=!1;if(i){let d=await vb(n);if(d===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(wh(d,yh))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:yh}),o=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Po=!0;return}}let c=o?"upgrade-only":"full";Mt.info("coze-cli install start",{package:_h,mode:c});try{await n("npm",["i","-g","--prefer-online",_h],{timeout:Eb,maxBuffer:10*1024*1024}),Mt.info("coze-cli install ok")}catch(d){Mt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Po=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Eh}),Mt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Mt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:Eh}),Mt.info("coze auth login ok")}catch(d){Mt.warn("coze auth login failed",{err:String(d)});return}Po=!0}finally{Ki=null}})(),Ki}async function bb(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:_b});return Ma(i)}catch{return}}async function vb(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:yb});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}un();Re();var Sb=10*6e4;function bh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Sb:e}function Do(t){return cn(t??J().configFile)}function $i(t,e){return ln(e??J().configFile,t)}import{randomBytes as qb}from"node:crypto";ar();qe();ne();import{createReadStream as Ib}from"node:fs";import{mkdir as Ab,readFile as kb,realpath as Tb,stat as Rb,writeFile as Cb}from"node:fs/promises";import{basename as Pb,dirname as vd,isAbsolute as Db,join as Ob,relative as Lb,resolve as vh,sep as Nb}from"node:path";import{createInterface as Mb}from"node:readline";var Ih=G("fs-rpc"),Vi=$e("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Ah(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>Vi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${Vi} bytes`);let i=await Th(t.path,e);return await Ab(vd(i),{recursive:!0}),await Cb(i,t.content,"utf8"),Ih.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function kh(t,e){let n=await Th(t.path,e),i=await Rb(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Vi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Vi} bytes`);let c;if(o&&i.size>Vi)c=await Bb(n,t.line??1,t.limit);else{let d=await kb(n,"utf8");if(o){let u=d.split(`
104
- `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
105
- `)}else c=d}return Ih.info("fs/read_text_file ok",{path:n,size:c.length}),{content:c}}async function Bb(t,e,n){let i=Mb({input:Ib(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof n=="number"?o+n: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(`
106
- `)}async function Th(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([Sh(vh(e)),Sh(vh(t))]),o=Lb(n,i);if(Fb(o,Nb,Db(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Fb(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Sh(t){let e=[],n=t;for(;n!==vd(n);)try{let i=await Tb(n);return e.length?Ob(i,...e.reverse()):i}catch{e.push(Pb(n)),n=vd(n)}return t}ne();var Rh=G("prompt-multimodal"),Ch=10*1024*1024,zb=15e3,Ub=6;async function Ph(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let c=n++,d=t[c];d!==void 0&&(e[c]=await Gb(d))}}let o=Array.from({length:Math.min(Ub,t.length)},()=>i());return await Promise.all(o),e}function Dh(t){return t.some(e=>e.type==="image")}async function Gb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Li(e.uri))return t;try{let{buf:n,contentType:i}=await Wb(e.uri),o=e.mimeType||Hb(i)||"application/octet-stream";return Rh.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 Rh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Hb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function Wb(t){let e=new AbortController,n=setTimeout(()=>e.abort(),zb);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>Ch)throw new Error(`image too large: ${o.byteLength} bytes (max ${Ch})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}fn();qe();ne();var q=G("core"),jb=3e4,Kb=/^(boe|ppe)_[A-Za-z0-9_-]+$/,$b="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",Vb="\u5BA1\u6279\u5DF2\u8D85\u65F6",Jb=3e4,Oo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Nr;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=bh(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(),q.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){q.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),q.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){q.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)&&q.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,d)=>{q.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:c,signal:d}),ji(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){q.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(kn(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>q.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){q.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(yo(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&&Kb.test(i)?this.currentCozeEnv=i:i&&q.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,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):q.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);n!==null&&await this.upstream.send(Lr(n,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Lr(n,o));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Lr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):q.warn("drop unknown notification",{method:e.method})}catch(o){q.error("handleFrame failed",{method:e.method,err:String(o)}),n!==null&&await this.upstream.send(kn(n,Gi(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=fo(n._meta);return q.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,$b,x,m)}}let d=Date.now(),u=!1;try{let h=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,h}finally{q.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=$f(i);switch(n){case"session/new":{let c=Zb();return q.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return q.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 k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Zt(e)?Kf(i._meta):void 0;if(u!==void 0&&!Nt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${ud(e.framework)}`);let h=await this.ensureRuntime(e,d);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,d,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 S=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(_){throw h.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),_}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(h.acpSessionId,x):e.activeTriggers.delete(h.acpSessionId);let m=fo(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&&Dh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let g=await Ph(c.prompt);try{let S=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:g});return h.lastActiveAt=Date.now(),S}catch(S){if(S instanceof k&&S.code==="AGENT_APPROVAL_TIMEOUT"){let _=h.pendingPermission;_&&(_.downstream.respondAgentRequest(_.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(_.upstreamId),h.pendingPermission=void 0);let v=h.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):void 0;return q.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,h,d,Vb,I,A)}throw S}finally{if(e.activeTriggers.delete(h.acpSessionId),e.activeGroupIds.delete(h.acpSessionId),h.pendingPermission=void 0,h.reloadAfterTurn){h.reloadAfterTurn=!1;let S=h.downstream;S&&(h.downstream=void 0,q.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:h.acpSessionId}),S.stop("reload-after-turn").catch(_=>q.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(_)})))}else h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(q.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,h=fo(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Zt(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(!Nt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${ud(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(g){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),g}else q.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return q.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};q.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let 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,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 Zt(e)&&(c.permissionMode=e.framework==="claude-code"?yd:ah),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(ut.GEN_MODEL_TOKEN,i,Jb);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(ji(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,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((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=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(q.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}),q.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){q.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 q.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),Zt(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){q.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(ji(i),this.isRuntimeBusy(e,i)){q.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)){q.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}q.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=>q.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 d=e.activeTriggers.get(n.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Or("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,n,i,o,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Or("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>q.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){q.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){q.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Qb(n)){q.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Zt(e)){let m=d.currentModeId;Nt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(g=>q.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(g)}))):typeof m=="string"&&!Nt(e.framework,m)&&q.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(Or("session/update",{...n,sessionId:o,_meta:u})).catch(m=>q.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}q.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Ah(c,o);n.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await kh(c,o);n.respondAgentRequest(i.id,d)}}catch(o){q.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,Gi(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 g=u?this.reverseSessionId(e,u):void 0,S=g?e.sessions.get(g):void 0;S&&(S.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...c,...g?{sessionId:g}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:g}),q.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:g,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(zi(o,"session/request_permission",_)).catch(v=>{this.pendingUpstream.delete(o),q.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.value;this.clearPendingPermissionFor(o),e.error?(q.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"&&Yb(e.result,o),q.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 _o(e.error)):i.value.resolve(e.result);return}q.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),d=e.get(c);if(d)return q.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:c}),{value:d,key:c}}}sendRequest(e,n,i=jb){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(zi(o,e,n)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Zt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),n.set(i,c)}await si(e.agentId,n,this.paths)}catch(n){q.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(kn(e,{code:n,message:i,data:{bridgeVersion:Dt}}))}};function Zb(){return qb(16).toString("hex")}function Yb(t,e){if(!t||typeof t!="object"){q.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){q.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"){q.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")&&q.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var Xb=["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."];function Qb(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{text:o}=i;return Xb.some(c=>o.startsWith(c))}un();ne();Re();import{randomBytes as ev}from"node:crypto";import{createServer as tv}from"node:http";var nv=1e6,Oh=G("ipc"),Lo=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(n=>[`${n.method} ${n.path}`,n])),this.paths=e.paths??J()}async start(){this.token=ev(32).toString("hex");let e=tv((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(),Oh.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 dn(this.paths.portFile,String(this.port)),await dn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){Ji(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Ji(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await rv(e)}catch(u){Ji(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ji(n,200,u??{ok:!0})}catch(u){Oh.error("IPC handler failed",{key:o,err:String(u)}),Ji(n,500,{error:u instanceof Error?u.message:String(u)})}}};function Ji(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function rv(t){let e=[],n=0;for await(let o of t){let c=o;if(n+=c.length,n>nv)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 vS=Ht(Rx(),1),SS=Ht(Wo(),1),IS=Ht(Hr(),1),AS=Ht(Ld(),1),kS=Ht(Bd(),1),TS=Ht(Wd(),1),Fx=Ht($o(),1),RS=Ht(Bx(),1);var zx=Fx.default;qe();ne();var{FWS:jS}=Zx(),De=G("upstream.frontier"),Xx="application/json",Qx="none",KS=15e3;function $S(t){class e extends zx{constructor(i){super(i,Xf,{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(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 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 is=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:Qf,...In(this.opts.ppeOverride)},n=$S(e),i=t0(this.opts.urlOverride),o={url:i,ws:n,fpID:Yf,aID:ho,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Xx,force:!0},payloadEncoding:{encoding:Qx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new jS(o),d=!1,u=null,h,x,m=new Promise((_,v)=>{h=_,x=v}),g=_=>{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}),_&&g();for(let v of this.connectHandlers)Promise.resolve(v({initial:_})).catch(I=>De.warn("onConnect handler threw (ignored)",{err:String(I)}))},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}),g(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let S=this.opts.openTimeoutMs??KS;u=setTimeout(()=>{g(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await m}catch(_){try{c.close(1e3,"open failed")}catch(v){De.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){De.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw De.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(De.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState: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;ep(c)||De.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:Xx,payloadEncoding:Qx})}catch(u){throw De.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let 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){De.debug("drop non-adapter frontier frame",{service:n});return}let i=ZS(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;ep(c)||De.info("frontier frame in",{logid:JS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:VS(i)}),Promise.resolve(this.handler(o)).catch(d=>De.warn("frontier frame handler threw",{err:String(d)}))}};function ep(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var tp=2e3;function VS(t){return t.length<=tp?t:`${t.slice(0,tp)}...<truncated, total ${t.length} chars>`}function JS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function ZS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}qe();ne();var $d=G("skill-publish"),YS="/api/marketplace/product/skill/publish_with_assets",XS=15e4;async function np(t,e={}){let i=`${Cr(Pr(e.handshakeBase))}${YS}`,o=e.timeoutMs??XS,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",...In(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);$d.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 k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${_.slice(0,200)}`)}let g=await x.json();if($d.info("skill publish response",{logid:m,httpStatus:x.status,code:g.code,msg:g.msg,dataSkillId:g.data?.skill_id??"",dataVersion:g.data?.version??""}),g.code!==void 0&&g.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${g.code} msg=${g.msg??"-"} logid=${m}`);let S={};return g.data?.skill_id!==void 0&&g.data.skill_id!==""&&(S.skillId=String(g.data.skill_id)),g.data?.version&&(S.version=g.data.version),$d.info("skill publish ok",{logid:m,skillId:S.skillId??"",version:S.version??""}),S}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 Vd=G("upstream.switchable"),na=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Vd.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 Vd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>Vd.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 Jd=G("upstream"),Vr=class{handler=null;async start(){Jd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Jd.info("NoopUpstream stopped",{reason:e})}async send(e){Jd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};qe();ne();un();ne();Re();import{promises as QS}from"node:fs";var rp=G("pat-token-store");async function ra(t=J()){try{let n=(await QS.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(rp.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"&&rp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ss(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await dn(e.patTokenFile,t,{mode:384})}Re();Re();import{promises as ia}from"node:fs";import{join as e1}from"node:path";function t1(t,e){return`#!/bin/sh
93
+ `}function fy(t){if(t.includes(`
94
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();Re();import{homedir as py}from"node:os";import{join as my}from"node:path";$e();te();var po="1008033",Vf="1289";var Jf="pbbp2",Zf="https://www.coze.cn",Yf="/api/coze_claw/resource/get_frontier_key",xy="https://www.coze.cn",hy="wss://frontier.coze.cn";function Pr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??xy}function Xf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??hy}function Sn(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 zi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Fi=G("handshake");async function Xc(t){let e=Pr(t.endpoint),r=t.timeoutMs??1e4,i=`${Dr(e)}${Yf}?aid=${encodeURIComponent(po)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Fi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),f=u.headers.get("x-tt-logid")??"",h=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${E.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${f}`);let _=g.data??{},v=typeof _.access_key=="string"&&_.access_key||typeof _.accessKey=="string"&&_.accessKey||void 0,y=typeof _.device_id=="string"&&_.device_id||typeof _.deviceId=="string"&&_.deviceId||void 0;if(!v||!y){let E=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${E}`)}return Fi.info("handshake ok",{remoteDeviceId:y,logid:f,traceId:h}),{accessKey:v,deviceId:y}}catch(u){if(u instanceof k)throw Fi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Fi.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Fi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var go=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",At="auto",mo=19e4,Qf=8192;function t0(t){return{model:Qc(t.model)??At,...t.modelToken?{modelToken:t.modelToken}:{}}}function n0(t){return!t||t===At}var gy=new Set(["auto","\u81EA\u52A8"]);function Qc(t){let e=t?.trim();if(e)return gy.has(e.toLowerCase())?At:e}function r0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=go,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||At;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 n0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function i0(t,e,r){let i={};if(t.modelToken?i.model=t.model||At:n0(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${go}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=wo(e,r);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??mo}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function s0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function wo(t,e){let{ttEnv:r,usePpe:i}=zi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function o0(t,e,r){if(!t.modelToken)return{};let i=wo(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
95
+ `)}}function ed(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function td(t){return t.model||At}function e0(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 a0(t,e,r,i){if(!t.modelToken)return null;let o=td(t),c=wo(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[e0(o,d,t.modelInfo?.contextWindow??mo,t.modelInfo?.maxOutput??Qf)],f=new Set([o]);for(let g of i??[])!g||f.has(g)||(f.add(g),u.push(e0(g,["text"],mo,Qf)));let h={baseUrl:`${go}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(h.headers=c),h}function wy(t){if(t!==void 0)return t?"auto":"text"}function nd(t,e,r){let i=wo(e,r),o=t.modelInfo?.contextWindow??mo,d=["model:"," provider: custom",` default: ${t.model||At}`,` base_url: ${go}/v1`,` context_length: ${o}`];if(t.modelInfo?.maxOutput&&d.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&d.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){d.push(" default_headers:");for(let[f,h]of Object.entries(i))d.push(` ${f}: ${JSON.stringify(h)}`)}d.push("compression:"),d.push(" threshold: 0.8"),d.push("approvals:"),d.push(` mode: ${JSON.stringify("off")}`),d.push(` cron_mode: ${JSON.stringify("approve")}`);let u=wy(t.modelInfo?.capabilities?.image);return u&&(d.push("agent:"),d.push(` image_input_mode: ${JSON.stringify(u)}`)),d.push("skills:"),d.push(" external_dirs:"),d.push(` - ${my(py(),".hermes","skills")}`),`${d.join(`
96
+ `)}
97
+ `}var Vn=G("hermes-config"),d0="dont_ask",l0="default";function Jn(t,e){return Ui(ze(t,e).root,"hermes-home")}async function yy(t){let e=Jn(t.agentId,t.paths);await _y(e,{recursive:!0,mode:448});let r=Bi({...process.env,...Mi(t.paths.agentEnvFile)});await ut(Ui(e,".env"),r,{mode:384});let i=nd(t.modelConfig,t.cozeEnv,t.mockScenario);await ut(Ui(e,"config.yaml"),i,{mode:384}),Vn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:r.length,yamlBytes:i.length})}async function u0(t){let e=Jn(t.agentId,t.paths),r=Ui(e,"state.db"),i=Ui(e,"config.yaml");Vn.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:r,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
+ `).slice(1,6).join(" | ")}),await c0(r,{force:!0}).catch(c=>Vn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=nd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ut(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 id(t,e){let r=Jn(t,e);Vn.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:r,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
+ `).slice(1,6).join(" | ")}),await c0(r,{recursive:!0,force:!0}).catch(i=>Vn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var rd=new Map;function f0(t){let e=rd.get(t.agentId);if(e)return e;let r=yy(t).finally(()=>rd.delete(t.agentId));return rd.set(t.agentId,r),r}var ne=G("agent-handlers"),h0=5*1024*1024,Iy=1,Ay=6,ky=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ty=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Cy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Ry=/^\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?Ry.test(e)||Cy.test(e)?e:(ne.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Py(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 yo=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let r=$n(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??ze(r,this.paths).workspace,c=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Lr(c,r,o,this.paths),f=[],h=new Set;for(let g of d){let _=le(u,g.relPath,"SKILL.md");await ud(_).then(y=>y.isFile()).catch(()=>!1)&&(f.push(By(g)),h.add(g.relPath))}if(e.scanLocal){let g=await I0(r,o,c,this.paths),_=await A0(r,c);for(let v of[...g,..._])h.has(v.relPath)||(h.add(v.relPath),f.push(v.skill))}return{skills:f}}async addSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((f,h)=>[f.skillId,h])),u=[];for(let f of o){let h=await bo({agentId:r,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});Eo(c,d,h),u.push(f)}return await ci(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],d=[],{base:u}=Lr(i.framework,r,i.workspace,this.paths);for(let f of c){if(!o.has(f.skillId)){d.push(f);continue}let h=le(u,f.relPath);ne.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:r,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:h}),await ad(h,{recursive:!0,force:!0}),ne.info("skill removed",{agentId:r,skillId:f.skillId,relPath:f.relPath})}return await ci(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=$n(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ne.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??ze(r,this.paths).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await Ly(r,o,c,e.skillName,d,this.paths);if(!u){let D=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${D}: ${e.skillName}`)}let{absDir:f,relPath:h,dirName:g}=u,_=le(f,"SKILL.md"),v=new xd.default;v.addLocalFolder(f,g);let y=v.toBuffer();if(y.length>p0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${p0}`);let E=await _o(_,{encoding:"utf8"}).then(D=>v0(D).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ne.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??E0(r,h);if(i&&!d){let D=i.skills??[],b=D.find(R=>R.relPath===h);b?(b.version=A,b.skillId=T):D.push({skillId:T,skillName:e.skillName,relPath:h,version:A,installedAt:Date.now(),...E?{description:E}:{}}),await ci(r,D)}return ne.info("skill published",{agentId:r,skillName:e.skillName,relPath:h,zipBytes:y.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[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,ne.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let f=c.downstream;c.downstream=void 0,ne.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(r).catch(h=>ne.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(h)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ne.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await ve(r);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return ne.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await xr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw ne.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Ue(i),ne.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await ve(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Ni(e.registry)&&o.push(`--registry=${e.registry}`);let c=Dy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Ty.test(d)&&o.push("--env",d);let u=await Py(o);return ne.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await ve(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ue(i),ne.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}):(ne.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST",`${ht.DELETE}: missing agentId`);ne.warn("[AUDIT] deleteAgent handler entry",{agentId:r,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 ve(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=ze(r);return c==="cloud"?(ne.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:r,path:d.root,deployType:c,reason:e.reason??""}),await ad(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ue(i)),ne.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Rr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Qc(e.model)??At,i=await ve(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ue(i),ne.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return ne.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;if(o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>ne.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)})),o.framework==="hermes"){let u=[];for(let[f,h]of o.allSessionQueues())u.push(h.enqueue(async()=>{let g=o.sessions.get(f);if(!(!g?.downstream||!g.acpSessionId))try{await g.downstream.setSessionModel?.({sessionId:g.acpSessionId,modelId:r})}catch(_){ne.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:f,acpId:g.acpSessionId,err:String(_)})}}));return await Promise.all(u),ne.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:r,cloudSessions:u.length}),{ok:!0}}let d=[];for(let[u,f]of o.allSessionQueues())d.push(f.enqueue(async()=>{let h=o.sessions.get(u);h?.downstream&&(await h.downstream.stop(`switchModel: ${r}`).catch(()=>{}),h.downstream=void 0)}));return await Promise.all(d),ne.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(Rr(e._meta,ht.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ht.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ht.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(r=>ne.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(r)})),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),ne.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,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await ai(e,o)}async clearPersistedAcpSessionIds(e){let r=await ve(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 Ue(r)}async repairAgent(e){if(Rr(e._meta,ht.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ht.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ht.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){ne.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){ne.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){ne.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Rr(e._meta,"_agent/getFileTree");let r=e._meta,i=$n(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await sd(d).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 oi(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=Jy(e.depth);return u.isDirectory()?{tree:await Vy(o,d,c,f)}:{tree:[{name:Zy(c),path:C0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Rr(e._meta,"_agent/getFileContent");let r=$n(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await sd(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 oi(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>h0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${h0})`);let d=await _o(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 ve(e).catch(()=>null))?.workspace??ze(e).workspace}safeJoin(e,r){let i=dd(e,r||"."),o=fd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${g0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return ve(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function y0(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,r,i){switch(t){case"claude-code":return{base:r,subdir:le(".claude","skills")};case"codex":case"openclaw":return{base:r,subdir:le(".agents","skills")};case"hermes":return{base:Jn(e,i??Z()),subdir:"skills"}}}function b0(t){let e=Ey();if(t==="claude-code")return[le(e,".claude","skills")];if(t==="codex")return[le(e,".agents","skills"),le(e,".codex","skills")];if(t==="openclaw")return[le(e,".agents","skills"),le(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA||le(e,"AppData","Local");return[le(r,"hermes","skills"),le(e,".hermes","skills")]}return[le(e,".hermes","skills")]}return[]}async function Oy(t,e,r,i,o,c){let d=async u=>ud(le(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=Lr(r,t,e,c),h=le(f,i),g=le(u,h);return await d(g)?{absDir:g,relPath:h}:null}for(let u of b0(r)){let f=le(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function Ly(t,e,r,i,o,c){let d=y0(i),u=await Oy(t,e,r,d,o,c);if(u)return{...u,dirName:d};let h=(o?await A0(t,r):await I0(t,e,r,c)).filter(v=>v.skill.skillName===i);if(h.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(v=>x0(v.relPath)).join(", ")} \u2014 rename or remove duplicates`);let g=h[0];return g?{absDir:o?g.relPath:le(e,g.relPath),relPath:g.relPath,dirName:x0(g.relPath)}:null}function E0(t,e){return(by("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function v0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
+ ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
102
+ `)){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 S0(t,e,r,i){let o=await m0(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 ud(le(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,h=le(r,f),g=le(e,f,"SKILL.md"),_=await _o(g,{encoding:"utf8"}).catch(()=>null);if(_===null)continue;let v=v0(_);c.push({relPath:h,skill:{skillId:E0(t,h),skillName:v.name||f,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function I0(t,e,r,i){let{base:o,subdir:c}=Lr(r,t,e,i);return S0(t,le(o,c),c,!1)}async function A0(t,e){let r=[],i=new Set;for(let o of b0(e)){let c=await S0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var Ny=3e4,My=50*1024*1024,p0=10*1024*1024,Or=3e4;async function bo(t){let{agentId:e,workspace:r,framework:i,skill:o,paths:c}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!u)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=y0(o.skillName),{base:h,subdir:g}=Lr(i,e,r,c),_=le(g,f),v=le(h,_);if(await od(v,{recursive:!0}),d){let E=Buffer.from(o.content,"utf8");Gi(E.length),await cd(le(v,"SKILL.md"),E,"utf8")}else{let E=await zy(o.downloadUrl);Gy(E)?await Wy(E,v):Hy(E)?await qy(E,v):await cd(le(v,"SKILL.md"),E.toString("utf8"),"utf8")}let y={skillId:o.skillId,skillName:o.skillName,relPath:_,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 ne.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:_,source:d?"content":"downloadUrl"}),y}function Eo(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 By(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 Fy(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 k0(t,e){let r=await ve(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Nt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Ue(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((_,v)=>[_.skillId,v])),u=c.filter(_=>_.builtin===!0&&!!_.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Ue(r,e),{status:"noop",count:0};let f=0,h=0,{base:g}=Lr(r.framework,t,r.workspace,e);ne.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:r.framework,prev:o,current:i,skillBase:g,builtinCount:u.length,builtinRelPaths:u.map(_=>_.relPath)});for(let _ of u)try{let v=le(g,_.relPath);ne.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:_.skillId,relPath:_.relPath,rmTarget:v}),await ad(v,{recursive:!0,force:!0});let y=await bo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Fy(_),...e?{paths:e}:{}});Eo(c,d,y),f+=1}catch(v){h+=1,ne.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:_.skillId,skillName:_.skillName,err:String(v)})}return r.skills=c,h===0&&(r.skillsRefreshedForVersion=i),await Ue(r,e),ne.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:h}),{status:"refreshed",count:f}}async function zy(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Gi(e);let r=Uy(t);return Gi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await _o(e);return Gi(r.length),r}if(Ni(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Ny);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 Gi(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Gi(t){if(t>My)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Uy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function Gy(t){return t.length>=2&&t[0]===31&&t[1]===139}function Hy(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 ld(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function qy(t,e){let r,i;try{r=new xd.default(t),i=r.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||ld(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(h=>h===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=jy(i),c=dd(e);for(let d of i){if(ld(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=dd(e,u),h=fd(c,f);if(h.startsWith("..")||h==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await od(f,{recursive:!0});continue}await od(vy(f),{recursive:!0});let g;try{g=d.getData()}catch(_){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${_.message}`,{cause:_})}await cd(f,g)}}function jy(t){let e;for(let r of t){let i=r.entryName;if(!i||ld(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 Wy(t,e){await Ky(t);let r=zf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await _0(w0.from(t),r)}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 Ky(t){let e=[],r=Cr({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(h=>h==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await _0(w0.from(t),r)}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 $y=5e3;async function Vy(t,e,r,i){return T0(t,e,r,i,{count:0})}async function T0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await m0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(ky.has(u.name)||u.isSymbolicLink())continue;if(o.count>=$y){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=le(e,u.name),h=Sy(le(r,u.name)),g=null;try{g=await sd(f)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let _={name:u.name,path:C0(fd(t,f)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(_.children=await T0(t,f,h,i-1,o)),d.push(_)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function Jy(t){return!t||t<=0?Iy:Math.min(t,Ay)}function Zy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function C0(t){return t.split(g0).join("/")}te();var In=G("agent-health-reporter"),Yy=1e4,Xy=3,Hi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Yy,this.livenessFailureThreshold=e.livenessFailureThreshold??Xy}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 r=[];for(let d of this.opts.core.agents.values()){let u=Qy(d);if(!u)continue;let f={agentId:d.agentId,status:u};d.patToken&&(f.patToken=d.patToken),d.accountId&&(f.accountId=d.accountId),r.push(f)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Nt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,In.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(In.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){In.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){In.warn("onTickEnd hook failed",{err:String(r)})}}};function Qy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Wt();import{mkdir as gd,rm as Wb,stat as Kb}from"node:fs/promises";import{homedir as $b}from"node:os";import{join as ox}from"node:path";ln();import{existsSync as lb}from"node:fs";import{release as ub}from"node:os";import{basename as fb,isAbsolute as xb}from"node:path";function qi(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 An(t,e){return{jsonrpc:"2.0",id:t,error:e}}$e();var vo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function R0(t){return"method"in t&&"id"in t&&t.id!==void 0}function D0(t){return"method"in t&&!("id"in t)}function So(t){return!("method"in t)&&"id"in t}var eb={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function tb(t){if(t!=null)return t instanceof Error?{name:t.name,message:ji(t.message)}:typeof t=="string"?ji(t):typeof t=="object"?rb(t):t}var nb=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function ji(t){let e=t;for(let[r,i]of nb)e=e.replace(r,i);return e}function rb(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=ji(i):e[r]=i;return e}function Wi(t){if(t instanceof k){let e=tb(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:eb[t.code]??Y.INTERNAL_ERROR,message:ji(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:ji(t instanceof Error?t.message:String(t))}}function P0(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 k(r,o,{retriable:e?.retriable??!1,cause:c})}function L0(t){return`${JSON.stringify(t)}
103
+ `}var O0=10*1024*1024,Io=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>O0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${O0} bytes`)}),[]}let r=this.buffer.split(`
104
+ `);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 M0={"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"},_T=Object.fromEntries(Object.entries(M0).map(([t,e])=>[e,t])),ib={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Br=class{seq=0;next(e,r){this.seq+=1;let i=M0[e]??sb(e),o=ib[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>N0(r?.[f]??"")),u=ob(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>N0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function sb(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function N0(t){return t.replace(/[:_\s]+/g,"-")}function ob(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Xt();ar();$e();te();Re();import{execFileSync as ab,spawnSync as cb}from"node:child_process";function Ki(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function $i(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),cb("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var hd=new Set;function B0(t){typeof t=="number"&&t>0&&hd.add(t)}function F0(t){typeof t=="number"&&hd.delete(t)}function z0(){for(let t of hd)$i(t,"SIGKILL")}var Fr="coze-bridge-daemon";function U0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return ab("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(`
105
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function G0(t,e){if(t.length===0)return;let r=e?.killFn??$i,i=e?.isAliveFn??Ki,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,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(f=>i(f));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var db=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function H0(t,e){if(!e)return null;for(let r of db)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function q0(t,e){return H0(t,e)}function j0(t,e){return H0(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 W0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let h=t.suspendedMs+o,g=r-t.startedAt-h;return{action:"suspend",suspendedDeltaMs:o,rearmMs:zr(g,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 K0=Ze("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),hb=200,pb=40,mb=Ze("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),gb=Ze("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),wb=Ze("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),_b=Ze("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),yb=Ze("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),bb=Ze("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),$0=500;function Eb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=$0?t:`${e.slice(0,$0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function vb(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 V0(t){try{return lb(t)}catch{return}}function Sb(t,e){return{platform:process.platform,osRelease:ub(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:xb(e.command)?V0(e.command):void 0,cwd:e.cwd,cwdExists:V0(e.cwd),envKeys:e.envKeys}}function Ib(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${fb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var pt=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Io({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 k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=$f(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,B0(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,F0(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=Sb(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 k("AGENT_SPAWN_FAILED",Ib(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()));$i(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||$i(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:yb,phase2GateMs:mb,livenessWindowMs:gb,absoluteMaxMs:wb,approvalMaxMs:bb,suspendThresholdMs:_b,...r};return this.call("session/prompt",e,K0,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,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(An(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=K0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=qi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let f=r.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,h)=>{let g={resolve:f,reject:h,timer:null,method:e,promptTimeout:null};if(o){let _=this.now(),v={cfg:o,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:zr(0,!1,o),sessionId:u};g.promptTimeout=v;let y=()=>{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=W0(E,v.cfg,I),T=D=>{v.armedAt=I,v.expectedIntervalMs=D,g.timer=setTimeout(y,D)};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}:{}}),h(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}:{}}),h(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(y,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(g.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),h(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(d)}catch(_){g.timer&&clearTimeout(g.timer),this.pending.delete(c),h(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(L0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(So(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new k("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:Eb(e.result)}),r.resolve(e.result));return}if(D0(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(R0(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(An(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(An(e.id,Wi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=P0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=j0(this.framework,vb(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(pb).join(`
106
+ `),o=q0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Ab(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 pt{framework="claude-code";constructor(e){let{command:r,args:i}=si("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 Ab(e)}};ln();import{mkdtempSync as kb,rmSync as Tb}from"node:fs";import{tmpdir as Cb}from"node:os";import{join as Rb}from"node:path";var J0=["default","acceptEdits","plan","auto","bypassPermissions"],Z0=["read-only","auto","full-access"];var Y0=["default","accept_edits","dont_ask"];function Mt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return J0.includes(e);case"codex":return Z0.includes(e);case"hermes":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 X0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function pd(t){switch(t){case"claude-code":return J0.join("/");case"codex":return Z0.join("/");case"hermes":return Y0.join("/");case"openclaw":return""}}var To=class extends pt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=si("codex",e.command,i),d=e.isolateCodexHome?kb(Rb(Cb(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,f={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(f),this.authMethodId=e.authMethodId,this.codexHomeDir=d}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}setSessionMode(e){let r=Mt("codex",e.modeId)?ko(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(Db(r)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Tb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Db(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=X0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}te();var Pb=G("hermes-downstream"),Co=class extends pt{framework="hermes";modelId;constructor(e){let r={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(r),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(r){Pb.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(r)})}}};$e();var Ob=3e4,Ur=class extends pt{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}`}]},Ob))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};jt();$e();te();Re();function md(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((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 Ro=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 kn,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)Vi(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 Vi(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();te();import{constants as Q0}from"node:fs";import{access as Lb,readFile as Nb}from"node:fs/promises";import{delimiter as Mb,dirname as Bb,join as ex}from"node:path";var et=G("framework-detector"),tx={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Fb=[".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??st,access:e.access??Lb,readFile:e.readFile??Nb}}async detect(e){let r=tx[e],i=await this.which(r);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return et.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(tx).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(Mb).filter(Boolean),i=this.env.platform==="win32"?["",...Fb]:[""];for(let o of r)for(let c of i){let d=ex(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?Q0.F_OK:Q0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let r;try{r=await this.env.readFile(e,"utf8")}catch(d){return et.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let o=r.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return et.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let c=ex(Bb(o),"hermes-acp");return await this.isExecutable(c)?(et.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:c}),c):(et.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:c}),null)}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return et.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return et.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 et.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 et.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?(et.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}:(et.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return et.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return et.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||et.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){et.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&&(Ub(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,d,u=f=>{c||(c=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",h=>{o+=h.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",h=>u({code:h,stdout:o}))}catch{u(null)}})}},zb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Ub(t){return t.replace(zb,"")}import{homedir as Gb}from"node:os";import{join as Hb}from"node:path";jt();Xt();ar();$e();te();async function ix(){let t=Hb(Gb(),".openclaw/openclaw.json");return ur(t)}async function sx(){return(await ix())?.gateway?.auth?.token??""}var nx=G("openclaw.config"),qb=[0,5e3,5e3],jb=Ze("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),rx="models.providers.",Do="agents.defaults.models",Po=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??qb,this.cliTimeoutMs=e.cliTimeoutMs??jb}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,nx.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=st(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=h=>{d||(d=!0,clearTimeout(f),h())};o.stderr?.on("data",h=>{c+=h.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",h=>u(()=>i(h))),o.on("close",h=>u(()=>{h===0?r():i(new Error(`exit ${h}: ${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){nx.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",`${rx}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${rx}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Do}[${e}]`,()=>this.runCli(["config","set",Do,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Do}[${e}]`,`${Do}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await ix())?.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"])))}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"])))}};var ue=G("agent-manager"),_d="acceptEdits",dx="full-access",lx="read-only";function Vb(t){return{INITIAL_AGENT_MODE:ko(t)}}var Jb=(t,e,r,i,o,c,d,u,f,h)=>{switch(t){case"claude-code":{let g={...o?{...r0(o),...o0(o,d,u)}:{},...f??{},IS_SANDBOX:"1"};return new Ao({cwd:r,env:g,agentId:i})}case"codex":{let g=dx;h!==void 0&&(Mt("codex",h)?g=h:ue.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let _=!!o,v={...o?{...s0(o),...i0(o,d,u)}:{},...Vb(g),..._?{NO_BROWSER:"1"}:{},...f??{}};return new To({cwd:r,agentId:i,...Object.keys(v).length>0?{env:v}:{},..._?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ur({command:e,cwd:r,agentId:i,...c?{sessionName:md(c)}:{}});case"hermes":return new Co({command:e,cwd:r,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model?{modelId:o.model}:{}})}};function wd(t){return t==="claude-code"||t==="codex"}var Zb={path:"",version:"cloud-deployed"},ax="openclaw_gateway_unavailable",Yb="openclaw_default_agent_missing";function cx(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 Xb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Qb=6e4,Oo=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??Jb,this.createTimeoutMs=e.createTimeoutMs??Qb,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Po({command:r})),this.openclawConfigDir=e.openclawConfigDir??ox($b(),".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=>{ue.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=ox(e,".env");if(await Kb(r).then(c=>c.isFile()).catch(()=>!1)){ue.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Bi({...process.env,...Mi(this.paths.agentEnvFile)});await ut(r,o,{mode:384}),ue.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ue.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await ve(e.agentId,this.paths).catch(()=>null),o=xo(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")ue.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>ue.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")ue.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>ue.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ue.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await ve(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Ue(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ue.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await ve(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Ue(T,this.paths))}return ue.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 D=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${D}`)}let u=ze(e.agentId,this.paths),f=o?"cloud":"local",h=e.framework==="openclaw"&&f==="local",g;h&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=g??(h?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??_??u.workspace,y=new AbortController,E=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&wd(e.framework)&&await lr(e.framework,y.signal);let T=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await gd(u.root,{recursive:!0}),await gd(v,{recursive:!0}),await gd(u.logs,{recursive:!0}),T(),h||await xr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Ha(v,"cloud"):await Ha(v,"local",_d)),T();let D=i,b=t0({model:e.model??D?.model}),R=Gf(e._meta)??D?.accountId,P=e.patToken??D?.patToken,B=f==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new Ro({agentId:e.agentId,framework:e.framework,workspace:v,model:b.model??At,deployType:f,...R?{accountId:R}:{},...P?{patToken:P}:{},...B?{modelInfo:B}:{}}),I.status="ok",D?.sessions){let V=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,se]of Object.entries(D.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ue.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:oe.permissionMode})):Mt(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:ue.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&ue.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(X,oe)}let re=Object.keys(D.sessions).length;re>0&&ue.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),A=!0;let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:b.model};f==="cloud"&&(M.deployType="cloud"),R&&(M.accountId=R),P&&(M.patToken=P),B&&(M.modelInfo=B),D?.skills&&(M.skills=D.skills),D?.agentName&&(M.agentName=D.agentName),D?.description&&(M.description=D.description),M.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Nt,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ue.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let J=e.initialSkills??[];if(J.length>0){let V=[...M.skills??[]],re=new Map(V.map((oe,C)=>[oe.skillId,C])),X=await Promise.allSettled(J.map(oe=>bo({agentId:e.agentId,workspace:v,framework:e.framework,skill:oe,paths:this.paths}))),se=0;for(let[oe,C]of X.entries()){let z=J[oe];z&&(C.status==="fulfilled"?(Eo(V,re,C.value),se++):ue.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:z.skillId,skillName:z.skillName,err:String(C.reason)}))}se>0&&(M.skills=V,ue.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:J.length}))}return await Ue(M,this.paths),ue.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(T){throw ue.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ue.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:r?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await Wb(u.root,{recursive:!0,force:!0}).catch(D=>ue.warn("rm agent dir failed (ignored)",{err:String(D)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&wd(e.framework))u=Zb;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`);wd(e.framework)&&!_s(e.framework)&&(ue.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(e.framework));let f=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,h;if(e.framework==="openclaw")h=await this.buildOpenclawDownstream({session:e,modelConfig:f,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else if(e.framework==="hermes"){let g={...this.buildBinShimPathEnv()};f&&(await f0({paths:this.paths,agentId:e.agentId,modelConfig:f,cozeEnv:o,mockScenario:c}),g.HERMES_HOME=Jn(e.agentId,this.paths)),h=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,g)}else{let g=e.sessions.get(i),_=Qt(e)?g?.permissionMode??dx:"full-access";h=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),_)}try{return await h.start(),await h.initialize(Xb),h}catch(g){let _=h instanceof pt?h.getStderrTail():[];throw _.length>0&&ue.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:_}),await h.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,g)}}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 k("AGENT_ENV_NOT_READY",cx(o),{cause:{reason:ax}})}catch(o){ue.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};ue.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 ue.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:Yb}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new k("AGENT_ENV_NOT_READY",cx(r),{cause:{reason:ax}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,f=md(o);if(r.deployType==="local"){let _=await this.ensureOpenclawDefaultAgent();return new Ur({command:u,cwd:_.workspace,agentId:_.id,sessionName:f})}let h=await sx(),g;if(i?.modelToken){let _=ed(o),v=td(i),y=`${_}/${v}`;if(!this.ensuredProviders.has(y)){let E=this.getOpenclawConfig(),I=await E.getAllowlistModelsForProvider(_),A=a0(i,c,d,I);A&&(await E.ensureProvider(_,A),await E.addModelToAllowlist(y),this.ensuredProviders.add(y))}g=y}return new Ur({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...h?{gatewayToken:h}:{},...g?{slashModelOnStart:g}:{}})}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=ed(c),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(h){f=!1,ue.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(h)})}try{await i.removeModelFromAllowlist(u)}catch(h){f=!1,ue.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(h)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as px}from"node:crypto";import{promises as oE}from"node:fs";import{basename as mx}from"node:path";$e();te();import{promises as eE}from"node:fs";import{basename as tE}from"node:path";var ux=G("file-upload"),nE="/api/coze_claw/file/agent_upload",rE=6e4;async function fx(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${nE}`,o=e.timeoutMs??rE,c=await eE.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",...Sn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,h=setTimeout(()=>f.abort(),o);ux.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),_=g.headers.get("x-tt-logid")??"";if(!g.ok){let E=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${_}: ${E.slice(0,200)}`)}let v=await g.json();if(v.code!==void 0&&v.code!==0)throw new k("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${_}`);let y=v.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(v).slice(0,200)}`);return ux.info("file upload ok",{uri:y,logid:_}),{uri:y}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${tE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(h)}}$e();te();import{extname as iE}from"node:path";var sE={".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 xx(t){let e=iE(t).toLowerCase();return sE[e]??"application/octet-stream"}Re();var Lo=G("agent-send"),hx=50*1024*1024;function gx(t,e,r){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new k("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function _x(t,e,r,i,o,c){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(h){u=h,f<2&&(Lo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(h)}),await new Promise(g=>setTimeout(g,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function yx(t,e){let{session:r,runtime:i}=gx(e.core,t.agentId,t.sessionId);if(!await oi(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await oE.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>hx)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${hx}`);let c=await xx(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 d=t.name??mx(t.path),u;try{u=await fx({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(h){throw Lo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:h instanceof k?h.code:"UNKNOWN",message:h instanceof Error?h.message:String(h)}),h}let f={sessionUpdate:"agent_file",messageId:px(),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 _x(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Lo.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 bx(t,e){let{session:r,runtime:i}=gx(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??mx(t.path),c={sessionUpdate:"group_file",messageId:px(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await _x(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Lo.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 Ex(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}Xt();te();ln();var Bt=G("coze-cli-installer"),vx="@coze/cli@latest",aE="coze",Sx="0.1.8",cE=5e3,dE=5e3,lE=9e4,Ix=1e4,Ji=null,No=!1;async function bd(t,e={}){if(No)return;if(Ji)return Ji;let r=e.exec??Kf;return Ji=(async()=>{try{let i=await uE(aE,r),o=!1;if(i){let d=await fE(r);if(d===void 0)Bt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Ex(d,Sx))Bt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Sx}),o=!0;else{Bt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),No=!0;return}}let c=o?"upgrade-only":"full";Bt.info("coze-cli install start",{package:vx,mode:c});try{await r("npm",["i","-g","--prefer-online",vx],{timeout:lE,maxBuffer:10*1024*1024}),Bt.info("coze-cli install ok")}catch(d){Bt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){No=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:Ix}),Bt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Bt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:Ix}),Bt.info("coze auth login ok")}catch(d){Bt.warn("coze auth login failed",{err:String(d)});return}No=!0}finally{Ji=null}})(),Ji}async function uE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:cE});return Ua(i)}catch{return}}async function fE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:dE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Wt();jt();Re();var xE=10*6e4;function Ax(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?xE:e}function Mo(t){return ur(t??Z().configFile)}function Zi(t,e){return fr(e??Z().configFile,t)}import{randomBytes as OE}from"node:crypto";ar();$e();te();import{createReadStream as hE}from"node:fs";import{mkdir as pE,readFile as mE,realpath as gE,stat as wE,writeFile as _E}from"node:fs/promises";import{basename as yE,dirname as Ed,isAbsolute as bE,join as EE,relative as vE,resolve as kx,sep as SE}from"node:path";import{createInterface as IE}from"node:readline";var Cx=G("fs-rpc"),Yi=Ze("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Rx(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Yi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Yi} bytes`);let i=await Px(t.path,e);return await pE(Ed(i),{recursive:!0}),await _E(i,t.content,"utf8"),Cx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Dx(t,e){let r=await Px(t.path,e),i=await wE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Yi&&!o)throw new k("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 AE(r,t.line??1,t.limit);else{let d=await mE(r,"utf8");if(o){let u=d.split(`
107
+ `),f=Math.max(0,(t.line??1)-1),h=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,h).join(`
108
+ `)}else c=d}return Cx.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function AE(t,e,r){let i=IE({input:hE(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 f of i)if(u>=o&&u<c&&d.push(f),u++,u>=c)break}finally{i.close()}return d.join(`
109
+ `)}async function Px(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([Tx(kx(e)),Tx(kx(t))]),o=vE(r,i);if(kE(o,SE,bE(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function kE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Tx(t){let e=[],r=t;for(;r!==Ed(r);)try{let i=await gE(r);return e.length?EE(i,...e.reverse()):i}catch{e.push(yE(r)),r=Ed(r)}return t}te();var Ox=G("prompt-multimodal"),Lx=10*1024*1024,TE=15e3,CE=6;async function Nx(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 RE(d))}}let o=Array.from({length:Math.min(CE,t.length)},()=>i());return await Promise.all(o),e}function Mx(t){return t.some(e=>e.type==="image")}async function RE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ni(e.uri))return t;try{let{buf:r,contentType:i}=await PE(e.uri),o=e.mimeType||DE(i)||"application/octet-stream";return Ox.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 Ox.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function DE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function PE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),TE);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>Lx)throw new Error(`image too large: ${o.byteLength} bytes (max ${Lx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}Wt();$e();te();var $=G("core"),LE=3e4,NE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,ME="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",BE="\u5BA1\u6279\u5DF2\u8D85\u65F6",FE=3e4,Bo=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=Ax(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}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){$.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&$.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let 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)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Vi(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){$.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(An(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>$.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(So(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&&NE.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Mr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Mr(r,o));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,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(o){$.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(An(r,Wi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let 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 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 f=o.sessions.get(c);if(f?.pendingPermission){let h=r._meta?.cozeTriggerMsgId,g=ho(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,ME,h,g)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,f}finally{$.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}=qf(i);switch(r){case"session/new":{let c=zE();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return $.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 k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Qt(e)?Hf(i._meta):void 0;if(u!==void 0&&!Mt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${pd(e.framework)}`);let f=await this.ensureRuntime(e,d);if(u!==void 0&&f.permissionMode===void 0&&(f.permissionMode=u,await this.persistSessionMapping(e)),f.replySeq=0,await this.ensureDownstream(e,d,f),!f.downstream||!f.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&f.permissionMode!==void 0&&f.permissionMode!==u){let v=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(y){throw f.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),y}}let h=i._meta?.cozeTriggerMsgId;h?e.activeTriggers.set(f.acpSessionId,h):e.activeTriggers.delete(f.acpSessionId);let g=ho(i._meta);if(g?e.activeGroupIds.set(f.acpSessionId,g):e.activeGroupIds.delete(f.acpSessionId),g&&f.cozeGroupId!==g&&(f.cozeGroupId=g,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Mx(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await Nx(c.prompt);try{let v=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:_});return f.lastActiveAt=Date.now(),v}catch(v){if(v instanceof k&&v.code==="AGENT_APPROVAL_TIMEOUT"){let y=f.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),f.pendingPermission=void 0);let E=f.acpSessionId,I=E?e.activeTriggers.get(E):void 0,A=E?e.activeGroupIds.get(E):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,f,d,BE,I,A)}throw v}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let v=f.downstream;v&&(f.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:f.acpSessionId}),v.stop("reload-after-turn").catch(y=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(y)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,d,f)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,f=ho(i._meta);if(!d)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(!Mt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${pd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let h=e.sessions.get(d)??await this.ensureRuntime(e,d);if(h.permissionMode===u)return{};let g=h.permissionMode;if(h.permissionMode=u,await this.persistSessionMapping(e),h.downstream?.isAlive()&&h.acpSessionId)try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(_){throw h.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),_}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${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 $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets: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,f=d.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,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 f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Qt(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?d0:l0:c.permissionMode=e.framework==="claude-code"?_d:lx),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ht.GEN_MODEL_TOKEN,i,FE);if(!o?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);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,r,i){if(Vi(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,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new k("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 f;try{f=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(h){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&($.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),h}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(h){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),i.acpSessionId=void 0;let g=await f.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let h=await f.sessionNew({cwd:e.workspace});i.acpSessionId=h.sessionId,await this.persistSessionMapping(e)}}catch(h){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,h}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),Qt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(h){$.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(h)})}}armIdleTimer(e,r,i){if(Vi(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let 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(f=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(HE(r)){$.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"&&Qt(e)){let g=d.currentModeId;Mt(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(_=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof g=="string"&&!Mt(e.framework,g)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let h=e.activeGroupIds.get(i);h&&(u.cozeGroupId=h),this.upstream.send(Nr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>$.warn("forward update failed",{agentId:e.agentId,err:String(g)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}$.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Rx(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Dx(c,o);r.respondAgentRequest(i.id,d)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Wi(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,f=u?e.activeTriggers.get(u):void 0,h={cozeAgentId:e.agentId};f&&(h.cozeTriggerMsgId=f);let g=u?e.activeGroupIds.get(u):void 0;g&&(h.cozeGroupId=g);let _=u?this.reverseSessionId(e,u):void 0,v=_?e.sessions.get(_):void 0;v&&(v.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let y={...c,..._?{sessionId:_}:{},_meta:h};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:_}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(qi(o,"session/request_permission",y)).catch(E=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),r.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?($.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&UE(e.result,o),$.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new vo(e.error)):i.value.resolve(e.result);return}$.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 $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=LE){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(qi(o,e,r)).catch(f=>{let h=this.pendingBridge.get(o);h&&(clearTimeout(h.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let 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&&Qt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ai(e.agentId,r,this.paths)}catch(r){$.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(An(e,{code:r,message:i,data:{bridgeVersion:Nt}}))}};function zE(){return OE(16).toString("hex")}function UE(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){$.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){$.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var GE=["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."],Bx="Warning: ";function HE(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(Bx)?i.text.slice(Bx.length):i.text;return GE.some(c=>o.startsWith(c))}jt();te();Re();import{randomBytes as qE}from"node:crypto";import{createServer as jE}from"node:http";var WE=1e6,Fx=G("ipc"),Fo=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=qE(32).toString("hex");let e=jE((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(),Fx.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 ut(this.paths.portFile,String(this.port)),await ut(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Xi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Xi(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await KE(e)}catch(u){Xi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Xi(r,200,u??{ok:!0})}catch(u){Fx.error("IPC handler failed",{key:o,err:String(u)}),Xi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Xi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function KE(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>WE)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 xS=qt(Oh(),1),hS=qt($o(),1),pS=qt(qr(),1),mS=qt(Od(),1),gS=qt(Md(),1),wS=qt(Hd(),1),Hh=qt(Yo(),1),_S=qt(Gh(),1);var qh=Hh.default;$e();te();var{FWS:NS}=ep(),Oe=G("upstream.frontier"),np="application/json",rp="none",MS=15e3;function BS(t){class e extends qh{constructor(i){super(i,Jf,{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(Pl("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");Oe.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Oe.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var as=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:Zf,...Sn(this.opts.ppeOverride)},r=BS(e),i=Xf(this.opts.urlOverride),o={url:i,ws:r,fpID:Vf,aID:po,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:np,force:!0},payloadEncoding:{encoding:rp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new NS(o),d=!1,u=null,f,h,g=new Promise((y,E)=>{f=y,h=E}),_=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?h(y):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Oe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&_();for(let E of this.connectHandlers)Promise.resolve(E({initial:y})).catch(I=>Oe.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Oe.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Oe.warn("frontier error",{code:y.code,msg:y.message}),_(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let v=this.opts.openTimeoutMs??MS;u=setTimeout(()=>{_(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await g}catch(y){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,y}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Oe.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)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:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;ip(c)||Oe.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:np,payloadEncoding:rp})}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 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){Oe.debug("drop non-adapter frontier frame",{service:r});return}let i=US(e);if(!i){Oe.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Oe.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Oe.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;ip(c)||Oe.info("frontier frame in",{logid:zS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:FS(i)}),Promise.resolve(this.handler(o)).catch(d=>Oe.warn("frontier frame handler threw",{err:String(d)}))}};function ip(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var sp=2e3;function FS(t){return t.length<=sp?t:`${t.slice(0,sp)}...<truncated, total ${t.length} chars>`}function zS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function US(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}}$e();te();var Kd=G("skill-publish"),GS="/api/marketplace/product/skill/publish_with_assets",HS=15e4;async function op(t,e={}){let i=`${Dr(Pr(e.handshakeBase))}${GS}`,o=e.timeoutMs??HS,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",...Sn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);Kd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let h=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),g=h.headers.get("x-tt-logid")??"";if(!h.ok){let y=await h.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${h.status} logid=${g}: ${y.slice(0,200)}`)}let _=await h.json();if(Kd.info("skill publish response",{logid:g,httpStatus:h.status,code:_.code,msg:_.msg,dataSkillId:_.data?.skill_id??"",dataVersion:_.data?.version??""}),_.code!==void 0&&_.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${_.code} msg=${_.msg??"-"} logid=${g}`);let v={};return _.data?.skill_id!==void 0&&_.data.skill_id!==""&&(v.skillId=String(_.data.skill_id)),_.data?.version&&(v.version=_.data.version),Kd.info("skill publish ok",{logid:g,skillId:v.skillId??"",version:v.version??""}),v}catch(h){throw h instanceof k?h:h.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(h),{cause:h})}finally{clearTimeout(f)}}te();var $d=G("upstream.switchable"),oa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;$d.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 $d.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>$d.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};te();var Vd=G("upstream"),Jr=class{handler=null;async start(){Vd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Vd.info("NoopUpstream stopped",{reason:e})}async send(e){Vd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};$e();te();jt();te();Re();import{promises as qS}from"node:fs";var ap=G("pat-token-store");async function aa(t=Z()){try{let r=(await qS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(ap.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"&&ap.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function cs(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await ut(e.patTokenFile,t,{mode:384})}Re();Re();import{promises as ca}from"node:fs";import{join as jS}from"node:path";function WS(t,e){return`#!/bin/sh
107
110
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
108
- `}function n1(t,e){return`@echo off\r
111
+ `}function KS(t,e){return`@echo off\r
109
112
  "${e}" "${t}" %*\r
110
- `}async function ip(t,e=J()){let n=e.binDir;await ia.mkdir(n,{recursive:!0});let i=e1(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?n1(t,o):t1(t,o);return await ia.readFile(i,"utf8").catch(()=>null)===c||(await ia.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ia.chmod(i,493)),n}ne();Re();import{execSync as sp}from"node:child_process";import{readFileSync as op,unlinkSync as r1}from"node:fs";import{mkdir as i1,open as s1,readFile as ap,unlink as Zd,writeFile as o1}from"node:fs/promises";import{dirname as a1}from"node:path";var c1=G("single-instance"),d1=t=>new Promise(e=>setTimeout(e,t)),sa=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??J().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Wi(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&&c1.warn("removing stale pid file",{stalePid:i}),await o1(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 ap(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Zd(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 ap(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 i1(a1(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await s1(n,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await d1(this.claimLockIntervalMs);continue}await Zd(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Zd(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=op(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Mr)||n.includes("lib/index.js"))}catch{}try{let n=sp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Mr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=sp(`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{op(this.pidFile,"utf8").trim()===String(this.selfPid)&&r1(this.pidFile)}catch{}})}};oa();ne();var nr=G("daemon.upstream-watchdog"),m1=12e4,w1=9e5,_1=3e4;function Xd(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var aa=class{constructor(e){this.opts=e;this.softMs=e.softMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",m1),this.hardMs=e.hardMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",w1),this.intervalMs=e.intervalMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",_1),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 H=G("daemon");async function lp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ol({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>je(C,t).logs,listAgentIds:()=>ws(t)});try{let{writeFileSync:C}=await import("node:fs");C(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
113
+ `}async function cp(t,e=Z()){let r=e.binDir;await ca.mkdir(r,{recursive:!0});let i=jS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?KS(t,o):WS(t,o);return await ca.readFile(i,"utf8").catch(()=>null)===c||(await ca.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ca.chmod(i,493)),r}te();Re();import{execSync as dp}from"node:child_process";import{readFileSync as lp,unlinkSync as $S}from"node:fs";import{mkdir as VS,open as JS,readFile as up,unlink as Jd,writeFile as ZS}from"node:fs/promises";import{dirname as YS}from"node:path";var XS=G("single-instance"),QS=t=>new Promise(e=>setTimeout(e,t)),da=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=>Ki(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&&XS.warn("removing stale pid file",{stalePid:i}),await ZS(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 up(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Jd(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 up(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 VS(YS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await JS(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 QS(this.claimLockIntervalMs);continue}await Jd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Jd(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=lp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Fr)||r.includes("lib/index.js"))}catch{}try{let r=dp(`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=dp(`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{lp(this.pidFile,"utf8").trim()===String(this.selfPid)&&$S(this.pidFile)}catch{}})}};la();te();var nr=G("daemon.upstream-watchdog"),a1=12e4,c1=9e5,d1=3e4;function Yd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ua=class{constructor(e){this.opts=e;this.softMs=e.softMs??Yd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",a1),this.hardMs=e.hardMs??Yd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",c1),this.intervalMs=e.intervalMs??Yd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",d1),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 r=e-this.downSince;if(r>=this.hardMs){nr.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,nr.warn("upstream watchdog: forcing reconnect",{downMs:r,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 q=G("daemon");async function hp(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Rl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>ze(C,t).logs,listAgentIds:()=>ys(t)});try{let{writeFileSync:C}=await import("node:fs");C(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
111
114
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
112
115
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
113
- `)}catch{}}let e=new sa({processTitle:Mr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Do(),o=i??{};xs({pid:process.pid}),H.info(i?"loaded bridge config":"initialized bridge config");let c=new na(new Vr),d=null,u=new Oo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(C,U,W,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(C,U,W,ee)}}),h=new Ro({paths:t,config:o,registry:u});d=h;let x,m,g=null,S={},_,v=null,I=null,A=null,T=new Tn;function P(C,U){return T.enqueue(()=>R(C,U))}function E(){I||(I=new aa({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:C=>{if(process.env[os]==="1"){H.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}H.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),I.start()}async function R(C,U){let W=C,ee=W?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Ye=Mi(W.env),xe=W.handshake_url,pe=W.frontier_url,vt=dp(W.env,xe,pe);if(A=W,!U?.force&&x===ee&&m===vt){let _e=await y1(t);return u.agents.size===0&&_e?(H.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),da(t,h).catch(ke=>H.warn("connect-noop auto-revive error (ignored)",{err:String(ke)}))):H.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let xt=!!x&&x!==ee,nn=m!==void 0&&m!==vt,Gt=xt||nn,rn=await Vc({privatecode:ee,...xe?{endpoint:xe}:{},ppeOverride:Ye});if(Gt){H.warn("connect config switched, resetting agents",{pcChanged:xt,envChanged:nn,previousPc:x?ca(x):"",nextPc:ca(ee)});for(let _e of[...u.agents.values()])await _e.dispose("connect config switch").catch(()=>{}),u.agents.delete(_e.agentId);u.disconnectedAgents.size>0&&(H.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"connect switch").catch(()=>{})}g=rn.deviceId,xs({deviceId:g,pid:process.pid}),bd({patToken:ee,env:W.env}).catch(_e=>H.warn("coze-cli setup error (ignored)",{err:String(_e)}));let Qr=new is({handshake:rn,privatecode:ee,...pe?{urlOverride:pe}:{},ppeOverride:Ye,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(Qr,"connect"),x=ee,m=vt,S=Ye,_=xe,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),H.info("mock scenario set",{scenario:W.mock_scenario})),v||(v=new Fi({core:u,getDeviceId:()=>g??"",onTickEnd:()=>N.retryPending().catch(_e=>H.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:$})),v.start(),E(),Gt&&da(t,h).catch(_e=>H.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),ss(ee,t).catch(_e=>H.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),H.info("/connect: WS established",{deviceId:g}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>h.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},B=new go({agents:u.agents,publishSkillToMarketplace:async C=>{let U=u.agents.get(C.agentId)?.patToken??x;if(!U)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return np({patToken:U,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(C,U)=>{let W=u.agents.get(C);if(W){await h.cleanupOpenclawSessionProviders(W).catch(Ye=>H.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(Ye)}));let ee=!0;try{await W.dispose(`disconnect: ${U}`)}catch(Ye){ee=!1,H.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(Ye)}),W.status="error"}ee&&(W.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,U)=>{let W=u.agents.get(C);W&&(await h.cleanupOpenclawSessionProviders(W).catch(ee=>H.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),await W.dispose(`delete: ${U}`).catch(ee=>H.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(C)},cleanupOpenclawProviders:async(C,U)=>{await h.cleanupOpenclawSessionProviders(C,U)},openclawRepair:async(C,U)=>{await h.openclawRepair(C,U)},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>B.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>B.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>B.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>B.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>B.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>B.getFileContent(C.params)),u.registerExtension("_agent/update",C=>B.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>B.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>B.switchModel(C.params)),u.registerExtension("_agent/reset",C=>B.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>B.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>B.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>B.upgradeBridge(C.params));let N=new Es({paths:t,handlers:B,agentManager:h,sendDetail:C=>u.sendRequest("_agent/detail",C)});O.ref=N;let $=async C=>{await Promise.allSettled(C.map(async U=>{try{await B.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),H.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(W){H.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(W)})}}))};c.onConnect(({initial:C})=>{H.info("frontier upstream connected, triggering detail sync",{initial:C}),N.syncAll(C?"initial-connect":"reconnect").catch(U=>H.warn("detail sync top-level error (ignored)",{err:String(U)}))});let j=new Lo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[os]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:g??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let U=C,W=U?.privatecode,ee=U?.pairing_code;if(!W||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ye=Mi(U.env),xe=U.handshake_url,pe=U.frontier_url,vt=dp(U.env,xe,pe),xt=!!x&&x!==W,nn=m!==void 0&&m!==vt,Gt=xt||nn,rn=await Vc({privatecode:W,...xe?{endpoint:xe}:{},ppeOverride:Ye});if(Gt){H.warn("pair config switched, resetting agents",{pcChanged:xt,envChanged:nn,previousPc:x?ca(x):"",nextPc:ca(W),previousEnvKey:m??"",nextEnvKey:vt});for(let ke of[...u.agents.values()])await ke.dispose("pair config switch").catch(()=>{}),u.agents.delete(ke.agentId);u.disconnectedAgents.size>0&&(H.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Vr,"pair switch").catch(()=>{})}g=rn.deviceId,xs({deviceId:g,pid:process.pid}),bd({patToken:W,env:U.env}).catch(ke=>H.warn("coze-cli setup error (ignored)",{err:String(ke)}));let Qr=new is({handshake:rn,privatecode:W,...pe?{urlOverride:pe}:{},ppeOverride:Ye,getPatTokenForAgent:ke=>u.agents.get(ke)?.patToken});await c.swap(Qr,"pair");try{let ke=new Jn;o.frameworksCache=await ke.detectAll(),await $i(o),H.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(ke){H.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ke)})}let _e=Object.keys(o.frameworksCache??{});try{let ke=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:W,frameworks:_e,_meta:{cozeDeviceId:g}});H.info("_agent/pair ok",{pairResult:ke}),x=W,m=vt,S=Ye,_=xe,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),H.info("mock scenario set",{scenario:U.mock_scenario})),ss(W,t).catch(Oe=>H.warn("writePatToken after /pair failed (ignored)",{err:String(Oe)})),v||(v=new Fi({core:u,getDeviceId:()=>g??"",onTickEnd:()=>N.retryPending().catch(Oe=>H.warn("detailSync.retryPending failed (ignored)",{err:String(Oe)})),onAuthFailures:$})),v.start(),E(),Gt&&da(t,h).catch(Oe=>H.warn("post-pair-switch auto-revive error (ignored)",{err:String(Oe)}));let rr;return U.agent_id&&(rr=await b1(U.agent_id,t,h,Oe=>u.sendRequest("_agent/detail",Oe),W).catch(Oe=>(H.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",...rr?{agent:rr}:{}}}catch(ke){return H.error("_agent/pair failed",{err:String(ke)}),{ok:!1,note:`pair failed: ${String(ke)}`}}}},{method:"POST",path:"/connect",handler:C=>P(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let U=C;return{ok:!0,result:await h.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async C=>{let U=C;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.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=U;return await(W.groupFile?mh:gh)(W,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(W){if(W instanceof k)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async C=>{let U=C?.agent_id,W=await u.reloadAgents(U);return H.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(H.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await j.start();try{await ip(t.libEntry,t)}catch(C){H.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),v1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Jn().detectAll(),await $i(o),o.frameworksCache)}).catch(C=>H.warn("startup warmup error (ignored)",{err:String(C)})),Wl().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(an(),Gl));for(let U of["claude-code","codex"]){let W=await C(U);W&&H.info("acp wrapper version",{framework:U,version:W})}}).catch(C=>H.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let se=null,oe={port:re,token:X,core:u,ipc:j,shutdown(C){return se||(H.info("daemon shutdown",{reason:C}),se=(async()=>{v?.stop(),I?.stop(),await u.stop(C),await j.stop(),await e.release()})(),se)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{oe.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>N0()),process.on("unhandledRejection",C=>{H.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{H.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
114
- `)}catch{}process.exit(1)}),H.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),I1({cliSpawned:process.env[os]==="1",readPatToken:()=>ra(t),connect:P}).catch(C=>H.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),oe}async function y1(t){return ws(t).length>0}function ca(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function dp(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function E1(t,e){let n=ws(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(fn(),ys));for(let c of n){await o(c,t).catch(d=>H.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),H.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),H.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){H.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function b1(t,e,n,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(fn(),ys)),d=await c(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);H.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let m=up(d),g={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await n.createAgent(g),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}H.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 v1(t){let e=t.logger??H;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 E1(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await da(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await S1(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function da(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(()=>(fn(),ys));H.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){H.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){H.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){H.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{H.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=up(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){H.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return H.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function S1(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 v0(o,t)).status==="refreshed"&&(i+=1)}catch(c){H.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&H.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function I1(t){let e=t.logger??H;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 up(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}oa();Re();import{readFile as fp}from"node:fs/promises";var tn=class{paths;constructor(e){this.paths=e??J()}async probe(e=1e3){let n=await la(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:k1(i)}}}async request(e){let n=await la(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,d=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:A1(h)}}finally{clearTimeout(d)}}};async function la(t){try{let[e,n]=await Promise.all([fp(t.portFile,"utf8"),fp(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 A1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function k1(t){return t instanceof Error?t.message:String(t)}Jt();ne();ar();import{spawn as T1}from"node:child_process";import{userInfo as xp}from"node:os";var Qd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",R1=new Set(["bash","zsh","sh","dash","ksh"]),hp=$e("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),C1=2e3;function P1(t,e=Qd){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 d of o.split(`
115
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function D1(){let t=(process.env.SHELL??"").trim()||(xp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return R1.has(e)?t:null}function O1(t){return new Promise(e=>{let n=`printf '%s' '${Qd}'; env; printf '%s' '${Qd}'`,i;try{i=T1(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??xp().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"),hp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},hp+C1)})}async function el(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=D1();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??O1)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=P1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Re();function Pn(t,...e){let n=[],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||n.push(c)}return{value:i,rest:n}}an();import{chmod as L1,copyFile as pp,mkdir as mp,readFile as cs,rename as gp,rm as rl,stat as il,writeFile as N1}from"node:fs/promises";import{homedir as KD}from"node:os";import{dirname as M1,join as Ut,resolve as sl,sep as as}from"node:path";import{fileURLToPath as B1}from"node:url";Jt();ne();Re();var Jr=G("dist-install");function wp(){return{darwin:{arm64:"@zed-industries/codex-acp-darwin-arm64",x64:"@zed-industries/codex-acp-darwin-x64"},linux:{arm64:"@zed-industries/codex-acp-linux-arm64",x64:"@zed-industries/codex-acp-linux-x64"},win32:{arm64:"@zed-industries/codex-acp-win32-arm64",x64:"@zed-industries/codex-acp-win32-x64"}}[process.platform]?.[process.arch]}function F1(){return process.platform==="win32"?"codex-acp.exe":"codex-acp"}function z1(t){let e=B1(t),n=M1(e),i=`${as}src${as}`;if(n.includes(i)||n.endsWith(`${as}src${as}cli`))return null;let o=sl(n,"index.js"),c=sl(n,"..","package.json");return{dist:o,pkgJson:c}}async function ol(t={}){let e=t.paths??J(),n=z1(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,d;try{let v=JSON.parse(await cs(o,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){return Jr.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=gs.map(v=>({name:v,spec:d[v]??"latest"})),h=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await Do(e.configFile)??{},m=x.libVersion,g=await cs(e.libEntry).then(()=>!0).catch(()=>!1),S=m===c,_=await _p(e,u);if(S&&g&&_)return{kind:"already-current",libVersion:c};if(!S||!g){await mp(e.libDir,{recursive:!0}),await pp(i,e.libEntry),await pp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=sl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
116
- `;await cs(v,"utf8").catch(()=>null)!==I&&await N1(v,I)}return _||(t.installWrappers?await t.installWrappers(e,h):await G1(e,h,u)),x.libVersion=c,await $i(x,e.configFile),Jr.info("dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),S&&g?{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 _p(t,e){for(let n of e){let i=Ut(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await cs(i,"utf8"))}catch(d){return Jr.warn("wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let c=o.version;if(!c)return Jr.warn("wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!U1(c,n.spec))return Jr.warn("wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:c,expected:n.spec}),!1}return!!await yp(Ut(t.libDir,"node_modules"))}function U1(t,e){let n=tl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=tl(i.slice(1));if(!c)return!0;if(nl(n,c)<0)return!1;let d=c[0]>0?[c[0]+1,0,0]:c[1]>0?[0,c[1]+1,0]:[0,0,c[2]+1];return nl(n,d)<0}let o=tl(i);return o?nl(n,o)===0:!0}function tl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function nl(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 G1(t,e,n){await q1(t.installLock,async()=>{if(await _p(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${as}.staging-${process.pid}-${i}`,c=Ut(o,"node_modules"),d=Ut(t.libDir,"node_modules");try{await mp(o,{recursive:!0}),await H1(e,o),await W1(c);let u=`${d}.trash-${i}`;await gp(d,u).catch(()=>{}),await gp(c,d),await rl(u,{recursive:!0,force:!0}).catch(()=>{}),Jr.info("wrapper closure installed",{liveNm:d,specs:e})}finally{await rl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function H1(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=et("npm",n,{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 W1(t){for(let e of gs){let n=Ut(t,...e.split("/")),i=JSON.parse(await cs(Ut(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=Ut(t,".bin",o),d=await il(c);process.platform!=="win32"&&!(d.mode&73)&&await L1(c,d.mode|73).catch(()=>{})}if(!await yp(t)){let e=wp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex-acp binary \u7F3A\u5931`)}}async function yp(t){let e=wp();if(!e)return!0;let n=Ut(t,...e.split("/")),i=Ut(n,"package.json"),o=Ut(n,"bin",F1()),[c,d]=await Promise.all([il(i).then(u=>u.isFile()).catch(()=>!1),il(o).then(u=>u.isFile()).catch(()=>!1)]);return c&&d}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 rl(t,{force:!0}).catch(()=>{})}}Da();ne();Re();import{closeSync as bp,fstatSync as vp,openSync as Sp,readFileSync as j1,readSync as K1,readdirSync as $1,statSync as V1}from"node:fs";import{join as ua}from"node:path";var J1=new Set(["debug","info","warn","error"]);function Ip(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 d=Pn(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&&J1.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),d.value&&(m.grep=d.value),m}function Z1(t,e){return t.agentId?ua(je(t.agentId,e).logs,cr("agent",t.date)):ua(e.bridgeLogsDir,cr("bridge",t.date))}function Y1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function X1(t,e){let n;try{n=$1(t)}catch{return[]}let i=[];for(let o of n){let c=Pa(o,e);if(!c)continue;let d=0;try{d=V1(ua(t,o)).size}catch{}i.push({file:ua(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Ap(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 Ep={debug:"90",info:"36",warn:"33",error:"31"},Q1=new Set(["ts","level","module","msg"]);function eI(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function kp(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=eI(n.ts),o=typeof n.level=="string"?n.level:"",c=o.toUpperCase().padEnd(5);e.color&&Ep[o]&&(c=`\x1B[${Ep[o]}m${c}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",h=Object.entries(n).filter(([x])=>!Q1.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function tI(t,e,n){let c=j1(t,"utf8").split(`
117
- `).filter(d=>d.length>0).filter(d=>Ap(d,{level:e.level,grep:e.grep}));for(let d of Y1(c,e.lines))process.stdout.write(`${kp(d,{raw:e.raw,color:n})}
118
- `)}async function Tp(t,e){let n=e.paths??J(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?je(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=X1(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
119
- `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
120
- `);return 0}let o=t.date??On(new Date),c=Z1({agentId:t.agentId,date:o},n);try{tI(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
116
+ `)}catch{}}let e=new da({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 Mo(),o=i??{};gs({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new oa(new Jr),d=null,u=new Bo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(C,z,H,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(C,z,H,ee)}}),f=new Oo({paths:t,config:o,registry:u});d=f;let h,g,_=null,v={},y,E=null,I=null,A=null,T=new kn;function D(C,z){return T.enqueue(()=>R(C,z))}function b(){I||(I=new ua({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:C=>{if(process.env[ds]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),I.start()}async function R(C,z){let H=C,ee=H?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Je=zi(H.env),he=H.handshake_url,pe=H.frontier_url,Tt=xp(H.env,he,pe);if(A=H,!z?.force&&h===ee&&g===Tt){let we=await l1(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,f).catch(Te=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let wt=!!h&&h!==ee,on=g!==void 0&&g!==Tt,Gt=wt||on,an=await Xc({privatecode:ee,...he?{endpoint:he}:{},ppeOverride:Je});if(Gt){q.warn("connect config switched, resetting agents",{pcChanged:wt,envChanged:on,previousPc:h?fa(h):"",nextPc:fa(ee)});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 Jr,"connect switch").catch(()=>{})}_=an.deviceId,gs({deviceId:_,pid:process.pid}),bd({patToken:ee,env:H.env}).catch(we=>q.warn("coze-cli setup error (ignored)",{err:String(we)}));let ei=new as({handshake:an,privatecode:ee,...pe?{urlOverride:pe}:{},ppeOverride:Je,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await c.swap(ei,"connect"),h=ee,g=Tt,v=Je,y=he,H.mock_scenario!==void 0&&(u.setMockScenario(H.mock_scenario),q.info("mock scenario set",{scenario:H.mock_scenario})),E||(E=new Hi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(we=>q.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:J})),E.start(),b(),Gt&&xa(t,f).catch(we=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),cs(ee,t).catch(we=>q.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),q.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>f.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let P={},B=new yo({agents:u.agents,paths:t,publishSkillToMarketplace:async C=>{let z=u.agents.get(C.agentId)?.patToken??h;if(!z)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return op({patToken:z,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:y,ppeOverride:v})},disposeAndMarkDisconnected:async(C,z)=>{let H=u.agents.get(C);if(H){await f.cleanupOpenclawSessionProviders(H).catch(Je=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(Je)})),H.framework==="hermes"&&H.deployType==="cloud"&&await id(C,t).catch(Je=>q.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(Je)}));let ee=!0;try{await H.dispose(`disconnect: ${z}`)}catch(Je){ee=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(Je)}),H.status="error"}ee&&(H.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,z)=>{let H=u.agents.get(C);H&&(await f.cleanupOpenclawSessionProviders(H).catch(ee=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),H.framework==="hermes"&&H.deployType==="cloud"&&await id(C,t).catch(ee=>q.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(ee)})),await H.dispose(`delete: ${z}`).catch(ee=>q.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!P.ref)throw new Error("agent-detail-sync not initialized yet");await P.ref.syncOne(C)},cleanupOpenclawProviders:async(C,z)=>{await f.cleanupOpenclawSessionProviders(C,z)},openclawRepair:async(C,z)=>{await f.openclawRepair(C,z)},hermesReset:async(C,z)=>{let H=await ve(C).catch(()=>null);!H||H.framework!=="hermes"||H.deployType!=="cloud"||await u0({paths:t,agentId:C,model:H.model,modelInfo:H.modelInfo,cozeEnv:z,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>B.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>B.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>B.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>B.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>B.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>B.getFileContent(C.params)),u.registerExtension("_agent/update",C=>B.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>B.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>B.switchModel(C.params)),u.registerExtension("_agent/reset",C=>B.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>B.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>B.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>B.upgradeBridge(C.params));let M=new vs({paths:t,handlers:B,agentManager:f,sendDetail:C=>u.sendRequest("_agent/detail",C)});P.ref=M;let J=async C=>{await Promise.allSettled(C.map(async z=>{try{await B.disconnectAgent({agentId:z.agentId,reason:`auth_failure: code=${z.code} ${z.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:z.agentId,code:z.code,message:z.message})}catch(H){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:z.agentId,err:String(H)})}}))};c.onConnect(({initial:C})=>{q.info("frontier upstream connected, triggering detail sync",{initial:C}),M.syncAll(C?"initial-connect":"reconnect").catch(z=>q.warn("detail sync top-level error (ignored)",{err:String(z)}))});let V=new Fo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ds]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let z=C,H=z?.privatecode,ee=z?.pairing_code;if(!H||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Je=zi(z.env),he=z.handshake_url,pe=z.frontier_url,Tt=xp(z.env,he,pe),wt=!!h&&h!==H,on=g!==void 0&&g!==Tt,Gt=wt||on,an=await Xc({privatecode:H,...he?{endpoint:he}:{},ppeOverride:Je});if(Gt){q.warn("pair config switched, resetting agents",{pcChanged:wt,envChanged:on,previousPc:h?fa(h):"",nextPc:fa(H),previousEnvKey:g??"",nextEnvKey:Tt});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.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 Jr,"pair switch").catch(()=>{})}_=an.deviceId,gs({deviceId:_,pid:process.pid}),bd({patToken:H,env:z.env}).catch(Te=>q.warn("coze-cli setup error (ignored)",{err:String(Te)}));let ei=new as({handshake:an,privatecode:H,...pe?{urlOverride:pe}:{},ppeOverride:Je,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(ei,"pair");try{let Te=new Zn;o.frameworksCache=await Te.detectAll(),await Zi(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let we=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:H,frameworks:we,_meta:{cozeDeviceId:_}});q.info("_agent/pair ok",{pairResult:Te}),h=H,g=Tt,v=Je,y=he,z.mock_scenario!==void 0&&(u.setMockScenario(z.mock_scenario),q.info("mock scenario set",{scenario:z.mock_scenario})),cs(H,t).catch(Ne=>q.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),E||(E=new Hi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(Ne=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:J})),E.start(),b(),Gt&&xa(t,f).catch(Ne=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let rr;return z.agent_id&&(rr=await f1(z.agent_id,t,f,Ne=>u.sendRequest("_agent/detail",Ne),H).catch(Ne=>(q.error("--agent-id ensureAgent failed",{agentId:z.agent_id,err:String(Ne)}),{ok:!1,agentId:z.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(Te){return q.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:C=>D(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let z=C;return{ok:!0,result:await f.createAgent(z)}}},{method:"POST",path:"/agent/send",handler:async C=>{let z=C;if(!z?.agentId||!z?.sessionId||!z?.kind||!z?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!h)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let H=z;return await(H.groupFile?bx:yx)(H,{core:u,patToken:h,handshakeBase:y,ppeOverride:v})}catch(H){if(H instanceof k)return{ok:!1,code:H.code,message:H.message};throw H}}},{method:"POST",path:"/reload",handler:async C=>{let z=C?.agent_id,H=await u.reloadAgents(z);return q.info("IPC /reload: recycled agent subprocesses",{agentId:z??"(all)",recycled:H}),{ok:!0,recycled:H}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await V.start();try{await cp(t.libEntry,t)}catch(C){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),x1({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Zn().detectAll(),await Zi(o),o.frameworksCache)}).catch(C=>q.warn("startup warmup error (ignored)",{err:String(C)})),Ul().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(ln(),Fl));for(let z of["claude-code","codex"]){let H=await C(z);H&&q.info("acp wrapper version",{framework:z,version:H})}}).catch(C=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let se=null,oe={port:re,token:X,core:u,ipc:V,shutdown(C){return se||(q.info("daemon shutdown",{reason:C}),se=(async()=>{E?.stop(),I?.stop(),await u.stop(C),await V.stop(),await e.release()})(),se)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{oe.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>z0()),process.on("unhandledRejection",C=>{q.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{q.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
117
+ `)}catch{}process.exit(1)}),q.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),p1({cliSpawned:process.env[ds]==="1",readPatToken:()=>aa(t),connect:D}).catch(C=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),oe}async function l1(t){return ys(t).length>0}function fa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function xp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function u1(t,e){let r=ys(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(Wt(),Es));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 f1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Wt(),Es)),d=await c(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=pp(d),_={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...g?{_meta:g}:{}};return await r.createAgent(_),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}q.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(f);let h=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:h?"cloud agent acknowledged":"created from cloud detail"}}async function x1(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 h1(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(()=>(Wt(),Es));q.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let f;try{f=await o(u,t)}catch(h){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(h)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let h=pp(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...h?{_meta:h}:{}},{revive:!0}),c+=1}catch(h){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(h)}),d+=1}}return q.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function h1(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 k0(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 p1(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 pp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}la();Re();import{readFile as mp}from"node:fs/promises";var sn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let r=await ha(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:g1(i)}}}async request(e){let r=await ha(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}),f=await u.text();return{status:u.status,body:m1(f)}}finally{clearTimeout(d)}}};async function ha(t){try{let[e,r]=await Promise.all([mp(t.portFile,"utf8"),mp(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 m1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function g1(t){return t instanceof Error?t.message:String(t)}Xt();te();ar();import{spawn as w1}from"node:child_process";import{userInfo as wp}from"node:os";var Xd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",_1=new Set(["bash","zsh","sh","dash","ksh"]),gp=Ze("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),y1=2e3;function b1(t,e=Xd){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(`
118
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function E1(){let t=(process.env.SHELL??"").trim()||(wp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return _1.has(e)?t:null}function v1(t){return new Promise(e=>{let r=`printf '%s' '${Xd}'; env; printf '%s' '${Xd}'`,i;try{i=w1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??wp().homedir}})}catch{e(null);return}let o="",c=!1,d=g=>{try{i.pid&&process.kill(-i.pid,g)}catch{}},u=g=>{c||(c=!0,clearTimeout(f),clearTimeout(h),e(g))};i.stdout?.on("data",g=>{o+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),gp),h=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},gp+y1)})}async function Qd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=E1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??v1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=b1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Re();function Rn(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}}ln();import{chmod as S1,copyFile as _p,mkdir as bp,readFile as us,rename as yp,rm as nl,stat as Ep,writeFile as I1}from"node:fs/promises";import{homedir as rP}from"node:os";import{dirname as A1,join as Le,resolve as rl,sep as ls}from"node:path";import{fileURLToPath as k1}from"node:url";Xt();te();Re();function Zr(t,e,r,i){rt(t.bridgeLogsDir,e,"dist-install",r,i)}function vp(){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 T1(){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 C1(t){let e=k1(t),r=A1(e),i=`${ls}src${ls}`;if(r.includes(i)||r.endsWith(`${ls}src${ls}cli`))return null;let o=rl(r,"index.js"),c=rl(r,"..","package.json");return{dist:o,pkgJson:c}}async function il(t={}){let e=t.paths??Z(),r=C1(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 us(o,"utf8"));c=E.version??"unknown",d=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=ws.map(E=>({name:E,spec:d[E]??"latest"})),f=u.map(({name:E,spec:I})=>`${E}@${I}`),h=await Mo(e.configFile)??{},g=h.libVersion,_=await us(e.libEntry).then(()=>!0).catch(()=>!1),v=g===c,y=await Sp(e,u);if(v&&_&&y)return{kind:"already-current",libVersion:c};if(!v||!_){await bp(e.libDir,{recursive:!0}),await _p(i,e.libEntry),await _p(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=rl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
119
+ `;await us(E,"utf8").catch(()=>null)!==I&&await I1(E,I)}return y||(t.installWrappers?await t.installWrappers(e,f):await P1(e,f,u)),h.libVersion=c,await Zi(h,e.configFile),Zr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:c}),v&&_?{kind:"already-current",libVersion:c}:g?{kind:"version-changed",fromVersion:g,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Sp(t,e){for(let r of e){let i=Le(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await us(i,"utf8"))}catch(d){return Zr(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 Zr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!R1(c,r.spec))return Zr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await Ip(Le(t.libDir,"node_modules"))}function R1(t,e){let r=el(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=el(i.slice(1));if(!c)return!0;if(tl(r,c)<0)return!1;let d=D1(c);return tl(r,d)<0}let o=el(i);return o?tl(r,o)===0:!0}function D1(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function el(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function tl(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 P1(t,e,r){await N1(t.installLock,async()=>{if(await Sp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ls}.staging-${process.pid}-${i}`,c=Le(o,"node_modules"),d=Le(t.libDir,"node_modules");try{await bp(o,{recursive:!0}),await O1(e,o),await L1(c);let u=`${d}.trash-${i}`;await yp(d,u).catch(()=>{}),await yp(c,d),await nl(u,{recursive:!0,force:!0}).catch(()=>{}),Zr(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await nl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function O1(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",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),c.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function L1(t){for(let e of ws){let r=Le(t,...e.split("/")),i=JSON.parse(await us(Le(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=Le(t,".bin",o),d=await Ep(c);process.platform!=="win32"&&!(d.mode&73)&&await S1(c,d.mode|73).catch(()=>{})}if(!await Ip(t)){let e=vp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Ip(t){let e=vp(),r=T1();if(!e||!r)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,r)];return(await Promise.all(c.map(u=>Ep(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function N1(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 nl(t,{force:!0}).catch(()=>{})}}Ma();te();Re();import{closeSync as kp,fstatSync as Tp,openSync as Cp,readFileSync as M1,readSync as B1,readdirSync as F1,statSync as z1}from"node:fs";import{join as pa}from"node:path";var U1=new Set(["debug","info","warn","error"]);function Rp(t){let e=t,r=Rn(e,"--agent-id");e=r.rest;let i=Rn(e,"--date");e=i.rest;let o=Rn(e,"-n","--lines");e=o.rest;let c=Rn(e,"--level");e=c.rest;let d=Rn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,h=c.value&&U1.has(c.value)?c.value:void 0,g={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(g.agentId=r.value),i.value&&(g.date=i.value),h&&(g.level=h),d.value&&(g.grep=d.value),g}function G1(t,e){return t.agentId?pa(ze(t.agentId,e).logs,cr("agent",t.date)):pa(e.bridgeLogsDir,cr("bridge",t.date))}function H1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function q1(t,e){let r;try{r=F1(t)}catch{return[]}let i=[];for(let o of r){let c=Na(o,e);if(!c)continue;let d=0;try{d=z1(pa(t,o)).size}catch{}i.push({file:pa(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Dp(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"&&!Ol(r,e.level))return!1}return!0}var Ap={debug:"90",info:"36",warn:"33",error:"31"},j1=new Set(["ts","level","module","msg"]);function W1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Pp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=W1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Ap[o]&&(c=`\x1B[${Ap[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",f=Object.entries(r).filter(([h])=>!j1.has(h)).map(([h,g])=>` ${h}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${d} ${u}${f}`}function K1(t,e,r){let c=M1(t,"utf8").split(`
120
+ `).filter(d=>d.length>0).filter(d=>Dp(d,{level:e.level,grep:e.grep}));for(let d of H1(c,e.lines))process.stdout.write(`${Pp(d,{raw:e.raw,color:r})}
121
+ `)}async function Op(t,e){let r=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?ze(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=q1(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
122
+ `),1;for(let h of f)process.stdout.write(`${h.date} ${(h.size/1024).toFixed(1)}KB ${h.file}
123
+ `);return 0}let o=t.date??Pn(new Date),c=G1({agentId:t.agentId,date:o},r);try{K1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
121
124
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
122
- (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
123
- `),1}return t.follow&&await iI(c,t,i),0}var nI=500;function rI(t){try{let e=Sp(t,"r");try{return vp(e).size}finally{bp(e)}}catch{return 0}}async function iI(t,e,n){let i=rI(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=Sp(t,"r");try{let x=vp(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),g=K1(h,m,0,m.length,i);u=m.subarray(0,g).toString("utf8"),i+=g}}finally{bp(h)}}catch{}if(u){let h=(o+u).split(`
124
- `);o=h.pop()??"";for(let x of h)x.length>0&&Ap(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${kp(x,{raw:e.raw,color:n})}
125
- `)}await new Promise(h=>setTimeout(h,nI))}}finally{process.off("SIGINT",d)}}import{basename as sI,resolve as oI}from"node:path";Re();var aI=9e4,cI={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 dI(t){return cI[t]??1}async function Rp(t,e={}){let n=e.paths??J();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
125
+ (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
126
+ `),1}return t.follow&&await J1(c,t,i),0}var $1=500;function V1(t){try{let e=Cp(t,"r");try{return Tp(e).size}finally{kp(e)}}catch{return 0}}async function J1(t,e,r){let i=V1(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let f=Cp(t,"r");try{let h=Tp(f).size;if(h>i){let g=Buffer.allocUnsafe(h-i),_=B1(f,g,0,g.length,i);u=g.subarray(0,_).toString("utf8"),i+=_}}finally{kp(f)}}catch{}if(u){let f=(o+u).split(`
127
+ `);o=f.pop()??"";for(let h of f)h.length>0&&Dp(h,{level:e.level,grep:e.grep})&&process.stdout.write(`${Pp(h,{raw:e.raw,color:r})}
128
+ `)}await new Promise(f=>setTimeout(f,$1))}}finally{process.off("SIGINT",d)}}import{basename as Z1,resolve as Y1}from"node:path";Re();var X1=9e4,Q1={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 e2(t){return Q1[t]??1}async function Lp(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>
126
129
  `),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.
127
- `),3;let i=await la(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.
128
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:oI(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 lI(i,"/agent/send",o,aI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
130
+ `),3;let i=await ha(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.
131
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:Y1(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 t2(i,"/agent/send",o,X1)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
129
132
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
130
- `),dI(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
131
- `);else{let d=t.name??sI(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})
132
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${uI(c.bytes)})
133
- `)}return 0}async function lI(t,e,n,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(n),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 uI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var zp=G("cli");function We(t,e){let{value:n,rest:i}=Pn(t,e);return{value:n,rest:i}}function ma(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
134
- `)}function NI(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:P}=We(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return MI(e.slice(1));if(e[0]==="log")return{mode:"log",...Ip(e.slice(1))};if(e[0]==="connect")return BI(e.slice(1));if(e.includes("--status"))return ma("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ma("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ma("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ma("--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}=We(n,"--pat-token");n=o;let{value:c,rest:d}=We(n,"--pair-code");n=d;let{value:u,rest:h}=We(n,"--env");n=h;let{value:x,rest:m}=We(n,"--handshake-url");n=m;let{value:g,rest:S}=We(n,"--frontier-url");n=S;let{value:_,rest:v}=We(n,"--mock-scenario");n=v;let{value:I}=We(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),g&&(T.frontierUrl=g),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function MI(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}=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:g}=We(i,"--session-id");i=g;let{value:S,rest:_}=We(i,"--mime");i=_;let v=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),d&&(A.name=d),h&&(A.agentId=h),m&&(A.sessionId=m),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function BI(t){let e=t,{value:n,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:g}=We(e,"--mock-scenario");e=g;let S=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),d&&(_.handshakeUrl=d),h&&(_.frontierUrl=h),m&&(_.mockScenario=m),S&&(_.skipRebuildEnv=!0),_}var FI=`
133
+ `),e2(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
134
+ `);else{let d=t.name??Z1(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})
135
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${n2(c.bytes)})
136
+ `)}return 0}async function t2(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(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function n2(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var jp=G("cli");function Ke(t,e){let{value:r,rest:i}=Rn(t,e);return{value:r,rest:i}}function ba(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
137
+ `)}function A2(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:D}=Ke(e.slice(1),"--agent-id");return D?{mode:"reload",agentId:D}:{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 k2(e.slice(1));if(e[0]==="log")return{mode:"log",...Rp(e.slice(1))};if(e[0]==="connect")return T2(e.slice(1));if(e.includes("--status"))return ba("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ba("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ba("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ba("--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}=Ke(r,"--pat-token");r=o;let{value:c,rest:d}=Ke(r,"--pair-code");r=d;let{value:u,rest:f}=Ke(r,"--env");r=f;let{value:h,rest:g}=Ke(r,"--handshake-url");r=g;let{value:_,rest:v}=Ke(r,"--frontier-url");r=v;let{value:y,rest:E}=Ke(r,"--mock-scenario");r=E;let{value:I}=Ke(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:c};return u&&(T.env=u),h&&(T.handshakeUrl=h),_&&(T.frontierUrl=_),y&&(T.mockScenario=y),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function k2(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}=Ke(i,"--caption");i=c;let{value:d,rest:u}=Ke(i,"--name");i=u;let{value:f,rest:h}=Ke(i,"--agent-id");i=h;let{value:g,rest:_}=Ke(i,"--session-id");i=_;let{value:v,rest:y}=Ke(i,"--mime");i=y;let E=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),d&&(A.name=d),f&&(A.agentId=f),g&&(A.sessionId=g),E&&(A.groupFile=!0),v&&(A.mimeType=v),A}function T2(t){let e=t,{value:r,rest:i}=Ke(e,"--pat-token");e=i;let{value:o,rest:c}=Ke(e,"--env");e=c;let{value:d,rest:u}=Ke(e,"--handshake-url");e=u;let{value:f,rest:h}=Ke(e,"--frontier-url");e=h;let{value:g,rest:_}=Ke(e,"--mock-scenario");e=_;let v=e.includes("--skip-rebuild-env"),y={mode:"connect"};return r&&(y.privatecode=r),o&&(y.env=o),d&&(y.handshakeUrl=d),f&&(y.frontierUrl=f),g&&(y.mockScenario=g),v&&(y.skipRebuildEnv=!0),y}var C2=`
135
138
  coze-bridge - local bridge daemon for cloud Agent Service
136
139
 
137
140
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -212,57 +215,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
212
215
 
213
216
  Internal:
214
217
  <node> <entry> --daemon daemon mode (OS supervisor only)
215
- `.trimStart();async function Up(t=process.argv,e={}){let n=NI(t);switch(n.mode){case"help":return process.stdout.write(FI),0;case"version":return process.stdout.write(`${Dt}
216
- `),0;case"daemon":{try{await lp()}catch(i){return zp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return zI(e);case"stop":return Hp(e);case"reload":return HI(n.agentId,e);case"log":return Tp(n,e);case"update":return UI(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),$I(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),VI(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Rp({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 Gp(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 zI(t){let e=t.paths??J(),n=new tn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
217
- `),1;if(i.kind==="stale")return await Gp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
218
- `),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
218
+ `.trimStart();async function Wp(t=process.argv,e={}){let r=A2(t);switch(r.mode){case"help":return process.stdout.write(C2),0;case"version":return process.stdout.write(`${Nt}
219
+ `),0;case"daemon":{try{await hp()}catch(i){return jp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return R2(e);case"stop":return $p(e);case"reload":return O2(r.agentId,e);case"log":return Op(r,e);case"update":return D2(e);case"purge":return N2(e);case"service-install":return M2(e);case"service-uninstall":return B2(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),F2(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),z2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Lp({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 Kp(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 R2(t){let e=t.paths??Z(),r=new sn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
220
+ `),1;if(i.kind==="stale")return await Kp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
221
+ `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
219
222
  ${JSON.stringify(o.body,null,2)}
220
- `),0}async function Hp(t){let e=t.paths??J(),n=new tn(e),i=t.daemonSweep??(async()=>{let h=M0();return await B0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await ls(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
221
- `)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
223
+ `),0}async function $p(t){let e=t.paths??Z(),r=new sn(e),i=t.daemonSweep??(async()=>{let f=U0();return await G0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await xs(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
224
+ `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
222
225
  `:`coze-bridge: not running
223
- `),0;if(u.kind==="stale")return await Gp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
224
- `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
225
- `),0}catch(h){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
226
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
227
- `),1)}}async function UI(t){return await Hp(t),(t.spawnNpx??GI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function GI(t){return new Promise(e=>{let n=et("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)}
228
- `),e(1)})})}async function HI(t,e){let n=new tn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
229
- `),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)
226
+ `),0;if(u.kind==="stale")return await Kp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
227
+ `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
228
+ `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
229
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
230
+ `),1)}}async function D2(t){return await $p(t),(t.spawnNpx??P2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function P2(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)}
231
+ `),e(1)})})}async function O2(t,e){let r=new sn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
232
+ `),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)
230
233
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
231
234
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
232
235
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
233
- `),1}}async function ls(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:n}=await Promise.resolve().then(()=>(Mp(),Np)),i=e(),o=n();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Wp(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??JI,c=t.paths??J();if(n.kind==="connected"){if(!WI(n.body))return n;ct(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=>ct(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await Fp(c.pidFile,o)}let d=t.spawnDaemon??cp,u=await ls(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Bp(e,i,o);if(h.kind==="connected")return h;ct(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){ct(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}ct(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 Fp(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)}
236
+ `),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(()=>(Gp(),Up)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Vp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??U2,c=t.paths??Z();if(r.kind==="connected"){if(!L2(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(f=>rt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await qp(c.pidFile,o)}let d=t.spawnDaemon??fp,u=await xs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Hp(e,i,o);if(f.kind==="connected")return f;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(f){rt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}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 qp(c.pidFile,o)}else u&&await u.install({activate:!1}).catch(f=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(f)}
234
237
  `));return process.stdout.write(`coze-bridge: starting daemon...
235
- `),await d({paths:t.paths}),Bp(e,i,o)}function WI(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 tn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
238
+ `),await d({paths:t.paths}),Hp(e,i,o)}function L2(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 N2(t){let e=new sn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
236
239
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
237
- `)}await new Promise(d=>setTimeout(d,500))}let i=await ls(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
240
+ `)}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
238
241
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
239
- `)}let o=t.paths??J(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
242
+ `)}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}
240
243
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
241
244
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
242
- `),0}async function jI(t){let e=await ls(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
245
+ `),0}async function M2(t){let e=await xs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
243
246
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
244
- `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
245
- `),1}}async function KI(t){let e=await ls(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
246
- `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
247
- `),1}}async function qp(t,e,n){if(e)return ct(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(ct(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ct(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)
248
- `),ct(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function $I(t,e,n,i={},o,c){let d=new tn(n.paths),u=n.paths??J(),h=await qp(u,c,n.reconstructEnv??el);if(await dd(u,h).catch(g=>ct(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!n.skipDistInstall){let g=await ol({paths:n.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
249
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
250
- `)}let x=await Wp(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
251
- `),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 g=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(g.status===200&&g.body?.ok){let S=g.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
247
+ `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
248
+ `),1}}async function B2(t){let e=await xs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
249
+ `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
250
+ `),1}}async function Jp(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)
251
+ `),rt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function F2(t,e,r,i={},o,c){let d=new sn(r.paths),u=r.paths??Z(),f=await Jp(u,c,r.reconstructEnv??Qd);if(await Yc(u,f).catch(_=>rt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!r.skipDistInstall){let _=await il({paths:r.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
252
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
253
+ `)}let h=await Vp(r,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
254
+ `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),o&&(g.agent_id=o);try{let _=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let v=_.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
252
255
  `),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"
253
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(g.body)}
254
- `),1}catch(g){return process.stderr.write(`coze-bridge: pair failed: ${String(g)}
255
- `),1}}async function VI(t,e,n={},i){let o=e.paths??J(),c=t??await ra(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 tn(e.paths),u=await qp(o,i,e.reconstructEnv??el);if(await dd(o,u).catch(m=>ct(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await ol({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
256
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
257
- `)}let h=await Wp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
258
- `),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 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"})
259
- `),t!==void 0&&await ss(c,o).catch(g=>zp.warn("writePatToken after connect failed (ignored)",{err:String(g)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
260
- `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
261
- `),1}}async function Bp(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 Fp(t,e,n=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<n;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Wi(u))return;await e(i)}}function JI(t){return new Promise(e=>setTimeout(e,t))}ne();function ZI(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 jp(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){let i=ZI(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
262
- `),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
256
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(_.body)}
257
+ `),1}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
258
+ `),1}}async function z2(t,e,r={},i){let o=e.paths??Z(),c=t??await aa(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 sn(e.paths),u=await Jp(o,i,e.reconstructEnv??Qd);if(await Yc(o,u).catch(g=>rt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await il({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
259
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
260
+ `)}let f=await Vp(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
261
+ `),1;let h={privatecode:c};r.env&&(h.env=r.env),r.handshakeUrl&&(h.handshake_url=r.handshakeUrl),r.frontierUrl&&(h.frontier_url=r.frontierUrl),r.mockScenario&&(h.mock_scenario=r.mockScenario);try{let g=await d.request({method:"POST",path:"/connect",body:h,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
262
+ `),t!==void 0&&await cs(c,o).catch(_=>jp.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
263
+ `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
264
+ `),1}}async function Hp(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 qp(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||!Ki(u))return;await e(i)}}function U2(t){return new Promise(e=>setTimeout(e,t))}te();function G2(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function Zp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=G2(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
265
+ `),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
263
266
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
264
267
  npx -y coze-bridge@latest stop
265
268
  npx -y coze-bridge@latest connect
266
269
 
267
- `)}jp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Ll("warn");Up(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
270
+ `)}Zp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Dl("warn");Wp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
268
271
  `),process.exit(1)});