coze-bridge 0.2.5 → 0.2.6

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 +80 -74
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,25 +5,25 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var Cg=Object.create;var Sa=Object.defineProperty;var Rg=Object.getOwnPropertyDescriptor;var Pg=Object.getOwnPropertyNames;var Dg=Object.getPrototypeOf,Og=Object.prototype.hasOwnProperty;var he=(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 ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ia=(t,e)=>{for(var r in e)Sa(t,r,{get:e[r],enumerable:!0})},Lg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pg(e))!Og.call(t,o)&&o!==r&&Sa(t,o,{get:()=>e[o],enumerable:!(i=Rg(e,o))||i.enumerable});return t};var Gt=(t,e,r)=>(r=t!=null?Cg(Dg(t)):{},Lg(e||!t||!t.__esModule?Sa(r,"default",{value:t,enumerable:!0}):r,t));function Je(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var sr=nt(()=>{"use strict"});import{createWriteStream as Ng,mkdirSync as Mg,readdirSync as Bg,unlinkSync as Fg}from"node:fs";import{join as El}from"node:path";function Dn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function or(t,e){return`${t}-${e}.log`}function Aa(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function zg(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 cs(t,e,r,i){let o;try{o=Bg(t)}catch{return}for(let c of o){let d=Aa(c,e);if(d&&zg(d,r,i))try{Fg(El(t,c))}catch{}}}var ei,ka=nt(()=>{"use strict";ei=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Dn(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{Mg(this.dir,{recursive:!0});let r=Ng(El(this.dir,or(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var Cg=Object.create;var Sa=Object.defineProperty;var Rg=Object.getOwnPropertyDescriptor;var Pg=Object.getOwnPropertyNames;var Dg=Object.getPrototypeOf,Og=Object.prototype.hasOwnProperty;var le=(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 Qe=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ia=(t,e)=>{for(var r in e)Sa(t,r,{get:e[r],enumerable:!0})},Lg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pg(e))!Og.call(t,o)&&o!==r&&Sa(t,o,{get:()=>e[o],enumerable:!(i=Rg(e,o))||i.enumerable});return t};var Gt=(t,e,r)=>(r=t!=null?Cg(Dg(t)):{},Lg(e||!t||!t.__esModule?Sa(r,"default",{value:t,enumerable:!0}):r,t));function $e(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var sr=Qe(()=>{"use strict"});import{createWriteStream as Ng,mkdirSync as Mg,readdirSync as Bg,unlinkSync as Fg}from"node:fs";import{join as yl}from"node:path";function Dn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function or(t,e){return`${t}-${e}.log`}function Aa(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function zg(t,e,r){let i=a=>{let[d,u,h]=a.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>r}function cs(t,e,r,i){let o;try{o=Bg(t)}catch{return}for(let a of o){let d=Aa(a,e);if(d&&zg(d,r,i))try{Fg(yl(t,a))}catch{}}}var ei,Ta=Qe(()=>{"use strict";ei=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Dn(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{Mg(this.dir,{recursive:!0});let r=Ng(yl(this.dir,or(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
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&&cs(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 Ug,mkdirSync as qg}from"node:fs";import{join as Gg}from"node:path";function vl(t){let e=t.retentionDays??Wg,r=t.clock??(()=>Dn(new Date));ls={bridgeSink:new ei(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ei(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();cs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])cs(t.agentLogsDir(o),"agent",i,e)}function Kg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Sl(t){Ta=t}function Il(t){return ar[Ta]<=ar[t]}function Al(t,e){let r=ar[t];return r===void 0?!0:r>=ar[e]}function us(t){bl={...t}}function kl(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`${Dn(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:kl(new Date),level:e,module:r,msg:i,...o})}
11
- `;qg(t,{recursive:!0}),Ug(Gg(t,or("bridge",Dn(new Date))),c)}catch{}}function $g(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ds(t,e,r,i,o){if(ar[t]<ar[Ta])return;let c=`${JSON.stringify({ts:kl(new Date),level:t,module:e,msg:r,...bl,...i})}
12
- `;if(ls){let d=$g(o,i),u=d?Kg(ls,d):ls.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?jg.write(c):Hg.write(c)}function W(t,e){return{debug:(r,i)=>ds("debug",t,r,i,e),info:(r,i)=>ds("info",t,r,i,e),warn:(r,i)=>ds("warn",t,r,i,e),error:(r,i)=>ds("error",t,r,i,e),child:r=>W(`${t}.${r}`,e),forAgent:r=>W(t,r)}}var ar,Ta,Hg,jg,bl,Wg,ls,ne=nt(()=>{"use strict";sr();ka();ar={debug:10,info:20,warn:30,error:40},Ta=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Hg=process.stdout,jg=process.stderr,bl={},Wg=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ls=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 Pl={};Ia(Pl,{ACP_WRAPPER_NPM_PACKAGES:()=>fs,_resetAcpInstallerForTests:()=>Qg,_setBinaryPathCacheForTests:()=>em,buildAcpSpawn:()=>ni,ensureAcpInstalled:()=>cr,getAcpBinaryPath:()=>hs,pickWhichLine:()=>Pa,probeAcpVersion:()=>Xg,resolveAcpCommand:()=>Rl});import{readFileSync as Tl}from"node:fs";import{createRequire as Vg}from"node:module";import{dirname as Jg,resolve as Zg}from"node:path";function Pa(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 Yg(t){let e=Cl.resolve(`${t.npmPackage}/package.json`),r=Jg(e),i=JSON.parse(Tl(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 Zg(r,o)}async function cr(t,e){let r=Ra[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ti.get(t);if(i)return i;try{let o=Yg(r);return ti.set(t,o),Ca.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ca.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 Xg(t){let e=Ra[t];if(e)try{let r=Cl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Tl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Ca.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function hs(t){return ti.get(t)}function Rl(t,e){if(e)return e;let r=hs(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 ni(t,e,r){if(e)return{command:e,args:[...r]};let i=Rl(t);return{command:process.execPath,args:[i,...r]}}function Qg(){ti.clear()}function em(t,e){ti.set(t,e)}var Ca,Ra,fs,Cl,ti,an=nt(()=>{"use strict";$e();ne();Ca=W("agents.acp-installer"),Ra={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},fs=Object.values(Ra).filter(t=>t!==void 0).map(t=>t.npmPackage),Cl=Vg(import.meta.url),ti=new Map});import{chmod as nm,mkdir as rm,readFile as im,rename as sm,rm as om,writeFile as am}from"node:fs/promises";import{dirname as cm}from"node:path";async function dr(t){try{let e=await im(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cn(t,e,r){await rm(cm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await am(i,e,{encoding:"utf8",mode:r?.mode}),await sm(i,t),r?.mode!==void 0&&await nm(t,r.mode)}catch(o){throw await om(i,{force:!0}).catch(()=>{}),o}}async function lr(t,e,r){await cn(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var dn=nt(()=>{"use strict"});import{promises as Ll,readdirSync as dm}from"node:fs";import{homedir as lm}from"node:os";import{sep as um,join as Ce,resolve as Nl}from"node:path";function ee(t){let e=t??lm(),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=ee()){let r=Ce(e.agentsRoot,t);return{root:r,config:Ce(r,"config.json"),workspace:Ce(r,"workspace"),logs:Ce(r,"logs")}}function xs(t=ee()){try{return dm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ri(t,e){let r=await Ll.realpath(Nl(t)).catch(()=>null);if(!r)return!1;let i=await Ll.realpath(Nl(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+um)}var Me=nt(()=>{"use strict"});var gs={};Ia(gs,{AGENT_CONFIG_FILE_MODE:()=>ps,enforceAgentConfigMode:()=>xm,loadAgentConfig:()=>Re,persistAgentSessions:()=>ii,persistAgentSkills:()=>si,saveAgentConfig:()=>Ue});import{chmod as fm,stat as hm}from"node:fs/promises";function Re(t,e){return dr(Ze(t,e).config)}function Ue(t,e){return lr(Ze(t.agentId,e).config,t,{mode:ps})}async function xm(t,e){if(process.platform==="win32")return;let r=Ze(t,e).config;try{let i=await hm(r);if(!i.isFile())return;let o=i.mode&511;o!==ps&&(await fm(r,ps),Ml.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Ml.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ii(t,e,r){let i=await Re(t,r);i&&(i.sessions=Object.fromEntries(e),await Ue(i,r))}async function si(t,e,r){let i=await Re(t,r);i&&(i.skills=e,await Ue(i,r))}var Ml,ps,ln=nt(()=>{"use strict";dn();ne();Me();Ml=W("agent-config"),ps=384});var La=ce((oI,zl)=>{zl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var ws=ce(ql=>{var Ul={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 ym(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(Ul))ql[t]=ym(Ul[t])});var Kl=ce((cI,Wl)=>{var Em=he("fs"),Be=he("path"),Gl=La(),bm=ws(),vm=typeof process=="object"&&process.platform==="win32",Hl=t=>typeof t=="object"&&t!==null,jl=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 Ie(t){this.sep=Be.sep,this.fs=Em,Hl(t)&&Hl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Wl.exports=Ie;Ie.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 bm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ie.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=Be.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};Ie.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 x=Be.dirname(t);c.fs.exists(x,function(g){g||c.makeDir(x),c.fs.open(t,"w",438,function(m,S){m?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,b){c.fs.write(b,e,0,e.length,0,function(){c.fs.close(b,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)})})})})})};Ie.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=Be.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&d.push(Be.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(r(f,o,c)))}),d}return r(t,void 0,!0)};Ie.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=Be.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Be.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(g,m){if(g)return e(g);i=i.concat(m),--d||e(null,i)}):--d||e(null,i))})})})};Ie.prototype.getAttributes=function(){};Ie.prototype.setAttributes=function(){};Ie.crc32update=function(t,e){return jl[(t^e)&255]^t>>>8};Ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ie.crc32update(r,t[i++]);return~r>>>0};Ie.methodToString=function(t){switch(t){case Gl.STORED:return"STORED ("+t+")";case Gl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ie.canonical=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.join(".",e)};Ie.zipnamefix=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.posix.join(".",e)};Ie.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]};Ie.sanitize=function(t,e){t=Be.resolve(Be.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Be.normalize(Be.join(t,r.slice(i,o).join(Be.sep)));if(c.indexOf(t)===0)return c}return Be.normalize(Be.join(t,Be.basename(e)))};Ie.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ie.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ie.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ie.fromDate2DOS=function(t){let e=0,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};Ie.isWin=vm;Ie.crcTable=jl});var Vl=ce((dI,$l)=>{var Sm=he("path");$l.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=Sm.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 Zl=ce((lI,Jl)=>{Jl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var hr=ce((uI,fr)=>{fr.exports=Kl();fr.exports.Constants=La();fr.exports.Errors=ws();fr.exports.FileAttr=Vl();fr.exports.decoder=Zl()});var Xl=ce((fI,Yl)=>{var un=hr(),U=un.Constants;Yl.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,f=0,x=0,g=0,m=0,S=0,y=0,b=0;t|=un.isWin?2560:768,r|=U.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,D=E=>Math.max(0,E)&255;return o=un.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return r},set flags(E){r=E},get flags_efs(){return(r&U.FLG_EFS)>0},set flags_efs(E){E?r|=U.FLG_EFS:r&=~U.FLG_EFS},get flags_desc(){return(r&U.FLG_DESC)>0},set flags_desc(E){E?r|=U.FLG_DESC:r&=~U.FLG_DESC},get method(){return i},set method(E){switch(E){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=E},get time(){return un.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=un.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return D(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 f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return g},set commentLength(E){g=E},get diskNumStart(){return m},set diskNumStart(E){m=A(E)},get inAttr(){return S},set inAttr(E){S=A(E)},get attr(){return y},set attr(E){y=A(E)},get fileAttr(){return(y||0)>>16&4095},get offset(){return b},set offset(E){b=A(E)},get encrypted(){return(r&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+x+g},get realDataOffset(){return b+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var R=E.slice(b,b+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 O=b+U.LOCHDR+I.fnameLen,F=O+I.extraLen;return E.slice(O,F)},loadFromBinary:function(E){if(E.length!==U.CENHDR||E.readUInt32LE(0)!==U.CENSIG)throw un.Errors.INVALID_CEN();t=E.readUInt16LE(U.CENVEM),e=E.readUInt16LE(U.CENVER),r=E.readUInt16LE(U.CENFLG),i=E.readUInt16LE(U.CENHOW),o=E.readUInt32LE(U.CENTIM),c=E.readUInt32LE(U.CENCRC),d=E.readUInt32LE(U.CENSIZ),u=E.readUInt32LE(U.CENLEN),f=E.readUInt16LE(U.CENNAM),x=E.readUInt16LE(U.CENEXT),g=E.readUInt16LE(U.CENCOM),m=E.readUInt16LE(U.CENDSK),S=E.readUInt16LE(U.CENATT),y=E.readUInt32LE(U.CENATX),b=E.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(U.LOCHDR);return E.writeUInt32LE(U.LOCSIG,0),E.writeUInt16LE(e,U.LOCVER),E.writeUInt16LE(r,U.LOCFLG),E.writeUInt16LE(i,U.LOCHOW),E.writeUInt32LE(o,U.LOCTIM),E.writeUInt32LE(c,U.LOCCRC),E.writeUInt32LE(d,U.LOCSIZ),E.writeUInt32LE(u,U.LOCLEN),E.writeUInt16LE(f,U.LOCNAM),E.writeUInt16LE(I.extraLen,U.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(U.CENHDR+f+x+g);return E.writeUInt32LE(U.CENSIG,0),E.writeUInt16LE(t,U.CENVEM),E.writeUInt16LE(e,U.CENVER),E.writeUInt16LE(r,U.CENFLG),E.writeUInt16LE(i,U.CENHOW),E.writeUInt32LE(o,U.CENTIM),E.writeUInt32LE(c,U.CENCRC),E.writeUInt32LE(d,U.CENSIZ),E.writeUInt32LE(u,U.CENLEN),E.writeUInt16LE(f,U.CENNAM),E.writeUInt16LE(x,U.CENEXT),E.writeUInt16LE(g,U.CENCOM),E.writeUInt16LE(m,U.CENDSK),E.writeUInt16LE(S,U.CENATT),E.writeUInt32LE(y,U.CENATX),E.writeUInt32LE(b,U.CENOFF),E},toJSON:function(){let E=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:E(d),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(g),diskNumStart:m,inAttr:S,attr:y,offset:b,centralHeaderSize:E(U.CENHDR+f+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var eu=ce((hI,Ql)=>{var xr=hr(),be=xr.Constants;Ql.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 be.ENDHDR+o},loadFromBinary:function(c){if((c.length!==be.ENDHDR||c.readUInt32LE(0)!==be.ENDSIG)&&(c.length<be.ZIP64HDR||c.readUInt32LE(0)!==be.ZIP64SIG))throw xr.Errors.INVALID_END();c.readUInt32LE(0)===be.ENDSIG?(t=c.readUInt16LE(be.ENDSUB),e=c.readUInt16LE(be.ENDTOT),r=c.readUInt32LE(be.ENDSIZ),i=c.readUInt32LE(be.ENDOFF),o=c.readUInt16LE(be.ENDCOM)):(t=xr.readBigUInt64LE(c,be.ZIP64SUB),e=xr.readBigUInt64LE(c,be.ZIP64TOT),r=xr.readBigUInt64LE(c,be.ZIP64SIZE),i=xr.readBigUInt64LE(c,be.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(be.ENDHDR+o);return c.writeUInt32LE(be.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,be.ENDSUB),c.writeUInt16LE(e,be.ENDTOT),c.writeUInt32LE(r,be.ENDSIZ),c.writeUInt32LE(i,be.ENDOFF),c.writeUInt16LE(o,be.ENDCOM),c.fill(" ",be.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 Ma=ce(Na=>{Na.EntryHeader=Xl();Na.MainHeader=eu()});var nu=ce((pI,tu)=>{tu.exports=function(t){var e=he("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 x=0;x<c.length;x++){var g=c[x];g.copy(u,f),f+=g.length}i&&i(u)}),o.end(t)}}}});var iu=ce((gI,ru)=>{var Im=+(process.versions?process.versions.node:"").split(".")[0]||0;ru.exports=function(t,e){var r=he("zlib");let i=Im>=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),x=0;f.fill(0);for(var g=0;g<d.length;g++){var m=d[g];m.copy(f,x),x+=m.length}o&&o(f)}),c.end(t)}}}});var du=ce((mI,cu)=>{"use strict";var{randomFillSync:su}=he("crypto"),Am=ws(),km=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}),au=(t,e)=>Math.imul(t,e)>>>0,ou=(t,e)=>km[(t^e)&255]^t>>>8,oi=()=>typeof su=="function"?su(Buffer.alloc(12)):oi.node();oi.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 _s={genSalt:oi};function ys(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])}ys.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ou(e[0],t),e[1]+=e[0]&255,e[1]=au(e[1],134775813)+1,e[2]=ou(e[2],e[1]>>>24),t};ys.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return au(t,t^1)>>8&255};function Tm(t){let e=new ys(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 Cm(t){let e=new ys(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 Rm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Tm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Am.WRONG_PASSWORD();return i(t.slice(12))}function Pm(t){Buffer.isBuffer(t)&&t.length>=12?_s.genSalt=function(){return t.slice(0,12)}:t==="node"?_s.genSalt=oi.node:_s.genSalt=oi}function Dm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Cm(r),c=_s.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)}cu.exports={decrypt:Rm,encrypt:Dm,_salter:Pm}});var lu=ce(Es=>{Es.Deflater=nu();Es.Inflater=iu();Es.ZipCrypto=du()});var Fa=ce((_I,uu)=>{var de=hr(),Om=Ma(),Ae=de.Constants,Ba=lu();uu.exports=function(t,e){var r=new Om.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let g=t,m=typeof g.decoder=="object"?g.decoder:de.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function y(E){if(!r.flags_desc&&!r.localHeader.flags_desc){if(de.crc32(E)!==r.localHeader.crc)return!1}else{let R={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==Ae.LOCSIG||e.readUInt32LE(O)==Ae.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ae.EXTSIG)R.crc=e.readUInt32LE(O+Ae.EXTCRC),R.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ),R.size=e.readUInt32LE(O+Ae.EXTLEN);else if(e.readUInt16LE(O+12)===19280)R.crc=e.readUInt32LE(O+Ae.EXTCRC-4),R.compressedSize=e.readUInt32LE(O+Ae.EXTSIZ-4),R.size=e.readUInt32LE(O+Ae.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(E)!==R.crc)return!1}return!0}function b(E,R,O){if(typeof R>"u"&&typeof E=="string"&&(O=E,E=void 0),c)return E&&R&&R(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return E&&R&&R(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw de.Errors.INVALID_PASS_PARAM();F=Ba.ZipCrypto.decrypt(F,r,O)}var B=Buffer.alloc(r.size);switch(r.method){case de.Constants.STORED:if(F.copy(B),y(B))return E&&R&&R(B),B;throw E&&R&&R(B,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var Z=new Ba.Inflater(F,r.size);if(E)Z.inflateAsync(function(J){J.copy(J,0),R&&(y(J)?R(J):R(J,de.Errors.BAD_CRC()))});else{if(Z.inflate(B).copy(B,0),!y(B))throw de.Errors.BAD_CRC(`"${m.decode(i)}"`);return B}break;default:throw E&&R&&R(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.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(r.method){case de.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),E&&R&&R(O),O;default:case de.Constants.DEFLATED:var F=new Ba.Deflater(d);if(E)F.deflateAsync(function(Z){O=Buffer.alloc(Z.length),r.compressedSize=Z.length,Z.copy(O),R&&R(O)});else{var B=F.deflate();return r.compressedSize=B.length,B}F=null;break}}else if(E&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,R){return de.readBigUInt64LE(E,R)}function T(E){try{for(var R=0,O,F,B;R+4<E.length;)O=E.readUInt16LE(R),R+=2,F=E.readUInt16LE(R),R+=2,B=E.slice(R,R+F),R+=F,Ae.ID_ZIP64===O&&D(B)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(E){var R,O,F,B;E.length>=Ae.EF_ZIP64_SCOMP&&(R=A(E,Ae.EF_ZIP64_SUNCOMP),r.size===Ae.EF_ZIP64_OR_32&&(r.size=R)),E.length>=Ae.EF_ZIP64_RHO&&(O=A(E,Ae.EF_ZIP64_SCOMP),r.compressedSize===Ae.EF_ZIP64_OR_32&&(r.compressedSize=O)),E.length>=Ae.EF_ZIP64_DSN&&(F=A(E,Ae.EF_ZIP64_RHO),r.offset===Ae.EF_ZIP64_OR_32&&(r.offset=F)),E.length>=Ae.EF_ZIP64_DSN+4&&(B=E.readUInt32LE(Ae.EF_ZIP64_DSN),r.diskNumStart===Ae.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(E){i=de.toBuffer(E,m.encode);var R=i[i.length-1];c=R===47||R===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,r.extraLength=E.length,T(E)},get comment(){return m.decode(o)},set comment(E){if(o=de.toBuffer(E,m.encode),r.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var E=m.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=de.toBuffer(E,de.decoder.encode),!c&&d.length?(r.size=d.length,r.method=de.Constants.DEFLATED,r.crc=de.crc32(E),r.changed=!0):r.method=de.Constants.STORED},getData:function(E){return r.changed?d:b(!1,null,E)},getDataAsync:function(E,R){r.changed?E(d):b(!0,E,R)},set attr(E){r.attr=E},get attr(){return r.attr},set header(E){r.loadFromBinary(E)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var E=r.centralHeaderToBinary(),R=de.Constants.CENHDR;return i.copy(E,R),R+=i.length,u.copy(E,R),R+=r.extraLength,o.copy(E,R),E},packLocalHeader:function(){let E=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let R=r.localHeaderToBinary(),O=Buffer.alloc(R.length+i.length+r.extraLocalLength);return R.copy(O,E),E+=R.length,i.copy(O,E),E+=i.length,f.copy(O,E),E+=f.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:r.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var xu=ce((yI,hu)=>{var fu=Fa(),Lm=Ma(),Ve=hr();hu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Lm.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:g,decoder:m}=x;t?b(x.readEntries):d=!0;function S(){let A=new Set;for(let T of Object.keys(i)){let D=T.split("/");if(D.pop(),!!D.length)for(let E=0;E<D.length;E++){let R=D.slice(0,E+1).join("/")+"/";A.add(R)}}for(let T of A)if(!(T in i)){let D=new fu(x);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,E=new fu(x,t);E.header=t.slice(D,D+=Ve.Constants.CENHDR),E.entryName=t.slice(D,D+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(D,D+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(D,D+E.header.commentLength)),A+=E.header.centralHeaderSize,r[T]=E,i[E.entryName]=E}f.clear(),S()}function b(A){var T=t.length-Ve.Constants.ENDHDR,D=Math.max(0,T-65535),E=D,R=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(D=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ve.Constants.ENDSIG){O=T,F=T,R=T+Ve.Constants.ENDHDR,E=T-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ve.Constants.END64SIG){E=D;continue}if(t.readUInt32LE(T)===Ve.Constants.ZIP64SIG){O=T,R=T+Ve.readBigUInt64LE(t,T+Ve.Constants.ZIP64SIZE)+Ve.Constants.ZIP64LEAD;break}}if(O==-1)throw Ve.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,R)),c.commentLength&&(o=t.slice(F+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 m.decode(o)},set comment(A){o=Ve.toBuffer(A,m.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=[],E=A.entryName;for(let R of r)R.entryName.startsWith(E)&&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,E=0;c.size=0,c.offset=0;let R=0;for(let B of this.entries){let Z=B.getCompressedData();B.header.offset=E;let J=B.packLocalHeader(),re=J.length+Z.length;E+=re,A.push(J),A.push(Z);let X=B.packCentralHeader();T.push(X),c.size+=X.length,D+=re+X.length,R++}D+=c.mainHeaderSize,c.offset=E,c.totalEntries=R,E=0;let O=Buffer.alloc(D);for(let B of A)B.copy(O,E),E+=B.length;for(let B of T)B.copy(O,E),E+=B.length;let F=c.toBinary();return o&&o.copy(F,Ve.Constants.ENDHDR),F.copy(O,E),t=O,d=!1,O},toAsyncBuffer:function(A,T,D,E){try{d||y(),I();let R=[],O=[],F=0,B=0,Z=0;c.size=0,c.offset=0;let J=function(re){if(re.length>0){let X=re.shift(),oe=X.entryName+X.extra.toString();D&&D(oe),X.getCompressedDataAsync(function(ae){E&&E(oe),X.header.offset=B;let P=X.packLocalHeader(),q=P.length+ae.length;B+=q,R.push(P),R.push(ae);let $=X.packCentralHeader();O.push($),c.size+=$.length,F+=q+$.length,Z++,J(re)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=Z,B=0;let X=Buffer.alloc(F);R.forEach(function(ae){ae.copy(X,B),B+=ae.length}),O.forEach(function(ae){ae.copy(X,B),B+=ae.length});let oe=c.toBinary();o&&o.copy(oe,Ve.Constants.ENDHDR),oe.copy(X,B),t=X,d=!1,A(X)}};J(Array.from(this.entries))}catch(R){T(R)}}}}});var mu=ce((EI,gu)=>{var Se=hr(),ve=he("path"),Nm=Fa(),Mm=xu(),On=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),pu=(...t)=>Se.findLast(t,e=>typeof e=="string"),Bm=(...t)=>Se.findLast(t,e=>typeof e=="function"),Fm={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};gu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Fm);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=Se.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Se(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Se.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Se.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let c=new Mm(r,i),{canonical:d,sanitize:u,zipnamefix:f}=Se;function x(y){if(y&&c){var b;if(typeof y=="string"&&(b=c.getEntry(ve.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(b=c.getEntry(y.entryName)),b)return b}return null}function g(y){let{join:b,normalize:I,sep:A}=ve.posix;return b(ve.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function m(y){return y instanceof RegExp?(function(b){return function(I){return b.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,b)=>{let I=b.slice(-1);return I=I===o.sep?o.sep:"",ve.relative(y,b)+I};return{readFile:function(y,b){var I=x(y);return I&&I.getData(b)||null},childCount:function(y){let b=x(y);if(b)return c.getChildCount(b)},readFileAsync:function(y,b){var I=x(y);I?I.getDataAsync(b):b(null,"getEntry failed for:"+y)},readAsText:function(y,b){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(b||"utf8")}return""},readAsTextAsync:function(y,b,I){var A=x(y);A?A.getDataAsync(function(T,D){if(D){b(T,D);return}T&&T.length?b(T.toString(I||"utf8")):b("")}):b("")},deleteFile:function(y,b=!0){var I=x(y);I&&c.deleteFile(I.entryName,b)},deleteEntry:function(y){var b=x(y);b&&c.deleteEntry(b.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,b){var I=x(y);I&&(I.comment=b)},getZipEntryComment:function(y){var b=x(y);return b&&b.comment||""},updateFile:function(y,b){var I=x(y);I&&I.setData(b)},addLocalFile:function(y,b,I,A){if(o.fs.existsSync(y)){b=b?g(b):"";let T=ve.win32.basename(ve.win32.normalize(y));b+=I||T;let D=o.fs.statSync(y),E=D.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);D.isDirectory()&&(b+=o.sep),this.addFile(b,E,A,D)}else throw Se.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,b){y=typeof y=="object"?y:{localPath:y};let I=ve.resolve(y.localPath),{comment:A}=y,{zipPath:T,zipName:D}=y,E=this;o.fs.stat(I,function(R,O){if(R)return b(R,!1);T=T?g(T):"";let F=ve.win32.basename(ve.win32.normalize(I));if(T+=D||F,O.isFile())o.fs.readFile(I,function(B,Z){return B?b(B,!1):(E.addFile(T,Z,A,O),setImmediate(b,void 0,!0))});else if(O.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),A,O),setImmediate(b,void 0,!0)})},addLocalFolder:function(y,b,I){if(I=m(I),b=b?g(b):"",y=ve.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),T=this;if(A.length)for(let D of A){let E=ve.join(b,S(y,D));I(E)&&T.addLocalFile(D,ve.dirname(E))}}else throw Se.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,b,I,A){A=m(A),I=I?g(I):"",y=ve.normalize(y);var T=this;o.fs.open(y,"r",function(D){if(D&&D.code==="ENOENT")b(void 0,Se.Errors.FILE_NOT_FOUND(y));else if(D)b(void 0,D);else{var E=o.findFiles(y),R=-1,O=function(){if(R+=1,R<E.length){var F=E[R],B=S(y,F).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(B)?o.fs.stat(F,function(Z,J){Z&&b(void 0,Z),J.isFile()?o.fs.readFile(F,function(re,X){re?b(void 0,re):(T.addFile(I+B,X,"",J),O())}):(T.addFile(I+B+"/",Buffer.alloc(0),"",J),O())}):process.nextTick(()=>{O()})}else b(!0,void 0)};O()}})},addLocalFolderAsync2:function(y,b){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=ve.resolve(g(y.localPath));let{zipPath:A,filter:T,namefix:D}=y;T instanceof RegExp?T=(function(O){return function(F){return O.test(F)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=O=>O);let E=O=>ve.join(A,D(S(localPath,O))),R=O=>ve.win32.basename(ve.win32.normalize(D(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?b(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):O?b(void 0,O):o.findFilesAsync(localPath,function(F,B){if(F)return b(F);B=B.filter(Z=>T(E(Z))),B.length||b(void 0,!1),setImmediate(B.reverse().reduce(function(Z,J){return function(re,X){if(re||X===!1)return setImmediate(Z,re,!1);I.addLocalFileAsync({localPath:J,zipPath:ve.dirname(E(J)),zipName:R(J)},Z)}},b))})})},addLocalFolderPromise:function(y,b){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},b),(T,D)=>{T&&A(T),D&&I(this)})})},addFile:function(y,b,I,A){y=f(y);let T=x(y),D=T!=null;D||(T=new Nm(i),T.entryName=y),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(b),D||c.setEntry(T),T},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return x(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,b,I,A,T,D){A=On(!1,A),T=On(!1,T),I=On(!0,I),D=pu(T,D);var E=x(y);if(!E)throw Se.Errors.NO_ENTRY();var R=d(E.entryName),O=u(b,D&&!E.isDirectory?D:I?R:ve.basename(R));if(E.isDirectory){var F=c.getEntryChildren(E);return F.forEach(function(J){if(J.isDirectory)return;var re=J.getData();if(!re)throw Se.Errors.CANT_EXTRACT_FILE();var X=d(J.entryName),oe=u(b,I?X:ve.basename(X));let ae=T?J.header.fileAttr:void 0;o.writeFileTo(oe,re,A,ae)}),!0}var B=E.getData(c.password);if(!B)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Se.Errors.CANT_OVERRIDE();let Z=T?y.header.fileAttr:void 0;return o.writeFileTo(O,B,A,Z),!0},test:function(y){if(!c)return!1;for(var b in c.entries)try{if(b.isDirectory)continue;var I=c.entries[b].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,b,I,A){if(I=On(!1,I),A=pu(I,A),b=On(!1,b),!c)throw Se.Errors.NO_ZIP();c.entries.forEach(function(T){var D=u(y,d(T.entryName));if(T.isDirectory){o.makeDir(D);return}var E=T.getData(A);if(!E)throw Se.Errors.CANT_EXTRACT_FILE();let R=I?T.header.fileAttr:void 0;o.writeFileTo(D,E,b,R);try{o.fs.utimesSync(D,T.header.time,T.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,b,I,A){if(A=Bm(b,I,A),I=On(!1,I),b=On(!1,b),!A)return new Promise((O,F)=>{this.extractAllToAsync(y,b,I,function(B){B?F(B):O(this)})});if(!c){A(Se.Errors.NO_ZIP());return}y=ve.resolve(y);let T=O=>u(y,ve.normalize(d(O.entryName))),D=(O,F)=>new Error(O+': "'+F+'"'),E=[],R=[];c.entries.forEach(O=>{O.isDirectory?E.push(O):R.push(O)});for(let O of E){let F=T(O),B=I?O.header.fileAttr:void 0;try{o.makeDir(F),B&&o.fs.chmodSync(F,B),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{A(D("Unable to create folder",F))}}R.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let Z=ve.normalize(d(F.entryName)),J=u(y,Z);F.getDataAsync(function(re,X){if(X)O(X);else if(!re)O(Se.Errors.CANT_EXTRACT_FILE());else{let oe=I?F.header.fileAttr:void 0;o.writeFileToAsync(J,re,b,oe,function(ae){ae||O(D("Unable to write file",J)),o.fs.utimes(J,F.header.time,F.header.time,function(P){P?O(D("Unable to set times",J)):O()})})}})}}},A)()},writeZip:function(y,b){if(arguments.length===1&&typeof y=="function"&&(b=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof b=="function"&&b(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,b){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},b);return new Promise((T,D)=>{!y&&i.filename&&(y=i.filename),y||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let R=O=>O?T(O):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(y,E,I,A,R)},D)})},toBufferPromise:function(){return new Promise((y,b)=>{c.toAsyncBuffer(y,b)})},toBuffer:function(y,b,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,b,I,A),null):c.compressToBuffer()}}}});import{execFile as j_,spawn as W_,spawnSync as zA}from"node:child_process";import{promisify as K_}from"node:util";function V_(t){if(process.platform!=="win32")return!1;if(Bf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Bf,"").toLowerCase();return $_.has(r)}function Ff(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return V_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function st(t,e=[],r={}){return W_(t,e,Ff(t,r))}function zf(t,e=[],r={}){return J_(t,e,Ff(t,r))}var $_,Bf,J_,Jt=nt(()=>{"use strict";$_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Bf=/\.(cmd|bat|ps1)$/i;J_=K_(j_)});var Yt=ce((bR,Ah)=>{"use strict";var Sh=["nodebuffer","arraybuffer","fragments"],Ih=typeof Blob<"u";Ih&&Sh.push("blob");Ah.exports={BINARY_TYPES:Sh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ih,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $i=ce((vR,Co)=>{"use strict";var{EMPTY_BUFFER:kb}=Yt(),gd=Buffer[Symbol.species];function Tb(t,e){if(t.length===0)return kb;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 gd(r.buffer,r.byteOffset,i):r}function kh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Th(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Cb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function md(t){if(md.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new gd(t):ArrayBuffer.isView(t)?e=new gd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),md.readOnly=!1),e}Co.exports={concat:Tb,mask:kh,toArrayBuffer:Cb,toBuffer:md,unmask:Th};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=he("bufferutil");Co.exports.mask=function(e,r,i,o,c){c<48?kh(e,r,i,o,c):t.mask(e,r,i,o,c)},Co.exports.unmask=function(e,r){e.length<32?Th(e,r):t.unmask(e,r)}}catch{}});var Ph=ce((SR,Rh)=>{"use strict";var Ch=Symbol("kDone"),wd=Symbol("kRun"),_d=class{constructor(e){this[Ch]=()=>{this.pending--,this[wd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wd]()}[wd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ch])}}};Rh.exports=_d});var Ur=ce((IR,Nh)=>{"use strict";var Vi=he("zlib"),Dh=$i(),Rb=Ph(),{kStatusCode:Oh}=Yt(),Pb=Buffer[Symbol.species],Db=Buffer.from([0,0,255,255]),Po=Symbol("permessage-deflate"),Xt=Symbol("total-length"),Fr=Symbol("callback"),Tn=Symbol("buffers"),zr=Symbol("error"),Ro,yd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ro){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ro=new Rb(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[Fr];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){Ro.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Ro.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"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Po]=this,this._inflate[Xt]=0,this._inflate[Tn]=[],this._inflate.on("error",Lb),this._inflate.on("data",Lh)}this._inflate[Fr]=i,this._inflate.write(e),r&&this._inflate.write(Db),this._inflate.flush(()=>{let c=this._inflate[zr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Dh.concat(this._inflate[Tn],this._inflate[Xt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Xt]=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"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Xt]=0,this._deflate[Tn]=[],this._deflate.on("data",Ob)}this._deflate[Fr]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Dh.concat(this._deflate[Tn],this._deflate[Xt]);r&&(c=new Pb(c.buffer,c.byteOffset,c.length-4)),this._deflate[Fr]=null,this._deflate[Xt]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Nh.exports=yd;function Ob(t){this[Tn].push(t),this[Xt]+=t.length}function Lh(t){if(this[Xt]+=t.length,this[Po]._maxPayload<1||this[Xt]<=this[Po]._maxPayload){this[Tn].push(t);return}this[zr]=new RangeError("Max payload size exceeded"),this[zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[zr][Oh]=1009,this.removeListener("data",Lh),this.reset()}function Lb(t){if(this[Po]._inflate=null,this[zr]){this[Fr](this[zr]);return}t[Oh]=1007,this[Fr](t)}});var qr=ce((AR,Do)=>{"use strict";var{isUtf8:Mh}=he("buffer"),{hasBlob:Nb}=Yt(),Mb=[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 Bb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ed(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 Fb(t){return Nb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Do.exports={isBlob:Fb,isValidStatusCode:Bb,isValidUTF8:Ed,tokenChars:Mb};if(Mh)Do.exports.isValidUTF8=function(t){return t.length<24?Ed(t):Mh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=he("utf-8-validate");Do.exports.isValidUTF8=function(e){return e.length<32?Ed(e):t(e)}}catch{}});var Ad=ce((kR,Hh)=>{"use strict";var{Writable:zb}=he("stream"),Bh=Ur(),{BINARY_TYPES:Ub,EMPTY_BUFFER:Fh,kStatusCode:qb,kWebSocket:Gb}=Yt(),{concat:bd,toArrayBuffer:Hb,unmask:jb}=$i(),{isValidStatusCode:Wb,isValidUTF8:zh}=qr(),Oo=Buffer[Symbol.species],xt=0,Uh=1,qh=2,Gh=3,vd=4,Sd=5,Lo=6,Id=class extends zb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ub[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[Gb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=xt}_write(e,r,i){if(this._opcode===8&&this._state==xt)return i();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 Oo(i.buffer,i.byteOffset+e,i.length-e),new Oo(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 Oo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case xt:this.getInfo(e);break;case Uh:this.getPayloadLength16(e);break;case qh:this.getPayloadLength64(e);break;case Gh:this.getMask();break;case vd:this.getData(e);break;case Sd:case Lo: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[Bh.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=Uh:this._payloadLength===127?this._state=qh: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=Gh:this._state=vd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vd}getData(e){let r=Fh;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&&jb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Sd,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[Bh.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===xt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=xt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=bd(i,r):this._binaryType==="arraybuffer"?o=Hb(bd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=xt):(this._state=Lo,setImmediate(()=>{this.emit("message",o,!0),this._state=xt,this.startLoop(e)}))}else{let o=bd(i,r);if(!this._skipUTF8Validation&&!zh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Sd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=xt):(this._state=Lo,setImmediate(()=>{this.emit("message",o,!1),this._state=xt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Fh),this.end();else{let i=e.readUInt16BE(0);if(!Wb(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Oo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=xt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xt):(this._state=Lo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xt,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(d,this.createError),d.code=c,d[qb]=o,d}};Hh.exports=Id});var Cd=ce((CR,Kh)=>{"use strict";var{Duplex:TR}=he("stream"),{randomFillSync:Kb}=he("crypto"),{types:{isUint8Array:$b}}=he("util"),jh=Ur(),{EMPTY_BUFFER:Vb,kWebSocket:Jb,NOOP:Zb}=Yt(),{isBlob:Gr,isValidStatusCode:Yb}=qr(),{mask:Wh,toBuffer:Jn}=$i(),pt=Symbol("kByteLength"),Xb=Buffer.alloc(4),No=8*1024,Zn,Hr=No,It=0,Qb=1,ev=2,kd=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=It,this.onerror=Zb,this[Jb]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||Xb,r.generateMask?r.generateMask(i):(Hr===No&&(Zn===void 0&&(Zn=Buffer.alloc(No)),Kb(Zn,0,No),Hr=0),i[0]=Zn[Hr++],i[1]=Zn[Hr++],i[2]=Zn[Hr++],i[3]=Zn[Hr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[pt]!==void 0?u=r[pt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let f=u;u>=65536?(c+=8,f=127):u>125&&(c+=2,f=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:o?(Wh(e,i,x,c,u),[x]):(Wh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=Vb;else{if(typeof e!="number"||!Yb(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($b(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[pt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Jn(e),o=e.length,c=Jn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Gr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Jn(e),o=e.length,c=Jn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Gr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[jh.extensionName],c=r.binary?2:1,d=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Gr(e)?(u=e.size,f=!1):(e=Jn(e),u=e.length,f=Jn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),r.fin&&(this._firstFragment=!0);let x={[pt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:d};Gr(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==It?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[pt],this._state=ev,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Td,this,u,o);return}this._bufferedBytes-=i[pt];let d=Jn(c);r?this.dispatch(d,r,i,o):(this._state=It,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(tv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[jh.extensionName];this._bufferedBytes+=i[pt],this._state=Qb,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Td(this,f,o);return}this._bufferedBytes-=i[pt],this._state=It,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][pt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][pt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Kh.exports=kd;function Td(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 tv(t,e,r){Td(t,e,r),t.onerror(e)}});var tx=ce((RR,ex)=>{"use strict";var{kForOnEventAttribute:Ji,kListener:Rd}=Yt(),$h=Symbol("kCode"),Vh=Symbol("kData"),Jh=Symbol("kError"),Zh=Symbol("kMessage"),Yh=Symbol("kReason"),jr=Symbol("kTarget"),Xh=Symbol("kType"),Qh=Symbol("kWasClean"),Qt=class{constructor(e){this[jr]=null,this[Xh]=e}get target(){return this[jr]}get type(){return this[Xh]}};Object.defineProperty(Qt.prototype,"target",{enumerable:!0});Object.defineProperty(Qt.prototype,"type",{enumerable:!0});var Yn=class extends Qt{constructor(e,r={}){super(e),this[$h]=r.code===void 0?0:r.code,this[Yh]=r.reason===void 0?"":r.reason,this[Qh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[$h]}get reason(){return this[Yh]}get wasClean(){return this[Qh]}};Object.defineProperty(Yn.prototype,"code",{enumerable:!0});Object.defineProperty(Yn.prototype,"reason",{enumerable:!0});Object.defineProperty(Yn.prototype,"wasClean",{enumerable:!0});var Wr=class extends Qt{constructor(e,r={}){super(e),this[Jh]=r.error===void 0?null:r.error,this[Zh]=r.message===void 0?"":r.message}get error(){return this[Jh]}get message(){return this[Zh]}};Object.defineProperty(Wr.prototype,"error",{enumerable:!0});Object.defineProperty(Wr.prototype,"message",{enumerable:!0});var Zi=class extends Qt{constructor(e,r={}){super(e),this[Vh]=r.data===void 0?null:r.data}get data(){return this[Vh]}};Object.defineProperty(Zi.prototype,"data",{enumerable:!0});var nv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Ji]&&o[Rd]===e&&!o[Ji])return;let i;if(t==="message")i=function(c,d){let u=new Zi("message",{data:d?c:c.toString()});u[jr]=this,Mo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Yn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[jr]=this,Mo(e,this,u)};else if(t==="error")i=function(c){let d=new Wr("error",{error:c,message:c.message});d[jr]=this,Mo(e,this,d)};else if(t==="open")i=function(){let c=new Qt("open");c[jr]=this,Mo(e,this,c)};else return;i[Ji]=!!r[Ji],i[Rd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Rd]===e&&!r[Ji]){this.removeListener(t,r);break}}};ex.exports={CloseEvent:Yn,ErrorEvent:Wr,Event:Qt,EventTarget:nv,MessageEvent:Zi};function Mo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Bo=ce((PR,nx)=>{"use strict";var{tokenChars:Yi}=qr();function Ft(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function rv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,f=-1,x=-1,g=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),d===void 0)if(g===-1&&Yi[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))g===-1&&f!==-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let y=t.slice(f,g);x===44?(Ft(e,y,r),r=Object.create(null)):d=y,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(g===-1&&Yi[x]===1)f===-1&&(f=m);else if(x===32||x===9)g===-1&&f!==-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m),Ft(r,t.slice(f,g),!0),x===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),f=g=-1}else if(x===61&&f!==-1&&g===-1)u=t.slice(f,m),f=g=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(Yi[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),o=!1}else if(c)if(Yi[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)c=!1,g=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)c=!0;else if(g===-1&&Yi[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))g===-1&&(g=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let y=t.slice(f,g);i&&(y=y.replace(/\\/g,""),i=!1),Ft(r,u,y),x===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 ${m}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=m);let S=t.slice(f,g);return d===void 0?Ft(e,S,r):(u===void 0?Ft(r,S,!0):i?Ft(r,u,S.replace(/\\/g,"")):Ft(r,u,S),Ft(e,d,r)),e}function iv(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(", ")}nx.exports={format:iv,parse:rv}});var qo=ce((LR,xx)=>{"use strict";var sv=he("events"),ov=he("https"),av=he("http"),sx=he("net"),cv=he("tls"),{randomBytes:dv,createHash:lv}=he("crypto"),{Duplex:DR,Readable:OR}=he("stream"),{URL:Pd}=he("url"),Cn=Ur(),uv=Ad(),fv=Cd(),{isBlob:hv}=qr(),{BINARY_TYPES:rx,CLOSE_TIMEOUT:xv,EMPTY_BUFFER:Fo,GUID:pv,kForOnEventAttribute:Dd,kListener:gv,kStatusCode:mv,kWebSocket:We,NOOP:ox}=Yt(),{EventTarget:{addEventListener:wv,removeEventListener:_v}}=tx(),{format:yv,parse:Ev}=Bo(),{toBuffer:bv}=$i(),ax=Symbol("kAborted"),Od=[8,13],en=["CONNECTING","OPEN","CLOSING","CLOSED"],vv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends sv{constructor(e,r,i){super(),this._binaryType=rx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fo,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]),cx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){rx.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 uv({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 fv(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",Av),o.on("drain",kv),o.on("error",Tv),o.on("message",Cv),o.on("ping",Rv),o.on("pong",Pv),c.onerror=Dv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",ux),e.on("data",Uo),e.on("end",fx),e.on("error",hx),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())}),lx(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){Ld(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Fo,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){Ld(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Fo,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){Ld(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||Fo,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(ye,"CONNECTING",{enumerable:!0,value:en.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:en.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:en.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:en.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Dd])return e[gv];return null},set(e){for(let r of this.listeners(t))if(r[Dd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Dd]:!0})}})});ye.prototype.addEventListener=wv;ye.prototype.removeEventListener=_v;xx.exports=ye;function cx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xv,protocolVersion:Od[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,!Od.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Od.join(", ")})`);let c;if(e instanceof Pd)c=e;else try{c=new Pd(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;zo(t,I);return}let x=d?443:80,g=dv(16).toString("base64"),m=d?ov.request:av.request,S=new Set,y;if(o.createConnection=o.createConnection||(d?Iv:Sv),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":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"]=yv({[Cn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!vv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.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 b;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")),b=t._req=m(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=m(o);o.timeout&&b.on("timeout",()=>{dt(t,b,"Opening handshake has timed out")}),b.on("error",I=>{b===null||b[ax]||(b=t._req=null,zo(t,I))}),b.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,b,"Maximum redirects exceeded");return}b.abort();let D;try{D=new Pd(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);zo(t,R);return}cx(t,D,r,i)}else t.emit("unexpected-response",b,I)||dt(t,b,`Unexpected server response: ${I.statusCode}`)}),b.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;b=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){dt(t,A,"Invalid Upgrade header");return}let E=lv("sha1").update(g+pv).digest("base64");if(I.headers["sec-websocket-accept"]!==E){dt(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){dt(t,A,O);return}R&&(t._protocol=R);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!y){dt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=Ev(F)}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Z=Object.keys(B);if(Z.length!==1||Z[0]!==Cn.extensionName){dt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(B[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(b,t):b.end()}function zo(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Sv(t){return t.path=t.socketPath,sx.connect(t)}function Iv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=sx.isIP(t.host)?"":t.host),cv.connect(t)}function dt(t,e,r){t._readyState=ye.CLOSING;let i=new Error(r);Error.captureStackTrace(i,dt),e.setHeader?(e[ax]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(zo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ld(t,e,r){if(e){let i=hv(e)?e.size:bv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${en[t.readyState]})`);process.nextTick(r,i)}}function Av(t,e){let r=this[We];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[We]!==void 0&&(r._socket.removeListener("data",Uo),process.nextTick(dx,r._socket),t===1005?r.close():r.close(t,e))}function kv(){let t=this[We];t.isPaused||t._socket.resume()}function Tv(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",Uo),process.nextTick(dx,e._socket),e.close(t[mv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ix(){this[We].emitClose()}function Cv(t,e){this[We].emit("message",t,e)}function Rv(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,ox),e.emit("ping",t)}function Pv(t){this[We].emit("pong",t)}function dx(t){t.resume()}function Dv(t){let e=this[We];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,lx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function lx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ux(){let t=this[We];if(this.removeListener("close",ux),this.removeListener("data",Uo),this.removeListener("end",fx),t._readyState=ye.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ix),t._receiver.on("finish",ix))}function Uo(t){this[We]._receiver.write(t)||this.pause()}function fx(){let t=this[We];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function hx(){let t=this[We];this.removeListener("error",hx),this.on("error",ox),t&&(t._readyState=ye.CLOSING,this.destroy())}});var _x=ce((MR,mx)=>{"use strict";var NR=qo(),{Duplex:Ov}=he("stream");function px(t){t.emit("close")}function Lv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function gx(t){this.removeListener("error",gx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Nv(t,e){let r=!0,i=new Ov({...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(px,i);return}let d=!1;t.once("error",function(f){d=!0,c(f)}),t.once("close",function(){d||c(o),process.nextTick(px,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",Lv),i.on("error",gx),i}mx.exports=Nv});var Nd=ce((BR,yx)=>{"use strict";var{tokenChars:Mv}=qr();function Bv(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&&Mv[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}yx.exports={parse:Bv}});var kx=ce((zR,Ax)=>{"use strict";var Fv=he("events"),Go=he("http"),{Duplex:FR}=he("stream"),{createHash:zv}=he("crypto"),Ex=Bo(),Xn=Ur(),Uv=Nd(),qv=qo(),{CLOSE_TIMEOUT:Gv,GUID:Hv,kWebSocket:jv}=Yt(),Wv=/^[+/0-9A-Za-z]{22}==$/,bx=0,vx=1,Ix=2,Md=class extends Fv{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:Gv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:qv,...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=Go.createServer((i,o)=>{let c=Go.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=Kv(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=bx}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===Ix){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xi,this);return}if(e&&this.once("close",e),this._state!==vx)if(this._state=vx,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(Xi,this):process.nextTick(Xi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Xi(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",Sx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Qn(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){Qn(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Wv.test(c)){Qn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Qn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qi(r,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=Uv.parse(f)}catch{Qn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&g!==void 0){let S=new Xn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Ex.parse(g);y[Xn.extensionName]&&(S.accept(y[Xn.extensionName]),m[Xn.extensionName]=S)}catch{Qn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(y,b,I,A)=>{if(!y)return Qi(r,b||401,I,A);this.completeUpgrade(m,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return Qi(r,401)}this.completeUpgrade(m,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[jv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>bx)return Qi(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${zv("sha1").update(r+Hv).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[Xn.extensionName]){let m=e[Xn.extensionName].params,S=Ex.format({[Xn.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&cs(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 Ug,mkdirSync as qg}from"node:fs";import{join as Gg}from"node:path";function bl(t){let e=t.retentionDays??Wg,r=t.clock??(()=>Dn(new Date));ls={bridgeSink:new ei(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ei(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();cs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])cs(t.agentLogsDir(o),"agent",i,e)}function Kg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function vl(t){ka=t}function Sl(t){return ar[ka]<=ar[t]}function Il(t,e){let r=ar[t];return r===void 0?!0:r>=ar[e]}function us(t){El={...t}}function Al(t){let e=(u,h=2)=>String(u).padStart(h,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),a=e(Math.floor(o/60)),d=e(o%60);return`${Dn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function et(t,e,r,i,o){try{let a=`${JSON.stringify({ts:Al(new Date),level:e,module:r,msg:i,...o})}
11
+ `;qg(t,{recursive:!0}),Ug(Gg(t,or("bridge",Dn(new Date))),a)}catch{}}function $g(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ds(t,e,r,i,o){if(ar[t]<ar[ka])return;let a=`${JSON.stringify({ts:Al(new Date),level:t,module:e,msg:r,...El,...i})}
12
+ `;if(ls){let d=$g(o,i),u=d?Kg(ls,d):ls.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?jg.write(a):Hg.write(a)}function q(t,e){return{debug:(r,i)=>ds("debug",t,r,i,e),info:(r,i)=>ds("info",t,r,i,e),warn:(r,i)=>ds("warn",t,r,i,e),error:(r,i)=>ds("error",t,r,i,e),child:r=>q(`${t}.${r}`,e),forAgent:r=>q(t,r)}}var ar,ka,Hg,jg,El,Wg,ls,te=Qe(()=>{"use strict";sr();Ta();ar={debug:10,info:20,warn:30,error:40},ka=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Hg=process.stdout,jg=process.stderr,El={},Wg=$e("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ls=null});var T,We=Qe(()=>{"use strict";T=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 Rl={};Ia(Rl,{ACP_WRAPPER_NPM_PACKAGES:()=>fs,_resetAcpInstallerForTests:()=>Qg,_setBinaryPathCacheForTests:()=>em,buildAcpSpawn:()=>ni,ensureAcpInstalled:()=>cr,getAcpBinaryPath:()=>hs,pickWhichLine:()=>Pa,probeAcpVersion:()=>Xg,resolveAcpCommand:()=>Cl});import{readFileSync as Tl}from"node:fs";import{createRequire as Vg}from"node:module";import{dirname as Jg,resolve as Yg}from"node:path";function Pa(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 Zg(t){let e=kl.resolve(`${t.npmPackage}/package.json`),r=Jg(e),i=JSON.parse(Tl(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 Yg(r,o)}async function cr(t,e){let r=Ra[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ti.get(t);if(i)return i;try{let o=Zg(r);return ti.set(t,o),Ca.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ca.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 T("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 Xg(t){let e=Ra[t];if(e)try{let r=kl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Tl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Ca.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function hs(t){return ti.get(t)}function Cl(t,e){if(e)return e;let r=hs(t);if(!r)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ni(t,e,r){if(e)return{command:e,args:[...r]};let i=Cl(t);return{command:process.execPath,args:[i,...r]}}function Qg(){ti.clear()}function em(t,e){ti.set(t,e)}var Ca,Ra,fs,kl,ti,an=Qe(()=>{"use strict";We();te();Ca=q("agents.acp-installer"),Ra={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},fs=Object.values(Ra).filter(t=>t!==void 0).map(t=>t.npmPackage),kl=Vg(import.meta.url),ti=new Map});import{chmod as nm,mkdir as rm,readFile as im,rename as sm,rm as om,writeFile as am}from"node:fs/promises";import{dirname as cm}from"node:path";async function dr(t){try{let e=await im(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cn(t,e,r){await rm(cm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await am(i,e,{encoding:"utf8",mode:r?.mode}),await sm(i,t),r?.mode!==void 0&&await nm(t,r.mode)}catch(o){throw await om(i,{force:!0}).catch(()=>{}),o}}async function lr(t,e,r){await cn(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var dn=Qe(()=>{"use strict"});import{promises as Ol,readdirSync as dm}from"node:fs";import{homedir as lm}from"node:os";import{sep as um,join as Ae,resolve as Ll}from"node:path";function Q(t){let e=t??lm(),r=Ae(e,".coze"),i=Ae(r,"bridge"),o=Ae(i,"lib"),a=Ae(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ae(o,"index.js"),binDir:Ae(i,"bin"),pidFile:Ae(i,"bridge.pid"),portFile:Ae(i,"bridge.port"),tokenFile:Ae(i,"bridge.token"),patTokenFile:Ae(i,"pat-token"),agentEnvFile:Ae(i,"agent-env.json"),logFile:Ae(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Ae(a,"daemon-stdio.log"),installLock:Ae(i,"install.lock"),configFile:Ae(i,"config.json"),agentsRoot:Ae(r,"agents")}}function Ve(t,e=Q()){let r=Ae(e.agentsRoot,t);return{root:r,config:Ae(r,"config.json"),workspace:Ae(r,"workspace"),logs:Ae(r,"logs")}}function xs(t=Q()){try{return dm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ri(t,e){let r=await Ol.realpath(Ll(t)).catch(()=>null);if(!r)return!1;let i=await Ol.realpath(Ll(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?r.toLowerCase():r,a=process.platform==="win32"?i.toLowerCase():i;return o===a||o.startsWith(a+um)}var Oe=Qe(()=>{"use strict"});var gs={};Ia(gs,{AGENT_CONFIG_FILE_MODE:()=>ps,enforceAgentConfigMode:()=>xm,loadAgentConfig:()=>Te,persistAgentSessions:()=>ii,persistAgentSkills:()=>si,saveAgentConfig:()=>Fe});import{chmod as fm,stat as hm}from"node:fs/promises";function Te(t,e){return dr(Ve(t,e).config)}function Fe(t,e){return lr(Ve(t.agentId,e).config,t,{mode:ps})}async function xm(t,e){if(process.platform==="win32")return;let r=Ve(t,e).config;try{let i=await hm(r);if(!i.isFile())return;let o=i.mode&511;o!==ps&&(await fm(r,ps),Nl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Nl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ii(t,e,r){let i=await Te(t,r);i&&(i.sessions=Object.fromEntries(e),await Fe(i,r))}async function si(t,e,r){let i=await Te(t,r);i&&(i.skills=e,await Fe(i,r))}var Nl,ps,ln=Qe(()=>{"use strict";dn();te();Oe();Nl=q("agent-config"),ps=384});var La=ae((fA,Fl)=>{Fl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var ws=ae(Ul=>{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 ym(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(zl))Ul[t]=ym(zl[t])});var Wl=ae((xA,jl)=>{var Em=le("fs"),Le=le("path"),ql=La(),bm=ws(),vm=typeof process=="object"&&process.platform==="win32",Gl=t=>typeof t=="object"&&t!==null,Hl=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 be(t){this.sep=Le.sep,this.fs=Em,Gl(t)&&Gl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}jl.exports=be;be.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){o+=e.sep+a;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw bm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};be.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var a=o.fs.statSync(t);if(a.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};be.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!r)return o(!1);a.fs.stat(t,function(u,h){if(d&&h.isDirectory())return o(!1);var x=Le.dirname(t);a.fs.exists(x,function(g){g||a.makeDir(x),a.fs.open(t,"w",438,function(w,S){w?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(_,v){a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?a.fs.write(S,e,0,e.length,0,function(){a.fs.close(S,function(){a.fs.chmod(t,i||438,function(){o(!0)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};be.prototype.findFiles=function(t){let e=this;function r(i,o,a){typeof o=="boolean"&&(a=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()&&a&&(d=d.concat(r(h,o,a)))}),d}return r(t,void 0,!0)};be.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,a){if(o)return e(o);let d=a.length;if(!d)return e(null,i);a.forEach(function(u){u=Le.join(t,u),r.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Le.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(g,w){if(g)return e(g);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};be.prototype.getAttributes=function(){};be.prototype.setAttributes=function(){};be.crc32update=function(t,e){return Hl[(t^e)&255]^t>>>8};be.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=be.crc32update(r,t[i++]);return~r>>>0};be.methodToString=function(t){switch(t){case ql.STORED:return"STORED ("+t+")";case ql.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};be.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};be.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.posix.join(".",e)};be.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]};be.sanitize=function(t,e){t=Le.resolve(Le.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var a=Le.normalize(Le.join(t,r.slice(i,o).join(Le.sep)));if(a.indexOf(t)===0)return a}return Le.normalize(Le.join(t,Le.basename(e)))};be.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};be.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};be.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)};be.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};be.isWin=vm;be.crcTable=Hl});var $l=ae((pA,Kl)=>{var Sm=le("path");Kl.exports=function(t,{fs:e}){var r=t||"",i=a(),o=null;function a(){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=Sm.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 Jl=ae((gA,Vl)=>{Vl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var hr=ae((mA,fr)=>{fr.exports=Wl();fr.exports.Constants=La();fr.exports.Errors=ws();fr.exports.FileAttr=$l();fr.exports.decoder=Jl()});var Zl=ae((wA,Yl)=>{var un=hr(),F=un.Constants;Yl.exports=function(){var t=20,e=10,r=0,i=0,o=0,a=0,d=0,u=0,h=0,x=0,g=0,w=0,S=0,_=0,v=0;t|=un.isWin?2560:768,r|=F.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,k=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&F.FLG_EFS)>0},set flags_efs(b){b?r|=F.FLG_EFS:r&=~F.FLG_EFS},get flags_desc(){return(r&F.FLG_DESC)>0},set flags_desc(b){b?r|=F.FLG_DESC:r&=~F.FLG_DESC},get method(){return i},set method(b){switch(b){case F.STORED:this.version=10;case F.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 a},set crc(b){a=A(b)},get compressedSize(){return d},set compressedSize(b){d=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return g},set commentLength(b){g=b},get diskNumStart(){return w},set diskNumStart(b){w=A(b)},get inAttr(){return S},set inAttr(b){S=A(b)},get attr(){return _},set attr(b){_=A(b)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(b){v=A(b)},get encrypted(){return(r&F.FLG_ENC)===F.FLG_ENC},get centralHeaderSize(){return F.CENHDR+h+x+g},get realDataOffset(){return v+F.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var C=b.slice(v,v+F.LOCHDR);if(C.readUInt32LE(0)!==F.LOCSIG)throw un.Errors.INVALID_LOC();I.version=C.readUInt16LE(F.LOCVER),I.flags=C.readUInt16LE(F.LOCFLG),I.flags_desc=(I.flags&F.FLG_DESC)>0,I.method=C.readUInt16LE(F.LOCHOW),I.time=C.readUInt32LE(F.LOCTIM),I.crc=C.readUInt32LE(F.LOCCRC),I.compressedSize=C.readUInt32LE(F.LOCSIZ),I.size=C.readUInt32LE(F.LOCLEN),I.fnameLen=C.readUInt16LE(F.LOCNAM),I.extraLen=C.readUInt16LE(F.LOCEXT);let O=v+F.LOCHDR+I.fnameLen,B=O+I.extraLen;return b.slice(O,B)},loadFromBinary:function(b){if(b.length!==F.CENHDR||b.readUInt32LE(0)!==F.CENSIG)throw un.Errors.INVALID_CEN();t=b.readUInt16LE(F.CENVEM),e=b.readUInt16LE(F.CENVER),r=b.readUInt16LE(F.CENFLG),i=b.readUInt16LE(F.CENHOW),o=b.readUInt32LE(F.CENTIM),a=b.readUInt32LE(F.CENCRC),d=b.readUInt32LE(F.CENSIZ),u=b.readUInt32LE(F.CENLEN),h=b.readUInt16LE(F.CENNAM),x=b.readUInt16LE(F.CENEXT),g=b.readUInt16LE(F.CENCOM),w=b.readUInt16LE(F.CENDSK),S=b.readUInt16LE(F.CENATT),_=b.readUInt32LE(F.CENATX),v=b.readUInt32LE(F.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(F.LOCHDR);return b.writeUInt32LE(F.LOCSIG,0),b.writeUInt16LE(e,F.LOCVER),b.writeUInt16LE(r,F.LOCFLG),b.writeUInt16LE(i,F.LOCHOW),b.writeUInt32LE(o,F.LOCTIM),b.writeUInt32LE(a,F.LOCCRC),b.writeUInt32LE(d,F.LOCSIZ),b.writeUInt32LE(u,F.LOCLEN),b.writeUInt16LE(h,F.LOCNAM),b.writeUInt16LE(I.extraLen,F.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(F.CENHDR+h+x+g);return b.writeUInt32LE(F.CENSIG,0),b.writeUInt16LE(t,F.CENVEM),b.writeUInt16LE(e,F.CENVER),b.writeUInt16LE(r,F.CENFLG),b.writeUInt16LE(i,F.CENHOW),b.writeUInt32LE(o,F.CENTIM),b.writeUInt32LE(a,F.CENCRC),b.writeUInt32LE(d,F.CENSIZ),b.writeUInt32LE(u,F.CENLEN),b.writeUInt16LE(h,F.CENNAM),b.writeUInt16LE(x,F.CENEXT),b.writeUInt16LE(g,F.CENCOM),b.writeUInt16LE(w,F.CENDSK),b.writeUInt16LE(S,F.CENATT),b.writeUInt32LE(_,F.CENATX),b.writeUInt32LE(v,F.CENOFF),b},toJSON:function(){let b=function(C){return C+" bytes"};return{made:t,version:e,flags:r,method:un.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(g),diskNumStart:w,inAttr:S,attr:_,offset:v,centralHeaderSize:b(F.CENHDR+h+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ql=ae((_A,Xl)=>{var xr=hr(),_e=xr.Constants;Xl.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return r},set size(a){r=a},get offset(){return i},set offset(a){i=a},get commentLength(){return o},set commentLength(a){o=a},get mainHeaderSize(){return _e.ENDHDR+o},loadFromBinary:function(a){if((a.length!==_e.ENDHDR||a.readUInt32LE(0)!==_e.ENDSIG)&&(a.length<_e.ZIP64HDR||a.readUInt32LE(0)!==_e.ZIP64SIG))throw xr.Errors.INVALID_END();a.readUInt32LE(0)===_e.ENDSIG?(t=a.readUInt16LE(_e.ENDSUB),e=a.readUInt16LE(_e.ENDTOT),r=a.readUInt32LE(_e.ENDSIZ),i=a.readUInt32LE(_e.ENDOFF),o=a.readUInt16LE(_e.ENDCOM)):(t=xr.readBigUInt64LE(a,_e.ZIP64SUB),e=xr.readBigUInt64LE(a,_e.ZIP64TOT),r=xr.readBigUInt64LE(a,_e.ZIP64SIZE),i=xr.readBigUInt64LE(a,_e.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(_e.ENDHDR+o);return a.writeUInt32LE(_e.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,_e.ENDSUB),a.writeUInt16LE(e,_e.ENDTOT),a.writeUInt32LE(r,_e.ENDSIZ),a.writeUInt32LE(i,_e.ENDOFF),a.writeUInt16LE(o,_e.ENDCOM),a.fill(" ",_e.ENDHDR),a},toJSON:function(){let a=function(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:a(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ma=ae(Na=>{Na.EntryHeader=Zl();Na.MainHeader=Ql()});var tu=ae((EA,eu)=>{eu.exports=function(t){var e=le("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),a=[],d=0;o.on("data",function(u){a.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<a.length;x++){var g=a[x];g.copy(u,h),h+=g.length}i&&i(u)}),o.end(t)}}}});var ru=ae((bA,nu)=>{var Im=+(process.versions?process.versions.node:"").split(".")[0]||0;nu.exports=function(t,e){var r=le("zlib");let i=Im>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var a=r.createInflateRaw(i),d=[],u=0;a.on("data",function(h){d.push(h),u+=h.length}),a.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var g=0;g<d.length;g++){var w=d[g];w.copy(h,x),x+=w.length}o&&o(h)}),a.end(t)}}}});var cu=ae((vA,au)=>{"use strict";var{randomFillSync:iu}=le("crypto"),Am=ws(),Tm=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}),ou=(t,e)=>Math.imul(t,e)>>>0,su=(t,e)=>Tm[(t^e)&255]^t>>>8,oi=()=>typeof iu=="function"?iu(Buffer.alloc(12)):oi.node();oi.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 _s={genSalt:oi};function ys(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])}ys.prototype.updateKeys=function(t){let e=this.keys;return e[0]=su(e[0],t),e[1]+=e[0]&255,e[1]=ou(e[1],134775813)+1,e[2]=su(e[2],e[1]>>>24),t};ys.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return ou(t,t^1)>>8&255};function km(t){let e=new ys(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let a of r)i[o++]=e.updateKeys(a^e.next());return i}}function Cm(t){let e=new ys(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let a of r){let d=e.next();i[o++]=a^d,e.updateKeys(a)}return i}}function Rm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=km(r),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw Am.WRONG_PASSWORD();return i(t.slice(12))}function Pm(t){Buffer.isBuffer(t)&&t.length>=12?_s.genSalt=function(){return t.slice(0,12)}:t==="node"?_s.genSalt=oi.node:_s.genSalt=oi}function Dm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Cm(r),a=_s.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(a,d),o(t,d,12)}au.exports={decrypt:Rm,encrypt:Dm,_salter:Pm}});var du=ae(Es=>{Es.Deflater=tu();Es.Inflater=ru();Es.ZipCrypto=cu()});var Fa=ae((IA,lu)=>{var ce=hr(),Om=Ma(),ve=ce.Constants,Ba=du();lu.exports=function(t,e){var r=new Om.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let g=t,w=typeof g.decoder=="object"?g.decoder:ce.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let C={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==ve.LOCSIG||e.readUInt32LE(O)==ve.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==ve.EXTSIG)C.crc=e.readUInt32LE(O+ve.EXTCRC),C.compressedSize=e.readUInt32LE(O+ve.EXTSIZ),C.size=e.readUInt32LE(O+ve.EXTLEN);else if(e.readUInt16LE(O+12)===19280)C.crc=e.readUInt32LE(O+ve.EXTCRC-4),C.compressedSize=e.readUInt32LE(O+ve.EXTSIZ-4),C.size=e.readUInt32LE(O+ve.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==r.compressedSize||C.size!==r.size||C.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==C.crc)return!1}return!0}function v(b,C,O){if(typeof C>"u"&&typeof b=="string"&&(O=b,b=void 0),a)return b&&C&&C(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var B=S();if(B.length===0)return b&&C&&C(B),B;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();B=Ba.ZipCrypto.decrypt(B,r,O)}var N=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(B.copy(N),_(N))return b&&C&&C(N),N;throw b&&C&&C(N,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var $=new Ba.Inflater(B,r.size);if(b)$.inflateAsync(function(K){K.copy(K,0),C&&(_(K)?C(K):C(K,ce.Errors.BAD_CRC()))});else{if($.inflate(N).copy(N,0),!_(N))throw ce.Errors.BAD_CRC(`"${w.decode(i)}"`);return N}break;default:throw b&&C&&C(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(b,C){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&C&&C(S()),S();if(d.length&&!a){var O;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),b&&C&&C(O),O;default:case ce.Constants.DEFLATED:var B=new Ba.Deflater(d);if(b)B.deflateAsync(function($){O=Buffer.alloc($.length),r.compressedSize=$.length,$.copy(O),C&&C(O)});else{var N=B.deflate();return r.compressedSize=N.length,N}B=null;break}}else if(b&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,C){return ce.readBigUInt64LE(b,C)}function k(b){try{for(var C=0,O,B,N;C+4<b.length;)O=b.readUInt16LE(C),C+=2,B=b.readUInt16LE(C),C+=2,N=b.slice(C,C+B),C+=B,ve.ID_ZIP64===O&&D(N)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(b){var C,O,B,N;b.length>=ve.EF_ZIP64_SCOMP&&(C=A(b,ve.EF_ZIP64_SUNCOMP),r.size===ve.EF_ZIP64_OR_32&&(r.size=C)),b.length>=ve.EF_ZIP64_RHO&&(O=A(b,ve.EF_ZIP64_SCOMP),r.compressedSize===ve.EF_ZIP64_OR_32&&(r.compressedSize=O)),b.length>=ve.EF_ZIP64_DSN&&(B=A(b,ve.EF_ZIP64_RHO),r.offset===ve.EF_ZIP64_OR_32&&(r.offset=B)),b.length>=ve.EF_ZIP64_DSN+4&&(N=b.readUInt32LE(ve.EF_ZIP64_DSN),r.diskNumStart===ve.EF_ZIP64_OR_16&&(r.diskNumStart=N))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,w.encode);var C=i[i.length-1];a=C===47||C===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,k(b)},get comment(){return w.decode(o)},set comment(b){if(o=ce.toBuffer(b,w.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var b=w.decode(i);return a?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){d=ce.toBuffer(b,ce.decoder.encode),!a&&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:v(!1,null,b)},getDataAsync:function(b,C){r.changed?b(d):v(!0,b,C)},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(),C=ce.Constants.CENHDR;return i.copy(b,C),C+=i.length,u.copy(b,C),C+=r.extraLength,o.copy(b,C),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=h.length;let C=r.localHeaderToBinary(),O=Buffer.alloc(C.length+i.length+r.extraLocalLength);return C.copy(O,b),b+=C.length,i.copy(O,b),b+=i.length,h.copy(O,b),b+=h.length,O},toJSON:function(){let b=function(C){return"<"+(C&&C.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 hu=ae((AA,fu)=>{var uu=Fa(),Lm=Ma(),Ke=hr();fu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),a=new Lm.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:g,decoder:w}=x;t?v(x.readEntries):d=!0;function S(){let A=new Set;for(let k of Object.keys(i)){let D=k.split("/");if(D.pop(),!!D.length)for(let b=0;b<D.length;b++){let C=D.slice(0,b+1).join("/")+"/";A.add(C)}}for(let k of A)if(!(k in i)){let D=new uu(x);D.entryName=k,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,h.add(D)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Ke.Constants.CENHDR)throw Ke.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(a.diskEntries);for(var A=a.offset,k=0;k<r.length;k++){var D=A,b=new uu(x,t);b.header=t.slice(D,D+=Ke.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[k]=b,i[b.entryName]=b}h.clear(),S()}function v(A){var k=t.length-Ke.Constants.ENDHDR,D=Math.max(0,k-65535),b=D,C=t.length,O=-1,B=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(D=0),k;k>=b;k--)if(t[k]===80){if(t.readUInt32LE(k)===Ke.Constants.ENDSIG){O=k,B=k,C=k+Ke.Constants.ENDHDR,b=k-Ke.Constants.END64HDR;continue}if(t.readUInt32LE(k)===Ke.Constants.END64SIG){b=D;continue}if(t.readUInt32LE(k)===Ke.Constants.ZIP64SIG){O=k,C=k+Ke.readBigUInt64LE(t,k+Ke.Constants.ZIP64SIZE)+Ke.Constants.ZIP64LEAD;break}}if(O==-1)throw Ke.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(O,C)),a.commentLength&&(o=t.slice(B+Ke.Constants.ENDHDR)),A&&_()}function I(){r.length>1&&!g&&r.sort((A,k)=>A.entryName.toLowerCase().localeCompare(k.entryName.toLowerCase()))}return{get entries(){return d||_(),r.filter(A=>!h.has(A))},get comment(){return w.decode(o)},set comment(A){o=Ke.toBuffer(A,w.encode),a.commentLength=o.length},getEntryCount:function(){return d?r.length:a.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||_(),i[A]||null},setEntry:function(A){d||_(),r.push(A),i[A.entryName]=A,a.totalEntries=r.length},deleteFile:function(A,k=!0){d||_();let D=i[A];this.getEntryChildren(D,k).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||_();let k=i[A],D=r.indexOf(k);D>=0&&(r.splice(D,1),delete i[A],a.totalEntries=r.length)},getEntryChildren:function(A,k=!0){if(d||_(),typeof A=="object")if(A.isDirectory&&k){let D=[],b=A.entryName;for(let C of r)C.entryName.startsWith(b)&&D.push(C);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let k=this.getEntryChildren(A);return k.includes(A)?k.length-1:k.length}return 0},compressToBuffer:function(){d||_(),I();let A=[],k=[],D=0,b=0;a.size=0,a.offset=0;let C=0;for(let N of this.entries){let $=N.getCompressedData();N.header.offset=b;let K=N.packLocalHeader(),ne=K.length+$.length;b+=ne,A.push(K),A.push($);let Z=N.packCentralHeader();k.push(Z),a.size+=Z.length,D+=ne+Z.length,C++}D+=a.mainHeaderSize,a.offset=b,a.totalEntries=C,b=0;let O=Buffer.alloc(D);for(let N of A)N.copy(O,b),b+=N.length;for(let N of k)N.copy(O,b),b+=N.length;let B=a.toBinary();return o&&o.copy(B,Ke.Constants.ENDHDR),B.copy(O,b),t=O,d=!1,O},toAsyncBuffer:function(A,k,D,b){try{d||_(),I();let C=[],O=[],B=0,N=0,$=0;a.size=0,a.offset=0;let K=function(ne){if(ne.length>0){let Z=ne.shift(),ie=Z.entryName+Z.extra.toString();D&&D(ie),Z.getCompressedDataAsync(function(oe){b&&b(ie),Z.header.offset=N;let R=Z.packLocalHeader(),z=R.length+oe.length;N+=z,C.push(R),C.push(oe);let j=Z.packCentralHeader();O.push(j),a.size+=j.length,B+=z+j.length,$++,K(ne)})}else{B+=a.mainHeaderSize,a.offset=N,a.totalEntries=$,N=0;let Z=Buffer.alloc(B);C.forEach(function(oe){oe.copy(Z,N),N+=oe.length}),O.forEach(function(oe){oe.copy(Z,N),N+=oe.length});let ie=a.toBinary();o&&o.copy(ie,Ke.Constants.ENDHDR),ie.copy(Z,N),t=Z,d=!1,A(Z)}};K(Array.from(this.entries))}catch(C){k(C)}}}}});var gu=ae((TA,pu)=>{var Ee=hr(),ye=le("path"),Nm=Fa(),Mm=hu(),On=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),xu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Bm=(...t)=>Ee.findLast(t,e=>typeof e=="function"),Fm={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};pu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Fm);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 a=new Mm(r,i),{canonical:d,sanitize:u,zipnamefix:h}=Ee;function x(_){if(_&&a){var v;if(typeof _=="string"&&(v=a.getEntry(ye.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=a.getEntry(_.entryName)),v)return v}return null}function g(_){let{join:v,normalize:I,sep:A}=ye.posix;return v(ye.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function w(_){return _ instanceof RegExp?(function(v){return function(I){return v.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",ye.relative(_,v)+I};return{readFile:function(_,v){var I=x(_);return I&&I.getData(v)||null},childCount:function(_){let v=x(_);if(v)return a.getChildCount(v)},readFileAsync:function(_,v){var I=x(_);I?I.getDataAsync(v):v(null,"getEntry failed for:"+_)},readAsText:function(_,v){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var A=x(_);A?A.getDataAsync(function(k,D){if(D){v(k,D);return}k&&k.length?v(k.toString(I||"utf8")):v("")}):v("")},deleteFile:function(_,v=!0){var I=x(_);I&&a.deleteFile(I.entryName,v)},deleteEntry:function(_){var v=x(_);v&&a.deleteEntry(v.entryName)},addZipComment:function(_){a.comment=_},getZipComment:function(){return a.comment||""},addZipEntryComment:function(_,v){var I=x(_);I&&(I.comment=v)},getZipEntryComment:function(_){var v=x(_);return v&&v.comment||""},updateFile:function(_,v){var I=x(_);I&&I.setData(v)},addLocalFile:function(_,v,I,A){if(o.fs.existsSync(_)){v=v?g(v):"";let k=ye.win32.basename(ye.win32.normalize(_));v+=I||k;let D=o.fs.statSync(_),b=D.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);D.isDirectory()&&(v+=o.sep),this.addFile(v,b,A,D)}else throw Ee.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=ye.resolve(_.localPath),{comment:A}=_,{zipPath:k,zipName:D}=_,b=this;o.fs.stat(I,function(C,O){if(C)return v(C,!1);k=k?g(k):"";let B=ye.win32.basename(ye.win32.normalize(I));if(k+=D||B,O.isFile())o.fs.readFile(I,function(N,$){return N?v(N,!1):(b.addFile(k,$,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return k+=o.sep,b.addFile(k,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=w(I),v=v?g(v):"",_=ye.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),k=this;if(A.length)for(let D of A){let b=ye.join(v,S(_,D));I(b)&&k.addLocalFile(D,ye.dirname(b))}}else throw Ee.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,A){A=w(A),I=I?g(I):"",_=ye.normalize(_);var k=this;o.fs.open(_,"r",function(D){if(D&&D.code==="ENOENT")v(void 0,Ee.Errors.FILE_NOT_FOUND(_));else if(D)v(void 0,D);else{var b=o.findFiles(_),C=-1,O=function(){if(C+=1,C<b.length){var B=b[C],N=S(_,B).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(N)?o.fs.stat(B,function($,K){$&&v(void 0,$),K.isFile()?o.fs.readFile(B,function(ne,Z){ne?v(void 0,ne):(k.addFile(I+N,Z,"",K),O())}):(k.addFile(I+N+"/",Buffer.alloc(0),"",K),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=ye.resolve(g(_.localPath));let{zipPath:A,filter:k,namefix:D}=_;k instanceof RegExp?k=(function(O){return function(B){return O.test(B)}})(k):typeof k!="function"&&(k=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=O=>O);let b=O=>ye.join(A,D(S(localPath,O))),C=O=>ye.win32.basename(ye.win32.normalize(D(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):o.findFilesAsync(localPath,function(B,N){if(B)return v(B);N=N.filter($=>k(b($))),N.length||v(void 0,!1),setImmediate(N.reverse().reduce(function($,K){return function(ne,Z){if(ne||Z===!1)return setImmediate($,ne,!1);I.addLocalFileAsync({localPath:K,zipPath:ye.dirname(b(K)),zipName:C(K)},$)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(k,D)=>{k&&A(k),D&&I(this)})})},addFile:function(_,v,I,A){_=h(_);let k=x(_),D=k!=null;D||(k=new Nm(i),k.entryName=_),k.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(k.header.time=A.mtime);var C=k.isDirectory?16:0;let O=k.isDirectory?16384:32768;return b?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=k.isDirectory?493:420,C=(C|O<<16)>>>0,k.attr=C,k.setData(v),D||a.setEntry(k),k},getEntries:function(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,v,I,A,k,D){A=On(!1,A),k=On(!1,k),I=On(!0,I),D=xu(k,D);var b=x(_);if(!b)throw Ee.Errors.NO_ENTRY();var C=d(b.entryName),O=u(v,D&&!b.isDirectory?D:I?C:ye.basename(C));if(b.isDirectory){var B=a.getEntryChildren(b);return B.forEach(function(K){if(K.isDirectory)return;var ne=K.getData();if(!ne)throw Ee.Errors.CANT_EXTRACT_FILE();var Z=d(K.entryName),ie=u(v,I?Z:ye.basename(Z));let oe=k?K.header.fileAttr:void 0;o.writeFileTo(ie,ne,A,oe)}),!0}var N=b.getData(a.password);if(!N)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Ee.Errors.CANT_OVERRIDE();let $=k?_.header.fileAttr:void 0;return o.writeFileTo(O,N,A,$),!0},test:function(_){if(!a)return!1;for(var v in a.entries)try{if(v.isDirectory)continue;var I=a.entries[v].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,v,I,A){if(I=On(!1,I),A=xu(I,A),v=On(!1,v),!a)throw Ee.Errors.NO_ZIP();a.entries.forEach(function(k){var D=u(_,d(k.entryName));if(k.isDirectory){o.makeDir(D);return}var b=k.getData(A);if(!b)throw Ee.Errors.CANT_EXTRACT_FILE();let C=I?k.header.fileAttr:void 0;o.writeFileTo(D,b,v,C);try{o.fs.utimesSync(D,k.header.time,k.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,A){if(A=Bm(v,I,A),I=On(!1,I),v=On(!1,v),!A)return new Promise((O,B)=>{this.extractAllToAsync(_,v,I,function(N){N?B(N):O(this)})});if(!a){A(Ee.Errors.NO_ZIP());return}_=ye.resolve(_);let k=O=>u(_,ye.normalize(d(O.entryName))),D=(O,B)=>new Error(O+': "'+B+'"'),b=[],C=[];a.entries.forEach(O=>{O.isDirectory?b.push(O):C.push(O)});for(let O of b){let B=k(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(D("Unable to create folder",B))}}C.reverse().reduce(function(O,B){return function(N){if(N)O(N);else{let $=ye.normalize(d(B.entryName)),K=u(_,$);B.getDataAsync(function(ne,Z){if(Z)O(Z);else if(!ne)O(Ee.Errors.CANT_EXTRACT_FILE());else{let ie=I?B.header.fileAttr:void 0;o.writeFileToAsync(K,ne,v,ie,function(oe){oe||O(D("Unable to write file",K)),o.fs.utimes(K,B.header.time,B.header.time,function(R){R?O(D("Unable to set times",K)):O()})})}})}}},A)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=a.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((k,D)=>{!_&&i.filename&&(_=i.filename),_||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let C=O=>O?k(O):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,I,A,C)},D)})},toBufferPromise:function(){return new Promise((_,v)=>{a.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,A){return typeof _=="function"?(a.toAsyncBuffer(_,v,I,A),null):a.compressToBuffer()}}}});import{execFile as j_,spawn as W_,spawnSync as W2}from"node:child_process";import{promisify as K_}from"node:util";function V_(t){if(process.platform!=="win32")return!1;if(Mf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Mf,"").toLowerCase();return $_.has(r)}function Bf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return V_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function rt(t,e=[],r={}){return W_(t,e,Bf(t,r))}function Ff(t,e=[],r={}){return J_(t,e,Bf(t,r))}var $_,Mf,J_,Jt=Qe(()=>{"use strict";$_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Mf=/\.(cmd|bat|ps1)$/i;J_=K_(j_)});var Zt=ae((DR,Ah)=>{"use strict";var Sh=["nodebuffer","arraybuffer","fragments"],Ih=typeof Blob<"u";Ih&&Sh.push("blob");Ah.exports={BINARY_TYPES:Sh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ih,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $i=ae((OR,Co)=>{"use strict";var{EMPTY_BUFFER:Ob}=Zt(),gd=Buffer[Symbol.species];function Lb(t,e){if(t.length===0)return Ob;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let a=t[o];r.set(a,i),i+=a.length}return i<e?new gd(r.buffer,r.byteOffset,i):r}function Th(t,e,r,i,o){for(let a=0;a<o;a++)r[i+a]=t[a]^e[a&3]}function kh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Nb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function md(t){if(md.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new gd(t):ArrayBuffer.isView(t)?e=new gd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),md.readOnly=!1),e}Co.exports={concat:Lb,mask:Th,toArrayBuffer:Nb,toBuffer:md,unmask:kh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=le("bufferutil");Co.exports.mask=function(e,r,i,o,a){a<48?Th(e,r,i,o,a):t.mask(e,r,i,o,a)},Co.exports.unmask=function(e,r){e.length<32?kh(e,r):t.unmask(e,r)}}catch{}});var Ph=ae((LR,Rh)=>{"use strict";var Ch=Symbol("kDone"),wd=Symbol("kRun"),_d=class{constructor(e){this[Ch]=()=>{this.pending--,this[wd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wd]()}[wd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ch])}}};Rh.exports=_d});var Ur=ae((NR,Nh)=>{"use strict";var Vi=le("zlib"),Dh=$i(),Mb=Ph(),{kStatusCode:Oh}=Zt(),Bb=Buffer[Symbol.species],Fb=Buffer.from([0,0,255,255]),Po=Symbol("permessage-deflate"),Xt=Symbol("total-length"),Fr=Symbol("callback"),kn=Symbol("buffers"),zr=Symbol("error"),Ro,yd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ro){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ro=new Mb(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[Fr];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 a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){Ro.add(o=>{this._decompress(e,r,(a,d)=>{o(),i(a,d)})})}compress(e,r,i){Ro.add(o=>{this._compress(e,r,(a,d)=>{o(),i(a,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Po]=this,this._inflate[Xt]=0,this._inflate[kn]=[],this._inflate.on("error",Ub),this._inflate.on("data",Lh)}this._inflate[Fr]=i,this._inflate.write(e),r&&this._inflate.write(Fb),this._inflate.flush(()=>{let a=this._inflate[zr];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Dh.concat(this._inflate[kn],this._inflate[Xt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Xt]=0,this._inflate[kn]=[],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 a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Xt]=0,this._deflate[kn]=[],this._deflate.on("data",zb)}this._deflate[Fr]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Dh.concat(this._deflate[kn],this._deflate[Xt]);r&&(a=new Bb(a.buffer,a.byteOffset,a.length-4)),this._deflate[Fr]=null,this._deflate[Xt]=0,this._deflate[kn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};Nh.exports=yd;function zb(t){this[kn].push(t),this[Xt]+=t.length}function Lh(t){if(this[Xt]+=t.length,this[Po]._maxPayload<1||this[Xt]<=this[Po]._maxPayload){this[kn].push(t);return}this[zr]=new RangeError("Max payload size exceeded"),this[zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[zr][Oh]=1009,this.removeListener("data",Lh),this.reset()}function Ub(t){if(this[Po]._inflate=null,this[zr]){this[Fr](this[zr]);return}t[Oh]=1007,this[Fr](t)}});var qr=ae((MR,Do)=>{"use strict";var{isUtf8:Mh}=le("buffer"),{hasBlob:qb}=Zt(),Gb=[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 Hb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ed(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 jb(t){return qb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Do.exports={isBlob:jb,isValidStatusCode:Hb,isValidUTF8:Ed,tokenChars:Gb};if(Mh)Do.exports.isValidUTF8=function(t){return t.length<24?Ed(t):Mh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=le("utf-8-validate");Do.exports.isValidUTF8=function(e){return e.length<32?Ed(e):t(e)}}catch{}});var Ad=ae((BR,Hh)=>{"use strict";var{Writable:Wb}=le("stream"),Bh=Ur(),{BINARY_TYPES:Kb,EMPTY_BUFFER:Fh,kStatusCode:$b,kWebSocket:Vb}=Zt(),{concat:bd,toArrayBuffer:Jb,unmask:Yb}=$i(),{isValidStatusCode:Zb,isValidUTF8:zh}=qr(),Oo=Buffer[Symbol.species],ft=0,Uh=1,qh=2,Gh=3,vd=4,Sd=5,Lo=6,Id=class extends Wb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Kb[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[Vb]=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,r,i){if(this._opcode===8&&this._state==ft)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 Oo(i.buffer,i.byteOffset+e,i.length-e),new Oo(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 Oo(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 ft:this.getInfo(e);break;case Uh:this.getPayloadLength16(e);break;case qh:this.getPayloadLength64(e);break;case Gh:this.getMask();break;case vd:this.getData(e);break;case Sd:case Lo: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[Bh.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=Uh:this._payloadLength===127?this._state=qh: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=Gh:this._state=vd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vd}getData(e){let r=Fh;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&&Yb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Sd,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[Bh.extensionName].decompress(e,this._fin,(o,a)=>{if(o)return r(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");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(a)}this.dataMessage(r),this._state===ft&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ft;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=bd(i,r):this._binaryType==="arraybuffer"?o=Jb(bd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ft):(this._state=Lo,setImmediate(()=>{this.emit("message",o,!0),this._state=ft,this.startLoop(e)}))}else{let o=bd(i,r);if(!this._skipUTF8Validation&&!zh(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===Sd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ft):(this._state=Lo,setImmediate(()=>{this.emit("message",o,!1),this._state=ft,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Fh),this.end();else{let i=e.readUInt16BE(0);if(!Zb(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(a);return}let o=new Oo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zh(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(a);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=Lo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ft,this.startLoop(r)}))}createError(e,r,i,o,a){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(d,this.createError),d.code=a,d[$b]=o,d}};Hh.exports=Id});var Cd=ae((zR,Kh)=>{"use strict";var{Duplex:FR}=le("stream"),{randomFillSync:Xb}=le("crypto"),{types:{isUint8Array:Qb}}=le("util"),jh=Ur(),{EMPTY_BUFFER:ev,kWebSocket:tv,NOOP:nv}=Zt(),{isBlob:Gr,isValidStatusCode:rv}=qr(),{mask:Wh,toBuffer:Jn}=$i(),ht=Symbol("kByteLength"),iv=Buffer.alloc(4),No=8*1024,Yn,Hr=No,St=0,sv=1,ov=2,Td=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=St,this.onerror=nv,this[tv]=void 0}static frame(e,r){let i,o=!1,a=2,d=!1;r.mask&&(i=r.maskBuffer||iv,r.generateMask?r.generateMask(i):(Hr===No&&(Yn===void 0&&(Yn=Buffer.alloc(No)),Xb(Yn,0,No),Hr=0),i[0]=Yn[Hr++],i[1]=Yn[Hr++],i[2]=Yn[Hr++],i[3]=Yn[Hr++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!r.mask||d)&&r[ht]!==void 0?u=r[ht]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let h=u;u>=65536?(a+=8,h=127):u>125&&(a+=2,h=126);let x=Buffer.allocUnsafe(o?u+a:a);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:o?(Wh(e,i,x,a,u),[x]):(Wh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let a;if(e===void 0)a=ev;else{if(typeof e!="number"||!rv(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)a=Buffer.allocUnsafe(2),a.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(a=Buffer.allocUnsafe(2+u),a.writeUInt16BE(e,0),typeof r=="string")a.write(r,2);else if(Qb(r))a.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[ht]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,a,!1,d,o]):this.sendFrame(t.frame(a,d),o)}ping(e,r,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Gr(e)?(o=e.size,a=!1):(e=Jn(e),o=e.length,a=Jn.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:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==St?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Gr(e)?(o=e.size,a=!1):(e=Jn(e),o=e.length,a=Jn.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:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==St?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[jh.extensionName],a=r.binary?2:1,d=r.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Gr(e)?(u=e.size,h=!1):(e=Jn(e),u=e.length,h=Jn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,a=0),r.fin&&(this._firstFragment=!0);let x={[ht]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:h,rsv1:d};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==St?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[ht],this._state=ov,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(kd,this,u,o);return}this._bufferedBytes-=i[ht];let d=Jn(a);r?this.dispatch(d,r,i,o):(this._state=St,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(av,this,a,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[jh.extensionName];this._bufferedBytes+=i[ht],this._state=sv,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");kd(this,h,o);return}this._bufferedBytes-=i[ht],this._state=St,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===St&&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,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)}};Kh.exports=Td;function kd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],a=o[o.length-1];typeof a=="function"&&a(e)}}function av(t,e,r){kd(t,e,r),t.onerror(e)}});var tx=ae((UR,ex)=>{"use strict";var{kForOnEventAttribute:Ji,kListener:Rd}=Zt(),$h=Symbol("kCode"),Vh=Symbol("kData"),Jh=Symbol("kError"),Yh=Symbol("kMessage"),Zh=Symbol("kReason"),jr=Symbol("kTarget"),Xh=Symbol("kType"),Qh=Symbol("kWasClean"),Qt=class{constructor(e){this[jr]=null,this[Xh]=e}get target(){return this[jr]}get type(){return this[Xh]}};Object.defineProperty(Qt.prototype,"target",{enumerable:!0});Object.defineProperty(Qt.prototype,"type",{enumerable:!0});var Zn=class extends Qt{constructor(e,r={}){super(e),this[$h]=r.code===void 0?0:r.code,this[Zh]=r.reason===void 0?"":r.reason,this[Qh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[$h]}get reason(){return this[Zh]}get wasClean(){return this[Qh]}};Object.defineProperty(Zn.prototype,"code",{enumerable:!0});Object.defineProperty(Zn.prototype,"reason",{enumerable:!0});Object.defineProperty(Zn.prototype,"wasClean",{enumerable:!0});var Wr=class extends Qt{constructor(e,r={}){super(e),this[Jh]=r.error===void 0?null:r.error,this[Yh]=r.message===void 0?"":r.message}get error(){return this[Jh]}get message(){return this[Yh]}};Object.defineProperty(Wr.prototype,"error",{enumerable:!0});Object.defineProperty(Wr.prototype,"message",{enumerable:!0});var Yi=class extends Qt{constructor(e,r={}){super(e),this[Vh]=r.data===void 0?null:r.data}get data(){return this[Vh]}};Object.defineProperty(Yi.prototype,"data",{enumerable:!0});var cv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Ji]&&o[Rd]===e&&!o[Ji])return;let i;if(t==="message")i=function(a,d){let u=new Yi("message",{data:d?a:a.toString()});u[jr]=this,Mo(e,this,u)};else if(t==="close")i=function(a,d){let u=new Zn("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[jr]=this,Mo(e,this,u)};else if(t==="error")i=function(a){let d=new Wr("error",{error:a,message:a.message});d[jr]=this,Mo(e,this,d)};else if(t==="open")i=function(){let a=new Qt("open");a[jr]=this,Mo(e,this,a)};else return;i[Ji]=!!r[Ji],i[Rd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Rd]===e&&!r[Ji]){this.removeListener(t,r);break}}};ex.exports={CloseEvent:Zn,ErrorEvent:Wr,Event:Qt,EventTarget:cv,MessageEvent:Yi};function Mo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Bo=ae((qR,nx)=>{"use strict";var{tokenChars:Zi}=qr();function Bt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function dv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,a=!1,d,u,h=-1,x=-1,g=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(g===-1&&Zi[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let _=t.slice(h,g);x===44?(Bt(e,_,r),r=Object.create(null)):d=_,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(g===-1&&Zi[x]===1)h===-1&&(h=w);else if(x===32||x===9)g===-1&&h!==-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w),Bt(r,t.slice(h,g),!0),x===44&&(Bt(e,d,r),r=Object.create(null),d=void 0),h=g=-1}else if(x===61&&h!==-1&&g===-1)u=t.slice(h,w),h=g=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(Zi[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),o=!1}else if(a)if(Zi[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)a=!1,g=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)a=!0;else if(g===-1&&Zi[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))g===-1&&(g=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let _=t.slice(h,g);i&&(_=_.replace(/\\/g,""),i=!1),Bt(r,u,_),x===44&&(Bt(e,d,r),r=Object.create(null),d=void 0),u=void 0,h=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=w);let S=t.slice(h,g);return d===void 0?Bt(e,S,r):(u===void 0?Bt(r,S,!0):i?Bt(r,u,S.replace(/\\/g,"")):Bt(r,u,S),Bt(e,d,r)),e}function lv(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 a=i[o];return Array.isArray(a)||(a=[a]),a.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}nx.exports={format:lv,parse:dv}});var qo=ae((jR,xx)=>{"use strict";var uv=le("events"),fv=le("https"),hv=le("http"),sx=le("net"),xv=le("tls"),{randomBytes:pv,createHash:gv}=le("crypto"),{Duplex:GR,Readable:HR}=le("stream"),{URL:Pd}=le("url"),Cn=Ur(),mv=Ad(),wv=Cd(),{isBlob:_v}=qr(),{BINARY_TYPES:rx,CLOSE_TIMEOUT:yv,EMPTY_BUFFER:Fo,GUID:Ev,kForOnEventAttribute:Dd,kListener:bv,kStatusCode:vv,kWebSocket:He,NOOP:ox}=Zt(),{EventTarget:{addEventListener:Sv,removeEventListener:Iv}}=tx(),{format:Av,parse:Tv}=Bo(),{toBuffer:kv}=$i(),ax=Symbol("kAborted"),Od=[8,13],en=["CONNECTING","OPEN","CLOSING","CLOSED"],Cv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends uv{constructor(e,r,i){super(),this._binaryType=rx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fo,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]),cx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){rx.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 mv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new wv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[He]=this,a[He]=this,e[He]=this,o.on("conclude",Dv),o.on("drain",Ov),o.on("error",Lv),o.on("message",Nv),o.on("ping",Mv),o.on("pong",Bv),a.onerror=Fv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",ux),e.on("data",Uo),e.on("end",fx),e.on("error",hx),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){at(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())}),lx(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){Ld(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Fo,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){Ld(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Fo,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){Ld(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||Fo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:en.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:en.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:en.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:en.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:en.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:en.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Dd])return e[bv];return null},set(e){for(let r of this.listeners(t))if(r[Dd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Dd]:!0})}})});me.prototype.addEventListener=Sv;me.prototype.removeEventListener=Iv;xx.exports=me;function cx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:yv,protocolVersion:Od[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,!Od.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Od.join(", ")})`);let a;if(e instanceof Pd)a=e;else try{a=new Pd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),t._url=a.href;let d=a.protocol==="wss:",u=a.protocol==="ws+unix:",h;if(a.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?h="The URL's pathname is empty":a.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;zo(t,I);return}let x=d?443:80,g=pv(16).toString("base64"),w=d?fv.request:hv.request,S=new Set,_;if(o.createConnection=o.createConnection||(d?Pv:Rv),o.defaultPort=o.defaultPort||x,o.port=a.port||x,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Cn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Av({[Cn.extensionName]:_.offer()})),r.length){for(let I of r){if(typeof I!="string"||!Cv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.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),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,k]of Object.entries(I))i.headers[A.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),v=t._req=w(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=w(o);o.timeout&&v.on("timeout",()=>{at(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[ax]||(v=t._req=null,zo(t,I))}),v.on("response",I=>{let A=I.headers.location,k=I.statusCode;if(A&&o.followRedirects&&k>=300&&k<400){if(++t._redirects>o.maxRedirects){at(t,v,"Maximum redirects exceeded");return}v.abort();let D;try{D=new Pd(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);zo(t,C);return}cx(t,D,r,i)}else t.emit("unexpected-response",v,I)||at(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,k)=>{if(t.emit("upgrade",I),t.readyState!==me.CONNECTING)return;v=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){at(t,A,"Invalid Upgrade header");return}let b=gv("sha1").update(g+Ev).digest("base64");if(I.headers["sec-websocket-accept"]!==b){at(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],O;if(C!==void 0?S.size?S.has(C)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){at(t,A,O);return}C&&(t._protocol=C);let B=I.headers["sec-websocket-extensions"];if(B!==void 0){if(!_){at(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=Tv(B)}catch{at(t,A,"Invalid Sec-WebSocket-Extensions header");return}let $=Object.keys(N);if($.length!==1||$[0]!==Cn.extensionName){at(t,A,"Server indicated an extension that was not requested");return}try{_.accept(N[Cn.extensionName])}catch{at(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cn.extensionName]=_}t.setSocket(A,k,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function zo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Rv(t){return t.path=t.socketPath,sx.connect(t)}function Pv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=sx.isIP(t.host)?"":t.host),xv.connect(t)}function at(t,e,r){t._readyState=me.CLOSING;let i=new Error(r);Error.captureStackTrace(i,at),e.setHeader?(e[ax]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(zo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ld(t,e,r){if(e){let i=_v(e)?e.size:kv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${en[t.readyState]})`);process.nextTick(r,i)}}function Dv(t,e){let r=this[He];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[He]!==void 0&&(r._socket.removeListener("data",Uo),process.nextTick(dx,r._socket),t===1005?r.close():r.close(t,e))}function Ov(){let t=this[He];t.isPaused||t._socket.resume()}function Lv(t){let e=this[He];e._socket[He]!==void 0&&(e._socket.removeListener("data",Uo),process.nextTick(dx,e._socket),e.close(t[vv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ix(){this[He].emitClose()}function Nv(t,e){this[He].emit("message",t,e)}function Mv(t){let e=this[He];e._autoPong&&e.pong(t,!this._isServer,ox),e.emit("ping",t)}function Bv(t){this[He].emit("pong",t)}function dx(t){t.resume()}function Fv(t){let e=this[He];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,lx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function lx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ux(){let t=this[He];if(this.removeListener("close",ux),this.removeListener("data",Uo),this.removeListener("end",fx),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[He]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ix),t._receiver.on("finish",ix))}function Uo(t){this[He]._receiver.write(t)||this.pause()}function fx(){let t=this[He];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function hx(){let t=this[He];this.removeListener("error",hx),this.on("error",ox),t&&(t._readyState=me.CLOSING,this.destroy())}});var _x=ae((KR,mx)=>{"use strict";var WR=qo(),{Duplex:zv}=le("stream");function px(t){t.emit("close")}function Uv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function gx(t){this.removeListener("error",gx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function qv(t,e){let r=!0,i=new zv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let u=!d&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(r=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,a){if(t.readyState===t.CLOSED){a(o),process.nextTick(px,i);return}let d=!1;t.once("error",function(h){d=!0,a(h)}),t.once("close",function(){d||a(o),process.nextTick(px,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,a,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,a,d)});return}t.send(o,d)},i.on("end",Uv),i.on("error",gx),i}mx.exports=qv});var Nd=ae(($R,yx)=>{"use strict";var{tokenChars:Gv}=qr();function Hv(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&&Gv[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 a=t.slice(r,o);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}yx.exports={parse:Hv}});var Tx=ae((JR,Ax)=>{"use strict";var jv=le("events"),Go=le("http"),{Duplex:VR}=le("stream"),{createHash:Wv}=le("crypto"),Ex=Bo(),Xn=Ur(),Kv=Nd(),$v=qo(),{CLOSE_TIMEOUT:Vv,GUID:Jv,kWebSocket:Yv}=Zt(),Zv=/^[+/0-9A-Za-z]{22}==$/,bx=0,vx=1,Ix=2,Md=class extends jv{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:Vv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:$v,...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=Go.createServer((i,o)=>{let a=Go.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=Xv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,a,d)=>{this.handleUpgrade(o,a,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=bx}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===Ix){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xi,this);return}if(e&&this.once("close",e),this._state!==vx)if(this._state=vx,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(Xi,this):process.nextTick(Xi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Xi(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",Sx);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Qn(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){Qn(this,e,r,400,"Invalid Upgrade header");return}if(a===void 0||!Zv.test(a)){Qn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Qn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qi(r,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=Kv.parse(h)}catch{Qn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&g!==void 0){let S=new Xn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Ex.parse(g);_[Xn.extensionName]&&(S.accept(_[Xn.extensionName]),w[Xn.extensionName]=S)}catch{Qn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(_,v,I,A)=>{if(!_)return Qi(r,v||401,I,A);this.completeUpgrade(w,a,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return Qi(r,401)}this.completeUpgrade(w,a,x,e,r,i,o)}completeUpgrade(e,r,i,o,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[Yv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>bx)return Qi(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Wv("sha1").update(r+Jv).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),g._protocol=w)}if(e[Xn.extensionName]){let w=e[Xn.extensionName].params,S=Ex.format({[Xn.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",x,o),a.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Sx),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(Xi,this)})),u(g,o)}};Ax.exports=Md;function Kv(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 Xi(t){t._state=Ix,t.emit("close")}function Sx(){this.destroy()}function Qi(t,e,r,i){r=r||Go.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} ${Go.STATUS_CODES[e]}\r
16
+ `)),a.removeListener("error",Sx),g.setSocket(a,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(Xi,this)})),u(g,o)}};Ax.exports=Md;function Xv(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 Xi(t){t._state=Ix,t.emit("close")}function Sx(){this.destroy()}function Qi(t,e,r,i){r=r||Go.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} ${Go.STATUS_CODES[e]}\r
17
17
  `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+r)}function Qn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,Qn),t.emit("wsClientError",d,r,e)}else Qi(r,i,o,c)}});var Ux=ce(ze=>{"use strict";var M=H;(function(t,e){let r=H,i=t();for(;;)try{if(-parseInt(r(609))/1+-parseInt(r(214))/2*(-parseInt(r(152))/3)+-parseInt(r(1330))/4*(parseInt(r(565))/5)+-parseInt(r(833))/6*(-parseInt(r(1375))/7)+parseInt(r(1261))/8+-parseInt(r(1117))/9+-parseInt(r(963))/10===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Ko,841012);var e1=Object["definePr"+M(215)],t1=Object[M(1536)+M(1232)+M(1074)],Nx=(t,e)=>function(){return t&&(e=(0,t[t1(t)[0]])(t=0)),e},n1=(t,e)=>{let r={dVBqy:function(o,c,d,u){return o(c,d,u)}};for(var i in e)r.dVBqy(e1,t,i,{get:e[i],enumerable:!0})};function Ko(){let t=["CM92AwrLige","y3jLyxrLrxi","yw5Hz2vY","C2v0y3vYC28","uffTENq","rKL1rKK","qwv2yNK","yM9L","B0XUu3G","sfDUB0K","DcbSAw1PDa","ywXty29Wzq","v3DQs1C","uffdALm","C1nZuw4","zM9YrwfJAa","yMLUyxj5","A3rVDxK","EMvzCfG","DwrSBNm","u2HHCMvKv28","zxq9DxrMltG","CgzYCwK","ihn1y2nLC3m","BIWGAg9ZDg4","Aw9UvgLTzw8","t3jkANK","mdaWmdaWmda","B3jL","vLzKD2y","Aw9Ul2PZB24","EwXcy0W","D3m6lY8","wKTPDfK","CvHXDui","CKToCxm","DMLJzuLeig8","tuf5D0C","B2zMBgLUzq","AufoAem","Bg93","uLb1BvG","AvfWB2u","oti2ogXruK9qEa","B2HSu0i","zgvIDwC","y3vYCMvUDeu","qw1VDw50","x2rLC3rYB3K","DujKzu4","uevVC3a","u1z3AhK","z0vjz0i","CLrWrLa","vfjODwq","rvPKsfa","u1Ptr1q","tK9xC28","yxGGCMv0CMK","uKjUyM8","r0P5q0G","u3ffBxu","rxjYB3jdB2q","ENLYz2i","B25mAw5L","sK5eu0C","BwnyBNu","Ahr0Chm6","Au1by1u","zM5uEu4","yxKSig5LDhC","yNHyChu","ywnOzwq","reTutha","zLj6y3O","zMzKsve","y2fSBa","zMzPqKu","rLbrv2y","zwT5swO","ywDL","y29Uy2f0","CMvZzxrdB3u","zg9Uzq","t1bftG","AgvKtwf4uMu","sM5cugK","sMjytva","mJa0odL2qxHHugi","Aw5N","y3vnDNO","rfLvCfy","x2nSzwfYvgK","ihrPBwvVDxq","B3jRzxjhBg8","DLnIAMC","v0LItw4","s0XVu0i","s3bctxa","sMT2vwm","AgjxDMi","l3DZl3yY","A3vuy08","qxDzwfu","DMfSDwu","yxbWBgLJyxq","AMfjuMm","z2vtEw5J","x2HHBMrSzu8","x3bPBMDqB24","Cujntwy","Dg9cExrLCW","zxj2AwnL","EwHOwNu","q2z2vKm","sKDAAfG","ENjSreW","BfjizuG","zw5HyMXLqxu","y3jLyxrLuMu","u2vXsuq","A2L5zxG","vgnVswO","Ec1TC2CTCw8","ChjVDg9JB2W","Bu5qzfG","renjENq","ohWXFdj8m3W","DgfYz2v0","Aw5KzxHpzG","EhPxqK0","A3jfs1q","EM5VvLy","vK9RwuO","B01pvfG","Ce9iENy","ruvKBxy","DhjPzxm","x1fVu01HBMe","tfDbs2C","vg1vsKS","yu1kDMe","q25juvq","y29UBMvJDca","BvLmwfq","B3jeAKy","sezkEfa","BMrWB2LUDca","AxPWzxa","Bgzev2S","seLorMy","zNLXD0C","x29UugfNzu4","y0vXB2W","x29UtwvZC2e","rLjptLrjrvi","CKXwt2O","Eunotfe","C2HPzNq","z2vjBMzVu3K","r0jquhC","qxfTyMy","De1YEuq","CgLzuvq","senxz3K","yMXVy2TLza","yKfyDMS","wu1KuNa","vLrkyuy","vLD6A08","Ae9Wzw5fDMu","x3bYzwzPEa","q25gAK8","sNH1wgi","r05orNG","wKzAsw4","vKLAzgu","rxrPzvO","C1Pktu4","zxH0zw5ZAw8","DhbzCKe","D0LJBuy","CgjgtuO","zu9Rr3a","yxv0B21HDgK","B25nzxnZywC","BgLTAxq","rLbTCKW","ChvZAa","DgvZDa","tfj5twK","ANftyuu","B25pCgvU","C3bSAxq","tuvtu0fhrv8","DwznD3a","uM14CNC","icSG","z2vY","rwzht1C","yLPTveC","EKL0suq","BM93","q09otKvdveK","yMnfyMy","A2DJAwu","D3zsBhC","sKHPuKm","zLL1wwu","CKnnAhy","wffpq08","twvZC2fNzuu","tfr2uKy","ruTntwC","D2LSBfjLy28","z2u6ia","q29Kzq","B3jpBMXPBMu","zMLUza","ufHWBKm","rgvKAwnHDgu","z2vnyMm","x3bYB3rVy28","yKnlAhm","DgnbEuS","zMLN","whvJAxm","uK9Tzem","AwXLx25HBwu","EKXYufO","v3bWvvm","D0PHuuy","ALjrEvK","A1zmBwi","CYbWyxjHBxm","DgLUzYbZzxi","qufgsvC","vufTyLK","zw5HyMXLvhi","BwfUDwfSihi","y2XLyxjtDg8","yxrLq291BNq","zwTTEM8","rM9kBMy","C0nur3q","y2HnyxHdB3u","D2fZq2XLyw4","m3WWFdj8mxW","B25VCgvU","z2v0t3DUuhi","zxf1ywXZ","y29UBMvJDgK","DwvIAee","D3jPDgu","v1bSrhG","C2vUzf9Hy2S","zNjVBu51Bwi","ugLlwfq","BNvTyMvY","C3rVCMu","CYbPBNn0yw4","C2nYAxb0","rNPRswG","t2PPuwy","BgvdCuG","AxbxCwK","rKfbyw4","zfDVCMTLCKC","qKH5why","ChbL","DxzIEeS","tKvzsvO","BwfnwLi","ywDLrxzLBNq","ywrKq291BNq","u25dD2W","tuHMEuW","AgLNAa","rgPSsNC","CMvHzfvjBNq","qMT4yLe","CNnVCL92ywW","q09fww0","EMr6r3m","Cu1yBNu","uuPTtha","AwXLtMfTzq","uwzAAvu","tLDHBvG","Cgf5Bg9Hzeu","yMHdqKm","z0zZt04","u0Xbq0C","B012t00","CM92AwrLihy","t2zlv0K","AwXSihvZzsa","qKfRC3G","zK15yum","y3r4","y29UC3rYDwm","C3rLBMvYCW","y29TCgXLDgu","ELnxzMS","rxzztgO","sen4B1y","v0LbsNe","zxncqMi","AwDHDg9Yt24","BM9Uzv9UB24","twzeAMC","ywX3yxLZ","zKfRveC","EKfntei","ywWGy3vYC28","v1bSwK4","y29UBMvJDa","vePZy3a","Dg9tDhjPBMC","oxWXmhWXmxW","y3ruAw1LB3u","wuHur2K","y2jZC2u","igzHAwWSig0","uM9OtNO","DuH0tNK","D24GCMvHC28","vu1zr0C","x21PBMLoyxy","id4G","Cg9W","AezquMm","t2v1DMm","BgvY","Efrurw52","x3bPBMDmB3m","DwjXBwy","x2zVCM1HDeu","wefvyuu","DxrVuMvJB24","y3Duuu8","zw5KCg9PBNq","yw1L","y29UBMvJDeu","wMvjEMK","CMv0CNLdB3u","s29Pq3i","B3vUDa","AgvHzgvYCW","C0Peqxe","r05uuwW","CMPuyvm","sMn1D2G","senvr28","qvv2q0q","vwjmyNK","rMX4z2q","Cwzkr0y","svbOyxq","AMXRsfO","CKLXAuS","s0zHCeO","mxWWFdr8nxW","C21bvui","yNL0zuXLBMC","rNzLCfm","Axnby2TdBgu","AwPQAu4","Be9Atuu","zwnVBM5Ly3q","Aw5Lza","EKLfvvO","AevYCM9Yrxy","tNDLthi","DgfIyxnL","t2XPywi","z2v0u3rVCMe","BLfKzgq","x0vysvnu","y09Wzw4","wgXvrxy","CM9YrxzLBNq","AxnmB25N","yw5ZzM9YBvq","Bu9HshC","swnSwKC","B3nLza","Dg9iyxnO","BLrOwfi","Bwv0Ag9K","tKPtB0e","wunoq28","s2DzBu0","twLZC2LUzYa","sgzWuuq","vu1cA0W","DNbZquW","vu1VCxe","Aw5PDcbrB1m","C0DRu1q","y2XVC2veqG","svDlvvq","z1jbq1y","EK5RyNe","ELDfEeS","BgPcCNu","x3bHDgHlzxK","CK52sgu","zxjFBxnNAwq","AMj1A2q","zNjVBuj5Dgu","B2fK","tgffz2q","t1vnv3O","zw1PDa","C2vYDMLJzq","Dg1hDgC","ze1TtM0","B3bLBKrc","otbRrhbttKi","DfvdCg8","su5Yr2y","y3vYC29Yx2y","x3nVy2TLDa","B25ozxr3B3i","vxPgufy","C0TABwy","BNrbBMrvCgq","qLHMz2O","zw5fDMvUDa","nhWW","yM9tEhK","re9vDwK","r09Azfi","rMvdDxq","AePftwG","BwvZC2fNzv8","qwfyr0m","tKDxtwG","uhDrzei","z2v0qwXSs2u","C25yA3G","zgLdyvK","t1bftL9fuLi","x25HDMLNyxq","rxHKq2S","rwreBe8","igzPzwXKoIa","zeHMy1m","reL5Dve","CwnLrw8","tKfusvzfx0u","C21bCeW","B25szwnLAxy","vvH0wK8","z090sxO","uMvhAKi","DxvIyNq","zgvSzxrL","uefNBgi","Defyzxe","yxv0BW","BKTpz0C","BNrLCG","Dg9cExrLC0i","AgfZ","ANjAvwW","DMTjAfq","BKnPyuG","AevKtfe","q0Xpu0ve","ALnJAxa","wxj0CLK","vgXtDwy","Cg93","y3vYC29Y","zuzPB3G","zhj2vhq","CLHWuKC","x3DZ","y2vZC0HHBMq","nta2otHMswz1C1a","B3bLCNr5","x2LZtwLUAvq","tg9Nsuq","yvrKBwi","x2nYzwf0zvm","ChjVDg90Exa","DgHHBIbSB2m","qMXKDvm","zvjiv3i","vLfhD2S","sfrfA3a","BgDPEMe","BM5Ly3q","EvjLy29UBMu","BNruCMLLC0m","zMDcz2e","wMLAA2u","v0HMzwe","r0PAzNi","ExvgC0O","BMvJDa","yw1Lu3bHy2u","B25tDg9Wsw0","z1rPBwvVDxq","uNPUAvi","A213CNK","Bwu6ia","u0PRD0y","CMvZzxruCMK","z2v0q3vYCMu","x2TLEvbHDgG","yMLUyxj5vhK","zwrPyxrLBhK","BMCGDxjSoIa","vfD0AMi","yxzrue0","s2THuKi","zwzJCfa","B2nRzxq","DKHAANC","BuDQEwu","tMfbzLe","AgDNqxu","yvHvtMy","Dhr3Awq","yNL0zxm","CgLUz0LUDgu","Axn1rLG","vNrHzMe","Buf3BKq","ihrPBwvZ","yvvXrei","DeLK","B3jLtMfTzxm","y2HHCKnVzgu","CMvWBgfJzq","CMLLC0nVDw4","D29gtuK","DuPnAeS","DuTyyMC","Dxf1DKu","zurqzNC","yvHou0e","reiGzMfPBgu","ywXSB2nvBNm","yMLUza","vezjsfy","rvz2ugC","A3PPBwu","zvvYBa","y0HvwvK","txbUzw8","AxjLza","Bwf4uMv0CMK","zgLZCgf0y2G","D3nZoI8V","zMLSDgvY","yuXlzK4","zunhCwq","qLrlExq","B2nRzxrgywK","Dgv4Dc9WBge","qNjTtNq","v2vPEgLUsLm","vg5eqMe","qwjVCNrfCNi","Bw9cCfa","vvLxwMe","qMTJzxG","r0fwCMu","yMX0B2q","tLD4rgK","zxjFCw9Zx2e","sM1uwui","quTxwe8","qLLeAum","CM92AwrLihC","rxzPyxO","Cu9LB00","CMD5Eve","yNvMzMvYzwq","quPSEwe","DuzLAvC","CgLUz0XVC3m","rwvzq2m","vuvnwMq","Ahr0Ca","ELvttwy","x2LZtwLUAvC","ywXSzwqGBxu","igXHCMDLCIa","qKXqs2u","zurXyLC","DgLTzw91Da","BhrPCgXLihq","s2TeyuG","whrQz0O","yM9KEq","u2vYDMLJzvC","B2jQzwn0u3q","B3bLBIa","zxH0ugf5Bg8","y1L3Evu","rM52wwy","wM1Jsw0","Bxvmq2e","CxL6se8","u2LpD1O","Dgzqs2C","x2nSzwfYugK","tg9NsurozxC","Aw9U","DuDUuum","q2z3tLC","qvLmsLm","twjJBMm","y3jLyxrLt3a","x2HHBMrSzva","De1LvK8","qK1Qu3G","y3vYCMvUDeK","AwLqCuS","CLPuuve","ugXWvg8","DMvUDa","CgLUz09Uy2u","Dg9mB3DLCKm","rxzLBNq","AxPNv1O","r3vdwwe","tfDrBKe","rMToCfu","thHZtMu","y2f0y2G","qK1vwhy","jMPZy2fSBgi","rgnuwwi","vejVqum","uLPZu3O","rNjVBNrPzxi","BMDuAw1LCG","zw5HyMXLuw8","v0TbExO","wwzfseG","Dxrjza","rLrbwMm","AxnszwfKEq","x2LUAxrqCM8","qLzWDhm","AvLTC3e","t2jQzwn0","zwPwwLC","vM9pzhG","AxmGDw5Kzwy","x3jLy29UBMu","C3vIyxjYyxK","v2HdzMG","Axn0tMi","seXlBeO","uM1tt0q","x29UvgLTzw8","CfHssey","shHgrfO","DxnLCKLW","o2nOyxjZzxq","Bg9NsurozxC","B2nRzxrtDwm","BMnoALa","tufyx1jfvfi","x2LUDgvYDMe","DxrMofDYAxq","ueLeteC","C2vYDMLJzs0","EKDHs2m","x3DZsw5ZDge","tg9JAW","zxjFAxnFywm","zLD5C1G","DhjPBq","zu5Hv2O","sLDlrfO","r2v1zhC","ig1LC3nHz2u","BgLUzq","z2v0q3vYC28","u1fwz3K","zMzLCG","z3PqBgy","vhjnuKe","zw5JB2rPBMC","rwrIAhu","tMTIwhy","v1D4ruu","zv9ZDwnJzxm","zxjYtxnN","x2LZv29YA2u","DNjgvhy","B0j1rw4","zNjVBNrPzxi","q21euwi","B3Deqw8","z1j1Bei","EMv1sfy","zw50tgLZDgu","A1Hpu0S","y3DsAuG","x2DLBMvYyxq","wfbmuNu","B25fCNjVCG","y29UDgv4Da","s3vUrLq","nhWZFdj8mxW","y1DIuK4","C3rhBxG","Cgfzuxa","zgf0yq","uurjswq","rMLSDNG","AuDQBhy","AuTSuw4","C0Xf","CMflq2i","rMvOCeu","u0vkrLe","Axvev3i","B2zM","t2f5rgC","DgvmB2Djre4","lcbTyxGGCMu","zNjVBunOyxi","sKDmEve","CgPgExi","C3fyCMu","qMvIwhm","y1ntyLG","CMXcBLK","zu9dtxm","ywjVCNq","DxjjteO","zMzmAw5L","t2TyAxm","ruHvwNy","ywnR","A3PKuxK","AenSB3nLrxy","q0DZCwe","Dg9hzw5LCMe","DhLWzq","y29UBMvJDfm","ugf2B0C","ywDLsgLKzq","zgrjrcWGzgu","Aw1LCYbPBIa","Bg9IywXty28","z3HJD08","zeHprMq","y3zZChy","u3nPB28","Chfxr0i","BvvfAvC","yw51Ce1LC3m","vxrrzNe","x29WDgLVBNm","CLzHBhvLCW","y2XVC2uSihC","y2n6Deu","wLfbEMy","C29YDa","CMHgvva","yxjOq04","rwXcDwW","zxjFCw9Z","Cw9Zx18","DePUDg0","Dxn5twW","swD5uui","C0XPC3rLBMu","zwvzuvy","ywn3D0C","zNjVBujPDhm","ywrKrxzLBNq","q0LvyvC","vvDhru4","EMHqAMW","vw5PBxbSzw0","r2XsAw8","yMPiv1O","DNPOB2y","t0LPALG","ywnRx2LK","AMH5Ewy","AwH0Ehy","D2XQAw8","thj6Dxy","yxnJCMLWDa","De1HBMfNzxi","z2v0","sNnZweq","Dw5ZAwDUzwq","y0DsEge","q0zXtgW","rKv6D2u","B25JBg9Zzq","zxnsBuK","uurLtLi","BwLUAvbYB2C","x21LC3nHz2u","zcWGDw5RBM8","q29Xz1i","v3DVtLm","yxfrB3m","qLDUDuW","se1ns1i","C0jf","BwvY","yxbWBhK","x29Uq2XVC2u","Dg1TuuC","tKDFrvjst1i","twXnq1u","AKrUAhO","BMvLzf9Hy2S","BgLUzw5V","v2zbCLC","wM9bqva","AhPcAfe","Bwf4twvZC2e","sfvLuuu","rfPRzLm","EeniDu0","mJi1nvbfCg1byW","CMPSBvq","Bg9N","x2rPC2nVBM4","qNrpsxO","CYbHBhjLywq","zxjYB3i","ExbL","yxnL","EK9vqu8","qxvprK4","z3zpA1K","vgTju3a","q291BNq","Dw5KzwzPBMu","yMfJA3vWigu","BxnNsuq","uhnvCLq","y3vZDg9Tshq","BMCGB3iGyw4","tNjzyK0","uwTXsxe","CMvJzwL2zwq","BxnN","ue9Rwvq","vxLPBfO","zxjFywnRx20","BNrfBMrWB2K","Dg9cExrLC0W","y0fju3q","AxnrB1nby2S","C2vYDMvYvgK","Dfbhsxq","v1j6Bfu","r3P1seq","venwq3a","zgvJB2rLzey","yMfSrxzLBNq","s3H4qw0","A1DvD0i","DMrPt2e","vKfTEKm","Bvn3CKq","D2PSvxm","nZaZmZjmrLDiA0G","ywXS","wM14EM8","B2fnr24","s2rtvuW","C0XtEhK","vKvXDhi","uMH3zgu","vMvbs0C","yxHfBu4","D0forM0","qu93zKe","uufkDhG","AMvJDfn0B3i","AgjXqNe","CvHYBeO","Axj6vKe","u0TeExa","y2jgs1e","CMvXDwLYzwq","CgzYAva","z1nNzNa","v3nWsvG","s0HAvfi","sKHvENq","rg55A0W","CLHztuG","ru53A0y","CMfUzg9T","zNDZxZeUmc4","Ec1TC2CTy3u","A0LVzvi","ihzHBgLKigq","yKLcCNG","BxHjAMO","Cg9PBNrdB24","C2v0u3rVCMe","B2PuDfm","AhHyBwq","C1jLBeO","EeDRAfi","se1sDhy","D3jPDgvvAw4","D0fWy2S","wxvxy1K","whrhD2O","C3vJy2vZCW","x3jLBw92zvC","y0DYDuu","y29SBM8","re9AAge","vhfUugS","A3jisLK","CMvZB2X2zq","y3vYC29Yx24","Cgz0txC","zvH3Ae8","yvzks2W","weXNq0G","qNfbCvu","vefMr0S","v1jQCxK","ywrK","ywjSquO","B2ftA24","BMzQuhC","BwvZC2fNztO","ru1rBxm","BMfyuuu","A3fey3u","zhPOt1a","EgzgBfu","BMv3vMvYC2K","uhDJsuK","mxW0Fdj8mhW","yNj1z3C","r29RwM0","y2uGBM90igK","uvHHDwC","C3rVCcbPBw0","u2nOzfC","A01Itvm","CfrtrhK","rKz4y0G","rwfZDMu","zgLZywjSzue","A2v5CW","rxfmq0O","DxPhqwS","BwLZzq","BgPdq2u","v1rdzKm","t3bLBKv2zw4","BwLUzW","B0zcz0u","u2XzAMK","C2DPza","B3vhvwi","t2jqA2u","BMnLq2XVC2u","EgPwsNm","BezSDxnO","BKXPBMu","ve9sswq","C2THvwm","CMvHC29U","x2rYB3bhBg8","rLDt","x3jLywr5q2W","re5ntxG","CNjVCK1LC3m","ignVzgu6ia","BgvUz3rO","rMH3tfi","AMLlvgW","vMvvyuG","vw5Oyw5KBgu","vMHyB3q","z3DJq3O","wvnJsNa","x3nLCuLK","EKD0Bu8","y29Kzq","B3nLrxzLBNq","seLYB2W","zwn0","DxjS","CMvQzwn0","zw1LBNq","z0LiD2C","t3zdAwi","z29PBMCGyxC","x2jPBMfYEvq","AM5Mt3y","x19LC01Vzhu","sKv6swW","CMXpq3a","CMvZzxrfBMq","CLryAxe","C3rYAw5N","svDTB0y","s3bsD3O","txDRtwS","zffHuNe","BhHTC3y","zM9Yy2u","wu1Au3C","ihrVihjLDhi","we9WEKS","CeLuvgy","Be1WANq","zxmGCMvHy2G","AgnhwwK","svrvvMS","Cwvjrvq","D0fOu00","A2v0ignVBNm","DNfnCLi","y0Toy3u","r0zywMy","BgvOr20","r011sNa","x29Ut3bLBG","y3jLyxrLtwu","wKLyAue","x3bPBMC","yKntz20","C2vUza","uLjpuG","x2vUzhbVAw4","B2LUDfjLywm","tw9KDwXL","uvv3qui","uMT0v1u","zxHrwNu","ELvbtuq","zMLSzw5HBwu","t09swe8","Dvrps3O","Egv0Bxa","CK9tqw0","sNjrEwq","tKz6qKG","CMvZDwX0","AwrI","tu1MBxe","C3j1vhi","D2vI","A2PQBeC","uef3tw8","tgLZDgvUzxi","z0P3BgS","v2LUzg93","z2L1z0q","wLPlzKu","vMrYquu","t21VCfO","t2LTC3q","Aw5L","yMjzrwK","CIb0DhDjra","zwTowuC","BMv4DcGPigm","DhDVCMTdAge","zw5XDwv1zq","AgvHzgvY","C3vRsfi","tgTPCwS","shbKuvK","A1n0yxr1C0m","z2z3EKS","t0XVz0i","y3nxzfm","wgnzyxm","x2nVBM5Ly3q","CM92AwrLigi","t2nMALG","x2n1CNnVCKy","z25stuG","zMvY","BeHHBMrSzxi","x2rLyNvN","B3v0sw50zxi","q05YDhm","mti0mNzyELntsq","yuDys1m","uMvJB25Uzwm","uxvLDwu","DhjHBNnHy3q","nhWZFdb8mNW","vNfpwNO","v05HyMi","zhPZv2K","teXyvue","svLeAKy","BNfyzhC","t3vND2O","B0jez0S","AM9PBG","sM1ID1G","zLHXvvO","tfn2uKO","zfffEeG","uKr1zfO","t3bMzLq","zxrxB3jRq2G","quLzy2e","x2XPC3rLBMu","CgvYC2LZDgu","Eg9qvKG","Aw5JBhvKzxm","BML0AwfSAxO","vhjSu1a","B25dBg9Zzq","vwfWtwy","CMvUDevUzha","x3vYBa","shvAswm","C2v0","BhrZtLO","EeDwqK8","DMvYC2LVBG","B2PTrNi","zxHWB3j0CW","yNbev1q","DhjPzxmGCMu","Cuj6Ew8","quzKAKy","qwjmruO","rKjQtuO","D3PNrhu","AejPy0W","BuLqzw8","C1vftvy","ENbOt0C","BwjNueK","zxjHDg9Y","q3rtrKW","u0P6wuS","v0L1AwO","lcbxzwjtB2m","yw1LoIa","q3vZDg9Trxi","B25LCNjVCG","v2vIu29JA2u","AwXK","uhjPBwfYEuS","vwPkDeq","t2HWs04","re1cyKS","BfvhteO","Dgv4DfbHEwW","tfnUy1O","CNnKqwS","y0L1vhG","shHWzuG","yvjiuM0","zMXwsNG","z3fduw0","BvnNDKW","EK5NreK","zw50zwqGDhK","uhffEha","rwHPD2O","CgnRvw4","B3vbs20","CMvTB3zLq2G","t21Xt1i","DNzVwhK","uMX6yMG","s0HNrLK","qK1IzeS","ign1CNnVCIa","BMrLEa","D1rpueW","zcWG","CMfTugfYyw0","sLnptLa","yMjNAM8","C2fNzq","CMvJzxzPzwq","qLHjzxG","igfYCMf5yNu","B3nTqNi","vgLTzw91Da","wwXcuwG","u2DSEvm","tgHTt3G","yxKSihrYEsa","AgvODvG","s05Szhi","ufzfy2m","CwjjuLO","Aw5KzxGGB3u","wMXmDLi","zw5JB2rLrNi","Dw5RBM93BIa","CMvKDwnL","yMvjs20","z25UvLK","mhWYFdf8nhW","ywXSq3vYC28","weL4BKq","ChL6ufy","sg5srvO","EKznALq","Cgf5Bg9Hza","Aw47y2HHCNm","zuL1vey","z3rny3y","DLbiwMe","r2HQtxO","wfzpwKq","y0vbuLa","otuZodK3mgHJu3DhDa","zeLLB1i","wMPNwfq","y2XVC2u","DerprhO","tKTgs08","uhvtv3G","C2v0sxrLBq","BxznC0C","zw50","rgXWzwe","BMrWB2LUDfq","DfLpuw0","uKHrCxy","Ae1LC3nHz2u","BNDXvum","rNfRuuG","CMvWBgfJzui","BMDLza","m3WYFdf8mhW","zxjYtM8","twLkrM4","AvfHqLa","tgzcvLa","ywnOzwqSihC","sgvTt0C","y3vYC29YlNm","x2n1CNnVCK4","A2fzq0e","AvbTB0q","y2HnyxHuCMK","qKn4Awe","vhHuA3q","Cfzlrfy","EvbXAgG","svLZD0S","Cgf5Bg9Hzfq","zNvUy3rPB24","CgjICdi","zw1kz0q","x2LUAxq","DxbKyxrLq3u","t29cEeG","x29UrxjYB3i","zhHZB2e","wK1hqKy","zgvSzxrLrge","ALfXA2u","x3DHAxq","uLjxD0i","zuzvwei","rvjst1i","yw5Nzq","qNjPzgDL","ufHuwfi","C2ntB3m","z2rxtNm","D2Dbzxy","y3rwr1K","x2LZsw5PDa","vu5zsuG","CefQyNy","BMvY","ru5MCMu","CgLUz19VBMm","z2v0sxrLBq","CNnVCKzPBgu","yxPtqwu","ter5rgK","DhbizwfKzxi","AxnrB1nnzxm","Dev2zw50","yNL0zu9MzNm","z2v0s2v5","vwPhELG","yxrHlcbKyxq","tNbcA3y","AfPYC1e","rKDis3O","Au5nBu4","q09oveLovuu","ywnRtxnNswq","CgLUz1rPBwu","Bhbzthi","x2fKzfDZtgK","ywD5t2i","x3nLBMrby2S","zwjtqLi","Ee5Qsxa","q29UzMLN","zMLpCMK","Dhj1y3rVCIa","C2XfwK0","y0HTB0S","v2rQwMS","DgvACNK","ruvdsNy","zfHgrwi","B2zMC2v0","Cw9Z","Ag9LwNm","uKzVse4","zvvqrxq","z2v0qwXS","ANHPy0u","AxPTyvy","zMHKt2O","qK5xugW","rffAvMy","u3rYyxrLz3K","B25SAw5L","BwvZ","wgzrsfK","A2X2Dgy","C3bSAwnL","qvfQyuG","ywzL","yMrFzgLK","yNvMzMvY","BxzlyNK","txflBuy","Dg9VigXHCMC","mhWXFdv8nhW","vurRtvy","zMj5sKu","CxPrtei","BwvKAwf0zwW","C0nVDw50zxi","qxbPCNm","y2resfK","AvD1CKG","suvtx0vsuK8","y291BNq","vKLgy0O","DwvwtgW","Ef9MCM9UDgK","B3jRig9MzMW","CMvTB3zLrxy","BxPTzu0","Dw50","yMz1DLC","sgfYBve","yxnZAwDU","sxLYBwm","Aw50zwDLCIa","Chv0","D2Lpr20","D1PkAfe","DgH6Aum","x2n1CNnVCK0","AfrOthu","rNbXuw0","B3HNtem","qxHUA3y","mtiYmteZogvou2PSAa","AKHozfq","uhLqCgm","AxnbCNjHEq","zMX1C2HfEha","tKLorvm","DxbNCMfKzw4","ue1Yt0C","sKLiDfu","BgXLs1y","yMrJDwm","y3jLyxrLrwW","x3fVC0rc","q09ACMW","B1fjvMy","CNzHBa","DNnrBKe","tKPKu0W","CNzHBfzHBhu","Egvss3O","sLn5quO","x0rctMfTzq","qxjUwLi","DgLir2S","x2rPC3bHDgm","sgX3Cxu","BgLZDgvUtMu","C2XPy2u","zhDUtLi","yu1tq2S","uM9eyuC","BMPZy1i","DwnPAvC","zv90Aw1LB3u","DKXrzeW","ywDLu2HVDW","q1DTshK","z05PEgK","y29UDgLUDwu","CgXLyxnLiha","rKLmrv9ot1q","ruDeD2C","t3PXBwO","ENHQuNm","DNv6Dfm","BMfTzq","AefJA01LC3m","EM9Uzem","ChLSrxu","rvPhEKq","yMfSu2nVCgu","qLDWEgS","EfvZzuvUDG","AxnFywnR","ruDUzgC","thrVA1O","qwniwMW","Dg9Y","zgvMAw5Luhi","x2LZtM9Kzq","x2HHBMrSzvi","AgfUz2u","x2LZqNjVD3m","rgXzveG","zgrmEhG","wKr0Dhq","rNHgwLy","B3bLBG","ihbYB3rVy28","q0Xpu0LorW","m3W0Fdj8mhW","zeXbq0i","B25tDgfYDfi","Cg9PBNrbBMq","D3jdqMu","C3nHz2vfDMu","zufJAW","y2HLy2TdDxi","AfvftLi","C2v0q3vYC28","y3jLyxrLq2W","C2L3C1q","y2XLyxi","t2DHy1m","CKX1De4","ELPUtNi","m3WYFdy","CMfNzvn5BMm","CK5etuS","y3vYDMfSDwu","Cxrwz1u","q3vZDg9Tq2W","CvDOB1e","rwHfCuu","Cgz4BeK","x2DLDeLUDgu","r2vwDfG","yxjYyxLIDwy","BwvZC2fNzq","mdaWma","tgLAwKq","B3DVDMW","txjNyNe","q2njuhy","CgfYC2u","txHjq3y","y1PvtKW","CuLgDMu","yu53vvu","uNzcDgu","Cg9XrgO","lcbOB3n0BMe","y2HLy2Tszwe","Dgvyvey","yxDewvO","B3bLCNr5tMe","C0L4zvu","ChrVCG","C3rYAw5NAwy","tMfTzq","C0nJD2m","zLvytLa","t3rTrKK","C3vIC3rYAw4","Egrhzve","CMvJB25Uzwm","q3bXC04","C3HdzxK","BMnVzgLUzW","yxbWzw5Kq2G","EMLmBLy","sKPjBwG","Ehjdvha","BwfW","zKzPugW","zvbkuvm","zNjHBwvuExa","A2v5","uMLosLC","aaaaaaaaaaa","tuzlt1u","x2LUAxrhBg8","ue5qvgm","v0PnufK","mtm0mZyYndHMquvvyLO","CMvHzhLtDge","BfrPBwvVDxq","x2rItMfTzq","qNDYyw8","B2XKvMvYC2K","zgvS","DvfcDvO","D1ruAvi","wu9csfm","v0vus2q","sg9PCKW","v215Cgm","ywTsEKu","s3bpB0y","tNvht1q","DNDuC0G","t2XMCMq","EsbJBg9Zzwq","DM1IvwW","CgfNzwHPzgu","DeLUDgvYy2u","CMfTzq","v2j3vfO","wgfSseC","DgHLBG"];return Ko=function(){return t},Ko()}function r1(){return Rx||(Rx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function i1(){let t=M;return Px||(Px=[IDBCursor.prototype.advance,IDBCursor[t(220)+"e"].continue,IDBCursor[t(220)+"e"][t(1155)+t(895)+"ey"]])}function s1(t){let e=M,r={SLACG:function(o,c){return o!==c},LSncZ:e(223),zphOG:function(o,c){return o(c)},Oeuvc:function(o){return o()},UjGzX:function(o,c){return o(c)},lMpjt:function(o,c,d){return o(c,d)},pfrqi:function(o,c){return o+c},bxXpu:e(942)+"t of ran"+e(1502),YtFRi:function(o,c){return o||c},mvMsG:e(1616),YMZSw:function(o,c){return o===c},nKOgG:"MMZKH",uzGAk:e(661)},i=new Promise((o,c)=>{let d=e,u={ZFAPf:d(655),hxXmd:function(m,S){return r[d(1037)](m,S)},ZiZke:function(m){return m()},cGruE:function(m,S,y){return r[d(759)](m,S,y)},ebSBR:function(m,S){return m+S}},f=()=>{let m=d;t[m(1100)+m(438)+m(1025)](u.ZFAPf,x),t[m(1100)+m(438)+m(1025)]("error",g)},x=()=>{let m=d;u[m(647)](o,Ut(t[m(792)])),u[m(231)](f)},g=()=>{let m=d;if(r[m(1579)](r[m(901)],m(223))){let S={sCTGt:m(571),GJyCH:function(b,I,A){return u[m(657)](b,I,A)}},y=_0x51cb88.buffer[m(1144)](_0x343771[m(1035)+"et"],u[m(1050)](_0x204c37[m(1651)+"th"],_0x75053f[m(1035)+"et"]));this._socket&&this[m(156)][m(776)]({data:y,fail:b=>{let I=m;this[I(1701)](S.sCTGt,S[I(1347)](_0x120b2f,S[I(1531)],{message:this["_formatE"+I(719)+"age"](b)}))}})}else r[m(883)](c,t[m(571)]),r[m(1619)](f)};t[d(515)+"Listener"](d(655),x),t[d(515)+d(799)](d(571),g)});return i[e(1286)](o=>{let c=e,d={fbZWG:function(u,f){return r[H(1309)](u,f)},zyrgb:function(u,f){return r[H(1309)](u,f)},xdGeQ:function(u,f){return u+f},lpYLr:function(u,f){return r.pfrqi(u,f)},eDqbW:r[c(1358)],MlMCU:c(1484),tAXeq:function(u,f){return r.YtFRi(u,f)},tvgtR:r[c(971)]};if(r[c(755)](r[c(195)],r[c(195)])){if(o instanceof IDBCursor){if(r[c(697)]!==r[c(697)])return _0x51e452(d.fbZWG(d[c(1350)](d[c(1241)](d[c(1046)](d[c(327)],_0x1a8f5b),d[c(554)]),d[c(193)](_0x344185,1))+d.tvgtR,_0x2ddc13));Fd[c(867)](o,t)}}else _0x1def2b[c(1475)](_0x12c650)})[e(368)](()=>{}),Vo[e(867)](i,t),i}function o1(t){let e=M,r={zeuHV:e(1589),WPlDx:e(571),pAjbv:e(472),leCqH:function(o){return o()},oaMGn:function(o,c){return o(c)}};if($o[e(198)](t))return;let i=new Promise((o,c)=>{let d=e,u={KFapJ:function(m){return r[H(1551)](m)},KkaRB:function(m,S){return r[H(612)](m,S)},izpep:"AbortError",bZGwo:function(m){return r[H(1551)](m)}},f=()=>{let m=H;t["removeEventListe"+m(1025)](r[m(437)],x),t["removeEv"+m(438)+"ner"](r[m(1541)],g),t[m(1100)+"entListe"+m(1025)](r[m(1024)],g)},x=()=>{u[H(1648)](o),f()},g=()=>{let m=H;u[m(251)](c,t[m(571)]||new DOMException(u[m(1435)],m(300)+"or")),u.bZGwo(f)};t[d(515)+"Listener"](r[d(437)],x),t[d(515)+"Listener"](r[d(1541)],g),t[d(515)+d(799)](r[d(1024)],g)});$o[e(867)](t,i)}function a1(t){Jo={DIyuQ:function(i,o){return i(o)}}[M(182)](t,Jo)}function c1(t){let e=M,r={nfjPw:function(i,o){return i(o)},VzdYa:function(i,o){return i(o)},OkXis:function(i,o){return i(o)},YlBQh:function(i,o){return i===o},StZQG:function(i,o){return i in o},bfuvW:e(334)+"oreNames",pZulI:function(i){return i()}};return r[e(934)](t,IDBDatabase[e(220)+"e"][e(837)+"ion"])&&!r.StZQG(r[e(1103)],IDBTransaction[e(220)+"e"])?function(i,...o){let c=e,d=t[c(1363)](r[c(674)](es,this),i,...o);return Bd.set(d,i.sort?i[c(502)]():[i]),r.VzdYa(Ut,d)}:r.pZulI(i1).includes(t)?function(...i){let o=e;return t[o(550)](r[o(475)](es,this),i),r.OkXis(Ut,Fd[o(531)](this))}:function(...i){return Ut(t.apply(r.nfjPw(es,this),i))}}function d1(t){let e=M,r={ITnRd:function(i,o){return i===o},krEKT:e(1e3),gRACV:function(i,o){return i instanceof o},ScyWx:function(i,o){return i(o)},csWdS:function(i){return i()}};return r.ITnRd(typeof t,r[e(1418)])?c1(t):(r[e(1689)](t,IDBTransaction)&&r.ScyWx(o1,t),Mx(t,r[e(821)](r1))?new Proxy(t,Jo):t)}function Ut(t){let e=M,r={hggAu:function(o,c){return o instanceof c},eFiox:function(o,c){return o(c)},TNHyQ:function(o,c){return o(c)},vmbUl:function(o,c){return o!==c}};if(r[e(257)](t,IDBRequest))return r[e(209)](s1,t);if(jo[e(198)](t))return jo.get(t);let i=r.TNHyQ(d1,t);return r[e(1280)](i,t)&&(jo[e(867)](t,i),Vo[e(867)](i,t)),i}var Mx,Rx,Px,Fd,$o,Bd,jo,Vo,Jo,es,Dx=Nx({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={rjlmT:t(838)+"1",hqbmt:function(r,i){return r+i},awdUb:function(r,i){return r+i},cbsse:function(r,i,o,c){return r(i,o,c)},aUqDB:function(r,i){return r+i},jjsKm:function(r,i){return r<i},LWAKg:function(r,i,o,c){return r(i,o,c)},ZmcIm:function(r,i){return r===i},ofYrl:t(767),rXpRG:function(r,i){return r instanceof i},ihtxv:function(r,i){return r===i},hehuX:t(1370),efcpP:function(r,i){return r===i},Oliab:function(r,i){return r!==i},QBcme:t(206),QJmLp:t(1647),WbqrU:t(1017),RRWwB:t(654),hcGYi:function(r,i){return r(i)},AhmAO:function(r,i){return r instanceof i},BCxia:function(r,i){return r===i},VqOZz:"store"};Mx=(r,i)=>i.some(o=>r instanceof o),Fd=new WeakMap,$o=new WeakMap,Bd=new WeakMap,jo=new WeakMap,Vo=new WeakMap,Jo={get(r,i,o){let c=t;if(e[c(339)](e.ofYrl,"cKNcu")){if(e[c(211)](r,IDBTransaction)){if(e[c(526)](i,e.hehuX))return $o[c(531)](r);if(e[c(252)](i,c(334)+c(268))){if(e[c(1662)](e.QBcme,e[c(1572)]))return r[c(334)+c(268)]||Bd[c(531)](r);{let d=e[c(566)][c(1480)]("|"),u=0;for(;;){switch(d[u++]){case"0":if(_0x673696[c(405)+"e"])return e.hqbmt(_0x2dd43b[c(405)+"e"](_0x151e66,_0x34e52d),_0x4ec5a5);continue;case"1":return e.awdUb(e[c(1609)](_0x183e98,_0x3a442d,_0x96b6ec,_0x335305),_0x58fe40);case"2":if(_0x2f8407[c(1540)])return e[c(266)](_0x32ef90[c(1540)](_0x1c7084,_0x331c37),_0x46a053);continue;case"3":if(e.jjsKm(_0x3170ab[c(721)],40))return e[c(1426)](_0xd235c8,_0x3cc63b,_0x323e58,_0x1f9257)+_0x516318;continue;case"4":if(!_0x41a114)return _0x4aaca9;continue}break}}}if(e.efcpP(i,c(1546))){if(e[c(1662)](e.WbqrU,e[c(1012)]))return o[c(334)+c(268)][1]?void 0:o[c(334)+c(1315)](o.objectStoreNames[0]);this[c(216)+"T"]?_0x400811[c(157)+"kStatusC"+c(1178)](({isConnected:d})=>{let u=c;this[u(1615)+"igatorOn"+u(418)]=d,d?this[u(1395)+u(711)]():this[u(1395)+u(474)]()}):this[c(323)+"X"]&&_0x4b3bf0[c(157)+c(818)+c(1178)](({isConnected:d})=>{let u=c;this[u(1615)+u(1595)+u(418)]=d,d?this["_handleO"+u(711)]():this[u(1395)+u(474)]()})}}return e[c(761)](Ut,r[i])}else return this._qosDB?.isReady},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e.AhmAO(r,IDBTransaction)&&(e[o(994)](i,e[o(938)])||e[o(994)](i,e[o(839)]))?!0:i in r}},es=r=>Vo[t(531)](r)}}),Bx={};n1(Bx,{deleteDB:()=>u1,openDB:()=>l1,unwrap:()=>es,wrap:()=>Ut});function l1(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=M,u={smAUB:function(g,m){return g(m)},GJZfr:function(g,m){return g(m)},PNPTc:function(g,m,S){return g(m,S)},fAkTG:function(g,m){return g===m},UEMZd:d(1160),dJiIL:d(966),BVpts:"versionc"+d(1178),wApck:function(g,m){return g(m)},XLgCH:"xVIwV",rOSAm:d(1123)+"eeded"},f=indexedDB[d(1184)](t,e),x=u[d(652)](Ut,f);return i&&(u.fAkTG(u[d(667)],u[d(667)])?f[d(515)+"Listener"](u[d(789)],g=>{let m=d;i(u[m(1650)](Ut,f.result),g[m(1266)+"on"],g[m(681)+"on"],u[m(233)](Ut,f[m(837)+m(346)]))}):(u[d(1259)](_0x164c3e,_0x1f8a60,16),u.PNPTc(_0x5d8ac8,_0x1c01fe,_0x57e939))),r&&f[d(515)+d(799)](d(1452),()=>r()),x[d(1286)](g=>{let m=d;u[m(1599)](u[m(320)],u[m(320)])?(c&&g[m(515)+m(799)](u.dJiIL,()=>c()),o&&g[m(515)+m(799)](u[m(383)],()=>o())):_0xf637d[m(567)](_0x575646)}).catch(()=>{}),x}function H(t,e){t=t-148;let r=Ko(),i=r[t];if(H.sUzEYP===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",m="";for(let S=0,y,b,I=0;b=f.charAt(I++);~b&&(y=S%4?y*64+b:b,S++%4)?g+=String.fromCharCode(255&y>>(-2*S&6)):0)b=x.indexOf(b);for(let S=0,y=g.length;S<y;S++)m+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(m)};H.ENPnCj=o,H.BPQsGQ={},H.sUzEYP=!0}let c=r[0],d=t+c,u=H.BPQsGQ[d];return u?i=u:(i=H.ENPnCj(i),H.BPQsGQ[d]=i),i}function u1(t,{blocked:e}={}){let r=M,i={cEqol:r(1452),xzWBM:function(c,d){return c(d)}},o=indexedDB[r(1009)+r(1661)](t);return e&&o[r(515)+r(799)](i[r(1440)],()=>e()),i[r(1417)](Ut,o).then(()=>{})}function Ox(t,e){let r=M,i={sruTr:function(f,x,g){return f(x,g)},eeYQV:function(f,x,g){return f(x,g)},VIZde:"readwrite",CaXWG:"readonly",ZKitY:function(f,x){return f instanceof x},EGDwg:function(f,x){return f===x},TlUzQ:"string",PKCxR:function(f,x){return f!==x},bdcuc:r(960),Xoanj:function(f,x){return f!==x},ddLxx:function(f,x){return f in x},Xucis:"wdbOR"};if(!(i[r(1320)](t,IDBDatabase)&&!(e in t)&&i[r(1158)](typeof e,i.TlUzQ)))if(i.PKCxR(i[r(1127)],i.bdcuc))i[r(795)](_0x34479b,_0x38ff7d,10),i[r(512)](_0x2d4be6,_0x50d9f7,_0x957585);else return;if(Wo[r(531)](e))return Wo.get(e);let o=e[r(270)](/FromIndex$/,""),c=i.Xoanj(e,o),d=zx.includes(o);if(!i[r(1181)](o,(c?IDBIndex:IDBObjectStore).prototype)||!(d||Fx[r(859)](o))){if(i[r(1513)]===i[r(1513)])return;this["_initPro"+r(698)]=null}let u=async function(f,...x){let g=r,m=this[g(837)+g(346)](f,d?i[g(1463)]:i.CaXWG),S=m[g(1546)];return c&&(S=S.index(x[g(1445)]())),(await Promise[g(610)]([S[o](...x),d&&m.done]))[0]};return Wo[r(867)](e,u),u}var Fx,zx,Wo,f1=Nx({"node_modules/idb/build/index.js"(){let t=M,e={ynWpv:t(671),uPcTX:t(191),qbIRZ:t(1199),RiNJW:function(o,c){return o(c)},FFxcH:t(531),hbqBq:"getAll",awDYZ:t(173)+"ys",pckUn:"count",RohNz:function(o){return o()},iiPqK:function(o){return o()}},r="4|5|3|1|0|2"[t(1480)]("|"),i=0;for(;;){switch(r[i++]){case"0":Wo=new Map;continue;case"1":zx=[t(1108),e.ynWpv,e.uPcTX,e[t(941)]];continue;case"2":e[t(1255)](a1,o=>({...o,get:(c,d,u)=>Ox(c,d)||o[t(531)](c,d,u),has:(c,d)=>!!Ox(c,d)||o[t(198)](c,d)}));continue;case"3":Fx=[e[t(692)],t(1036),e[t(623)],e[t(1231)],e[t(913)]];continue;case"4":e[t(1611)](Dx);continue;case"5":e[t(356)](Dx);continue}break}}}),h1={idb:function(t){let e=M;t[e(872)]=Promise[e(662)]()[e(1286)](()=>(f1(),Bx)).then(function(r){return r})}},Lx={};function zt(t){let e=M,r={Aevby:e(446)+"0"},i=r[e(1293)][e(1480)]("|"),o=0;for(;;){switch(i[o++]){case"0":return c[e(872)];case"1":h1[t](c,c.exports,zt);continue;case"2":var c=Lx[t]={exports:{}};continue;case"3":if(d!==void 0)return d.exports;continue;case"4":var d=Lx[t];continue}break}}zt.d=(t,e)=>{let r=H;for(var i in e)zt.o(e,i)&&!zt.o(t,i)&&Object[r(1175)+r(215)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;zt.o=(e,r)=>Object[t(220)+"e"]["hasOwnPr"+t(215)].call(e,r)})(),(()=>{let t=M,e={uJMhK:function(r,i){return r!=i},VTJaF:t(579)+"d",vHZjw:t(780),KkDaH:t(743)+"le"};zt.r=r=>{let i=t;e[i(273)](e[i(1455)],typeof Symbol)&&Symbol[i(1605)+"Tag"]&&Object[i(1175)+"operty"](r,Symbol[i(1605)+"Tag"],{value:e[i(254)]}),Object["definePr"+i(215)](r,e[i(330)],{value:!0})}})();var De={};(()=>{let t=M,e={KHZTR:function(a,n,s){return a(n,s)},FAAan:function(a,n){return a===n},TkISp:"LimPL",bltod:function(a,n){return a(n)},HMMKR:function(a,n){return a+n},FqkQH:function(a,n){return a*n},PsUrT:function(a,n){return a(n)},hThLu:function(a,n,s){return a(n,s)},smApL:function(a,n){return a(n)},TCVCp:t(1216),ajMZu:"ffff",oLnSx:"timeout",NFzBH:t(1062),FxFZV:"message_id",urILJ:"grXyW",CfwNW:function(a,n){return a>n},JGZhX:function(a,n){return a>n},vsQnA:function(a,n){return a<n},JWKDZ:function(a,n){return a-n},EMQms:function(a,n){return a!==n},KLoSB:t(1151),BAksx:"bYlsH",UMoqq:function(a,n){return a!==n},nThXR:function(a,n){return a-n},ffiBE:function(a,n){return a===n},HnREZ:function(a,n){return a<n},BXIex:function(a,n,s){return a(n,s)},GNTQl:function(a,n,s){return a(n,s)},ipWqi:function(a,n){return a!==n},EtieZ:t(516),CtSFL:function(a,n){return a>>>n},NkbXv:function(a,n){return a(n)},rKNqs:function(a,n){return a&n},MxICv:t(1680)+"required"+t(180)+t(1391),uBdeN:function(a,n){return a!==n},giugD:t(1641),emJgD:function(a){return a()},WHfea:function(a,n){return a(n)},zLrPZ:t(1683),ljBru:function(a,n,s){return a(n,s)},KunFT:function(a,n){return a!==n},BWpxk:function(a,n){return a(n)},CGsqa:function(a,n,s){return a(n,s)},gEIgB:function(a,n,s){return a(n,s)},ccztE:function(a,n){return a!==n},QfZiU:function(a,n,s){return a(n,s)},cdDHY:function(a,n,s){return a(n,s)},eIuTF:function(a,n,s){return a(n,s)},wANFm:function(a,n){return a!==n},wzgDu:function(a,n,s){return a(n,s)},gzPlf:function(a,n,s){return a(n,s)},nqXdw:function(a,n){return a!==n},CfvVC:function(a,n){return a!==n},LSvRJ:function(a,n){return a!==n},znoVV:t(1342),wvRlw:function(a,n){return a!==n},OORXO:function(a,n,s){return a(n,s)},AaXGC:function(a,n,s){return a(n,s)},AIYca:function(a,n,s){return a(n,s)},HFTxW:function(a,n,s){return a(n,s)},WwoNS:function(a,n,s){return a(n,s)},vkIhT:function(a,n,s){return a(n,s)},IclZG:function(a,n){return a(n)},zNkbq:function(a,n,s){return a(n,s)},uGnQC:function(a,n){return a(n)},JmbwX:t(1680)+t(628)+t(180)+t(1407),DcTYb:t(1680)+"required"+t(180)+t(217),lxUYy:t(1680)+t(628)+" field: service",cHUYY:function(a,n){return a===n},HoirL:function(a,n){return a&n},pfriP:function(a,n){return a(n)},UDkMV:function(a,n,s){return a(n,s)},dIeoR:function(a,n){return a(n)},ojTtS:function(a,n,s){return a(n,s)},VIFcJ:function(a,n){return a+n},OfSLo:t(519)+t(910)+"pe: ",PwcII:function(a,n){return a>=n},WhCfh:function(a,n){return a>n},osmBr:"Skip pas"+t(1297),SQVgy:function(a,n){return a*n},SEJFQ:function(a,n){return a>n},OayDg:"Read pas"+t(1297),akRzE:function(a,n,s){return a(n,s)},FehpE:function(a,n){return a&n},OmopZ:function(a,n){return a+n},GFXZf:function(a,n){return a+n},nwqUC:function(a,n){return a&n},MfDjg:function(a,n){return a|n},hbWvb:function(a,n){return a<n},YMdRp:function(a,n){return a==n},zFMjT:function(a,n){return a&n},hzBhQ:function(a,n){return a+n},vPHZa:function(a,n){return a&n},qMXnu:function(a,n){return a|n},UzFPV:function(a,n){return a<<n},muLCa:function(a,n){return a|n},poqDj:function(a,n){return a<<n},cGRxa:function(a,n){return a&n},tPGIt:function(a,n){return a<n},VdrAE:function(a,n){return a>=n},WTCfC:function(a,n){return a<=n},ZeIzi:function(a,n){return a==n},yPqhh:function(a,n){return a&n},tmGtg:function(a,n){return a>=n},aXNSA:function(a,n){return a+n},RvBte:function(a,n){return a+n},zItID:t(763),GMuJp:function(a,n){return a&n},qzQLB:function(a,n){return a<<n},ENwkF:function(a,n){return a&n},UYWZa:function(a,n){return a&n},gFsON:function(a,n){return a<n},dxsoa:function(a,n){return a!==n},fXqUZ:t(1217),aMJva:function(a,n){return a+n},qXrlJ:function(a,n){return a>>n},LLXUA:t(1170),rjTaS:t(524),flVJx:function(a,n){return a||n},JNDSG:"ack_code",CcIPv:function(a,n){return a==n},ObPke:function(a,n){return a(n)},Piuee:function(a,n){return a instanceof n},yhhZu:t(274),fnTyN:"rxgHp",lxmsv:t(536),mHYkO:function(a,n){return a>=n},NaAfQ:function(a,n){return a<=n},slEZM:function(a,n){return a<n},RktWU:function(a,n){return a+n},qIFve:function(a,n){return a<n},esBBb:function(a,n){return a<n},LRyMi:function(a,n){return a<=n},FoJnf:function(a,n){return a+n},FnvYf:function(a,n){return a<<n},ubqmf:function(a,n){return a<n},HfpQD:function(a,n){return a&n},sJDAq:function(a,n){return a|n},BYDiC:function(a,n){return a>>n},BrmNt:function(a,n){return a|n},AcHZl:function(a,n){return a>>n},diCaY:function(a,n){return a&n},MtIIf:function(a,n){return a>>n},qtVgU:function(a,n){return a|n},ueVLl:function(a,n){return a&n},tMeVO:function(a,n){return a>>n},oaSkn:function(a,n){return a+n},PMrOG:function(a,n){return a(n)},vqMrR:function(a,n){return a(n)},SnCwl:function(a,n){return a===n},njscR:t(161),pIoJM:function(a,n,s){return a(n,s)},kzime:function(a,n,s){return a(n,s)},pftMw:function(a,n){return a||n},aVJKl:t(579)+"d",Easve:t(1685)+t(278)+"d",MYnxR:t(178),COZrl:t(521),jhyyf:function(a,n){return a<n},gvOkY:function(a,n){return a>=n},RPumX:function(a,n){return a&n},eSqza:function(a,n){return a&n},gnRMH:function(a,n){return a|n},oMOTX:function(a,n){return a&n},vrFTv:function(a,n){return a(n)},PQCjS:function(a,n){return a&n},ArnZR:"wezrA",HarmQ:t(412),RBnbo:function(a,n){return a<<n},EtZKm:function(a,n){return a&n},eOCMs:function(a,n){return a(n)},maMZR:function(a,n){return a&n},kXOSK:t(783),YCDzP:function(a,n){return a(n)},HSbDj:function(a,n){return a&n},NJSoA:function(a,n){return a<<n},sUEMV:function(a,n){return a&n},pqnXg:function(a,n){return a&n},PuSWx:function(a,n){return a!==n},BebXs:t(494),klvtf:function(a,n){return a(n)},iQaBP:function(a,n){return a&n},DOUui:function(a,n){return a&n},Hlwqu:"jSGea",UtQfq:function(a,n){return a&n},EZGzD:function(a,n){return a+n},BLPKe:function(a,n,s){return a(n,s)},Lkiqk:function(a,n){return a>>>n},bbYEi:function(a,n){return a<<n},nqEcm:"IYFMz",YScJp:function(a,n){return a>>>n},udlns:function(a,n){return a>>>n},HIrol:function(a,n){return a>>>n},SchdW:function(a,n){return a<n},Mpneo:function(a,n,s){return a(n,s)},NWxDi:function(a,n){return a!==n},fMyaC:function(a,n){return a+n},tiHGk:function(a,n){return a>>>n},PlpTo:function(a,n){return a+n},Vycrx:function(a,n){return a>>>n},WspIX:function(a,n){return a!==n},kIoeR:function(a,n){return a|n},OLogB:function(a,n){return a>>>n},ncnKW:function(a,n){return a&n},SqEmu:function(a,n){return a>>>n},oBDgK:function(a,n){return a|n},BlduS:function(a,n){return a!==n},WNabb:function(a,n){return a>>>n},zondC:function(a,n){return a>>>n},Bkcex:function(a,n){return a+n},Zmxzo:function(a,n){return a&n},VpnpH:function(a,n){return a>>>n},pylEu:function(a,n){return a(n)},GAVre:function(a,n){return a|n},cIuTx:function(a,n){return a===n},YfEHH:"VITjf",fbyJE:t(1514),UMYGG:function(a,n){return a===n},ekNYG:function(a,n){return a|n},wrCBe:function(a,n){return a<<n},jHNdT:function(a,n){return a|n},nQddd:function(a,n){return a|n},wIcmF:function(a,n){return a<<n},ltsNZ:function(a,n){return a<<n},IWmoF:function(a,n){return a<<n},TrlSP:function(a,n){return a<<n},ReGjB:function(a,n){return a<<n},jaIRc:function(a,n){return a>>>n},DYUpV:function(a,n){return a|n},nQbVi:function(a,n){return a<<n},gOtIz:function(a,n){return a&n},ZImAg:function(a,n){return a>>>n},TJscp:function(a,n){return a&n},DQZVf:function(a,n){return a(n)},Egnlh:function(a,n){return a<=n},ziLnV:function(a,n){return a+n},LDyDi:function(a,n){return a|n},SglyS:function(a,n){return a%n},owDAo:function(a,n){return a|n},mIPeo:function(a,n){return a/n},rgyyQ:function(a,n){return a+n},xFYud:function(a,n){return a*n},VWzkO:function(a,n){return a===n},ffdIQ:function(a,n){return a>>>n},MNYSX:function(a,n){return a>>>n},teXTF:function(a,n){return a&n},KxxAm:function(a,n){return a+n},eoZLA:function(a,n){return a>>>n},QAJtx:function(a,n){return a<<n},OgacS:"sIETr",bvSfs:function(a,n){return a===n},pnlfP:function(a,n){return a>>>n},fUXNP:function(a,n){return a===n},Aqmbf:function(a,n){return a>=n},NTroB:function(a,n){return a|n},qVHro:function(a,n){return a<<n},HxFDZ:function(a,n){return a&n},Apirs:function(a,n){return a&n},eNaWj:function(a,n){return a>=n},isuFX:function(a,n){return a|n},VEqtr:function(a,n){return a<<n},DjlJw:function(a,n){return a<<n},kqDcu:function(a,n){return a+n},FBjMJ:t(292),vvoXy:function(a,n){return a===n},iIRGY:function(a,n){return a+n},IWKUT:function(a,n){return a+n},CaJGW:function(a,n){return a&n},tfPKg:function(a,n){return a>>>n},ApuKX:function(a,n){return a>>>n},Rlzbh:function(a,n){return a&n},WKAyz:function(a,n){return a>>>n},dXFEb:function(a,n){return a&n},rsdAk:function(a,n){return a>>>n},rXYMH:function(a,n){return a&n},BHyXv:function(a,n){return a>>>n},ZQAzf:function(a,n){return a&n},tUCpo:function(a,n){return a>>>n},gzQrB:t(1065),gfwzK:"5|3|2|1|"+t(163),axEmN:t(1481)+t(1014),BNWPl:t(403)+t(1094)+"R",naXQE:"CONNECTI"+t(553),sLSxy:t(176)+"OR",uHtNy:t(184)+t(777),PKOrn:function(a,n){return a-n},KpBMp:function(a,n){return a>>n},ljCCe:function(a,n){return a|n},VAmzC:function(a,n){return a===n},mSwrD:t(940),OoBxH:t(1649)+t(1203),iuDWr:t(1534)+"4",drvTt:t(1027)+t(428)+"s",ablAJ:"ping_onc"+t(1150)+"t",zNgDI:function(a,n){return a!==n},LxFIB:t(179),PavoG:function(a,n){return a>=n},bIBrx:function(a,n){return a===n},qfJGF:function(a,n){return a!==n},arXHt:t(1161),ekmzo:function(a,n){return a!=n},XPLRu:function(a,n){return a instanceof n},BqAqU:t(1392)+t(1317),fhdOj:t(508),gJwlk:"gvjau",cuMvz:t(571),esRmI:function(a,n){return a+n},YCNCo:function(a,n){return a+n},UCLjy:function(a,n){return a<n},HMRtv:function(a,n){return a===n},UAmbY:function(a,n){return a&n},BTKyt:function(a,n){return a!==n},aTdmb:t(1390),NcqMr:"KRlKa",OfKWI:t(281),EeYCc:function(a,n,s){return a(n,s)},Iyrmc:t(966),bCSgm:function(a,n){return a(n)},jxicE:t(1215),zZnNr:function(a,n,s){return a(n,s)},DQJZN:function(a,n,s){return a(n,s)},xrCTp:function(a,n){return a===n},GNNFx:t(546),EvYLj:function(a,n){return a===n},RDudZ:function(a,n){return a===n},Rmxrw:t(194),lgiza:t(539),AhVLf:t(1285),NWamX:"Yiday",zeYpX:t(1495),zUSMf:function(a,n){return a+n},fyqwG:function(a,n){return a&n},orDjF:function(a,n){return a||n},FTAZc:t(1225),IYswK:t(491),JxuXb:t(769),IgyQB:t(393),zSWfk:t(949)+"3",qBMMf:t(811)+t(324)+t(329)+t(487)+"process",KrPrJ:function(a,n){return a(n)},jbukd:function(a,n){return a<n},qWhoQ:function(a,n){return a<n},FzkIh:function(a,n){return a&n},GBPPw:function(a,n){return a<n},NZkxn:function(a,n){return a<=n},Filvx:function(a,n){return a<n},bZmTG:function(a,n){return a|n},MWxzd:function(a,n){return a&n},lgDnr:function(a,n){return a&n},TcoIj:function(a,n){return a>=n},LhmOx:function(a,n){return a===n},pfxlI:t(337),ojmFr:function(a,n){return a-n},JHUzt:function(a,n){return a|n},zAMLB:function(a,n){return a|n},KgYmM:function(a,n){return a<<n},XlUEv:function(a,n){return a&n},vcRru:function(a,n){return a&n},EqLCJ:function(a,n){return a>>n},DKTLp:function(a,n){return a+n},CoqgR:function(a,n){return a&n},ElBul:function(a,n){return a<n},pOHzv:function(a,n){return a|n},lleKV:function(a,n){return a>>n},dQaRq:function(a,n){return a&n},sZJMN:function(a,n){return a===n},oxgLC:function(a,n){return a===n},dMmNm:function(a,n){return a+n},KpOoF:function(a,n){return a&n},wljio:function(a,n){return a&n},RzniR:function(a,n){return a>>n},hUENR:function(a,n){return a>>n},sqXre:function(a,n){return a&n},JIHtU:function(a,n){return a>>n},oMvOM:t(748),uFeiW:function(a,n){return a(n)},ejVZW:function(a,n,s,l){return a(n,s,l)},aXUNf:function(a,n){return a instanceof n},Mbcnc:function(a,n){return a===n},pdSif:"Lcvaz",CnFjO:function(a,n){return a!=n},MHfyL:function(a,n){return a instanceof n},TWtjb:function(a,n){return a instanceof n},ouGUb:t(296)+t(956)+t(1308),GeVtX:t(1294),NKFKO:t(1556),izmaV:function(a,n){return a===n},CmDQb:t(1470),tMryD:function(a,n){return a>=n},dQExH:t(1340),tDODz:function(a,n){return a(n)},rTXiq:t(945)+"reason",VeAKG:t(1548),HWnoI:t(321),ilGrt:t(370)+"ack=frontierJSONP",ncNjP:t(1344),Dlpea:function(a,n){return a&n},tYOQm:function(a,n){return a>>>n},FPmrL:t(793),stGmx:function(a,n){return a(n)},DlYTH:t(1338),FGHKz:function(a,n){return a(n)},MqKmF:function(a,n,s,l){return a(n,s,l)},JzCfZ:"LmUmd",eDPfw:function(a,n,s){return a(n,s)},WfArW:function(a,n){return a!==n},BkxbQ:"eWBFA",TnDBa:t(834),wZJhQ:function(a,n){return a instanceof n},wjlUs:function(a,n){return a instanceof n},HCxoV:t(1303),TBoAC:function(a,n){return a!==n},wTTiR:"wRKEp",GlRio:function(a,n){return a===n},QHZgY:t(1374),ctVGY:function(a,n){return a===n},WRjqy:t(684),xfFlU:t(1343),dHOFd:function(a,n){return a+n},wgAev:"cvCdo",ITUVk:function(a,n,s){return a(n,s)},WIbMn:"rvZFJ",boSxy:function(a,n){return a!==n},fFiPl:t(1404),jqSaE:function(a,n){return a||n},ziLrm:function(a,n){return a||n},FIuFI:t(724),HpdQY:"ZoqSd",VOkYJ:function(a,n){return a||n},FPQWf:function(a,n){return a!=n},iYmsq:t(1276),AOwfA:function(a,n,s,l){return a(n,s,l)},izgWZ:t(1098)+t(506),UjJtD:t(1098)+t(307)+"ck",JfZSe:function(a,n,s,l){return a(n,s,l)},Geudw:function(a,n,s){return a(n,s)},gNixi:t(1098)+t(591)+t(705),RHQqv:function(a,n,s,l){return a(n,s,l)},dHfcS:t(556),ePJQS:function(a,n){return a&&n},ZZKfE:function(a,n,s){return a(n,s)},FvepS:t(1018),bcEbf:t(587),kuTcO:function(a,n){return a-n},DZkfS:function(a,n){return a(n)},PRboh:function(a,n){return a(n)},sSsQn:"wckBk",QkqIq:function(a,n){return a instanceof n},owovl:"none_none",zrlDL:function(a,n){return a<n},jiKTl:function(a,n){return a>n},Axnkv:function(a,n){return a>n},SlYji:function(a,n){return a+n},AFdjF:t(605),hUQJx:function(a,n){return a(n)},thziC:function(a,n){return a+n},xetmp:function(a,n){return a|n},CtCru:function(a,n){return a(n)},ZoAAP:function(a,n){return a+n},mGjye:function(a,n){return a+n},rhFUP:t(1616),aqQos:function(a,n){return a===n},NEYIZ:function(a,n){return a+n},TrMRA:function(a,n){return a===n},Ougwj:"store",Wmypc:function(a,n){return a!==n},rlOCp:t(1299),qceEo:function(a,n){return a>n},eCGqd:function(a,n){return a!==n},EfGOW:t(1366),RFoHN:function(a,n){return a&n},hEdLQ:function(a,n){return a<n},xeRKz:function(a,n,s){return a(n,s)},PiKXT:function(a,n){return a>>>n},JnBPi:t(1187)+"1",Bwrao:function(a,n){return a+n},LxsNe:function(a,n,s,l){return a(n,s,l)},mXMtu:function(a,n){return a+n},LhOHu:function(a,n){return a<n},mvKby:function(a,n){return a|n},CpqsN:function(a,n){return a<<n},KHgFY:function(a,n){return a<<n},SJkwF:function(a,n){return a+n},vFyka:function(a,n){return a|n},UVXBj:function(a,n){return a+n},JSyAJ:function(a,n){return a+n},AptEb:function(a,n){return a>>>n},AKWXO:function(a,n){return a>>>n},uebhA:function(a,n){return a+n},BMjSx:function(a,n){return a>>>n},VVdwf:function(a,n){return a&n},ijjiN:function(a,n){return a+n},VQGwk:function(a,n){return a+n},iQpoe:function(a,n){return a&n},ZIXiA:function(a,n){return a+n},dkrhv:"6|0|5|7|"+t(1414)+t(1606)+"4",ROpoJ:function(a,n){return a<n},hpTcF:function(a,n){return a|n},POkYT:function(a,n){return a>>>n},bCKhs:function(a,n){return a<<n},qLCOX:function(a,n){return a<n},AJlya:function(a,n){return a|n},JdMVj:function(a,n){return a|n},LWQnA:function(a,n){return a&n},XQOCO:function(a,n){return a&n},LfBVP:function(a,n){return a<n},DOZha:function(a,n){return a>>>n},zOUAO:function(a,n){return a|n},ZlLvR:function(a,n){return a>n},sklEe:function(a,n){return a(n)},RZsSz:t(989)+t(1399),qOeoM:function(a,n,s,l){return a(n,s,l)},hZrsQ:t(814),BMbdK:function(a,n,s,l){return a(n,s,l)},UMBkL:t(148),IwZeO:function(a,n,s,l){return a(n,s,l)},jlkHZ:t(407)+t(1162),YOBHS:t(1162),LTvRF:t(1206),jMgeb:function(a,n){return a(n)},TmUJK:function(a,n){return a(n)},EKMMg:function(a,n,s){return a(n,s)},CNrts:function(a,n){return a+n},vSbjg:t(155)+t(1515),DCIzt:t(1157)+t(1665),JHiRC:"cursor_n"+t(1629),sukHR:t(1526)+"econnect"+t(1376),SJzYK:function(a,n){return a===n},bbgjo:t(1451),JrQyd:t(1608),zGtmO:function(a,n,s,l){return a(n,s,l)},PwQdB:"INSTANT",usyMl:t(1043),xjVJs:function(a,n,s,l){return a(n,s,l)},hoeZs:function(a){return a()},HTLSw:"setdb",sIxeU:function(a,n){return a(n)},CnIQT:function(a,n){return a===n},TTwwo:t(272),tcAyK:function(a,n){return a-n},uTOKz:function(a,n){return a||n},vCbhN:"code",UNYIH:function(a,n,s){return a(n,s)},fgBga:t(1098)+t(1695),tmmQG:function(a,n){return a(n)},acwwG:function(a,n,s){return a(n,s)},qyzHO:t(1098)+"er_ttl",PvddU:t(1410)+"s",mbgPI:function(a,n,s){return a(n,s)},SjorT:"x-msg-cursor_name",EECJv:t(639)+t(1568)+"ue",YRAFX:function(a,n){return a===n},UWGEN:t(1686),pjFyr:t(625),OrJjy:function(a){return a()},jQqke:t(425),kmwry:function(a,n){return a<n},beIKm:function(a){return a()},azSAe:function(a){return a()},PMCev:function(a,n){return a&n},PIDLG:function(a,n){return a<<n},VoOdx:function(a,n){return a&n},XtjgJ:function(a,n){return a<<n},bqcjU:function(a,n){return a&n},aRHRm:function(a,n){return a&n},qdvic:function(a,n){return a===n},OhpKN:function(a){return a()},QUwAB:t(408),VQIVM:function(a,n){return a(n)},geMbc:function(a){return a()},FpqQm:function(a,n){return a!==n},JJImh:t(1640),hdmJk:"eIApk",Ehiwj:function(a,n,s){return a(n,s)},AAFIW:function(a,n){return a!==n},XOpzK:"bye",zJKYK:function(a,n){return a(n)},WppUS:function(a,n,s){return a(n,s)},lUGLJ:function(a,n,s){return a(n,s)},HemOG:function(a,n){return a!==n},yCNLQ:function(a,n){return a<<n},DNMMx:"xqiDX",zhPjl:t(1598),Jcuwh:function(a,n){return a===n},JkvUc:t(1214)+t(828),Ssioo:t(1001),OUMWz:function(a,n){return a/n},zJXDQ:function(a,n){return a===n},RWWZU:"please p"+t(311)+t(1521)+t(889)+t(765)+t(1054)+t(388)+t(1657),OcfjX:t(535),PEosp:function(a,n,s){return a(n,s)},hmDtO:t(688)+t(247)+" reconnect",FeCut:"pageshow",GuCYa:t(1325),bAXvk:t(1281),ENfre:t(1073),Rhwde:function(a,n){return a(n)},ISkJI:function(a,n){return a|n},zdzGs:function(a,n){return a<<n},lOZME:function(a,n){return a<<n},xrLmK:function(a,n){return a<<n},ZMGBF:function(a,n){return a===n},ohlSB:"rLutN",jnfOv:t(1625),CHMXA:"FTUuO",EGndg:t(1354),MFKOU:t(290),CnLKx:t(1319),SkwCB:t(1080),QDIId:t(259),uQBuZ:"device_id",ouAKm:"please p"+t(824)+t(486)+t(1323)+t(809),JOLfr:t(1e3),KpRwz:function(a,n,s){return a(n,s)},rLVOj:t(638)+"0",dLACB:t(1242)+"t",xoPVH:function(a,n){return a-n},yFfjV:function(a,n,s){return a(n,s)},cWbRN:function(a,n){return a!==n},AQjaH:t(877),FntjX:function(a,n){return a(n)},HTEkp:t(1442)+">",rCMhv:function(a,n){return a===n},NGWMh:t(1219),KoiCr:t(703),mOqaI:function(a,n){return a*n},IYDjF:function(a,n){return a>n},lkRSh:function(a,n,s){return a(n,s)},XIxnD:"jThdp",NINES:t(740)+t(937)+t(1242)+t(1522)+"ver",siwsT:"timeout, try reconnecting",Eviaz:function(a,n){return a===n},qXquB:t(1542),fRzcz:"0|3|2|1|4",ufMwp:t(1184),Lrzuv:function(a,n){return a!==n},fhcKE:t(174),rlBnY:t(740)+t(1357)+t(1099)+t(807),cwTQO:t(477),yeklR:function(a,n){return a<n},Oimst:function(a,n){return a===n},zUAMD:t(1660),cHmoK:function(a,n){return a*n},mAwnD:function(a,n){return a-n},paYQp:function(a,n){return a>n},zLusj:"DNHEq",Ihcza:function(a,n){return a>>>n},XLyiq:function(a,n){return a===n},NbYkg:t(1291),gIHwg:t(722),kVLmb:t(634),mzmeM:t(499)+t(1547)+t(686)+t(860)+"ed",xerXK:function(a,n){return a===n},kzdQy:t(499)+t(570)+t(1279),XcYas:t(1156)+t(1287)+t(641)+t(1038)+"a must be a stri"+t(584)+t(931)+t(421),MBLoh:t(1545),UyilZ:function(a,n){return a instanceof n},OtmFI:function(a,n){return a instanceof n},jrZUl:function(a,n){return a(n)},gMBBK:function(a,n){return a(n)},KNldr:t(1156)+"rovide a valid s"+t(1399),uquvE:function(a,n){return a instanceof n},GOZdR:function(a,n){return a(n)},OvCib:"sent",WJMPY:function(a,n){return a<n},PAwsz:t(813),SxxVh:function(a,n){return a||n},gRulB:function(a,n){return a==n},xGkhR:function(a,n){return a(n)},asmZK:function(a,n){return a!==n},cAISt:t(1519),LDYZN:t(1013),pJzUe:function(a,n){return a+n},PyPpc:function(a,n){return a&n},dzhOP:function(a,n){return a|n},sxCey:function(a,n){return a<n},JEzIl:function(a,n){return a===n},ktouy:t(685),wAhSM:function(a,n){return a(n)},TqnPk:t(655),lfDWk:t(1256),JGLyQ:function(a,n){return a===n},xGVBO:t(801),raKCb:function(a,n){return a===n},nCiaH:t(385),HxpeH:t(1507)+t(1554)+t(488)+"pe",pqWGB:function(a,n){return a===n},AIxLp:function(a,n){return a===n},cFEvx:function(a,n){return a===n},UbLby:t(1307)+"rkerGlob"+t(1298),oBuEn:function(a,n){return a!=n},tpYrA:function(a,n){return a!=n},kjjlG:function(a,n){return a===n},DMBbK:function(a,n){return a!=n}};zt.r(De),zt.d(De,{FWS:()=>Ig,CustomErrorEvent:()=>il,createCloseEvent:()=>mt,ReconnectEvent:()=>rl,createErrorEvent:()=>lt,decodedFrame:()=>nn,createOpenEvent:()=>ll,CustomCloseEvent:()=>sl,createReconnectEvent:()=>fa,FrontierMessageEvent:()=>al,encodeFrame:()=>qt,createMessageEvent:()=>dl,OpenEvent:()=>cl,ErrorCode:()=>sn,Event:()=>nr,MessageEvent:()=>ol});let r="";function i(a=""){let n=t;if(e[n(1553)]("LimPL",e[n(577)])){let l=""+Date[n(1489)](),h=r||(r=e.bltod(f,a)),p=Math[n(637)]()[n(1605)](16)[n(1144)](-6);return e[n(547)](e.HMMKR(e[n(547)]("02",l),h),p)}else return _0x307895.bytes[e.KHZTR(_0x487b8c,_0x2b4067,1)]}function o(){let a=t;return e.HMMKR(1e4*Date[a(1489)](),Math.floor(e[a(979)](1e4,Math[a(637)]())))}function c(a){let n=t;return(e[n(582)](Array,8)[n(847)]("0")+e[n(1113)](parseInt,a,10)[n(1605)](2))[n(1144)](-8)}function d(a){let n=t;return e[n(547)](e[n(582)](Array,4)[n(847)]("0"),e.KHZTR(parseInt,a,2)[n(1605)](16))[n(1144)](-4)}function u(a){let n=t,s=a[n(1480)](/\./)[n(1250)](p=>c(p)),l=[];return l[0]=e.smApL(d,s[0]+s[1]),l[1]=e[n(185)](d,s[2]+s[3]),[n(1216),"0000",e[n(600)],n(1216),"0000",e.ajMZu,l[0],l[1]][n(847)]("")}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}/[n(1476)](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(1476)](a);return s?e[n(582)](u,a):l?x(a):n(1314)+n(1314)+n(1314)+n(1314)}function x(a){let n=t,s={iANhC:n(1027)+n(1150)+"t",MMfmq:e[n(1295)],skaUc:function(l,h,p){return l(h,p)},rZTQQ:e.NFzBH,qBzyo:e[n(1183)]};if(e.urILJ===e[n(473)]){let l="",h=[],p=0,_=0,v=!0,w=n(1216);if(e[n(348)](a[n(1416)]("::"),-1)){let C=a[n(1480)]("::");for(let L=0;L<C[n(721)];L++){let j=C[L];if(e[n(1402)](j[n(1416)](":"),0)){let z=j[n(1480)](":");v&&(p=z.length),_+=z[n(721)];for(let G=0;e[n(1133)](G,z.length);G++)if(z[G][n(721)]!==4){let fe=w[n(1240)+"g"](0,e[n(415)](4,z[G].length)),ie=fe.concat(z[G]);h[n(1475)](ie)}else h[n(1475)](z[G]);v=!1}else if(e[n(676)](e[n(1384)],e[n(1584)])){if(e[n(1684)](4,j.length)){let z=w[n(1240)+"g"](0,e[n(415)](4,j[n(721)])),G=z.concat(j);h[n(1475)](G)}else h.push(j);v&&(p+=1),_+=1,v=!1}else this[n(1622)+"sCounter"]?.addCount(),this.emit(s[n(1326)],s[n(794)]),this[n(1622)+n(1090)]?.[n(1229)+n(1532)+"nt"]()?this["_handleR"+n(1656)]():this._ping()}let N="";for(let L=0;L<e[n(1675)](8,_);L++)N=N[n(1368)](w);for(let L=0;e[n(1133)](L,h[n(721)]);L++)e[n(1364)](L,p)&&(l=l[n(1368)](N)),l=l[n(1368)](h[L]);return l}{let C=a[n(1480)](":");for(let N=0;e[n(953)](N,C[n(721)]);N++){let L=C[N];if(C[N][n(721)]!==4){let j=w[n(1240)+"g"](0,e[n(1675)](4,C[N].length)),z=j[n(1368)](L);l=l.concat(z)}else l=l[n(1368)](L)}return l}}else this._intervalTimeoutId=null,this[n(404)+"l"]=36e5,this[n(1129)]=s[n(713)](_0x38a850,s[n(357)],s[n(875)])}function g(a,n){let s=t,l=a[s(1254)];e[s(676)](void 0,l)&&(e.BXIex(we,n,10),e[s(1113)](q,n,l));let h=a[s(1391)];h!==void 0&&(e[s(1637)](we,n,18),q(n,h))}function m(a){let n=t;if(e[n(1552)](n(1431),e[n(1464)])){let s={};e:for(;!e.PsUrT(J,a);){let l=me(a);switch(e[n(886)](l,3)){case 0:break e;case 1:s.key=e[n(632)](P,a,e[n(305)](me,a));break;case 2:s[n(1391)]=P(a,e[n(426)](me,a));break;default:T(a,e[n(1322)](7,l))}}if(e[n(1364)](void 0,s.key))throw new Error(n(1680)+n(628)+" field: key");if(e.ffiBE(void 0,s[n(1391)]))throw new Error(e[n(1222)]);return s}else return _0x287213[n(429)]||_0x231aec.errNo?(n(675)+" "+(_0x33fd41.errMsg||"")+n(720)+(_0xf99bb0[n(983)]||""))[n(413)]():_0x3dbdd8.stringify(_0x244975)}function S(a){let n=t;if(e[n(1336)](n(369),e[n(802)])){let s=e[n(1002)](R);return e[n(1113)](y,a,s),e.WHfea(B,s)}else{let s=(n(683)+"3")[n(1480)]("|"),l=0;for(;;){switch(s[l++]){case"0":this._isInit=!0;continue;case"1":this[n(778)+n(530)]?.["resetEnd"+n(644)+n(1512)]();continue;case"2":this[n(717)+n(1673)]=!1;continue;case"3":this[n(823)]();continue;case"4":this["_pingLos"+n(1090)]?.[n(1369)+n(196)]();continue}break}}}function y(a,n){let s=t,l={WrOHQ:function(ie,wt){return e[H(582)](ie,wt)},YuWcY:function(ie){return e[H(1002)](ie)}},h=a.SeqID;e[s(1684)](void 0,h)&&(we(n,8),gt(n,h));let p=a[s(217)];p!==void 0&&(we(n,16),gt(n,p));let _=a[s(148)];if(e[s(1336)](void 0,_))if(e[s(1553)](e[s(1516)],e.zLrPZ))we(n,24),e.ljBru(gt,n,D(_));else return s(433)+"_"+this._DBName;let v=a[s(1676)];e.KunFT(void 0,v)&&(we(n,32),gt(n,e[s(1168)](D,v)));let w=a[s(1635)];if(e[s(445)](void 0,w))for(let ie of w){e[s(1692)](we,n,42);let wt=e[s(1002)](R);e[s(480)](g,ie,wt),e[s(1339)](we,n,wt[s(1473)]),e[s(480)]($,n,wt),O(wt)}let C=a[s(1576)+s(1245)];e[s(500)](void 0,C)&&(e[s(1574)](we,n,50),e[s(1092)](q,n,C));let N=a[s(999)+"ype"];e[s(445)](void 0,N)&&(we(n,58),e[s(957)](q,n,N));let L=a[s(955)];e[s(619)](void 0,L)&&(we(n,66),e[s(879)](we,n,L[s(721)]),e[s(422)](ae,n,L));let j=a.LogIDNew;e.nqXdw(void 0,j)&&(we(n,74),e[s(957)](q,n,j));let z=a[s(596)+s(702)];e[s(1401)](void 0,z)&&(e[s(850)](e[s(1419)],s(1342))?(this[s(1022)]=!1,l.WrOHQ(_0x27c8c2,this[s(823)+s(1312)+s(379)]),l[s(653)](_0x1b3a90)):(e[s(957)](we,n,82),q(n,z)));let G=a[s(581)];e[s(1493)](void 0,G)&&(e[s(786)](we,n,90),e[s(170)](q,n,G));let fe=a.frameType;e[s(850)](void 0,fe)&&(we(n,96),e.GNTQl(gt,n,e[s(1168)](D,fe)))}function b(a){return e[t(582)](I,F(a))}function I(a){let n=t,s={};e:for(;!e[n(185)](J,a);){let l=e.PsUrT(me,a);switch(e[n(886)](l,3)){case 0:break e;case 1:s.SeqID=e[n(855)](At,a,!0);break;case 2:s[n(217)]=e.HFTxW(At,a,!0);break;case 3:s.service=e[n(426)](me,a);break;case 4:s[n(1676)]=e[n(426)](me,a);break;case 5:{let h=e[n(1168)](A,a);(s[n(1635)]||(s.headers=[]))[n(1475)](e[n(426)](m,a)),a[n(1473)]=h;break}case 6:s["payloadE"+n(1245)]=e[n(544)](P,a,me(a));break;case 7:s[n(999)+n(572)]=P(a,e[n(185)](me,a));break;case 8:s[n(955)]=e[n(1113)](oe,a,me(a));break;case 9:s[n(345)]=e[n(200)](P,a,e[n(232)](me,a));break;case 10:s[n(596)+n(702)]=P(a,e[n(1672)](me,a));break;case 11:s[n(581)]=e.zNkbq(P,a,me(a));break;case 12:s[n(1253)+"e"]=e[n(347)](me,a);break;default:e.gEIgB(T,a,e[n(1322)](7,l))}}if(e.FAAan(void 0,s[n(1407)]))throw new Error(e[n(848)]);if(e.ffiBE(void 0,s[n(217)]))throw new Error(e[n(371)]);if(e[n(1364)](void 0,s[n(148)]))throw new Error(e.lxUYy);if(e.cHUYY(void 0,s[n(1676)]))throw new Error(n(1680)+"required"+n(180)+"method");return s}function A(a){let n=t,s=me(a),l=a[n(1473)];return a.limit=e[n(547)](a[n(1061)],s),l}function T(a,n){let s=t;switch(n){case 0:for(;e.HoirL(128,e[s(629)](te,a)););break;case 2:e[s(1086)](Z,a,e.dIeoR(me,a));break;case 5:e[s(480)](Z,a,4);break;case 1:e[s(646)](Z,a,8);break;default:throw new Error(e[s(1096)](e.OfSLo,n))}}function D(a){let n=t;return a|=0,{low:a,high:a>>31,unsigned:e[n(682)](a,0)}}let E=[];function R(){let a=t,n=E[a(1617)]();return n?(n[a(1061)]=n[a(1473)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){E[t(1475)](a)}function F(a){return{bytes:a,offset:0,limit:a[t(721)]}}function B(a){let n=t,s=a[n(260)],l=a[n(1473)];return e.ffiBE(s[n(721)],l)?s:s[n(390)](0,l)}function Z(a,n){let s=t;if(e[s(391)](e.HMMKR(a.offset,n),a[s(1473)]))throw new Error(e[s(932)]);a[s(1061)]+=n}function J(a){let n=t;return e.PwcII(a.offset,a[n(1473)])}function re(a,n){let s=t,l=a[s(260)],h=a[s(1061)],p=a[s(1473)],_=e.HMMKR(h,n);if(_>l[s(721)]){let v=new Uint8Array(e[s(420)](2,_));v[s(867)](l),a[s(260)]=v}return a[s(1061)]=_,e[s(458)](_,p)&&(a.limit=_),h}function X(a,n){let s=t,l=a[s(1061)];if(e[s(547)](l,n)>a[s(1473)])throw new Error(e[s(461)]);return a[s(1061)]+=n,l}function oe(a,n){let s=t,l=X(a,n);return a[s(260)][s(390)](l,l+n)}function ae(a,n){let s=t,l=e.akRzE(re,a,n[s(721)]);a[s(260)][s(867)](n,l)}function P(a,n){let s=t,l=e[s(1274)](X,a,n),h=String[s(464)+s(1503)],p=a[s(260)],_="\uFFFD",v="";for(let w=0;w<n;w++){let C=p[e.VIFcJ(w,l)],N,L,j,z;if(e[s(285)](e[s(1322)](128,C),0))v+=h(C);else if(e.FAAan(e[s(457)](224,C),192))e[s(682)](e[s(805)](w,1),n)?v+=_:(N=p[e.GFXZf(e[s(547)](w,l),1)],e[s(978)](192,N)!==128?v+=_:(z=e.MfDjg(e[s(1272)](31,C)<<6,e[s(978)](63,N)),e[s(1387)](z,128)?v+=_:(v+=h(z),w++)));else if(e[s(1454)](e[s(954)](240,C),224))e[s(682)](e[s(768)](w,2),n)?v+=_:(N=p[e[s(560)](w,l)+1],L=p[w+l+2],e[s(959)](e[s(1571)](N,e[s(158)](L,8)),49344)!==32896?v+=_:(z=e[s(340)](e[s(1227)](e[s(534)](15,C),12),(63&N)<<6)|e.nwqUC(63,L),e[s(597)](z,2048)||e.VdrAE(z,55296)&&e[s(700)](z,57343)?v+=_:(v+=h(z),w+=2)));else if(e.ZeIzi(e[s(997)](248,C),240))if(e[s(149)](w+3,n))v+=_;else if(N=p[e[s(1096)](e.aXNSA(w,l),1)],L=p[e.OmopZ(e[s(1226)](w,l),2)],j=p[e[s(1226)](w+l,3)],e[s(619)](e[s(457)](e.qMXnu(N,L<<8)|e[s(1227)](j,16),12632256),8421504))v+=_;else if(e[s(1488)]==="MYTiZ")_0x38ab4d[s(867)](_0x45132b,_0x77018d);else if(z=e[s(340)](e[s(770)](7,C)<<18|e.rKNqs(63,N)<<12,e[s(1088)](e[s(636)](63,L),6))|e[s(302)](63,j),e[s(1578)](z,65536)||e[s(391)](z,1114111))v+=_;else if(e[s(1007)](e[s(849)],s(440)))z-=65536,v+=e.eIuTF(h,e[s(1428)](e[s(624)](z,10),55296),e[s(1226)](e[s(1272)](1023,z),56320)),w+=3;else{let G=this._endpointManager?.[s(244)+"ntEndpoint"]();this._debug(s(335)+G),e.emJgD(_0x153c18)}else v+=_}return v}function q(a,n){let s=t,l={YrtrY:function(h,p){return e.CcIPv(h,p)},UQGRB:function(h,p){return e[H(707)](h,p)},BtOIz:function(h,p){return e.Piuee(h,p)}};if(e[s(500)](e[s(1400)],"uKXbg")){let{SeqID:h,LogID:p,service:_,LogIDNew:v,method:w}=_0x4e81ea[s(1215)];this[s(1049)]({SeqID:h,LogID:p,LogIDNew:v,service:_,method:w,headers:[{key:e[s(842)],value:"1"},{key:e[s(1638)],value:e.flVJx(v,"")},{key:e[s(1352)],value:"0"}]})}else{let h=n[s(721)],p=0;for(let w=0;w<h;w++)if(e[s(285)](e[s(1356)],e[s(753)])){if(l[s(205)](s(748),typeof _0x2d1d96)){let C=new _0x2cf1cc(l.UQGRB(_0xbc5bf,_0x39825b));return _0x222207(_0x38c107,C,0),C}return l[s(569)](_0xa13588,_0xef79f4)?new _0x503939(_0x5e40d5):new _0x331fea(_0x4ced73[s(1081)],_0x150c41[s(1035)+"et"],_0x5bb8b0[s(1651)+"th"])}else{let C=n[s(269)+"At"](w);e.mHYkO(C,55296)&&e[s(256)](C,56319)&&e.slEZM(e[s(1428)](w,1),h)&&(C=e[s(782)](e[s(1088)](C,10),n[s(269)+"At"](++w))-56613888),p+=C<128?1:e[s(1224)](C,2048)?2:C<65536?3:4}e[s(170)](we,a,p);let _=e[s(786)](re,a,p),v=a[s(260)];for(let w=0;e[s(1594)](w,h);w++){let C=n[s(269)+"At"](w);e[s(682)](C,55296)&&e[s(1477)](C,56319)&&e[s(1530)](w,1)<h&&(C=e.JWKDZ(e[s(1428)](e[s(338)](C,10),n[s(269)+"At"](++w)),56613888)),e.vsQnA(C,128)?v[_++]=C:(e[s(1623)](C,2048)?v[_++]=e[s(1681)](e[s(624)](C,6),31)|192:(e[s(1594)](C,65536)?v[_++]=e.sJDAq(e[s(310)](C,12)&15,224):(v[_++]=e[s(297)](e.UYWZa(e[s(1173)](C,18),7),240),v[_++]=e.qMXnu(e[s(175)](e.MtIIf(C,12),63),128)),v[_++]=e.qtVgU(e.ueVLl(e[s(353)](C,6),63),128)),v[_++]=e[s(1636)](63&C,128))}}}function $(a,n){let s=t,l=e[s(1274)](re,a,n.limit),h=a[s(260)],p=n[s(260)];for(let _=0,v=n.limit;e.esBBb(_,v);_++)h[e[s(673)](_,l)]=p[_]}function te(a){let n=t;if(e[n(1562)](e[n(1148)],n(604)))e[n(1124)](_0x3414ca,this[n(1396)+n(238)+"Id"]),e[n(766)](_0x1fd609,this[n(389)+n(1607)+n(267)]),this[n(1396)+n(238)+"Id"]=null,this[n(389)+n(1607)+n(267)]=null;else return a[n(260)][e.pIoJM(X,a,1)]}function et(a,n){let s=t,l=e.kzime(re,a,1);a[s(260)][l]=n}function me(a){let n=t,s={ZFZIn:function(_,v){return e[H(664)](_,v)},agyOb:function(_,v){return _!=v},AuOFN:e[n(666)],pVKDV:function(_,v){return e[n(906)](_,v)},vwTsH:e[n(693)]},l=0,h=0,p;do if(e.MYnxR===e[n(1130)]){if(s[n(1462)](_0x7af527,_0x2c84a6))return new _0x5ac317(_0x5b4fac,_0x29e191);if(s.ZFZIn(_0x52233a,_0x37a206)&&s[n(1048)](s[n(575)],typeof _0x193ff3))return new _0x14242d(_0x571279,_0xb35422);if(s[n(996)](_0x3d17d7,_0xe8c78)&&s[n(575)]!=typeof _0xab2153)return new _0x3e8e9f(_0x1de0a0,_0x126833);throw new _0x208187(s[n(1277)])}else p=e[n(629)](te,a),e[n(525)](l,32)&&(h|=e[n(1088)](e[n(636)](127,p),l)),l+=7;while(e.FehpE(128,p));return h}function we(a,n){let s=t;for(n>>>=0;e[s(576)](n,128);)e[s(1637)](et,a,e.MfDjg(e[s(1328)](127,n),128)),n>>>=7;e[s(422)](et,a,n)}function At(a,n){let s=t,l={Vtafa:function(w,C){return e[H(1224)](w,C)},HUeQE:function(w,C){return w|C},QXaug:function(w,C){return w&C},ZDttt:function(w,C){return e[H(1224)](w,C)},AYLJS:function(w,C){return e.eSqza(w,C)},NJdSL:function(w,C){return e.MtIIf(w,C)},sRelJ:function(w,C){return e[H(827)](w,C)},Flxgd:function(w,C){return e[H(1421)](w,C)},NpBkv:function(w,C){return e[H(1272)](w,C)},OIijX:function(w,C,N){return e.vkIhT(w,C,N)},WWxEE:s(571)},h=0,p=0,_=0,v;if(v=e.vrFTv(te,a),h=e[s(1300)](127,v),e[s(636)](128,v))if(e[s(1139)]!==e[s(1104)]){if(v=e[s(707)](te,a),h|=e[s(1346)](e[s(1421)](127,v),7),128&v&&(v=e[s(1168)](te,a),h|=e[s(1227)](e[s(534)](127,v),14),e.EtZKm(128,v)&&(v=e[s(471)](te,a),h|=e[s(338)](e[s(1559)](127,v),21),e.ueVLl(128,v)))){if(e.ccztE(e[s(439)],e[s(439)]))e[s(283)](_0x851883,_0x38ccfa,24),e[s(1092)](_0xdf3e53,_0x123028,_0x3461f3(_0x115420));else if(v=e.YCDzP(te,a),p=e.HSbDj(127,v),128&v&&(v=e[s(1672)](te,a),p|=e.NJSoA(e[s(882)](127,v),7),128&v&&(v=e[s(964)](te,a),p|=e.pqnXg(127,v)<<14,128&v))){if(e[s(969)](e[s(468)],e[s(468)]))BYFhlz[s(263)](_0x3ed5bd,2048)?_0x332c3f[_0x4f225a++]=BYFhlz[s(562)](BYFhlz[s(687)](_0x599f3c>>6,31),192):(BYFhlz[s(1182)](_0x5d73ba,65536)?_0x5883d[_0x30ba7a++]=BYFhlz[s(349)](BYFhlz[s(1134)](_0x5e1e82,12),15)|224:(_0x4da0fd[_0x18ea9c++]=BYFhlz[s(648)](BYFhlz.QXaug(BYFhlz.NJdSL(_0x26bd27,18),7),240),_0x2d5d48[_0x1a1848++]=BYFhlz[s(1643)](BYFhlz[s(1134)](_0x1cedf2,12),63)|128),_0x5918a8[_0x231159++]=BYFhlz[s(349)](BYFhlz[s(1134)](_0x307fef,6),63)|128),_0x542524[_0x21a975++]=BYFhlz[s(648)](BYFhlz[s(1039)](63,_0x41802a),128);else if(v=e.PsUrT(te,a),p|=(127&v)<<21,e[s(175)](128,v)&&(v=e.klvtf(te,a),_=e[s(985)](127,v),e[s(165)](128,v)))if(e[s(1553)](e[s(1142)],e[s(1142)]))v=e[s(426)](te,a),_|=e[s(496)](127,v)<<7;else return this[s(1129)][s(1527)+s(1204)]()}}}else{let w=l[s(523)](_0x76301f,l[s(427)],{message:_0x5806e0.message,code:_0x251424[s(1481)+s(1014)],error:_0x20beba});this["_dispatc"+s(1659)+s(972)](w)}return{low:h|e[s(338)](p,28),high:e[s(1571)](e[s(886)](p,4),e[s(158)](_,24)),unsigned:n}}function gt(a,n){let s=t;if(e[s(445)](e.nqEcm,"klEmH")){let l=e.YScJp(n.low,0),h=e[s(1306)](e.muLCa(e.Lkiqk(n.low,28),e[s(1677)](n.high,4)),0),p=e.HIrol(n[s(1564)],24),_=e[s(1562)](0,p)?e.cHUYY(0,h)?e[s(953)](l,16384)?e.hbWvb(l,128)?1:2:e[s(1055)](l,2097152)?3:4:e.vsQnA(h,16384)?e[s(1055)](h,128)?5:6:h<2097152?7:8:e[s(689)](p,128)?9:10,v=e[s(286)](re,a,_),w=a[s(260)];switch(_){case 10:w[e[s(1530)](v,9)]=e[s(165)](p>>>7,1);case 9:w[e[s(768)](v,8)]=e[s(306)](9,_)?128|p:e.HSbDj(127,p);case 8:w[e[s(1585)](v,7)]=_!==8?e[s(1597)](e[s(1140)](h,21),128):e[s(1559)](h>>>21,127);case 7:w[e[s(358)](v,6)]=e[s(1336)](7,_)?e[s(1207)](e.YScJp(h,14),128):e[s(1328)](e.Vycrx(h,14),127);case 6:w[e[s(1428)](v,5)]=e.WspIX(6,_)?e[s(640)](e[s(820)](h,7),128):e.ncnKW(e[s(1348)](h,7),127);case 5:w[e[s(358)](v,4)]=e.ipWqi(5,_)?e[s(846)](128,h):e[s(1272)](127,h);case 4:w[e[s(277)](v,3)]=_!==4?e[s(728)](l,21)|128:e.HoirL(l>>>21,127);case 3:w[e[s(1530)](v,2)]=e[s(222)](3,_)?e.kIoeR(e[s(840)](l,14),128):e[s(1097)](e[s(1164)](l,14),127);case 2:w[e[s(303)](v,1)]=_!==2?e[s(1207)](e[s(1140)](l,7),128):e[s(611)](e.VpnpH(l,7),127);case 1:w[v]=_!==1?128|l:e[s(1421)](127,l)}}else{let l=0,h=_0x5748c7,p=e[s(1166)](_0xe2f5d8,4);for(;h<p;){let{value:_,offset:v}=e[s(326)](_0x4f7850,_0x471a05,h);h=v,l=e[s(816)](e[s(808)](l,8),0),l+=_}return{value:l,offset:p}}}function nn(a){return e[t(707)](b,a)}function qt(a){return e[t(1165)](S,a)}let rn=65536,Yr=e[t(1436)],Ee=e[t(1056)](rn,rn),Te=Ee*Ee,tr=e[t(881)](Te,2),Ne=String[t(220)+"e"][t(269)+"At"];class xe{constructor(n,s,l){let h=t;this[h(1669)]=!0,this[h(1327)]=e[h(1571)](0,n),this[h(1564)]=e[h(304)](0,s),this[h(533)]=!!l}static[t(1669)](n){let s=t;if(e[s(903)](e[s(378)],e[s(1087)]))this[s(404)+s(710)]();else return n&&e[s(1614)](!0,n[s(1669)])}static fromBits(n,s,l){return new xe(n,s,l)}static[t(1697)+"s"](n,s,l){let h=t;return l?xe["fromByte"+h(455)](n,s):xe["fromByte"+h(548)](n,s)}static[t(1697)+t(455)](n,s){let l=t;return new xe(e[l(810)](e[l(1636)](n[0]|n[1]<<8,n[2]<<16),e[l(1191)](n[3],24)),e.jHNdT(e[l(1664)](n[4],e[l(1468)](n[5],8)),n[6]<<16)|e.ltsNZ(n[7],24),s)}static[t(1697)+t(548)](n,s){let l=t;return new xe(e[l(340)](n[4]<<24|e[l(749)](n[5],16)|n[6]<<8,n[7]),e[l(1118)](e[l(1118)](e[l(868)](n[0],24),e.qzQLB(n[1],16)),e[l(861)](n[2],8))|n[3],s)}static fromHash(n){let s=t;return e[s(1364)](n,Yr)?nl:new xe(e.BrmNt(e[s(304)](Ne[s(1363)](n,0),e[s(1468)](Ne.call(n,1),8))|e[s(868)](Ne[s(1363)](n,2),16),e[s(189)](Ne[s(1363)](n,3),24))>>>0,e[s(1393)](e[s(640)](e.BrmNt(e[s(1378)](Ne[s(1363)](n,4),e[s(868)](Ne.call(n,5),8)),e.nQbVi(Ne.call(n,6),16)),Ne[s(1363)](n,7)<<24),0),!0)}[t(1674)](){let n=t;return String[n(464)+"Code"](255&this[n(1327)],e[n(1272)](e[n(1164)](this[n(1327)],8),255),e[n(188)](this[n(1327)]>>>16,255),e.ZImAg(this.low,24),e[n(959)](255,this[n(1564)]),e[n(1604)](this[n(1564)]>>>8,255),e[n(636)](e[n(1348)](this[n(1564)],16),255),e[n(1306)](this[n(1564)],24))}static[t(1543)+"er"](n,s=!0){let l=t;if(e[l(1071)](isNaN,n))return s?Bp:nl;if(s){if(e[l(682)](n,Te))return zp}else{if(e.Egnlh(n,-tr))return Up;if(e[l(804)](e[l(1247)](n,1),tr))return Fp}return xe[l(514)](e.LDyDi(e[l(935)](n,Ee),0),e[l(435)](e.mIPeo(n,Ee),0),s)}toNumber(){let n=t;return this[n(533)]?e[n(1226)](e.SQVgy(e.tiHGk(this[n(1564)],0),Ee),this[n(1327)]>>>0):e.rgyyQ(e.xFYud(this[n(1564)],Ee),e[n(816)](this[n(1327)],0))}isZero(){let n=t;return e[n(285)](0,this[n(1564)])&&e[n(1456)](0,this[n(1327)])}[t(671)](n){let s=t;xe.isLong(n)||(n=xe[s(1543)+"er"](n));let l=e[s(1362)](this.high,16),h=65535&this[s(1564)],p=e.MNYSX(this[s(1327)],16),_=65535&this.low,v=e[s(816)](n[s(1564)],16),w=e[s(1230)](65535,n.high),C=n.low>>>16,N=65535&n[s(1327)],L=0,j=0,z=0,G=0;return G+=e[s(782)](_,N),z+=e[s(733)](G,16),G&=65535,z+=e[s(603)](p,C),j+=z>>>16,z&=65535,j+=e.EZGzD(h,w),L+=e.eoZLA(j,16),j&=65535,L+=e[s(547)](l,v),L&=65535,xe[s(514)](e[s(846)](e[s(1677)](z,16),G),e[s(621)](L,16)|j,this.unsigned)}[t(1537)](n){let s=t,l={WETKd:s(1184)};if(e[s(445)](e[s(1200)],e[s(1200)]))this.emit(l[s(1271)],_0x11a011),this.onopen&&this.onopen(_0x36184a);else return xe[s(1669)](n)||(n=xe.fromNumber(n)),e[s(619)](this.unsigned,n.unsigned)&&e.bvSfs(this[s(1564)]>>>31,1)&&e[s(285)](e.pnlfP(n[s(1564)],31),1)?!1:e[s(1238)](this.high,n[s(1564)])&&this[s(1327)]===n.low}addOne(){let n=t;if(e[n(285)](n(599),e[n(878)])){let s=_0x3332b0[_0x44e79f++];if(e.WTCfC(s,127))_0x17be62+=_0x4a15ff[n(464)+n(1503)](s);else if(e[n(1448)](s,192)&&e[n(597)](s,224))_0x52998d+=_0x1f32bd["fromChar"+n(1503)](e.NTroB(e.qVHro(e[n(165)](31,s),6),e.ncnKW(63,_0x23147a[_0x290904++])));else if(s>=224&&s<240)_0x4f366e+=_0x36532b[n(464)+n(1503)](e[n(1636)](e[n(397)](15,s)<<12|e.poqDj(e.cGRxa(63,_0x4e9518[_0x32b2a7++]),6),e[n(1091)](63,_0x2b4857[_0x4dba87++])));else if(e[n(414)](s,240)){let l=(e[n(640)](e[n(262)](e[n(615)](e[n(1604)](7,s),18),e.DjlJw(e[n(534)](63,_0x5a5fa9[_0x12ee3d++]),12)),e[n(749)](e[n(1091)](63,_0x136ee7[_0x2aa700++]),6))|63&_0x27260c[_0x5349f6++])-65536;_0x56ccc0+=_0x43fa28[n(464)+n(1503)](e[n(678)](55296,l>>10)),_0x585711+=_0x47afe0[n(464)+"Code"](56320+e[n(959)](1023,l))}}else return e[n(1553)](-1,this[n(1327)])&&e[n(285)](-1,this[n(1564)])?xe.fromBits(0,0,this[n(533)]):e[n(917)](-1,this.low)?xe[n(514)](0,e.iIRGY(this[n(1564)],1),this.unsigned):xe[n(514)](e[n(1688)](this[n(1327)],1),this.high,this[n(533)])}[t(1398)](n){let s=t;return n?this[s(593)+"E"]():this[s(197)+"E"]()}[t(593)+"E"](){let n=t,s=this[n(1564)],l=this.low;return[e.CaJGW(255,l),l>>>8&255,e[n(997)](e[n(343)](l,16),255),e.ApuKX(l,24),255&s,e.tiHGk(s,8)&255,e[n(918)](s>>>16,255),e[n(377)](s,24)]}[t(197)+"E"](){let n=t,s=this[n(1564)],l=this[n(1327)];return[e[n(377)](s,24),e[n(918)](e[n(886)](s,16),255),e.dXFEb(e[n(902)](s,8),255),e[n(635)](255,s),e[n(1555)](l,24),e[n(165)](e[n(886)](l,16),255),e[n(501)](e[n(153)](l,8),255),255&l]}}let nl=new xe(0,0,!1),Bp=new xe(0,0,!0),Fp=xe[t(514)](-1,2147483647,!1),zp=xe[t(514)](-1,-1,!0),Up=xe[t(514)](0,-2147483648,!1);var sn=(function(a){let n=t;if(e.dxsoa(e.gzQrB,"LNPgt")){let s=e[n(819)][n(1480)]("|"),l=0;for(;;){switch(s[l++]){case"0":return a;case"1":a[a[e[n(618)]]=5004]=e[n(618)];continue;case"2":a[a[e[n(1070)]]=5003]=e[n(1070)];continue;case"3":a[a[e[n(677)]]=5002]=e[n(677)];continue;case"4":a[a[e[n(614)]]=5005]=e[n(614)];continue;case"5":a[a[e[n(1612)]]=5001]=e[n(1612)];continue}break}}else return this[n(216)+"T"]||this[n(323)+"X"]?this["_miniNav"+n(1595)+n(418)]:(this[n(1179)+"er"]||this._isWorker)&&this[n(497)][n(1143)+"tworkCha"+n(981)]?_0x129c16[n(1351)]:!0})({});class nr{constructor(n){let s=t;this[s(482)]=n,this[s(1415)]=null}}class rl extends nr{constructor(n,s){let l=t,h={VhXot:function(p,_){return e.Aqmbf(p,_)},gtMcv:function(p,_){return e.SchdW(p,_)},uvbxK:function(p,_){return e.PKOrn(p,_)},cnhof:function(p,_){return p<<_},YTqft:function(p,_){return e[H(1060)](p,_)},moBpP:function(p,_){return e[H(1385)](p,_)},HFJxP:function(p,_){return p|_},jScip:function(p,_){return e[H(699)](p,_)},mOaHw:function(p,_){return e[H(611)](p,_)}};if(e[l(606)](e[l(607)],l(712))){let p=_0x4f8e60[l(269)+"At"](_0x526366);OZdaIC[l(726)](p,55296)&&p<=56319&&OZdaIC[l(958)](_0x4aa354+1,_0x4d3192)&&(p=OZdaIC[l(1557)](OZdaIC.cnhof(p,10)+_0x2aa732[l(269)+"At"](++_0x19a808),56613888)),OZdaIC[l(958)](p,128)?_0x93ed48[_0x250bb9++]=p:(p<2048?_0x32b76d[_0x24bd87++]=OZdaIC.YTqft(OZdaIC[l(301)](p,6),31)|192:(p<65536?_0x197d3b[_0x31dd82++]=OZdaIC[l(1433)](OZdaIC.moBpP(p,12)&15,224):(_0x2dcee5[_0x22a068++]=OZdaIC[l(204)](OZdaIC[l(1671)](OZdaIC[l(301)](p,18),7),240),_0x1ca8c6[_0x3037d2++]=OZdaIC[l(204)](OZdaIC.moBpP(p,12)&63,128)),_0x492ebc[_0xcfbed6++]=OZdaIC[l(301)](p,6)&63|128),_0x41da74[_0xa1c6d0++]=OZdaIC.YTqft(63,p)|128)}else super(n),this[l(1215)]=s&&s[l(1215)]||null}}class il extends nr{constructor(n,s){let l=t,h=e[l(1005)][l(1480)]("|"),p=0;for(;;){switch(h[p++]){case"0":this.error=s&&s.error||null;continue;case"1":super(n);continue;case"2":this[l(1215)]=s&&s.message||"";continue;case"3":this[l(557)]=s&&s.lineno||0;continue;case"4":this[l(658)]=s&&s[l(658)]||0;continue;case"5":this[l(785)]=s&&s[l(785)]||"";continue;case"6":this[l(731)]=s&&s[l(731)]||5001;continue}break}}}class sl extends nr{constructor(n,s){let l=t,h=e[l(459)][l(1480)]("|"),p=0;for(;;){switch(h[p++]){case"0":this[l(731)]=s&&s.code||0;continue;case"1":this[l(1533)]=s&&s[l(1533)]||!1;continue;case"2":this[l(714)]=s&&s[l(714)]||"";continue;case"3":super(n);continue;case"4":this["willReco"+l(227)]=s&&s[l(1501)+l(227)]||!1;continue}break}}}class ol extends nr{constructor(n,s){let l=t,h={dwnNR:"success",TxTkt:e[l(210)],Olfrd:e[l(672)]};e[l(909)](l(179),e.LxFIB)?(_0x21fb9e(h[l(1145)]),this[l(460)](h[l(995)],_0x3802e1),this[l(460)](h[l(1278)],_0x4ae3c7)):(super(n),this[l(450)]=s&&s[l(450)]||null)}}class al extends ol{constructor(n,s){let l=t;super(n),this[l(450)]=s&&s[l(450)]||null,this.message=s&&s[l(1215)]||null}}class cl extends nr{constructor(n,s){let l=t;super(n),this[l(450)]=s&&s.data||null}}function lt(a,{message:n,code:s,error:l}){return new il(a,{message:n,code:s,error:l})}function mt(a,{code:n,reason:s,wasClean:l,willReconnect:h}){return new sl(a,{code:n,reason:s,wasClean:l,willReconnect:h})}function dl(a,{data:n,message:s}){return new al(a,{data:n,message:s})}function ll(a,{data:n}){return new cl(a,{data:n})}function fa(a,{message:n}){return new rl(a,{message:n})}class ul{constructor(n,s){let l=t;this[l(1628)+"s"]=n,this[l(288)+"es"]=s,this["currentI"+l(922)]=0,this[l(1333)+l(974)+l(271)+"t"]=0}[t(746)+"pointCon"+t(1512)](){let n=t;this["currentI"+n(922)]=0,this[n(1333)+"ndpointT"+n(271)+"t"]=0}[t(243)+"es"](){let n=t;this["currentE"+n(974)+n(271)+"t"]=0}[t(244)+t(592)+"nt"](){let n=t;return this[n(1628)+"s"][this[n(355)+n(922)]]}["getCurre"+t(592)+t(229)+t(1634)](){let n=t;return this[n(1333)+n(974)+n(271)+"t"]}[t(1229)+t(993)+"es"](){let n=t;return!!(e[n(484)](this[n(355)+"ndex"],this[n(1628)+"s"][n(721)])||this[n(355)+n(922)]===e[n(415)](this[n(1628)+"s"][n(721)],1)&&e[n(642)](this[n(1333)+"ndpointT"+n(271)+"t"],this[n(288)+"es"]))}[t(1194)+"rentEndp"+t(779)+t(1372)+t(1424)](){let n=t;return this.currentIndex==this[n(1628)+"s"][n(721)]?!0:this["currentE"+n(974)+n(271)+"t"]>this.maxRetries}[t(980)+"ackupEnd"+t(1190)+"UpdateCo"+t(1102)](){let n=t;if(e[n(1644)](e.arXHt,n(453)))return this[n(1333)+"ndpointTriesCount"]=1,this[n(355)+n(922)]++,this[n(1628)+"s"][this[n(355)+n(922)]];if(this._options["disableAutoRecon"+n(235)]||this[n(717)+n(1673)])return;this[n(1177)+"econnect"]()}["getCurre"+t(592)+t(160)+"ateCount"](){let n=t,s={XWCHf:function(l,h){return e.ekmzo(l,h)},mNPdX:function(l,h){return l instanceof h},PqExp:function(l,h){return e[H(442)](l,h)},zWExK:e[n(668)]};return e[n(1069)]!==e[n(800)]?(this[n(1333)+n(974)+n(271)+"t"]++,this[n(244)+"ntEndpoint"]()):s.XWCHf(n(748),typeof _0xbf6f2d)&&(s[n(1412)](_0x57f342,_0x65ce3e)||_0x3d7f11[n(1081)]&&s[n(911)](_0x4380ab[n(1081)],_0x27f08a))||typeof _0x111eea!="string"?"":(_0x5acc92[n(1221)](_0x12fe06),s[n(1691)])}}let rr=(e[t(666)]!=typeof globalThis&&e[t(465)](e.xGVBO,globalThis[t(1587)+t(1174)].name)||e[t(1459)](e[t(666)],typeof window)&&e.RDudZ(e[t(869)],window["construc"+t(1174)][t(1162)]))&&e.FPQWf("undefined",typeof document),Pn=e.FPQWf(e[t(666)],typeof globalThis)&&(e[t(456)](e.nCiaH,globalThis[t(1587)+t(1174)][t(1162)])||e[t(904)]===globalThis[t(1587)+t(1174)][t(1162)])&&e.aVJKl!=typeof tt,Xr=(e[t(1365)]("undefined",typeof globalThis)&&e[t(493)](e[t(201)],globalThis[t(1587)+"tor"][t(1162)])||e[t(1631)](e.aVJKl,typeof globalThis)||e[t(1529)](t(579)+"d",typeof globalThis)&&!!globalThis[t(298)+t(1016)])&&e[t(666)]!=typeof wx,Qr=e[t(1459)](t(579)+"d",typeof globalThis)&&(e.AIxLp(e[t(904)],globalThis[t(1587)+"tor"][t(1162)])||e.cFEvx(e[t(1642)],globalThis[t(1587)+t(1174)][t(1162)])||t(333)+t(1381)+t(1167)===globalThis["construc"+t(1174)].name)&&e.oBuEn(e[t(666)],typeof self),qp=e[t(1467)](e[t(666)],typeof globalThis)&&e[t(201)]===globalThis[t(1587)+t(1174)][t(1162)]&&e[t(432)](e.aVJKl,typeof global)&&e[t(797)](e.nCiaH,global[t(1587)+"tor"].name)&&e[t(666)]!=typeof process&&!!process[t(870)];class ha{constructor(){let n=t;this[n(856)+"rs"]={}}[t(1701)](n,...s){let l=t,h=this[l(856)+"rs"][n];if(h)h[l(1144)]()[l(1302)](p=>p.fn[l(550)](p[l(1586)],s));else if(e[l(903)](e[l(1377)],n)&&!this[l(892)]){let p=s.length&&s[0];if(p instanceof Error)throw p;let _=new Error(e[l(538)](l(725)+"d error.",p?e[l(1678)](e[l(1678)](" (",p.message),")"):""));throw _[l(444)]=p,p}return this}off(n,s){let l=t;if(n===void 0)this._listeners={};else if(e[l(1614)](void 0,s))this[l(856)+"rs"][n]=null;else{let h=this._listeners[n];if(h)for(let p=0;e.UCLjy(p,h[l(721)]);)e[l(650)](h[p].fn,s)?h[l(1077)](p,1):++p}return this}on(n,s,l){let h=t;return(this[h(856)+"rs"][n]||(this[h(856)+"rs"][n]=[]))[h(1475)]({fn:s,ctx:l||this}),this}}class Gp extends ha{[t(1624)+t(719)+t(1367)](n){let s=t;return n[s(429)]||n.errNo?(s(675)+" "+(n[s(429)]||"")+s(720)+(n[s(983)]||""))[s(413)]():JSON[s(1235)+"y"](n)}constructor(n,s,l){let h=t;super(),this[h(156)]=null,Xr&&wx[h(483)+h(253)]&&(this[h(156)]=wx[h(483)+h(253)]({url:n,protocols:s,header:l,fail:this["_createS"+h(295)+h(829)][h(280)](this),success:this[h(219)+h(401)+h(213)+"ler"].bind(this)})),Pn&&tt[h(483)+h(253)]&&(this[h(156)]=tt[h(483)+h(253)]({url:n,protocols:s,header:l,fail:this[h(219)+h(295)+h(829)].bind(this),success:this[h(219)+h(401)+h(213)+"ler"][h(280)](this)}))}[t(219)+t(401)+t(213)+t(1620)](){let n=t;e.NcqMr!==e.NcqMr?(_0x1aa0b1[n(867)](_0x2a4100,_0x307568),_0x226fdd[n(867)](_0x16d6b0,_0x5f4424)):Promise.resolve().then(()=>{let s=n,l={MiJFn:function(h,p){return e[H(682)](h,p)},kmPPP:function(h,p){return e[H(1524)](h,p)}};if(e[s(294)](e[s(218)],s(469)))this["_addWsLi"+s(1588)]();else{for(_0x74c149>>>=0;xlPMex[s(984)](_0x2fc09,128);)_0x8506a1(_0x59a14d,xlPMex.kmPPP(127,_0x56e920)|128),_0x24f8a9>>>=7;_0x3571f7(_0x6542d,_0x46afce)}})}[t(219)+"ocketFai"+t(829)](n){let s=t,l={LCjQa:function(h,p){return e[H(775)](h,p)},iWurH:function(h){return h()}};Promise[s(662)]()[s(1286)](()=>{let h=s;if(e[h(1582)]!=="OFoQw"){let p=lt(e[h(1377)],{message:this[h(1624)+"rrorMessage"](n)});this[h(1701)](e[h(1377)],p);let _=e[h(319)](mt,h(966),{reason:this[h(1624)+"rrorMess"+h(1367)](n)});this.emit(e.Iyrmc,_)}else AOpVKG.LCjQa(_0x37668d,_0x1cbb16(_0x4f1dae[h(792)])),AOpVKG[h(1093)](_0x848a48)})}[t(1047)+t(1588)](){let n=t,s={pTSDy:function(l){return e.emJgD(l)},avQPM:function(l,h,p){return e[H(930)](l,h,p)},dzsWi:"close",gxcwO:function(l,h,p){return e.DQJZN(l,h,p)},OmqOR:e[n(1377)]};e.xrCTp(e[n(1461)],n(863))?(_0x328069(_0x23e125.error),XzBrSL[n(691)](_0x44ef52)):(this[n(156)][n(1479)](l=>{let h=n;this[h(1701)](h(1184),s[h(250)](ll,h(1184),{...l,data:l[h(429)]||""}))}),this[n(156)][n(862)](l=>{let h=n;this[h(1701)](s[h(841)],s.gxcwO(mt,s[h(841)],{...l}))}),this[n(156)][n(1472)+"e"](l=>{let h=n;this[h(1701)](e.jxicE,e[h(1202)](dl,e[h(1067)],{...l}))}),this[n(156)][n(443)](l=>{let h=n;this[h(1701)](s[h(916)],s[h(489)](lt,s[h(916)],{...l,message:l.errMsg||""}))}))}send(n){let s=t,l={WSTXk:function(h,p){return h===p},gSgfp:function(h,p){return e[H(1591)](h,p)},gdWNs:function(h,p){return e[H(852)](h,p)},UXtZO:e[s(1483)],FlWDp:e[s(210)],aMSCk:function(h,p,_){return e[s(422)](h,p,_)},OpffT:e[s(1377)],vzhof:e[s(226)],Ozqmj:function(h,p,_){return h(p,_)}};if(e[s(442)](n,Uint8Array))if(e.FAAan(e.AhVLf,s(1285))){let h=n[s(1081)].slice(n[s(1035)+"et"],n.byteLength+n[s(1035)+"et"]);this._socket&&this[s(156)].send({data:h,fail:p=>{let _=s;if(l[_(1019)](l[_(522)],l[_(522)]))this.emit(l.OpffT,l.aMSCk(lt,"error",{message:this["_formatE"+_(719)+_(1367)](p)}));else{let{pingInterval:v,pingFrequency:w}=this[_(497)];if((l.WSTXk("hi",_0x2b3c9d[_(450)])&&l[_(630)](_(1598),w)||l[_(1019)](l[_(187)],w))&&(this[_(344)+_(375)](),this[_(1701)](l.FlWDp,"success"),this[_(1396)+_(238)+"Id"]=l[_(1146)](_0x84b7c2,this._ping[_(280)](this),v)),l[_(630)]("hi",_0x222b6f[_(450)]))return;try{_0x563688(this,_0x66b307,[_0x4d1f5a,_0x4b3198,_0x125e50,_0x887e72,_0x188795,_0x2a9499])}catch(C){let N=_0x3ac4bf(l.OpffT,{message:C.message,code:_0x2e40f0[_(1481)+_(1014)],error:C});this[_(1141)+_(1659)+_(972)](N)}}}})}else this["_message"+s(836)][s(1445)](),this[s(541)+s(836)][s(1475)](_0x12a370);else this[s(156)]&&this[s(156)][s(776)]({data:n,fail:h=>{let p=s;this.emit(l[p(853)],l[p(1159)](lt,l[p(853)],{message:this[p(1624)+"rrorMess"+p(1367)](h)}))}})}[t(966)](n,s){let l=t;if(e.ipWqi(e[l(1575)],e[l(1305)]))this[l(156)]&&this._socket[l(966)]({code:n,reason:s});else return this[l(1333)+l(974)+"riesCount"]=1,this["currentI"+l(922)]++,this.endpoints[this[l(355)+l(922)]]}[t(515)+t(799)](n,s){let l=t,h={piYQT:function(p,_){return e[H(1133)](p,_)},SsRAG:function(p,_){return e[H(348)](p,_)},mSgvL:function(p,_){return p(_)},xCHuM:function(p,_){return e[H(322)](p,_)},iPmoD:function(p,_){return e[H(1438)](p,_)},HINFf:function(p,_){return e[H(768)](p,_)},iMAcU:function(p,_){return e.orDjF(p,_)}};if(e[l(642)](e[l(380)],e[l(998)])){let p=h[l(1355)](_0x424733,8192),_=p>>>1,v=null,w=p;return function(C){let N=l;if(h[N(1450)](C,1)||h.SsRAG(C,_))return h.mSgvL(_0x325325,C);h[N(564)](w,C)>p&&(v=h[N(908)](_0x3405d5,p),w=0);let L=_0xbbe1cf[N(1363)](v,w,w+=C);return h[N(992)](7,w)&&(w=h[N(1437)](7|w,1)),L}}else this.on(n,s)}["removeEventListe"+t(1025)](n,s){this[t(460)](n,s)}get[t(1262)+"te"](){let n=t;return this[n(156)][n(1262)+"te"]}get[t(246)+"pe"](){let n=t;return this[n(156)][n(246)+"pe"]}set[t(246)+"pe"](n){}get[t(735)](){let n=t;if(e.zNgDI(e[n(1460)],e[n(1460)]))this["flushExp"+n(287)]();else return this[n(156)][n(735)]}get[t(1411)](){let n=t;if(e.KunFT(e[n(510)],e[n(510)]))++_0xb060ba,_0x4194c8+=4;else return this[n(156)][n(1411)]}get[t(1466)+"ns"](){let n=t;return this[n(156)][n(1466)+"ns"]}get[t(315)+"Amount"](){return 0}}function Hp(a,n){let s=t;if(n)return new n(a.url,a[s(1411)]);if(e[s(664)](Xr,Pn))return new Gp(a[s(735)],a[s(1411)],a[s(1635)]);if(e[s(664)](rr,Qr)&&s(579)+"d"!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(735)],a[s(1411)+"s"])}function jp(a){let n=t,s=e[n(1590)].split("|"),l=0;for(;;){switch(s[l++]){case"0":if(a)return!0;continue;case"1":if(Pn&&tt["connectS"+n(253)])return!0;continue;case"2":if(Xr&&wx[n(483)+n(253)])return!0;continue;case"3":return!1;case"4":if(e.flVJx(rr,Qr)&&e[n(1529)](e[n(666)],typeof WebSocket)&&WebSocket)return!0;continue}break}}function fl(a,n,s){let l=-1;async function h(p){let _=H;return p<=l?Promise[_(736)](new Error(e[_(1397)])):(l=p,p===s.length?Promise[_(662)]():s[p][_(280)](a)(n,h[_(280)](null,p+1)))}e.KrPrJ(h,0)}function hl(a){let n=t,s=0,l=0;for(let h=0;e[n(689)](h,a[n(721)]);++h)l=a[n(269)+"At"](h),e[n(1696)](l,128)?s+=1:e.qWhoQ(l,2048)?s+=2:e[n(1249)](e.HoirL(64512,l),55296)&&e[n(642)](e[n(1549)](64512,a[n(269)+"At"](h+1)),56320)?(++h,s+=4):s+=3;return s}function xl(a,n,s){let l=t;if(e[l(1447)](e[l(415)](s,n),1))return"";let h="";for(let p=n;e[l(1696)](p,s);){let _=a[p++];if(e.NZkxn(_,127))h+=String[l(464)+l(1503)](_);else if(_>=192&&e[l(452)](_,224))h+=String["fromChar"+l(1503)](e[l(1487)](e[l(1088)](e.UtQfq(31,_),6),63&a[p++]));else if(_>=224&&e[l(1209)](_,240))h+=String[l(464)+l(1503)](e[l(808)](e.MWxzd(15,_),12)|e.lgDnr(63,a[p++])<<6|e[l(1097)](63,a[p++]));else if(e[l(1409)](_,240))if(e[l(936)](e[l(1211)],l(962))){let v=_0x584492[l(1215)][l(955)];v&&_0x44e813[l(1196)+"rs"](v)}else{let v=e.ojmFr(e[l(633)](e[l(1600)](e[l(435)](e[l(1679)](7&_,18),e[l(1191)](e[l(1667)](63,a[p++]),12)),e[l(1346)](63&a[p++],6)),e.vcRru(63,a[p++])),65536);h+=String[l(464)+"Code"](e[l(314)](55296,e[l(696)](v,10))),h+=String[l(464)+l(1503)](e.DKTLp(56320,e[l(543)](1023,v)))}}return h}function xa(a,n,s){let l=t,h=s,p,_;for(let v=0;e.hbWvb(v,a[l(721)]);++v)if(p=a[l(269)+"At"](v),p<128)n[s++]=p;else if(e[l(505)](p,2048))n[s++]=e[l(1422)](e[l(1126)](p,6),192),n[s++]=e[l(640)](e[l(752)](63,p),128);else if(e[l(1465)](e[l(770)](64512,p),55296)&&e[l(1115)](64512&(_=a[l(269)+"At"](v+1)),56320)){let w=(l(1085)+"3|2")[l(1480)]("|"),C=0;for(;;){switch(w[C++]){case"0":p=e[l(150)](e[l(277)](65536,e[l(1565)](1023&p,10)),e[l(1275)](1023,_));continue;case"1":++v;continue;case"2":n[s++]=e[l(1207)](e.Zmxzo(63,p),128);continue;case"3":n[s++]=e[l(1487)](e[l(1438)](e[l(353)](p,6),63),128);continue;case"4":n[s++]=e[l(527)](p>>12,63)|128;continue;case"5":n[s++]=e[l(1031)](e[l(239)](p,18),240);continue}break}}else n[s++]=e[l(1378)](e[l(1195)](p,12),224),n[s++]=e[l(467)](e[l(1125)](p,6),63)|128,n[s++]=63&p|128;return e[l(1675)](s,h)}async function pl(a){let n=t;if(e.oMvOM==typeof a){let s=new Uint8Array(e[n(317)](hl,a));return e[n(386)](xa,a,s,0),s}return e[n(258)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a.buffer,a[n(1035)+"et"],a[n(1651)+"th"])}function Wp(a){let n=t,s={CWmHy:function(h,p,_,v){return h(p,_,v)}};if(e[n(350)](e.pdSif,"CxTXQ"))for(var l in _0x3e928a)bFitjK[n(1153)](_0x234a2f,_0x339a39,l,{get:_0x1cc1b2[l],enumerable:!0});else try{return e[n(1459)](e.oMvOM,typeof a)&&(e[n(1563)](a,ArrayBuffer)||a[n(1081)]&&e[n(249)](a.buffer,ArrayBuffer))||e[n(1529)](e.oMvOM,typeof a)?"":(JSON[n(1221)](a),e.BqAqU)}catch{return e[n(1220)](e[n(1580)],typeof a)?e[n(706)]:""}}let Kp=(a,n)=>{let s=t;switch(a){case e[s(1213)]:case e[s(968)]:return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class $p{constructor(n){let s=t;this["maxLossC"+s(1634)]=n,this[s(1095)]=0}[t(1561)](){let n=t;e[n(1068)](e[n(434)],n(1470))?this.count++:this.emit(e[n(1106)],e.ljBru(_0x19f84b,n(966),{..._0x1385f8}))}["checkRea"+t(1532)+"nt"](){let n=t;return e[n(1449)](this[n(1095)],this.maxLossCount)}[t(1369)+t(196)](n=0){let s=t;this.maxLossCount=n,this[s(1095)]=0}}async function Vp(a){let n=t,s={uubbt:function(l,h){return e[H(973)](l,h)},pITTf:function(l,h){return l>>>h},xtzzV:function(l,h){return l>>>h},SiOwZ:function(l,h){return e.UYWZa(l,h)},kMbMS:function(l,h){return e[H(975)](l,h)},EVvPg:e[n(747)],wiOGm:function(l,h){return e[n(431)](l,h)},istNb:n(1314)+n(1314)+n(1314)+n(1314)};return new Promise(l=>{let h=n;if(e[h(445)](e.dQExH,e[h(851)])){let p=this.high,_=this[h(1327)];return[RliNNi[h(190)](255,_),RliNNi.pITTf(_,8)&255,RliNNi.pITTf(_,16)&255,RliNNi[h(758)](_,24),RliNNi.uubbt(255,p),RliNNi.xtzzV(p,8)&255,RliNNi[h(342)](p>>>16,255),RliNNi[h(690)](p,24)]}else{if(!rr)return e[h(967)](l,e[h(747)]);try{let p=document[h(1128)+h(737)](e[h(617)]);window[h(433)+h(926)]=_=>{let v=h;document[v(332)]["removeCh"+v(894)](p),window.frontierJSONP=void 0,l(_&&_[v(588)]||s[v(282)])},p.type="text/jav"+h(529),p.src=e[h(322)](a[h(270)](/^ws/,e[h(1296)]),e.ilGrt);try{document[h(332)][h(1246)+h(894)](p)}catch{document[h(332)][h(915)+h(894)](p)}}catch{if(e.ipWqi(e[h(402)],h(159)))window[h(433)+h(926)]=void 0,e[h(185)](l,h(945)+h(714));else{let p=/(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}/[h(1476)](_0x42bc40),_=/(([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]))/[h(1476)](_0x8e0ada);return p?RliNNi[h(1109)](_0x3a7a51,_0x27d442):_?_0x59a8c4(_0x66cf95):RliNNi[h(392)]}}}})}function on(a,n,s){let l=t;return!!a?.[l(1505)](h=>h[l(1254)]===n&&h[l(1391)]===s)}function ir(a,n){let s=t;return a?.[s(1505)](l=>l[s(1254)]===n)?.[s(1391)]}let pa=null;async function Jp(){let a=t;return pa||(pa=Promise.resolve().then(zt[a(280)](zt,e[a(1474)]))),pa}class Zp extends ha{constructor(n,s){let l=t;super(),this._dbName=n,this[l(245)]=s,this[l(1129)]=void 0,this[l(382)+l(698)]=null}async[t(151)](){let n=t;if(e[n(1591)](e[n(1180)],e.DlYTH))await this[n(1003)]();else return _0x1567a1(_0x22d520[n(550)](xJiVKM.stGmx(_0x390900,this),_0x175958))}async[t(1003)](){let n=t,s={rNDMK:function(l){return e[H(1002)](l)},IPhat:function(l,h,p,_){return e[H(1083)](l,h,p,_)}};if(!this[n(1129)]){if(this[n(382)+n(698)])return this[n(382)+n(698)];try{if(n(476)===e.JzCfZ)return _0x3f82f0(e[n(1041)](_0x4bd9bc,_0x47ce5f));{let l=this[n(1264)],h=this[n(245)];this[n(382)+"mise"]=(async()=>{let p=n,{openDB:_}=await s[p(1205)](Jp);this[p(1129)]=await s[p(1645)](_,"frontier_"+l,1,{upgrade(v){v["createOb"+p(622)+"e"](l,{keyPath:h})}})})(),await this[n(382)+"mise"]}}catch(l){console[n(567)](l)}finally{this[n(382)+n(698)]=null}}}async[t(531)](n){let s=t,l={XVOZD:function(h,p,_){return h(p,_)},kWCuQ:function(h,p,_){return e[H(1690)](h,p,_)},kaYCA:function(h,p){return e[H(631)](h,p)},COEYm:function(h,p,_){return e[H(276)](h,p,_)},mcXnu:function(h,p,_){return h(p,_)}};if(e[s(558)](e[s(1567)],e[s(1567)])){let h=_0x4e8f41[s(1254)];h!==void 0&&(WHxIJg[s(961)](_0xafb47d,_0x3eb4ff,10),WHxIJg.kWCuQ(_0x1b364f,_0x26d70b,h));let p=_0x8c2518[s(1391)];WHxIJg[s(991)](void 0,p)&&(WHxIJg[s(1569)](_0x18d5ac,_0x58fd50,18),WHxIJg[s(1353)](_0x1b5375,_0x15a8a1,p))}else try{return await this[s(1003)](),this[s(1129)]?.[s(531)](this[s(1264)],n)}catch(h){if(e[s(1493)](e[s(299)],e.TnDBa))return this._socket.protocol;console[s(567)](h)}}async set(n,s){let l=t;return await this._init(),this[l(1129)]?.[l(1108)](this[l(1264)],n)}async[t(1267)](n){let s=t,l={FkNpU:function(h,p){return e[H(1110)](h,p)},NrYbM:function(h,p){return e[H(608)](h,p)},bpDWT:e[s(706)],FJgVy:e[s(668)],kgcie:"applicat"+s(1317)+s(399)+"=utf-8",HuZIc:"string",PAglb:e[s(1592)]};try{if(e[s(372)](e[s(1269)],e[s(1269)]))if(l[s(366)](_0x1a8138[s(955)],_0x246b5e)){let h=this[s(497)][s(1576)+"ncoding"]instanceof _0x5b5721?{force:!!this[s(497)]["payloadE"+s(1245)][s(754)],encoding:this[s(497)].payloadEncoding.encoding?this[s(497)]["payloadE"+s(1245)][s(424)][s(270)](/\s/g,"")[s(361)+s(573)]():""}:{force:!1,encoding:this._options[s(1576)+"ncoding"]?this[s(497)][s(1576)+s(1245)].replace(/\s/g,"")[s(361)+"ase"]():""},p=_0x687bc5["payloadE"+s(1245)]?_0x316f59["payloadE"+s(1245)][s(270)](/\s/g,"")["toLowerC"+s(573)]():"",_=l[s(585)](this[s(497)][s(999)+"ype"],_0x83b718)?{force:!!this[s(497)][s(999)+s(572)].force,type:this[s(497)][s(999)+s(572)].type?this[s(497)][s(999)+s(572)][s(482)][s(270)](/\s/g,"")[s(361)+s(573)]():""}:{force:!1,type:this[s(497)]["payloadT"+s(572)]?this._options[s(999)+s(572)][s(270)](/\s/g,"")[s(361)+s(573)]():""},v=_0x2fa944[s(999)+s(572)]?_0x1fb1bb[s(999)+s(572)][s(270)](/\s/g,"")["toLowerC"+s(573)]():"",w=_[s(754)]?_.type:v||_[s(482)],C=h[s(754)]?h[s(424)]:p||h[s(424)],N=[l[s(873)],l.FJgVy,l[s(1492)],l[s(866)]],L=[s(1596)+"e",l[s(192)]];this[s(497)][s(1525)+s(1670)+s(336)+"ad"]&&N[s(859)](w)&&(!C||L.includes(C))?_0x4e6c8d["textPayl"+s(1698)]=_0x3e9739(_0x1dc301[s(955)],0,_0x5862a9[s(955)][s(1651)+"th"]):_0x59df46[s(900)+s(1698)]=""}else _0x540934[s(900)+s(1698)]="";else return await this[s(1003)](),this._qosDB?.[s(191)](this._dbName,n)}catch(h){console.log(h)}}async[t(1199)](){let n=t;try{return await this[n(1003)](),this[n(1129)]?.clear(this[n(1264)])}catch(s){console[n(567)](s)}}async[t(695)](){let n=t;return await this._init(),this[n(1129)]?.getAllKeys(this[n(1264)])}async getAll(){let n=t;return e[n(520)]("JbXMP",e.QHZgY)?(await this[n(1003)](),this._qosDB?.[n(1066)](this[n(1264)])):this._qosDB?.[n(1267)](_0x445044)}async closeDB(){let n=t;try{this[n(1129)]?.[n(966)](),this._qosDB=void 0}catch(s){console[n(567)](s)}}get[t(381)](){let n=t;if(e[n(1021)]("AEnUb",e[n(670)]))_0x431dae instanceof _0xdab201&&_0x103397[n(867)](_0x24f853,_0x1be908);else try{return!!this[n(1129)]}catch(s){return console[n(567)](s),!1}}}class Yp{constructor(n,s){let l=t;this._DBName=n,this[l(1693)]=s,this._qosDB=localStorage}async openDB(){}get[t(1458)](){let n=t;return n(433)+"_"+this[n(1138)]}async[t(531)](n){let s=t,l=this._qosDB.getItem(this[s(1458)]);return JSON[s(1221)](l||"{}")[n]}async[t(867)](n,s){let l=t,h=this._qosDB[l(1028)](this[l(1458)]),p=JSON[l(1221)](h||"{}");return p[s||n[this[l(1693)]]]=n,this[l(1129)][l(970)](this[l(1458)],JSON[l(1235)+"y"](p)),s||n[this[l(1693)]]}async[t(1267)](n){let s=t;if(e[s(680)]!=="PkBUq"){let l=this._qosDB[s(1028)](this[s(1458)]),h=JSON.parse(e[s(1432)](l,"{}"));return h[n]=void 0,this[s(1129)][s(970)](this[s(1458)],JSON[s(1235)+"y"](h))}else{let l=this[s(1129)][s(1663)+"geSync"](this[s(1458)]),h=_0xde8d85[s(1221)](e[s(664)](l,"{}"));return h[_0x2e3e59]=void 0,this[s(1129)][s(645)+s(1394)](this._prefix,_0xf02c81.stringify(h))}}async[t(1199)](){return this[t(1129)].clear()}async[t(695)](){let n=t;if(e[n(1020)]!==e[n(1020)]){let s=this[n(541)+n(836)][n(946)]((l,h)=>(l+=h&&h[n(1651)+"th"]||0,l),0);return e[n(490)](s,this._ws?this[n(212)][n(315)+n(1334)]:0)}else{let s=this[n(1129)].getItem(this._prefix),l=JSON[n(1221)](e[n(664)](s,"{}"));return Object[n(695)](l)}}async[t(1066)](){let n=t,s=this[n(1129)][n(1028)](this._prefix),l=JSON[n(1221)](e[n(664)](s,"{}"));return Object.values(l)}[t(1687)](){let n=t;if(e.xrCTp(e[n(1383)],e.WIbMn))return Promise[n(662)]();{let s=n(1430)+_0x242cff+(n(1610)+n(1345)+"es reached");this[n(1141)+"hErrorEv"+n(972)](e.ITUVk(_0x58b72c,n(571),{message:s,code:_0x5138fc[n(403)+n(1094)+"R"],error:_0x6665aa}));return}}get[t(381)](){return!!this[t(1129)]}}class Xp{constructor(n,s){let l=t;if(e.boSxy(e[l(1251)],e[l(1251)]))return this[l(212)]?this._ws.readyState:this._options[l(1471)+"cOpen"]?this[l(1490)+"NG"]:this[l(203)];this[l(1138)]=n,this._pathKey=s,this[l(1129)]=Pn?tt:Xr?wx:null}async[t(151)](){}get[t(1458)](){return t(433)+"_"+this._DBName}async[t(531)](n){let s=t,l=this[s(1129)][s(1663)+"geSync"](this._prefix);return JSON.parse(e[s(1478)](l,"{}"))[n]}async[t(867)](n,s){let l=t,h=this._qosDB[l(1663)+l(1394)](this[l(1458)]),p=JSON[l(1221)](e[l(1432)](h,"{}"));return p[s||n[this[l(1693)]]]=n,this._qosDB[l(645)+l(1394)](this[l(1458)],JSON.stringify(p)),s||n[this._pathKey]}async del(n){let s=t,l=this[s(1129)][s(1663)+s(1394)](this[s(1458)]),h=JSON[s(1221)](e[s(1432)](l,"{}"));return h[n]=void 0,this[s(1129)][s(645)+s(1394)](this[s(1458)],JSON[s(1235)+"y"](h))}async[t(1199)](){let n=t;return this[n(1129)][n(1527)+n(1204)]()}async[t(695)](){let n=t,s=this[n(1129)][n(1663)+n(1446)+"nc"](this._prefix),l=JSON[n(1221)](e.ziLrm(s,"{}"));return Object[n(695)](l)}async getAll(){let n=t,s={ZjgXT:function(l,h){return e.jHNdT(l,h)}};if(n(1506)===n(948))this[n(1669)]=!0,this[n(1327)]=FNgKpG[n(965)](0,_0xbf722e),this.high=0|_0x3f938a,this[n(533)]=!!_0x4e4ee9;else{let l=this[n(1129)][n(1663)+n(1446)+"nc"](this._prefix),h=JSON[n(1221)](l||"{}");return Object.values(h)}}[t(1687)](){let n=t;if(e[n(850)](e[n(1292)],e[n(817)]))return Promise.resolve();this[n(1701)](n(1184),e[n(762)](_0x5b176b,"open",{..._0x24929a,data:_0x1cf07a.errMsg||""}))}get[t(381)](){return!!this[t(1129)]}}function gl(a,n){let s=t;if(e[s(1420)](Pn,Pn))return new Xp(a,n);if((rr||Qr)&&e[s(1365)](e[s(666)],typeof indexedDB))return new Zp(a,n);if((rr||Qr)&&e[s(1365)](e[s(666)],typeof localStorage))return new Yp(a,n);throw new Error(e[s(693)])}class Qp{constructor(){let n=t;this[n(404)+n(1263)+"Id"]=null,this[n(404)+"l"]=36e5,this._qosDB=gl(e[n(791)],e[n(1183)])}async[t(404)+t(710)](){let n=t;e[n(1076)](clearInterval,this._intervalTimeoutId),this[n(404)+n(1263)+"Id"]=setInterval(()=>{let s=n;this[s(1121)+s(287)]()},this._interval)}async openDB(){let n=t;await this[n(1129)][n(151)]()[n(1286)](()=>{let s=n;this[s(404)+s(710)]()})}async[t(1121)+"ired"](){let n=t;(await this[n(1129)]?.[n(1066)]()||[])[n(291)](({timestamp:h})=>h<Date[n(1489)]())[n(1302)](h=>{let p=n;this[p(1129)]?.[p(1267)](h[p(169)+"id"])})}async del(n){let s=t;return this[s(1129)]?.[s(1267)](n)}async[t(867)](n,s){let l=t;return this._qosDB?.[l(867)]({message_id:n,timestamp:s})}async[t(531)](n){let s=t;return this[s(1129)]?.[s(531)](n)}async[t(1687)](){let n=t;e[n(1165)](clearInterval,this[n(404)+n(1263)+"Id"]),await this[n(1129)]?.[n(1687)]()}get[t(381)](){return this[t(1129)]?.isReady}}function ga(a){let n=t;if(e[n(384)]!=="NuGOT")!this[n(823)+"Lock"]&&(this[n(778)+n(530)]?.["resetEnd"+n(644)+"fig"](),this[n(1622)+n(1090)]?.[n(1369)+"nter"](),this[n(717)+n(1673)]=!1,this[n(1022)]=!0,this._connect());else{let s=!!this[n(497)][n(376)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(620)](on,a[n(1215)][n(1635)],e[n(363)],"2"),h=l&&on(a[n(1215)][n(1635)],e[n(896)],"1"),p=l&&e.JfZSe(on,a.message.headers,n(1098)+n(411)+"k","1"),_=p?e[n(416)](ir,a[n(1215)][n(1635)],e[n(1154)])?.[n(1480)](",")[n(291)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:p,ackMsgIds:_}}}async function ml(){let a=t;return this[a(1425)+a(1485)]||(this[a(1425)+a(1485)]=new Qp),this[a(1425)+a(1485)][a(381)]||await this[a(1425)+a(1485)][a(151)](),this._QoSManager}async function eg(a,n){let s=t,{enableAutoAck:l}=this._options,h=e[s(976)](on,a[s(1215)][s(1635)],e[s(181)],"1"),p=on(a[s(1215)].headers,e.LLXUA,"1"),_=ga.call(this,a);if(e[s(1252)](l,h)){let{SeqID:v,LogID:w,service:C,LogIDNew:N,method:L}=a.message;this[s(1049)]({SeqID:v,LogID:w,LogIDNew:N,service:C,method:L,headers:[{key:e.LLXUA,value:"1"},{key:s(524),value:N||""},{key:e[s(1352)],value:"0"}]})}p&&!_[s(595)]&&this[s(1141)+s(1163)+s(1560)](a),n()}async function tg(a,n){let s=t;if(e.EvYLj(s(1018),e[s(1652)]))this[s(830)](e[s(1491)],a[s(1215)]),n();else{let l=e[s(803)](_0x47d78a,_0x2a5fe5,1);_0x21dc60.bytes[l]=_0x507b0e}}async function ng(a,n){let s=t,l={LtokZ:function(p,_){return e[H(1449)](p,_)},OjiQf:function(p,_){return p===_},TRhud:function(p,_){return e[H(1389)](p,_)}},h=e[s(563)](nn,await e.PRboh(pl,a.data));try{if(e[s(258)](h[s(955)],Uint8Array))if(e[s(1301)]!=="ZZLFE"){let p=e[s(1563)](this[s(497)]["payloadE"+s(1245)],Object)?{force:!!this[s(497)][s(1576)+s(1245)].force,encoding:this[s(497)][s(1576)+"ncoding"][s(424)]?this._options[s(1576)+s(1245)].encoding[s(270)](/\s/g,"")[s(361)+s(573)]():""}:{force:!1,encoding:this._options["payloadE"+s(1245)]?this[s(497)][s(1576)+s(1245)][s(270)](/\s/g,"")[s(361)+s(573)]():""},_=h[s(1576)+"ncoding"]?h[s(1576)+s(1245)][s(270)](/\s/g,"")[s(361)+s(573)]():"",v=e[s(586)](this[s(497)][s(999)+s(572)],Object)?{force:!!this[s(497)][s(999)+s(572)][s(754)],type:this[s(497)][s(999)+s(572)].type?this[s(497)]["payloadT"+s(572)][s(482)][s(270)](/\s/g,"")["toLowerC"+s(573)]():""}:{force:!1,type:this._options[s(999)+s(572)]?this[s(497)]["payloadT"+s(572)][s(270)](/\s/g,"")["toLowerC"+s(573)]():""},w=h[s(999)+"ype"]?h[s(999)+s(572)].replace(/\s/g,"")[s(361)+s(573)]():"",C=v[s(754)]?v[s(482)]:w||v[s(482)],N=p[s(754)]?p[s(424)]:_||p[s(424)],L=[e.ouGUb,e[s(668)],s(1392)+"ion/json"+s(399)+"=utf-8",e[s(1580)]],j=[e[s(1218)],s(1303)];this[s(497)]["enableTransformT"+s(336)+"ad"]&&L[s(859)](C)&&(!N||j.includes(N))?h["textPayl"+s(1698)]=e[s(386)](xl,h.payload,0,h.payload.byteLength):h.textPayload=""}else return!!(cJlcOQ[s(1172)](this[s(355)+s(922)],this[s(1628)+"s"].length)||cJlcOQ[s(1550)](this[s(355)+s(922)],cJlcOQ[s(1341)](this[s(1628)+"s"][s(721)],1))&&cJlcOQ[s(1550)](this[s(1333)+s(974)+"riesCount"],this[s(288)+"es"]));else h["textPayl"+s(1698)]=""}catch(p){h[s(900)+s(1698)]="",console[s(567)](p)}a[s(1215)]=h,e[s(1002)](n)}function rg(a,n,s){let l=t,h=e[l(906)](s,8192),p=e.YScJp(h,1),_=null,v=h;return function(w){let C=l;if(e[C(1403)](w,1)||e[C(723)](w,p))return a(w);e[C(1116)](e.SlYji(v,w),h)&&(e[C(1456)](e[C(876)],e[C(876)])?(_=e.hUQJx(a,h),v=0):_0x49d3ee(this,_0x11df44,[_0x2c2065,_0x507315,_0x5427f2,_0x23ee74,_0x93f839,_0x49b4f9]));let N=n[C(1363)](_,v,v+=w);return e[C(165)](7,v)&&(v=e[C(1111)](e[C(788)](7,v),1)),N}}let ig=4294967295;function sg(a,n,s){let l=t;return e.CtCru(RangeError,e[l(559)](e[l(277)](e[l(1360)](e[l(255)](l(942)+"t of range: ",a),l(1484)),e[l(1432)](n,1))+e[l(503)],s))}function og(a,n,s){let l=t;if(e.Wmypc(l(598),e[l(745)])){if(e[l(183)](s,ig))throw new Error(l(1107)+l(1084)+"e");let h=3;for(;h>=0;){if(e[l(293)](e[l(1486)],e.EfGOW))return e[l(606)](-1,this[l(1327)])&&e[l(545)](-1,this.high)?_0x14b32f.fromBits(0,0,this[l(533)]):this[l(1327)]===-1?_0x4078e0[l(514)](0,e[l(1558)](this[l(1564)],1),this.unsigned):_0x468b0c.fromBits(e[l(673)](this.low,1),this[l(1564)],this[l(533)]);{let p=e[l(1064)](255,s);e[l(386)](wa,p,a,n+h),s>>>=8,h--}}return e[l(782)](n,4)}else{if(xJiVKM[l(423)](_0x252d9e,l(1370)))return _0x16a639.get(_0x49fe87);if(_0x3976a6===l(334)+l(268))return _0x50f042["objectSt"+l(268)]||_0x55ed46[l(531)](_0x48a3c3);if(_0x212112===xJiVKM[l(845)])return _0x1f0f64[l(334)+l(268)][1]?void 0:_0x46d1f1[l(334)+l(1315)](_0x4a55ac["objectSt"+l(268)][0])}}function ag(a,n){let s=t,l=0,h=n,p=n+4;for(;e[s(202)](h,p);){let{value:_,offset:v}=e[s(1136)](ma,a,h);h=v,l=e[s(1544)](e[s(1227)](l,8),0),l+=_}return{value:l,offset:p}}function cg(a,n,s){let l=t,h=e[l(1373)].split("|"),p=0;for(;;){switch(h[p++]){case"0":if(n[l(1540)])return n[l(1540)](a,s)+s;continue;case"1":return e[l(1265)](e[l(367)](xa,a,n,s),s);case"2":if(n[l(405)+"e"])return e.mXMtu(n.utf8Write(a,s),s);continue;case"3":if(!a)return s;continue;case"4":if(e.LhOHu(a[l(721)],40))return e.RHQqv(xa,a,n,s)+s;continue}break}}function dg(a,n){let s=t,l=new xe(e[s(1487)](e.mvKby(e[s(1243)](a[e[s(322)](n,4)],24),e[s(919)](a[e[s(242)](n,5)],16)),e[s(621)](a[e[s(704)](n,6)],8))|a[n+7],e.bZmTG(e.vFyka(e[s(1600)](e.KHgFY(a[n+0],24),e[s(621)](a[e[s(1428)](n,1)],16)),e[s(749)](a[n+2],8)),a[e[s(1428)](n,3)]),!0);return n+=8,{value:l,offset:e.UVXBj(n,8)}}function lg(a,n,s){let l=t,h=a[l(1327)],p=a[l(1564)];return n[s]=p>>>24,n[e[l(1137)](s,1)]=e.AptEb(p,16)&255,n[s+2]=e[l(309)](p,8)&255,n[s+3]=255&p,n[e[l(1539)](s,4)]=e[l(354)](h,24),n[s+5]=e[l(1316)](e[l(1362)](h,16),255),n[e[l(1654)](s,6)]=h>>>8&255,n[e[l(1247)](s,7)]=255&h,s+=8,s}function ma(a,n){let s=t;return a[s(1566)+"8"]?{value:a[s(1566)+"8"](n),offset:n+1}:{value:e[s(1064)](255,a[n]),offset:e[s(224)](n,1)}}function wa(a,n,s){let l=t;return n[l(651)+"t8"]?n[l(651)+"t8"](a,s):n[s]=e[l(1329)](255,a),e[l(773)](s,1)}let ug=function(a){return new Uint8Array(a)},fg=e[t(898)](e[t(666)],typeof Buffer)?Buffer[t(279)+t(1079)]:rg(ug,Uint8Array[t(220)+"e"][t(390)]),hg=16,_a=32;function xg(a){let n=t,s=0,l={};for(let h=0;h<a[n(721)];h++)l[a[h][n(663)+n(1629)]]=e.sklEe(hl,a[h][n(663)+n(1629)]),s+=14+l[a[h]["cursor_n"+n(1629)]];return[s,l]}function wl(a,n,s){let l=t,[h,p]=e.jMgeb(xg,a),_=e[l(1427)](fg,h),v=0;return a[l(1302)](w=>{let C=l;console.log(e[C(373)],w,w[C(148)]),v=e[C(313)](wa,0,_,v),console[C(567)](e[C(1040)],v),v=e[C(920)](og,_,v,w[C(148)]||0),console[C(567)](e[C(1682)],v),v=e.IwZeO(wa,p[w[C(663)+C(1629)]],_,v),console[C(567)](e[C(1646)],v),v=e[C(920)](cg,w[C(663)+C(1629)],_,v),console.log(e[C(1270)],v),v=e.JfZSe(lg,xe[C(1543)+"er"](w.cursor||n),_,v),console[C(567)](e[C(1499)],v)}),{frameType:_a,headers:[{key:l(155)+l(1515),value:s}],payload:_}}function pg(a){let n=t,s=0,l=[];for(;e[n(1623)](s,a[n(1651)+"th"]);){let{offset:h}=ma(a,s);s=h;let p={cursor_name:"",cursor:0,service:0},{value:_,offset:v}=ag(a,s);p[n(148)]=_,s=v;let{value:w,offset:C}=e[n(1500)](ma,a,s);s=C,p[n(663)+"ame"]=xl(a,s,e[n(832)](s,w)),s+=w;let{value:N,offset:L}=e[n(930)](dg,a,s);p[n(208)]=N.toNumber(),s=L,l.push(p)}return l}function gg(){let a=t;return{frameType:_a,headers:[{key:e[a(1382)],value:e[a(1413)]}],payload:void 0}}class mg{constructor(n,s,l){let h=t;this[h(990)+h(236)]=n,this["_cursorF"+h(1573)]=s,this[h(541)+"Strategy"]=l,this[h(1129)]=e[h(416)](gl,this[h(990)+h(236)],e[h(1494)])}async[t(151)](){let n=t;await this[n(1129)][n(151)]()}async getCursors(){let n=t;if(e[n(887)](e[n(927)],e[n(790)])){let{url:s}=e.jqSaE(_0x447f67,{}),l=_0x54db97[n(1120)](s)?s:e[n(1580)]==typeof s?[s]:[];_0x522739&&_0x24f296.assign(this[n(497)],_0x51c9ed),l&&l[n(721)]?this[n(778)+n(530)]=new _0x3cd0f9(l,this._options[n(288)+"es"]):this["_endpoin"+n(530)]?.[n(746)+n(644)+n(1512)](),this[n(1622)+n(1090)]?.[n(1369)+n(196)](this[n(497)][n(318)+"Count"]),this["_readyCl"+n(1673)]=!1,this[n(212)]&&this[n(212)][n(1262)+"te"]!==this[n(203)]?this["_disconn"+n(734)](1e3,e[n(815)],!0):(this[n(1022)]=!0,this[n(823)]())}else{if(!this[n(1129)][n(381)])return;let s=this["_message"+n(1072)],l=await this[n(1129)][n(1066)]();switch(console.log(n(950)+n(498),l),s){case"ALL":return l&&l[n(721)]?e[n(730)](wl,l,0,this["_cursorF"+n(1573)]):void 0;case e[n(172)]:return;case e[n(509)]:return l&&l[n(721)]?e[n(709)](wl,l,0,this[n(826)+n(1573)]):e[n(1063)](gg)}}}async set(n,s,l){let h=t;return console[h(567)](e.HTLSw,n,s,l),this[h(1129)][h(867)]({cursor_name:n,cursor:s,service:l})}async[t(1196)+"rs"](n){let s=t,l=e[s(1233)](pg,n);for(let h of l)console[s(567)](s(1290)+"r",l),await this[s(1129)][s(867)](h)}async[t(531)](n){let s=t;return(await this[s(1129)][s(531)](n))?.cursor}async[t(1687)](){let n=t;await this[n(1129)][n(1687)]()}[t(1004)+t(1029)+t(1236)](n){let s=t;this[s(826)+s(1573)]=n}get[t(381)](){let n=t;return this._qosDB[n(381)]}}let wg="__x_msg_"+t(507);async function _l(a){let n=t;if(!this[n(497)][n(376)+"S"])return null;let{aID:s,fpID:l,messageStrategy:h}=this[n(497)],p=e.ziLrm(a,wg);try{return this[n(1112)+n(1289)]?a&&this[n(1112)+n(1289)]["updateCursorFile"+n(1236)](a):this._cursorManager=new mg(l+"_"+s+"_"+p,p,h),this["_cursorM"+n(1289)].isReady||await this[n(1112)+n(1289)].openDB(),this["_cursorM"+n(1289)]}catch{return e[n(1429)](n(272),e.TTwwo)?null:this[n(1129)]?.[n(531)](_0x24d376)}}async function _g(a,n){let s=t,l=on(a.message.headers,e.vCbhN,"-1"),h=e[s(620)](on,a[s(1215)][s(1635)],s(1170),"1"),p=e.UNYIH(ir,a[s(1215)][s(1635)],e[s(230)]),_=e[s(552)](Number,e[s(513)](ir,a[s(1215)][s(1635)],e[s(341)]))||0,v=ga.call(this,a),w=e[s(976)](on,a[s(1215)].headers,e.PvddU,"2"),C=e[s(884)](ir,a[s(1215)][s(1635)],e.SjorT),N=e[s(305)](Number,e[s(632)](ir,a[s(1215)][s(1635)],e[s(1059)]));if(v[s(595)])return n();let L=v[s(1033)+"sage"]?await ml[s(1363)](this):null;if(a[s(1215)][s(148)]>0&&h&&!l||e[s(943)](a[s(1215)][s(148)],0)){if(p&&v[s(1033)+s(928)]&&L){if(!!!await L[s(531)](p))if(e.YRAFX(e[s(517)],e[s(466)])){if(_0x458483.length!==4){let z=_0x1a590c.substring(0,e[s(1511)](4,_0x3a285b[s(721)])),G=z.concat(_0x13453e);_0x2faf16.push(G)}else _0x1b1712[s(1475)](_0x5b4f8e);_0x3141e8&&(_0x4f373b+=1),_0x550bdb+=1,_0x247075=!1}else this[s(1141)+s(977)+s(362)](a),await L[s(867)](p,e[s(255)](Date.now(),_));return e.OrJjy(n)}if(w)if(e[s(1010)]!==e[s(1010)]){let j=this._qosDB[s(1028)](this[s(1458)]),z=_0x16ee88[s(1221)](e[s(787)](j,"{}"));return _0x2e97b8[s(695)](z)}else{let j=await _l.call(this);if(!j)return this[s(1141)+"hMessage"+s(362)](a),e[s(1002)](n);let z=await j[s(531)](C)??-1;if(e[s(240)](z,N))this[s(1141)+"hMessage"+s(362)](a),j[s(867)](C,N,a[s(1215)][s(148)]);else throw new Error(s(929)+s(417)+s(921)+N+(s(325)+s(221)+s(1601)+"r ")+z);return e[s(1002)](n)}return this[s(1141)+s(977)+s(362)](a),e[s(947)](n)}}async function yg(a,n){let s=t,l=ga.call(this,a);if(!l[s(1033)+s(928)])return e[s(1030)](n);let h=await ml.call(this);if(l[s(1653)+s(495)+"age"]&&l[s(1044)+"s"][s(721)])for(let p of l[s(1044)+"s"])await h.del(p);n()}async function Eg(a,n){let s=t,l=e.qdvic(a[s(1215)][s(1253)+"e"],hg),h=a[s(1215)][s(1253)+"e"]===_a;if(e[s(1252)](!l,!h))return e[s(1063)](n);let p=e[s(170)](ir,a.message[s(1635)],e[s(1382)]);if(!p)return e[s(897)](n);let _=await _l[s(1363)](this,p);if(!_)return e.emJgD(n);if(l)if(e[s(903)](e[s(781)],e[s(781)])){let v=await _[s(419)+"rs"](),w={frameType:v?.[s(1253)+"e"],SeqID:xe[s(1543)+"er"](this[s(729)]++),LogID:xe.fromNumber(this[s(497)]["logIDGen"+s(885)]()),service:9e3,method:5,headers:v?.headers,payload:v?.[s(955)]},C=S(w);this[s(212)]&&this[s(212)][s(1262)+"te"]&&this[s(212)].send(C)}else{let v=e[s(297)](e[s(435)](e.PMCev(7,_0x38cc46)<<18|e[s(406)](e[s(387)](63,_0x56918f[_0x6d11dd++]),12),e[s(331)](63&_0xeaca21[_0x44f1ca++],6)),e.bqcjU(63,_0x36229f[_0x3f02ff++]))-65536;_0x4a99f3+=_0x2da415["fromChar"+s(1503)](e[s(490)](55296,v>>10)),_0x1023b4+=_0x1b3ee8[s(464)+s(1503)](e.ZIXiA(56320,e[s(905)](1023,v)))}if(h){let v=a[s(1215)][s(955)];v&&_[s(1196)+"rs"](v)}}let bg=async function(a,n){let s=t;this[s(1022)]=!1,e.VQIVM(clearTimeout,this["_connect"+s(1312)+s(379)]),e[s(1508)](n)},vg=async function(a,n){let s=t;if(!this[s(212)]||this[s(212)][s(1262)+"te"]!==this[s(1371)])return e[s(1313)](n);let{pingInterval:l}=this._options;this[s(778)+"tManager"]?.[s(746)+s(644)+s(1512)]();for(let p=0;p<this[s(541)+"Queue"][s(721)];p++)if(e[s(1114)](e[s(1248)],e.hdmJk)){let _=this[s(541)+"Queue"][p];if(this._ws[s(1262)+"te"]===this.OPEN&&e.uBdeN(null,_))this[s(212)]&&this[s(212)][s(776)](_),this["_message"+s(836)][p]=null;else break}else return new _0x2d1964(_0x1d010b,{message:_0x3eadcf,code:_0x43eaf1,error:_0x5277ae});this[s(541)+s(836)]=this[s(541)+s(836)][s(291)](p=>!!p),this["_pingPon"+s(238)+"Id"]=e.gEIgB(setTimeout,()=>this[s(774)](),l),this[s(1141)+s(1457)+"nt"](a),this._isBrowser&&this[s(212)]&&(this[s(212)].binaryType=this[s(741)+s(572)]);let h=this["_endpoin"+s(530)]?.[s(244)+"ntEndpoint"]();this[s(830)](s(335)+h+s(1310)),n()},Sg=async function(a,n){let s=t,l=this[s(778)+s(530)]?.[s(244)+s(592)+"nt"]();this[s(830)]("open "+l),e.geMbc(n)};class Ig extends ha{constructor(n){let s=t,l={kiyex:function(v,w){return v>>>w},oQIVf:function(v,w){return e[H(1209)](v,w)},bhCBC:function(v,w){return e[H(1444)](v,w)},PAwMo:function(v,w,C,N){return v(w,C,N)},WIAJq:function(v,w){return v===w},MwkMk:s(1053),bpXqh:e[s(718)],KdSUL:e[s(1377)],iKlQn:e[s(518)],WIuij:function(v,w){return e[s(1639)](v,w)},LaEgd:e[s(1483)],WbwTZ:e.drvTt,EhEqE:"success",yuFsJ:function(v,w,C){return e[s(1023)](v,w,C)}};super(),this[s(1615)+s(1595)+s(418)]=!0,this._isBrowser=rr,this[s(1176)]=qp,this[s(216)+"T"]=Pn,this[s(323)+"X"]=Xr,this[s(430)+"r"]=Qr,this[s(541)+s(836)]=[],this[s(778)+s(530)]=null,this[s(717)+s(1673)]=!1,this[s(741)+s(572)]=e[s(1386)],this._connectLock=!1,this[s(823)+s(1312)+"utId"]=null,this[s(389)+s(1607)+"tId"]=null,this[s(1396)+s(238)+"Id"]=null,this[s(729)]=0,this[s(1022)]=!1,this[s(865)]="",this[s(1425)+s(1485)]=null,this[s(1112)+s(1289)]=null,this[s(1622)+"sCounter"]=null,this[s(1509)+"ls"]=e[s(492)],this[s(203)]=3,this[s(1490)+"NG"]=0,this[s(1371)]=1,this[s(1186)]=2,this[s(771)]=v=>{let w=s,C={RoDaG:function(N,L){return l[H(1408)](N,L)},iNMmN:function(N,L){return N&L},eXwhO:function(N,L){return l[H(1131)](N,L)},sCcwc:function(N,L){return N|L},xhxHG:function(N,L){return l[H(1577)](N,L)},gwcCz:function(N,L){return N<L}};try{l.PAwMo(fl,this,v,[bg,vg,Sg])}catch(N){if(l[w(1593)](l[w(751)],l.bpXqh)){let L={EEdmv:function(z,G){let fe=w;return lOqklo[fe(1147)](z,G)},WPlZN:function(z,G){let fe=w;return lOqklo[fe(1042)](z,G)},gqCQm:function(z,G){let fe=w;return lOqklo[fe(665)](z,G)},pbFMJ:function(z,G){let fe=w;return lOqklo[fe(1237)](z,G)},rNvHe:function(z,G){return lOqklo.iNMmN(z,G)},teZry:function(z,G){return lOqklo.sCcwc(z,G)},xNjIp:function(z,G){return lOqklo.xhxHG(z,G)},jEsOP:function(z,G){let fe=w;return lOqklo[fe(727)](z,G)},pXRHF:function(z,G){let fe=w;return lOqklo[fe(727)](z,G)},JmTYB:function(z,G){return z>G},uciiW:function(z,G){return z|G}},j=4294967295;return function(z,G,fe=!0){let ie=w;if(j=L[ie(1423)](L[ie(1602)](127,z[G]),0),L[ie(907)](z[G++],128))return{value:fe?j:0|j,offset:G};if(j=L[ie(1423)](j|(127&z[G])<<7,0),L.gqCQm(z[G++],128))return{value:fe?j:0|j,offset:G};if(j=L[ie(1469)](j,L[ie(1694)](127,z[G])<<14)>>>0,z[G++]<128)return{value:fe?j:L[ie(1058)](0,j),offset:G};if(j=(j|L[ie(1051)](L[ie(1602)](127,z[G]),21))>>>0,L.jEsOP(z[G++],128))return{value:fe?j:L[ie(1469)](0,j),offset:G};if(j=L[ie(1423)](L[ie(1469)](j,L[ie(1051)](15&z[G],28)),0),L[ie(396)](z[G++],128))return{value:fe?j:L[ie(1469)](0,j),offset:G};if(L[ie(308)](G+=5,z[ie(721)]))throw G=z.length,_0x2cddca(G,10,z[ie(721)]);return{value:fe?j:L[ie(1149)](0,j),offset:G}}}else{let L=lt(l.KdSUL,{message:N[w(1215)],code:sn[w(176)+"OR"],error:N});this[w(1141)+w(1659)+w(972)](L)}}},this[s(1441)+"ge"]=async v=>{let w=s,{pingInterval:C,pingFrequency:N}=this[w(497)];if((l[w(1593)]("hi",v[w(450)])&&l[w(1593)](l[w(454)],N)||l[w(888)](l[w(1699)],N))&&(this[w(344)+"ngTimer"](),this[w(1701)](l[w(1284)],l[w(1210)]),this["_pingPon"+w(238)+"Id"]=l[w(234)](setTimeout,this._ping[w(280)](this),C)),!l.WIuij("hi",v[w(450)]))try{l[w(798)](fl,this,v,[ng,eg,yg,Eg,_g,tg])}catch(L){let j=l[w(234)](lt,l.KdSUL,{message:L[w(1215)],code:sn[w(1481)+w(1014)],error:L});this["_dispatc"+w(1659)+w(972)](j)}},this._onError=v=>{let w=s,C=this[w(778)+w(530)]?.[w(1229)+w(993)+"es"](),N=this[w(778)+w(530)]?.[w(244)+"ntEndpoint"]();if(C&&!v.message){let L="connect "+N+(" fail, m"+w(1345)+w(760)+"ed");this[w(1141)+w(1659)+w(972)](lt(l[w(613)],{message:L,code:sn["MAX_RETR"+w(1094)+"R"],error:v}));return}this._ws&&this[w(212)][w(1262)+"te"]===this[w(1371)]&&this["_disconn"+w(734)](),this[w(1141)+"hErrorEvent"](lt(l[w(613)],{message:v[w(1215)],code:sn[w(184)+w(777)],error:v}))},this._onClose=async v=>{let w=s;this[w(1379)+w(549)](),this[w(344)+w(375)](),this[w(656)+w(511)+"rs"](),this[w(212)]=null,this[w(823)+w(410)]=!1;let C=this[w(778)+w(530)]?.[w(1229)+w(993)+"es"]();if(!C&&this[w(177)+w(1504)]()&&!this[w(717)+"osed"]){let N=this._endpointManager?.["getCurre"+w(592)+"nt"](),L=this[w(497)][w(1242)+w(1282)+w(1234)](v[w(731)],v[w(714)]);this[w(1141)+w(479)+"ent"](e[w(912)](mt,e[w(1106)],{code:1006,reason:v[w(714)]||w(1538)+"ng faile"+w(542)+"wn reaso"+w(1311)+w(890)+N,willReconnect:L})),L&&this[w(823)]();return}if(e[w(1523)](1e3,v.code)&&this[w(717)+w(1673)]){this[w(1141)+w(479)+w(972)](mt(e[w(1106)],{code:1e3,reason:e[w(757)]})),this[w(778)+w(530)]?.[w(746)+"pointCon"+w(1512)](),this[w(1622)+w(1090)]?.[w(1369)+"nter"]();return}if(e[w(619)](1e3,v.code)&&C){let N=this[w(778)+w(530)]?.[w(244)+w(592)+"nt"](),L=v.reason;L||(L=await e.zJKYK(Vp,this[w(865)])),L=w(1538)+"ng faile"+w(924)+L+(w(1228)+w(241))+N+(", max re"+w(874)+"ached"),this["_dispatc"+w(479)+"ent"](e.WppUS(mt,"close",{code:v[w(731)],reason:L}));let j=w(1430)+N+(w(1610)+"ax retries reached");this[w(1141)+w(1659)+w(972)](e[w(899)](lt,e[w(1377)],{message:j,code:sn["MAX_RETR"+w(1094)+"R"]})),this["_endpoin"+w(530)]?.[w(746)+w(644)+"fig"](),this[w(1622)+"sCounter"]?.[w(1369)+"nter"]();return}if(e[w(988)](1e3,v[w(731)])&&!v.reason){let N=this[w(778)+w(530)]?.["getCurre"+w(592)+"nt"]();this[w(1141)+w(479)+w(972)](e[w(200)](mt,e[w(1106)],{code:v[w(731)],reason:w(1538)+"ng failed, unkno"+w(1613)+w(1311)+w(890)+N})),this[w(778)+w(530)]?.["resetEnd"+w(644)+w(1512)](),this[w(1622)+w(1090)]?.[w(1369)+w(196)]();return}this[w(1141)+w(479)+w(972)](v),this[w(778)+w(530)]?.[w(746)+"pointCon"+w(1512)](),this[w(1622)+w(1090)]?.[w(1369)+"nter"]()},this[s(537)]=null,this[s(892)]=null,this.onmessage=null,this.onopen=null,this["onStartR"+s(1656)]=null,this[s(186)+s(1193)]=null,this[s(237)+s(1089)+"yReconnect"]=null,this["_handleO"+s(711)]=this[s(1395)+s(711)].bind(this),this["_handleO"+s(474)]=this["_handleO"+s(474)].bind(this),this[s(352)+"ageHide"]=this["_handleP"+s(485)][s(280)](this),this["_handleP"+s(1152)]=this["_handleP"+s(1152)][s(280)](this),this[s(497)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1700)](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(1483)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:p}=n,_=Array[s(1120)](h)?h:e.oMvOM==typeof h?[h]:[];if(!_||e.zJXDQ(0,_[s(721)]))throw new Error(s(1156)+s(1581)+"alid url");if(!e.sklEe(jp,p))throw new Error(e.RWWZU);Object[s(1105)](this[s(497)],n),this[s(778)+s(530)]=new ul(_,this[s(497)][s(288)+"es"]),this["_pingLos"+s(1090)]=new $p(this[s(497)][s(318)+s(578)]),this[s(497)][s(1471)+s(1666)]&&(this[s(1022)]=!0,this[s(823)]()),this[s(497)][s(1143)+"tworkCha"+s(981)]&&(this._isMiniTT||this[s(323)+"X"]?this[s(1439)+s(854)+s(1015)]():this._isBrowser&&this[s(1258)+"balEventListener"]())}[t(1395)+t(711)](){let n=t;this[n(497)][n(694)+n(1626)+n(235)]||this[n(717)+n(1673)]||this["_handleR"+n(1656)]()}[t(1395)+t(474)](){let n=t;if(e[n(844)](e.OcfjX,e[n(825)]))this.on(_0x3c28a6,_0x9daf16);else{this["_destroy"+n(893)+"t"]();let s=e[n(1337)](fa,n(1242)+"t",{message:e.hmDtO});this["onStopImmediatel"+n(228)+"ct"]&&this[n(237)+n(1089)+n(228)+"ct"](s)}}[t(1258)+t(602)+t(799)](){let n=t;this._isBrowser&&window[n(515)+"Listener"](n(1073),this[n(1395)+n(711)]),this._isBrowser&&window[n(515)+n(799)](n(1325),this[n(1395)+n(474)]),this[n(1179)+"er"]&&window[n(515)+"Listener"](n(1281),this[n(352)+"ageHide"]),this._isBrowser&&window.addEventListener(e[n(167)],this[n(352)+"ageShow"])}[t(715)+t(602)+t(799)](){let n=t;this[n(1179)+"er"]&&window[n(1100)+n(438)+n(1025)](n(1073),this[n(1395)+n(711)]),this[n(1179)+"er"]&&window["removeEv"+n(438)+n(1025)](e[n(364)],this[n(1395)+n(474)]),this[n(1179)+"er"]&&window[n(1100)+n(438)+n(1025)](e[n(1453)],this["_handleP"+n(485)]),this[n(1179)+"er"]&&window[n(1100)+n(438)+n(1025)](e[n(167)],this._handlePageShow)}[t(352)+t(485)](n){let s=t;!n[s(857)+"d"]&&(this[s(1179)+"er"]&&window[s(1100)+s(438)+s(1025)](s(1281),this[s(352)+s(485)]),this[s(1179)+"er"]&&window[s(1100)+s(438)+s(1025)](e[s(167)],this[s(352)+"ageShow"]),this[s(966)]()),this._isBrowser&&window[s(1100)+"entListener"](e[s(1026)],this["_handleO"+s(711)]),this._isBrowser&&window[s(1100)+s(438)+s(1025)](e.GuCYa,this[s(1395)+s(474)])}[t(352)+"ageShow"](n){let s=t;n[s(857)+"d"]&&(this[s(177)+s(1504)]()&&(!this[s(212)]||this[s(212)].readyState!==this.OPEN||e[s(1552)](this[s(212)].readyState,this[s(1490)+"NG"]))&&this[s(1395)+s(711)](),this._isBrowser&&window[s(515)+s(799)](e[s(1026)],this["_handleO"+s(711)]),this[s(1179)+"er"]&&window["addEvent"+s(799)]("offline",this[s(1395)+"ffLine"]))}async[t(441)+t(284)](n){let s=t,l={aPtaT:function(h,p){return h===p},myHJu:function(h,p){return e.Vycrx(h,p)},jDnhz:function(h,p){return e.ISkJI(h,p)},wJaQF:function(h,p){return e[H(1570)](h,p)},TAfGK:function(h,p){return e[H(316)](h,p)},hFPRc:function(h,p){return h|p},JpVDk:function(h,p){return e[H(1655)](h,p)},eVSVn:function(h,p){return e.xrLmK(h,p)},RmSOD:function(h,p){return e[H(868)](h,p)}};if(e[s(1008)](e[s(1331)],s(1201))){let{fpID:h,deviceID:p,bddID:_,ttwID:v,accessKey:w,aID:C,customParams:N={},enableAutoAck:L,enableQoS:j,QoSLevel:z,env:G}=this[s(497)],fe,ie,wt;if(this[s(1179)+"er"]||this[s(323)+"X"]||this[s(216)+"T"])if(e[s(742)]!==e.CHMXA)fe=location&&e[s(1631)](e[s(1171)],location[s(1411)])?e[s(1257)]:e.CnLKx,ie=n.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),wt=/^wss(.*:\/\/)/.test(n)?n:""+fe+ie;else return wWeRxR.aPtaT(_0x5c21d2,_0x42cbd4)?_0x419e43:new _0x2851a6(wWeRxR.myHJu(wWeRxR[s(555)](wWeRxR[s(555)](wWeRxR.jDnhz(_0x47adef[s(1363)](_0x522c23,0),wWeRxR[s(1518)](_0x1aec5e[s(1363)](_0x124162,1),8)),wWeRxR[s(1518)](_0x447f01[s(1363)](_0x38f976,2),16)),_0x53e4ac[s(1363)](_0x29531a,3)<<24),0),wWeRxR.myHJu(wWeRxR.TAfGK(wWeRxR[s(669)](wWeRxR[s(1618)](_0x2c0db5[s(1363)](_0x5a2d15,4),wWeRxR.JpVDk(_0x3fd245[s(1363)](_0x836ade,5),8)),wWeRxR.eVSVn(_0x360bdd[s(1363)](_0x26b537,6),16)),wWeRxR[s(394)](_0x4bbbfe[s(1363)](_0x3c43ad,7),24)),0),!0);else fe=e.MFKOU,ie=n[s(270)](/(^http)((?:[s]*:\/\/))/,""),wt=/(^ws)((?:[s]*:\/\/))/.test(ie)?ie:""+fe+ie;let ya=_?e.SkwCB:v?e[s(451)]:e[s(1268)],yl=_||v||p;if(!yl||!ya)throw new Error(e[s(914)]);let Ag=e[s(1631)](e.JOLfr,typeof N)?await e.hoeZs(N):N,kg=G?e.KpRwz(Kp,G[s(1169)],G[s(1621)]):{},Ea=Object[s(1105)]({device_platform:s(796),version_code:e[s(1443)],access_key:w,fpid:h,aid:C,[ya]:yl,xsack:L?1:0,xaack:L?1:0,xsqos:j?1:0,qos_level:j?z:void 0,qos_sdk_version:2,...kg},Ag),Tg=Object.keys(Ea)[s(946)]((ba,va)=>Ea[va]!==void 0?""+ba+(ba?"&":"?")+va+"="+Ea[va]:ba,"");return wt+s(1388)+Tg}else _0x506a19(xJiVKM[s(1233)](_0x8238e0,_0x4afb80[s(792)]),_0x58dbf2[s(1266)+"on"],_0x3c4b20.newVersion,xJiVKM[s(616)](_0xd303eb,_0x38b01d[s(837)+s(346)]))}async[t(823)](){let n=t;if(!(this[n(823)+"Lock"]||this[n(717)+n(1673)])){this[n(823)+"Lock"]=!0;try{let s=this["_endpoin"+n(530)]?.["checkCur"+n(864)+n(779)+n(1372)+n(1424)](),{timeoutInterval:l}=this._options;if(s){let p=this[n(778)+"tManager"]?.[n(244)+"ntEndpoint"](),_=this[n(778)+n(530)]?.[n(980)+"ackupEnd"+n(1190)+"UpdateCo"+n(1102)](),v=this[n(778)+"tManager"]?.["getCurrentEndpoi"+n(229)+n(1634)]();if(_){let w="connect "+p+(n(1380)+n(463)+n(874)+n(987)+n(1583)+n(580)+n(1434))+_+(n(756)+"y"),C=e[n(750)](lt,n(571),{message:w,code:sn[n(403)+"IES_ERROR"]});this[n(830)](w),this["_dispatchErrorEv"+n(972)](C),this[n(865)]=await this[n(441)+n(284)](_),this._debug("connect "+_+" "+v+n(265)),this["_removeW"+n(511)+"rs"]()}else{let w="connect "+p+(n(1380)+", max re"+n(874)+n(1359));this[n(830)](w),this[n(1141)+"hErrorEv"+n(972)](e.UNYIH(lt,e[n(1377)],{message:w,code:sn[n(403)+"IES_ERROR"]}));return}}else{let p=this[n(778)+n(530)]?.[n(244)+"ntEndpoi"+n(160)+n(1528)](),_=this[n(778)+n(530)]?.[n(244)+"ntEndpoi"+n(229)+n(1634)]();this[n(865)]=await this[n(441)+n(284)](p||""),this[n(830)](n(1430)+p+" "+_+" times"),this[n(656)+n(511)+"rs"]()}if(this[n(1022)])this._isInit=!1;else{let p=e.UDkMV(fa,e[n(1188)],{message:"start"});this[n(1189)+n(1656)]&&this["onStartR"+n(1656)](p)}let h=this[n(778)+n(530)]?.[n(244)+n(592)+"ntTriesC"+n(1634)]()||0;h>1&&await this[n(1011)](e[n(858)](h,1)),this._debug(n(1538)+n(248)+this[n(865)]+(n(1185)+"ls: ")+this[n(1509)+"ls"]),this[n(212)]=e.KHZTR(Hp,{url:this[n(865)],protocols:[this[n(1509)+"ls"]],headers:this[n(497)][n(540)+n(925)+"s"][n(583)+n(1032)]},this[n(497)].ws),(this._isBrowser||this[n(430)+"r"])&&this[n(212)]&&(this[n(212)][n(246)+"pe"]=this._binaryType),this["_addWsLi"+n(1588)](),this[n(823)+n(1312)+n(379)]=e.yFfjV(setTimeout,this._onTimeout[n(280)](this),l)}catch(s){throw this[n(823)+n(410)]=!1,s}}}["_clearTi"+t(549)](){let n=t;e[n(447)](e[n(1078)],e[n(1078)])?this.emit(e[n(1377)],_0x30258f(e.cuMvz,{message:this[n(1624)+n(719)+n(1367)](_0x4d1f53)})):(e[n(448)](clearTimeout,this["_connect"+n(1312)+n(379)]),this[n(823)+n(1312)+"utId"]=null)}_clearPingTimer(){let n=t;e.FntjX(clearTimeout,this[n(1396)+"gTimeoutId"]),e[n(582)](clearTimeout,this[n(389)+n(1607)+n(267)]),this[n(1396)+n(238)+"Id"]=null,this["_reconne"+n(1607)+n(267)]=null}[t(830)](...n){let s=t;this[s(497)][s(1332)]&&console[s(567)][s(550)](console,[e[s(225)],...n])}[t(1212)+t(1135)+"e"](n){let s=t;if(e[s(1496)](e[s(171)],e[s(1633)]))this[s(1615)+s(1595)+s(418)]=_0x5655a0,_0x1b8bff?this[s(1395)+s(711)]():this[s(1395)+s(474)]();else{let{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:p}=this._options,_=e.mOqaI(l,Math[s(207)](p,n-1));return e[s(843)](_,h)?h:_}}[t(774)](){let n=t;if(e[n(164)](n(1324),"MAywG"))return this["_dispatc"+n(977)+n(362)](_0xeabf4f),_0x49f964();if(this._ws&&e[n(887)](this[n(212)][n(1262)+"te"],this.CONNECTING)){this[n(344)+n(375)](),this[n(1396)+n(238)+"Id"]=e.lkRSh(setTimeout,this[n(774)][n(280)](this),this[n(497)][n(261)+n(1132)]);return}if(!this[n(212)]||e[n(676)](this._ws[n(1262)+"te"],this.OPEN))return void this[n(1177)+"econnect"]();this[n(212)]&&this[n(212)][n(776)]("hi"),this[n(389)+n(1607)+n(267)]=e[n(422)](setTimeout,this["_handleReconnect"+n(933)][n(280)](this),this[n(497)][n(1045)+n(831)+"val"])}[t(1177)+t(1656)+t(933)](){let n=t;this[n(1622)+n(1090)]?.addCount(),this[n(1701)](e[n(672)],e[n(1295)]),this[n(1622)+"sCounter"]?.checkReachMaxCount()?this[n(1177)+n(1656)]():this._ping()}[t(177)+"orOnline"](){let n=t,s={WdjZk:function(l){return e.geMbc(l)}};if(e[n(951)]!==e.XIxnD)uDbglv[n(1057)](_0x3b7513),_0x217480();else return this[n(216)+"T"]||this[n(323)+"X"]?this["_miniNav"+n(1595)+n(418)]:(this._isBrowser||this[n(430)+"r"])&&this[n(497)][n(1143)+n(812)+n(981)]?navigator[n(1351)]:!0}[t(1177)+t(1656)](){let n=t;!this._navigatorOnline()||this["_readyCl"+n(1673)]||(this[n(778)+n(530)]?.["resetEnd"+n(644)+"fig"](),this[n(1622)+n(1090)]?.[n(1369)+"nter"](),this[n(212)]?this[n(568)+n(734)](1001,e[n(1122)],!0):this._connect())}["_onPageN"+t(854)+t(1015)](){let n=t;this[n(216)+"T"]?tt["onNetwor"+n(818)+n(1178)](({isConnected:s})=>{let l=n;this[l(1615)+l(1595)+"line"]=s,s?this[l(1395)+l(711)]():this[l(1395)+l(474)]()}):this[n(323)+"X"]&&wx[n(157)+"kStatusC"+n(1178)](({isConnected:s})=>{let l=n;this[l(1615)+l(1595)+"line"]=s,s?this["_handleO"+l(711)]():this[l(1395)+l(474)]()})}[t(1011)](n){return new Promise(s=>{let l=H;e[l(1086)](setTimeout,s,this["_getInte"+l(1135)+"e"](n))})}[t(568)+t(734)](n=1e3,s="",l=!1){let h=t;this[h(212)]&&this[h(1335)+h(893)+"t"](n,s,l)}[t(395)+"ut"](){let n=t,s=this[n(778)+n(530)]?.[n(244)+n(592)+"nt"]();this[n(830)]("connect "+s+n(1380)),this[n(568)+n(734)](1001,e[n(1198)],!0)}_sendAck(n){let s=t,l=qt(n);this[s(212)]&&e[s(312)](this[s(212)][s(1262)+"te"],this.OPEN)&&(this[s(212)]&&this[s(212)][s(776)](l),this[s(830)](e[s(1321)],n))}[t(656)+t(511)+"rs"](){let n=t,s=e[n(1361)][n(1480)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[n(212)])return;continue;case"1":this[n(212)][n(1100)+n(438)+n(1025)](e.jxicE,this[n(1441)+"ge"]);continue;case"2":this[n(212)]["removeEv"+n(438)+n(1025)](e.Iyrmc,this[n(551)]);continue;case"3":this[n(212)]["removeEv"+n(438)+"ner"](e[n(1482)],this._onOpen);continue;case"4":this[n(212)]["removeEventListe"+n(1025)](e[n(1377)],this[n(1006)]);continue}break}}[t(1047)+t(1588)](){let n=t;if(e[n(528)](e.fhcKE,n(880))){if(!this[n(212)])return;this[n(212)][n(515)+"Listener"](e.ufMwp,this[n(771)]),this[n(212)]["addEvent"+n(799)](e[n(1106)],this[n(551)]),this[n(212)]["addEvent"+n(799)](e[n(1067)],this._onMessage),this[n(212)]["addEvent"+n(799)](e[n(1377)],this._onError)}else this["_addWsLi"+n(1588)]()}[t(409)+"nceClose"](n=1e3,s=""){let l=t;try{this[l(212)]&&this._ws.close(n,s)}catch{}}[t(1335)+t(893)+"t"](n=1e3,s="",l=!1){let h=t;if(this["_clearPi"+h(375)](),this[h(1379)+"mer"](),this[h(656)+h(511)+"rs"](),this[h(409)+h(708)](1e3,s),this[h(823)+"Lock"]=!1,l&&this[h(177)+h(1504)]()&&!this._readyClosed){if(this["_endpoin"+h(530)]?.[h(1229)+"chMaxTries"]()){let _=this[h(778)+h(530)]?.["getCurre"+h(592)+"nt"]();this[h(1141)+h(479)+h(972)](e[h(422)](mt,e.Iyrmc,{code:1006,reason:h(1430)+_+(h(1380)+h(463)+h(874)+h(1359)),wasClean:!0}))}else if(h(643)===h(643)){let _=this[h(497)][h(1242)+h(1282)+h(1234)](n,s);this[h(1141)+"hCloseEvent"](e[h(1517)](mt,e.Iyrmc,{code:n,reason:s,wasClean:!0,willReconnect:_})),_&&this[h(823)]()}else this[h(1138)]=_0x2a82ef,this[h(1693)]=_0x41e234,this[h(1129)]=_0x27d5b2?_0x18d3b2:_0xa76023?_0x220500:null;return}this[h(177)+"orOnline"]()||this["_readyCl"+h(1673)]?this["_dispatc"+h(479)+"ent"](e[h(646)](mt,e[h(1106)],{code:n,reason:e[h(757)]})):this[h(1141)+"hCloseEv"+h(972)](mt(e[h(1106)],{code:1006,reason:e[h(470)]})),this[h(212)]=null,this["_endpoin"+h(530)]?.[h(746)+"pointCon"+h(1512)](),this["_pingLos"+h(1090)]?.[h(1369)+h(196)]()}[t(1141)+t(1457)+"nt"](n){let s=t;this[s(1701)](s(1184),n),this[s(1535)]&&this.onopen(n)}["_dispatc"+t(977)+"Event"](n){let s=t;this[s(1701)](e[s(1067)],n),this.onmessage&&this.onmessage(n)}["_dispatc"+t(1163)+"ageEvent"](n){let s=t;this.emit(e[s(1627)],n),this[s(186)+s(1193)]&&this[s(186)+s(1193)](n)}["_dispatchErrorEv"+t(972)](n){let s=t;this.emit(e.cuMvz,n),this[s(892)]&&this[s(892)](n)}[t(1141)+t(479)+t(972)](n){let s=t;this[s(1701)](s(966),n),this[s(537)]&&this[s(537)](n)}get[t(246)+"pe"](){let n=t;if(e[n(806)](n(1660),e[n(784)]))return this[n(212)]?this._ws.binaryType:this[n(741)+"ype"];{let s=_0x1c0f01.split(":");_0x490307&&(_0x185e85=s[n(721)]),_0x3fd069+=s[n(721)];for(let l=0;e.yeklR(l,s.length);l++)if(e[n(164)](4,s[l].length)){let h=_0x104670[n(1240)+"g"](0,e[n(871)](4,s[l][n(721)])),p=h.concat(s[l]);_0x1203f4[n(1475)](p)}else _0x3d83b9[n(1475)](s[l]);_0x3f201d=!1}}set[t(246)+"pe"](n){let s=t;this[s(741)+s(572)]=n,this[s(212)]&&(this._ws[s(246)+"pe"]=n)}get[t(1632)+"nt"](){let n=t;if(e[n(650)](e.zLusj,n(1658))){let{initReconnectInterval:s,maxReconnectInterval:l,reconnectIntervalGrowFactor:h}=this[n(497)],p=e[n(1056)](s,_0x11c546[n(207)](h,e[n(264)](_0x45e6c2,1)));return e[n(449)](p,l)?l:p}else return this["_endpoin"+n(530)]?.[n(244)+n(592)+n(229)+n(1634)]()||0}get[t(315)+t(1334)](){let n=t,s={INrGf:function(l,h){return l===h},cZUNL:function(l,h){return e.Ihcza(l,h)},Wdskw:function(l,h){return e[H(1115)](l,h)},wTOPL:"yLZTY",salCW:"ngKTk"};if(e.XLyiq(e.NbYkg,e[n(738)]))_0x28bc41[n(567)](_0x1da1d2);else return this[n(541)+n(836)].reduce((h,p)=>{let _=n;return s[_(154)](s[_(923)],s.salCW)?(_0x4fcc51[_(1669)](_0x325774)||(_0x455a0c=_0x3d0169[_(1543)+"er"](_0x3f7a2e)),this[_(533)]!==_0x48813a[_(533)]&&oCVxkM[_(154)](oCVxkM[_(1223)](this[_(1564)],31),1)&&oCVxkM.Wdskw(_0x544b91.high>>>31,1)?!1:this[_(1564)]===_0x32b485[_(1564)]&&oCVxkM[_(154)](this[_(1327)],_0x21726a[_(1327)])):(h+=p&&p.byteLength||0,h)},0)+(this._ws?this[n(212)][n(315)+"Amount"]:0)}get[t(1466)+"ns"](){let n=t;return this[n(212)]?this[n(212)][n(1466)+"ns"]:""}get[t(1411)](){let n=t;return this[n(212)]?this[n(212)][n(1411)]:""}get readyState(){let n=t;return this[n(212)]?this._ws[n(1262)+"te"]:this[n(497)].automaticOpen?this[n(1490)+"NG"]:this[n(203)]}get[t(735)](){let n=t;return this[n(212)]?this[n(212)][n(735)]:this[n(865)]}[t(966)](n=1e3,s){let l=t;if(e[l(445)](l(634),e[l(1520)]))_0x47d4ae="wss://",_0x46c1bf=_0x1b225d.replace(/(^http)((?:[s]*:\/\/))/,""),_0x8aec2b=/(^ws)((?:[s]*:\/\/))/[l(1476)](_0x53d845)?_0x382aa7:""+_0x43311c+_0x504de3;else{if(this._readyClosed=!0,this["_clearTi"+l(549)](),this[l(344)+"ngTimer"](),this["_dropGlo"+l(602)+l(799)](),this[l(1425)+l(1485)]?.[l(1687)](),!this[l(212)])return void this[l(830)](e[l(1101)]);if(this[l(212)][l(1262)+"te"]===this[l(203)]||e.xerXK(this[l(212)][l(1262)+"te"],this[l(1186)]))return void this[l(830)](e[l(478)]);this[l(1335)+l(893)+"t"](n,s)}}async[t(776)](n,s){let l=t;if(e[l(1273)]("dfJok","DNfjI")){if(e[l(1454)](null,n))throw new Error(e[l(822)]);e.MBLoh==typeof n&&(n=JSON[l(1235)+"y"](n)),typeof n!="string"&&!e.UyilZ(n,ArrayBuffer)&&!(n[l(1081)]&&e[l(1239)](n[l(1081)],ArrayBuffer))&&(n=JSON.stringify(n));let h=await e[l(199)](pl,n),p=e.gMBBK(Wp,n),{method:_=0,service:v=this._options[l(148)],logID:w=this[l(497)]["logIDGen"+l(885)](),headers:C=this[l(497)].headers,payloadEncoding:N=this[l(497)][l(1576)+l(1245)],payloadType:L=this[l(497)].payloadType,logIDNew:j=this[l(497)][l(400)+l(1052)][l(1405)+l(481)+l(462)+"ew"]?i(this[l(497)][l(400)+l(1052)][l(398)]):""}=s||{};if(!v)throw new Error(e[l(939)]);let z={SeqID:xe[l(1543)+"er"](this[l(729)]++),LogID:xe[l(1543)+"er"](w),service:v,method:_,headers:C,payloadEncoding:e[l(590)](N,Object)?N[l(424)]?N[l(424)]:"":N,payloadType:e[l(275)](L,Object)?L[l(482)]?L.type:p:L||p,payload:h,LogIDNew:j},G=e[l(166)](qt,z);return this[l(212)]&&e.FAAan(this._ws[l(1262)+"te"],this[l(1371)])?(this[l(212)]&&this[l(212)][l(776)](G),this[l(830)](e[l(739)],z)):e[l(1260)](this[l(541)+l(836)].length,this[l(497)][l(561)+"geQueueLength"])?(this[l(541)+l(836)][l(1475)](G),this[l(830)](e.PAwsz,z)):(this["_message"+l(836)][l(1445)](),this[l(541)+"Queue"].push(G)),{seqID:this[l(729)],logID:w,logIDNew:j}}else return this[l(212)]?this[l(212)][l(1411)]:""}async[t(1242)+"t"](n){let s=t,{url:l}=e.SxxVh(n,{}),h=Array[s(1120)](l)?l:e[s(436)](s(748),typeof l)?[l]:[];n&&Object[s(1105)](this[s(497)],n),h&&h[s(721)]?this[s(778)+s(530)]=new ul(h,this._options.maxRetries):this._endpointManager?.[s(746)+s(644)+s(1512)](),this._pingLossCounter?.[s(1369)+s(196)](this._options[s(318)+s(578)]),this["_readyCl"+s(1673)]=!1,this[s(212)]&&this[s(212)][s(1262)+"te"]!==this[s(203)]?this._disconnect(1e3,e[s(815)],!0):(this[s(1022)]=!0,this._connect())}async[t(1603)](){let n=t;if(e.asmZK(e[n(594)],e.LDYZN)){if(!this[n(823)+"Lock"]){let s=(n(982)+"4").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(1022)]=!0;continue;case"1":this[n(717)+n(1673)]=!1;continue;case"2":this["_pingLos"+n(1090)]?.[n(1369)+n(196)]();continue;case"3":this["_endpoin"+n(530)]?.[n(746)+n(644)+n(1512)]();continue;case"4":this[n(823)]();continue}break}}}else _0x53caf8=xJiVKM[n(649)](_0x3e29df,_0x349543)}[t(515)+t(799)](n,s){let l=t;e[l(744)](e[l(1304)],e[l(1304)])?this.on(n,s):(_0x576a58=_0x193ab5[e.pJzUe(_0x4db3ef+_0x17797d,1)],_0x1f9602=_0x40ac74[e[l(704)](_0x350ede,_0x2ea1a4)+2],e.CfvVC(e[l(1119)](_0xb73580|e[l(1227)](_0x444e40,8),49344),32896)?_0x52167e+=_0x225083:(_0x39a5b5=e[l(679)](e[l(1636)](e[l(978)](15,_0x18ffa4)<<12,e[l(189)](e[l(1091)](63,_0x500134),6)),e[l(1272)](63,_0x4d3feb)),e[l(1244)](_0x334f9c,2048)||e.tmGtg(_0x4552a8,55296)&&_0x570f07<=57343?_0xeb2c32+=_0x442623:(_0x5b7153+=_0x174c9e(_0x31edd8),_0x2e05a1+=2)))}[t(289)+"Event"](n){let{type:s}=n;this.emit(s,n)}[t(1100)+"entListener"](n,s){this[t(460)](n,s)}[t(360)](){let n=t,s={HUXGA:function(l,h){return e[H(764)](l,h)},hJEMh:e[n(660)],arhCN:e[n(210)],JssXD:n(328),BYHVa:function(l,h,p){return l(h,p)},cbFKQ:e[n(672)]};return new Promise((l,h)=>{let p=n,_={pyzPV:function(C,N){return s.HUXGA(C,N)},ylBcL:s[p(168)],uRKDm:s.arhCN,SKDyp:p(1027)+p(1150)+"t",XfQHY:s[p(532)]};this[p(344)+p(375)](),this["_pingPon"+p(238)+"Id"]=s.BYHVa(setTimeout,this[p(774)][p(280)](this),this[p(497)][p(261)+p(1132)]);let v=()=>{let C=p;_.pyzPV(l,_[C(1318)]),this[C(460)](_.uRKDm,v),this[C(460)](_[C(626)],w)},w=()=>{let C=p;_[C(952)](h,_[C(1075)]),this.off(_.uRKDm,v),this.off(C(1027)+"e_timeout",w)};this.on(s[p(504)],v),this.on(s[p(627)],w),this[p(774)]()})}}})(),ze[M(1208)+M(732)]=De[M(1208)+M(732)],ze.CustomErrorEvent=De[M(891)+M(1668)],ze[M(1349)+"e"]=De[M(1349)+"e"],ze.Event=De[M(362)],ze[M(716)]=De[M(716)],ze[M(374)+"MessageE"+M(359)]=De.FrontierMessageEvent,ze[M(1498)+"vent"]=De[M(1498)+M(359)],ze[M(701)+"t"]=De[M(701)+"t"],ze["Reconnec"+M(1034)]=De[M(835)+"tEvent"],ze[M(1197)+"oseEvent"]=De[M(1197)+"oseEvent"],ze[M(1288)+M(1668)]=De[M(1288)+M(1668)],ze[M(772)+M(1192)+"nt"]=De.createMessageEvent,ze[M(351)+M(162)]=De[M(351)+M(162)],ze["createRe"+M(1630)+M(359)]=De[M(1406)+M(1630)+M(359)],ze[M(601)+M(1283)]=De[M(601)+M(1283)],ze[M(944)+"ame"]=De[M(944)+M(1629)];for(Ho in De)[M(1208)+M(732),"CustomEr"+M(1668),M(1349)+"e","Event",M(716),M(374)+M(1498)+"vent",M(1498)+"vent",M(701)+"t",M(835)+M(1034),"createCloseEvent",M(1288)+M(1668),M(772)+M(1192)+"nt",M(351)+M(162),M(1406)+M(1630)+M(359),M(601)+M(1283),M(944)+M(1629)][M(1416)](Ho)===-1&&(ze[Ho]=De[Ho]);var Ho;Object[M(1175)+M(215)](ze,M(743)+"le",{value:!0})});import{existsSync as L1,openSync as N1}from"node:fs";import{mkdir as M1}from"node:fs/promises";import{dirname as B1}from"node:path";import{fileURLToPath as F1}from"node:url";function U1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Hd(t=ee()){return L1(t.libEntry)?t.libEntry:F1(new URL("../index.ts",import.meta.url))}async function Xx(t={}){let e=t.paths??ee(),r=t.entryOverride??Hd(e),i=U1(e,process.env.COZE_BRIDGE_LOG_MODE);await M1(B1(i),{recursive:!0});let o=N1(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,[rs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return z1.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var z1,rs,ea=nt(()=>{"use strict";Jt();ne();Me();z1=W("spawn-daemon"),rs="COZE_BRIDGE_DAEMON"});import{spawn as BS}from"node:child_process";import{mkdir as FS,unlink as zS,writeFile as US}from"node:fs/promises";import{dirname as qS,join as GS}from"node:path";function Jr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function HS(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Jr(r)}</key>
20
+ `+r)}function Qn(t,e,r,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,Qn),t.emit("wsClientError",d,r,e)}else Qi(r,i,o,a)}});var Ux=ae(Me=>{"use strict";var M=U;(function(t,e){let r=U,i=t();for(;;)try{if(parseInt(r(1578))/1+parseInt(r(795))/2+parseInt(r(569))/3+parseInt(r(911))/4+parseInt(r(1827))/5*(-parseInt(r(1714))/6)+-parseInt(r(1787))/7+-parseInt(r(430))/8*(parseInt(r(1029))/9)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Ko,460330);var oS=Object[M(1653)+"operty"],aS=Object["getOwnPr"+M(1871)+M(715)],Nx=(t,e)=>function(){return t&&(e=(0,t[{OptJS:function(o,a){return o(a)}}.OptJS(aS,t)[0]])(t=0)),e},cS=(t,e)=>{let r={HpiGQ:function(o,a,d,u){return o(a,d,u)}};for(var i in e)r.HpiGQ(oS,t,i,{get:e[i],enumerable:!0})};function dS(){return Rx||(Rx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ko(){let t=["rhrvy3m","BIWGAg9ZDg4","C3PQreG","vM1jvwG","zhzSy2C","qMvcuuS","vvbLz0C","CK5As2u","EMLXvfq","y09Wzw4","Ec1TC2CTy3u","AvDPEvu","uhjPBwfYEuS","C2v0q3vYC28","tgT0uLC","tufyx1jfvfi","BgHxwem","B21HC0G","zxjYtM8","Dev2zw50","y3vYC29Yx24","x2LZtwLUAvC","AhvwDfi","Aw9UvgLTzw8","v2LUzg93","B2XKvMvYC2K","y29UBMvJDgK","EvjLy29UBMu","x21LC3nHz2u","qxDqwK8","DhLWzq","twDqzLO","ALrxrgu","t25ZB20","x2DLBMvYyxq","A25yu08","BMfTzq","x29Uq2XVC2u","ueH0C20","AevYCM9Yrxy","qwz2Bvi","zgvMAw5Luhi","ALHbvMm","y2fSBa","yxL0seG","v3DuyKq","swrhzuK","ywDL","zhzlvxa","wNr2AM4","sM93seu","ruLpugO","ueDezw4","nhWXFdn8mNW","ywWGy3vYC28","DxrVuMvJB24","qvnvtum","z3LVDvi","u21hDxC","z2u6ia","rLDmuxy","B0XVB04","zNDZxZeUmc4","BfPRqMO","s3PvEgS","s21RAMK","yw1Lu3bHy2u","z1rzDKG","ueXrDMm","BNrfBMrWB2K","C2v0sxrLBq","AhHnAfq","Aw5PDcbrB1m","tuzAyue","DMjPD3m","EKPJvuO","se5JrKu","rxvuEuG","v01jDMC","x3vYBa","uLr6q0K","s1ztCuC","AMPsvxq","zw5HyMXLuw8","yxbWBgLJyxq","x2DLDeLUDgu","zvfbs24","ywXpCgi","B25nzxnZywC","CMvZzxrfBMq","yxfkDei","veDRwu4","BwvKAwf0zwW","z2v0sxrLBq","uKPLuue","vgvTwK4","B2jQzwn0u3q","zv90Aw1LB3u","z0nyvgi","yNLL","uMvJB25Uzwm","z0LLCNy","ntu2odKWwwDmB2ng","EKvevgK","tw9KDwXL","uvfqwfC","D3jPDgu","uKv1rvG","AxbeCwm","Bw52zwK","DgvZDa","DhjPzxmGCMu","vfPjDMS","x2n1CNnVCKy","CMvXDwLYzwq","x3bYzwzPEa","s3nQAeW","vvrctMe","wKfot0q","s3zJswG","yxKSihrYEsa","EMnIyLG","B1bfCw4","DhLLr2m","DwTTu2G","y29UC3rYDwm","sK5gCue","y1v0y1q","Aw5KzxG","rKLmrv9ot1q","EeriuKW","DLbSu1u","reD6rfm","EgzxqKq","DKz2rwS","tuLYBxO","vNzUs3O","wxLLCxu","sgzTyxa","D1r3t0e","BufWCei","Bg16vu8","A2PuCMm","x194x21Zz18","BuTdr2q","DenYCwO","CNbQzLy","qvH6Cfi","x2XPC3rLBMu","D21JqLu","AxnrB1nnzxm","CMvWBgfJzui","x2LZv29YA2u","CMvTB3zLq2G","yw1Osfe","tg9NsurozxC","ywnOzwqSihC","zxbRtge","sMP6qNu","mdaWmdaWmda","A2HqAhq","ywDLu2HVDW","Au5erNa","ANH2sNu","B25tDgfYDfi","zw1LBNq","wMHfrNu","te9Sugy","CMfTzq","Ahr0Ca","q3jiD0S","Dgv4Dc9WBge","BNvTyMvY","CKnZtxO","EMn4rLq","ntC5mtyYnuDcDgXvvW","y3jLyxrLuMu","q2vTtKy","u2TPCcbWyxm","rNnKC2q","wK9ss2W","y29Kzq","r0fLCM8","CMvHzfvjBNq","s0P4qvq","zevmwfy","B2nRzxrtDwm","ywTIrNK","Ae5Ws0O","wxHpvva","DxjS","z1rJBLi","zgL6Du0","z25JA3y","D25LBfu","veDVt00","DxnLCKLW","y29UDgLUDwu","rNLdt3m","Bgrsrg0","wxfOruq","C3rVCcbPBw0","yNL0zuXLBMC","zxLPD0W","yKvmELa","BfHOz2O","ALPSBhq","Eujsywq","BxnNsuq","Exb3u1u","yNvMzMvYzwq","B2zM","Bg9IywXty28","tLDZveK","ywnRDxbfBMq","mJvjzK1hBuS","zgLZCgf0y2G","zxH0ugf5Bg8","y3jLyxrLtwu","ugzOv20","x2LUAxrqCM8","D1rlsxm","qwvoqKi","ywXPzcb1CMW","C2Xvs0O","zKPMExe","wuXRque","D3b3tNm","CNzsq0q","x2zVCM1HDeu","Bg9N","EMvnDLy","A3D1zLy","wu9nvw0","qKfSBxG","ruXLDMe","Cg93","t210yMu","n3W1Fdn8mG","zM9SD0e","sNfLvuW","AMrzvNK","yKrXuNO","wMDwqKq","igfYCMf5yNu","BNfStfm","AxnAzxjV","y3jLyxrLrwW","svzcwwy","veTUsfq","wKvVCgC","s2rts3K","AMXJuNq","DgvmB2Djre4","svrjAxe","y3vYCMvUDeu","wezwwNC","DgfYz2v0","x2nVBM5Ly3q","B3bLCNr5tMe","C2v0y3vYC28","pxv0zI04","DfLUr0W","ywrJwwW","sxHQyNK","x2nSzwfYugK","BvjvD0S","CNnVCL9Uyw0","AwzPDNm","zwvKzwq","DNbXEg8","z2vjBMzVu3K","CgLUz1rPBwu","rMTUsuK","AwDHDg9Yt24","y25Mvwe","EePKuu8","zNjVBu51Bwi","AwXLtMfTzq","CMvZDwX0","sKD5Efa","Chv0","quXm","DMvYC2LVBMm","v2zhDhG","v3vQsMq","BLrRwgW","rvzOsem","zg5Qs1C","x2LZsw5PDa","B3v0sw50zxi","zxjFAxnFywm","tKPJAfK","rev4yKe","q3vZDg9Tq2W","x2rPC3bHDgm","D2fZq2XLyw4","Ec11C2uT","re1pD2u","x3jLywr5q2W","uvHrEhO","Bhb4tue","CMvHzhDYAxq","svfdA3G","u0fJAuW","txbVBNy","Aw5N","zcWGDw5RBM8","AgfZ","Eg9XCLe","z05zr2u","C2DPza","ywLzCvi","uNLiqwy","ywrKq291BNq","BMrWB2LUDfq","mZa0yu10EhLg","sgrtCvq","zxjHDg9Y","zePly2u","uNjYEKu","wwLqCwu","AwrI","B25VCgvU","Euvxuui","zw50tgLZDgu","BuHQCfy","aaaaaaaaaaa","qxbUCfu","A1ndB0m","tMLIrfi","rxzRwxm","z0fXwMO","Dgv4DfbHEwW","EsbJBg9Zzwq","x3DZ","zw1PDa","qwnQyNG","zKv6BuG","AwThsKS","DMvUDa","tw9TqLy","B3bLBG","qNPgBvm","BMzKCfy","B3bLBIa","BhrPCgXLihq","z2v0","x2TLEvbHDgG","EMjeD3e","sfnbu24","BKf2B0e","vw9xyK0","q29UzMLN","B2fK","uxzVC2K","CMvWBgfJzq","quHWtgC","y291BNq","uuzMsMu","B3jLtMfTzxm","Cg9W","rxffDe8","rgDUC0q","zvjkt0K","ANv6CLm","A2v5CW","werQq3e","uLnbrMS","y2fYv20","x2fKzfDZtgK","Bwu6ia","zxHWB3j0CW","Aw50zwDLCIa","BMrLEa","BgHzzK4","s1HZsuO","qKLYuLG","y3vYCMvUDeK","y2HLy2TdDxi","ywXS","x3nLCuLK","ueHVrM0","zxjFBxnNAwq","CuvkreG","ywnRx2nVzgu","ihjLy29UBMu","AwTms3C","r0zqCwq","tLDmyui","qxzZwue","wLHbCxC","De1HBMfNzxi","x3bHDgHlzxK","Bgz5C2K","Dxrjza","Buneq2e","vujUDMG","vezjsM8","y29SBM8","zNjVBuj5Dgu","CLHxqwS","CNzHBa","y2vZC0HHBMq","r3znqNi","rLDt","tMzXs08","zxmGCMvHy2G","CxnNtNK","zw5fDMvUDa","Ae9Wzw5fDMu","Bg93","Cw1kC2W","Aw1LCYbPBIa","C21fzvO","igzPzwXKoIa","yw5Hz2vY","CMvJzxzPzwq","CwnvufC","ihzHBgLKihm","ufnVvfu","vNvlBeq","tvvnAMq","zcbLCNjVCI4","vw1VtMq","y2HLy2Tszwe","AgLNAa","C2XPy2u","x0rctMfTzq","DgHHBIbSB2m","wuPRr3m","x2rItMfTzq","qKjdzhq","rMDiBuO","BMvJDa","zg1oEfy","y2XrwgC","vMTwr1i","z3j0CKy","BhPMBeu","x2n1CNnVCK0","ihzHBgLKigq","B25Uzwn0Aw4","D1PbBem","ignVzgu6ia","EKfKwvm","wNzlELm","whbgwvm","BMCGB3iGyw4","wMP5vLC","CvnnueC","CvfOt0W","vvHdv2W","u05wzui","DhbizwfKzxi","mtmZmdGZm0z0wezyAG","ANHTrue","B25fCNjVCG","tfjjugO","igzHAwWSig0","z1rPBwvVDxq","CKnVwwi","svnTAwK","x2HHBMrSzva","y3jLyxrLt3a","u3r2suu","vevjAwO","uNnfBfu","AeXhD1a","ChbL","teHqzK8","B25szwnLAxy","s0Xlthy","CMfTugfYyw0","q25AugW","vhrlExK","q3rKENi","zxj2AwnL","C2vUDa","qLDQCeG","CMvZzxrdB3u","BKXktKm","vKTUBNm","CffYq3a","z29PBMCGyxC","q1LIu1y","whHyugS","C3rLBMvYCW","Dg9tDhjPBMC","vwjJAvq","A3PMAeW","qwjVCNrfCNi","ENjdDMS","EgLnvxK","A2TUwvi","A3DNsvC","zeziBwm","s29nu1y","qwrZCxG","zw5XDwv1zq","DcbSAw1PDa","yNrct2q","t3v6twu","CMvTB3zLrxy","B3vUDa","BgLUzw5V","rwjhuem","B3bLCNr5","CgfNzxnOB3C","ENn6rfe","zNjVBNrPzxi","CgvxCu8","CwztAhu","x2n1CNnVCK4","zgf0yq","y2f0y2G","yNHRuva","CMTLCKDSB2i","vMjtqLa","tNjmwxi","yKX1z28","rwzwz3i","BgLZDgvUtMu","qw1VDw50","whv4s1m","DgLTzw91DcW","vu5Jqvq","y3jLyxrLt2i","CwzRsuS","wgH1uuu","zKP2Chq","ugzuzhK","vNLws1q","CMvJzwL2zwq","u0nVq0q","q1Pfv3m","yxv0BW","x2HHBMrSzvi","C2v0u3rVCMe","l3DZl3yY","yK9fBMW","zw5HyMXLvhi","yMTwsKe","tgDNBfy","EwnSyLm","ze9ZwK4","vg5bqM4","B3bLBKrc","CuLtB0G","ihrPBwvVDxq","teXrzw4","DxbIBfa","z295CNq","r25fvxC","mxWWFdj8nhW","s2zjEeG","uuX6tMm","z1nHshq","q29Kzq","B3vMD1G","tuvtu0fhrv8","mxWYFdn8nhW","sg1ltMK","y1nrvei","zujbtKq","Cgf5Bg9Hza","vhfvzuW","wvDXDg0","AgvHzgvY","sujiEMm","sfjYr28","y29TCgXLDgu","rLn2Ava","BeHHBMrSzxi","sLDkuMq","BezSDxnO","tgPWreK","yMrhq1a","x2rYB3bhBg8","Cw9Zx18","yxLjENq","yxnJCMLWDa","CxbWzeC","B25LCNjVCG","ChvZAa","lcbTyxGGCMu","sMLjzLe","wefHEw8","y3vYC29Y","y29UBMvJDfm","y3PvDhK","uvbdu0G","rNjVBNrPzxi","Bwf4uMv0CMK","yu13wLu","ChvTyvu","vuLXqLO","vhzVEeu","q0Xpu0LorW","twvZC2fNzuu","Bufnv0S","BwvZ","y2XVC2veqG","BMnLq2XVC2u","s3LWzwW","t1bftL9fuLi","BNrLCG","Aw9U","rMHxD1i","t1HJzwS","C1nqz0W","CgXLyxnLiha","seXTu0q","DLris0e","B2LUDfjLywm","EujIBwK","Bfr4DwG","yurIq1e","BNruCMLLC0m","BKjRq3e","ELzuAw4","ANjdDLa","zfDVCMTLCKC","C2XptM4","suj3EeS","A1bkC0u","weTbA28","zMLN","Aen1wM0","DfHJwgC","D3nZoI8V","y3ruAw1LB3u","rfrqC2O","BMrrq1q","D3jPDgvvAw4","tNbJExe","Dejfshe","s0jWwLi","BM94q2e","y0XbsM4","x3bYB3rVy28","EMXIwKi","x2LZtwLUAvq","rLnbse0","Ae1LC3nHz2u","ALzNwue","Bhz1yK4","wK9MwhK","AhLqwwO","A0reuLe","vhbYrLm","ChjVy2vZCW","uMvHzcbWyxm","Cg9PBNrbBMq","rKPJvxe","x19LC01Vzhu","y29UBMvJDa","ywXty29Wzq","C3jJq3a","v2vPEgLUsLm","C3vJy2vZCW","wgr3zM4","y2XLyxi","BunAv2C","x3nLBMrby2S","D09PCMm","CgfYC2u","q09oveLovuu","AwXLx25HBwu","ExbL","x29UrxjYB3i","Aw47y2HHCNm","qxrZALO","vgPSDg0","ANbvCfy","zMTZse4","z2vY","q0Xpu0ve","wfrxrwC","C2vUza","wvDZseC","mti0odGWohrJy25lsW","C0jf","EeTfzw8","Bvj4z0y","C0DlCfO","Efrurw52","C01WB2W","sM12twm","vLbYAxa","zu9lCKC","mxW0Fdz8mhW","vLHzELy","rhPny3G","q25Vu04","AM9PBG","zwnVBM5Ly3q","yNL0zxm","sMTRwue","ywLdr2m","B25JBg9Zzq","x3bPBMDqB24","Bwf4tg9ZC0m","qMHsBee","uhHKtMW","Cg9PBNrdB24","ywzL","yM9L","vMfcqKi","y2HnyxHdB3u","rMXHDvy","yxbWBhK","zMzmAw5L","z1nizMW","CuP5tvq","Dg9iyxnO","tNDywLK","sgrpsNq","DKrfvMu","rfzku2y","BwvZC2fNztO","C0Xf","rgvKAwnHDgu","A0PNDw4","zM9YrwfJAa","BKXPBMu","zxjFCw9Z","zg9Uzq","wefVqve","uhnrA28","u0LAA2W","wfnWEKC","t3LNu2q","u0HHD0m","z05vBgG","tMLOvLa","zgvSzxrL","x2nSzwfYvgK","BezAuwS","ruDNELK","vxbKyxrLq28","Dgv4Dc9Qyxy","Aw5KzxGGB3u","Bxn5we8","vgrnr3u","y21AAMG","sw9Hvvm","CKDtAeu","uwPdtwq","C2nYAxb0","Bu5srMe","x3fVC0rc","ENbevhe","A2v0ignVBNm","BgLTAxq","s3n0uLK","re9SEeG","vw5PBxbSzw0","AxnmB25N","mNW0Fdb8m3W","B25ozxr3B3i","tMnNswm","C3zfvfi","tgLZDgvUzxi","uvfsv1m","A3PpywC","ywXSq3vYC28","rKnsue8","zwDoA04","rNvgCLy","v2D1v0i","B2zMBgLUzq","Cfv3v1K","C2vRDhe","rKztz1e","DLDZC2K","B25SAw5L","DMzbCg0","q1zJuvu","twjOCMO","B01euxq","Cwjhu1q","Ewjgywy","wwPPuha","B3jRzxjhBg8","y3vYC29Yx2y","BMCGzMfPBgu","Exrnwfu","zMzLCG","wxjPuKS","DhjPzxm","DgLTzw91Da","rNnVq1q","sNDbyue","s1jYAg8","su5tvefova","t2zOuvG","otG5odi0ver1sez1","rw92ugO","EMfREfu","qNjOr3y","AgvHzgvYCW","x29Ut3bLBG","C3vmCwy","wLzUwhC","u2HHCMvKv28","vKn0yvu","ruXWvLC","vfrzshK","Cfbfq3e","yxnL","Egf1sei","whfPEuW","rgPkENe","ywLYrfK","ywnRtxnNswq","A1votNG","q2zsBLe","CuX5Cg4","tg1utMe","sg9iu3i","zuHbtfi","werRvgy","t3rhwhy","vMTuwKG","D2vI","x21PBMLoyxy","wevIDvm","BgLUzq","DxbNCMfKzw4","DeLUDgvYy2u","CMvHzg9UBhK","zxfWz1m","DxvPqxy","Dhr3Awq","BxnxB2W","v1fHAK8","yxv0B21HDgK","DenUANu","C3rYAw5NAwy","r1rWEwS","yMfJA3vWigu","ywrKrxzLBNq","A2Tpzfq","CNHjswe","igXHCMDLCIa","AuLZwM4","EgfXDNG","x3jLy29UBMu","BwTLv3K","DMroz1C","Eu1TDvi","y29UBMvJDca","yxGGCMv0CMK","u1DAtMC","vxDUtue","r050vvq","C1HJA1K","C2fNzq","A3HovLC","tKHeCg4","sMXgDwm","DKLdB0e","ywnR","v3nry1G","CgLUz19VBMm","z2v0u3rVCMe","DcbVzIbYyw4","yxbYqvK","D3L2C2q","CNnVCKzPBgu","t1bftG","DMvY","B0HVru0","vMr0r20","DhLtCKq","Dg9cExrLC0i","zw5JB2rLrNi","tKLnCfK","BfrPBwvVDxq","tMDZsw8","sKfssMe","Cxbcs2C","vMfIBM4","wNn1sxa","BKLoy2G","B2vkC08","uMfJrKK","CxverMS","rxzPBuq","tKPys1G","uvjrtuG","D0DZtKy","uhfICfe","r3f5tu4","Eufxt0i","Cgu6ia","EM1utfK","AwXIAe8","BhzmD3i","AgvKtwf4uMu","zgLZywjSzue","B2npuxi","DgHLBG","swnYDeS","AgHgCve","Dw5KzwzPBMu","zgjnBei","rvjst1i","vMXsEMm","wvngyuC","tKTbB3y","CgLUz0LUDgu","thDuz1e","zgvS","nZqZnfnAwNDXBa","uLfOywm","DMfS","t01vANa","thnOshu","sxv3sNu","ywrK","BwfUDwfSihi","x3bPBMC","C0Lirgy","r3LgCwK","v2HQuLG","DKzUs0m","qwrIC1K","Bhn5CwC","CenTB0i","tKfusvzfx0u","zKT5vhq","DffqAvq","vwfYrvG","zNjHBwvuExa","t3bLBKv2zw4","C2HPzNq","vuHWqxC","uwrMy1G","Dw50","CMvUDevUzha","u1PNr3m","zMLSzw5HBwu","C2vYDMLJzs0","DMfSDwu","su9iC2m","B25tDg9Wsw0","v05qC1O","CunTqMu","DhDvq3e","rNzqzwS","zgvSzxrLrge","v2vIu29JA2u","yNL0zu9MzNm","DfbVDeu","u3zoDgm","tg9Nsuq","ywnOzwq","uMfXDMy","B3nLza","ysbTDxn0igi","C3bSAwnL","CNjVCK1LC3m","AfLRwuW","u2HTuNm","sLnptLa","yLLfqM4","yMfSu2nVCgu","sgXvBfq","A1bKshy","DwDHEum","C3f4DMy","rvfPCwG","ELHvzhG","zM9Yy2u","qvP1Auu","s016Bee","sKHAtMW","C2v0zgi","B3jRig9MzMW","EwvPu20","Bwv0Ag9K","zgLPyLu","AvrevvC","rhjsAhK","EKXjs1u","BwvZC2fNzq","sMvTBNa","vLvWDMq","uvPSChm","tvrUvwK","zMzMzG","zwn0","yxbWzw5Kq2G","Ahr0Chm6","B3fcDuq","A1zTsfi","yw1L","D2LSBfjLy28","y2XLyxjtDg8","tvDXA1e","ChjVDg90Exa","s052s0q","zMvY","vfzSrw4","BML0AwfSAxO","yMLUza","uMj1sgi","wg9srvm","AxnFywnR","CKjYAfq","DMfSDwvZ","BwvY","x2rPC2nVBM4","zw5JB2rPBMC","rMrWsLy","v3fHA1y","yvzksLm","C3jJ","zef4qwC","zw50","CgLUz0XVC3m","BM9Uzv9UB24","DhrNs3y","C29YDa","Dg9mB3DLCKm","zMX1C2HfEha","y3f1B3O","DunZwu0","zLvJuLy","yuvSsgy","Dg1Ztxa","rMnhzwS","BMPZse8","wMrqtLO","CMvKDwnL","BNrbBMrvCgq","icSG","y1L4t28","tgDmDvK","C2vUzf9Hy2S","BfzqvxC","DvnOug0","CNL0v00","AxmGDw5Kzwy","Ew1Xq0S","Aw5JBhvKzxm","wxj5t1q","AK5Qq2q","yMXVy2TLza","u2XpuvO","t25mwue","zgvJB2rLzey","yMLUyxj5vhK","A2v5","Cgf5Bg9Hzfq","BxL1tNa","zgr6rgG","ywXSzwqGBxu","AffeAuW","weTqqxy","zw5NDgG","x2nYzwf0zvm","x2HHBMrSzu8","seftCLa","DhjHBNnHy3q","u2HtwfO","CMLLC0nVDw4","z29mr2C","C2LnCui","yMfSrxzLBNq","y2HnyxHuCMK","zhvsr0m","vhLxrLm","CgfNzwHPzgu","vgLTzw91Da","sKXPrMC","wfPOu2e","AvftzKG","Bg9Nsurhzw4","B25mAw5L","ChrVCG","Dxn0yKy","zKL2BxO","q3vZDg9Trxi","r3rQtfq","zxrxB3jRq2G","BgvUz3rO","y2HHCKnVzgu","yM9KEq","AenSB3nLrxy","y3r6zKC","ruzMAwi","u2jttwW","ChjVDg9JB2W","zfHdu28","rM5Au3m","yw5ZzM9YBvq","zxq9DxrMltG","ywDLrxzLBNq","AefJA01LC3m","CgvYC2LZDgu","zw5HyMXLqxu","r0DYELe","z3vPuLe","Bw15twW","CeHfDfi","CM9YrxzLBNq","y29Uy2f0","x2LUAxrhBg8","zxjYB3i","Cefnu00","DK5Kree","DxbKyxrLq3u","ihrVihjLDhi","yw51Ce1LC3m","CMvZB2X2zq","sufpyK8","Dw5JDfG","Awrzs2W","yxrHlcbKyxq","rxjYB3jdB2q","r2vywwO","sKzTCNO","x29UugfNzu4","BMLbvuW","C2v0","ExD5rKC","sKvmzM8","AK1XsMm","BMv3vMvYC2K","zxnVtMW","sw9Tsxa","tMPou2u","re5bC00","Bu1Hs3m","q0zyBNG","DNnTy3G","zxboqLO","z0Xnq3q","tg9JAW","ywXSB2nvBNm","AvLiAKW","yw5Nzq","s2zYr2K","EuvuB08","whv6qM4","u29NvLq","wNfVAxa","ExHVweW","vhDmwgi","y2XVC2uSihC","AMHbwuy","u3rYyxrLz3K","ELDNwhi","CeDjtKW","CYbPBNn0yw4","B2z6v2u","ywr2yw5Jzq","zufJAW","BhD1uu8","BNnYAuu","z0zqCMG","uxvLDwu","uLjpuG","AMvJDfn0B3i","y2XVC2u","Ag9yCgy","t016q3K","wgHezgO","DgLUzYbZzxi","rLDLqw4","C3jpBha","tefYuw8","B0rlCLq","r2fYEKK","zK12q1K","EgngyM8","y3jLyxrLq2W","x2LZqNjVD3m","Eg5Rs1m","yureDMG","q0HjyxK","CNzHBfzHBhu","tMT2wMq","Bunky04","BMDLza","C2vYDMLJzq","terOq3O","s3D2thC","Egv3Du4","C0XPC3rLBMu","AhrTBMi","Bg9NsurozxC","Avrxu1e","uxbOrLG","tMrgvNu","vgfN","BMDuAw1LCG","Ef9MCM9UDgK","rgjVAxi","lcbxzwjtB2m","ywnRx2LK","s29Ouha","D213B04","vhnswuC","CuvkqKO","ywnRpwzYB24","DgrdD3q","B2nRzxq","x2LZtM9Kzq","zennshe","B3nLrxzLBNq","uxrpD2C","Cw9Z","q1LWs0q","Dw5ZAwDUzwq","BMnVzgLUzW","zvLcBMy","Dg9VigXHCMC","uLHwqKu","EfDLr1O","z2vtEw5J","B2zMC2v0","Bu5vrMG","C1vfzK0","DwvXBhi","BwfW","C29Tzq","tfbKB0S","Dg9cExrLC0W","z0LWvg4","CgjICdi","vvr0zfK","x2LUAxq","x0vysvnu","wxf4yw4","yvjdwu4","rK5RCeK","A1n0yxr1C0m","svDIBgK","q3Pbsg0","tLHsvhC","EgTrExm","x3nVy2TLDa","Dhj1y3rVCIa","CYbHBhjLywq","yujSze0","B3jpBMXPBMu","y1fsDgu","zvvYBa","BMvY","sNjNwge","v3b6q3a","Axnby2TdBgu","AxnrB1nby2S","wwrdqKm","ChnoswW","x3jLBw92zvC","D1LbqKG","Bhm6ia","C3bSAxq","CMfUzg9T","sg9uCge","BwvZC2fNzv8","vg5Qy0G","CM92AwrLige","suvtx0vsuK8","wuvdz1O","zw5KCg9PBNq","DgnyueG","DgLLCKPtt04","tgXcruS","BLbOsgS","DgfIyxnL","C0XJqKy","vLLMsgC","Ee5oz00","yNPdq3a","EeHksfe","t3P0CKG","rhvHzNm","wKfPBgC","ALHUrNK","rMPPtK8","EhbSuKi","x29WDgLVBNm","uerrsM0","zMLUza","u0f2svO","BM93","C3rHCNq","ywDLsgLKzq","wxncvhK","qMztr1C","ihrPBwvZ","yNvMzMvY","AvLMqwq","DgfIt1u","EufIzee","zw50zwqGDhK","y2vbt2e","CMv0CNLdB3u","EgDlANC","vhfzrwS","y29UBMvJDeu","z2v0qwXSs2u","AxnszwfKEq","vgXRB00","BgvY","zNvUy3rPB24","uKHtwfq","vfz3sgC","CMvQzwn0","v2TfDxy","Bwf4twvZC2e","sNjcBNG","CKfzBMC","CMPctMe","ugPfEfK","Dg9Y","Bez2Chi","AgfXAxm","DxrMofDYAxq","swX4vfe","r3rJt3G","rg1SBMO","y05xyLe","z2vrDwv1zuW","u0zfrvG","sLLnv1O","AhfoAei","ywvvDMu","CMvHC29U","ANjmAKS","ihrYEsbYzwm","o2nOyxjZzxq","yM1Wz0K","Dw5RBM93BIa","AuDPrLy","BMCGDxjSoIa","zgvIDwC","Ce5vwwW","x3bPBMDmB3m","thPzyxa","wKvjsw8","y3jLyxrLrxi","vMTPzvG","vNPuqKS","twPuEgS","AgfUz2u","BMLtA3y","t0T3zvi","q3fzEKS","Dg9oDw1Izxi","rwjkBMG","C3nHz2vfDMu","DhzcDu0","t2jQzwn0","D2vrBLi","x2LUDgvYDMe","ruj1AwG","zMTPD0u","vMj1D3q","Aw5KzxHpzG","y1LKANy","EfvZzuvUDG","zMLSDgvY","y1fVqwO","x2vUzhbVAw4","zfDLwKO","Aw9Ul2PZB24","Du10qK0","D3m6lY8","BejszfO","x25HDMLNyxq","z2v0q3vYCMu","t2ngEfK","zNjVBunOyxi","AfrrCMO","C3rYAw5N","ELPMuNe","qKTPEKm","yxnZAwDU","v0viqxa","zxndzxm","Aw5L","C3rVCMu","B1rzq2u","sxbvsgu","zNjVBujPDhm","y3r4","AwnTEM4","z2v0q3vYC28","x2jPBMfYEvq","x29UvgLTzw8","wKvIqLm","t1DOt1a","rhnmuw0","zsbHihn0CMK","twLZC2LUzYa","ywX3yxLZ","wg9fu0q","wwH6zg4","x2rLyNvN","x29UtwvZC2e","tg1JBhi","BxLoEKq","CejbBgG","mhWYFdf8nhW","tfvYvxC","q09otKvdveK","yxrLq291BNq","BhnJze0","v2PIwvi","B25pCgvU","C3vIC3rYAw4","jMPZy2fSBgi","x3DZsw5ZDge","zMv3s0K","CMzgrgy","y3vYC29YlNm","AKzutNu","whb1z00","D24GCMvHC28","CejvAhq","C2vYDMvYvgK","AxjLza","B3jL","Cef5C1G","ywrKt25L","AxnbCNjHEq","C3vIyxjYyxK","AwXK","s0vPvvG","y29UDgv4Da","Aw5Lza","z2v0s2v5","Aevptw4","q291BNq","yw1LoIa","oxWXFdD8ohW","y2Dsswm","DeLK","AKTYyuy","v3bQwKq","wgjdv0W","zxjYtxnN","CKTuz1C","rMXiuw0","yKvwB2K","CMvJB25Uzwm","EuPiyLK","BM5Ly3q","B1fhrwO","y3vYDMfSDwu","v2nnwfa","wxHxy0m","x1fVu01HBMe","rLjptLrjrvi","y2nKCfu","DhDVCMTdAge","u2vXsuq","ndy3nJK3rNnKCvbj","q3P5EgW","zNPVshu","suDUDgi","su5IvuS","BhDJrhe","wuL3wwW","Cgf5Bg9Hzeu","zMXVB3i","z2v0qwXS","v01Ir2i","uvzzBNO","CMvHzhLtDge","y2vzsvy","qNrZyLy","CMvZzxruCMK","BwLZzq","zKngyuC","C0nVDw50zxi","zv9ZDwnJzxm","CLrcwee","tMfTzq","BfLYs28","rxzLBNq","rK9drMy","zxH0zw5ZAw8","vwTJthK","AeL0y0O","CMfNzvn5BMm","t1rOwge","B25TzxnZywC","uNvcA0m","x2rLC3rYB3K","t3Lnz2S"];return Ko=function(){return t},Ko()}function lS(){let t=M;return Px||(Px=[IDBCursor[t(1116)+"e"][t(1273)],IDBCursor[t(1116)+"e"].continue,IDBCursor[t(1116)+"e"][t(1809)+t(1624)+"ey"]])}function uS(t){let e=M,r={Vabnn:e(774),Dboir:e(718),LHPfO:e(604),ShmRs:function(o,a){return o(a)},bupPf:function(o){return o()},dTQAT:function(o,a){return o(a)},gNUlh:e(1109),qEJDH:e(1488),xKEeo:function(o,a){return o!==a},dOsZN:e(1097)},i=new Promise((o,a)=>{let d=e,u={roEAn:r[d(1315)],omasH:r[d(584)],EbJnh:function(w,S){return r[d(1079)](w,S)},cmZjh:function(w,S){return r.ShmRs(w,S)},YWqtm:function(w){return r.bupPf(w)},ZHrqW:function(w,S){return r.dTQAT(w,S)}},h=()=>{let w=d;t["removeEv"+w(439)+w(1366)](r[w(997)],x),t[w(617)+w(439)+"ner"](w(1225),g)},x=()=>{let w=d;if(u.roEAn!==u[w(1629)])u[w(1470)](o,u[w(859)](zt,t[w(393)])),u[w(681)](h);else return null},g=()=>{let w=d;u.ZHrqW(a,t.error),u[w(681)](h)};t[d(956)+d(877)](r[d(997)],x),t[d(956)+"Listener"](d(1225),g)});return i[e(1017)](o=>{let a=e,d={ziqTT:r[a(848)],LgLuY:a(744),mHjpV:r[a(498)]};r[a(797)](a(1097),r[a(659)])?(this[a(409)+a(758)+a(1601)](_0x1e2067),_0x44d6f8[a(1241)](_0x26497f,_0x5c44e9,_0x63beba[a(1101)][a(1302)])):o instanceof IDBCursor&&(r[a(797)]("XxXPk",a(600))?(_0x503a69=_0x5d8e3d&&d[a(1620)]==_0x4dedcc[a(1209)]?d[a(1154)]:d[a(440)],_0xa76f54=_0x2b6aaa[a(470)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x4dd801=/^wss(.*:\/\/)/[a(1722)](_0x99f059)?_0xe23b56:""+_0x5634ac+_0x60ca01):Fd[a(1241)](o,t))})[e(629)](()=>{}),Vo[e(1241)](i,t),i}function fS(t){let e=M,r={JELfo:e(685),kkOdT:e(1225),NjNSe:"abort",QXQxz:function(o){return o()},OMzCy:function(o,a){return o(a)},mnvei:function(o,a){return o!==a},jFTNu:e(1336)};if($o.has(t))return;let i=new Promise((o,a)=>{let d=e,u={DsLQm:function(h,x){return r[U(1283)](h,x)},NwXZY:d(605)+"or",NihVP:function(h){return h()}};if(r[d(1721)](r[d(1537)],r[d(1537)]))return _0x295044||(_0x42e19c=[_0x1fe4ce[d(1116)+"e"][d(1273)],_0xe35655[d(1116)+"e"][d(1809)],_0x48159b[d(1116)+"e"]["continue"+d(1624)+"ey"]]);{let h=()=>{let w=d;t[w(617)+w(439)+"ner"](r[w(1243)],x),t["removeEv"+w(439)+w(1366)](r[w(957)],g),t[w(617)+w(439)+w(1366)](r[w(1248)],g)},x=()=>{let w=d;o(),r[w(414)](h)},g=()=>{let w=d;u[w(1513)](a,t[w(1225)]||new DOMException(u[w(830)],u[w(830)])),u[w(849)](h)};t[d(956)+d(877)](r[d(1243)],x),t[d(956)+d(877)](r[d(957)],g),t[d(956)+d(877)](r[d(1248)],g)}});$o.set(t,i)}function hS(t){Jo={UsRac:function(r,i){return r(i)}}.UsRac(t,Jo)}function xS(t){let e=M,r={VvnKz:function(i,o){return i(o)},JNFqA:function(i,o,a){return i(o,a)},TPySz:function(i,o){return i!==o},dWeZJ:"AiIHE",WguWB:function(i,o){return i(o)},YIwYl:function(i,o){return i(o)},NlZhq:function(i,o){return i===o},RJeQA:function(i){return i()}};return r.NlZhq(t,IDBDatabase[e(1116)+"e"].transaction)&&!(e(1708)+e(474)in IDBTransaction.prototype)?function(i,...o){let a=e,d=t[a(1655)](r[a(1748)](es,this),i,...o);return Bd[a(1241)](d,i[a(1139)]?i[a(1139)]():[i]),r[a(1748)](zt,d)}:r[e(1706)](lS)[e(1161)](t)?function(...i){let o=e;if(r.TPySz(r[o(1485)],"CHizy"))return t.apply(es(this),i),zt(Fd[o(461)](this));{let a={Mbhrj:function(d,u,h){return r[o(1738)](d,u,h)}};return new _0x5f4faf(d=>{let u=o;a[u(893)](_0x567133,d,this[u(1697)+"rvalValue"](_0x4f7e41))})}}:function(...i){let o=e;return r[o(884)](zt,t.apply(r[o(1584)](es,this),i))}}function pS(t){let e=M,r={oMDQt:function(i,o){return i===o},Omtbe:e(1425),xnkKS:function(i,o){return i(o)},NysMD:function(i,o){return i instanceof o},MGfln:function(i,o){return i(o)},KRrho:function(i,o,a){return i(o,a)},aMdRF:function(i){return i()}};return r[e(894)](typeof t,r[e(1849)])?r[e(1295)](xS,t):(r.NysMD(t,IDBTransaction)&&r.MGfln(fS,t),r[e(908)](Mx,t,r.aMdRF(dS))?new Proxy(t,Jo):t)}function zt(t){let e=M,r={DrRhy:function(o,a){return o(a)},ndQCT:function(o,a){return o(a)},goLGg:function(o,a){return o!==a}};if(t instanceof IDBRequest)return r[e(1099)](uS,t);if(jo[e(422)](t))return jo[e(461)](t);let i=r[e(747)](pS,t);return r[e(1183)](i,t)&&(jo[e(1241)](t,i),Vo.set(i,t)),i}var Mx,Rx,Px,Fd,$o,Bd,jo,Vo,Jo,es,Dx=Nx({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={rfFDf:"header",vcUuq:function(r,i,o,a){return r(i,o,a)},pPECq:"name",QtOwg:function(r,i){return r(i)},IoaUS:t(899)+"ile_name",JowHE:function(r,i){return r instanceof i},yjvaW:t(1686),ttPUD:t(841),CnZPl:function(r,i){return r===i},KNvKD:t(1708)+t(474),VkieX:t(1502),azNHa:function(r,i){return r(i)},FSviP:"BIKdc",SogVT:function(r,i){return r===i},mNUFh:function(r,i){return r in i}};Mx=(r,i)=>i[t(1343)](o=>r instanceof o),Fd=new WeakMap,$o=new WeakMap,Bd=new WeakMap,jo=new WeakMap,Vo=new WeakMap,Jo={get(r,i,o){let a=t,d={mMaKs:function(u,h,x,g){return u(h,x,g)},CrHwK:e[a(1535)],uCsYM:function(u,h,x,g){return e.vcUuq(u,h,x,g)},oHoEM:"service-name",wZAlC:e[a(923)],mCDCa:function(u,h){return e[a(1328)](u,h)},mLzjb:e[a(860)]};if(e[a(1662)](r,IDBTransaction))if(e.yjvaW!==a(1686)){let[u,h]=d.mCDCa(_0x2b5bf9,_0x24490c),x=d[a(510)](_0x55c8f3,u),g=0;return _0x335077[a(838)](w=>{let S=a;_0x5bfdaf[S(1842)]("cursor.s"+S(591),w,w[S(1302)]),g=d[S(1250)](_0x543a63,0,x,g),_0x788437[S(1842)](d[S(1782)],g),g=d[S(1143)](_0xc6654e,x,g,w[S(1302)]||0),_0x218cfd.log(S(1302),g),g=_0x2635d8(h[w.cursor_name],x,g),_0x352b8e[S(1842)](d[S(987)],g),g=_0x3b5998(w.cursor_name,x,g),_0x2996a4[S(1842)](d[S(557)],g),g=d.mMaKs(_0x4eebaf,_0x13c533[S(391)+"er"](w.cursor||_0x28fdf3),x,g),_0x3d4128[S(1842)]("curvalue",g)}),{frameType:_0x4ea80f,headers:[{key:d.mLzjb,value:_0x967d7d}],payload:x}}else{if(i===e.ttPUD)return $o[a(461)](r);if(e[a(588)](i,e[a(1117)]))return r[a(1708)+a(474)]||Bd.get(r);if(e[a(588)](i,e[a(1462)]))return o[a(1708)+a(474)][1]?void 0:o[a(1708)+a(1543)](o[a(1708)+a(474)][0])}return e.azNHa(zt,r[i])},set(r,i,o){let a=t;return e[a(686)]!=="PuwSG"?(r[i]=o,!0):this[a(449)]?this[a(449)][a(1590)+"te"]:this[a(1401)][a(951)+a(1621)]?this[a(1526)+"NG"]:this[a(791)]},has(r,i){let o=t;return e[o(1662)](r,IDBTransaction)&&(i===e.ttPUD||e[o(1262)](i,e[o(1462)]))?!0:e[o(1339)](i,r)}},es=r=>Vo[t(461)](r)}}),Bx={};cS(Bx,{deleteDB:()=>mS,openDB:()=>gS,unwrap:()=>es,wrap:()=>zt});function gS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:a}={}){let d=M,u={TVlEn:function(g,w){return g!==w},XpFYS:"FiTwL",cUtcT:function(g,w,S,_,v){return g(w,S,_,v)},Hjkpc:function(g,w){return g(w)},LArQo:function(g,w){return g*w},YxOUP:"iioAE",gFPrh:"TTLmy",rNZKe:d(397)+d(1465),lvubN:function(g,w){return g(w)}},h=indexedDB[d(456)](t,e),x=u[d(760)](zt,h);return i&&h[d(956)+d(877)](d(943)+d(383),g=>{let w=d,S={upblP:function(_,v){return _||v}};if(u[w(1119)](u[w(561)],u[w(561)])){let _=this[w(865)][w(1705)](this._prefix),v=_0xb11088[w(780)](S[w(665)](_,"{}"));return _0x3f86e6[w(480)](v)}else u[w(1739)](i,zt(h[w(393)]),g.oldVersion,g[w(1245)+"on"],u.Hjkpc(zt,h[w(1180)+w(721)]))}),r&&h["addEvent"+d(877)](d(1164),()=>r()),x[d(1017)](g=>{let w=d;if(u[w(1119)](u[w(1801)],u[w(1277)]))a&&g[w(956)+w(877)](w(1281),()=>a()),o&&g[w(956)+w(877)](u[w(1619)],()=>o());else return u.LArQo(1e4,_0x311849[w(1405)]())+_0x498544[w(1586)](u[w(1288)](1e4,_0x47a82d[w(1377)]()))})[d(629)](()=>{}),x}function mS(t,{blocked:e}={}){let r=M,i={JARJa:r(1164),AxCHY:function(a,d){return a(d)}},o=indexedDB[r(1066)+r(1389)](t);return e&&o[r(956)+r(877)](i[r(995)],()=>e()),i.AxCHY(zt,o)[r(1017)](()=>{})}function Ox(t,e){let r=M,i={VgMdP:r(753),BfSGW:r(416)+"e",hhFqQ:r(945),EqEtO:function(h,x){return h instanceof x},pAysX:function(h,x){return h in x},cYuId:function(h,x){return h===x},nvjra:"string",vWssi:function(h,x){return h!==x}};if(!(i[r(476)](t,IDBDatabase)&&!i[r(1544)](e,t)&&i.cYuId(typeof e,i.nvjra)))return;if(Wo[r(461)](e))return Wo[r(461)](e);let o=e[r(470)](/FromIndex$/,""),a=i[r(889)](e,o),d=zx[r(1161)](o);if(!(o in(a?IDBIndex:IDBObjectStore)[r(1116)+"e"])||!(d||Fx[r(1161)](o)))return;let u=async function(h,...x){let g=r;if(g(753)!==i.VgMdP)this[g(1832)+g(1594)]=null;else{let w=this[g(1180)+"ion"](h,d?i[g(1409)]:i[g(1019)]),S=w[g(1502)];return a&&(S=S[g(1740)](x.shift())),(await Promise[g(494)]([S[o](...x),d&&w[g(841)]]))[0]}};return Wo.set(e,u),u}var Fx,zx,Wo,wS=Nx({"node_modules/idb/build/index.js"(){let t=M,e={DQJId:t(668)+"5|3",ApnpU:function(o){return o()},VuKlD:function(o){return o()},jlcRt:t(461),tXcXg:t(1552),NcgIc:"getAllKeys",FlauV:"count",WwTbD:t(1035),CJIvJ:t(850),nLcKs:t(776)},r=e.DQJId[t(1376)]("|"),i=0;for(;;){switch(r[i++]){case"0":e[t(442)](Dx);continue;case"1":e[t(535)](Dx);continue;case"2":Fx=[e[t(1864)],e[t(743)],t(1587),e[t(875)],e[t(824)]];continue;case"3":hS(o=>({...o,get:(a,d,u)=>Ox(a,d)||o[t(461)](a,d,u),has:(a,d)=>!!Ox(a,d)||o.has(a,d)}));continue;case"4":zx=[t(395),e[t(1657)],e.CJIvJ,e.nLcKs];continue;case"5":Wo=new Map;continue}break}}}),_S={idb:function(t){let e=M,r={vtQjl:e(1225),zpDTq:e(1745)};t[e(486)]=Promise[e(1231)]()[e(1017)](()=>(wS(),Bx))[e(1017)](function(i){let o=e,a={vdNgW:function(d,u,h){return d(u,h)},IUGis:r.vtQjl};if(r[o(866)]===o(1745))return i;{let d=a[o(964)](_0x15ffb0,a.IUGis,{message:_0xa49301.message,code:_0xbba135[o(674)+o(1022)],error:_0x226d25});this[o(409)+o(1651)+o(1135)](d)}})}},Lx={};function U(t,e){t=t-382;let r=Ko(),i=r[t];if(U.kgXEsf===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",w="";for(let S=0,_,v,I=0;v=h.charAt(I++);~v&&(_=S%4?_*64+v:v,S++%4)?g+=String.fromCharCode(255&_>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,_=g.length;S<_;S++)w+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(w)};U.OwAyks=o,U.YMdmNq={},U.kgXEsf=!0}let a=r[0],d=t+a,u=U.YMdmNq[d];return u?i=u:(i=U.OwAyks(i),U.YMdmNq[d]=i),i}function Ft(t){let e=M,r={IVBYf:e(1524)+"3"},i=r[e(1860)][e(1376)]("|"),o=0;for(;;){switch(i[o++]){case"0":var a=Lx[t];continue;case"1":var d=Lx[t]={exports:{}};continue;case"2":if(a!==void 0)return a[e(486)];continue;case"3":return d[e(486)];case"4":_S[t](d,d[e(486)],Ft);continue}break}}Ft.d=(t,e)=>{let r=U;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object[r(1653)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Ft.o=(e,r)=>Object[t(1116)+"e"]["hasOwnPr"+t(621)].call(e,r)})(),(()=>{let t=M,e={lhYfN:function(r,i){return r-i},zmTLY:"HRymU",LmTNa:"xonTr",cWVXA:function(r,i){return r!=i},rCoYb:t(1020)+"d",hwWqw:t(1716),suLqf:"__esModule"};Ft.r=r=>{let i=t;if(e[i(1011)]===e[i(933)]){let o=_0x11e582[i(1531)+"g"](0,e[i(489)](4,_0x200c27[i(1202)])),a=o[i(1223)](_0x2d6c10);_0x269b2b[i(698)](a)}else e.cWVXA(e[i(575)],typeof Symbol)&&Symbol.toStringTag&&Object[i(1653)+i(621)](r,Symbol[i(602)+i(1312)],{value:e.hwWqw}),Object[i(1653)+i(621)](r,e[i(917)],{value:!0})}})();var Ce={};(()=>{let t=M,e={epkLa:function(c,n){return c(n)},vFnKC:function(c,n){return c+n},yBRad:function(c,n){return c+n},hyPYj:function(c,n){return c*n},YLkAA:function(c,n){return c*n},ISmii:function(c,n){return c(n)},XDjCq:function(c,n,s){return c(n,s)},YSFaG:function(c,n){return c+n},iWiyU:function(c,n){return c===n},cQRte:t(1816),ZXAqw:function(c,n){return c(n)},ZjyVW:function(c,n){return c(n)},XhuQE:function(c,n){return c+n},GnEUw:"0000",bmpgI:t(1106),VjUxV:function(c,n){return c(n)},psNIl:function(c,n){return c(n)},DtUcs:function(c,n){return c(n)},lFvpr:function(c,n){return c instanceof n},srOlp:t(1783)+t(785)+"et=utf-8",XAoAQ:t(1696)+"ion/json",XuxKS:"application/json"+t(1451)+t(1873),Acjbx:t(1495),SWZNg:"binary",tCnju:function(c,n,s,l){return c(n,s,l)},czUty:t(407),UTtdY:t(1855),lYrKo:function(c,n){return c<n},iIsZn:function(c,n){return c!==n},UIqBZ:function(c,n){return c-n},IdGeI:"yaEtY",mGLfC:t(1553),niAUL:function(c,n){return c-n},iGiFV:function(c,n,s){return c(n,s)},yclbS:function(c,n){return c(n)},iTVoO:function(c,n){return c(n)},NwEgH:function(c,n){return c(n)},VaBBB:t(1515)+"required"+t(529)+t(1169),lhWXC:function(c,n){return c===n},tGrsT:t(1515)+t(1726)+t(529)+"value",FcGek:function(c){return c()},Pwqfm:function(c,n){return c(n)},FWLQv:function(c,n){return c&n},rxIIa:function(c,n,s){return c(n,s)},nPhHk:function(c,n,s){return c(n,s)},noxCa:function(c,n,s){return c(n,s)},IQCkx:function(c,n){return c!==n},pCmoB:function(c,n,s){return c(n,s)},AvsYA:function(c,n,s){return c(n,s)},airDY:function(c,n){return c!==n},FzUOK:function(c,n){return c!==n},XhDdj:function(c,n,s){return c(n,s)},ocOQr:function(c,n,s){return c(n,s)},zbDwq:"VAtSh",JqeUL:function(c,n,s){return c(n,s)},XZhSa:function(c,n){return c!==n},btBOd:function(c,n,s){return c(n,s)},sXckY:function(c,n){return c!==n},VdtGm:function(c,n,s){return c(n,s)},JWJRd:function(c,n,s){return c(n,s)},esoNl:function(c,n){return c>>>n},WMIvg:function(c,n){return c&n},gNYGe:function(c,n){return c<n},KMzlA:function(c,n){return c|n},KwvLw:function(c,n){return c>>>n},LshHu:function(c,n){return c<<n},TemZN:function(c,n){return c|n},NfqKO:function(c,n){return c>n},UoWbM:function(c,n,s,l){return c(n,s,l)},nsriE:function(c,n){return c<=n},tmsMp:function(c,n){return c+n},QPCSH:function(c,n){return c<<n},JrBnx:function(c,n){return c|n},PfhWm:function(c,n){return c&n},dnjKW:function(c,n){return c|n},HRrGo:function(c,n){return c&n},gnckv:function(c,n){return c>>n},FSAHM:t(806),EFfib:"ifivs",oqBuD:function(c,n,s){return c(n,s)},QjCMd:function(c,n){return c(n)},LPdoK:function(c,n){return c(n)},CnoSN:function(c,n){return c(n)},ZdPNZ:function(c,n){return c(n)},bkVJA:function(c,n){return c(n)},QUapr:function(c,n){return c(n)},Xdwfn:function(c,n,s){return c(n,s)},NWLaB:function(c,n){return c(n)},ITaAW:t(1515)+t(1726)+t(529)+t(1577),KEiUX:"Missing "+t(1726)+t(529)+t(1071),StvIE:t(1515)+t(1726)+t(529)+t(1302),xkQys:t(1515)+"required"+t(529)+t(1096),ZhEFu:function(c,n){return c&n},wOirc:function(c,n){return c(n)},zszDQ:t(871)+t(1415)+t(1010),RtXrM:t(1092),FWeAn:function(c,n){return c>=n},LjpDI:t(1166),AwPZO:t(1111),LwTgQ:t(598)+"ay, try "+t(1566)+t(1285)+t(986),tYnGL:function(c,n){return c===n},Yyequ:t(1052),Dmlnj:t(1790)+t(614),OpVLE:t(1253),mRUwK:function(c,n){return c+n},myNzD:function(c,n){return c>n},XoESD:function(c,n){return c+n},mmyMl:function(c,n){return c(n)},XoRES:function(c,n){return c<n},YWsHG:function(c,n){return c<<n},kjTrc:function(c,n){return c&n},yAbdA:t(737),sxiTm:function(c,n,s){return c(n,s)},FjiNO:function(c,n){return c&n},zUfEv:function(c,n){return c>=n},SAvIZ:function(c,n){return c+n},RaMSv:function(c,n){return c!==n},SHawC:t(625),ypwSU:"KuEXn",KVSqG:function(c,n){return c|n},QFfJe:function(c,n){return c&n},VPrip:function(c,n){return c<n},TGkYN:function(c,n){return c(n)},UarEX:function(c,n){return c==n},dmNxV:function(c,n){return c>=n},KzUxk:function(c,n){return c+n},twUCq:function(c,n){return c+n},Ctdzr:function(c,n){return c!==n},FgHmJ:function(c,n){return c|n},cQoAj:function(c,n){return c|n},FknII:function(c,n){return c|n},huVtR:function(c,n){return c<<n},dCMHq:function(c,n){return c&n},DzMcx:function(c,n){return c>=n},GqyMN:function(c,n){return c+n},lwcDq:function(c,n){return c+n},Fsdsd:function(c,n){return c+n},zakxU:function(c,n){return c!==n},Mponv:function(c,n){return c|n},lXhgj:function(c,n){return c<<n},BBCdt:function(c,n){return c|n},myuNp:function(c,n){return c|n},aiYqR:function(c,n){return c<<n},NibDR:function(c,n){return c&n},rAYng:function(c,n){return c&n},XbCWL:function(c,n){return c<<n},vZBST:function(c,n){return c&n},DjJzq:function(c,n){return c&n},LLQen:function(c,n){return c>n},QLzNc:function(c,n){return c&n},Zqoip:function(c,n){return c<n},bGDcC:function(c,n){return c>=n},DTPsj:function(c,n){return c<n},GAero:function(c,n){return c<<n},ldRDm:function(c,n){return c<n},kwgIW:function(c,n,s){return c(n,s)},TFIJo:function(c,n){return c<n},LgglV:function(c,n){return c<n},CfRnQ:function(c,n){return c-n},TdMGu:function(c,n){return c+n},oufwX:function(c,n){return c<n},jZllt:function(c,n){return c<n},xmqqV:function(c,n){return c|n},cSQTB:function(c,n){return c|n},UPegG:function(c,n){return c&n},QRQMH:function(c,n){return c>>n},vDEVe:function(c,n){return c|n},XAayo:function(c,n){return c&n},UwnMA:function(c,n){return c&n},sGKpZ:function(c,n,s){return c(n,s)},Ztvjn:function(c,n){return c instanceof n},qLypn:"Unhandle"+t(537),sqxvf:function(c,n){return c+n},esCes:function(c,n){return c+n},aElHf:function(c,n){return c===n},TtKyy:"nYtjn",KstRY:t(1391),PHtsm:function(c,n){return c>=n},WsQcX:function(c,n,s){return c(n,s)},yeiSm:function(c,n,s){return c(n,s)},vpqxo:t(1281),grtrF:function(c,n){return c(n)},jxmEA:function(c,n){return c&n},kPdHv:function(c,n){return c&n},LJhwh:function(c,n){return c&n},zWgXr:function(c,n){return c===n},adcYl:function(c,n){return c(n)},XFVZw:function(c,n){return c&n},kDDRQ:function(c,n){return c<<n},ctzfG:t(1710),HMIoa:t(1742),ZEIIo:function(c,n){return c|n},nqlLS:function(c,n){return c>>>n},BWjpH:t(891),folwA:function(c,n){return c<<n},sSPgL:function(c,n){return c===n},aytHH:function(c,n){return c<n},WhjRX:function(c,n){return c<n},unctX:function(c,n){return c<n},CFXnx:function(c,n){return c<n},KoMSV:function(c,n){return c+n},haqis:function(c,n){return c+n},DEmig:function(c,n){return c&n},bxkQP:function(c,n){return c|n},jXnFy:function(c,n){return c>>>n},OtGXv:function(c,n){return c&n},sIHDf:function(c,n){return c+n},VzTBK:function(c,n){return c|n},RTzCI:function(c,n){return c>>>n},YXugU:function(c,n){return c+n},EVhHC:function(c,n){return c>>>n},YECgZ:function(c,n){return c>>>n},gLMCt:function(c,n){return c|n},nfdpV:function(c,n){return c>>>n},SxvcL:function(c,n){return c&n},BLEgE:function(c,n){return c!==n},KfrGi:function(c,n){return c|n},akbFy:function(c,n){return c&n},FCRPO:function(c,n){return c===n},cYdjv:t(1131),zLIKU:function(c,n){return c(n)},BKizC:function(c,n){return c|n},mlNqI:function(c,n){return c|n},SrAoL:function(c,n){return c|n},hItcJ:function(c,n){return c|n},PHoFm:function(c,n){return c|n},gTcnR:function(c,n){return c|n},kxNVW:function(c,n){return c<<n},mAppB:function(c,n){return c|n},zJcUJ:function(c,n){return c|n},CYpKD:function(c,n){return c<<n},rytWM:function(c,n){return c===n},DGzDS:function(c,n){return c|n},yBbmi:function(c,n){return c|n},OcFxY:function(c,n){return c|n},qISoH:function(c,n){return c<<n},OuzMe:function(c,n){return c<<n},WpjZD:function(c,n){return c&n},UTBNa:function(c,n){return c>>>n},MTnUi:function(c,n){return c>>>n},tPotE:function(c,n){return c>=n},OfhQX:function(c,n){return c|n},qlcYz:function(c,n){return c%n},zWzYw:function(c,n){return c/n},KXsIJ:function(c,n){return c+n},icmzn:function(c,n){return c*n},ybFaf:function(c,n){return c>>>n},IbDpY:function(c,n){return c&n},JlFuc:function(c,n){return c>>>n},jNjCd:function(c,n){return c+n},aDbCQ:function(c,n){return c<<n},YiPqe:function(c,n){return c<<n},dizuM:function(c,n){return c!==n},pSCfZ:function(c,n){return c>>>n},RrrzE:function(c,n){return c===n},gyouR:function(c,n){return c&n},nFZtf:function(c,n){return c>>>n},weQnR:function(c,n){return c&n},ELeva:function(c,n){return c>>>n},IqWCG:function(c,n){return c&n},eOKrG:function(c,n){return c>>>n},xoqrQ:function(c,n){return c!==n},shlHE:t(1862),bQMLV:"RpNkE",RHSXT:function(c,n){return c>>>n},ceAOa:function(c,n){return c&n},XKPAv:function(c,n){return c>>>n},aeUve:function(c,n){return c&n},TlkoM:function(c,n){return c>>>n},jMqJc:t(1045)+t(1279),xplRB:t(1526)+"NG_ERROR",Hbckw:t(1627)+t(1382)+"R",ZOfXy:t(674)+t(1022),qpBKg:t(719)+"OR",bLugo:t(873)+"1",TEIij:function(c,n){return c!==n},yEWQB:t(1487),goyrt:function(c,n){return c>=n},lVPUw:function(c,n){return c===n},DOlxH:function(c,n){return c!==n},yJHbY:function(c,n,s){return c(n,s)},bzCCp:function(c,n){return c===n},wyvsd:t(1876),qtWUq:t(926),mCJcN:function(c,n){return c===n},fEzmH:"error",eQAKn:function(c,n){return c<n},bEVoi:"pCXIz",vTHKA:function(c,n,s){return c(n,s)},QZlps:t(941),WkEuv:function(c,n,s){return c(n,s)},rGShE:"open",amhHQ:t(1198),iQSfH:function(c,n){return c||n},gAqZj:function(c,n){return c|n},mAMWK:function(c,n){return c&n},YriRK:function(c,n){return c<<n},AeMdT:function(c,n){return c>>n},LOlPf:function(c,n){return c(n)},AHpLg:"IBHzc",lvLwr:t(1101),dAxAg:"iXCqd",NgsIo:function(c,n,s){return c(n,s)},juzrS:function(c,n){return c===n},msWol:"wlEHl",eHALR:function(c,n,s){return c(n,s)},AeNBB:function(c,n){return c instanceof n},ATGyY:t(1234),TqUeL:function(c,n,s,l,f){return c(n,s,l,f)},bYEBn:"upgraden"+t(383),UbciT:function(c,n){return c!==n},AXzpR:t(1861),aMwZU:function(c,n,s){return c(n,s)},HSASn:function(c,n){return c||n},PfTdy:function(c,n){return c!=n},JGyxP:t(1020)+"d",rvRCD:function(c,n){return c===n},VbSBP:t(1395),UmoNd:function(c,n){return c<n},FvPek:function(c,n){return c<n},eZcsS:function(c,n){return c===n},IomIp:function(c,n){return c===n},aDDvh:function(c,n){return c<n},fewKI:function(c,n){return c<n},NJchY:function(c,n){return c<=n},qOcMx:function(c,n){return c>=n},SAciL:function(c,n){return c<n},mkeWy:function(c,n){return c>=n},eqpgS:function(c,n){return c|n},dFHmc:function(c,n){return c|n},ooKVq:function(c,n){return c&n},yMmuR:function(c,n){return c&n},yEToO:function(c,n){return c|n},cNWbQ:function(c,n){return c|n},Yqxan:function(c,n){return c<<n},nINch:function(c,n){return c>>n},vFvEk:function(c,n){return c+n},WMbGb:function(c,n){return c<n},vnRiB:function(c,n){return c|n},msyXO:function(c,n){return c>>n},lmzUO:function(c,n){return c|n},xqFse:function(c,n){return c===n},nAvoA:function(c,n){return c&n},bOEnl:function(c,n){return c&n},rpjfV:function(c,n){return c&n},VkVGR:function(c,n){return c&n},lzflE:function(c,n){return c|n},HoHSr:function(c,n){return c|n},hYkYL:function(c,n){return c&n},Raqvf:function(c,n){return c&n},GtjLT:function(c,n){return c&n},tcXPH:function(c,n){return c|n},ITIiq:function(c,n){return c>>n},ELpVW:function(c,n){return c|n},aprAY:function(c,n){return c&n},yARmU:function(c,n){return c|n},kEhiv:function(c,n){return c-n},xoQse:function(c,n){return c(n)},MgPfZ:function(c,n){return c instanceof n},ytMXU:function(c,n){return c instanceof n},IOHsc:t(821),DVJSf:function(c,n){return c(n)},jhAYF:t(1453)+t(1448),MjTxk:"&jscallb"+t(1322)+"tierJSONP",cnfUa:function(c,n){return c!==n},zZfRq:"BtsbV",ddzDh:t(436),qfkIK:t(774),SlOQZ:function(c,n){return c(n)},aBldM:t(979)+"e_success",NJXKX:t(979)+t(1709)+"t",jXAVc:function(c,n){return c===n},XKAko:t(648),wnelU:function(c,n,s){return c(n,s)},zEDTi:t(1144),hxWTD:function(c,n){return c!==n},TVwHg:t(1581),kPJsE:function(c,n){return c>n},FOCFf:t(1810),gSaHt:function(c,n){return c!==n},JYMWZ:t(1270),siMqB:function(c,n){return c<n},XTWEg:function(c,n){return c(n)},ymqCK:function(c,n){return c+n},tabOU:t(733),YdCBC:function(c,n){return c||n},mKCGd:function(c,n){return c===n},TXrtI:"fjjQQ",TqYEk:t(1272),WEHAp:function(c,n){return c||n},zcbbX:t(1439),tyeGc:function(c,n){return c||n},CVcQU:function(c,n){return c!=n},RsElU:function(c,n){return c!=n},gIpTn:t(1684)+"DB failed",GeXYj:function(c,n){return c===n},JrgXa:t(1102),bgyJY:t(1329),XPNQs:t(1379)+"id",OphsF:t(1353),QdfcX:t(1155),uuiAv:function(c,n){return c!==n},dbMlB:t(1644),YryOT:t(890),qCmBe:t(885),clQXg:"HcYzv",duRGC:function(c,n,s){return c(n,s)},uwPRA:function(c,n,s){return c(n,s)},XagSt:function(c,n){return c!==n},PLQvc:t(572),egNkN:t(1314)+t(840),SNVeB:t(1314)+"er_qos_ack",quDFk:"x_frontier_ack_m"+t(425),HnNCU:"need_ack",NXtcT:t(1124),lBRdZ:function(c,n){return c&&n},NXRTw:function(c,n){return c||n},EQiqh:t(499),ZvKzS:t(647),svETR:function(c){return c()},fzoHu:function(c,n){return c(n)},BIrRX:function(c,n){return c(n)},xaqvx:function(c,n){return c instanceof n},OMUjp:function(c,n){return c instanceof n},DMOwe:t(1137)+"e",QphFX:function(c,n,s,l){return c(n,s,l)},FuFrV:function(c){return c()},kqlUi:function(c,n){return c&n},Czyxl:function(c,n){return c+n},CzAHm:function(c,n){return c|n},vICoA:function(c,n){return c||n},GNtUT:function(c,n){return c===n},qsgNy:t(1647),pumaU:function(c,n){return c(n)},OygSd:function(c,n){return c+n},XHCeI:t(1152),KLKLv:" > ",MFZaA:function(c,n){return c>n},AfvmR:t(487)+t(1334)+"e",eBAND:function(c,n){return c+n},EvimD:function(c,n){return c+n},wGsNF:function(c,n){return c+n},sUEfM:function(c,n){return c!==n},RuBkC:t(1750),hNpKJ:function(c,n){return c<n},rBrhT:function(c,n){return c|n},vPlSU:function(c,n){return c|n},azIMh:function(c,n){return c+n},pUwWY:function(c,n){return c<<n},iVKAm:function(c,n){return c+n},cgRIc:function(c,n){return c|n},yxoXL:function(c,n){return c<<n},XcGoT:function(c,n){return c+n},BnVIp:function(c,n){return c+n},EBuih:function(c,n){return c&n},wxipO:function(c,n){return c+n},KdSKy:function(c,n){return c&n},QQPXW:function(c,n){return c+n},yDTjE:function(c,n){return c===n},LWXky:t(1540),lpxMA:t(694),alOpb:function(c,n){return c|n},gTYvH:function(c,n){return c|n},qbGST:function(c,n){return c&n},DEsgN:function(c,n){return c>n},XeCmB:"2|4|6|0|"+t(1556)+"3|5|10",TTYHy:function(c,n,s,l){return c(n,s,l)},ikLKw:t(1536)+t(591),qcUPW:t(1058)+t(1648),rjBNa:"service",LlBEK:function(c,n){return c!==n},lsyqg:t(1291),WujJd:function(c,n){return c(n)},jjRUt:function(c,n,s,l){return c(n,s,l)},lFZQk:"veqCa",rCsMz:t(1023),HlUlT:"cursor_f"+t(782),NkvZd:t(1741)+t(1350),IBwxK:t(1632)+t(1112),fkiwE:t(751),yXhxm:t(880)+"rValues",XuzBn:t(396),SIZkl:t(909),WpzCp:function(c,n){return c===n},SZgGs:t(1319),ikGJK:t(1719),Onsom:t(1093),lwyVg:function(c,n){return c(n)},szjDH:t(1872)+"r",MomBV:"OwsqH",gCJdj:"TfbdW",ZqJPa:t(855)+t(695),hQDiL:function(c,n){return c+n},WjbYR:function(c,n,s,l){return c(n,s,l)},Adsqx:t(1525),AdbsY:t(845),TnjcH:"GoiwB",gIerv:t(974),qppdG:t(1321),qqRDb:"code",iTDUW:"x_fronti"+t(497),SvNtc:function(c,n){return c(n)},HLmSD:t(1314)+"er_ttl",NKAov:"x-msg-qos",OThXa:"x-msg-cu"+t(1879)+"e",ruiJV:function(c,n){return c>n},dJKce:function(c,n){return c+n},FoRNh:function(c){return c()},HoTpa:function(c){return c()},lscdM:function(c){return c()},EovPj:function(c,n){return c>>n},GGrzQ:function(c,n){return c|n},CemNF:function(c,n){return c&n},ilbhO:function(c,n){return c===n},YxWcC:function(c,n){return c&&n},hqNhB:function(c){return c()},JkkYA:"aTrQH",LDhCz:function(c){return c()},ceYIV:function(c,n,s){return c(n,s)},kSCoC:function(c){return c()},MUMjd:function(c,n){return c<<n},EuTyH:function(c,n){return c|n},kknYR:function(c,n){return c!==n},pAMSM:t(1434),lTxuh:t(827),Lmclr:t(1516),xauHB:function(c,n){return c===n},BhRlA:t(650),jKraF:function(c,n,s){return c(n,s)},UNcAT:function(c,n){return c===n},WNPsZ:t(1132),sLcBF:function(c,n,s){return c(n,s)},yxyqS:function(c,n,s){return c(n,s)},XpqTb:function(c,n){return c>n},OyMgk:function(c,n){return c&n},EvkYs:function(c,n){return c/n},hxMhT:t(781),oQGEj:t(725)+"rovide v"+t(1835),FlHQm:t(725)+"rovide ws params"+t(1316)+t(867)+t(1360)+t(1159)+t(1551),iNDFp:function(c,n){return c===n},ueqlr:"aFpzn",VRCEW:function(c,n,s){return c(n,s)},FsoCT:t(1813)+"ediately"+t(500)+"ct",NIMpY:"pagehide",XpugM:t(622),fKyTt:t(734),UzVSg:"UtGPV",iYfAd:t(1282),xHJHQ:function(c,n){return c(n)},YjiPp:function(c,n){return c(n)},ccdpU:t(1249),xOUCy:function(c,n){return c!==n},BxdxK:t(1109),YJkGs:"ws://",xNicv:t(744),OWhOP:t(948),xJdQO:"device_id",wmcBU:t(725)+"rovide bddID, deviceID or ttwID",tUYYQ:"function",Kmkji:t(939),nTkXl:function(c,n){return c<<n},LktRW:t(1812),oSorR:t(1734),nMAaa:function(c,n,s){return c(n,s)},wWNfz:"reconnect",WQajO:t(1406),OXcek:function(c,n){return c>n},MDeYH:function(c,n,s){return c(n,s)},AZuiE:function(c,n){return c(n)},pBAlh:t(1574)+">",khPht:function(c,n){return c*n},AtsjZ:function(c,n){return c-n},BrhGv:function(c,n){return c>n},IPRxe:function(c,n,s){return c(n,s)},cYxOo:function(c,n){return c!==n},HdOJt:function(c,n,s){return c(n,s)},xMpOV:t(905),ttgKv:"hPTfW",srcCp:function(c,n,s){return c(n,s)},ZEbBS:t(639)+t(1450)+t(556)+"g",SwRNw:"2|4|3|1|0",YsBTy:function(c,n){return c!==n},jdYVy:t(1504),eRJOI:t(789),fJvpt:t(1711),SbSMl:t(805)+t(1850),tQPiT:function(c,n){return c===n},UkcLy:function(c,n){return c===n},xcFbo:t(1266)+t(1271)+"ce not i"+t(1120)+"ed",QutEA:t(1784),vYpIW:function(c,n){return c(n)},xewuN:"please p"+t(1381)+t(533)+"ervice",mJvkw:function(c,n){return c===n},kmBld:t(592),ZAilg:t(613),qmJsl:function(c,n){return c>>n},aRCYN:function(c,n){return c|n},mCZWg:function(c,n){return c&n},VUpvd:function(c,n){return c&n},XDkTf:function(c,n){return c|n},VkTZH:function(c,n){return c|n},HdSqT:t(1036)+t(810)+t(420),TvoxE:function(c,n){return c!==n},PGDen:"HYwqN",NQLpj:function(c,n,s){return c(n,s)},KohPp:t(1616),TyWFS:t(595),CYbSV:t(787),IuwJu:function(c,n){return c(n)},bDqRz:t(441),BzFmS:function(c,n){return c*n},TnABn:function(c,n){return c===n},zAdYS:t(1636),hTQrj:function(c,n){return c!=n},JmvMc:function(c,n){return c===n},zlbZB:"Dedicate"+t(736)+"lobalScope",carWm:function(c,n){return c===n},FdpJV:function(c,n){return c!=n},HmKNi:function(c,n){return c===n},bdGCP:t(919)+t(631)+t(771),cquoz:"ServiceW"+t(898)+t(1082),JFmrz:function(c,n){return c!=n},zXUdx:t(1473),owVhE:function(c,n){return c!=n},QEeoY:function(c,n,s){return c(n,s)},SFEEX:t(1755)+t(693)};Ft.r(Ce),Ft.d(Ce,{FWS:()=>Ig,CustomErrorEvent:()=>il,createCloseEvent:()=>pt,ReconnectEvent:()=>rl,createErrorEvent:()=>ct,decodedFrame:()=>nn,createOpenEvent:()=>ll,CustomCloseEvent:()=>sl,createReconnectEvent:()=>fa,FrontierMessageEvent:()=>al,encodeFrame:()=>Ut,createMessageEvent:()=>dl,OpenEvent:()=>cl,ErrorCode:()=>sn,Event:()=>nr,MessageEvent:()=>ol});let r="";function i(c=""){let n=t,s="02",l=""+Date[n(1405)](),f=r||(r=e[n(1769)](h,c)),p=Math.random()[n(602)](16)[n(541)](-6);return e[n(1041)](e[n(1819)](s+l,f),p)}function o(){let c=t;return e[c(762)](1e4,Date[c(1405)]())+Math[c(1586)](e[c(1838)](1e4,Math[c(1377)]()))}function a(c){let n=t;return(e[n(576)](Array,8)[n(809)]("0")+e[n(481)](parseInt,c,10)[n(602)](2)).slice(-8)}function d(c){let n=t;return e[n(1024)](e[n(576)](Array,4).join("0"),e[n(481)](parseInt,c,2)[n(602)](16))[n(541)](-4)}function u(c){let n=t;if(e.iWiyU(e.cQRte,e[n(1364)])){let s=c[n(1376)](/\./)[n(1342)](p=>a(p)),l=[];return l[0]=e[n(505)](d,e[n(1819)](s[0],s[1])),l[1]=e[n(563)](d,e[n(643)](s[2],s[3])),[e.GnEUw,e[n(667)],e.GnEUw,e[n(667)],e.GnEUw,e[n(1452)],l[0],l[1]][n(809)]("")}else throw this[n(1870)+"Lock"]=!1,_0x3e2436}function h(c){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}/[n(1722)](c),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(1722)](c);return s?e.VjUxV(u,c):l?e[n(1372)](x,c):n(1771)+n(1771)+"00000000"+n(1771)}function x(c){let n=t;if(e[n(704)]!==e[n(1348)]){let s="",l=[],f=0,p=0,y=!0,E="0000";if(c.indexOf("::")>-1){let m=c.split("::");for(let L=0;e.lYrKo(L,m[n(1202)]);L++){let H=m[L];if(H.indexOf(":")>0){let J=H.split(":");y&&(f=J[n(1202)]),p+=J[n(1202)];for(let V=0;e[n(1600)](V,J[n(1202)]);V++)if(J[V][n(1202)]!==4){let Be=E[n(1531)+"g"](0,4-J[V][n(1202)]),gt=Be.concat(J[V]);l[n(698)](gt)}else l[n(698)](J[V]);y=!1}else{if(e[n(960)](4,H.length)){let J=E[n(1531)+"g"](0,4-H[n(1202)]),V=J[n(1223)](H);l[n(698)](V)}else l[n(698)](H);y&&(f+=1),p+=1,y=!1}}let P="";for(let L=0;e[n(1600)](L,e[n(710)](8,p));L++)P=P[n(1223)](E);for(let L=0;L<l[n(1202)];L++)L===f?(s=s.concat(P),s=s[n(1223)](l[L])):s=s.concat(l[L]);return s}{let m=c[n(1376)](":");for(let P=0;P<m.length;P++){let L=m[P];if(e.iIsZn(4,m[P][n(1202)]))if(e[n(1658)]!==e.mGLfC){let H=E.substring(0,e[n(1240)](4,m[P][n(1202)])),J=H.concat(L);s=s.concat(J)}else return VKRoXL[n(1612)](_0x24a3c7,_0x21a257[n(825)](_0xd236be(this),_0x3a17c1));else s=s.concat(L)}return s}}else if(_0x4462cc.payload instanceof _0x57b1a2){let s=e[n(1436)](this[n(1401)]["payloadE"+n(1332)],_0x185e64)?{force:!!this[n(1401)][n(1585)+n(1332)][n(1089)],encoding:this[n(1401)][n(1585)+"ncoding"][n(1129)]?this._options[n(1585)+n(1332)][n(1129)][n(470)](/\s/g,"")[n(1140)+"ase"]():""}:{force:!1,encoding:this[n(1401)][n(1585)+"ncoding"]?this._options.payloadEncoding.replace(/\s/g,"")[n(1140)+n(924)]():""},l=_0x52270f[n(1585)+n(1332)]?_0x27bd01[n(1585)+n(1332)][n(470)](/\s/g,"")[n(1140)+"ase"]():"",f=e[n(1436)](this[n(1401)][n(1170)+n(783)],_0x54b81f)?{force:!!this[n(1401)][n(1170)+n(783)].force,type:this[n(1401)][n(1170)+n(783)][n(1642)]?this[n(1401)][n(1170)+n(783)].type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options[n(1170)+n(783)]?this[n(1401)][n(1170)+n(783)].replace(/\s/g,"")[n(1140)+n(924)]():""},p=_0x5e8137[n(1170)+n(783)]?_0x41c19f[n(1170)+n(783)][n(470)](/\s/g,"")["toLowerC"+n(924)]():"",y=f[n(1089)]?f[n(1642)]:p||f[n(1642)],E=s.force?s[n(1129)]:l||s[n(1129)],m=[e[n(1287)],e[n(842)],e[n(638)],e[n(451)]],P=[n(1137)+"e",e[n(968)]];this[n(1401)][n(655)+"ansformT"+n(1829)+"ad"]&&m[n(1161)](y)&&(!E||P.includes(E))?_0x4835ed[n(447)+n(468)]=e.tCnju(_0x4d33f6,_0x385780[n(679)],0,_0x2b2121[n(679)][n(1814)+"th"]):_0x291e87[n(447)+"oad"]=""}else _0x33e0dd[n(447)+n(468)]=""}function g(c,n){let s=t,l=c[s(1169)];l!==void 0&&(e[s(481)](pe,n,10),e.XDjCq(z,n,l));let f=c[s(1059)];f!==void 0&&(e[s(481)](pe,n,18),e[s(1454)](z,n,f))}function w(c){let n=t,s={};e:for(;!e[n(658)](K,c);){let l=e.iTVoO(xe,c);switch(l>>>3){case 0:break e;case 1:s.key=R(c,e.NwEgH(xe,c));break;case 2:s.value=R(c,e[n(658)](xe,c));break;default:e[n(481)](k,c,7&l)}}if(e.iWiyU(void 0,s.key))throw new Error(e[n(822)]);if(e[n(1628)](void 0,s[n(1059)]))throw new Error(e.tGrsT);return s}function S(c){let n=t,s=e[n(1147)](C);return _(c,s),e.Pwqfm(N,s)}function _(c,n){let s=t,l={FJcUq:function(qt,mt){return e.yBRad(qt,mt)},QQRWS:function(qt,mt){return e[U(1672)](qt,mt)}},f=c[s(1577)];e.iIsZn(void 0,f)&&(e[s(958)](pe,n,8),xt(n,f));let p=c[s(1071)];p!==void 0&&(pe(n,16),e[s(1388)](xt,n,p));let y=c[s(1302)];e[s(960)](void 0,y)&&(pe(n,24),e.rxIIa(xt,n,D(y)));let E=c[s(1096)];e[s(960)](void 0,E)&&(e[s(752)](pe,n,32),xt(n,e[s(505)](D,E)));let m=c[s(915)];if(e[s(417)](void 0,m))for(let qt of m){e[s(1454)](pe,n,42);let mt=e[s(1147)](C);e[s(1044)](g,qt,mt),pe(n,mt[s(868)]),e[s(504)](j,n,mt),O(mt)}let P=c.payloadEncoding;e[s(928)](void 0,P)&&(pe(n,50),e[s(1044)](z,n,P));let L=c["payloadT"+s(783)];e.FzUOK(void 0,L)&&(pe(n,58),e[s(1284)](z,n,L));let H=c[s(679)];H!==void 0&&(e[s(1016)](pe,n,66),e[s(1044)](pe,n,H[s(1202)]),e[s(958)](oe,n,H));let J=c.LogIDNew;if(e[s(960)](void 0,J)){if(e[s(960)](e[s(463)],e[s(463)]))return _0x244958[s(1795)+"8"]?{value:_0x3fc161[s(1795)+"8"](_0x447a03),offset:l[s(768)](_0x4b5f5b,1)}:{value:l[s(878)](255,_0x5594f1[_0x59beb7]),offset:l[s(768)](_0x3f8188,1)};e[s(1044)](pe,n,74),e[s(1852)](z,n,J)}let V=c[s(1541)+"ming"];e[s(928)](void 0,V)&&(pe(n,82),e.noxCa(z,n,V));let Be=c[s(1820)];e[s(1192)](void 0,Be)&&(e[s(615)](pe,n,90),z(n,Be));let gt=c[s(1049)+"e"];e[s(971)](void 0,gt)&&(e.VdtGm(pe,n,96),e.JWJRd(xt,n,D(gt)))}function v(c){let n=t;return e.DtUcs(I,e[n(1769)](B,c))}function I(c){let n=t,s={GtcOx:function(l,f){return e[U(1246)](l,f)},RacFI:function(l,f){return e[U(1690)](l,f)},Duafs:function(l,f){return e[U(424)](l,f)},NrLYr:function(l,f){return e[U(1091)](l,f)},fJfyq:function(l,f){return e[U(1304)](l,f)},oTYCe:function(l,f){return e[U(1033)](l,f)},vqdgs:function(l,f){return e[U(1707)](l,f)},Npcyq:function(l,f){return l&f},FnJBX:function(l,f){return e.NfqKO(l,f)},TpMoK:function(l,f,p,y){return e.UoWbM(l,f,p,y)},FnZSs:function(l,f){return l>=f},smEeZ:function(l,f){return e[U(1276)](l,f)},sektq:function(l,f){return e.yBRad(l,f)},prltb:function(l,f){return l-f},BAlmx:function(l,f){return e.tmsMp(l,f)},JwAaA:function(l,f){return e[U(705)](l,f)},EIOPj:function(l,f){return e[U(1431)](l,f)},kJgun:function(l,f){return l>>f},parXp:function(l,f){return e[U(424)](l,f)},ustbF:function(l,f){return l|f},JjzBu:function(l,f){return e[U(1831)](l,f)},qJyMT:function(l,f){return e[U(402)](l,f)},ukmSh:function(l,f){return e[U(684)](l,f)},KJxAT:function(l,f){return e[U(1805)](l,f)},guiRQ:function(l,f){return e.JrBnx(l,f)}};if(e.XZhSa(e[n(757)],n(1335))){let l={};e:for(;!e[n(1372)](K,c);)if(e[n(971)](e[n(1207)],n(382))){let f={TsRYG:function(y,E){return s[n(1440)](y,E)},RSAFk:function(y,E){return s.RacFI(y,E)},QVYnz:function(y,E){return s[n(1396)](y,E)},vsmcx:function(y,E){return s.NrLYr(y,E)},eYBnf:function(y,E){return s[n(1837)](y,E)},oLooN:function(y,E){return s[n(1503)](y,E)},LzYap:function(y,E){return y<E},TwLXb:function(y,E){return s[n(633)](y,E)},zrCvk:function(y,E){return s[n(1440)](y,E)},mRxgF:function(y,E){return s.vqdgs(y,E)},KvcIh:function(y,E){return s.GtcOx(y,E)},jrCvP:function(y,E){return s[n(749)](y,E)},xNNgM:function(y,E){return y<E},FFSgQ:function(y,E){return s[n(633)](y,E)},EzQjs:function(y,E){return s.FnJBX(y,E)},eyiwL:function(y,E,m,P){return s.TpMoK(y,E,m,P)}},p=4294967295;return function(y,E,m=!0){let P=n;if(p=f[P(1320)](f[P(482)](127,y[E]),0),f[P(1589)](y[E++],128))return{value:m?p:f[P(1252)](0,p),offset:E};if(p=f.eYBnf(f[P(1252)](p,f[P(1673)](127&y[E],7)),0),f[P(1459)](y[E++],128))return{value:m?p:f[P(1265)](0,p),offset:E};if(p=f[P(606)](f[P(798)](p,f[P(1673)](127&y[E],14)),0),f[P(1459)](y[E++],128))return{value:m?p:0|p,offset:E};if(p=f[P(1333)](p|f[P(1673)](f[P(482)](127,y[E]),21),0),y[E++]<128)return{value:m?p:0|p,offset:E};if(p=f[P(1731)](f[P(1252)](p,f[P(1673)](f[P(735)](15,y[E]),28)),0),f[P(1392)](y[E++],128))return{value:m?p:f[P(888)](0,p),offset:E};if(f.EzQjs(E+=5,y[P(1202)]))throw E=y[P(1202)],f[P(1815)](_0x59c6b1,E,10,y[P(1202)]);return{value:m?p:0|p,offset:E}}}else{let f=xe(c);switch(e[n(1304)](f,3)){case 0:break e;case 1:l[n(1577)]=It(c,!0);break;case 2:l[n(1071)]=e[n(1110)](It,c,!0);break;case 3:l.service=e[n(862)](xe,c);break;case 4:l.method=e.psNIl(xe,c);break;case 5:{let p=A(c);(l[n(915)]||(l[n(915)]=[]))[n(698)](e[n(1344)](w,c)),c[n(868)]=p;break}case 6:l["payloadE"+n(1332)]=e[n(688)](R,c,e[n(808)](xe,c));break;case 7:l.payloadType=R(c,xe(c));break;case 8:l[n(679)]=ie(c,e.ZdPNZ(xe,c));break;case 9:l[n(1767)]=e[n(1016)](R,c,e[n(656)](xe,c));break;case 10:l.serverTiming=R(c,e.QUapr(xe,c));break;case 11:l[n(1820)]=e[n(775)](R,c,e[n(503)](xe,c));break;case 12:l[n(1049)+"e"]=e[n(505)](xe,c);break;default:e.VdtGm(k,c,7&f)}}if(e.lhWXC(void 0,l[n(1577)]))throw new Error(e.ITaAW);if(l.LogID===void 0)throw new Error(e[n(1549)]);if(l[n(1302)]===void 0)throw new Error(e[n(579)]);if(e.lhWXC(void 0,l[n(1096)]))throw new Error(e[n(1358)]);return l}else{let l=_0x376d4a[n(1203)+"At"](_0x3b143b);s[n(1211)](l,55296)&&s[n(528)](l,56319)&&s.Duafs(s[n(887)](_0xfdb12a,1),_0x1ce65d)&&(l=s.prltb(s[n(1846)](s[n(907)](l,10),_0x2b52ec[n(1203)+"At"](++_0x2567ec)),56613888)),l<128?_0x1b44c1[_0x4f447f++]=l:(l<2048?_0x4ec788[_0x5a5c7c++]=s[n(1663)](s[n(1001)](s[n(837)](l,6),31),192):(s.parXp(l,65536)?_0x233547[_0x4626c8++]=l>>12&15|224:(_0x4a979a[_0x2c039e++]=s[n(1197)](s[n(1770)](l>>18,7),240),_0x36872b[_0x4c2fd3++]=s[n(828)](s[n(1736)](s[n(1796)](l,12),63),128)),_0x148355[_0x5c938d++]=s[n(1219)](s[n(1001)](l>>6,63),128)),_0x18d9fa[_0x314c5f++]=s[n(1736)](63,l)|128)}}function A(c){let n=t,s=e[n(862)](xe,c),l=c.limit;return c[n(868)]=e.yBRad(c.offset,s),l}function k(c,n){let s=t;switch(n){case 0:for(;e[s(1778)](128,e[s(1612)](ee,c)););break;case 2:e.XDjCq($,c,e[s(779)](xe,c));break;case 5:$(c,4);break;case 1:$(c,8);break;default:throw new Error(e[s(623)]+n)}}function D(c){let n=t,s={pNUYl:function(l,f,p){return e[U(988)](l,f,p)},niSkv:"cursor_n"+n(1112)};if(e[n(1623)](e.RtXrM,n(1323)))this[n(627)+n(1678)]=_0x966f56,this._cursorFileName=_0x5e6cd8,this[n(1640)+"Strategy"]=_0x44785d,this[n(865)]=s[n(1457)](_0x6607c4,this["_cursorN"+n(1678)],s[n(1466)]);else return c|=0,{low:c,high:e[n(1805)](c,31),unsigned:e.FWeAn(c,0)}}let b=[];function C(){let c=t,n=b[c(475)]();return n?(n[c(1338)]=n[c(868)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(c){let n=t;e[n(960)](e[n(690)],e[n(1641)])?b[n(698)](c):_0x423fb5[n(641)+n(1280)+"e"](_0x26cf51,{keyPath:_0x3bedf1})}function B(c){return{bytes:c,offset:0,limit:c[t(1202)]}}function N(c){let n=t,s={GFPqd:e[n(1027)]};if(e[n(1874)](e[n(1749)],n(1052))){let l=c[n(811)],f=c[n(868)];return e.lhWXC(l[n(1202)],f)?l:l[n(1547)](0,f)}else{if(!this[n(1490)+n(1363)]()||this[n(413)+n(1074)])return;this[n(1484)+"tManager"]?.[n(1701)+n(819)+n(741)](),this["_pingLos"+n(1596)]?.["resetCou"+n(720)](),this[n(449)]?this[n(1128)+"ect"](1001,s[n(502)],!0):this[n(1870)]()}}function $(c,n){let s=t;if(e[s(520)](e.XhuQE(c[s(1338)],n),c[s(868)]))throw new Error(e[s(1441)]);c[s(1338)]+=n}function K(c){let n=t;if(e.OpVLE!==e.OpVLE){let s=this[n(1484)+"tManager"]?.[n(1491)+"ntEndpoint"]();this[n(1519)](n(459)+s),_0x546f16()}else return e[n(1286)](c[n(1338)],c[n(868)])}function ne(c,n){let s=t,l=c[s(811)],f=c[s(1338)],p=c.limit,y=e[s(1878)](f,n);if(e[s(520)](y,l[s(1202)])){let E=new Uint8Array(e[s(1838)](2,y));E[s(1241)](l),c[s(811)]=E}return c[s(1338)]=y,e[s(520)](y,p)&&(c[s(868)]=y),f}function Z(c,n){let s=t,l=c.offset;if(e.myNzD(e[s(1146)](l,n),c[s(868)]))throw new Error(s(766)+s(614));return c[s(1338)]+=n,l}function ie(c,n){let s=t,l=e.btBOd(Z,c,n);return c[s(811)][s(1547)](l,e[s(1517)](l,n))}function oe(c,n){let s=t;if(e[s(1414)]!==e[s(1414)]){let l=0,f=0,p;do p=e[s(1220)](_0x1f2420,_0x505e21),e[s(1123)](l,32)&&(f|=e[s(794)](127&p,l)),l+=7;while(e[s(1754)](128,p));return f}else{let l=e.sxiTm(ne,c,n.length);c[s(811)][s(1241)](n,l)}}function R(c,n){let s=t,l=Z(c,n),f=String[s(1493)+s(672)],p=c[s(811)],y="\uFFFD",E="";for(let m=0;m<n;m++){let P=p[e[s(1819)](m,l)],L,H,J,V;(128&P)===0?E+=f(P):e[s(1399)](224,P)===192?e.zUfEv(m+1,n)?E+=y:(L=p[e[s(1041)](e.SAvIZ(m,l),1)],e.RaMSv(e[s(1778)](192,L),128)?E+=y:e[s(847)]===e[s(1821)]?(VKRoXL[s(862)](_0x11d09a,_0x5a4bdb[s(1225)]),VKRoXL[s(1147)](_0x3ad9f7)):(V=e[s(1693)](e[s(794)](e.QFfJe(31,P),6),e[s(473)](63,L)),e[s(803)](V,128)?E+=y:(E+=e[s(1703)](f,V),m++))):e[s(1048)](240&P,224)?e[s(549)](e[s(1024)](m,2),n)?E+=y:(L=p[e[s(643)](e[s(1676)](m,l),1)],H=p[e[s(1064)](m+l,2)],e[s(590)](e[s(1778)](e[s(547)](L,H<<8),49344),32896)?E+=y:(V=e[s(1483)](e[s(387)](e[s(1634)](15&P,12),e[s(1033)](e[s(1778)](63,L),6)),63&H),e[s(1123)](V,2048)||e[s(1286)](V,55296)&&V<=57343?E+=y:(E+=e[s(576)](f,V),m+=2))):e.dCMHq(248,P)==240?e[s(807)](e[s(1008)](m,3),n)?E+=y:(L=p[m+l+1],H=p[e[s(1583)](m+l,2)],J=p[e[s(643)](e[s(1791)](m,l),3)],e[s(913)](e[s(1326)](e[s(419)](e[s(1693)](L,e[s(1033)](H,8)),e[s(1817)](J,16)),12632256),8421504)?E+=y:(V=e[s(546)](e.myuNp(e[s(426)](e[s(444)](7,P),18),e[s(1432)](63,L)<<12),e[s(1561)](e.vZBST(63,H),6))|e[s(927)](63,J),V<65536||e[s(664)](V,1114111)?E+=y:(V-=65536,E+=f(e[s(1805)](V,10)+55296,e[s(670)](1023,V)+56320),m+=3))):E+=y}return E}function z(c,n){let s=t,l=n[s(1202)],f=0;for(let E=0;e[s(1263)](E,l);E++){let m=n[s(1203)+"At"](E);e.bGDcC(m,55296)&&e[s(1276)](m,56319)&&e.DTPsj(E+1,l)&&(m=e.lwcDq(e[s(1794)](m,10),n[s(1203)+"At"](++E))-56613888),f+=e[s(1811)](m,128)?1:m<2048?2:m<65536?3:4}e[s(609)](pe,c,f);let p=ne(c,f),y=c[s(811)];for(let E=0;e[s(512)](E,l);E++){let m=n[s(1203)+"At"](E);e[s(1286)](m,55296)&&e[s(1276)](m,56319)&&e[s(657)](e[s(1583)](E,1),l)&&(m=e[s(931)](e[s(858)](m<<10,n.charCodeAt(++E)),56613888)),e.oufwX(m,128)?y[p++]=m:(e[s(1818)](m,2048)?y[p++]=e.gnckv(m,6)&31|192:(e.gNYGe(m,65536)?y[p++]=e.xmqqV(e[s(1432)](e[s(1805)](m,12),15),224):(y[p++]=e[s(1672)](m>>18,7)|240,y[p++]=e[s(677)](e[s(1618)](e.QRQMH(m,12),63),128)),y[p++]=e[s(832)](e[s(701)](e[s(1805)](m,6),63),128)),y[p++]=e[s(832)](e[s(969)](63,m),128))}}function j(c,n){let s=t,l=e[s(1016)](ne,c,n[s(868)]),f=c[s(811)],p=n[s(811)];for(let y=0,E=n[s(868)];e[s(1600)](y,E);y++)f[y+l]=p[y]}function ee(c){let n=t;return c.bytes[e[n(799)](Z,c,1)]}function Xe(c,n){let s=t,l=ne(c,1);c[s(811)][l]=n}function xe(c){let n=t;if(e.aElHf(n(1242),e[n(589)])){let s=_0x890ebe[n(1202)]&&_0x56f199[0];if(e[n(1661)](s,_0xe3d050))throw s;let l=new _0xdb533d(e[n(1064)](e[n(932)],s?e[n(1086)](e[n(1500)](" (",s.message),")"):""));throw l.context=s,s}else{let s=0,l=0,f;do if(e[n(869)]===e[n(869)])f=ee(c),e.jZllt(s,32)&&(l|=e[n(1399)](127,f)<<s),s+=7;else return _0x31e098[n(811)][_0x44ab1b(_0x3ceb7a,1)];while(128&f);return l}}function pe(c,n){let s=t;for(n>>>=0;e[s(1650)](n,128);)e[s(978)](Xe,c,127&n|128),n>>>=7;Xe(c,n)}function It(c,n){let s=t,l=0,f=0,p=0,y;if(y=e[s(552)](ee,c),l=e[s(570)](127,y),128&y&&(y=e[s(656)](ee,c),l|=e.huVtR(e.ZhEFu(127,y),7),e.kPdHv(128,y)&&(y=e[s(576)](ee,c),l|=e[s(1794)](127&y,14),e.LJhwh(128,y))))if(e.zWgXr(s(1825),s(1825))){if(y=e[s(1875)](ee,c),l|=e.lXhgj(e.FWLQv(127,y),21),128&y&&(y=e[s(779)](ee,c),f=e[s(701)](127,y),e[s(927)](128,y)&&(y=ee(c),f|=e[s(426)](e[s(1868)](127,y),7),128&y&&(y=ee(c),f|=e[s(969)](127,y)<<14,128&y&&(y=ee(c),f|=e.kDDRQ(e[s(1868)](127,y),21),e[s(1084)](128,y))))))if(e[s(1206)]===e.HMIoa){let E=this[s(1484)+s(506)]?.[s(1491)+s(1681)+"nt"](),m=this[s(1401)][s(1566)+s(944)+"ptor"](_0x5a40d9[s(1793)],_0x495364.reason);this["_dispatc"+s(1205)+s(1135)](e[s(1095)](_0xb6e3ca,e[s(384)],{code:1006,reason:_0x557eb3[s(1448)]||s(1638)+s(900)+"d, unkno"+s(1539)+s(1613)+s(1555)+E,willReconnect:m})),m&&this._connect();return}else y=e[s(576)](ee,c),p=e[s(1690)](127,y),e[s(670)](128,y)&&(y=e[s(1149)](ee,c),p|=e[s(444)](127,y)<<7)}else return _0x1d0f6e?this.toBytesLE():this[s(990)+"E"]();return{low:e[s(1460)](l,e[s(1561)](f,28)),high:e[s(419)](e[s(1857)](f,4),e[s(1794)](p,24)),unsigned:n}}function xt(c,n){let s=t,l={TprFS:e.Acjbx,tySrD:function(f,p){return f!=p}};if(e[s(1623)](e[s(593)],e[s(593)])){let f=n[s(525)]>>>0,p=(e.esoNl(n.low,28)|e[s(1851)](n[s(540)],4))>>>0,y=n[s(540)]>>>24,E=e.zWgXr(0,y)?e[s(724)](0,p)?f<16384?e[s(1656)](f,128)?1:2:e[s(1040)](f,2097152)?3:4:e[s(1233)](p,16384)?e[s(1600)](p,128)?5:6:e[s(1656)](p,2097152)?7:8:e[s(1251)](y,128)?9:10,m=e[s(1016)](ne,c,E),P=c[s(811)];switch(E){case 10:P[e[s(611)](m,9)]=e[s(684)](e[s(1857)](y,7),1);case 9:P[e[s(1024)](m,8)]=E!==9?128|y:127&y;case 8:P[e.haqis(m,7)]=e.zakxU(8,E)?e[s(1171)](e[s(1246)](p,21),128):e.DEmig(e[s(1304)](p,21),127);case 7:P[e[s(1517)](m,6)]=e[s(417)](7,E)?e[s(630)](e[s(1246)](p,14),128):e.PfhWm(e.jXnFy(p,14),127);case 6:P[m+5]=e.sXckY(6,E)?e[s(1246)](p,7)|128:e.OtGXv(e[s(1398)](p,7),127);case 5:P[e[s(1038)](m,4)]=e.iIsZn(5,E)?e[s(1463)](128,p):127&p;case 4:P[m+3]=e[s(928)](4,E)?e[s(1171)](e.RTzCI(f,21),128):e[s(1672)](f>>>21,127);case 3:P[e.YXugU(m,2)]=E!==3?e[s(402)](e[s(401)](f,14),128):e.YECgZ(f,14)&127;case 2:P[e[s(1008)](m,1)]=e.XZhSa(2,E)?e[s(1254)](e[s(458)](f,7),128):e.SxvcL(f>>>7,127);case 1:P[m]=e.BLEgE(1,E)?e.KfrGi(128,f):e[s(1799)](127,f)}}else return l[s(764)]!=typeof _0x43c985&&(_0x4c0569 instanceof _0x16e262||_0x4548ac.buffer&&_0x16cba3.buffer instanceof _0x34d9c8)||l[s(989)](l[s(764)],typeof _0x5d90bd)?"":(_0x674485.parse(_0x4bfb3e),s(1696)+"ion/json")}function nn(c){let n=t;return e[n(881)](n(1131),e[n(1480)])?e[n(1100)](v,c):_0x78982b||(_0x2565ac=[_0x5099db,_0x59ebb0,_0x4d498d,_0x26f350,_0x4287be])}function Ut(c){return S(c)}let rn=65536,Zr=e[t(1854)],we=rn*rn,Ie=e[t(457)](we,we),tr=e[t(445)](Ie,2),De=String[t(1116)+"e"][t(1203)+"At"];class ue{constructor(n,s,l){let f=t;this[f(872)]=!0,this[f(525)]=e[f(1259)](0,n),this[f(540)]=0|s,this[f(1331)]=!!l}static[t(872)](n){let s=t;return n&&e.lhWXC(!0,n[s(872)])}static fromBits(n,s,l){return new ue(n,s,l)}static[t(514)+"s"](n,s,l){let f=t;return l?ue[f(514)+f(835)](n,s):ue[f(514)+f(796)](n,s)}static["fromByte"+t(835)](n,s){let l=t;return new ue(e[l(1259)](e[l(1497)](e.mlNqI(n[0],e.huVtR(n[1],8)),e[l(705)](n[2],16)),e.QPCSH(n[3],24)),e.SrAoL(e.hItcJ(e[l(1463)](n[4],n[5]<<8),e[l(763)](n[6],16)),e[l(763)](n[7],24)),s)}static["fromByte"+t(796)](n,s){let l=t;return new ue(e[l(496)](e[l(1803)](e[l(1605)](e[l(1634)](n[4],24),n[5]<<16),e[l(973)](n[6],8)),n[7]),e[l(1752)](e[l(1687)](e[l(1330)](n[0],24),n[1]<<16),e[l(426)](n[2],8))|n[3],s)}static fromHash(n){let s=t;return e[s(1158)](n,Zr)?nl:new ue(e[s(1744)](e[s(729)](De.call(n,0)|e[s(1330)](De[s(1655)](n,1),8),e[s(1561)](De[s(1655)](n,2),16)),e[s(426)](De[s(1655)](n,3),24))>>>0,e[s(1383)](e.BKizC(e[s(1492)](De[s(1655)](n,4),e[s(662)](De[s(1655)](n,5),8)),e.OuzMe(De[s(1655)](n,6),16))|e[s(426)](De[s(1655)](n,7),24),0),!0)}[t(829)](){let n=t;return String[n(1493)+n(672)](e[n(1084)](255,this[n(525)]),e[n(1560)](e.UTBNa(this.low,8),255),e[n(1831)](e[n(1729)](this[n(525)],16),255),this[n(525)]>>>24,e.dCMHq(255,this[n(540)]),e[n(1672)](e[n(1105)](this.high,8),255),this.high>>>16&255,e[n(1692)](this[n(540)],24))}static fromNumber(n,s=!0){let l=t;if(e[l(1875)](isNaN,n))return s?Bp:nl;if(s){if(e[l(1069)](n,Ie))return zp}else{if(e[l(1276)](n,-tr))return Up;if(e[l(1437)](n,1)>=tr)return Fp}return ue.fromBits(e[l(910)](e.qlcYz(n,we),0),e.SrAoL(e.zWzYw(n,we),0),s)}[t(1469)](){let n=t;return this[n(1331)]?e[n(490)](e.hyPYj(e[n(1246)](this[n(540)],0),we),this.low>>>0):e[n(1507)](this[n(540)],we)+e[n(896)](this[n(525)],0)}[t(1858)](){let n=t;return e[n(1874)](0,this.high)&&this[n(525)]===0}[t(1035)](n){let s=t;ue.isLong(n)||(n=ue[s(391)+"er"](n));let l=e.RTzCI(this.high,16),f=e[s(570)](65535,this[s(540)]),p=e.KwvLw(this[s(525)],16),y=e[s(1799)](65535,this[s(525)]),E=n[s(540)]>>>16,m=65535&n.high,P=e[s(1383)](n[s(525)],16),L=e.IbDpY(65535,n[s(525)]),H=0,J=0,V=0,Be=0;return Be+=e[s(1437)](y,L),V+=e[s(975)](Be,16),Be&=65535,V+=e[s(858)](p,P),J+=e[s(975)](V,16),V&=65535,J+=e[s(643)](f,m),H+=e.nqlLS(J,16),J&=65535,H+=e[s(1163)](l,E),H&=65535,ue[s(1505)](e[s(1605)](e[s(731)](V,16),Be),e[s(832)](e[s(435)](H,16),J),this[s(1331)])}equals(n){let s=t;return ue[s(872)](n)||(n=ue[s(391)+"er"](n)),e[s(1804)](this[s(1331)],n[s(1331)])&&e[s(1874)](e.esoNl(this[s(540)],31),1)&&e[s(1874)](e.pSCfZ(n[s(540)],31),1)?!1:e[s(434)](this.high,n[s(540)])&&this[s(525)]===n.low}[t(1545)](){let n=t;return e[n(881)](-1,this[n(525)])&&e.RrrzE(-1,this.high)?ue[n(1505)](0,0,this[n(1331)]):this[n(525)]===-1?ue[n(1505)](0,e.Fsdsd(this[n(540)],1),this[n(1331)]):ue[n(1505)](this.low+1,this[n(540)],this[n(1331)])}toBytes(n){return n?this[t(1345)+"E"]():this.toBytesBE()}[t(1345)+"E"](){let n=t,s=this[n(540)],l=this.low;return[255&l,e.gyouR(l>>>8,255),e.SxvcL(e.nFZtf(l,16),255),e[n(401)](l,24),e[n(1474)](255,s),e.UwnMA(e[n(1847)](s,8),255),e.IqWCG(e[n(804)](s,16),255),s>>>24]}[t(990)+"E"](){let n=t;if(e[n(423)](e.shlHE,e.bQMLV)){let s=this.high,l=this[n(525)];return[s>>>24,e[n(1778)](e[n(1426)](s,16),255),e[n(1618)](e[n(1105)](s,8),255),e[n(1416)](255,s),e[n(1175)](l,24),e[n(1399)](l>>>16,255),e[n(1447)](e[n(1423)](l,8),255),255&l]}else return _0x2ba65c&&(_0x335fe1=(0,_0x39c515[_0x1e0700(_0x401b5d)[0]])(_0x403ef5=0)),_0x46a1b2}}let nl=new ue(0,0,!1),Bp=new ue(0,0,!0),Fp=ue.fromBits(-1,2147483647,!1),zp=ue[t(1505)](-1,-1,!0),Up=ue[t(1505)](0,-2147483648,!1);var sn=(function(c){let n=t;return c[c[n(1045)+"RROR"]=5001]=e[n(1244)],c[c[e[n(1400)]]=5002]=e[n(1400)],c[c[n(1627)+"IES_ERROR"]=5003]=e.Hbckw,c[c[e[n(761)]]=5004]=e.ZOfXy,c[c[n(719)+"OR"]=5005]=e[n(996)],c})({});class nr{constructor(n){let s=t;this[s(1642)]=n,this[s(1869)]=null}}class rl extends nr{constructor(n,s){let l=t;super(n),this[l(1101)]=s&&s[l(1101)]||null}}class il extends nr{constructor(n,s){let l=t;super(n),this[l(1225)]=s&&s[l(1225)]||null,this[l(513)]=s&&s[l(513)]||0,this[l(1057)]=s&&s[l(1057)]||"",this[l(619)]=s&&s[l(619)]||0,this.message=s&&s.message||"",this[l(1793)]=s&&s[l(1793)]||5001}}class sl extends nr{constructor(n,s){let l=t,f=(l(1665)+"0")[l(1376)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[l(1113)+l(1568)]=s&&s[l(1113)+"nnect"]||!1;continue;case"1":this[l(1793)]=s&&s[l(1793)]||0;continue;case"2":this[l(410)]=s&&s[l(410)]||!1;continue;case"3":this.reason=s&&s[l(1448)]||"";continue;case"4":super(n);continue}break}}}class ol extends nr{constructor(n,s){let l=t;super(n),this[l(628)]=s&&s.data||null}}class al extends ol{constructor(n,s){let l=t;super(n),this[l(628)]=s&&s[l(628)]||null,this[l(1101)]=s&&s[l(1101)]||null}}class cl extends nr{constructor(n,s){let l=t;super(n),this[l(628)]=s&&s[l(628)]||null}}function ct(c,{message:n,code:s,error:l}){return new il(c,{message:n,code:s,error:l})}function pt(c,{code:n,reason:s,wasClean:l,willReconnect:f}){return new sl(c,{code:n,reason:s,wasClean:l,willReconnect:f})}function dl(c,{data:n,message:s}){return new al(c,{data:n,message:s})}function ll(c,{data:n}){let s=t;if(e.FCRPO(s(1487),e[s(438)]))return new cl(c,{data:n});{let p=e[s(634)][s(1376)]("|"),y=0;for(;;){switch(p[y++]){case"0":var l=_0x43b028[_0x387273]={exports:{}};continue;case"1":return l[s(486)];case"2":var f=_0x359386[_0x7cdb6e];continue;case"3":_0x299063[_0xa9bdfd](l,l.exports,_0x31e630);continue;case"4":if(VKRoXL[s(580)](void 0,f))return f[s(486)];continue}break}}}function fa(c,{message:n}){return new rl(c,{message:n})}class ul{constructor(n,s){let l=t;this[l(1384)+"s"]=n,this[l(707)+"es"]=s,this[l(492)+"ndex"]=0,this.currentEndpointTriesCount=0}[t(1701)+"pointCon"+t(741)](){let n=t;this[n(492)+n(488)]=0,this[n(1867)+n(429)+n(1182)+"t"]=0}[t(1593)+"es"](){let n=t;this[n(1867)+n(429)+"riesCount"]=0}[t(1491)+t(1681)+"nt"](){let n=t;return this[n(1384)+"s"][this[n(492)+n(488)]]}[t(1491)+"ntEndpoi"+t(732)+t(618)](){return this["currentEndpointT"+t(1182)+"t"]}[t(539)+t(1186)+"es"](){let n=t;return!!(e.goyrt(this["currentI"+n(488)],this.endpoints[n(1202)])||e[n(1156)](this[n(492)+n(488)],e[n(1240)](this[n(1384)+"s"][n(1202)],1))&&this["currentE"+n(429)+n(1182)+"t"]===this.maxRetries)}["checkCur"+t(1055)+t(728)+"hedMaxRe"+t(904)](){let n=t;return this["currentI"+n(488)]==this[n(1384)+"s"][n(1202)]?!0:e.LLQen(this[n(1867)+"ndpointT"+n(1182)+"t"],this[n(707)+"es"])}[t(1763)+t(1826)+"pointAnd"+t(854)+"unt"](){let n=t;if(e[n(1393)](e[n(983)],e.qtWUq)){let s=_0x5c1588[n(1169)];s!==void 0&&(_0x4853f9(_0x380860,10),e.JWJRd(_0x439b7d,_0x5724a1,s));let l=_0x1048c1[n(1059)];e[n(870)](void 0,l)&&(_0x535e53(_0x447bdb,18),e[n(1567)](_0x47f9af,_0x19bd01,l))}else return this[n(1867)+n(429)+n(1182)+"t"]=1,this[n(492)+n(488)]++,this[n(1384)+"s"][this[n(492)+n(488)]]}[t(1491)+t(1681)+t(1151)+t(1527)](){let n=t;return this[n(1867)+n(429)+n(1182)+"t"]++,this["getCurre"+n(1681)+"nt"]()}}let rr=(e.JGyxP!=typeof globalThis&&e[t(660)](t(1636),globalThis[t(1737)+"tor"].name)||e[t(645)](e[t(394)],typeof window)&&e[t(559)]===window.constructor[t(1648)])&&e[t(1494)](e[t(394)],typeof document),Pn=e[t(892)](e[t(394)],typeof globalThis)&&(e[t(802)](t(1473),globalThis[t(1737)+t(1435)][t(1648)])||e[t(755)]===globalThis["construc"+t(1435)][t(1648)])&&e[t(394)]!=typeof tt,Xr=(e[t(1494)](e[t(394)],typeof globalThis)&&e[t(483)](t(1473),globalThis[t(1737)+"tor"][t(1648)])||e[t(394)]==typeof globalThis||e[t(645)](e[t(394)],typeof globalThis)&&!!globalThis[t(773)+"Bridge"])&&e[t(1130)](e.JGyxP,typeof wx),Qr=e[t(394)]!=typeof globalThis&&(e[t(676)](t(836)+t(736)+t(1824)+"pe",globalThis[t(1737)+t(1435)].name)||e[t(691)]===globalThis[t(1737)+"tor"][t(1648)]||e[t(479)](e[t(1142)],globalThis.constructor[t(1648)]))&&e[t(1238)](e.JGyxP,typeof self),qp=t(1020)+"d"!=typeof globalThis&&e[t(1088)]===globalThis[t(1737)+t(1435)].name&&e[t(581)](e.JGyxP,typeof global)&&e[t(1623)](t(1473),global[t(1737)+t(1435)].name)&&e.owVhE(e[t(394)],typeof process)&&!!process.version;class ha{constructor(){let n=t;this[n(1760)+"rs"]={}}[t(450)](n,...s){let l=t,f=this[l(1760)+"rs"][n];if(f)f.slice()[l(838)](p=>p.fn[l(825)](p[l(1506)],s));else if(e[l(1300)](e.fEzmH,n)&&!this[l(697)]){let p=s[l(1202)]&&s[0];if(p instanceof Error)throw p;let y=new Error(e[l(490)](e[l(932)],p?e[l(1878)](" (",p.message)+")":""));throw y[l(1550)]=p,p}return this}off(n,s){let l=t;if(n===void 0)this[l(1760)+"rs"]={};else if(s===void 0)this._listeners[n]=null;else{let f=this[l(1760)+"rs"][n];if(f)for(let p=0;e[l(1698)](p,f[l(1202)]);)e[l(724)](f[p].fn,s)?f[l(1076)](p,1):++p}return this}on(n,s,l){let f=t;return(this[f(1760)+"rs"][n]||(this._listeners[n]=[]))[f(698)]({fn:s,ctx:l||this}),this}}class Gp extends ha{["_formatE"+t(1077)+t(1659)](n){let s=t;return n[s(1562)]||n[s(1630)]?(s(834)+" "+(n[s(1562)]||"")+s(558)+(n[s(1630)]||"")).trim():JSON.stringify(n)}constructor(n,s,l){let f=t;if(e[f(1565)]===e[f(1565)])super(),this[f(1359)]=null,Xr&&wx[f(703)+f(1324)]&&(this[f(1359)]=wx[f(703)+f(1324)]({url:n,protocols:s,header:l,fail:this[f(1177)+"ocketFailHandler"][f(1121)](this),success:this[f(1177)+f(1798)+f(517)+"ler"].bind(this)})),Pn&&tt["connectS"+f(1324)]&&(this[f(1359)]=tt[f(703)+f(1324)]({url:n,protocols:s,header:l,fail:this["_createSocketFai"+f(687)][f(1121)](this),success:this[f(1177)+f(1798)+f(517)+f(1424)][f(1121)](this)}));else try{this[f(449)]&&this[f(449)][f(1281)](_0x8ea394,_0x594a99)}catch{}}["_createS"+t(1798)+"cessHand"+t(1424)](){let n=t;Promise[n(1231)]()[n(1017)](()=>{let s=n;this[s(484)+s(601)]()})}[t(1177)+"ocketFai"+t(687)](n){let s=t;Promise[s(1231)]().then(()=>{let l=s,f=ct(e[l(452)],{message:this["_formatE"+l(1077)+l(1659)](n)});this[l(450)](e[l(452)],f);let p=e[l(727)](pt,e[l(384)],{reason:this[l(1841)+l(1077)+l(1659)](n)});this[l(450)]("close",p)})}["_addWsLi"+t(601)](){let n=t,s={njsHO:function(l,f){return e[U(1193)](l,f)},jxvJu:function(l,f){return l-f},SmGuw:function(l,f){return e[U(446)](l,f)},Cvjtk:function(l,f){return l<<f},UXCWl:function(l,f){return e[U(714)](l,f)},ASUMC:function(l,f){return e[U(903)](l,f)},RyHAf:function(l,f){return e[U(1399)](l,f)},ZQmpd:function(l,f){return e[U(1794)](l,f)},aiCGc:function(l,f){return l+f},MIrmz:function(l,f){return e.AeMdT(l,f)},RbuHb:function(l,f){return e[U(1437)](l,f)},IpZzL:function(l,f){return e.LOlPf(l,f)},Yhzdn:function(l,f){return e.lVPUw(l,f)},VmIUh:e[n(471)],PqbpQ:e[n(1013)],kUNNx:function(l,f,p){return e[n(727)](l,f,p)},TZIvk:n(1225)};if(e[n(971)](e[n(1134)],e[n(1134)])){let l=this[n(865)][n(1705)](this._prefix);return _0x4fb347[n(780)](s[n(1148)](l,"{}"))[_0x588252]}else this._socket[n(1530)](l=>{let f=n;if(e[f(1104)]==="YOoEf"){let p=s[f(1775)](s[f(1670)](s[f(1670)](s.Cvjtk(s[f(566)](7,_0x511384),18)|s[f(1668)](s[f(427)](63,_0x4496a9[_0x551af2++]),12),s.ZQmpd(s[f(566)](63,_0x33f198[_0x3562a0++]),6)),s[f(566)](63,_0x3a7d29[_0xb1eae1++])),65536);_0x2ba1c7+=_0x39dfd2[f(1493)+f(672)](s[f(813)](55296,s[f(1747)](p,10))),_0x51f6c9+=_0x3bb3be[f(1493)+f(672)](s[f(1122)](56320,1023&p))}else this[f(450)](f(456),e[f(1429)](ll,e[f(861)],{...l,data:l.errMsg||""}))}),this._socket.onClose(l=>{let f=n;if(e[f(881)](e[f(1766)],e[f(1766)]))this[f(450)](e[f(384)],pt(f(1281),{...l}));else return _0x15055c?_0x1d89c9[f(514)+f(835)](_0x31c059,_0x1decb7):_0x3c2cb2["fromByte"+f(796)](_0x551ef1,_0x142cdf)}),this[n(1359)][n(1700)+"e"](l=>{let f=n,p={mNRFa:function(y,E){return s.IpZzL(y,E)}};s[f(1518)](s[f(1615)],f(683))?this.emit(s[f(1007)],s[f(930)](dl,s[f(1007)],{...l})):(_0x230ea9(_0x1957cc,32),_0x31befd(_0x20bce5,fvNocB[f(864)](_0x414451,_0x5b93a3)))}),this[n(1359)][n(571)](l=>{let f=n;this[f(450)](s[f(1724)],ct(s[f(1724)],{...l,message:l[f(1562)]||""}))})}[t(793)](n){let s=t;if(e[s(1834)](n,Uint8Array))if(e[s(881)](e.ATGyY,e.ATGyY)){let l=n.buffer[s(541)](n[s(1068)+"et"],n.byteLength+n.byteOffset);this[s(1359)]&&this._socket.send({data:l,fail:f=>{let p=s;this[p(450)](e[p(452)],e[p(994)](ct,e[p(452)],{message:this[p(1841)+"rrorMess"+p(1659)](f)}))}})}else return new _0x3612ed(_0x193340,_0x24d1d9,_0x402c83);else this[s(1359)]&&this._socket[s(793)]({data:n,fail:l=>{let f=s,p={iTWSQ:function(y,E,m){return e[U(775)](y,E,m)}};e[f(479)](e[f(949)],f(669))?(EKpvRT[f(1309)](_0x2cb1f9,_0x10f80e,50),EKpvRT[f(1309)](_0x45d93a,_0x2abc0f,_0x3758c8)):this[f(450)](e[f(452)],e[f(935)](ct,"error",{message:this[f(1841)+"rrorMess"+f(1659)](l)}))}})}[t(1281)](n,s){let l=t;this[l(1359)]&&this[l(1359)].close({code:n,reason:s})}[t(956)+t(877)](n,s){let l=t;if(e[l(603)](l(1085),e[l(1759)]))this.on(n,s);else{let f={uShPm:function(p,y,E,m,P){let L=l;return VKRoXL[L(680)](p,y,E,m,P)},hLGwP:function(p,y){return p(y)}};_0x46195a[l(956)+"Listener"](VKRoXL[l(1081)],p=>{let y=l;f[y(1157)](_0x18c881,f[y(582)](_0x584c65,_0xa2aeaf[y(393)]),p[y(1637)+"on"],p[y(1245)+"on"],f.hLGwP(_0x10d5c2,_0x533f3f[y(1180)+y(721)]))})}}[t(617)+"entListe"+t(1366)](n,s){this.off(n,s)}get[t(1590)+"te"](){return this[t(1359)].readyState}get binaryType(){let n=t;return this[n(1359)][n(1168)+"pe"]}set[t(1168)+"pe"](n){}get[t(1802)](){let n=t;return this[n(1359)][n(1802)]}get[t(1209)](){let n=t;return this[n(1359)][n(1209)]}get[t(1603)+"ns"](){let n=t,s={VCtaU:"success",EfVgr:function(l,f,p){return e[U(708)](l,f,p)}};if(e[n(913)](n(1786),n(1786)))this[n(1877)+n(1313)](),this[n(450)](n(979)+n(1597)+"s",s[n(920)]),this[n(815)+"gTimeoutId"]=s[n(635)](_0xc673b5,this[n(1037)][n(1121)](this),_0xd4f7a);else return this[n(1359)][n(1603)+"ns"]}get[t(1822)+t(637)](){return 0}}function Hp(c,n){let s=t;if(n)return new n(c[s(1802)],c.protocol);if(e[s(464)](Xr,Pn))return new Gp(c[s(1802)],c[s(1209)],c[s(915)]);if(e[s(1193)](rr,Qr)&&e[s(645)](s(1020)+"d",typeof WebSocket)&&WebSocket)return new WebSocket(c[s(1802)],c[s(1209)+"s"])}function jp(c){let n=t;return!!(c||Xr&&wx["connectS"+n(1324)]||Pn&&tt[n(703)+n(1324)]||(rr||Qr)&&e[n(645)](e[n(394)],typeof WebSocket)&&WebSocket)}function fl(c,n,s){let l=t,f={iYHjL:"next() c"+l(1173)+l(460)+l(527)+l(765),MWqkQ:function(p,y){return e.esCes(p,y)},VyVKT:function(p,y){return e.myNzD(p,y)},xgKjw:e[l(1441)]};if(e[l(1840)](e[l(632)],e[l(632)])){let p=-1;async function y(E){let m=l;return E<=p?Promise[m(1428)](new Error(f[m(1257)])):(p=E,E===s.length?Promise[m(1231)]():s[E][m(1121)](c)(n,y[m(1121)](null,f[m(1115)](E,1))))}y(0)}else{if(mEGpzM[l(646)](_0x2ccee2[l(1338)]+_0x411ed0,_0x35600b.limit))throw new _0x4381dd(mEGpzM[l(1418)]);_0x18fc76[l(1338)]+=_0x587910}}function hl(c){let n=t,s=0,l=0;for(let f=0;e[n(538)](f,c.length);++f)l=c.charCodeAt(f),e[n(1065)](l,128)?s+=1:l<2048?s+=2:e.eZcsS(e[n(1326)](64512,l),55296)&&e[n(1247)](e[n(937)](64512,c.charCodeAt(e[n(1819)](f,1))),56320)?(++f,s+=4):s+=3;return s}function xl(c,n,s){let l=t;if(e[l(1296)](e[l(710)](s,n),1))return"";let f="";for(let p=n;e[l(1534)](p,s);){let y=c[p++];if(e[l(406)](y,127))f+=String[l(1493)+l(672)](y);else if(e.qOcMx(y,192)&&e[l(418)](y,224))f+=String[l(1493)+"Code"](e.Mponv(e[l(1033)](e[l(1669)](31,y),6),e[l(473)](63,c[p++])));else if(e[l(963)](y,224)&&e[l(538)](y,240))f+=String[l(1493)+"Code"](e[l(946)](e[l(610)](e.ooKVq(15,y)<<12,e.kxNVW(63&c[p++],6)),e[l(965)](63,c[p++])));else if(e[l(963)](y,240)){let E=e[l(1260)](e[l(1442)](e[l(1351)](e[l(670)](7,y),18),e[l(662)](e.mAMWK(63,c[p++]),12))|e[l(1399)](63,c[p++])<<6,63&c[p++])-65536;f+=String.fromCharCode(e[l(490)](55296,e[l(999)](E,10))),f+=String[l(1493)+l(672)](e[l(1746)](56320,e[l(1799)](1023,E)))}}return f}function xa(c,n,s){let l=t,f=s,p,y;for(let E=0;E<c[l(1202)];++E)p=c.charCodeAt(E),p<128?n[s++]=p:e[l(1588)](p,2048)?(n[s++]=e.vnRiB(e.msyXO(p,6),192),n[s++]=e[l(1753)](63&p,128)):e.xqFse(e[l(465)](64512,p),55296)&&e[l(1623)](e.bOEnl(64512,y=c[l(1203)+"At"](e[l(1064)](E,1))),56320)?(p=e.sIHDf(65536,e[l(662)](e[l(1758)](1023,p),10))+e[l(551)](1023,y),++E,n[s++]=e[l(553)](e[l(857)](p,18),240),n[s++]=e[l(934)](e[l(1078)](e[l(999)](p,12),63),128),n[s++]=e[l(910)](e[l(1073)](e[l(857)](p,6),63),128),n[s++]=e[l(1200)](63,p)|128):(n[s++]=e[l(1385)](e[l(1866)](p,12),224),n[s++]=e[l(921)](e[l(982)](p>>6,63),128),n[s++]=e.yARmU(e.gyouR(63,p),128));return e.kEhiv(s,f)}async function pl(c){let n=t;if(e.UarEX(e[n(451)],typeof c)){let s=new Uint8Array(e.xoQse(hl,c));return xa(c,s,0),s}return e[n(1643)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[n(1411)],c[n(1068)+"et"],c[n(1814)+"th"])}function Wp(c){let n=t;try{return e[n(645)](n(1495),typeof c)&&(e.lFvpr(c,ArrayBuffer)||c[n(1411)]&&e[n(901)](c[n(1411)],ArrayBuffer))||e.Acjbx!=typeof c?"":(JSON[n(780)](c),e[n(842)])}catch{return e[n(1048)](e[n(451)],typeof c)?e.srOlp:""}}let Kp=(c,n)=>{let s=t;switch(c){case e[s(1060)]:case s(583):return{[s(411)+c]:1,"x-tt-env":n};default:return{}}};class $p{constructor(n){let s=t;this[s(816)+s(618)]=n,this[s(472)]=0}[t(428)](){this.count++}["checkRea"+t(823)+"nt"](){let n=t;return e[n(666)](this[n(472)],this[n(816)+"ount"])}[t(594)+t(720)](n=0){let s=t;this[s(816)+"ount"]=n,this[s(472)]=0}}async function Vp(c){let n=t,s={KHCZe:function(l,f){return e[U(833)](l,f)},VkVnr:e[n(1267)],rXWAk:n(863),CqYzK:n(1781),pQrCp:e[n(1464)],lZkBj:function(l,f){return e[n(389)](l,f)},wYABH:"gAEoq"};if(e[n(870)](e[n(1496)],n(1592)))_0x58bec2-=65536,_0x5b26c2+=e[n(1388)](_0x87593f,e[n(643)](_0x2aae12>>10,55296),e[n(1038)](e[n(701)](1023,_0x133636),56320)),_0x544e8f+=3;else return new Promise(l=>{let f=n;if(!rr)return l(f(1453)+f(1448));try{let p=document[f(1859)+f(1777)](s[f(515)]);window[f(624)+f(1080)]=y=>{let E=f;document.body[E(1765)+"ild"](p),window[E(624)+"JSONP"]=void 0,s.KHCZe(l,y&&y.msg||s.VkVnr)},p[f(1642)]=f(855)+f(695),p[f(1133)]=c[f(470)](/^ws/,s[f(1468)])+s[f(597)];try{s[f(1675)](s[f(1374)],f(1181))?document[f(1204)][f(1108)+f(1548)](p):this.on(_0xfb26b4,_0x3b76ce)}catch{document.body[f(1765)+f(1548)](p)}}catch{window[f(624)+"JSONP"]=void 0,l(s.VkVnr)}})}function on(c,n,s){let l=t;return!!c?.[l(1403)](f=>f.key===n&&f[l(1059)]===s)}function ir(c,n){let s=t;return c?.[s(1403)](l=>l.key===n)?.[s(1059)]}let pa=null;async function Jp(){let c=t;return pa||(pa=Promise[c(1231)]()[c(1017)](Ft.bind(Ft,e[c(1172)]))),pa}class Yp extends ha{constructor(n,s){let l=t;if(e[l(1654)]("SCoCD",e[l(740)]))super(),this[l(545)]=n,this[l(462)]=s,this[l(865)]=void 0,this._initPromise=null;else{let f={vNdDA:function(E,m){return E(m)},luhIj:e[l(642)],sMpol:l(979)+"e_success",htmnb:"ping_onc"+l(1709)+"t",jmQBu:function(E,m){return e[l(1165)](E,m)},lwuQO:l(905)};this[l(1877)+l(1313)](),this[l(815)+l(574)+"Id"]=_0x32dcfa(this[l(1037)][l(1121)](this),this[l(1401)][l(1026)+"rval"]);let p=()=>{let E=l;f[E(1227)](_0x1626fa,f.luhIj),this[E(1823)](f[E(801)],p),this[E(1823)](f[E(1307)],y)},y=()=>{let E=l;f.jmQBu(_0x24a610,f[E(1275)]),this.off(f[E(801)],p),this[E(1823)]("ping_onc"+E(1709)+"t",y)};this.on(e[l(1362)],p),this.on(e[l(1004)],y),this[l(1037)]()}}async openDB(){let n=t,s={ffQLh:function(l,f,p){return e.kwgIW(l,f,p)},ZORKl:function(l,f,p){return e[U(1806)](l,f,p)}};e[n(870)](e[n(1715)],"fUcRV")?(jHuWOe.ffQLh(_0x51d501,_0x2ede4c,10),jHuWOe[n(1792)](_0x25abe0,_0x5169d6,_0x993935)):await this[n(1349)]()}async _init(){let n=t,s={iENtm:function(l){return l()},mPjKL:function(l,f,p,y){return l(f,p,y)}};if(e.hxWTD(e[n(1427)],"IGntb"))return n(624)+"_"+this[n(542)];if(this[n(865)])return;if(this["_initPro"+n(1594)])return this[n(1832)+n(1594)];try{let l=this._dbName,f=this[n(462)];this["_initPro"+n(1594)]=(async()=>{let p=n,{openDB:y}=await s.iENtm(Jp);this[p(865)]=await s.mPjKL(y,"frontier_"+l,1,{upgrade(E){E["createOb"+p(1280)+"e"](l,{keyPath:f})}})})(),await this[n(1832)+n(1594)]}catch(l){console[n(1842)](l)}finally{this[n(1832)+n(1594)]=null}}async[t(461)](n){let s=t;try{return await this[s(1349)](),this[s(865)]?.[s(461)](this._dbName,n)}catch(l){console[s(1842)](l)}}async[t(1241)](n,s){let l=t;return await this[l(1349)](),this[l(865)]?.[l(395)](this[l(545)],n)}async[t(1028)](n){let s=t;try{return await this[s(1349)](),this[s(865)]?.[s(850)](this[s(545)],n)}catch(l){console[s(1842)](l)}}async[t(776)](){let n=t,s={oDKrT:function(l,f){return e[U(1024)](l,f)},wTwOA:function(l,f){return e[U(739)](l,f)},wpwNs:function(l,f){return l*f}};try{return await this._init(),this._qosDB?.clear(this[n(545)])}catch(l){if(e.FOCFf===e[n(1602)])console[n(1842)](l);else{let f=_0x319f65[n(811)],p=_0x402598[n(1338)],y=_0x2e437e[n(868)],E=xSBizU[n(1289)](p,_0x3ed7af);if(xSBizU[n(1751)](E,f[n(1202)])){let m=new _0x357037(xSBizU[n(1839)](2,E));m[n(1241)](f),_0x3ade29.bytes=m}return _0x3c07a6[n(1338)]=E,xSBizU[n(1751)](E,y)&&(_0x4cbec2[n(868)]=E),p}}}async[t(480)](){let n=t;if(e[n(671)](e.JYMWZ,e[n(1445)]))this[n(1359)]&&this._socket.close({code:_0x28f7f6,reason:_0x5a40b5});else return await this._init(),this[n(865)]?.[n(1421)+"ys"](this[n(545)])}async getAll(){let n=t;return await this[n(1349)](),this[n(865)]?.[n(1587)](this[n(545)])}async[t(716)](){let n=t;try{this[n(865)]?.[n(1281)](),this[n(865)]=void 0}catch(s){console[n(1842)](s)}}get isReady(){let n=t;try{return!!this[n(865)]}catch(s){if(e[n(881)](n(733),e[n(1413)]))return console[n(1842)](s),!1;{let l=0,f={};for(let p=0;e[n(1184)](p,_0x321ffe.length);p++)f[_0x485f9e[p][n(1632)+"ame"]]=e[n(792)](_0x3be1e6,_0x1ea680[p]["cursor_n"+n(1112)]),l+=e[n(1160)](14,f[_0x49ac6e[p]["cursor_n"+n(1112)]]);return[l,f]}}}}class Zp{constructor(n,s){let l=t;this[l(542)]=n,this[l(507)]=s,this._qosDB=localStorage}async[t(661)](){}get[t(1727)](){return t(624)+"_"+this._DBName}async[t(461)](n){let s=t,l=this[s(865)][s(1705)](this[s(1727)]);return JSON.parse(l||"{}")[n]}async set(n,s){let l=t;if(e[l(1756)](e.TXrtI,e[l(1419)])){let f=this[l(865)].getStorageSync(this[l(1727)]);return _0x3dd18c[l(780)](e.YdCBC(f,"{}"))[_0x133bc4]}else{let f=this[l(865)][l(1705)](this[l(1727)]),p=JSON[l(780)](f||"{}");return p[s||n[this._pathKey]]=n,this._qosDB[l(1682)](this[l(1727)],JSON[l(953)+"y"](p)),s||n[this._pathKey]}}async[t(1028)](n){let s=t,l=this[s(865)][s(1705)](this._prefix),f=JSON[s(780)](l||"{}");return f[n]=void 0,this._qosDB[s(1682)](this[s(1727)],JSON[s(953)+"y"](f))}async[t(776)](){let n=t;return this[n(865)][n(776)]()}async[t(480)](){let n=t,s=this[n(865)][n(1705)](this[n(1727)]),l=JSON[n(780)](s||"{}");return Object.keys(l)}async[t(1587)](){let n=t,s=this[n(865)][n(1705)](this[n(1727)]),l=JSON[n(780)](e.HSASn(s,"{}"));return Object[n(1126)](l)}closeDB(){return Promise[t(1231)]()}get[t(1422)](){return!!this[t(865)]}}class Xp{constructor(n,s){let l=t;this[l(542)]=n,this[l(507)]=s,this[l(865)]=Pn?tt:Xr?wx:null}async openDB(){}get[t(1727)](){return t(624)+"_"+this._DBName}async[t(461)](n){let s=t,l=this._qosDB.getStorageSync(this[s(1727)]);return JSON[s(780)](e.WEHAp(l,"{}"))[n]}async set(n,s){let l=t,f=this[l(865)][l(980)+l(1337)](this[l(1727)]),p=JSON[l(780)](e.iQSfH(f,"{}"));return p[s||n[this[l(507)]]]=n,this._qosDB[l(652)+l(1337)](this._prefix,JSON[l(953)+"y"](p)),s||n[this[l(507)]]}async[t(1028)](n){let s=t,l=this[s(865)][s(980)+s(1337)](this[s(1727)]),f=JSON[s(780)](e[s(1499)](l,"{}"));return f[n]=void 0,this[s(865)][s(652)+s(1337)](this[s(1727)],JSON[s(953)+"y"](f))}async clear(){let n=t;return this._qosDB[n(1114)+n(1606)]()}async[t(480)](){let n=t,s=this[n(865)]["getStora"+n(385)+"nc"](this[n(1727)]),l=JSON[n(780)](s||"{}");return Object.keys(l)}async[t(1587)](){let n=t,s=this[n(865)][n(980)+n(385)+"nc"](this[n(1727)]),l=JSON[n(780)](s||"{}");return Object.values(l)}closeDB(){return Promise.resolve()}get[t(1422)](){return!!this[t(865)]}}function gl(c,n){let s=t;if(e[s(1840)](s(511),e[s(1733)]))return _0x25d5cc[s(748)+"t8"]?_0x5d161e.writeUint8(_0x2612e1,_0x16a9ba):_0x23fddd[_0x4481cd]=255&_0x3dfdd,e.yBRad(_0x59d919,1);if(e[s(1735)](Pn,Pn))return new Xp(c,n);if(e[s(464)](rr,Qr)&&e[s(892)](e[s(394)],typeof indexedDB))return new Yp(c,n);if(e[s(1371)](rr,Qr)&&e.RsElU("undefined",typeof localStorage))return new Zp(c,n);throw new Error(e[s(1346)])}class Qp{constructor(){let n=t;if(e[n(1237)](e.JrgXa,e[n(1367)]))this["_interva"+n(993)+"Id"]=null,this[n(1475)+"l"]=36e5,this[n(865)]=e[n(708)](gl,e.bgyJY,e.XPNQs);else return this[n(1359)][n(1802)]}async[t(1475)+t(689)](){let n=t;if(e[n(1269)](n(1353),e.OphsF))clearInterval(this[n(1475)+"lTimeoutId"]),this["_interva"+n(993)+"Id"]=e[n(1016)](setInterval,()=>{this[n(1141)+"ired"]()},this._interval);else return this[n(756)+"T"]||this[n(1633)+"X"]?this[n(940)+n(388)+n(942)]:(this[n(1294)+"er"]||this[n(1764)+"r"])&&this[n(1401)][n(636)+"tworkChanged"]?_0x15627f[n(1195)]:!0}async[t(661)](){let n=t;await this[n(865)][n(661)]().then(()=>{let s=n;this[s(1475)+s(689)]()})}async[t(1141)+t(1542)](){let n=t;(await this[n(865)]?.[n(1587)]()||[])[n(1482)](({timestamp:f})=>f<Date[n(1405)]())[n(838)](f=>{let p=n;this._qosDB?.[p(1028)](f[p(1379)+"id"])})}async[t(1028)](n){let s=t;return this[s(865)]?.[s(1028)](n)}async[t(1241)](n,s){let l=t;return this._qosDB?.[l(1241)]({message_id:n,timestamp:s})}async[t(461)](n){return this[t(865)]?.get(n)}async[t(716)](){let n=t;e[n(947)](e.dbMlB,e[n(1021)])?(this._ws&&this[n(449)].send(_0x27d10b),this[n(1519)](e[n(1053)],_0x51d087)):(e.DVJSf(clearInterval,this[n(1475)+n(993)+"Id"]),await this[n(865)]?.[n(716)]())}get isReady(){let n=t,s={ZVnXw:function(l,f){return l!==f},yAWOB:e[n(1162)],RQhac:e[n(1063)]};if(n(1018)===e[n(550)])_0x1e5639[n(1216)+"d"]&&(this[n(1490)+n(1363)]()&&(!this[n(449)]||s[n(918)](this._ws[n(1590)+"te"],this.OPEN)||s[n(918)](this[n(449)][n(1590)+"te"],this.CONNECTING))&&this["_handleO"+n(839)](),this[n(1294)+"er"]&&_0x2ae112["addEvent"+n(877)](s[n(1009)],this[n(1178)+n(839)]),this._isBrowser&&_0x205084["addEvent"+n(877)](s[n(1030)],this[n(1178)+"ffLine"]));else return this[n(865)]?.[n(1422)]}}function ga(c){let n=t,s={ipDqc:function(l,f,p){return e[U(1187)](l,f,p)},YKyNf:n(1225),ZANOD:function(l,f){return e[n(1269)](l,f)},CHIay:function(l,f,p){return e.uwPRA(l,f,p)}};if(e.XagSt("LRIPj",e[n(1680)])){let l=this[n(1484)+n(506)]?.[n(539)+n(1186)+"es"](),f=this["_endpoin"+n(506)]?.[n(1491)+n(1681)+"nt"]();if(l&&!_0x1ff618[n(1101)]){let p=n(966)+f+(" fail, m"+n(967)+n(521)+"ed");this[n(409)+n(1651)+n(1135)](s[n(1720)](_0x4ac5cb,s.YKyNf,{message:p,code:_0x400c57[n(1627)+n(1382)+"R"],error:_0x4d6889}));return}this[n(449)]&&s[n(1730)](this[n(449)][n(1590)+"te"],this[n(985)])&&this[n(1128)+n(1107)](),this[n(409)+n(1651)+n(1135)](s[n(1297)](_0x50f25d,n(1225),{message:_0x2095e7.message,code:_0x229a58[n(1045)+"RROR"],error:_0x1dd544}))}else{let l=!!this[n(1401)][n(1695)+"S"];if(!l)return{enabled:l,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let f=on(c.message[n(915)],e[n(882)],"2"),p=f&&e[n(952)](on,c[n(1101)][n(915)],e[n(567)],"1"),y=f&&on(c[n(1101)][n(915)],"x_fronti"+n(405)+"k","1"),E=y?e[n(988)](ir,c[n(1101)].headers,e[n(1002)])?.[n(1376)](",")[n(1482)](Boolean)||[]:[];return{enabled:l,isQoSMessage:f,isQoSAck:p,isAckCleanupMessage:y,ackMsgIds:E}}}async function ml(){let c=t;return this[c(1573)+c(790)]||(this[c(1573)+c(790)]=new Qp),this[c(1573)+c(790)][c(1422)]||await this["_QoSMana"+c(790)][c(661)](),this[c(1573)+c(790)]}async function eg(c,n){let s=t,{enableAutoAck:l}=this[s(1401)],f=e[s(952)](on,c[s(1101)].headers,e.HnNCU,"1"),p=on(c[s(1101)][s(915)],e.NXtcT,"1"),y=ga[s(1655)](this,c);if(e[s(1489)](l,f)){let{SeqID:E,LogID:m,service:P,LogIDNew:L,method:H}=c.message;this[s(778)]({SeqID:E,LogID:m,LogIDNew:L,service:P,method:H,headers:[{key:s(1124),value:"1"},{key:s(1317),value:e[s(1357)](L,"")},{key:e[s(1087)],value:"0"}]})}p&&!y[s(1370)]&&this[s(409)+s(1215)+s(1214)](c),e.FcGek(n)}async function tg(c,n){let s=t;this[s(1519)](e[s(560)],c[s(1101)]),e.svETR(n)}async function ng(c,n){let s=t,l=e[s(1580)](nn,await e[s(491)](pl,c.data));try{if(e[s(961)](l.payload,Uint8Array)){let f=e[s(1032)](this[s(1401)][s(1585)+s(1332)],Object)?{force:!!this._options[s(1585)+s(1332)][s(1089)],encoding:this[s(1401)][s(1585)+s(1332)].encoding?this[s(1401)][s(1585)+s(1332)].encoding.replace(/\s/g,"")[s(1140)+s(924)]():""}:{force:!1,encoding:this[s(1401)][s(1585)+s(1332)]?this[s(1401)][s(1585)+s(1332)].replace(/\s/g,"")[s(1140)+s(924)]():""},p=l[s(1585)+"ncoding"]?l[s(1585)+s(1332)][s(470)](/\s/g,"").toLowerCase():"",y=e[s(1436)](this._options[s(1170)+s(783)],Object)?{force:!!this[s(1401)]["payloadT"+s(783)][s(1089)],type:this[s(1401)][s(1170)+s(783)][s(1642)]?this[s(1401)][s(1170)+"ype"][s(1642)][s(470)](/\s/g,"")[s(1140)+s(924)]():""}:{force:!1,type:this[s(1401)][s(1170)+s(783)]?this[s(1401)].payloadType[s(470)](/\s/g,"")["toLowerC"+s(924)]():""},E=l[s(1170)+s(783)]?l[s(1170)+s(783)].replace(/\s/g,"")["toLowerC"+s(924)]():"",m=y[s(1089)]?y[s(1642)]:E||y[s(1642)],P=f.force?f[s(1129)]:p||f.encoding,L=["text/pla"+s(785)+s(1213),s(1696)+s(1486),e[s(638)],s(1495)],H=[e[s(412)],e[s(968)]];this[s(1401)][s(655)+s(1212)+s(1829)+"ad"]&&L[s(1161)](m)&&(!P||H.includes(P))?l[s(447)+s(468)]=e[s(1310)](xl,l[s(679)],0,l[s(679)][s(1814)+"th"]):l.textPayload=""}else l[s(447)+s(468)]=""}catch(f){l[s(447)+"oad"]="",console[s(1842)](f)}c[s(1101)]=l,e[s(883)](n)}function rg(c,n,s){let l=t,f=e[l(976)](s,8192),p=f>>>1,y=null,E=f;return function(m){let P=l;if(m<1||m>p)return e[P(576)](c,m);e[P(1522)](E+m,f)&&(y=e[P(1779)](c,f),E=0);let L=n.call(y,E,E+=m);return e.kqlUi(7,E)&&(E=e[P(1579)](e[P(1356)](7,E),1)),L}}let ig=4294967295;function sg(c,n,s){let l=t;return e[l(970)](e[l(522)],l(1647))?e[l(709)](RangeError,e[l(846)](e.Czyxl(e[l(1819)](l(856)+l(981)+l(1671)+c,e.XHCeI),e.HSASn(n,1))+e[l(586)],s)):l(624)+"_"+this[l(542)]}function og(c,n,s){let l=t;if(e[l(1685)](s,ig))throw new Error(e[l(1652)]);let f=3;for(;e.mkeWy(f,0);){let p=255&s;wa(p,c,e[l(678)](n,f)),s>>>=8,f--}return e[l(1003)](n,4)}function ag(c,n){let s=t,l=0,f=n,p=e[s(1006)](n,4);for(;e.eQAKn(f,p);){let{value:y,offset:E}=ma(c,f);f=E,l=e[s(1398)](e[s(1330)](l,8),0),l+=y}return{value:l,offset:p}}function cg(c,n,s){let l=t;if(e[l(1340)](e[l(1609)],e[l(1609)]))this[l(1725)+"ileName"]=_0x1382ba;else{let f=(l(675)+"0")[l(1376)]("|"),p=0;for(;;){switch(f[p++]){case"0":return e[l(1160)](e[l(952)](xa,c,n,s),s);case"1":if(!c)return s;continue;case"2":if(e[l(1800)](c[l(1202)],40))return e.vFvEk(xa(c,n,s),s);continue;case"3":if(n[l(1438)+"e"])return n[l(1438)+"e"](c,s)+s;continue;case"4":if(n[l(1718)])return e[l(858)](n[l(1718)](c,s),s);continue}break}}}function dg(c,n){let s=t,l=new ue(e[s(1125)](e[s(1743)](c[e.azIMh(n,4)]<<24,e[s(886)](c[e[s(1676)](n,5)],16))|e.YWsHG(c[n+6],8),c[e.iVKAm(n,7)]),e[s(832)](e[s(1557)](e.cSQTB(e[s(1264)](c[n+0],24),c[e.XcGoT(n,1)]<<16),e[s(616)](c[e.BnVIp(n,2)],8)),c[n+3]),!0);return n+=8,{value:l,offset:e.OygSd(n,8)}}function lg(c,n,s){let l=t,f=c[l(525)],p=c[l(540)];return n[s]=e[l(458)](p,24),n[s+1]=e[l(1476)](e[l(975)](p,16),255),n[s+2]=e[l(1476)](e[l(975)](p,8),255),n[s+3]=e[l(1560)](255,p),n[e.wxipO(s,4)]=f>>>24,n[s+5]=f>>>16&255,n[e[l(1404)](s,6)]=e[l(1863)](e.EVhHC(f,8),255),n[e[l(1717)](s,7)]=e.LJhwh(255,f),s+=8,s}function ma(c,n){let s=t;return c[s(1795)+"8"]?{value:c[s(1795)+"8"](n),offset:e[s(611)](n,1)}:{value:e[s(684)](255,c[n]),offset:e[s(1146)](n,1)}}function wa(c,n,s){let l=t,f={CZEWs:function(p,y){return e.CnoSN(p,y)}};return e.yDTjE(e.LWXky,e[l(415)])?sfZHYJ[l(649)](_0x44a9b9,_0x4374eb):(n[l(748)+"t8"]?n[l(748)+"t8"](c,s):n[s]=255&c,s+1)}let ug=function(c){return new Uint8Array(c)},fg=e[t(394)]!=typeof Buffer?Buffer[t(1256)+t(820)]:e.QEeoY(rg,ug,Uint8Array[t(1116)+"e"][t(1547)]),hg=16,_a=32;function xg(c){let n=t,s=0,l={};for(let f=0;e[n(746)](f,c[n(1202)]);f++)l[c[f][n(1632)+"ame"]]=hl(c[f]["cursor_n"+n(1112)]),s+=e.YSFaG(14,l[c[f][n(1632)+n(1112)]]);return[s,l]}function wl(c,n,s){let l=t,f={lfysi:function(p,y){return p+y},WIizC:function(p,y){return p(y)},TGoOM:function(p,y,E){return p(y,E)},VKnns:e.XeCmB,tBEHq:function(p,y,E,m){return e[U(922)](p,y,E,m)},Vbuwt:function(p,y,E,m){return e[U(466)](p,y,E,m)},kzOag:e[l(501)],pHEtR:function(p,y,E,m){return p(y,E,m)},INbUK:e[l(532)],DqugP:e[l(1433)]};if(e[l(1387)](e[l(1043)],e[l(1043)]))return sDfFhT[l(508)](sDfFhT.WIizC(_0x3dbdf0,4)[l(809)]("0"),sDfFhT[l(1807)](_0x1c3b4d,_0x15d2f8,2)[l(602)](16))[l(541)](-4);{let[p,y]=e.mmyMl(xg,c),E=e[l(399)](fg,p),m=0;return c[l(838)](P=>{let L=l,H=f[L(596)][L(1376)]("|"),J=0;for(;;){switch(H[J++]){case"0":m=f[L(750)](og,E,m,P[L(1302)]||0);continue;case"1":m=f[L(1478)](wa,y[P["cursor_n"+L(1112)]],E,m);continue;case"2":console.log(f[L(879)],P,P[L(1302)]);continue;case"3":console[L(1842)](L(1648),m);continue;case"4":m=f[L(1221)](wa,0,E,m);continue;case"5":m=lg(ue[L(391)+"er"](P[L(702)]||n),E,m);continue;case"6":console.log(L(682),m);continue;case"7":console[L(1842)](f[L(1582)],m);continue;case"8":m=f[L(1478)](cg,P[L(1632)+"ame"],E,m);continue;case"9":console[L(1842)](f.DqugP,m);continue;case"10":console[L(1842)](L(1570),m);continue}break}}),{frameType:_a,headers:[{key:l(899)+l(782),value:s}],payload:E}}}function pg(c){let n=t,s=0,l=[];for(;s<c[n(1814)+"th"];){let{offset:f}=ma(c,s);s=f;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:E}=ag(c,s);p[n(1302)]=y,s=E;let{value:m,offset:P}=e[n(1284)](ma,c,s);s=P,p["cursor_n"+n(1112)]=e[n(1694)](xl,c,s,e[n(1437)](s,m)),s+=m;let{value:L,offset:H}=e.btBOd(dg,c,s);p.cursor=L.toNumber(),s=H,l.push(p)}return l}function gg(){let c=t;return e[c(852)]!==e[c(1785)]?{frameType:_a,headers:[{key:e[c(1083)],value:e[c(1299)]}],payload:void 0}:this[c(865)]?.[c(461)](_0x4cf927)}class mg{constructor(n,s,l){let f=t;this[f(627)+"ameSpace"]=n,this[f(1725)+f(392)]=s,this[f(1640)+"Strategy"]=l,this._qosDB=gl(this[f(627)+"ameSpace"],e[f(738)])}async openDB(){let n=t;if(e[n(971)](e[n(1477)],n(1728)))await this[n(865)][n(661)]();else return this[n(1359)][n(1603)+"ns"]}async getCursors(){let n=t;if(!this[n(865)][n(1422)])return;let s=this["_message"+n(1268)],l=await this[n(865)][n(1587)]();switch(console[n(1842)](e.yXhxm,l),s){case e[n(1261)]:return l&&l[n(1202)]?wl(l,0,this._cursorFileName):void 0;case e[n(844)]:return;case"CONTINUE":return l&&l.length?wl(l,0,this[n(1725)+"ileName"]):e[n(1147)](gg)}}async[t(1241)](n,s,l){let f=t,p={xiMUy:function(y,E){return e.WpzCp(y,E)},aKARV:function(y,E){return e[U(434)](y,E)}};if(e[f(1056)]===e[f(453)]){if(SHEyWh.xiMUy(void 0,_0x2f48a4))this[f(1760)+"rs"]={};else if(SHEyWh[f(607)](void 0,_0x471b6f))this._listeners[_0x3500a9]=null;else{let y=this[f(1760)+"rs"][_0x193962];if(y)for(let E=0;E<y[f(1202)];)SHEyWh.aKARV(y[E].fn,_0x37e533)?y.splice(E,1):++E}return this}else return console[f(1842)](e[f(1645)],n,s,l),this[f(865)][f(1241)]({cursor_name:n,cursor:s,service:l})}async[t(1625)+"rs"](n){let s=t,l=e.lwyVg(pg,n);for(let f of l)console[s(1842)](e[s(1614)],l),await this._qosDB[s(1241)](f)}async[t(461)](n){let s=t;return(await this[s(865)][s(461)](n))?.[s(702)]}async[t(716)](){await this[t(865)].closeDB()}[t(1228)+t(984)+t(1599)](n){let s=t,l={qfShu:function(f,p){return e[U(671)](f,p)}};e[s(479)](e[s(455)],e.gCJdj)?(this[s(1490)+"orOnline"]()&&(!this._ws||l[s(626)](this[s(449)][s(1590)+"te"],this[s(985)])||l[s(626)](this[s(449)].readyState,this[s(1526)+"NG"]))&&this[s(1178)+s(839)](),this._isBrowser&&_0x59bd3b[s(956)+"Listener"](s(890),this[s(1178)+"nLine"]),this[s(1294)+"er"]&&_0x4c35ac[s(956)+"Listener"](s(885),this._handleOffLine)):this[s(1725)+s(392)]=n}get[t(1422)](){let n=t;return this._qosDB[n(1422)]}}let wg=e[t(1444)];async function _l(c){let n=t,s={HASrP:function(l,f){return l(f)},rKTgW:e.jhAYF,oRMyM:e.ZqJPa,slUKJ:function(l,f){return e[U(1174)](l,f)},qSMPG:n(1781),NEoBQ:function(l,f,p,y){return e[n(1529)](l,f,p,y)}};if(e.TEIij(e[n(612)],n(1525))){let l=_0x1df987[n(1859)+n(1777)]("script");_0x5de871[n(624)+n(1080)]=f=>{let p=n;_0x3996f8[p(1204)][p(1765)+"ild"](l),_0x27f1e4[p(624)+p(1080)]=void 0,xTMMuL[p(1179)](_0x35efde,f&&f.msg||xTMMuL[p(1563)])},l.type=xTMMuL.oRMyM,l.src=xTMMuL[n(1836)](_0x56cba6[n(470)](/^ws/,xTMMuL[n(564)]),n(1532)+n(1322)+n(1386)+"P");try{_0x41f57c[n(1204)][n(1108)+n(1548)](l)}catch{_0x49a304[n(1204)][n(1765)+n(1548)](l)}}else{if(!this[n(1401)].enableQoS)return null;let{aID:l,fpID:f,messageStrategy:p}=this[n(1401)],y=e[n(1371)](c,wg);try{if(e.airDY(e[n(1042)],e[n(1380)]))return this[n(554)+n(530)]?c&&this["_cursorM"+n(530)][n(1228)+n(984)+"Name"](c):this[n(554)+n(530)]=new mg(f+"_"+l+"_"+y,y,p),this[n(554)+n(530)][n(1422)]||await this["_cursorM"+n(530)][n(661)](),this[n(554)+n(530)];throw _0x24510b=_0xddd8d7[n(1202)],xTMMuL.NEoBQ(_0x38e1b8,_0xf13cc3,10,_0x2ba5e6[n(1202)])}catch{if(e.tYnGL(e[n(1713)],e[n(696)]))_0x4c7d99(_0x1785a1,96),_0x376b6a(_0x55add6,_0x3f9162(_0xbdcc29));else return null}}}async function _g(c,n){let s=t,l=on(c[s(1101)][s(915)],e.qqRDb,"-1"),f=on(c[s(1101)][s(915)],e.NXtcT,"1"),p=e[s(958)](ir,c[s(1101)][s(915)],e[s(1098)]),y=e[s(1070)](Number,ir(c.message[s(915)],e[s(726)]))||0,E=ga.call(this,c),m=e[s(1529)](on,c[s(1101)][s(915)],e[s(1025)],"2"),P=e[s(615)](ir,c[s(1101)][s(915)],e[s(1607)]),L=Number(ir(c[s(1101)][s(915)],s(1622)+"rsor_value"));if(E.isQoSAck)return n();let H=E[s(1762)+s(972)]?await ml[s(1655)](this):null;if(e[s(1522)](c[s(1101)][s(1302)],0)&&f&&!l||e.ruiJV(c[s(1101)][s(1302)],0)){if(p&&E[s(1762)+"sage"]&&H)return!!!await H.get(p)&&(this[s(409)+s(758)+s(1601)](c),await H[s(1241)](p,e[s(433)](Date[s(1405)](),y))),e.FoRNh(n);if(m){let J=await _l[s(1655)](this);if(!J)return this[s(409)+s(758)+s(1601)](c),e[s(876)](n);let V=await J[s(461)](P)??-1;if(e.TFIJo(V,L))this[s(409)+s(758)+s(1601)](c),J.set(P,L,c.message.service);else throw new Error(s(531)+" message cursor "+L+(s(959)+s(543)+s(1666)+"r ")+V);return e[s(1378)](n)}return this[s(409)+s(758)+s(1601)](c),e[s(1528)](n)}}async function yg(c,n){let s=t,l=ga[s(1655)](this,c);if(!l[s(1762)+"sage"])return e.FcGek(n);let f=await ml[s(1655)](this);if(l[s(1369)+s(1230)+s(1659)]&&l.ackMsgIds[s(1202)])for(let p of l[s(929)+"s"])await f[s(1028)](p);n()}async function Eg(c,n){let s=t,l=e[s(1368)](c[s(1101)][s(1049)+"e"],hg),f=e[s(1012)](c[s(1101)][s(1049)+"e"],_a);if(e[s(1572)](!l,!f))return n();let p=e[s(978)](ir,c[s(1101)][s(915)],e.HlUlT);if(!p)return e[s(1446)](n);let y=await _l.call(this,p);if(!y)return e.FcGek(n);if(l){let E=await y[s(1508)+"rs"](),m={frameType:E?.[s(1049)+"e"],SeqID:ue[s(391)+"er"](this[s(495)]++),LogID:ue[s(391)+"er"](this[s(1401)][s(1194)+s(432)]()),service:9e3,method:5,headers:E?.[s(915)],payload:E?.[s(679)]},P=S(m);this[s(449)]&&this[s(449)][s(1590)+"te"]&&this[s(449)].send(P)}if(f)if(e[s(1756)](e[s(812)],e[s(812)])){let E=c[s(1101)][s(679)];E&&y[s(1625)+"rs"](E)}else _0x430da1[_0xbd761c++]=e[s(1005)](_0x169872,12)|224,_0x39f430[_0x13132b++]=e[s(1260)](e[s(912)](_0x4d5b27,6)&63,128),_0x3ddb3d[_0x20f445++]=e[s(1218)](e[s(1789)](63,_0x2059af),128)}let bg=async function(c,n){let s=t;this._isInit=!1,clearTimeout(this["_connect"+s(1635)+s(509)]),e[s(876)](n)},vg=async function(c,n){let s=t;if(!this[s(449)]||this[s(449)][s(1590)+"te"]!==this.OPEN)return e[s(1303)](n);let{pingInterval:l}=this[s(1401)];this["_endpoin"+s(506)]?.[s(1701)+s(819)+s(741)]();for(let p=0;e[s(673)](p,this[s(1640)+s(1278)][s(1202)]);p++){let y=this[s(1640)+s(1278)][p];if(this._ws[s(1590)+"te"]===this[s(985)]&&y!==null)this[s(449)]&&this[s(449)][s(793)](y),this["_message"+s(1278)][p]=null;else break}this["_message"+s(1278)]=this["_message"+s(1278)][s(1482)](p=>!!p),this[s(815)+s(574)+"Id"]=e[s(1591)](setTimeout,()=>this[s(1037)](),l),this["_dispatc"+s(524)+"nt"](c),this[s(1294)+"er"]&&this[s(449)]&&(this[s(449)][s(1168)+"pe"]=this[s(1509)+s(783)]);let f=this[s(1484)+"tManager"]?.[s(1491)+s(1681)+"nt"]();this[s(1519)]("open "+f+" success"),e[s(443)](n)},Sg=async function(c,n){let s=t,l={FhWwR:function(f,p){return e[U(1356)](f,p)},zeMvV:function(f,p){return e[U(536)](f,p)},Qvosi:function(f,p){return e[U(1707)](f,p)},ZsuIp:function(f,p){return e[U(1689)](f,p)}};if(e[s(608)](e[s(1226)],e[s(730)])){let f=this[s(1484)+s(506)]?.[s(1491)+s(1681)+"nt"]();this[s(1519)](s(459)+f),n()}else return new _0x182ea7(HnvYVi[s(722)](HnvYVi[s(722)](HnvYVi[s(722)](_0x48ac31[0],_0xc4eac6[1]<<8),HnvYVi[s(1843)](_0x379803[2],16)),HnvYVi.zeMvV(_0x54865f[3],24)),HnvYVi[s(469)](HnvYVi[s(998)](_0x11340b[4]|HnvYVi[s(1843)](_0x33b44d[5],8),HnvYVi[s(1843)](_0x47eed4[6],16)),_0x245656[7]<<24),_0x56f003)};class Ig extends ha{constructor(n){let s=t,l={GyFqi:function(E,m,P,L){return E(m,P,L)},GarzI:function(E,m,P){return e.yxyqS(E,m,P)},dvKUp:function(E,m,P){return E(m,P)},JLiFg:e[s(452)],hCuZm:function(E,m){return E===m},HMOAb:function(E,m){return e.XpqTb(E,m)},oTmqz:s(487)+s(1334)+"e",dXCSo:function(E,m){return E>=m},IWbli:function(E,m){return e[s(1611)](E,m)},wTKIs:function(E,m){return E+m},IIzBG:function(E,m){return E+m}};super(),this[s(940)+"igatorOnline"]=!0,this[s(1294)+"er"]=rr,this[s(1325)]=qp,this._isMiniTT=Pn,this[s(1633)+"X"]=Xr,this._isWorker=Qr,this[s(1640)+s(1278)]=[],this[s(1484)+s(506)]=null,this[s(413)+s(1074)]=!1,this[s(1509)+s(783)]="arraybuf"+s(1118),this[s(1870)+"Lock"]=!1,this[s(1870)+s(1635)+"utId"]=null,this[s(962)+s(745)+s(1558)]=null,this["_pingPon"+s(574)+"Id"]=null,this[s(495)]=0,this._isInit=!1,this[s(1691)]="",this[s(1573)+"ger"]=null,this[s(554)+s(530)]=null,this[s(1458)+"sCounter"]=null,this[s(754)+"ls"]=s(1347),this[s(791)]=3,this[s(1526)+"NG"]=0,this[s(985)]=1,this.CLOSING=2,this._onOpen=E=>{let m=s;try{l[m(1039)](fl,this,E,[bg,vg,Sg])}catch(P){let L=l[m(1290)](ct,m(1225),{message:P[m(1101)],code:sn.OPEN_ERROR,error:P});this["_dispatchErrorEv"+m(1135)](L)}},this[s(1520)+"ge"]=async E=>{let m=s,{pingInterval:P,pingFrequency:L}=this._options;if((e[m(1145)]("hi",E[m(628)])&&e[m(1628)](e[m(1521)],L)||e[m(925)](e[m(817)],L))&&(this[m(1877)+m(1313)](),this[m(450)](e[m(1362)],e[m(642)]),this["_pingPon"+m(574)+"Id"]=e[m(1559)](setTimeout,this[m(1037)].bind(this),P)),!e[m(925)]("hi",E[m(628)]))try{e[m(1529)](fl,this,E,[ng,eg,yg,Eg,_g,tg])}catch(H){let J=e[m(1095)](ct,e[m(452)],{message:H[m(1101)],code:sn[m(674)+"ERROR"],error:H});this[m(409)+"hErrorEvent"](J)}},this[s(784)]=E=>{let m=s,P=this[m(1484)+m(506)]?.["checkRea"+m(1186)+"es"](),L=this[m(1484)+m(506)]?.[m(1491)+"ntEndpoint"]();if(P&&!E[m(1101)]){let H="connect "+L+(m(573)+"ax retri"+m(521)+"ed");this[m(409)+m(1651)+m(1135)](l[m(1660)](ct,l[m(1191)],{message:H,code:sn[m(1627)+m(1382)+"R"],error:E}));return}this[m(449)]&&l[m(742)](this._ws[m(1590)+"te"],this.OPEN)&&this[m(1128)+"ect"](),this[m(409)+m(1651)+"ent"](l[m(1660)](ct,l[m(1191)],{message:E.message,code:sn[m(1045)+m(1279)],error:E}))},this._onClose=async E=>{let m=s;this[m(851)+m(1127)](),this._clearPingTimer(),this._removeWsListeners(),this[m(449)]=null,this[m(1870)+"Lock"]=!1;let P=this["_endpoin"+m(506)]?.["checkRea"+m(1186)+"es"]();if(!P&&this[m(1490)+m(1363)]()&&!this[m(413)+m(1074)]){let L=this[m(1484)+m(506)]?.[m(1491)+m(1681)+"nt"](),H=this._options[m(1566)+m(944)+m(1196)](E[m(1793)],E.reason);this["_dispatc"+m(1205)+"ent"](e[m(1284)](pt,e[m(384)],{code:1006,reason:E[m(1448)]||m(1638)+"ng faile"+m(421)+"wn reason, hostn"+m(1555)+L,willReconnect:H})),H&&this._connect();return}if(E[m(1793)]!==1e3&&this[m(413)+m(1074)]){this[m(409)+m(1205)+m(1135)](e[m(1454)](pt,m(1281),{code:1e3,reason:"bye"})),this[m(1484)+m(506)]?.[m(1701)+m(819)+m(741)](),this[m(1458)+m(1596)]?.["resetCou"+m(720)]();return}if(e.hxWTD(1e3,E.code)&&P)if(e[m(640)](e[m(1062)],"BMlXG")){if(fcRuJK.HMOAb(_0x28095b,_0x3bfc0f))throw new _0x47bb69(fcRuJK.oTmqz);let L=3;for(;fcRuJK[m(1210)](L,0);){let H=fcRuJK[m(1355)](255,_0xe82298);fcRuJK[m(1039)](_0x1078aa,H,_0x490ee2,fcRuJK[m(1833)](_0x393de5,L)),_0x2b9209>>>=8,L--}return fcRuJK.IIzBG(_0x6a5e7d,4)}else{let L=this[m(1484)+m(506)]?.[m(1491)+m(1681)+"nt"](),H=E[m(1448)];H||(H=await e.mmyMl(Vp,this._url)),H=m(1638)+"ng failed, "+H+(", hostna"+m(485))+L+(m(699)+m(1723)+m(1072)),this["_dispatchCloseEv"+m(1135)](e[m(935)](pt,m(1281),{code:E[m(1793)],reason:H}));let J=m(966)+L+(m(573)+"ax retri"+m(521)+"ed");this[m(409)+"hErrorEvent"](ct("error",{message:J,code:sn[m(1627)+"IES_ERROR"]})),this[m(1484)+m(506)]?.[m(1701)+m(819)+m(741)](),this[m(1458)+m(1596)]?.[m(594)+m(720)]();return}if(e[m(580)](1e3,E.code)&&!E[m(1448)]){let L=this[m(1484)+"tManager"]?.[m(1491)+m(1681)+"nt"]();this[m(409)+m(1205)+m(1135)](e[m(1390)](pt,m(1281),{code:E[m(1793)],reason:"connecting faile"+m(421)+m(1539)+m(1613)+m(1555)+L})),this[m(1484)+"tManager"]?.[m(1701)+m(819)+m(741)](),this[m(1458)+m(1596)]?.[m(594)+m(720)]();return}this[m(409)+m(1205)+m(1135)](E),this[m(1484)+m(506)]?.[m(1701)+"pointCon"+m(741)](),this[m(1458)+m(1596)]?.[m(594)+m(720)]()},this[s(814)]=null,this[s(697)]=null,this[s(1608)+"e"]=null,this[s(437)]=null,this["onStartR"+s(810)]=null,this[s(585)+s(1274)]=null,this[s(1061)+s(1704)+s(1639)+"ct"]=null,this[s(1178)+s(839)]=this[s(1178)+s(839)][s(1121)](this),this["_handleO"+s(826)]=this[s(1178)+"ffLine"][s(1121)](this),this[s(577)+s(1407)]=this[s(577)+s(1407)][s(1121)](this),this["_handleP"+s(1773)]=this[s(577)+s(1773)][s(1121)](this),this[s(1401)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(445)](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(817)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1683)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:p}=n,y=Array[s(1546)](f)?f:e.UarEX(e[s(451)],typeof f)?[f]:[];if(!y||e[s(1145)](0,y[s(1202)]))throw new Error(e[s(1569)]);if(!jp(p))throw new Error(e[s(1564)]);Object[s(1498)](this[s(1401)],n),this[s(1484)+s(506)]=new ul(y,this[s(1401)][s(707)+"es"]),this[s(1458)+s(1596)]=new $p(this[s(1401)]["pingLoss"+s(1554)]),this[s(1401)][s(951)+s(1621)]&&(this[s(403)]=!0,this._connect()),this[s(1401)][s(636)+s(1576)+s(1301)]&&(this[s(756)+"T"]||this[s(1633)+"X"]?this[s(1239)+s(1201)+s(1258)]():this._isBrowser&&this[s(1224)+s(1185)+"Listener"]())}[t(1178)+"nLine"](){let n=t;this[n(1401)][n(1015)+n(1667)+n(548)]||this[n(413)+"osed"]||this[n(651)+n(810)]()}["_handleO"+t(826)](){let n=t;if(e[n(1774)](e[n(1341)],e[n(1341)])){this[n(1610)+n(1067)+"t"]();let s=e.VRCEW(fa,n(1566)+"t",{message:e[n(906)]});this[n(1061)+n(1704)+n(1639)+"ct"]&&this[n(1061)+"mediatel"+n(1639)+"ct"](s)}else this["_message"+n(1278)][n(1051)](),this[n(1640)+n(1278)][n(698)](_0x4305c5)}[t(1224)+t(1185)+t(877)](){let n=t;this[n(1294)+"er"]&&window.addEventListener(e[n(1162)],this[n(1178)+n(839)]),this._isBrowser&&window[n(956)+n(877)](e[n(1063)],this[n(1178)+n(826)]),this[n(1294)+"er"]&&window["addEvent"+n(877)](e[n(992)],this["_handleP"+n(1407)]),this[n(1294)+"er"]&&window["addEvent"+n(877)](e[n(1538)],this["_handleP"+n(1773)])}[t(692)+t(1185)+t(877)](){let n=t,s={jpUpV:function(l,f){return e[U(491)](l,f)},PSoTU:function(l,f){return e.yxoXL(l,f)},oeJsO:function(l,f){return e[U(654)](l,f)}};e[n(1874)](e[n(1046)],e[n(1046)])?(this[n(1294)+"er"]&&window[n(617)+n(439)+n(1366)](e[n(1162)],this[n(1178)+n(839)]),this[n(1294)+"er"]&&window[n(617)+n(439)+n(1366)](e[n(1063)],this[n(1178)+n(826)]),this._isBrowser&&window[n(617)+n(439)+n(1366)](e[n(992)],this[n(577)+n(1407)]),this[n(1294)+"er"]&&window[n(617)+n(439)+"ner"](e[n(1538)],this["_handleP"+n(1773)])):(_0x2d1077=mwlkms[n(788)](_0x4c448a,_0x50fbc6),_0x4d8f6e|=mwlkms[n(534)](mwlkms[n(1e3)](127,_0x3c5eeb),7))}[t(577)+"ageHide"](n){let s=t;e.UzVSg===e[s(1412)]?this[s(450)](e[s(384)],e[s(1806)](_0x32da43,e.vpqxo,{..._0xe50391})):(!n.persisted&&(this[s(1294)+"er"]&&window[s(617)+"entListe"+s(1366)](s(1189),this[s(577)+"ageHide"]),this[s(1294)+"er"]&&window[s(617)+s(439)+s(1366)](e[s(1538)],this[s(577)+s(1773)]),this[s(1281)]()),this._isBrowser&&window["removeEv"+s(439)+s(1366)](e[s(1162)],this[s(1178)+s(839)]),this[s(1294)+"er"]&&window["removeEv"+s(439)+s(1366)](e[s(1063)],this[s(1178)+s(826)]))}["_handleP"+t(1773)](n){let s=t;if(n.persisted)if(e[s(580)](e.ccdpU,e[s(1575)])){if(_0x4077a6 instanceof _0x3008d3)return VKRoXL[s(1394)](_0x2ce6a7,_0x278864);if(_0x4001af.has(_0xd2a919))return _0x599d68.get(_0x43a329);let l=VKRoXL[s(897)](_0x488581,_0x29f49e);return l!==_0x281dab&&(_0x178ecc[s(1241)](_0x3e468c,l),_0x5cd24a[s(1241)](l,_0xdb3acc)),l}else this[s(1490)+s(1363)]()&&(!this[s(449)]||e.xOUCy(this[s(449)][s(1590)+"te"],this[s(985)])||e[s(671)](this[s(449)][s(1590)+"te"],this[s(1526)+"NG"]))&&this[s(1178)+s(839)](),this[s(1294)+"er"]&&window.addEventListener(e.YryOT,this[s(1178)+s(839)]),this[s(1294)+"er"]&&window[s(956)+s(877)](s(885),this["_handleO"+s(826)])}async["_generat"+t(1365)](n){let s=t,{fpID:l,deviceID:f,bddID:p,ttwID:y,accessKey:E,aID:m,customParams:P={},enableAutoAck:L,enableQoS:H,QoSLevel:J,env:V}=this[s(1401)],Be,gt,qt;this[s(1294)+"er"]||this._isMiniWX||this[s(756)+"T"]?(Be=location&&e[s(1048)](e.BxdxK,location[s(1209)])?s(744):e[s(544)],gt=n.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),qt=/^wss(.*:\/\/)/[s(1722)](n)?n:""+Be+gt):(Be=e.xNicv,gt=n[s(470)](/(^http)((?:[s]*:\/\/))/,""),qt=/(^ws)((?:[s]*:\/\/))/[s(1722)](gt)?gt:""+Be+gt);let mt=p?"bd_did":y?e[s(1512)]:e[s(390)],ya=p||y||f;if(e[s(1735)](!ya,!mt))throw new Error(e[s(1761)]);let Ag=e[s(1048)](e.tUYYQ,typeof P)?await P():P,Tg=V?e[s(609)](Kp,V[s(1481)],V[s(800)]):{},Ea=Object[s(1498)]({device_platform:e[s(1677)],version_code:s(1674)+"0",access_key:E,fpid:l,aid:m,[mt]:ya,xsack:L?1:0,xaack:L?1:0,xsqos:H?1:0,qos_level:H?J:void 0,qos_sdk_version:2,...Tg},Ag),kg=Object[s(480)](Ea)[s(1150)]((ba,va)=>Ea[va]!==void 0?""+ba+(ba?"&":"?")+va+"="+Ea[va]:ba,"");return qt+s(653)+kg}async[t(1870)](){let n=t,s={tCrqj:function(l,f){return e[U(1497)](l,f)},WcMXP:function(l,f){return e[U(400)](l,f)},aqJtB:function(l,f){return l<<f},jVgYA:function(l,f){return e.KMzlA(l,f)},qDoiM:function(l,f){return e[U(1442)](l,f)},JiIfQ:function(l,f){return l<<f}};if(!(this["_connect"+n(1255)]||this["_readyCl"+n(1074)])){this[n(1870)+n(1255)]=!0;try{let l=this[n(1484)+n(506)]?.[n(493)+n(1055)+n(728)+n(1014)+n(904)](),{timeoutInterval:f}=this._options;if(l){if(e.IomIp(e[n(1626)],e.oSorR))return new _0x3b07e6(wbMIAC.tCrqj(wbMIAC[n(1757)](wbMIAC[n(1571)](_0x5c0d25[4],24),wbMIAC[n(1571)](_0x5bb605[5],16))|wbMIAC[n(1702)](_0x19ca32[6],8),_0x2f9391[7]),wbMIAC.tCrqj(wbMIAC[n(759)](wbMIAC.qDoiM(wbMIAC[n(1571)](_0x32d5a1[0],24),wbMIAC[n(700)](_0x5d85c0[1],16)),wbMIAC[n(700)](_0x328ddf[2],8)),_0x3f9736[3]),_0x236bb3);{let y=this[n(1484)+"tManager"]?.[n(1491)+"ntEndpoint"](),E=this[n(1484)+"tManager"]?.[n(1763)+"ackupEnd"+n(767)+n(854)+n(1054)](),m=this[n(1484)+n(506)]?.[n(1491)+n(1681)+n(732)+n(618)]();if(E){let P=n(966)+y+(n(663)+n(699)+n(1723)+n(1768)+"ill use "+n(955)+"ndpoint ")+E+(n(1229)+"y"),L=e.nMAaa(ct,e.fEzmH,{message:P,code:sn[n(1627)+n(1382)+"R"]});this[n(1519)](P),this[n(409)+n(1651)+"ent"](L),this._url=await this[n(1646)+n(1365)](E),this._debug(n(966)+E+" "+m+n(1410)),this[n(1373)+n(1306)+"rs"]()}else{let P=n(966)+y+(n(663)+n(699)+n(1723)+"ached");this[n(1519)](P),this[n(409)+n(1651)+n(1135)](ct(e[n(452)],{message:P,code:sn[n(1627)+"IES_ERROR"]}));return}}}else{let y=this._endpointManager?.[n(1491)+n(1681)+"ntAndUpdateCount"](),E=this[n(1484)+n(506)]?.[n(1491)+"ntEndpoi"+n(732)+"ount"]();this[n(1691)]=await this[n(1646)+"eUrl"](e[n(976)](y,"")),this[n(1519)](n(966)+y+" "+E+" times"),this._removeWsListeners()}if(this[n(403)])this._isInit=!1;else{let y=e[n(1429)](fa,e.wWNfz,{message:e[n(950)]});this[n(1776)+n(810)]&&this[n(1776)+"econnect"](y)}let p=this[n(1484)+"tManager"]?.[n(1491)+n(1681)+n(732)+n(618)]()||0;e[n(723)](p,1)&&await this._wait(e.CfRnQ(p,1)),this[n(1519)](n(1638)+n(1455)+this[n(1691)]+(" protoco"+n(1375))+this._protocols),this[n(449)]=e.MDeYH(Hp,{url:this[n(1691)],protocols:[this[n(754)+"ls"]],headers:this[n(1401)]["miniProg"+n(587)+"s"]["customHt"+n(568)]},this._options.ws),(this._isBrowser||this[n(1764)+"r"])&&this[n(449)]&&(this._ws[n(1168)+"pe"]=this[n(1509)+n(783)]),this["_addWsLi"+n(601)](),this[n(1870)+n(1635)+n(509)]=setTimeout(this[n(1510)+"ut"][n(1121)](this),f)}catch(l){throw this._connectLock=!1,l}}}[t(851)+"mer"](){let n=t;clearTimeout(this[n(1870)+"ionTimeo"+n(509)]),this[n(1870)+n(1635)+"utId"]=null}[t(1877)+t(1313)](){let n=t;e[n(709)](clearTimeout,this[n(815)+"gTimeoutId"]),e[n(1090)](clearTimeout,this[n(962)+n(745)+n(1558)]),this["_pingPon"+n(574)+"Id"]=null,this[n(962)+"ctTimeou"+n(1558)]=null}[t(1519)](...n){let s=t;this[s(1401)][s(1456)]&&console.log[s(825)](console,[e[s(1523)],...n])}[t(1697)+"rvalValue"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:p}=this._options,y=e[s(1772)](l,Math[s(1848)](p,e[s(786)](n,1)));return e[s(914)](y,f)?f:y}[t(1037)](){let n=t;if(this[n(449)]&&this._ws[n(1590)+"te"]===this[n(1526)+"NG"]){this[n(1877)+n(1313)](),this[n(815)+n(574)+"Id"]=e.IPRxe(setTimeout,this[n(1037)][n(1121)](this),this[n(1401)][n(1026)+n(516)]);return}if(!this[n(449)]||e[n(1153)](this[n(449)].readyState,this[n(985)]))return void this[n(651)+n(810)]();this[n(449)]&&this[n(449)][n(793)]("hi"),this[n(962)+n(745)+n(1558)]=e[n(831)](setTimeout,this[n(651)+n(810)+"Timeout"][n(1121)](this),this._options[n(386)+n(404)+n(1031)])}["_handleR"+t(810)+t(1190)](){let n=t;this[n(1458)+n(1596)]?.addCount(),this[n(450)](n(979)+"e_timeout",e.xMpOV),this[n(1458)+n(1596)]?.["checkRea"+n(823)+"nt"]()?this[n(651)+n(810)]():this._ping()}[t(1490)+t(1363)](){let n=t;return this[n(756)+"T"]||this[n(1633)+"X"]?this[n(940)+n(388)+n(942)]:(this[n(1294)+"er"]||this._isWorker)&&this._options["listenNe"+n(1576)+n(1301)]?navigator[n(1195)]:!0}[t(651)+"econnect"](){let n=t;!this[n(1490)+"orOnline"]()||this[n(413)+"osed"]||(this[n(1484)+n(506)]?.[n(1701)+n(819)+n(741)](),this["_pingLos"+n(1596)]?.[n(594)+"nter"](),this[n(449)]?this[n(1128)+n(1107)](1001,n(598)+n(1732)+n(1566)+n(1285)+n(986),!0):this[n(1870)]())}[t(1239)+t(1201)+t(1258)](){let n=t,s={PxdNl:function(l,f){return l===f},GvMBr:e[n(1138)]};this._isMiniTT?tt["onNetwor"+n(1354)+n(1465)](({isConnected:l})=>{let f=n;if(s[f(818)](s[f(518)],s.GvMBr))this[f(940)+"igatorOnline"]=l,l?this[f(1178)+f(839)]():this[f(1178)+f(826)]();else{let p=new _0x50fc13(2*_0x8ec604);p[f(1241)](_0x43ee65),_0x17748f.bytes=p}}):this[n(1633)+"X"]&&wx[n(874)+n(1354)+n(1465)](({isConnected:l})=>{let f=n;this[f(940)+f(388)+"line"]=l,l?this[f(1178)+f(839)]():this[f(1178)+f(826)]()})}_wait(n){let s={tvBuM:function(l,f,p){return e[U(772)](l,f,p)}};return new Promise(l=>{let f=U;s[f(1472)](setTimeout,l,this[f(1697)+f(1298)+"e"](n))})}[t(1128)+t(1107)](n=1e3,s="",l=!1){let f=t;this._ws&&this[f(1610)+f(1067)+"t"](n,s,l)}[t(1510)+"ut"](){let n=t,s=this[n(1484)+n(506)]?.["getCurre"+n(1681)+"nt"]();this[n(1519)]("connect "+s+" timeout"),this[n(1128)+n(1107)](1001,e[n(1511)],!0)}[t(778)](n){let s=t,l=Ut(n);this._ws&&e[s(479)](this[s(449)][s(1590)+"te"],this[s(985)])&&(this._ws&&this[s(449)][s(793)](l),this[s(1519)](e.QdfcX,n))}[t(1373)+t(1306)+"rs"](){let n=t;this[n(449)]&&(this._ws[n(617)+n(439)+n(1366)](e.rGShE,this[n(916)]),this._ws[n(617)+n(439)+n(1366)](e.vpqxo,this[n(1649)]),this[n(449)][n(617)+"entListener"](e[n(1013)],this[n(1520)+"ge"]),this[n(449)][n(617)+n(439)+n(1366)](e[n(452)],this[n(784)]))}[t(484)+t(601)](){let n=t,s=e.SwRNw.split("|"),l=0;for(;;){switch(s[l++]){case"0":this._ws[n(956)+n(877)](e.fEzmH,this[n(784)]);continue;case"1":this[n(449)][n(956)+n(877)](e[n(1013)],this[n(1520)+"ge"]);continue;case"2":if(!this[n(449)])return;continue;case"3":this[n(449)][n(956)+n(877)](e[n(384)],this[n(1649)]);continue;case"4":this[n(449)][n(956)+n(877)](e[n(861)],this[n(916)]);continue}break}}[t(1533)+"nceClose"](n=1e3,s=""){let l=t;try{this[l(449)]&&this[l(449)].close(n,s)}catch{}}[t(1610)+t(1067)+"t"](n=1e3,s="",l=!1){let f=t;if(this[f(1877)+f(1313)](),this[f(851)+f(1127)](),this["_removeW"+f(1306)+"rs"](),this[f(1533)+f(717)](1e3,s),this["_connect"+f(1255)]=!1,l&&this[f(1490)+f(1363)]()&&!this[f(413)+f(1074)])if(e[f(1408)](e[f(1853)],e[f(478)])){if(this[f(1484)+f(506)]?.[f(539)+f(1186)+"es"]()){let y=this["_endpoin"+f(506)]?.[f(1491)+"ntEndpoint"]();this[f(409)+f(1205)+f(1135)](pt(e[f(384)],{code:1006,reason:"connect "+y+(f(663)+f(699)+"tries re"+f(1072)),wasClean:!0}))}else{let y=this._options["reconnec"+f(944)+"ptor"](n,s);this[f(409)+"hCloseEv"+f(1135)](e.JqeUL(pt,e.vpqxo,{code:n,reason:s,wasClean:!0,willReconnect:y})),y&&this[f(1870)]()}return}else _0x3a3921[f(486)]=_0x30fd19[f(1231)]()[f(1017)](()=>(_0x2082c0(),_0x1490ec))[f(1017)](function(p){return p});this[f(1490)+f(1363)]()||this[f(413)+f(1074)]?this[f(409)+f(1205)+f(1135)](pt(e[f(384)],{code:n,reason:e[f(644)]})):this[f(409)+"hCloseEvent"](pt(e[f(384)],{code:1006,reason:"going away, netw"+f(1094)+f(1501)})),this[f(449)]=null,this[f(1484)+f(506)]?.[f(1701)+"pointConfig"](),this["_pingLos"+f(1596)]?.[f(594)+"nter"]()}[t(409)+t(524)+"nt"](n){let s=t;this[s(450)](e[s(861)],n),this[s(437)]&&this[s(437)](n)}[t(409)+t(758)+"Event"](n){let s=t;this[s(450)](s(1101),n),this[s(1608)+"e"]&&this[s(1608)+"e"](n)}[t(409)+t(1215)+t(1214)](n){let s=t;this[s(450)](s(977),n),this[s(585)+s(1274)]&&this[s(585)+s(1274)](n)}[t(409)+"hErrorEv"+t(1135)](n){let s=t;this[s(450)](s(1225),n),this[s(697)]&&this[s(697)](n)}[t(409)+"hCloseEv"+t(1135)](n){let s=t;this.emit(e[s(384)],n),this[s(814)]&&this[s(814)](n)}get binaryType(){let n=t;return this[n(449)]?this[n(449)][n(1168)+"pe"]:this[n(1509)+n(783)]}set[t(1168)+"pe"](n){let s=t;this["_binaryT"+s(783)]=n,this[s(449)]&&(this[s(449)].binaryType=n)}get[t(1417)+"nt"](){let n=t;return this[n(1484)+n(506)]?.[n(1491)+n(1681)+n(732)+n(618)]()||0}get["buffered"+t(637)](){let n=t,s=this[n(1640)+n(1278)][n(1150)]((l,f)=>(l+=f&&f[n(1814)+"th"]||0,l),0);return e[n(678)](s,this[n(449)]?this[n(449)][n(1822)+n(637)]:0)}get[t(1603)+"ns"](){let n=t;return this[n(449)]?this[n(449)].extensions:""}get[t(1209)](){let n=t;return this[n(449)]?this._ws[n(1209)]:""}get[t(1590)+"te"](){let n=t;return this[n(449)]?this[n(449)][n(1590)+"te"]:this[n(1401)][n(951)+n(1621)]?this[n(1526)+"NG"]:this[n(791)]}get url(){let n=t;return this[n(449)]?this._ws[n(1802)]:this[n(1691)]}[t(1281)](n=1e3,s){let l=t,f=e[l(1208)][l(1376)]("|"),p=0;for(;;){switch(f[p++]){case"0":this["_dropGlo"+l(1185)+l(877)]();continue;case"1":this["_readyCl"+l(1074)]=!0;continue;case"2":this[l(1610)+l(1067)+"t"](n,s);continue;case"3":if(e[l(1047)](this._ws[l(1590)+"te"],this[l(791)])||e[l(1604)](this._ws.readyState,this[l(712)]))return void this[l(1519)]("close, w"+l(1361)+l(448));continue;case"4":this[l(851)+"mer"]();continue;case"5":if(!this[l(449)])return void this[l(1519)](e[l(1292)]);continue;case"6":this[l(1877)+l(1313)]();continue;case"7":this[l(1573)+l(790)]?.closeDB();continue}break}}async[t(793)](n,s){let l=t;if(e.UarEX(null,n))throw new Error(l(725)+l(1381)+l(555)+l(1235)+l(1075)+l(1514)+l(562)+l(1856)+l(902));e.QutEA==typeof n&&(n=JSON[l(953)+"y"](n)),l(1495)!=typeof n&&!e.AeNBB(n,ArrayBuffer)&&!(n.buffer&&n.buffer instanceof ArrayBuffer)&&(n=JSON[l(953)+"y"](n));let f=await pl(n),p=e.vYpIW(Wp,n),{method:y=0,service:E=this._options.service,logID:m=this._options.logIDGenerator(),headers:P=this[l(1401)][l(915)],payloadEncoding:L=this[l(1401)][l(1585)+l(1332)],payloadType:H=this[l(1401)].payloadType,logIDNew:J=this[l(1401)][l(1308)+l(467)][l(1217)+"toGenera"+l(1865)+"ew"]?e[l(576)](i,this[l(1401)][l(1308)+"Config"][l(1808)]):""}=e[l(1499)](s,{});if(!E)throw new Error(e[l(1305)]);let V={SeqID:ue[l(391)+"er"](this[l(495)]++),LogID:ue[l(391)+"er"](m),service:E,method:y,headers:P,payloadEncoding:e[l(1834)](L,Object)?L[l(1129)]?L[l(1129)]:"":L,payloadType:H instanceof Object?H[l(1642)]?H.type:p:H||p,payload:f,LogIDNew:J},Be=e.ZXAqw(Ut,V);return this[l(449)]&&e.mJvkw(this._ws.readyState,this[l(985)])?(this[l(449)]&&this._ws[l(793)](Be),this[l(1519)](e.kmBld,V)):this["_message"+l(1278)][l(1202)]<this[l(1401)][l(1430)+l(1443)+l(1176)]?(this[l(1640)+l(1278)][l(698)](Be),this._debug(e[l(1397)],V)):(this[l(1640)+l(1278)][l(1051)](),this[l(1640)+l(1278)][l(698)](Be)),{seqID:this._seqId,logID:m,logIDNew:J}}async[t(1566)+"t"](n){let s=t,{url:l}=e.NXRTw(n,{}),f=Array[s(1546)](l)?l:e[s(451)]==typeof l?[l]:[];n&&Object[s(1498)](this[s(1401)],n),f&&f[s(1202)]?this[s(1484)+s(506)]=new ul(f,this[s(1401)][s(707)+"es"]):this[s(1484)+s(506)]?.[s(1701)+s(819)+"fig"](),this[s(1458)+s(1596)]?.[s(594)+s(720)](this[s(1401)][s(1136)+"Count"]),this["_readyCl"+s(1074)]=!1,this._ws&&e[s(417)](this[s(449)][s(1590)+"te"],this[s(791)])?this[s(1128)+"ect"](1e3,e[s(431)],!0):e[s(711)](s(1797),e[s(1664)])?(this[s(403)]=!0,this[s(1870)]()):(_0x3e5496<2048?_0x523043[_0x582e6e++]=e[s(526)](_0x3768a0,6)&31|192:(e[s(1818)](_0x291438,65536)?_0x304e3c[_0x4bcd49++]=e[s(1352)](e[s(777)](e[s(1866)](_0x5dcd04,12),15),224):(_0x3858eb[_0x1c3e89++]=e[s(610)](e[s(1103)](_0x2554c8>>18,7),240),_0xf1c82c[_0x55b300++]=e[s(936)](_0x5db734>>12&63,128)),_0x4f4d41[_0x248223++]=e[s(938)](_0x20926f>>6&63,128)),_0x33f300[_0x9e7204++]=63&_0x10b54a|128)}async[t(770)](){let n=t;if(e.RrrzE(e[n(1318)],e.KohPp)){if(!this[n(1870)+n(1255)]){let s=e.bLugo[n(1376)]("|"),l=0;for(;;){switch(s[l++]){case"0":this["_readyCl"+n(1074)]=!1;continue;case"1":this[n(1870)]();continue;case"2":this["_endpoin"+n(506)]?.[n(1701)+n(819)+n(741)]();continue;case"3":this._isInit=!0;continue;case"4":this[n(1458)+n(1596)]?.["resetCou"+n(720)]();continue}break}}}else{for(_0x2da55d>>>=0;e.PHtsm(_0x183b11,128);)e.oqBuD(_0x162688,_0x1fecd9,e.XDkTf(e.Raqvf(127,_0x47762c),128)),_0x368e74>>>=7;e.NQLpj(_0x353906,_0x5e0078,_0x11520e)}}[t(956)+t(877)](n,s){let l=t,f={EbGPC:"reconnect",iuEsr:e[l(950)]};if(e[l(1188)]===e[l(599)]){let p=_0xe2e8b1(ruVIni[l(620)],{message:ruVIni.iuEsr});this[l(1776)+l(810)]&&this[l(1776)+l(810)](p)}else this.on(n,s)}[t(1828)+t(1601)](n){let{type:s}=n;this.emit(s,n)}["removeEventListe"+t(1366)](n,s){this[t(1823)](n,s)}pingOnce(){let n=t,s={ISqFq:function(l,f){return e[U(1034)](l,f)},rTBXA:"timeout",OKweR:e[n(1004)],BeBQK:e[n(642)],EGgzY:e[n(1362)],NdFVu:function(l,f,p){return e.JqeUL(l,f,p)}};return new Promise((l,f)=>{let p=n,y={GWpVG:function(P,L){return P(L)},jrLjK:s[p(1617)],YOMUm:s[p(853)]};this[p(1877)+p(1313)](),this[p(815)+"gTimeoutId"]=s[p(1311)](setTimeout,this[p(1037)][p(1121)](this),this[p(1401)][p(1026)+"rval"]);let E=()=>{let P=p;y.GWpVG(l,y[P(1449)]),this[P(1823)](y[P(1845)],E),this[P(1823)](P(979)+P(1709)+"t",m)},m=()=>{let P=p;s.ISqFq(f,s[P(1598)]),this.off(P(979)+P(1597)+"s",E),this[P(1823)](s.OKweR,m)};this.on(s.EGgzY,E),this.on(s[p(1467)],m),this[p(1037)]()})}}})(),Me["CustomCl"+M(1327)]=Ce[M(408)+M(1327)],Me[M(1199)+M(1222)]=Ce[M(1199)+"rorEvent"],Me[M(1236)+"e"]=Ce.ErrorCode,Me[M(1601)]=Ce[M(1601)],Me.FWS=Ce[M(519)],Me[M(706)+"MessageE"+M(454)]=Ce[M(706)+M(713)+M(454)],Me[M(713)+M(454)]=Ce[M(713)+M(454)],Me.OpenEvent=Ce.OpenEvent,Me[M(1712)+M(1631)]=Ce[M(1712)+"tEvent"],Me[M(1293)+M(1327)]=Ce[M(1293)+M(1327)],Me["createEr"+M(1222)]=Ce.createErrorEvent,Me[M(1830)+M(1471)+"nt"]=Ce["createMe"+M(1471)+"nt"],Me[M(578)+M(523)]=Ce[M(578)+M(523)],Me[M(1788)+M(1420)+M(454)]=Ce[M(1788)+M(1420)+M(454)],Me[M(1167)+M(1780)]=Ce["decodedF"+M(1780)],Me[M(991)+M(1112)]=Ce.encodeFrame;for(Ho in Ce)["CustomCloseEvent","CustomEr"+M(1222),M(1236)+"e",M(1601),M(519),"Frontier"+M(713)+M(454),"MessageE"+M(454),M(1050)+"t",M(1712)+"tEvent",M(1293)+M(1327),M(1461)+M(1222),M(1830)+M(1471)+"nt",M(578)+"enEvent",M(1788)+"connectE"+M(454),"decodedF"+M(1780),"encodeFr"+M(1112)][M(1479)](Ho)===-1&&(Me[Ho]=Ce[Ho]);var Ho;Object[M(1653)+"operty"](Me,M(769)+"le",{value:!0})});import{existsSync as US,openSync as qS}from"node:fs";import{mkdir as GS}from"node:fs/promises";import{dirname as HS}from"node:path";import{fileURLToPath as jS}from"node:url";function KS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Hd(t=Q()){return US(t.libEntry)?t.libEntry:jS(new URL("../index.ts",import.meta.url))}async function Xx(t={}){let e=t.paths??Q(),r=t.entryOverride??Hd(e),i=KS(e,process.env.COZE_BRIDGE_LOG_MODE);await GS(HS(i),{recursive:!0});let o=qS(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=rt(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[rs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return WS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var WS,rs,ea=Qe(()=>{"use strict";Jt();te();Oe();WS=q("spawn-daemon"),rs="COZE_BRIDGE_DAEMON"});import{spawn as H1}from"node:child_process";import{mkdir as j1,unlink as W1,writeFile as K1}from"node:fs/promises";import{dirname as $1,join as V1}from"node:path";function Jr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function J1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Jr(r)}</key>
21
21
  <string>${Jr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function jS(t,e){return new Promise((r,i)=>{let o=BS(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 Vr,os,oa,Xd,Ep=nt(()=>{"use strict";ne();Vr=W("supervisor.launchd"),os="ai.coze.bridge",oa=jS,Xd={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function Y1(t,e){return new Promise((r,i)=>{let o=H1(t,e,{stdio:["ignore","pipe","pipe"]}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Vr,os,oa,Xd,Ep=Qe(()=>{"use strict";te();Vr=q("supervisor.launchd"),os="ai.coze.bridge",oa=Y1,Xd={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>
@@ -44,11 +44,11 @@ ${e}
44
44
  <key>StandardOutPath</key>
45
45
  <string>${Jr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Jr(t.logFile)}</string>${HS(t.env)}
47
+ <string>${Jr(t.logFile)}</string>${J1(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return GS(t.homeDir,"Library","LaunchAgents",`${os}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await FS(qS(i),{recursive:!0}),await US(i,this.renderConfig(t),"utf8"),Vr.info("plist written",{plistPath:i,activate:r}),!r)return;await oa("launchctl",["unload","-w",i]).catch(c=>Vr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await oa("launchctl",["load","-w",i]),Vr.info("launchd job loaded",{label:os});let o=process.getuid?.()??0;await oa("launchctl",["kickstart","-k",`gui/${o}/${os}`]),Vr.info("launchd job kickstarted",{label:os,uid:o})},async uninstall(t){let e=this.configPath(t);await oa("launchctl",["unload","-w",e]).catch(r=>Vr.warn("launchctl unload failed (ignored)",{err:String(r)})),await zS(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Vr.info("launchd job removed",{plistPath:e})}}});import{spawn as WS}from"node:child_process";import{mkdir as KS,unlink as $S,writeFile as VS}from"node:fs/promises";import{dirname as JS,join as bp}from"node:path";function ca(t,e){return t.isRoot?e:["--user",...e]}function YS(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function da(t,e){return new Promise((r,i)=>{let o=WS(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 aa,Zr,ZS,Qd,vp=nt(()=>{"use strict";ne();aa=W("supervisor.systemd"),Zr="coze-bridge.service",ZS="/etc/systemd/system";Qd={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return V1(t.homeDir,"Library","LaunchAgents",`${os}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await j1($1(i),{recursive:!0}),await K1(i,this.renderConfig(t),"utf8"),Vr.info("plist written",{plistPath:i,activate:r}),!r)return;await oa("launchctl",["unload","-w",i]).catch(a=>Vr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await oa("launchctl",["load","-w",i]),Vr.info("launchd job loaded",{label:os});let o=process.getuid?.()??0;await oa("launchctl",["kickstart","-k",`gui/${o}/${os}`]),Vr.info("launchd job kickstarted",{label:os,uid:o})},async uninstall(t){let e=this.configPath(t);await oa("launchctl",["unload","-w",e]).catch(r=>Vr.warn("launchctl unload failed (ignored)",{err:String(r)})),await W1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Vr.info("launchd job removed",{plistPath:e})}}});import{spawn as Z1}from"node:child_process";import{mkdir as X1,unlink as Q1,writeFile as eI}from"node:fs/promises";import{dirname as tI,join as bp}from"node:path";function ca(t,e){return t.isRoot?e:["--user",...e]}function rI(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function da(t,e){return new Promise((r,i)=>{let o=Z1(t,e,{stdio:["ignore","pipe","pipe"]}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var aa,Yr,nI,Qd,vp=Qe(()=>{"use strict";te();aa=q("supervisor.systemd"),Yr="coze-bridge.service",nI="/etc/systemd/system";Qd={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
- ${YS(t.env)}
62
+ ${rI(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?bp(ZS,Zr):bp(t.homeDir,".config","systemd","user",Zr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await KS(JS(i),{recursive:!0}),await VS(i,this.renderConfig(t),"utf8"),aa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await da("systemctl",ca(t,["daemon-reload"])),await da("systemctl",ca(t,r?["enable","--now",Zr]:["enable",Zr])),aa.info("systemd unit enabled",{unitName:Zr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await da("systemctl",ca(t,["disable","--now",Zr])).catch(r=>aa.warn("systemctl disable failed (ignored)",{err:String(r)})),await $S(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await da("systemctl",ca(t,["daemon-reload"])).catch(()=>{}),aa.info("systemd unit removed",{unitPath:e})}}});import{spawn as XS}from"node:child_process";import{join as QS}from"node:path";function Sp(t,e){return new Promise((r,i)=>{let o=XS(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 el,la,tl,Ip=nt(()=>{"use strict";ne();el=W("supervisor.taskscheduler"),la="CozeBridge",tl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?bp(nI,Yr):bp(t.homeDir,".config","systemd","user",Yr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await X1(tI(i),{recursive:!0}),await eI(i,this.renderConfig(t),"utf8"),aa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await da("systemctl",ca(t,["daemon-reload"])),await da("systemctl",ca(t,r?["enable","--now",Yr]:["enable",Yr])),aa.info("systemd unit enabled",{unitName:Yr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await da("systemctl",ca(t,["disable","--now",Yr])).catch(r=>aa.warn("systemctl disable failed (ignored)",{err:String(r)})),await Q1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await da("systemctl",ca(t,["daemon-reload"])).catch(()=>{}),aa.info("systemd unit removed",{unitPath:e})}}});import{spawn as iI}from"node:child_process";import{join as sI}from"node:path";function Sp(t,e){return new Promise((r,i)=>{let o=iI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var el,la,tl,Ip=Qe(()=>{"use strict";te();el=q("supervisor.taskscheduler"),la="CozeBridge",tl={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,50 +86,56 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return QS(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 Sp("schtasks",["/Create","/SC","ONLOGON","/TN",la,"/TR",r,"/RU",t.userName,"/F"]),el.info("task scheduler entry created",{task:la,logFile:t.logFile})},async uninstall(t){await Sp("schtasks",["/Delete","/TN",la,"/F"]).catch(e=>el.warn("schtasks /Delete failed (ignored)",{err:String(e)})),el.info("task scheduler entry removed",{task:la})}}});var Ap={};Ia(Ap,{buildContext:()=>s2,getSupervisor:()=>n2,launchdSupervisor:()=>Xd,systemdSupervisor:()=>Qd,taskSchedulerSupervisor:()=>tl});import{homedir as e2,userInfo as t2}from"node:os";function n2(t=process.platform){switch(t){case"darwin":return Xd;case"linux":return Qd;case"win32":return tl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function i2(){let t={};for(let e of r2){let r=process.env[e];r&&(t[e]=r)}return t}function s2(){let t=ee();return{nodeBin:process.execPath,entry:Hd(t),logFile:t.logFile,homeDir:e2(),userName:t2().username,isRoot:process.getuid?.()===0,env:i2()}}var r2,kp=nt(()=>{"use strict";Me();ea();Ep();vp();Ip();r2=["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 Dl=W("acp-installer-warmup"),tm=["claude-code","codex"];async function Ol(t={}){let e=t.ensure??cr,i=(await Promise.allSettled(tm.map(async o=>{let c=await e(o);Dl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Dl.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))})}ln();ne();import{readdir as mm}from"node:fs/promises";import{mkdir as Bl,readFile as pm,writeFile as Fl}from"node:fs/promises";import{join as Da}from"node:path";var gm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ur(t,e,r){await Bl(t,{recursive:!0});let i=gm[e],o=Da(t,i);return await Fl(o,r??"","utf8"),o}async function Oa(t,e,r){let i=Da(t,".claude");await Bl(i,{recursive:!0});let o=Da(i,"settings.local.json"),c={};try{let u=await pm(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 Fl(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=W("agent-detail-sync"),wm=6e4,_m=5*6e4,ms=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await mm(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 Re(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 Re(e,this.opts.paths);if(!i){Xe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,_m):wm;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 ur(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var rd=Gt(mu(),1);import{createHash as Q_}from"node:crypto";import{lstat as Jc,mkdir as Zc,readFile as lo,readdir as r0,rm as Yc,stat as td,writeFile as Xc}from"node:fs/promises";import{homedir as ey}from"node:os";import{basename as e0,dirname as ty,join as ge,normalize as ny,relative as nd,resolve as Qc,sep as i0}from"node:path";import{Readable as s0}from"node:stream";import{pipeline as o0}from"node:stream/promises";import qm from"events";import it from"fs";import{EventEmitter as Dc}from"node:events";import Xu from"node:stream";import{StringDecoder as Gm}from"node:string_decoder";import tf from"node:path";import vr from"node:fs";import{dirname as tw,parse as nw}from"path";import{EventEmitter as lw}from"events";import hc from"assert";import{Buffer as Hn}from"buffer";import*as bu from"zlib";import uw from"zlib";import{posix as gr}from"node:path";import{basename as Fw}from"node:path";import Js from"fs";import Rt from"fs";import Cu from"path";import{win32 as Zw}from"node:path";import Mu from"path";import mf from"node:fs";import h_ from"node:assert";import{randomBytes as wf}from"node:crypto";import se from"node:fs";import Fe from"node:path";import _f from"fs";import io from"node:fs";import Si from"node:path";import ct from"node:fs";import y_ from"node:fs/promises";import Xs from"node:path";import{join as Rf}from"node:path";import at from"node:fs";import Of from"node:path";var zm=Object.defineProperty,Um=(t,e)=>{for(var r in e)zm(t,r,{get:e[r],enumerable:!0})},wu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Hm=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof Xu||jm(t)||Wm(t)),jm=t=>!!t&&typeof t=="object"&&t instanceof Dc&&typeof t.pipe=="function"&&t.pipe!==Xu.Writable.prototype.pipe,Wm=t=>!!t&&typeof t=="object"&&t instanceof Dc&&typeof t.write=="function"&&typeof t.end=="function",Ht=Symbol("EOF"),jt=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),bs=Symbol("emittingEnd"),ai=Symbol("emittedError"),vs=Symbol("closed"),_u=Symbol("read"),Ss=Symbol("flush"),yu=Symbol("flushChunk"),_t=Symbol("encoding"),pr=Symbol("decoder"),qe=Symbol("flowing"),ci=Symbol("paused"),yr=Symbol("resume"),Ge=Symbol("buffer"),Qe=Symbol("pipes"),He=Symbol("bufferLength"),za=Symbol("bufferPush"),Is=Symbol("bufferShift"),Ye=Symbol("objectMode"),ke=Symbol("destroyed"),Ua=Symbol("error"),qa=Symbol("emitData"),Eu=Symbol("emitEnd"),Ga=Symbol("emitEnd2"),kt=Symbol("async"),Ha=Symbol("abort"),As=Symbol("aborted"),di=Symbol("signal"),Ln=Symbol("dataListeners"),ot=Symbol("discarded"),li=t=>Promise.resolve().then(t),Km=t=>t(),$m=t=>t==="end"||t==="finish"||t==="prefinish",Vm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Jm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Qu=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[yr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Zm=class extends Qu{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)}},Ym=t=>!!t.objectMode,Xm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Dc{[qe]=!1;[ci]=!1;[Qe]=[];[Ge]=[];[Ye];[_t];[kt];[pr];[Ht]=!1;[fn]=!1;[bs]=!1;[vs]=!1;[ai]=null;[He]=0;[ke]=!1;[di];[As]=!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");Ym(e)?(this[Ye]=!0,this[_t]=null):Xm(e)?(this[_t]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[_t]=null),this[kt]=!!e.async,this[pr]=this[_t]?new Gm(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ge]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:r}=e;r&&(this[di]=r,r.aborted?this[Ha]():r.addEventListener("abort",()=>this[Ha]()))}get bufferLength(){return this[He]}get encoding(){return this[_t]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[kt]}set async(t){this[kt]=this[kt]||!!t}[Ha](){this[As]=!0,this.emit("abort",this[di]?.reason),this.destroy(this[di]?.reason)}get aborted(){return this[As]}set aborted(t){}write(t,e,r){if(this[As])return!1;if(this[Ht])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[kt]?li:Km;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Jm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vm(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[qe]&&this[He]!==0&&this[Ss](!0),this[qe]?this.emit("data",t):this[za](t),this[He]!==0&&this.emit("readable"),r&&i(r),this[qe]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[pr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[pr].write(t)),this[qe]&&this[He]!==0&&this[Ss](!0),this[qe]?this.emit("data",t):this[za](t),this[He]!==0&&this.emit("readable"),r&&i(r),this[qe]):(this[He]!==0&&this.emit("readable"),r&&i(r),this[qe])}read(t){if(this[ke])return null;if(this[ot]=!1,this[He]===0||t===0||t&&t>this[He])return this[jt](),null;this[Ye]&&(t=null),this[Ge].length>1&&!this[Ye]&&(this[Ge]=[this[_t]?this[Ge].join(""):Buffer.concat(this[Ge],this[He])]);let e=this[_u](t||null,this[Ge][0]);return this[jt](),e}[_u](t,e){if(this[Ye])this[Is]();else{let r=e;t===r.length||t===null?this[Is]():typeof r=="string"?(this[Ge][0]=r.slice(t),e=r.slice(0,t),this[He]-=t):(this[Ge][0]=r.subarray(t),e=r.subarray(0,t),this[He]-=t)}return this.emit("data",e),!this[Ge].length&&!this[Ht]&&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[Ht]=!0,this.writable=!1,(this[qe]||!this[ci])&&this[jt](),this}[yr](){this[ke]||(!this[Ln]&&!this[Qe].length&&(this[ot]=!0),this[ci]=!1,this[qe]=!0,this.emit("resume"),this[Ge].length?this[Ss]():this[Ht]?this[jt]():this.emit("drain"))}resume(){return this[yr]()}pause(){this[qe]=!1,this[ci]=!0,this[ot]=!1}get destroyed(){return this[ke]}get flowing(){return this[qe]}get paused(){return this[ci]}[za](t){this[Ye]?this[He]+=1:this[He]+=t.length,this[Ge].push(t)}[Is](){return this[Ye]?this[He]-=1:this[He]-=this[Ge][0].length,this[Ge].shift()}[Ss](t=!1){do;while(this[yu](this[Is]())&&this[Ge].length);!t&&!this[Ge].length&&!this[Ht]&&this.emit("drain")}[yu](t){return this.emit("data",t),this[qe]}pipe(t,e){if(this[ke])return t;this[ot]=!1;let r=this[fn];return e=e||{},t===wu.stdout||t===wu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Qe].push(e.proxyErrors?new Zm(this,t,e):new Qu(this,t,e)),this[kt]?li(()=>this[yr]()):this[yr]()),t}unpipe(t){let e=this[Qe].find(r=>r.dest===t);e&&(this[Qe].length===1?(this[qe]&&this[Ln]===0&&(this[qe]=!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[qe]&&this[yr]();else if(t==="readable"&&this[He]!==0)super.emit("readable");else if($m(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ai]){let i=e;this[kt]?li(()=>i.call(this,this[ai])):i.call(this,this[ai])}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[qe]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[ot]&&!this[Qe].length&&(this[qe]=!1)),e}get emittedEnd(){return this[fn]}[jt](){!this[bs]&&!this[fn]&&!this[ke]&&this[Ge].length===0&&this[Ht]&&(this[bs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[vs]&&this.emit("close"),this[bs]=!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[kt]?(li(()=>this[qa](r)),!0):this[qa](r);if(t==="end")return this[Eu]();if(t==="close"){if(this[vs]=!0,!this[fn]&&!this[ke])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ai]=r,super.emit(Ua,r);let o=!this[di]||this.listeners("error").length?super.emit("error",r):!1;return this[jt](),o}else if(t==="resume"){let o=super.emit("resume");return this[jt](),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[jt](),i}[qa](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[jt](),e}[Eu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[kt]?(li(()=>this[Ga]()),!0):this[Ga]())}[Ga](){if(this[pr]){let e=this[pr].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[_t]?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[Ht])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(ke,f),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(ke,f),this.pause(),i({value:x,done:!!this[Ht]})},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((x,g)=>{o=g,i=x,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(Ua,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(Ua,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[Ge].length=0,this[He]=0;let e=this;return typeof e.close=="function"&&!this[vs]&&e.close(),t?this.emit("error",t):this.emit(ke),this}static get isStream(){return Hm}},Qm=it.writev,bn=Symbol("_autoClose"),vt=Symbol("_close"),ui=Symbol("_ended"),le=Symbol("_fd"),ja=Symbol("_finished"),Vt=Symbol("_flags"),Wa=Symbol("_flush"),uc=Symbol("_handleChunk"),fc=Symbol("_makeBuf"),bi=Symbol("_mode"),ks=Symbol("_needDrain"),Ir=Symbol("_onerror"),Ar=Symbol("_onopen"),Ka=Symbol("_onread"),Er=Symbol("_onwrite"),vn=Symbol("_open"),bt=Symbol("_path"),mn=Symbol("_pos"),Tt=Symbol("_queue"),br=Symbol("_read"),$a=Symbol("_readSize"),$t=Symbol("_reading"),fi=Symbol("_remain"),Va=Symbol("_size"),Bs=Symbol("_write"),Nn=Symbol("_writing"),Fs=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Oc=class extends Kn{[Gn]=!1;[le];[bt];[$a];[$t]=!1;[Va];[fi];[bn];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[Gn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[bt]=t,this[$a]=e.readSize||16*1024*1024,this[$t]=!1,this[Va]=typeof e.size=="number"?e.size:1/0,this[fi]=this[Va],this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[br]():this[vn]()}get fd(){return this[le]}get path(){return this[bt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){it.open(this[bt],"r",(t,e)=>this[Ar](t,e))}[Ar](t,e){t?this[Ir](t):(this[le]=e,this.emit("open",e),this[br]())}[fc](){return Buffer.allocUnsafe(Math.min(this[$a],this[fi]))}[br](){if(!this[$t]){this[$t]=!0;let t=this[fc]();if(t.length===0)return process.nextTick(()=>this[Ka](null,0,t));it.read(this[le],t,0,t.length,null,(e,r,i)=>this[Ka](e,r,i))}}[Ka](t,e,r){this[$t]=!1,t?this[Ir](t):this[uc](e,r)&&this[br]()}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ir](t){this[$t]=!0,this[vt](),this.emit("error",t)}[uc](t,e){let r=!1;return this[fi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[fi]<=0)&&(r=!1,this[vt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[br](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},ew=class extends Oc{[vn](){let t=!0;try{this[Ar](null,it.openSync(this[bt],"r")),t=!1}finally{t&&this[vt]()}}[br](){let t=!0;try{if(!this[$t]){this[$t]=!0;do{let e=this[fc](),r=e.length===0?0:it.readSync(this[le],e,0,e.length,null);if(!this[uc](r,e))break}while(!0);this[$t]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}},Qs=class extends qm{readable=!1;writable=!0;[Gn]=!1;[Nn]=!1;[ui]=!1;[Tt]=[];[ks]=!1;[bt];[bi];[bn];[le];[Fs];[Vt];[ja]=!1;[mn];constructor(t,e){e=e||{},super(e),this[bt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[bi]=e.mode===void 0?438:e.mode,this[mn]=typeof e.start=="number"?e.start:void 0,this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[mn]!==void 0?"r+":"w";this[Fs]=e.flags===void 0,this[Vt]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[vn]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[bt]}[Ir](t){this[vt](),this[Nn]=!0,this.emit("error",t)}[vn](){it.open(this[bt],this[Vt],this[bi],(t,e)=>this[Ar](t,e))}[Ar](t,e){this[Fs]&&this[Vt]==="r+"&&t&&t.code==="ENOENT"?(this[Vt]="w",this[vn]()):t?this[Ir](t):(this[le]=e,this.emit("open",e),this[Nn]||this[Wa]())}end(t,e){return t&&this.write(t,e),this[ui]=!0,!this[Nn]&&!this[Tt].length&&typeof this[le]=="number"&&this[Er](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[ui]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[Nn]||this[Tt].length?(this[Tt].push(t),this[ks]=!0,!1):(this[Nn]=!0,this[Bs](t),!0)}[Bs](t){it.write(this[le],t,0,t.length,this[mn],(e,r)=>this[Er](e,r))}[Er](t,e){t?this[Ir](t):(this[mn]!==void 0&&typeof e=="number"&&(this[mn]+=e),this[Tt].length?this[Wa]():(this[Nn]=!1,this[ui]&&!this[ja]?(this[ja]=!0,this[vt](),this.emit("finish")):this[ks]&&(this[ks]=!1,this.emit("drain"))))}[Wa](){if(this[Tt].length===0)this[ui]&&this[Er](null,0);else if(this[Tt].length===1)this[Bs](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],Qm(this[le],t,this[mn],(e,r)=>this[Er](e,r))}}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},ef=class extends Qs{[vn](){let t;if(this[Fs]&&this[Vt]==="r+")try{t=it.openSync(this[bt],this[Vt],this[bi])}catch(e){if(e?.code==="ENOENT")return this[Vt]="w",this[vn]();throw e}else t=it.openSync(this[bt],this[Vt],this[bi]);this[Ar](null,t)}[vt](){if(this[bn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}[Bs](t){let e=!0;try{this[Er](null,it.writeSync(this[le],t,0,t.length,this[mn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},rw=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"]]),iw=t=>!!t.sync&&!!t.file,sw=t=>!t.sync&&!!t.file,ow=t=>!!t.sync&&!t.file,aw=t=>!t.sync&&!t.file,cw=t=>!!t.file,dw=t=>rw.get(t)||t,Lc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=dw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Pi=(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=Lc(c);if(o?.(f,d),iw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(sw(f)){let x=e(f,d);return u?x.then(()=>u(),u):x}else if(ow(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(f,d)}else if(aw(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}),fw=uw.constants||{ZLIB_VERNUM:4736},Dt=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},fw)),hw=Hn.concat,vu=Object.getOwnPropertyDescriptor(Hn,"concat"),xw=t=>t,Ja=vu?.writable===!0||vu?.set!==void 0?t=>{Hn.concat=t?xw:hw}:t=>{},jn=Symbol("_superWrite"),Ts=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"}},Za=Symbol("flushFlag"),Nc=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 bu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new bu[e](t)}catch(r){throw new Ts(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 Ts(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return hc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[Za]: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=Hn.from(t,e)),this.#e)return;hc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Ja(!0);let d;try{let f=typeof t[Za]=="number"?t[Za]:this.#r;d=this.#t._processChunk(t,f),Ja(!1)}catch(f){Ja(!1),this.#o(new Ts(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 Ts(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[jn](Hn.from(f));for(let x=1;x<d.length;x++)u=this[jn](d[x])}else u=this[jn](Hn.from(d));return r&&r(),u}},nf=class extends Nc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Dt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Dt.Z_FINISH,t.fullFlushFlag=Dt.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(Dt.Z_SYNC_FLUSH),hc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},pw=class extends nf{#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)}},gw=class extends nf{constructor(t){super(t,"Unzip")}},rf=class extends Nc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Dt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Dt.BROTLI_OPERATION_FLUSH,super(t,e)}},mw=class extends rf{constructor(t){super(t,"BrotliCompress")}},ww=class extends rf{constructor(t){super(t,"BrotliDecompress")}},sf=class extends Nc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Dt.ZSTD_e_end,t.fullFlushFlag=Dt.ZSTD_e_flush,super(t,e)}},_w=class extends sf{constructor(t){super(t,"ZstdCompress")}},yw=class extends sf{constructor(t){super(t,"ZstdDecompress")}},Ew=(t,e)=>{if(Number.isSafeInteger(t))t<0?vw(t,e):bw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},bw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},vw=(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]=of(o):o===0?e[i-1]=0:(r=!0,e[i-1]=af(o))}},Sw=t=>{let e=t[0],r=e===128?Aw(t.subarray(1,t.length)):e===255?Iw(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},Iw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=of(c):c===0?d=c:(i=!0,d=af(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Aw=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},of=t=>(255^t)&255,af=t=>(255^t)+1&255,kw={};Um(kw,{code:()=>Mc,isCode:()=>zs,isName:()=>Tw,name:()=>eo,normalFsTypes:()=>cf});var zs=t=>eo.has(t),Tw=t=>Mc.has(t),cf=new Set(["0","","1","2","3","4","5","6","7","D"]),eo=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"]]),Mc=new Map(Array.from(eo).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=cf.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??Ya(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),zs(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 x=Mn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Mn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??Ya(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Ya(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([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=Cw(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=Xa(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=Xa(t,e+476,12,this.atime)||this.needPax,this.needPax=Xa(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:eo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Mc.get(t));if(zs(e)||e==="Unsupported")this.#e=e;else if(zs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Cw=(t,e)=>{let r=t,i="",o,c=gr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=gr.dirname(r),r=gr.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=gr.join(gr.basename(i),r),i=gr.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.*/,""),Ya=(t,e,r)=>Rw(wn(t,e,r)),Rw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,r)=>Number(t[e])&128?Sw(t.subarray(e,e+r)):Dw(t,e,r),Pw=t=>isNaN(t)?void 0:t,Dw=(t,e,r)=>Pw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Ow={12:8589934591,8:2097151},_n=(t,e,r,i)=>i===void 0?!1:i>Ow[r]||i<0?(Ew(i,t.subarray(e,e+r)),!0):(Lw(t,e,r,i),!1),Lw=(t,e,r,i)=>t.write(Nw(i,r),e,r,"ascii"),Nw=(t,e)=>Mw(Math.floor(t).toString(8),e),Mw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Xa=(t,e,r,i)=>i===void 0?!1:_n(t,e,r,i.getTime()/1e3),Bw=new Array(156).join("\0"),Bn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Bw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Vs=class df{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/"+Fw(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 df(zw(Uw(e),r),i)}},zw=(t,e)=>e?Object.assign({},e,t):t,Uw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(qw,Object.create(null)),qw=(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},Gw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Gw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Hw=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))))}},to=(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))},jw=1024*1024,xc=Buffer.from([31,139]),pc=Buffer.from([40,181,47,253]),Ww=Math.max(xc.length,pc.length),ut=Symbol("state"),Fn=Symbol("writeEntry"),Wt=Symbol("readEntry"),Qa=Symbol("nextEntry"),Su=Symbol("processEntry"),Ct=Symbol("extendedHeader"),hi=Symbol("globalExtendedHeader"),hn=Symbol("meta"),Iu=Symbol("emitMeta"),_e=Symbol("buffer"),Kt=Symbol("queue"),xn=Symbol("ended"),ec=Symbol("emittedEnd"),zn=Symbol("emit"),Pe=Symbol("unzip"),Cs=Symbol("consumeChunk"),Rs=Symbol("consumeChunkSub"),tc=Symbol("consumeBody"),Au=Symbol("consumeMeta"),ku=Symbol("consumeHeader"),xi=Symbol("consuming"),nc=Symbol("bufferConcat"),Ps=Symbol("maybeEnd"),mr=Symbol("writing"),pn=Symbol("aborted"),Ds=Symbol("onDone"),Un=Symbol("sawValidEntry"),Os=Symbol("sawNullBlock"),Ls=Symbol("sawEOF"),Tu=Symbol("closeStream"),Kw=()=>!0,Ri=class extends lw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Kt]=[];[_e];[Wt];[Fn];[ut]="begin";[hn]="";[Ct];[hi];[xn]=!1;[Pe];[pn]=!1;[Un];[Os]=!1;[Ls]=!1;[mr]=!1;[xi]=!1;[ec]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ds,()=>{(this[ut]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ds,t.ondone):this.on(Ds,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||jw,this.filter=typeof t.filter=="function"?t.filter:Kw;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[Tu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){to(this,t,e,r)}[ku](t,e){this[Un]===void 0&&(this[Un]=!1);let r;try{r=new Wn(t,e,this[Ct],this[hi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Os]?(this[Ls]=!0,this[ut]==="begin"&&(this[ut]="header"),this[zn]("eof")):(this[Os]=!0,this[zn]("nullBlock"));else if(this[Os]=!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 Hw(r,this[Ct],this[hi]);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[ut]="ignore",o.resume()):o.size>0&&(this[hn]="",o.on("data",c=>this[hn]+=c),this[ut]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[ut]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ut]="body":(this[ut]="header",o.end()),this[Wt]?this[Kt].push(o):(this[Kt].push(o),this[Qa]())))}}}[Tu](){queueMicrotask(()=>this.emit("close"))}[Su](t){let e=!0;if(!t)this[Wt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Wt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Qa]()),e=!1);return e}[Qa](){do;while(this[Su](this[Kt].shift()));if(this[Kt].length===0){let t=this[Wt];!t||t.flowing||t.size===t.remain?this[mr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[tc](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[ut]="header",this[Fn]=void 0,r.end()),o.length}[Au](t,e){let r=this[Fn],i=this[tc](t,e);return!this[Fn]&&r&&this[Iu](r),i}[zn](t,e,r){this[Kt].length===0&&!this[Wt]?this.emit(t,e,r):this[Kt].push([t,e,r])}[Iu](t){switch(this[zn]("meta",this[hn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=Vs.parse(this[hn],this[Ct],!1);break;case"GlobalExtendedHeader":this[hi]=Vs.parse(this[hn],this[hi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[hn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[hn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[pn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,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[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<Ww)return this[_e]=t,r?.(),!0;for(let d=0;this[Pe]===void 0&&d<xc.length;d++)t[d]!==xc[d]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<pc.length;d++)if(t[d]!==pc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Pe]===!1&&c)if(t.length<512)if(this[xn])this.brotli=!0;else return this[_e]=t,r?.(),!0;else try{new Wn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||o)){let d=this[xn];this[xn]=!1,this[Pe]=this[Pe]===void 0?new gw({}):o?new yw({}):new ww({}),this[Pe].on("data",f=>this[Cs](f)),this[Pe].on("error",f=>this.abort(f)),this[Pe].on("end",()=>{this[xn]=!0,this[Cs]()}),this[mr]=!0;let u=!!this[Pe][d?"end":"write"](t);return this[mr]=!1,r?.(),u}}this[mr]=!0,this[Pe]?this[Pe].write(t):this[Cs](t),this[mr]=!1;let i=this[Kt].length>0?!1:this[Wt]?this[Wt].flowing:!0;return!i&&this[Kt].length===0&&this[Wt]?.once("drain",()=>this.emit("drain")),r?.(),i}[nc](t){t&&!this[pn]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[Ps](){if(this[xn]&&!this[ec]&&!this[pn]&&!this[xi]){this[ec]=!0;let t=this[Fn];if(t&&t.blockRemain){let e=this[_e]?this[_e].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[_e]&&t.write(this[_e]),t.end()}this[zn](Ds)}}[Cs](t){if(this[xi]&&t)this[nc](t);else if(!t&&!this[_e])this[Ps]();else if(t){if(this[xi]=!0,this[_e]){this[nc](t);let e=this[_e];this[_e]=void 0,this[Rs](e)}else this[Rs](t);for(;this[_e]&&this[_e]?.length>=512&&!this[pn]&&!this[Ls];){let e=this[_e];this[_e]=void 0,this[Rs](e)}this[xi]=!1}(!this[_e]||this[xn])&&this[Ps]()}[Rs](t){let e=0,r=t.length;for(;e+512<=r&&!this[pn]&&!this[Ls];)switch(this[ut]){case"begin":case"header":this[ku](t,e),e+=512;break;case"ignore":case"body":e+=this[tc](t,e);break;case"meta":e+=this[Au](t,e);break;default:throw new Error("invalid state: "+this[ut])}e<r&&(this[_e]=this[_e]?Buffer.concat([t.subarray(e),this[_e]]):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[Pe]?(t&&this[Pe].write(t),this[Pe].end()):(this[xn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ps]())),this}},vi=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)},$w=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},lf=(t,e)=>{let r=new Map(e.map(c=>[vi(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||nw(c).root||".",f;if(c===u)f=!1;else{let x=r.get(c);f=x!==void 0?x:o(tw(c),u)}return r.set(c,f),f};t.filter=i?(c,d)=>i(c,d)&&o(vi(c)):c=>o(vi(c))},Vw=t=>{let e=new Ri(t),r=t.file,i;try{i=vr.openSync(r,"r");let o=vr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=vr.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=vr.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{vr.closeSync(i)}catch{}}},Jw=(t,e)=>{let r=new Ri(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),vr.stat(o,(u,f)=>{if(u)d(u);else{let x=new Oc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(r)}})})},kr=Pi(Vw,Jw,t=>new Ri(t),t=>new Ri(t),(t,e)=>{e?.length&&lf(t,e),t.noResume||$w(t)}),uf=(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:Yw,parse:Ru}=Zw,Bc=t=>{let e="",r=Ru(t);for(;Yw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Ru(t)}return[e,t]},no=["|","<",">","?",":"],Fc=no.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Xw=new Map(no.map((t,e)=>[t,Fc[e]])),Qw=new Map(Fc.map((t,e)=>[t,no[e]])),Pu=t=>no.reduce((e,r)=>e.split(r).join(Xw.get(r)),t),e_=t=>Fc.reduce((e,r)=>e.split(r).join(Qw.get(r)),t),ff=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),vi(e)+"/"+t):Q(t),t_=16*1024*1024,Du=Symbol("process"),Ou=Symbol("file"),Lu=Symbol("directory"),gc=Symbol("symlink"),Nu=Symbol("hardlink"),pi=Symbol("header"),Us=Symbol("read"),mc=Symbol("lstat"),qs=Symbol("onlstat"),wc=Symbol("onread"),_c=Symbol("onreadlink"),yc=Symbol("openfile"),Ec=Symbol("onopenfile"),yn=Symbol("close"),Zs=Symbol("mode"),bc=Symbol("awaitDrain"),rc=Symbol("ondrain"),Pt=Symbol("prefix"),hf=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=Lc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||t_,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]=Bc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=e_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Cu.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[qs](o):this[mc]()}warn(t,e,r={}){return to(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[mc](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[qs](e)})}[qs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=i_(t),this.emit("stat",t),this[Du]()}[Du](){switch(this.type){case"File":return this[Ou]();case"Directory":return this[Lu]();case"SymbolicLink":return this[gc]();default:return this.end()}}[Zs](t){return uf(t,this.type==="Directory",this.portable)}[Pt](t){return ff(t,this.prefix)}[pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Wn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[Zs](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 Vs({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Lu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[pi](),this.end()}[gc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[_c](e)})}[_c](t){this.linkpath=Q(t),this[pi](),this.end()}[Nu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Cu.relative(this.cwd,t)),this.stat.size=0,this[pi](),this.end()}[Ou](){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[Nu](e);this.linkCache.set(t,this.absolute)}if(this[pi](),this.stat.size===0)return this.end();this[yc]()}[yc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ec](e)})}[Ec](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[Us]()}[Us](){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");Rt.read(t,e,r,i,o,(c,d)=>{if(c)return this[yn](()=>this.emit("error",c));this[wc](d)})}[yn](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[wc](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[rc]():this[bc](()=>this[rc]())}[bc](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)}[rc](){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[Us]()}},n_=class extends hf{sync=!0;[mc](){this[qs](Rt.lstatSync(this.absolute))}[gc](){this[_c](Rt.readlinkSync(this.absolute))}[yc](){this[Ec](Rt.openSync(this.absolute,"r"))}[Us](){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=Rt.readSync(e,r,i,o,c);this[wc](d),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[bc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},r_=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 to(this,t,e,r)}constructor(t,e={}){let r=Lc(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[Zs](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]=Bc(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[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new Vs({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Pt](t){return ff(t,this.prefix)}[Zs](t){return uf(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}},i_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",s_=class Sr{tail;head;length=0;static create(e=[]){return new Sr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)a_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)c_(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 Sr;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 Sr;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 Sr;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 Sr;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=o_(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 o_(t,e,r){let i=e,o=e?e.next:t.head,c=new zc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function a_(t,e){t.tail=new zc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function c_(t,e){t.head=new zc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var zc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Bu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Fu=Buffer.alloc(1024),Gs=Symbol("onStat"),gi=Symbol("ended"),yt=Symbol("queue"),mi=Symbol("pendingLinks"),gn=Symbol("current"),qn=Symbol("process"),wi=Symbol("processing"),Ns=Symbol("processJob"),Et=Symbol("jobs"),ic=Symbol("jobDone"),Hs=Symbol("addFSEntry"),zu=Symbol("addTarEntry"),vc=Symbol("stat"),Sc=Symbol("readdir"),js=Symbol("onreaddir"),Ws=Symbol("pipe"),Uu=Symbol("entry"),sc=Symbol("entryOpt"),Ks=Symbol("writeEntryClass"),xf=Symbol("write"),oc=Symbol("ondrain"),ro=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Ks];onWriteEntry;[yt];[mi]=new Map;[Et]=0;[wi]=!1;[gi]=!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[Ks]=hf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new pw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new mw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new _w(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[oc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[oc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[yt]=new s_,this[Et]=0,this.jobs=Number(t.jobs)||4,this[wi]=!1,this[gi]=!1}[xf](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[gi]=!0,this[qn](),r&&r(),this}write(t){if(this[gi])throw new Error("write after end");return typeof t=="string"?this[Hs](t):this[zu](t),this.flowing}[zu](t){let e=Q(Mu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Bu(t.path,e);r.entry=new r_(t,this[sc](r)),r.entry.on("end",()=>this[ic](r)),this[Et]+=1,this[yt].push(r)}this[qn]()}[Hs](t){let e=Q(Mu.resolve(this.cwd,t));this[yt].push(new Bu(t,e)),this[qn]()}[vc](t){t.pending=!0,this[Et]+=1;let e=this.follow?"stat":"lstat";Js[e](t.absolute,(r,i)=>{t.pending=!1,this[Et]-=1,r?this.emit("error",r):this[Gs](t,i)})}[Gs](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[gn])this[Ns](t);else{let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);i?i.push(t):this[mi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[qn]()}[Sc](t){t.pending=!0,this[Et]+=1,Js.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[Et]-=1,e)return this.emit("error",e);this[js](t,r)})}[js](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[qn]()}[qn](){if(!this[wi]){this[wi]=!0;for(let t=this[yt].head;t&&this[Et]<this.jobs;t=t.next)if(this[Ns](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[wi]=!1,this[gi]&&this[yt].length===0&&this[Et]===0&&(this.zip?this.zip.end(Fu):(super.write(Fu),super.end()))}}get[gn](){return this[yt]&&this[yt].head&&this[yt].head.value}[ic](t){this[yt].shift(),this[Et]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);if(i){this[mi].delete(r);for(let o of i)o.pending=!1,this[Ns](o)}}this[qn]()}[Ns](t){if(t.pending&&t.pendingLink&&t===this[gn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[gn]&&!t.piped&&this[Ws](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Gs](t,e):this[vc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[js](t,e):this[Sc](t),!t.readdir)return}if(t.entry=this[Uu](t),!t.entry){t.ignore=!0;return}t===this[gn]&&!t.piped&&this[Ws](t)}}}[sc](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}}[Uu](t){this[Et]+=1;try{return new this[Ks](t.path,this[sc](t)).on("end",()=>this[ic](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[oc](){this[gn]&&this[gn].entry&&this[gn].entry.resume()}[Ws](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](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={}){to(this,t,e,r)}},Uc=class extends ro{sync=!0;constructor(t){super(t),this[Ks]=n_}pause(){}resume(){}[vc](t){let e=this.follow?"statSync":"lstatSync";this[Gs](t,Js[e](t.absolute))}[Sc](t){this[js](t,Js.readdirSync(t.absolute))}[Ws](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[xf](i)})}},d_=(t,e)=>{let r=new Uc(t),i=new ef(t.file,{mode:t.mode||438});r.pipe(i),pf(r,e)},l_=(t,e)=>{let r=new ro(t),i=new Qs(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 gf(r,e).catch(c=>r.emit("error",c)),o},pf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?kr({file:tf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},gf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await kr({file:tf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},u_=(t,e)=>{let r=new Uc(t);return pf(r,e),r},f_=(t,e)=>{let r=new ro(t);return gf(r,e).catch(i=>r.emit("error",i)),r},qI=Pi(d_,l_,u_,f_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),x_=process.env.__FAKE_PLATFORM__||process.platform,yf=x_==="win32",{O_CREAT:Ef,O_NOFOLLOW:qu,O_TRUNC:bf,O_WRONLY:vf}=_f.constants,Sf=Number(process.env.__FAKE_FS_O_FILENAME__)||_f.constants.UV_FS_O_FILEMAP||0,p_=yf&&!!Sf,g_=512*1024,m_=Sf|bf|Ef|vf,Gu=!yf&&typeof qu=="number"?qu|bf|Ef|vf:null,If=Gu!==null?()=>Gu:p_?t=>t<g_?m_:"w":()=>"w",Ic=(t,e,r)=>{try{return io.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},Ys=(t,e,r,i)=>{io.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},w_=(t,e,r,i,o)=>{if(e.isDirectory())Af(Si.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Si.resolve(t,e.name);Ys(d,r,i,o)});else{let c=Si.resolve(t,e.name);Ys(c,r,i,o)}},Af=(t,e,r,i)=>{io.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 Ys(t,e,r,i);let d=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return Ys(t,e,r,i)}};for(let x of c)w_(t,x,e,r,f)})},__=(t,e,r,i)=>{e.isDirectory()&&kf(Si.resolve(t,e.name),r,i),Ic(Si.resolve(t,e.name),r,i)},kf=(t,e,r)=>{let i;try{i=io.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Ic(t,e,r);throw c}for(let o of i)__(t,o,e,r);return Ic(t,e,r)},Tf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},so=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},E_=(t,e)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Tf(t,r?.code||"ENOTDIR")),e(r)})},b_=(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),x=e.preserve,g=e.unlink,m=Q(e.cwd),S=(b,I)=>{b?r(b):I&&f?Af(I,d,u,A=>S(A)):c?ct.chmod(t,o,r):r()};if(t===m)return E_(t,S);if(x)return y_.mkdir(t,{mode:o,recursive:!0}).then(b=>S(null,b??void 0),S);let y=Q(Xs.relative(m,t)).split("/");Ac(m,y,o,g,m,void 0,S)},Ac=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),f=Q(Xs.resolve(t+"/"+u));ct.mkdir(f,r,Cf(f,e,r,i,o,c,d))},Cf=(t,e,r,i,o,c,d)=>u=>{u?ct.lstat(t,(f,x)=>{if(f)f.path=f.path&&Q(f.path),d(f);else if(x.isDirectory())Ac(t,e,r,i,o,c,d);else if(i)ct.unlink(t,g=>{if(g)return d(g);ct.mkdir(t,r,Cf(t,e,r,i,o,c,d))});else{if(x.isSymbolicLink())return d(new so(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Ac(t,e,r,i,o,c,d))},v_=t=>{let e=!1,r;try{e=ct.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Tf(t,r??"ENOTDIR")}},S_=(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,x=e.unlink,g=Q(e.cwd),m=b=>{b&&u&&kf(b,c,d),o&&ct.chmodSync(t,i)};if(t===g)return v_(g),m();if(f)return m(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(Xs.relative(g,t)).split("/"),y;for(let b=S.shift(),I=g;b&&(I+="/"+b);b=S.shift()){I=Q(Xs.resolve(I));try{ct.mkdirSync(I,i),y=y||I}catch{let A=ct.lstatSync(I);if(A.isDirectory())continue;if(x){ct.unlinkSync(I),ct.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new so(I,I+"/"+S.join("/"))}}return m(y)},ac=Object.create(null),Hu=1e4,wr=new Set,I_=t=>{wr.has(t)?wr.delete(t):ac[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),wr.add(t);let e=ac[t],r=wr.size-Hu;if(r>Hu/10){for(let i of wr)if(wr.delete(i),delete ac[i],--r<=0)break}return e},A_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,k_=A_==="win32",T_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Rf(i,r)),e.push(r||"/"),e},[]),C_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=k_?["win32 parallelization disabled"]:t.map(i=>vi(Rf(I_(i))));let r=new Set(t.map(i=>T_(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}},R_=()=>process.umask(),ju=Symbol("onEntry"),kc=Symbol("checkFs"),Wu=Symbol("checkFs2"),Tc=Symbol("isReusable"),ft=Symbol("makeFs"),Cc=Symbol("file"),Rc=Symbol("directory"),$s=Symbol("link"),Ku=Symbol("symlink"),$u=Symbol("hardlink"),Ei=Symbol("ensureNoSymlink"),Vu=Symbol("unsupported"),Ju=Symbol("checkPath"),cc=Symbol("stripAbsolutePath"),En=Symbol("mkdir"),je=Symbol("onError"),Ms=Symbol("pending"),Zu=Symbol("pend"),_r=Symbol("unpend"),dc=Symbol("ended"),lc=Symbol("maybeClose"),Pc=Symbol("skip"),Ii=Symbol("doChown"),Ai=Symbol("uid"),ki=Symbol("gid"),Ti=Symbol("checkedCwd"),P_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ci=P_==="win32",D_=1024,O_=(t,e)=>{if(!Ci)return se.unlink(t,e);let r=t+".DELETE."+wf(16).toString("hex");se.rename(t,r,i=>{if(i)return e(i);se.unlink(r,e)})},L_=t=>{if(!Ci)return se.unlinkSync(t);let e=t+".DELETE."+wf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},Yu=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,qc=class extends Ri{[dc]=!1;[Ti]=!1;[Ms]=0;reservations=new C_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[dc]=!0,this[lc]()},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:D_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ci,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Fe.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:R_():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[ju](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[lc](){this[dc]&&this[Ms]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[cc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Bc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Ci&&/^[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=Fe.posix.dirname(t.path),f=Fe.posix.normalize(Fe.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}[Ju](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[cc](t,"path")||!this[cc](t,"linkpath"))return!1;if(t.absolute=Fe.isAbsolute(t.path)?Q(Fe.resolve(t.path)):Q(Fe.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}=Fe.win32.parse(String(t.absolute));t.absolute=i+Pu(String(t.absolute).slice(i.length));let{root:o}=Fe.win32.parse(t.path);t.path=o+Pu(t.path.slice(o.length))}return!0}[ju](t){if(!this[Ju](t))return t.resume();switch(h_.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[kc](t);default:return this[Vu](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[_r](),e.resume())}[En](t,e,r){b_(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)}[Ii](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}[Ai](t){return Yu(this.uid,t.uid,this.processUid)}[ki](t){return Yu(this.gid,t.gid,this.processGid)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Qs(String(t.absolute),{flags:If(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[je](u,t),e()});let o=1,c=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[je](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,f=>{f?this[je](f,t):this[_r](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,g=t.mtime;se.futimes(f,x,g,m=>m?se.utimes(u,x,g,S=>c(S&&m)):c())}if(typeof f=="number"&&this[Ii](t)){o++;let x=this[Ai](t),g=this[ki](t);typeof x=="number"&&typeof g=="number"&&se.fchown(f,x,g,m=>m?se.chown(u,x,g,S=>c(S&&m)):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)}[Rc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[En](String(t.absolute),r,i=>{if(i){this[je](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[_r](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ii](t)&&(o++,se.chown(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)),c)),c()})}[Vu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ku](t,e){let r=Q(Fe.relative(this.cwd,Fe.resolve(Fe.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ei](t,this.cwd,r,()=>this[$s](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[$u](t,e){let r=Q(Fe.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ei](t,this.cwd,i,()=>this[$s](t,r,"link",e),o=>{this[je](o,t),e()})}[Ei](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Fe.resolve(e,c);se.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new so(d,Fe.resolve(d,r.join("/"))));this[Ei](t,d,r,i,o)})}[Zu](){this[Ms]++}[_r](){this[Ms]--,this[lc]()}[Pc](t){this[_r](),t.resume()}[Tc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ci}[kc](t){this[Zu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Wu](t,r))}[Wu](t,e){let r=d=>{e(d)},i=()=>{this[En](this.cwd,this.dmode,d=>{if(d){this[je](d,t),r();return}this[Ti]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Fe.dirname(String(t.absolute)));if(d!==this.cwd)return this[En](d,this.dmode,u=>{if(u){this[je](u,t),r();return}c()})}c()},c=()=>{se.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Pc](t),r();return}if(d||this[Tc](t,u))return this[ft](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[ft](g??null,t,r);return f?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),f=>this[ft](f??null,t,r))}if(t.absolute===this.cwd)return this[ft](null,t,r);O_(String(t.absolute),f=>this[ft](f??null,t,r))})};this[Ti]?o():i()}[ft](t,e,r){if(t){this[je](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Cc](e,r);case"Link":return this[$u](e,r);case"SymbolicLink":return this[Ku](e,r);case"Directory":case"GNUDumpDir":return this[Rc](e,r)}}[$s](t,e,r,i){se[r](e,String(t.absolute),o=>{o?this[je](o,t):(this[_r](),t.resume()),i()})}},_i=t=>{try{return[null,t()]}catch(e){return[e,null]}},Pf=class extends qc{sync=!0;[ft](t,e){return super[ft](t,e,()=>{})}[kc](t){if(!this[Ti]){let o=this[En](this.cwd,this.dmode);if(o)return this[je](o,t);this[Ti]=!0}if(t.absolute!==this.cwd){let o=Q(Fe.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[En](o,this.dmode);if(c)return this[je](c,t)}}let[e,r]=_i(()=>se.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Pc](t);if(e||this[Tc](t,r))return this[ft](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?_i(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ft](d,t)}let[o]=_i(()=>se.rmdirSync(String(t.absolute)));this[ft](o,t)}let[i]=t.absolute===this.cwd?[]:_i(()=>L_(String(t.absolute)));this[ft](i,t)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(o)}catch(f){u=f}(d||u)&&this[je](d||u,t),e()},o;try{o=se.openSync(String(t.absolute),If(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{se.writeSync(o,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{se.futimesSync(o,u,f)}catch(x){try{se.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[Ii](t)){let u=this[Ai](t),f=this[ki](t);try{se.fchownSync(o,Number(u),Number(f))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[Rc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[En](String(t.absolute),r);if(i){this[je](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ii](t))try{se.chownSync(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)))}catch{}e(),t.resume()}[En](t,e){try{return S_(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}}[Ei](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Fe.resolve(c,d);let[u,f]=_i(()=>se.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new so(c,Fe.resolve(e,r.join("/"))))}i()}[$s](t,e,r,i){let o=`${r}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[je](c,t)}}},N_=t=>{let e=new Pf(t),r=t.file,i=mf.statSync(r),o=t.maxReadSize||16*1024*1024;new ew(r,{readSize:o,size:i.size}).pipe(e)},M_=(t,e)=>{let r=new qc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),mf.stat(o,(u,f)=>{if(u)d(u);else{let x=new Oc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(r)}})})},Df=Pi(N_,M_,t=>new Pf(t),t=>new qc(t),(t,e)=>{e?.length&&lf(t,e)}),B_=(t,e)=>{let r=new Uc(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,m=0;g<512;g+=m){if(m=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(!m)break e}let f=new Wn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,F_(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},F_=(t,e,r,i,o)=>{let c=new ef(t.file,{fd:i,start:r});e.pipe(c),U_(e,o)},z_=(t,e)=>{e=Array.from(e);let r=new ro(t),i=(o,c,d)=>{let u=(S,y)=>{S?at.close(o,b=>d(S)):d(null,y)},f=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),m=(S,y)=>{if(S||y===void 0)return u(S);if(x+=y,x<512&&y)return at.read(o,g,x,g.length-x,f+x,m);if(f===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let b=new Wn(g);if(!b.cksumValid)return u(null,f);let I=512*Math.ceil((b.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),x=0,at.read(o,g,0,512,f,m)};at.read(o,g,0,512,f,m)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(f||!x)return c(f);at.fstat(x,(g,m)=>{if(g)return at.close(x,()=>c(g));i(x,m.size,(S,y)=>{if(S)return c(S);let b=new Qs(t.file,{fd:x,start:y});r.pipe(b),b.on("error",c),b.on("close",o),q_(r,e)})})};at.open(t.file,d,u)})},U_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?kr({file:Of.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},q_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await kr({file:Of.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},yi=Pi(B_,z_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!cw(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")}),nA=Pi(yi.syncFile,yi.asyncFile,yi.syncNoFile,yi.asyncNoFile,(t,e=[])=>{yi.validate?.(t,e),G_(t)}),G_=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))};ln();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 oo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Lf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ao(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Nf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Mf(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}Jt();$e();ne();Me();$e();function Tr(t,e){if(oo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Di(t){return t.startsWith("http://")||t.startsWith("https://")}function Cr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as $A}from"node:fs";import{dirname as JA,join as ZA}from"node:path";import{fileURLToPath as XA}from"node:url";var Ot="0.2.5";$e();ne();var co="1008033",Uf="1289";var qf="pbbp2",Gf="https://www.coze.cn",Hf="/api/coze_claw/resource/get_frontier_key",Z_="https://www.coze.cn",Y_="wss://frontier.coze.cn";function Rr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Z_}function jf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Y_}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 Li(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Oi=W("handshake");async function Gc(t){let e=Rr(t.endpoint),r=t.timeoutMs??1e4,i=`${Cr(e)}${Hf}?aid=${encodeURIComponent(co)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Oi.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")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let b=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.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 m=g.data??{},S=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,y=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!S||!y){let b=JSON.stringify(g).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return Oi.info("handshake ok",{remoteDeviceId:y,logid:f,traceId:x}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof k)throw Oi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Oi.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Oi.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 jc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Lt="auto",Hc=15e4,Wf=8192;function $f(t){return{model:Wc(t.model)??Lt,...t.modelToken?{modelToken:t.modelToken}:{}}}function Vf(t){return!t||t===Lt}var X_=new Set(["auto","\u81EA\u52A8"]);function Wc(t){let e=t?.trim();if(e)return X_.has(e.toLowerCase())?Lt:e}function Jf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=jc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Lt;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 Vf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Zf(t,e,r){let i={};if(t.modelToken?i.model=t.model||Lt:Vf(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${jc}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=Kc(e,r);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??Hc}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function Yf(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Kc(t,e){let{ttEnv:r,usePpe:i}=Li(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Xf(t,e,r){if(!t.modelToken)return{};let i=Kc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
- `)}}function $c(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Vc(t){return t.model||Lt}function Kf(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 Qf(t,e,r,i){if(!t.modelToken)return null;let o=Vc(t),c=Kc(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[Kf(o,d,t.modelInfo?.contextWindow??Hc,t.modelInfo?.maxOutput??Wf)],f=new Set([o]);for(let g of i??[])!g||f.has(g)||(f.add(g),u.push(Kf(g,["text"],Hc,Wf)));let x={baseUrl:`${jc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}var pe=W("agent-handlers"),t0=5*1024*1024,ry=1,iy=6,sy=new Set(["node_modules",".git",".coze","dist","build",".next"]),oy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,ay=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,cy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function dy(t){let e=t?.trim();return e?cy.test(e)||ay.test(e)?e:(pe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function ly(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 uo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=$n(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ze(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let f of c){let x=ge(o,f.relPath,"SKILL.md");await td(x).then(m=>m.isFile()).catch(()=>!1)&&(d.push(py(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await f0(r,o,f),g=await h0(r,f);for(let m of[...x,...g])u.has(m.relPath)||(u.add(m.relPath),d.push(m.skill))}return{skills:d}}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,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await fo({agentId:r,workspace:i.workspace,framework:i.framework,skill:f});ho(c,d,x),u.push(f)}return await si(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=[];for(let u of c){if(!o.has(u.skillId)){d.push(u);continue}let f=ge(i.workspace,u.relPath);await Yc(f,{recursive:!0,force:!0}),pe.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await si(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");pe.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).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await fy(r,o,c,e.skillName,d);if(!u){let D=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${D}: ${e.skillName}`)}let{absDir:f,relPath:x,dirName:g}=u,m=ge(f,"SKILL.md"),S=new rd.default;S.addLocalFolder(f,g);let y=S.toBuffer();if(y.length>n0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${n0}`);let b=await lo(m,{encoding:"utf8"}).then(D=>l0(D).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...b?{description:b}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):pe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??d0(r,x);if(i&&!d){let D=i.skills??[],E=D.find(R=>R.relPath===x);E?(E.version=A,E.skillId=T):D.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...b?{description:b}:{}}),await si(r,D)}return pe.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,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,pe.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,pe.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(r).catch(x=>pe.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return pe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Re(r);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return pe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await ur(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw pe.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),pe.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Re(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Di(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&&oy.test(d)&&o.push("--env",d);let u=await ly(o);return pe.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Re(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ue(i),pe.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}):(pe.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST",`${ht.DELETE}: missing agentId`);let i=await Re(r),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"?await Yc(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ue(i)),pe.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Tr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Wc(e.model)??Lt,i=await Re(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ue(i),pe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return pe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>pe.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,f]of o.allSessionQueues())d.push(f.enqueue(async()=>{let x=o.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${r}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),pe.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(Tr(e._meta,ht.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ht.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ht.RESET),await this.runDetailSync(e.agentId,ht.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),pe.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ii(e,o)}async clearPersistedAcpSessionIds(e){let r=await Re(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(Tr(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){pe.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){pe.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){pe.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Tr(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 Jc(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 ri(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=ky(e.depth);return u.isDirectory()?{tree:await Ay(o,d,c,f)}:{tree:[{name:Ty(c),path:g0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Tr(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 Jc(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 ri(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>t0)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${t0})`);let d=await lo(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 Re(e).catch(()=>null))?.workspace??Ze(e).workspace}safeJoin(e,r){let i=Qc(e,r||"."),o=nd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${i0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Re(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function a0(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 id(t){return t==="claude-code"?ge(".claude","skills"):ge(".agents","skills")}function c0(t){let e=ey();return t==="claude-code"?[ge(e,".claude","skills")]:t==="codex"?[ge(e,".agents","skills"),ge(e,".codex","skills")]:[ge(e,".agents","skills"),ge(e,".openclaw","skills")]}async function uy(t,e,r,i){let o=async c=>td(ge(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=ge(id(e),r),d=ge(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of c0(e)){let d=ge(c,r);if(await o(d))return{absDir:d,relPath:d}}return null}async function fy(t,e,r,i,o){let c=a0(i),d=await uy(e,r,c,o);if(d)return{...d,dirName:c};let f=(o?await h0(t,r):await f0(t,e,r)).filter(m=>m.skill.skillName===i);if(f.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${f.map(m=>e0(m.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=f[0];return x?{absDir:o?x.relPath:ge(e,x.relPath),relPath:x.relPath,dirName:e0(x.relPath)}:null}function d0(t,e){return(Q_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function l0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
89
+ `},configPath(t){return sI(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 Sp("schtasks",["/Create","/SC","ONLOGON","/TN",la,"/TR",r,"/RU",t.userName,"/F"]),el.info("task scheduler entry created",{task:la,logFile:t.logFile})},async uninstall(t){await Sp("schtasks",["/Delete","/TN",la,"/F"]).catch(e=>el.warn("schtasks /Delete failed (ignored)",{err:String(e)})),el.info("task scheduler entry removed",{task:la})}}});var Ap={};Ia(Ap,{buildContext:()=>uI,getSupervisor:()=>cI,launchdSupervisor:()=>Xd,systemdSupervisor:()=>Qd,taskSchedulerSupervisor:()=>tl});import{homedir as oI,userInfo as aI}from"node:os";function cI(t=process.platform){switch(t){case"darwin":return Xd;case"linux":return Qd;case"win32":return tl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function lI(){let t={};for(let e of dI){let r=process.env[e];r&&(t[e]=r)}return t}function uI(){let t=Q();return{nodeBin:process.execPath,entry:Hd(t),logFile:t.logFile,homeDir:oI(),userName:aI().username,isRoot:process.getuid?.()===0,env:lI()}}var dI,Tp=Qe(()=>{"use strict";Oe();ea();Ep();vp();Ip();dI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();an();var Pl=q("acp-installer-warmup"),tm=["claude-code","codex"];async function Dl(t={}){let e=t.ensure??cr,i=(await Promise.allSettled(tm.map(async o=>{let a=await e(o);Pl.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&Pl.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))})}ln();te();import{readdir as mm}from"node:fs/promises";import{mkdir as Ml,readFile as pm,writeFile as Bl}from"node:fs/promises";import{join as Da}from"node:path";var gm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ur(t,e,r){await Ml(t,{recursive:!0});let i=gm[e],o=Da(t,i);return await Bl(o,r??"","utf8"),o}async function Oa(t,e,r){let i=Da(t,".claude");await Ml(i,{recursive:!0});let o=Da(i,"settings.local.json"),a={};try{let u=await pm(o,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(a=h)}catch{}let d=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=r)}return a.permissions=d,await Bl(o,JSON.stringify(a,null,2),"utf8"),o}var Ye=q("agent-detail-sync"),wm=6e4,_m=5*6e4,ms=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await mm(r)}catch(o){Ye.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Ye.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await Te(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){Ye.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){Ye.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Ye.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){Ye.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Ye.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await Te(e,this.opts.paths);if(!i){Ye.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){Ye.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),g=x?Math.min(x.currentDelay*2,_m):wm;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(o.agentId&&o.agentId!==e){Ye.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let a=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,a=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,a=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,a=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Ye.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&Ye.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){Ye.debug("detail sync: no diff",{agentId:e});return}await Fe(i,this.opts.paths),Ye.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}),Ye.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await ur(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var rd=Gt(gu(),1);import{createHash as Q_}from"node:crypto";import{lstat as Jc,mkdir as Yc,readFile as lo,readdir as n0,rm as Zc,stat as td,writeFile as Xc}from"node:fs/promises";import{homedir as ey}from"node:os";import{basename as Qf,dirname as ty,join as he,normalize as ny,relative as nd,resolve as Qc,sep as r0}from"node:path";import{Readable as i0}from"node:stream";import{pipeline as s0}from"node:stream/promises";import qm from"events";import nt from"fs";import{EventEmitter as Dc}from"node:events";import Zu from"node:stream";import{StringDecoder as Gm}from"node:string_decoder";import ef from"node:path";import vr from"node:fs";import{dirname as tw,parse as nw}from"path";import{EventEmitter as lw}from"events";import hc from"assert";import{Buffer as Hn}from"buffer";import*as Eu from"zlib";import uw from"zlib";import{posix as gr}from"node:path";import{basename as Fw}from"node:path";import Js from"fs";import Ct from"fs";import ku from"path";import{win32 as Yw}from"node:path";import Nu from"path";import gf from"node:fs";import h_ from"node:assert";import{randomBytes as mf}from"node:crypto";import re from"node:fs";import Ne from"node:path";import wf from"fs";import io from"node:fs";import Si from"node:path";import ot from"node:fs";import y_ from"node:fs/promises";import Xs from"node:path";import{join as Cf}from"node:path";import st from"node:fs";import Df from"node:path";var zm=Object.defineProperty,Um=(t,e)=>{for(var r in e)zm(t,r,{get:e[r],enumerable:!0})},mu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Hm=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof Zu||jm(t)||Wm(t)),jm=t=>!!t&&typeof t=="object"&&t instanceof Dc&&typeof t.pipe=="function"&&t.pipe!==Zu.Writable.prototype.pipe,Wm=t=>!!t&&typeof t=="object"&&t instanceof Dc&&typeof t.write=="function"&&typeof t.end=="function",Ht=Symbol("EOF"),jt=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),bs=Symbol("emittingEnd"),ai=Symbol("emittedError"),vs=Symbol("closed"),wu=Symbol("read"),Ss=Symbol("flush"),_u=Symbol("flushChunk"),wt=Symbol("encoding"),pr=Symbol("decoder"),ze=Symbol("flowing"),ci=Symbol("paused"),yr=Symbol("resume"),Ue=Symbol("buffer"),Ze=Symbol("pipes"),qe=Symbol("bufferLength"),za=Symbol("bufferPush"),Is=Symbol("bufferShift"),Je=Symbol("objectMode"),Se=Symbol("destroyed"),Ua=Symbol("error"),qa=Symbol("emitData"),yu=Symbol("emitEnd"),Ga=Symbol("emitEnd2"),At=Symbol("async"),Ha=Symbol("abort"),As=Symbol("aborted"),di=Symbol("signal"),Ln=Symbol("dataListeners"),it=Symbol("discarded"),li=t=>Promise.resolve().then(t),Km=t=>t(),$m=t=>t==="end"||t==="finish"||t==="prefinish",Vm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Jm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Xu=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[yr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ym=class extends Xu{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)}},Zm=t=>!!t.objectMode,Xm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Dc{[ze]=!1;[ci]=!1;[Ze]=[];[Ue]=[];[Je];[wt];[At];[pr];[Ht]=!1;[fn]=!1;[bs]=!1;[vs]=!1;[ai]=null;[qe]=0;[Se]=!1;[di];[As]=!1;[Ln]=0;[it]=!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");Zm(e)?(this[Je]=!0,this[wt]=null):Xm(e)?(this[wt]=e.encoding,this[Je]=!1):(this[Je]=!1,this[wt]=null),this[At]=!!e.async,this[pr]=this[wt]?new Gm(this[wt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ue]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ze]});let{signal:r}=e;r&&(this[di]=r,r.aborted?this[Ha]():r.addEventListener("abort",()=>this[Ha]()))}get bufferLength(){return this[qe]}get encoding(){return this[wt]}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[Je]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[At]}set async(t){this[At]=this[At]||!!t}[Ha](){this[As]=!0,this.emit("abort",this[di]?.reason),this.destroy(this[di]?.reason)}get aborted(){return this[As]}set aborted(t){}write(t,e,r){if(this[As])return!1;if(this[Ht])throw new Error("write after end");if(this[Se])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[At]?li:Km;if(!this[Je]&&!Buffer.isBuffer(t)){if(Jm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Je]?(this[ze]&&this[qe]!==0&&this[Ss](!0),this[ze]?this.emit("data",t):this[za](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[ze]):t.length?(typeof t=="string"&&!(e===this[wt]&&!this[pr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[wt]&&(t=this[pr].write(t)),this[ze]&&this[qe]!==0&&this[Ss](!0),this[ze]?this.emit("data",t):this[za](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[ze]):(this[qe]!==0&&this.emit("readable"),r&&i(r),this[ze])}read(t){if(this[Se])return null;if(this[it]=!1,this[qe]===0||t===0||t&&t>this[qe])return this[jt](),null;this[Je]&&(t=null),this[Ue].length>1&&!this[Je]&&(this[Ue]=[this[wt]?this[Ue].join(""):Buffer.concat(this[Ue],this[qe])]);let e=this[wu](t||null,this[Ue][0]);return this[jt](),e}[wu](t,e){if(this[Je])this[Is]();else{let r=e;t===r.length||t===null?this[Is]():typeof r=="string"?(this[Ue][0]=r.slice(t),e=r.slice(0,t),this[qe]-=t):(this[Ue][0]=r.subarray(t),e=r.subarray(0,t),this[qe]-=t)}return this.emit("data",e),!this[Ue].length&&!this[Ht]&&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[Ht]=!0,this.writable=!1,(this[ze]||!this[ci])&&this[jt](),this}[yr](){this[Se]||(!this[Ln]&&!this[Ze].length&&(this[it]=!0),this[ci]=!1,this[ze]=!0,this.emit("resume"),this[Ue].length?this[Ss]():this[Ht]?this[jt]():this.emit("drain"))}resume(){return this[yr]()}pause(){this[ze]=!1,this[ci]=!0,this[it]=!1}get destroyed(){return this[Se]}get flowing(){return this[ze]}get paused(){return this[ci]}[za](t){this[Je]?this[qe]+=1:this[qe]+=t.length,this[Ue].push(t)}[Is](){return this[Je]?this[qe]-=1:this[qe]-=this[Ue][0].length,this[Ue].shift()}[Ss](t=!1){do;while(this[_u](this[Is]())&&this[Ue].length);!t&&!this[Ue].length&&!this[Ht]&&this.emit("drain")}[_u](t){return this.emit("data",t),this[ze]}pipe(t,e){if(this[Se])return t;this[it]=!1;let r=this[fn];return e=e||{},t===mu.stdout||t===mu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Ze].push(e.proxyErrors?new Ym(this,t,e):new Xu(this,t,e)),this[At]?li(()=>this[yr]()):this[yr]()),t}unpipe(t){let e=this[Ze].find(r=>r.dest===t);e&&(this[Ze].length===1?(this[ze]&&this[Ln]===0&&(this[ze]=!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 r=super.on(t,e);if(t==="data")this[it]=!1,this[Ln]++,!this[Ze].length&&!this[ze]&&this[yr]();else if(t==="readable"&&this[qe]!==0)super.emit("readable");else if($m(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ai]){let i=e;this[At]?li(()=>i.call(this,this[ai])):i.call(this,this[ai])}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[it]&&!this[Ze].length&&(this[ze]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[it]&&!this[Ze].length&&(this[ze]=!1)),e}get emittedEnd(){return this[fn]}[jt](){!this[bs]&&!this[fn]&&!this[Se]&&this[Ue].length===0&&this[Ht]&&(this[bs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[vs]&&this.emit("close"),this[bs]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Se&&this[Se])return!1;if(t==="data")return!this[Je]&&!r?!1:this[At]?(li(()=>this[qa](r)),!0):this[qa](r);if(t==="end")return this[yu]();if(t==="close"){if(this[vs]=!0,!this[fn]&&!this[Se])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ai]=r,super.emit(Ua,r);let o=!this[di]||this.listeners("error").length?super.emit("error",r):!1;return this[jt](),o}else if(t==="resume"){let o=super.emit("resume");return this[jt](),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[jt](),i}[qa](t){for(let r of this[Ze])r.dest.write(t)===!1&&this.pause();let e=this[it]?!1:super.emit("data",t);return this[jt](),e}[yu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[At]?(li(()=>this[Ga]()),!0):this[Ga]())}[Ga](){if(this[pr]){let e=this[pr].end();if(e){for(let r of this[Ze])r.dest.write(e);this[it]||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[Je]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Je]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Je])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[wt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Se,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[it]=!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[Ht])return e();let i,o,a=x=>{this.off("data",d),this.off("end",u),this.off(Se,h),e(),o(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(Se,h),this.pause(),i({value:x,done:!!this[Ht]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Se,h),e(),i({done:!0,value:void 0})},h=()=>a(new Error("stream destroyed"));return new Promise((x,g)=>{o=g,i=x,this.once(Se,h),this.once("error",a),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[it]=!1;let t=!1,e=()=>(this.pause(),this.off(Ua,e),this.off(Se,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(Ua,e),this.once(Se,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Se])return t?this.emit("error",t):this.emit(Se),this;this[Se]=!0,this[it]=!0,this[Ue].length=0,this[qe]=0;let e=this;return typeof e.close=="function"&&!this[vs]&&e.close(),t?this.emit("error",t):this.emit(Se),this}static get isStream(){return Hm}},Qm=nt.writev,bn=Symbol("_autoClose"),bt=Symbol("_close"),ui=Symbol("_ended"),de=Symbol("_fd"),ja=Symbol("_finished"),Vt=Symbol("_flags"),Wa=Symbol("_flush"),uc=Symbol("_handleChunk"),fc=Symbol("_makeBuf"),bi=Symbol("_mode"),Ts=Symbol("_needDrain"),Ir=Symbol("_onerror"),Ar=Symbol("_onopen"),Ka=Symbol("_onread"),Er=Symbol("_onwrite"),vn=Symbol("_open"),Et=Symbol("_path"),mn=Symbol("_pos"),Tt=Symbol("_queue"),br=Symbol("_read"),$a=Symbol("_readSize"),$t=Symbol("_reading"),fi=Symbol("_remain"),Va=Symbol("_size"),Bs=Symbol("_write"),Nn=Symbol("_writing"),Fs=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Oc=class extends Kn{[Gn]=!1;[de];[Et];[$a];[$t]=!1;[Va];[fi];[bn];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[Gn]=!1,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Et]=t,this[$a]=e.readSize||16*1024*1024,this[$t]=!1,this[Va]=typeof e.size=="number"?e.size:1/0,this[fi]=this[Va],this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[br]():this[vn]()}get fd(){return this[de]}get path(){return this[Et]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){nt.open(this[Et],"r",(t,e)=>this[Ar](t,e))}[Ar](t,e){t?this[Ir](t):(this[de]=e,this.emit("open",e),this[br]())}[fc](){return Buffer.allocUnsafe(Math.min(this[$a],this[fi]))}[br](){if(!this[$t]){this[$t]=!0;let t=this[fc]();if(t.length===0)return process.nextTick(()=>this[Ka](null,0,t));nt.read(this[de],t,0,t.length,null,(e,r,i)=>this[Ka](e,r,i))}}[Ka](t,e,r){this[$t]=!1,t?this[Ir](t):this[uc](e,r)&&this[br]()}[bt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,nt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ir](t){this[$t]=!0,this[bt](),this.emit("error",t)}[uc](t,e){let r=!1;return this[fi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[fi]<=0)&&(r=!1,this[bt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[br](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},ew=class extends Oc{[vn](){let t=!0;try{this[Ar](null,nt.openSync(this[Et],"r")),t=!1}finally{t&&this[bt]()}}[br](){let t=!0;try{if(!this[$t]){this[$t]=!0;do{let e=this[fc](),r=e.length===0?0:nt.readSync(this[de],e,0,e.length,null);if(!this[uc](r,e))break}while(!0);this[$t]=!1}t=!1}finally{t&&this[bt]()}}[bt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,nt.closeSync(t),this.emit("close")}}},Qs=class extends qm{readable=!1;writable=!0;[Gn]=!1;[Nn]=!1;[ui]=!1;[Tt]=[];[Ts]=!1;[Et];[bi];[bn];[de];[Fs];[Vt];[ja]=!1;[mn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[bi]=e.mode===void 0?438:e.mode,this[mn]=typeof e.start=="number"?e.start:void 0,this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[mn]!==void 0?"r+":"w";this[Fs]=e.flags===void 0,this[Vt]=e.flags===void 0?r:e.flags,this[de]===void 0&&this[vn]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[de]}get path(){return this[Et]}[Ir](t){this[bt](),this[Nn]=!0,this.emit("error",t)}[vn](){nt.open(this[Et],this[Vt],this[bi],(t,e)=>this[Ar](t,e))}[Ar](t,e){this[Fs]&&this[Vt]==="r+"&&t&&t.code==="ENOENT"?(this[Vt]="w",this[vn]()):t?this[Ir](t):(this[de]=e,this.emit("open",e),this[Nn]||this[Wa]())}end(t,e){return t&&this.write(t,e),this[ui]=!0,!this[Nn]&&!this[Tt].length&&typeof this[de]=="number"&&this[Er](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[ui]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[Nn]||this[Tt].length?(this[Tt].push(t),this[Ts]=!0,!1):(this[Nn]=!0,this[Bs](t),!0)}[Bs](t){nt.write(this[de],t,0,t.length,this[mn],(e,r)=>this[Er](e,r))}[Er](t,e){t?this[Ir](t):(this[mn]!==void 0&&typeof e=="number"&&(this[mn]+=e),this[Tt].length?this[Wa]():(this[Nn]=!1,this[ui]&&!this[ja]?(this[ja]=!0,this[bt](),this.emit("finish")):this[Ts]&&(this[Ts]=!1,this.emit("drain"))))}[Wa](){if(this[Tt].length===0)this[ui]&&this[Er](null,0);else if(this[Tt].length===1)this[Bs](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],Qm(this[de],t,this[mn],(e,r)=>this[Er](e,r))}}[bt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,nt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Qu=class extends Qs{[vn](){let t;if(this[Fs]&&this[Vt]==="r+")try{t=nt.openSync(this[Et],this[Vt],this[bi])}catch(e){if(e?.code==="ENOENT")return this[Vt]="w",this[vn]();throw e}else t=nt.openSync(this[Et],this[Vt],this[bi]);this[Ar](null,t)}[bt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,nt.closeSync(t),this.emit("close")}}[Bs](t){let e=!0;try{this[Er](null,nt.writeSync(this[de],t,0,t.length,this[mn])),e=!1}finally{if(e)try{this[bt]()}catch{}}}},rw=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"]]),iw=t=>!!t.sync&&!!t.file,sw=t=>!t.sync&&!!t.file,ow=t=>!!t.sync&&!t.file,aw=t=>!t.sync&&!t.file,cw=t=>!!t.file,dw=t=>rw.get(t)||t,Lc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=dw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Pi=(t,e,r,i,o)=>Object.assign((a=[],d,u)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=Lc(a);if(o?.(h,d),iw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(sw(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(ow(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(h,d)}else if(aw(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),fw=uw.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},fw)),hw=Hn.concat,bu=Object.getOwnPropertyDescriptor(Hn,"concat"),xw=t=>t,Ja=bu?.writable===!0||bu?.set!==void 0?t=>{Hn.concat=t?xw:hw}:t=>{},jn=Symbol("_superWrite"),ks=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Ya=Symbol("flushFlag"),Nc=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 Eu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Eu[e](t)}catch(r){throw new ks(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 ks(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return hc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[Ya]: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=Hn.from(t,e)),this.#e)return;hc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},Ja(!0);let d;try{let h=typeof t[Ya]=="number"?t[Ya]:this.#r;d=this.#t._processChunk(t,h),Ja(!1)}catch(h){Ja(!1),this.#o(new ks(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new ks(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[jn](Hn.from(h));for(let x=1;x<d.length;x++)u=this[jn](d[x])}else u=this[jn](Hn.from(d));return r&&r(),u}},tf=class extends Nc{#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),hc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},pw=class extends tf{#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)}},gw=class extends tf{constructor(t){super(t,"Unzip")}},nf=class extends Nc{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)}},mw=class extends nf{constructor(t){super(t,"BrotliCompress")}},ww=class extends nf{constructor(t){super(t,"BrotliDecompress")}},rf=class extends Nc{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)}},_w=class extends rf{constructor(t){super(t,"ZstdCompress")}},yw=class extends rf{constructor(t){super(t,"ZstdDecompress")}},Ew=(t,e)=>{if(Number.isSafeInteger(t))t<0?vw(t,e):bw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},bw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},vw=(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]=sf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=of(o))}},Sw=t=>{let e=t[0],r=e===128?Aw(t.subarray(1,t.length)):e===255?Iw(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},Iw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=sf(a):a===0?d=a:(i=!0,d=of(a)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Aw=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},sf=t=>(255^t)&255,of=t=>(255^t)+1&255,Tw={};Um(Tw,{code:()=>Mc,isCode:()=>zs,isName:()=>kw,name:()=>eo,normalFsTypes:()=>af});var zs=t=>eo.has(t),kw=t=>Mc.has(t),af=new Set(["0","","1","2","3","4","5","6","7","D"]),eo=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"]]),Mc=new Map(Array.from(eo).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),a=af.has(o),d=a?r:void 0,u=a?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??Za(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),zs(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 x=Mn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Mn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??Za(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Za(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="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=Cw(this.path||"",r),o=i[0],a=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=Xa(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,a)||this.needPax,t[e+475]!==0?this.needPax=Bn(t,e+345,155,a)||this.needPax:(this.needPax=Bn(t,e+345,130,a)||this.needPax,this.needPax=Xa(t,e+476,12,this.atime)||this.needPax,this.needPax=Xa(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:eo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Mc.get(t));if(zs(e)||e==="Unsupported")this.#e=e;else if(zs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Cw=(t,e)=>{let r=t,i="",o,a=gr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=gr.dirname(r),r=gr.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=gr.join(gr.basename(i),r),i=gr.dirname(i));while(i!==a&&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.*/,""),Za=(t,e,r)=>Rw(wn(t,e,r)),Rw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,r)=>Number(t[e])&128?Sw(t.subarray(e,e+r)):Dw(t,e,r),Pw=t=>isNaN(t)?void 0:t,Dw=(t,e,r)=>Pw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Ow={12:8589934591,8:2097151},_n=(t,e,r,i)=>i===void 0?!1:i>Ow[r]||i<0?(Ew(i,t.subarray(e,e+r)),!0):(Lw(t,e,r,i),!1),Lw=(t,e,r,i)=>t.write(Nw(i,r),e,r,"ascii"),Nw=(t,e)=>Mw(Math.floor(t).toString(8),e),Mw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Xa=(t,e,r,i)=>i===void 0?!1:_n(t,e,r,i.getTime()/1e3),Bw=new Array(156).join("\0"),Bn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Bw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Vs=class cf{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 a=0;a<512;a++)o[a]=0;new Wn({path:("PaxHeader/"+Fw(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 a=r+512;a<o.length;a++)o[a]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,a=Buffer.byteLength(o),d=Math.floor(Math.log(a)/Math.log(10))+1;return a+d>=Math.pow(10,d)&&(d+=1),d+a+o}static parse(e,r,i=!1){return new cf(zw(Uw(e),r),i)}},zw=(t,e)=>e?Object.assign({},e,t):t,Uw=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(qw,Object.create(null)),qw=(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 a=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=");return t[a]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(a)?new Date(Number(d)*1e3):/^[0-9]+$/.test(d)?+d:d,t},Gw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,X=Gw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Hw=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=X(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?X(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=X(t.path)),t.linkpath&&(t.linkpath=X(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},to=(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))},jw=1024*1024,xc=Buffer.from([31,139]),pc=Buffer.from([40,181,47,253]),Ww=Math.max(xc.length,pc.length),dt=Symbol("state"),Fn=Symbol("writeEntry"),Wt=Symbol("readEntry"),Qa=Symbol("nextEntry"),vu=Symbol("processEntry"),kt=Symbol("extendedHeader"),hi=Symbol("globalExtendedHeader"),hn=Symbol("meta"),Su=Symbol("emitMeta"),ge=Symbol("buffer"),Kt=Symbol("queue"),xn=Symbol("ended"),ec=Symbol("emittedEnd"),zn=Symbol("emit"),ke=Symbol("unzip"),Cs=Symbol("consumeChunk"),Rs=Symbol("consumeChunkSub"),tc=Symbol("consumeBody"),Iu=Symbol("consumeMeta"),Au=Symbol("consumeHeader"),xi=Symbol("consuming"),nc=Symbol("bufferConcat"),Ps=Symbol("maybeEnd"),mr=Symbol("writing"),pn=Symbol("aborted"),Ds=Symbol("onDone"),Un=Symbol("sawValidEntry"),Os=Symbol("sawNullBlock"),Ls=Symbol("sawEOF"),Tu=Symbol("closeStream"),Kw=()=>!0,Ri=class extends lw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Kt]=[];[ge];[Wt];[Fn];[dt]="begin";[hn]="";[kt];[hi];[xn]=!1;[ke];[pn]=!1;[Un];[Os]=!1;[Ls]=!1;[mr]=!1;[xi]=!1;[ec]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ds,()=>{(this[dt]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ds,t.ondone):this.on(Ds,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||jw,this.filter=typeof t.filter=="function"?t.filter:Kw;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[Tu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){to(this,t,e,r)}[Au](t,e){this[Un]===void 0&&(this[Un]=!1);let r;try{r=new Wn(t,e,this[kt],this[hi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Os]?(this[Ls]=!0,this[dt]==="begin"&&(this[dt]="header"),this[zn]("eof")):(this[Os]=!0,this[zn]("nullBlock"));else if(this[Os]=!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 Hw(r,this[kt],this[hi]);if(!this[Un])if(o.remain){let a=()=>{o.invalid||(this[Un]=!0)};o.on("end",a)}else this[Un]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[zn]("ignoredEntry",o),this[dt]="ignore",o.resume()):o.size>0&&(this[hn]="",o.on("data",a=>this[hn]+=a),this[dt]="meta"):(this[kt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[dt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[dt]="body":(this[dt]="header",o.end()),this[Wt]?this[Kt].push(o):(this[Kt].push(o),this[Qa]())))}}}[Tu](){queueMicrotask(()=>this.emit("close"))}[vu](t){let e=!0;if(!t)this[Wt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Wt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Qa]()),e=!1);return e}[Qa](){do;while(this[vu](this[Kt].shift()));if(this[Kt].length===0){let t=this[Wt];!t||t.flowing||t.size===t.remain?this[mr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[tc](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[dt]="header",this[Fn]=void 0,r.end()),o.length}[Iu](t,e){let r=this[Fn],i=this[tc](t,e);return!this[Fn]&&r&&this[Su](r),i}[zn](t,e,r){this[Kt].length===0&&!this[Wt]?this.emit(t,e,r):this[Kt].push([t,e,r])}[Su](t){switch(this[zn]("meta",this[hn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[kt]=Vs.parse(this[hn],this[kt],!1);break;case"GlobalExtendedHeader":this[hi]=Vs.parse(this[hn],this[hi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[kt]??Object.create(null);this[kt]=e,e.path=this[hn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[kt]||Object.create(null);this[kt]=e,e.linkpath=this[hn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[pn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,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[ke]===void 0||this.brotli===void 0&&this[ke]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<Ww)return this[ge]=t,r?.(),!0;for(let d=0;this[ke]===void 0&&d<xc.length;d++)t[d]!==xc[d]&&(this[ke]=!1);let o=!1;if(this[ke]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<pc.length;d++)if(t[d]!==pc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[ke]===!1&&a)if(t.length<512)if(this[xn])this.brotli=!0;else return this[ge]=t,r?.(),!0;else try{new Wn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[ke]===void 0||this[ke]===!1&&(this.brotli||o)){let d=this[xn];this[xn]=!1,this[ke]=this[ke]===void 0?new gw({}):o?new yw({}):new ww({}),this[ke].on("data",h=>this[Cs](h)),this[ke].on("error",h=>this.abort(h)),this[ke].on("end",()=>{this[xn]=!0,this[Cs]()}),this[mr]=!0;let u=!!this[ke][d?"end":"write"](t);return this[mr]=!1,r?.(),u}}this[mr]=!0,this[ke]?this[ke].write(t):this[Cs](t),this[mr]=!1;let i=this[Kt].length>0?!1:this[Wt]?this[Wt].flowing:!0;return!i&&this[Kt].length===0&&this[Wt]?.once("drain",()=>this.emit("drain")),r?.(),i}[nc](t){t&&!this[pn]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Ps](){if(this[xn]&&!this[ec]&&!this[pn]&&!this[xi]){this[ec]=!0;let t=this[Fn];if(t&&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[zn](Ds)}}[Cs](t){if(this[xi]&&t)this[nc](t);else if(!t&&!this[ge])this[Ps]();else if(t){if(this[xi]=!0,this[ge]){this[nc](t);let e=this[ge];this[ge]=void 0,this[Rs](e)}else this[Rs](t);for(;this[ge]&&this[ge]?.length>=512&&!this[pn]&&!this[Ls];){let e=this[ge];this[ge]=void 0,this[Rs](e)}this[xi]=!1}(!this[ge]||this[xn])&&this[Ps]()}[Rs](t){let e=0,r=t.length;for(;e+512<=r&&!this[pn]&&!this[Ls];)switch(this[dt]){case"begin":case"header":this[Au](t,e),e+=512;break;case"ignore":case"body":e+=this[tc](t,e);break;case"meta":e+=this[Iu](t,e);break;default:throw new Error("invalid state: "+this[dt])}e<r&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[pn]||(this[ke]?(t&&this[ke].write(t),this[ke].end()):(this[xn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ps]())),this}},vi=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)},$w=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},df=(t,e)=>{let r=new Map(e.map(a=>[vi(a),!0])),i=t.filter,o=(a,d="")=>{let u=d||nw(a).root||".",h;if(a===u)h=!1;else{let x=r.get(a);h=x!==void 0?x:o(tw(a),u)}return r.set(a,h),h};t.filter=i?(a,d)=>i(a,d)&&o(vi(a)):a=>o(vi(a))},Vw=t=>{let e=new Ri(t),r=t.file,i;try{i=vr.openSync(r,"r");let o=vr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=vr.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(a);for(;d<o.size;){let h=vr.readSync(i,u,0,a,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{vr.closeSync(i)}catch{}}},Jw=(t,e)=>{let r=new Ri(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{r.on("error",d),r.on("end",a),vr.stat(o,(u,h)=>{if(u)d(u);else{let x=new Oc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Tr=Pi(Vw,Jw,t=>new Ri(t),t=>new Ri(t),(t,e)=>{e?.length&&df(t,e),t.noResume||$w(t)}),lf=(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:Zw,parse:Cu}=Yw,Bc=t=>{let e="",r=Cu(t);for(;Zw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Cu(t)}return[e,t]},no=["|","<",">","?",":"],Fc=no.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Xw=new Map(no.map((t,e)=>[t,Fc[e]])),Qw=new Map(Fc.map((t,e)=>[t,no[e]])),Ru=t=>no.reduce((e,r)=>e.split(r).join(Xw.get(r)),t),e_=t=>Fc.reduce((e,r)=>e.split(r).join(Qw.get(r)),t),uf=(t,e)=>e?(t=X(t).replace(/^\.(\/|$)/,""),vi(e)+"/"+t):X(t),t_=16*1024*1024,Pu=Symbol("process"),Du=Symbol("file"),Ou=Symbol("directory"),gc=Symbol("symlink"),Lu=Symbol("hardlink"),pi=Symbol("header"),Us=Symbol("read"),mc=Symbol("lstat"),qs=Symbol("onlstat"),wc=Symbol("onread"),_c=Symbol("onreadlink"),yc=Symbol("openfile"),Ec=Symbol("onopenfile"),yn=Symbol("close"),Ys=Symbol("mode"),bc=Symbol("awaitDrain"),rc=Symbol("ondrain"),Rt=Symbol("prefix"),ff=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=Lc(e);super(),this.path=X(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||t_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=X(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?X(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[a,d]=Bc(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=e_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=X(r.absolute||ku.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[qs](o):this[mc]()}warn(t,e,r={}){return to(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[mc](){Ct.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[qs](e)})}[qs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=i_(t),this.emit("stat",t),this[Pu]()}[Pu](){switch(this.type){case"File":return this[Du]();case"Directory":return this[Ou]();case"SymbolicLink":return this[gc]();default:return this.end()}}[Ys](t){return lf(t,this.type==="Directory",this.portable)}[Rt](t){return uf(t,this.prefix)}[pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Wn({path:this[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](this.linkpath):this.linkpath,mode:this[Ys](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 Vs({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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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)}[Ou](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[pi](),this.end()}[gc](){Ct.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[_c](e)})}[_c](t){this.linkpath=X(t),this[pi](),this.end()}[Lu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=X(ku.relative(this.cwd,t)),this.stat.size=0,this[pi](),this.end()}[Du](){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[Lu](e);this.linkCache.set(t,this.absolute)}if(this[pi](),this.stat.size===0)return this.end();this[yc]()}[yc](){Ct.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ec](e)})}[Ec](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[Us]()}[Us](){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");Ct.read(t,e,r,i,o,(a,d)=>{if(a)return this[yn](()=>this.emit("error",a));this[wc](d)})}[yn](t=()=>{}){this.fd!==void 0&&Ct.close(this.fd,t)}[wc](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[rc]():this[bc](()=>this[rc]())}[bc](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)}[rc](){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[Us]()}},n_=class extends ff{sync=!0;[mc](){this[qs](Ct.lstatSync(this.absolute))}[gc](){this[_c](Ct.readlinkSync(this.absolute))}[yc](){this[Ec](Ct.openSync(this.absolute,"r"))}[Us](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:a}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let d=Ct.readSync(e,r,i,o,a);this[wc](d),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[bc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Ct.closeSync(this.fd),t()}},r_=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 to(this,t,e,r)}constructor(t,e={}){let r=Lc(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=X(t.path),this.mode=t.mode!==void 0?this[Ys](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?X(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Bc(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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](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 Vs({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[Rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Rt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let a=this.header?.block;if(!a)throw new Error("failed to encode header");super.write(a),t.pipe(this)}[Rt](t){return uf(t,this.prefix)}[Ys](t){return lf(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}},i_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",s_=class Sr{tail;head;length=0;static create(e=[]){return new Sr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)a_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)c_(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 Sr;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 Sr;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 a=0;o;a++)i=e(i,o.value,a),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 a=this.length-1;o;a--)i=e(i,o.value,a),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let 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 Sr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,a=0;for(a=0;o&&a<e;a++)o=o.next;for(;o&&a<r;a++,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 Sr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,a=this.tail;for(;a&&o>r;o--)a=a.prev;for(;a&&o>e;o--,a=a.prev)i.push(a.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 a=[];for(let d=0;o&&d<r;d++)a.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=o_(this,o,d);return a}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 o_(t,e,r){let i=e,o=e?e.next:t.head,a=new zc(r,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function a_(t,e){t.tail=new zc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function c_(t,e){t.head=new zc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var zc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Mu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Bu=Buffer.alloc(1024),Gs=Symbol("onStat"),gi=Symbol("ended"),_t=Symbol("queue"),mi=Symbol("pendingLinks"),gn=Symbol("current"),qn=Symbol("process"),wi=Symbol("processing"),Ns=Symbol("processJob"),yt=Symbol("jobs"),ic=Symbol("jobDone"),Hs=Symbol("addFSEntry"),Fu=Symbol("addTarEntry"),vc=Symbol("stat"),Sc=Symbol("readdir"),js=Symbol("onreaddir"),Ws=Symbol("pipe"),zu=Symbol("entry"),sc=Symbol("entryOpt"),Ks=Symbol("writeEntryClass"),hf=Symbol("write"),oc=Symbol("ondrain"),ro=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Ks];onWriteEntry;[_t];[mi]=new Map;[yt]=0;[wi]=!1;[gi]=!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=X(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[Ks]=ff,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new pw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new mw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new _w(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[oc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[oc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[_t]=new s_,this[yt]=0,this.jobs=Number(t.jobs)||4,this[wi]=!1,this[gi]=!1}[hf](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[gi]=!0,this[qn](),r&&r(),this}write(t){if(this[gi])throw new Error("write after end");return typeof t=="string"?this[Hs](t):this[Fu](t),this.flowing}[Fu](t){let e=X(Nu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Mu(t.path,e);r.entry=new r_(t,this[sc](r)),r.entry.on("end",()=>this[ic](r)),this[yt]+=1,this[_t].push(r)}this[qn]()}[Hs](t){let e=X(Nu.resolve(this.cwd,t));this[_t].push(new Mu(t,e)),this[qn]()}[vc](t){t.pending=!0,this[yt]+=1;let e=this.follow?"stat":"lstat";Js[e](t.absolute,(r,i)=>{t.pending=!1,this[yt]-=1,r?this.emit("error",r):this[Gs](t,i)})}[Gs](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[gn])this[Ns](t);else{let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);i?i.push(t):this[mi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[qn]()}[Sc](t){t.pending=!0,this[yt]+=1,Js.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[yt]-=1,e)return this.emit("error",e);this[js](t,r)})}[js](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[qn]()}[qn](){if(!this[wi]){this[wi]=!0;for(let t=this[_t].head;t&&this[yt]<this.jobs;t=t.next)if(this[Ns](t.value),t.value.ignore){let e=t.next;this[_t].removeNode(t),t.next=e}this[wi]=!1,this[gi]&&this[_t].length===0&&this[yt]===0&&(this.zip?this.zip.end(Bu):(super.write(Bu),super.end()))}}get[gn](){return this[_t]&&this[_t].head&&this[_t].head.value}[ic](t){this[_t].shift(),this[yt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);if(i){this[mi].delete(r);for(let o of i)o.pending=!1,this[Ns](o)}}this[qn]()}[Ns](t){if(t.pending&&t.pendingLink&&t===this[gn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[gn]&&!t.piped&&this[Ws](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Gs](t,e):this[vc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[js](t,e):this[Sc](t),!t.readdir)return}if(t.entry=this[zu](t),!t.entry){t.ignore=!0;return}t===this[gn]&&!t.piped&&this[Ws](t)}}}[sc](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}}[zu](t){this[yt]+=1;try{return new this[Ks](t.path,this[sc](t)).on("end",()=>this[ic](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[oc](){this[gn]&&this[gn].entry&&this[gn].entry.resume()}[Ws](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](a+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={}){to(this,t,e,r)}},Uc=class extends ro{sync=!0;constructor(t){super(t),this[Ks]=n_}pause(){}resume(){}[vc](t){let e=this.follow?"statSync":"lstatSync";this[Gs](t,Js[e](t.absolute))}[Sc](t){this[js](t,Js.readdirSync(t.absolute))}[Ws](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[Hs](a+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[hf](i)})}},d_=(t,e)=>{let r=new Uc(t),i=new Qu(t.file,{mode:t.mode||438});r.pipe(i),xf(r,e)},l_=(t,e)=>{let r=new ro(t),i=new Qs(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((a,d)=>{i.on("error",d),i.on("close",a),r.on("error",d)});return pf(r,e).catch(a=>r.emit("error",a)),o},xf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Tr({file:ef.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},pf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Tr({file:ef.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},u_=(t,e)=>{let r=new Uc(t);return xf(r,e),r},f_=(t,e)=>{let r=new ro(t);return pf(r,e).catch(i=>r.emit("error",i)),r},$A=Pi(d_,l_,u_,f_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),x_=process.env.__FAKE_PLATFORM__||process.platform,_f=x_==="win32",{O_CREAT:yf,O_NOFOLLOW:Uu,O_TRUNC:Ef,O_WRONLY:bf}=wf.constants,vf=Number(process.env.__FAKE_FS_O_FILENAME__)||wf.constants.UV_FS_O_FILEMAP||0,p_=_f&&!!vf,g_=512*1024,m_=vf|Ef|yf|bf,qu=!_f&&typeof Uu=="number"?Uu|Ef|yf|bf:null,Sf=qu!==null?()=>qu:p_?t=>t<g_?m_:"w":()=>"w",Ic=(t,e,r)=>{try{return io.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},Zs=(t,e,r,i)=>{io.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},w_=(t,e,r,i,o)=>{if(e.isDirectory())If(Si.resolve(t,e.name),r,i,a=>{if(a)return o(a);let d=Si.resolve(t,e.name);Zs(d,r,i,o)});else{let a=Si.resolve(t,e.name);Zs(a,r,i,o)}},If=(t,e,r,i)=>{io.readdir(t,{withFileTypes:!0},(o,a)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!a.length)return Zs(t,e,r,i);let d=a.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return Zs(t,e,r,i)}};for(let x of a)w_(t,x,e,r,h)})},__=(t,e,r,i)=>{e.isDirectory()&&Af(Si.resolve(t,e.name),r,i),Ic(Si.resolve(t,e.name),r,i)},Af=(t,e,r)=>{let i;try{i=io.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Ic(t,e,r);throw a}for(let o of i)__(t,o,e,r);return Ic(t,e,r)},Tf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},so=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},E_=(t,e)=>{ot.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Tf(t,r?.code||"ENOTDIR")),e(r)})},b_=(t,e,r)=>{t=X(t);let i=e.umask??18,o=e.mode|448,a=(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,g=e.unlink,w=X(e.cwd),S=(v,I)=>{v?r(v):I&&h?If(I,d,u,A=>S(A)):a?ot.chmod(t,o,r):r()};if(t===w)return E_(t,S);if(x)return y_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let _=X(Xs.relative(w,t)).split("/");Ac(w,_,o,g,w,void 0,S)},Ac=(t,e,r,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),h=X(Xs.resolve(t+"/"+u));ot.mkdir(h,r,kf(h,e,r,i,o,a,d))},kf=(t,e,r,i,o,a,d)=>u=>{u?ot.lstat(t,(h,x)=>{if(h)h.path=h.path&&X(h.path),d(h);else if(x.isDirectory())Ac(t,e,r,i,o,a,d);else if(i)ot.unlink(t,g=>{if(g)return d(g);ot.mkdir(t,r,kf(t,e,r,i,o,a,d))});else{if(x.isSymbolicLink())return d(new so(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,Ac(t,e,r,i,o,a,d))},v_=t=>{let e=!1,r;try{e=ot.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Tf(t,r??"ENOTDIR")}},S_=(t,e)=>{t=X(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,g=X(e.cwd),w=v=>{v&&u&&Af(v,a,d),o&&ot.chmodSync(t,i)};if(t===g)return v_(g),w();if(h)return w(ot.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=X(Xs.relative(g,t)).split("/"),_;for(let v=S.shift(),I=g;v&&(I+="/"+v);v=S.shift()){I=X(Xs.resolve(I));try{ot.mkdirSync(I,i),_=_||I}catch{let A=ot.lstatSync(I);if(A.isDirectory())continue;if(x){ot.unlinkSync(I),ot.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new so(I,I+"/"+S.join("/"))}}return w(_)},ac=Object.create(null),Gu=1e4,wr=new Set,I_=t=>{wr.has(t)?wr.delete(t):ac[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),wr.add(t);let e=ac[t],r=wr.size-Gu;if(r>Gu/10){for(let i of wr)if(wr.delete(i),delete ac[i],--r<=0)break}return e},A_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,T_=A_==="win32",k_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Cf(i,r)),e.push(r||"/"),e},[]),C_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=T_?["win32 parallelization disabled"]:t.map(i=>vi(Cf(I_(i))));let r=new Set(t.map(i=>k_(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 a=o.at(-1);a instanceof Set?a.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(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 a of r){let d=this.#e.get(a);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(a);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let h of u)o.add(h)}for(let a of i){let d=this.#e.get(a),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(a);continue}else if(u.size===1){d.shift();let h=d[0];typeof h=="function"&&o.add(h)}else u.delete(t)}return this.#r.delete(t),o.forEach(a=>this.#i(a)),!0}},R_=()=>process.umask(),Hu=Symbol("onEntry"),Tc=Symbol("checkFs"),ju=Symbol("checkFs2"),kc=Symbol("isReusable"),lt=Symbol("makeFs"),Cc=Symbol("file"),Rc=Symbol("directory"),$s=Symbol("link"),Wu=Symbol("symlink"),Ku=Symbol("hardlink"),Ei=Symbol("ensureNoSymlink"),$u=Symbol("unsupported"),Vu=Symbol("checkPath"),cc=Symbol("stripAbsolutePath"),En=Symbol("mkdir"),Ge=Symbol("onError"),Ms=Symbol("pending"),Ju=Symbol("pend"),_r=Symbol("unpend"),dc=Symbol("ended"),lc=Symbol("maybeClose"),Pc=Symbol("skip"),Ii=Symbol("doChown"),Ai=Symbol("uid"),Ti=Symbol("gid"),ki=Symbol("checkedCwd"),P_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ci=P_==="win32",D_=1024,O_=(t,e)=>{if(!Ci)return re.unlink(t,e);let r=t+".DELETE."+mf(16).toString("hex");re.rename(t,r,i=>{if(i)return e(i);re.unlink(r,e)})},L_=t=>{if(!Ci)return re.unlinkSync(t);let e=t+".DELETE."+mf(16).toString("hex");re.renameSync(t,e),re.unlinkSync(e)},Yu=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,qc=class extends Ri{[dc]=!1;[ki]=!1;[Ms]=0;reservations=new C_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[dc]=!0,this[lc]()},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:D_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ci,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=X(Ne.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:R_():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[Hu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[lc](){this[dc]&&this[Ms]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[cc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,a]=Bc(r),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Ci&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Ne.posix.dirname(t.path),h=Ne.posix.normalize(Ne.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[Vu](t){let e=X(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=X(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[cc](t,"path")||!this[cc](t,"linkpath"))return!1;if(t.absolute=Ne.isAbsolute(t.path)?X(Ne.resolve(t.path)):X(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:X(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+Ru(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Ru(t.path.slice(o.length))}return!0}[Hu](t){if(!this[Vu](t))return t.resume();switch(h_.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[Tc](t);default:return this[$u](t)}}[Ge](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[_r](),e.resume())}[En](t,e,r){b_(X(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)}[Ii](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}[Ai](t){return Yu(this.uid,t.uid,this.processUid)}[Ti](t){return Yu(this.gid,t.gid,this.processGid)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Qs(String(t.absolute),{flags:Sf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&re.close(i.fd,()=>{}),i.write=()=>!0,this[Ge](u,t),e()});let o=1,a=u=>{if(u){i.fd&&re.close(i.fd,()=>{}),this[Ge](u,t),e();return}--o===0&&i.fd!==void 0&&re.close(i.fd,h=>{h?this[Ge](h,t):this[_r](),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,g=t.mtime;re.futimes(h,x,g,w=>w?re.utimes(u,x,g,S=>a(S&&w)):a())}if(typeof h=="number"&&this[Ii](t)){o++;let x=this[Ai](t),g=this[Ti](t);typeof x=="number"&&typeof g=="number"&&re.fchown(h,x,g,w=>w?re.chown(u,x,g,S=>a(S&&w)):a())}a()});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)}[Rc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[En](String(t.absolute),r,i=>{if(i){this[Ge](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[_r](),t.resume())};t.mtime&&!this.noMtime&&(o++,re.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ii](t)&&(o++,re.chown(String(t.absolute),Number(this[Ai](t)),Number(this[Ti](t)),a)),a()})}[$u](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Wu](t,e){let r=X(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ei](t,this.cwd,r,()=>this[$s](t,String(t.linkpath),"symlink",e),i=>{this[Ge](i,t),e()})}[Ku](t,e){let r=X(Ne.resolve(this.cwd,String(t.linkpath))),i=X(String(t.linkpath)).split("/");this[Ei](t,this.cwd,i,()=>this[$s](t,r,"link",e),o=>{this[Ge](o,t),e()})}[Ei](t,e,r,i,o){let a=r.shift();if(this.preservePaths||a===void 0)return i();let d=Ne.resolve(e,a);re.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new so(d,Ne.resolve(d,r.join("/"))));this[Ei](t,d,r,i,o)})}[Ju](){this[Ms]++}[_r](){this[Ms]--,this[lc]()}[Pc](t){this[_r](),t.resume()}[kc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ci}[Tc](t){this[Ju]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[ju](t,r))}[ju](t,e){let r=d=>{e(d)},i=()=>{this[En](this.cwd,this.dmode,d=>{if(d){this[Ge](d,t),r();return}this[ki]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=X(Ne.dirname(String(t.absolute)));if(d!==this.cwd)return this[En](d,this.dmode,u=>{if(u){this[Ge](u,t),r();return}a()})}a()},a=()=>{re.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Pc](t),r();return}if(d||this[kc](t,u))return this[lt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[lt](g??null,t,r);return h?re.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return re.rmdir(String(t.absolute),h=>this[lt](h??null,t,r))}if(t.absolute===this.cwd)return this[lt](null,t,r);O_(String(t.absolute),h=>this[lt](h??null,t,r))})};this[ki]?o():i()}[lt](t,e,r){if(t){this[Ge](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Cc](e,r);case"Link":return this[Ku](e,r);case"SymbolicLink":return this[Wu](e,r);case"Directory":case"GNUDumpDir":return this[Rc](e,r)}}[$s](t,e,r,i){re[r](e,String(t.absolute),o=>{o?this[Ge](o,t):(this[_r](),t.resume()),i()})}},_i=t=>{try{return[null,t()]}catch(e){return[e,null]}},Rf=class extends qc{sync=!0;[lt](t,e){return super[lt](t,e,()=>{})}[Tc](t){if(!this[ki]){let o=this[En](this.cwd,this.dmode);if(o)return this[Ge](o,t);this[ki]=!0}if(t.absolute!==this.cwd){let o=X(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[En](o,this.dmode);if(a)return this[Ge](a,t)}}let[e,r]=_i(()=>re.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Pc](t);if(e||this[kc](t,r))return this[lt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=a?_i(()=>{re.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[lt](d,t)}let[o]=_i(()=>re.rmdirSync(String(t.absolute)));this[lt](o,t)}let[i]=t.absolute===this.cwd?[]:_i(()=>L_(String(t.absolute)));this[lt](i,t)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{re.closeSync(o)}catch(h){u=h}(d||u)&&this[Ge](d||u,t),e()},o;try{o=re.openSync(String(t.absolute),Sf(t.size),r)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[Ge](d,t)),t.pipe(a)),a.on("data",d=>{try{re.writeSync(o,d,0,d.length)}catch(u){i(u)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{re.futimesSync(o,u,h)}catch(x){try{re.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Ii](t)){let u=this[Ai](t),h=this[Ti](t);try{re.fchownSync(o,Number(u),Number(h))}catch(x){try{re.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Rc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[En](String(t.absolute),r);if(i){this[Ge](i,t),e();return}if(t.mtime&&!this.noMtime)try{re.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ii](t))try{re.chownSync(String(t.absolute),Number(this[Ai](t)),Number(this[Ti](t)))}catch{}e(),t.resume()}[En](t,e){try{return S_(X(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}}[Ei](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let a=e;for(let d of r){a=Ne.resolve(a,d);let[u,h]=_i(()=>re.lstatSync(a));if(u)return i();if(h.isSymbolicLink())return o(new so(a,Ne.resolve(e,r.join("/"))))}i()}[$s](t,e,r,i){let o=`${r}Sync`;try{re[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[Ge](a,t)}}},N_=t=>{let e=new Rf(t),r=t.file,i=gf.statSync(r),o=t.maxReadSize||16*1024*1024;new ew(r,{readSize:o,size:i.size}).pipe(e)},M_=(t,e)=>{let r=new qc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{r.on("error",d),r.on("close",a),gf.stat(o,(u,h)=>{if(u)d(u);else{let x=new Oc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Pf=Pi(N_,M_,t=>new Rf(t),t=>new qc(t),(t,e)=>{e?.length&&df(t,e)}),B_=(t,e)=>{let r=new Uc(t),i=!0,o,a;try{try{o=st.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=st.openSync(t.file,"w+");else throw h}let d=st.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let g=0,w=0;g<512;g+=w){if(w=st.readSync(o,u,g,u.length-g,a+g),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let h=new Wn(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,F_(t,r,a,o,e)}finally{if(i)try{st.closeSync(o)}catch{}}},F_=(t,e,r,i,o)=>{let a=new Qu(t.file,{fd:i,start:r});e.pipe(a),U_(e,o)},z_=(t,e)=>{e=Array.from(e);let r=new ro(t),i=(o,a,d)=>{let u=(S,_)=>{S?st.close(o,v=>d(S)):d(null,_)},h=0;if(a===0)return u(null,0);let x=0,g=Buffer.alloc(512),w=(S,_)=>{if(S||_===void 0)return u(S);if(x+=_,x<512&&_)return st.read(o,g,x,g.length-x,h+x,w);if(h===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let v=new Wn(g);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>a||(h+=I+512,h>=a))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,st.read(o,g,0,512,h,w)};st.read(o,g,0,512,h,w)};return new Promise((o,a)=>{r.on("error",a);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",st.open(t.file,d,u);if(h||!x)return a(h);st.fstat(x,(g,w)=>{if(g)return st.close(x,()=>a(g));i(x,w.size,(S,_)=>{if(S)return a(S);let v=new Qs(t.file,{fd:x,start:_});r.pipe(v),v.on("error",a),v.on("close",o),q_(r,e)})})};st.open(t.file,d,u)})},U_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Tr({file:Df.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},q_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Tr({file:Df.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},yi=Pi(B_,z_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!cw(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")}),c2=Pi(yi.syncFile,yi.asyncFile,yi.syncNoFile,yi.asyncNoFile,(t,e=[])=>{yi.validate?.(t,e),G_(t)}),G_=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))};ln();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 oo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Of(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ao(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Lf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Nf(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}Jt();We();te();Oe();We();function kr(t,e){if(oo(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Di(t){return t.startsWith("http://")||t.startsWith("https://")}function Cr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as Q2}from"node:fs";import{dirname as tT,join as nT}from"node:path";import{fileURLToPath as iT}from"node:url";var Dt="0.2.6";We();te();var co="1008033",zf="1289";var Uf="pbbp2",qf="https://www.coze.cn",Gf="/api/coze_claw/resource/get_frontier_key",Y_="https://www.coze.cn",Z_="wss://frontier.coze.cn";function Rr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Y_}function Hf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Z_}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 Li(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Oi=q("handshake");async function Gc(t){let e=Rr(t.endpoint),r=t.timeoutMs??1e4,i=`${Cr(e)}${Gf}?aid=${encodeURIComponent(co)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),r);Oi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:a.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 T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${v.slice(0,200)}`)}let g=await u.json();if(g.code!==void 0&&g.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${g.code} msg=${g.msg??"-"} logid=${h}`);let w=g.data??{},S=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!S||!_){let v=JSON.stringify(g).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${v}`)}return Oi.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:S,deviceId:_}}catch(u){if(u instanceof T)throw Oi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Oi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let h=u.cause;throw Oi.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 T("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",Hc=15e4,jf=8192;function Kf(t){return{model:Wc(t.model)??Ot,...t.modelToken?{modelToken:t.modelToken}:{}}}function $f(t){return!t||t===Ot}var X_=new Set(["auto","\u81EA\u52A8"]);function Wc(t){let e=t?.trim();if(e)return X_.has(e.toLowerCase())?Ot:e}function Vf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=jc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Ot;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 $f(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Jf(t,e,r){let i={};if(t.modelToken?i.model=t.model||Ot:$f(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${jc}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},a=Kc(e,r);Object.keys(a).length>0&&(o.http_headers=a),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??Hc}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function Yf(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Kc(t,e){let{ttEnv:r,usePpe:i}=Li(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Zf(t,e,r){if(!t.modelToken)return{};let i=Kc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([a,d])=>`${a}:${d}`).join(`
92
+ `)}}function $c(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Vc(t){return t.model||Ot}function Wf(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 Xf(t,e,r,i){if(!t.modelToken)return null;let o=Vc(t),a=Kc(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[Wf(o,d,t.modelInfo?.contextWindow??Hc,t.modelInfo?.maxOutput??jf)],h=new Set([o]);for(let g of i??[])!g||h.has(g)||(h.add(g),u.push(Wf(g,["text"],Hc,jf)));let x={baseUrl:`${jc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(a).length>0&&(x.headers=a),x}var fe=q("agent-handlers"),e0=5*1024*1024,ry=1,iy=6,sy=new Set(["node_modules",".git",".coze","dist","build",".next"]),oy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,ay=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,cy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function dy(t){let e=t?.trim();return e?cy.test(e)||ay.test(e)?e:(fe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function ly(t){return new Promise((e,r)=>{let i=rt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,a=d=>{o||(o=!0,d?r(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",d=>a(d))})}var uo=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=$n(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ve(r).workspace,a=i?.skills??[],d=[],u=new Set;for(let h of a){let x=he(o,h.relPath,"SKILL.md");await td(x).then(w=>w.isFile()).catch(()=>!1)&&(d.push(py(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await u0(r,o,h),g=await f0(r,h);for(let w of[...x,...g])u.has(w.relPath)||(u.add(w.relPath),d.push(w.skill))}return{skills:d}}async addSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((h,x)=>[h.skillId,x])),u=[];for(let h of o){let x=await fo({agentId:r,workspace:i.workspace,framework:i.framework,skill:h});ho(a,d,x),u.push(h)}return await si(r,a),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??[]),a=i.skills??[],d=[];for(let u of a){if(!o.has(u.skillId)){d.push(u);continue}let h=he(i.workspace,u.relPath);await Zc(h,{recursive:!0,force:!0}),fe.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await si(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=$n(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");fe.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??Ve(r).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await fy(r,o,a,e.skillName,d);if(!u){let D=d?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${D}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:g}=u,w=he(h,"SKILL.md"),S=new rd.default;S.addLocalFolder(h,g);let _=S.toBuffer();if(_.length>t0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${t0}`);let v=await lo(w,{encoding:"utf8"}).then(D=>d0(D).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):fe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let A=I.version??"v1.0",k=I.skillId??e.skillId??c0(r,x);if(i&&!d){let D=i.skills??[],b=D.find(C=>C.relPath===x);b?(b.version=A,b.skillId=k):D.push({skillId:k,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await si(r,D)}return fe.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:k,version:A}),{ok:!0,skillId:k,version:A}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,a]of i.sessions){if(!a.downstream)continue;let d=a.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,fe.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let h=a.downstream;a.downstream=void 0,fe.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),h.stop(r).catch(x=>fe.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return fe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Te(r);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return fe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await ur(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw fe.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Fe(i),fe.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 T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Te(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Di(e.registry)&&o.push(`--registry=${e.registry}`);let a=dy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&oy.test(d)&&o.push("--env",d);let u=await ly(o);return fe.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:a,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 T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Te(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Fe(i),fe.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}):(fe.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new T("IPC_BAD_REQUEST",`${ut.DELETE}: missing agentId`);let i=await Te(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let d=Ve(r);return a==="cloud"?await Zc(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Fe(i)),fe.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(kr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Wc(e.model)??Ot,i=await Te(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Fe(i),fe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return fe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let a=o.model;o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,a).catch(u=>fe.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,h]of o.allSessionQueues())d.push(h.enqueue(async()=>{let x=o.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${r}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),fe.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(kr(e._meta,ut.RESET),!e.agentId)throw new T("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,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),fe.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let a of i.sessions.values())a.acpSessionId=void 0,a.replySeq=0,a.loadingSession=!1,a.spawnFailCount=void 0,a.spawnFailedAt=void 0;let o=new Map;for(let[a,d]of i.sessions)o.set(a,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ii(e,o)}async clearPersistedAcpSessionIds(e){let r=await Te(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 Fe(r)}async repairAgent(e){if(kr(e._meta,ut.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ut.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${ut.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){fe.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,r,i){if(!this.opts.detailSyncer){fe.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){fe.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){kr(e._meta,"_agent/getFileTree");let r=e._meta,i=$n(r),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),u=await Jc(d).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${a}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await ri(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let h=Ty(e.depth);return u.isDirectory()?{tree:await Ay(o,d,a,h)}:{tree:[{name:ky(a),path:p0(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){kr(e._meta,"_agent/getFileContent");let r=$n(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new T("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),a=await Jc(o).catch(()=>null);if(!a||!a.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await ri(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>e0)throw new T("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${e0})`);let d=await lo(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:a.size}:{content:d.toString("utf8"),encoding:"utf-8",size:a.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await Te(e).catch(()=>null))?.workspace??Ve(e).workspace}safeJoin(e,r){let i=Qc(e,r||"."),o=nd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${r0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Te(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function o0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new T("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new T("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function id(t){return t==="claude-code"?he(".claude","skills"):he(".agents","skills")}function a0(t){let e=ey();return t==="claude-code"?[he(e,".claude","skills")]:t==="codex"?[he(e,".agents","skills"),he(e,".codex","skills")]:[he(e,".agents","skills"),he(e,".openclaw","skills")]}async function uy(t,e,r,i){let o=async a=>td(he(a,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let a=he(id(e),r),d=he(t,a);return await o(d)?{absDir:d,relPath:a}:null}for(let a of a0(e)){let d=he(a,r);if(await o(d))return{absDir:d,relPath:d}}return null}async function fy(t,e,r,i,o){let a=o0(i),d=await uy(e,r,a,o);if(d)return{...d,dirName:a};let h=(o?await f0(t,r):await u0(t,e,r)).filter(w=>w.skill.skillName===i);if(h.length>1)throw new T("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(w=>Qf(w.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=h[0];return x?{absDir:o?x.relPath:he(e,x.relPath),relPath:x.relPath,dirName:Qf(x.relPath)}:null}function c0(t,e){return(Q_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function d0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
93
  ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
94
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function u0(t,e,r,i){let o=await r0(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 td(ge(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,x=ge(r,f),g=ge(e,f,"SKILL.md"),m=await lo(g,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let S=l0(m);c.push({relPath:x,skill:{skillId:d0(t,x),skillName:S.name||f,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function f0(t,e,r){let i=id(r);return u0(t,ge(e,i),i,!1)}async function h0(t,e){let r=[],i=new Set;for(let o of c0(e)){let c=await u0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var hy=3e4,xy=50*1024*1024,n0=10*1024*1024,Pr=3e4;async function fo(t){let{agentId:e,workspace:r,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=a0(o.skillName),f=id(i),x=ge(f,u),g=ge(r,x);if(await Zc(g,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Ni(S.length),await Xc(ge(g,"SKILL.md"),S,"utf8")}else{let S=await my(o.downloadUrl);_y(S)?await vy(S,g):yy(S)?await Ey(S,g):await Xc(ge(g,"SKILL.md"),S.toString("utf8"),"utf8")}let m={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 pe.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),m}function ho(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 py(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 gy(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 x0(t,e){let r=await Re(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Ot,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((g,m)=>[g.skillId,m])),u=c.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Ue(r,e),{status:"noop",count:0};let f=0,x=0;for(let g of u)try{await Yc(ge(r.workspace,g.relPath),{recursive:!0,force:!0});let m=await fo({agentId:t,workspace:r.workspace,framework:r.framework,skill:gy(g)});ho(c,d,m),f+=1}catch(m){x+=1,pe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(m)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Ue(r,e),pe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function my(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ni(e);let r=wy(t);return Ni(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await lo(e);return Ni(r.length),r}if(Di(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),hy);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 Ni(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 Ni(t){if(t>xy)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function wy(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 _y(t){return t.length>=2&&t[0]===31&&t[1]===139}function yy(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 ed(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Ey(t,e){let r,i;try{r=new rd.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||ed(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=by(i),c=Qc(e);for(let d of i){if(ed(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Qc(e,u),x=nd(c,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Zc(f,{recursive:!0});continue}await Zc(ty(f),{recursive:!0});let g;try{g=d.getData()}catch(m){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${m.message}`,{cause:m})}await Xc(f,g)}}function by(t){let e;for(let r of t){let i=r.entryName;if(!i||ed(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 vy(t,e){await Sy(t);let r=Df({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`))},Pr);try{await o0(s0.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Sy(t){let e=[],r=kr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`))},Pr);try{await o0(s0.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Pr}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 Iy=5e3;async function Ay(t,e,r,i){return p0(t,e,r,i,{count:0})}async function p0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await r0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(sy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Iy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=ge(e,u.name),x=ny(ge(r,u.name)),g=null;try{g=await Jc(f)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let m={name:u.name,path:g0(nd(t,f)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(m.children=await p0(t,f,x,i-1,o)),d.push(m)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function ky(t){return!t||t<=0?ry:Math.min(t,iy)}function Ty(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function g0(t){return t.split(i0).join("/")}ne();var In=W("agent-health-reporter"),Cy=1e4,Ry=3,Mi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Cy,this.livenessFailureThreshold=e.livenessFailureThreshold??Ry}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=Py(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:Ot,_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 Py(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}ln();import{mkdir as ld,rm as vE,stat as SE}from"node:fs/promises";import{homedir as IE}from"node:os";import{join as K0}from"node:path";an();import{existsSync as jy}from"node:fs";import{release as Wy}from"node:os";import{basename as Ky,isAbsolute as $y}from"node:path";function Bi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Dr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Or(t,e){return{jsonrpc:"2.0",id:t,result:e}}function An(t,e){return{jsonrpc:"2.0",id:t,error:e}}$e();var xo=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 m0(t){return"method"in t&&"id"in t&&t.id!==void 0}function w0(t){return"method"in t&&!("id"in t)}function po(t){return!("method"in t)&&"id"in t}var Dy={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 Oy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Fi(t.message)}:typeof t=="string"?Fi(t):typeof t=="object"?Ny(t):t}var Ly=[[/\/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 Fi(t){let e=t;for(let[r,i]of Ly)e=e.replace(r,i);return e}function Ny(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Fi(i):e[r]=i;return e}function zi(t){if(t instanceof k){let e=Oy(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:Dy[t.code]??Y.INTERNAL_ERROR,message:Fi(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:Fi(t instanceof Error?t.message:String(t))}}function _0(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 E0(t){return`${JSON.stringify(t)}
95
- `}var y0=10*1024*1024,go=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>y0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${y0} bytes`)}),[]}let r=this.buffer.split(`
96
- `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var v0={"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"},Bk=Object.fromEntries(Object.entries(v0).map(([t,e])=>[e,t])),My={"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:[]},Lr=class{seq=0;next(e,r){this.seq+=1;let i=v0[e]??By(e),o=My[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>b0(r?.[f]??"")),u=Fy(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>b0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function By(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function b0(t){return t.replace(/[:_\s]+/g,"-")}function Fy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}dn();import{readFileSync as zy}from"node:fs";var Uy=384;async function sd(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await lr(t.agentEnvFile,r,{mode:Uy})}function od(t){try{let e=JSON.parse(zy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function S0(t,e,r={},i=o=>o){return{...i({...t,...od(e)}),...r}}Jt();sr();$e();ne();Me();import{execFileSync as qy,spawnSync as Gy}from"node:child_process";function Ui(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 r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Gy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ad=new Set;function I0(t){typeof t=="number"&&t>0&&ad.add(t)}function A0(t){typeof t=="number"&&ad.delete(t)}function k0(){for(let t of ad)qi(t,"SIGKILL")}var Nr="coze-bridge-daemon";function T0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return qy("pgrep",["-U",String(o),"-f",Nr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function C0(t,e){if(t.length===0)return;let r=e?.killFn??qi,i=e?.isAliveFn??Ui,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 Hy=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function R0(t,e){if(!e)return null;for(let r of Hy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function P0(t,e){return R0(t,e)}function D0(t,e){return R0(t,e)}function Mr(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 O0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,g=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Mr(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:Mr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Mr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Mr(c,!1,e)}}var L0=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Vy=200,Jy=40,Zy=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Yy=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Xy=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Qy=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),eE=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),tE=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),N0=500;function nE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=N0?t:`${e.slice(0,N0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function rE(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 M0(t){try{return jy(t)}catch{return}}function iE(t,e){return{platform:process.platform,osRelease:Wy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:$y(e.command)?M0(e.command):void 0,cwd:e.cwd,cwdExists:M0(e.cwd),envKeys:e.envKeys}}function sE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ky(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Nt=class{constructor(e){this.opts=e;this.log=W(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new go({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Lr;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=S0(process.env,this.opts.agentEnvFile??ee().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,I0(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>Vy&&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,A0(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=iE(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",sE(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()));qi(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||qi(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:eE,phase2GateMs:Zy,livenessWindowMs:Yy,absoluteMaxMs:Xy,approvalMaxMs:tE,suspendThresholdMs:Qy,...r};return this.call("session/prompt",e,L0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Dr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Or(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=L0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Bi(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,x)=>{let g={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),S={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:Mr(0,!1,o),sessionId:u};g.promptTimeout=S;let y=()=>{let b={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=O0(b,S.cfg,I),T=D=>{S.armedAt=I,S.expectedIntervalMs=D,g.timer=setTimeout(y,D)};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`)))};g.timer=setTimeout(y,S.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}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(d)}catch(m){g.timer&&clearTimeout(g.timer),this.pending.delete(c),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(E0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(po(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:nE(e.result)}),r.resolve(e.result));return}if(w0(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(m0(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,zi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=_0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=D0(this.framework,rE(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(Jy).join(`
98
- `),o=P0(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 oE(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 mo=class extends Nt{framework="claude-code";constructor(e){let{command:r,args:i}=ni("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 oE(e)}};an();import{mkdtempSync as aE,rmSync as cE}from"node:fs";import{tmpdir as dE}from"node:os";import{join as lE}from"node:path";var B0=["default","acceptEdits","plan","auto","bypassPermissions"],F0=["read-only","auto","full-access"];function Mt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return B0.includes(e);case"codex":return F0.includes(e);case"openclaw":return!1}}function wo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function z0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function cd(t){switch(t){case"claude-code":return B0.join("/");case"codex":return F0.join("/");case"openclaw":return""}}var _o=class extends Nt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ni("codex",e.command,i),d=e.isolateCodexHome?aE(lE(dE(),"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)?wo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(uE(r)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{cE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function uE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=z0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}$e();var fE=3e4,Br=class extends Nt{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}`}]},fE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};dn();$e();ne();Me();function dd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}an();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 yo=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)Gi(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 Gi(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 U0}from"node:fs";import{access as hE}from"node:fs/promises";import{delimiter as xE,join as pE}from"node:path";var St=W("framework-detector"),q0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},gE=[".exe",".cmd",".bat",".ps1"],Vn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??hE}}async detect(e){let r=q0[e],i=await this.which(r);if(!i)return St.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(q0).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(xE).filter(Boolean),i=this.env.platform==="win32"?["",...gE]:[""];for(let o of r)for(let c of i){let d=pE(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?U0.F_OK:U0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return St.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return St.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return St.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return St.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(St.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(St.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return St.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return St.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||St.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){St.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(wE(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",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},mE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function wE(t){return t.replace(mE,"")}import{homedir as _E}from"node:os";import{join as yE}from"node:path";dn();Jt();sr();$e();ne();async function j0(){let t=yE(_E(),".openclaw/openclaw.json");return dr(t)}async function W0(){return(await j0())?.gateway?.auth?.token??""}var G0=W("openclaw.config"),EE=[0,5e3,5e3],bE=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),H0="models.providers.",Eo="agents.defaults.models",bo=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??EE,this.cliTimeoutMs=e.cliTimeoutMs??bE}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,G0.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=x=>{d||(d=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?r():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",r],["Config path not found","Nothing was changed"])))}catch(i){G0.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",`${H0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${H0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Eo}[${e}]`,()=>this.runCli(["config","set",Eo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Eo}[${e}]`,`${Eo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await j0())?.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=W("agent-manager"),fd="acceptEdits",J0="full-access",Z0="read-only";function AE(t){return{INITIAL_AGENT_MODE:wo(t)}}var kE=(t,e,r,i,o,c,d,u,f,x)=>{switch(t){case"claude-code":{let g={...o?{...Jf(o),...Xf(o,d,u)}:{},...f??{},IS_SANDBOX:"1"};return new mo({cwd:r,env:g,agentId:i})}case"codex":{let g=J0;x!==void 0&&(Mt("codex",x)?g=x:ue.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let m=!!o,S={...o?{...Yf(o),...Zf(o,d,u)}:{},...AE(g),...m?{NO_BROWSER:"1"}:{},...f??{}};return new _o({cwd:r,agentId:i,...Object.keys(S).length>0?{env:S}:{},...m?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Br({command:e,cwd:r,agentId:i,...c?{sessionName:dd(c)}:{}})}};function ud(t){return t==="claude-code"||t==="codex"}function TE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(CE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
94
+ `)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!a||!a[2])continue;let d=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function l0(t,e,r,i){let o=await n0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let a=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await td(he(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=he(r,h),g=he(e,h,"SKILL.md"),w=await lo(g,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let S=d0(w);a.push({relPath:x,skill:{skillId:c0(t,x),skillName:S.name||h,...S.description?{description:S.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function u0(t,e,r){let i=id(r);return l0(t,he(e,i),i,!1)}async function f0(t,e){let r=[],i=new Set;for(let o of a0(e)){let a=await l0(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var hy=3e4,xy=50*1024*1024,t0=10*1024*1024,Pr=3e4;async function fo(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let a=typeof o.content=="string"&&o.content.length>0,d=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!a&&!d)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=o0(o.skillName),h=id(i),x=he(h,u),g=he(r,x);if(await Yc(g,{recursive:!0}),a){let S=Buffer.from(o.content,"utf8");Ni(S.length),await Xc(he(g,"SKILL.md"),S,"utf8")}else{let S=await my(o.downloadUrl);_y(S)?await vy(S,g):yy(S)?await Ey(S,g):await Xc(he(g,"SKILL.md"),S.toString("utf8"),"utf8")}let w={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return fe.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:a?"content":"downloadUrl"}),w}function ho(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 py(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 gy(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 h0(t,e){let r=await Te(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Dt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Fe(r,e),{status:"seeded",count:0};let a=[...r.skills??[]],d=new Map(a.map((g,w)=>[g.skillId,w])),u=a.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Fe(r,e),{status:"noop",count:0};let h=0,x=0;for(let g of u)try{await Zc(he(r.workspace,g.relPath),{recursive:!0,force:!0});let w=await fo({agentId:t,workspace:r.workspace,framework:r.framework,skill:gy(g)});ho(a,d,w),h+=1}catch(w){x+=1,fe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(w)})}return r.skills=a,x===0&&(r.skillsRefreshedForVersion=i),await Fe(r,e),fe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function my(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ni(e);let r=wy(t);return Ni(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await lo(e);return Ni(r.length),r}if(Di(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),hy);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new T("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Ni(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new T("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ni(t){if(t>xy)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function wy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new T("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 _y(t){return t.length>=2&&t[0]===31&&t[1]===139}function yy(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 ed(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Ey(t,e){let r,i;try{r=new rd.default(t),i=r.getEntries()}catch(d){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||ed(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=by(i),a=Qc(e);for(let d of i){if(ed(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=Qc(e,u),x=nd(a,h);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Yc(h,{recursive:!0});continue}await Yc(ty(h),{recursive:!0});let g;try{g=d.getData()}catch(w){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await Xc(h,g)}}function by(t){let e;for(let r of t){let i=r.entryName;if(!i||ed(i))continue;let o=i.indexOf("/");if(o<=0)return;let a=i.slice(0,o+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function vy(t,e){await Sy(t);let r=Pf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`))},Pr);try{await s0(i0.from(t),r)}catch(a){throw a instanceof T?a:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Pr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function Sy(t){let e=[],r=Tr({onReadEntry:a=>{let d=a.path,u=a.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`))},Pr);try{await s0(i0.from(t),r)}catch(a){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Pr}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Iy=5e3;async function Ay(t,e,r,i){return x0(t,e,r,i,{count:0})}async function x0(t,e,r,i,o){if(i<=0)return[];let a;try{a=await n0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if(sy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Iy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=he(e,u.name),x=ny(he(r,u.name)),g=null;try{g=await Jc(h)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let w={name:u.name,path:p0(nd(t,h)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(w.children=await x0(t,h,x,i-1,o)),d.push(w)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function Ty(t){return!t||t<=0?ry:Math.min(t,iy)}function ky(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function p0(t){return t.split(r0).join("/")}te();var In=q("agent-health-reporter"),Cy=1e4,Ry=3,Mi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Cy,this.livenessFailureThreshold=e.livenessFailureThreshold??Ry}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=Py(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),r.push(h)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Dt,_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 a=o?.authFailures;if(a&&a.length>0&&(In.warn("heartbeat received authFailures from cloud",{count:a.length,agentIds:a.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(a)}catch(d){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 Py(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}ln();import{mkdir as ld,rm as CE,stat as RE}from"node:fs/promises";import{homedir as PE}from"node:os";import{join as K0}from"node:path";an();import{existsSync as jy}from"node:fs";import{release as Wy}from"node:os";import{basename as Ky,isAbsolute as $y}from"node:path";function Bi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Dr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Or(t,e){return{jsonrpc:"2.0",id:t,result:e}}function An(t,e){return{jsonrpc:"2.0",id:t,error:e}}We();var xo=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 g0(t){return"method"in t&&"id"in t&&t.id!==void 0}function m0(t){return"method"in t&&!("id"in t)}function po(t){return!("method"in t)&&"id"in t}var Dy={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 Oy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Fi(t.message)}:typeof t=="string"?Fi(t):typeof t=="object"?Ny(t):t}var Ly=[[/\/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 Fi(t){let e=t;for(let[r,i]of Ly)e=e.replace(r,i);return e}function Ny(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Fi(i):e[r]=i;return e}function zi(t){if(t instanceof T){let e=Oy(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:Dy[t.code]??Y.INTERNAL_ERROR,message:Fi(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:Fi(t instanceof Error?t.message:String(t))}}function w0(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,a=t.data;if(i&&e){let{message:d,...u}=e;a=u}return new T(r,o,{retriable:e?.retriable??!1,cause:a})}function y0(t){return`${JSON.stringify(t)}
95
+ `}var _0=10*1024*1024,go=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>_0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${_0} bytes`)}),[]}let r=this.buffer.split(`
96
+ `);this.buffer=r.pop()??"";let i=[];for(let o of r){let a=o.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(d){this.onError?.({line:a,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var b0={"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"},HT=Object.fromEntries(Object.entries(b0).map(([t,e])=>[e,t])),My={"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:[]},Lr=class{seq=0;next(e,r){this.seq+=1;let i=b0[e]??By(e),o=My[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(h=>E0(r?.[h]??"")),u=Fy(d).join(":");u&&a.push(u)}else r&&Object.values(r).some(d=>d)&&a.push(Object.values(r).filter(Boolean).map(d=>E0(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function By(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function E0(t){return t.replace(/[:_\s]+/g,"-")}function Fy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}dn();import{readFileSync as zy}from"node:fs";var Uy=384;async function sd(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await lr(t.agentEnvFile,r,{mode:Uy})}function od(t){try{let e=JSON.parse(zy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function v0(t,e,r={},i=o=>o){return{...i({...t,...od(e)}),...r}}Jt();sr();We();te();Oe();import{execFileSync as qy,spawnSync as Gy}from"node:child_process";function Ui(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 r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Gy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ad=new Set;function S0(t){typeof t=="number"&&t>0&&ad.add(t)}function I0(t){typeof t=="number"&&ad.delete(t)}function A0(){for(let t of ad)qi(t,"SIGKILL")}var Nr="coze-bridge-daemon";function T0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return qy("pgrep",["-U",String(o),"-f",Nr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function k0(t,e){if(t.length===0)return;let r=e?.killFn??qi,i=e?.isAliveFn??Ui,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<a&&t.some(h=>i(h));u+=d)await o(Math.min(d,a-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var Hy=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function C0(t,e){if(!e)return null;for(let r of Hy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function R0(t,e){return C0(t,e)}function P0(t,e){return C0(t,e)}function Mr(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 D0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,g=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Mr(g,t.firstFrameSeen,e)}}let a=r-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return a>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?a<e.phase2GateMs?{action:"continue",rearmMs:Mr(a,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Mr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Mr(a,!1,e)}}var O0=$e("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Vy=200,Jy=40,Yy=$e("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Zy=$e("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Xy=$e("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Qy=$e("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),eE=$e("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),tE=$e("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),L0=500;function nE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=L0?t:`${e.slice(0,L0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function rE(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 N0(t){try{return jy(t)}catch{return}}function iE(t,e){return{platform:process.platform,osRelease:Wy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:$y(e.command)?N0(e.command):void 0,cwd:e.cwd,cwdExists:N0(e.cwd),envKeys:e.envKeys}}function sE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ky(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Lt=class{constructor(e){this.opts=e;this.log=q(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new go({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Lr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=v0(process.env,this.opts.agentEnvFile??Q().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=rt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,S0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let a of this.decoder.push(o))this.dispatch(a)}catch(a){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(a)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let a=o.trimEnd();this.stderrRing.push(a),this.stderrRing.length>Vy&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,a)=>{this.stopped=!0,I0(i.pid),(o!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:a,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,a));for(let u of this.exitHandlers)u(o,a)}),i.on("error",o=>{let a=o,d=iE(a,{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 T("AGENT_SPAWN_FAILED",sE(a,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(a=>r.once("exit",()=>a()));qi(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||qi(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:eE,phase2GateMs:Yy,livenessWindowMs:Zy,absoluteMaxMs:Xy,approvalMaxMs:tE,suspendThresholdMs:Qy,...r};return this.call("session/prompt",e,O0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Dr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Or(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=O0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=Bi(a,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let h=r.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let g={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),S={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Mr(0,!1,o),sessionId:u};g.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=D0(v,S.cfg,I),k=D=>{S.armedAt=I,S.expectedIntervalMs=D,g.timer=setTimeout(_,D)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),k(A.rearmMs);return}if(A.action==="continue"){k(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),x(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),x(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(_,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(g.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,g);try{this.writeFrame(d)}catch(w){g.timer&&clearTimeout(g.timer),this.pending.delete(a),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(y0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(po(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 T("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:nE(e.result)}),r.resolve(e.result));return}if(m0(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(g0(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 a=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!a)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(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,zi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=w0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=P0(this.framework,rE(e));return i?new T(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 T("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(Jy).join(`
98
+ `),o=R0(this.framework,i);return o?new T(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new T("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 oE(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 mo=class extends Lt{framework="claude-code";constructor(e){let{command:r,args:i}=ni("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 oE(e)}};an();import{mkdtempSync as aE,rmSync as cE}from"node:fs";import{tmpdir as dE}from"node:os";import{join as lE}from"node:path";var M0=["default","acceptEdits","plan","auto","bypassPermissions"],B0=["read-only","auto","full-access"];function Nt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return M0.includes(e);case"codex":return B0.includes(e);case"openclaw":return!1}}function wo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function F0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function cd(t){switch(t){case"claude-code":return M0.join("/");case"codex":return B0.join("/");case"openclaw":return""}}var _o=class extends Lt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:a}=ni("codex",e.command,i),d=e.isolateCodexHome?aE(lE(dE(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,h={command:o,args:a,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(h),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=Nt("codex",e.modeId)?wo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(uE(r)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{cE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function uE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=F0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}We();var fE=3e4,Br=class extends Lt{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}`}]},fE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};dn();We();te();Oe();function dd(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((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 yo=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 Tn,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)Gi(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 Gi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Yt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Jt();te();import{constants as z0}from"node:fs";import{access as hE}from"node:fs/promises";import{delimiter as xE,join as pE}from"node:path";var vt=q("framework-detector"),U0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},gE=[".exe",".cmd",".bat",".ps1"],Vn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??rt,access:e.access??hE}}async detect(e){let r=U0[e],i=await this.which(r);if(!i)return vt.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(U0).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(xE).filter(Boolean),i=this.env.platform==="win32"?["",...gE]:[""];for(let o of r)for(let a of i){let d=pE(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?z0.F_OK:z0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return vt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return vt.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 vt.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 vt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=o.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(vt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(vt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return vt.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 vt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||vt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},a=r.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){vt.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&&(wE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",a=!1,d,u=h=>{a||(a=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{o+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},mE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function wE(t){return t.replace(mE,"")}import{homedir as _E}from"node:os";import{join as yE}from"node:path";dn();Jt();sr();We();te();async function H0(){let t=yE(_E(),".openclaw/openclaw.json");return dr(t)}async function j0(){return(await H0())?.gateway?.auth?.token??""}var q0=q("openclaw.config"),EE=[0,5e3,5e3],bE=$e("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),G0="models.providers.",Eo="agents.defaults.models",bo=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new Tn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??EE,this.cliTimeoutMs=e.cliTimeoutMs??bE}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let a=this.retryDelaysMs[o]??0;a>0&&await new Promise(d=>setTimeout(d,a));try{return await r()}catch(d){i=d,q0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=rt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};o.stderr?.on("data",x=>{a+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?r():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(a=>o.includes(a)))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){q0.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",`${G0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${G0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Eo}[${e}]`,()=>this.runCli(["config","set",Eo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Eo}[${e}]`,`${Eo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await H0())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,a=[];for(let d of Object.keys(i))d.startsWith(o)&&a.push(d.slice(o.length));return a}ensureAgent(e,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"])))}};import{readFile as vE,writeFile as SE}from"node:fs/promises";import{join as IE}from"node:path";var AE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
99
+ `),TE=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
100
+ `);function kE(t){return t.length===0?t:`${(t.endsWith(`
101
+ `)?t.slice(0,-1):t).split(`
102
+ `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
99
103
  `)}
100
- `}function CE(t){if(t.includes(`
101
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var RE={path:"",version:"cloud-deployed"},$0="openclaw_gateway_unavailable",PE="openclaw_default_agent_missing";function V0(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 DE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},OE=6e4,vo=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??kE,this.createTimeoutMs=e.createTimeoutMs??OE,this.detectorFactory=e.detectorFactory??(()=>new Vn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new bo({command:r})),this.openclawConfigDir=e.openclawConfigDir??K0(IE(),".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=K0(e,".env");if(await SE(r).then(c=>c.isFile()).catch(()=>!1)){ue.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=TE({...process.env,...od(this.paths.agentEnvFile)});await cn(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 Re(e.agentId,this.paths).catch(()=>null),o=oo(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 Re(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 Re(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])throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ze(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",g;x&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??m??u.workspace,y=new AbortController,b=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&ud(e.framework)&&await cr(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 ld(u.root,{recursive:!0}),await ld(S,{recursive:!0}),await ld(u.logs,{recursive:!0}),T(),x||await ur(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Oa(S,"cloud"):await Oa(S,"local",fd)),T();let D=i,E=$f({model:e.model??D?.model}),R=Lf(e._meta)??D?.accountId,O=e.patToken??D?.patToken,F=f==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new yo({agentId:e.agentId,framework:e.framework,workspace:S,model:E.model??Lt,deployType:f,...R?{accountId:R}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",D?.sessions){let J=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,oe]of Object.entries(D.sessions)){let ae={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};J?oe.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",ue.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:ae.permissionMode})):Mt(e.framework,oe.permissionMode)?ae.permissionMode=oe.permissionMode:ue.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&ue.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),oe.cozeGroupId&&(ae.cozeGroupId=oe.cozeGroupId),I.sessions.set(X,ae)}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 B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:E.model};f==="cloud"&&(B.deployType="cloud"),R&&(B.accountId=R),O&&(B.patToken=O),F&&(B.modelInfo=F),D?.skills&&(B.skills=D.skills),D?.agentName&&(B.agentName=D.agentName),D?.description&&(B.description=D.description),B.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):ue.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let Z=e.initialSkills??[];if(Z.length>0){let J=[...B.skills??[]],re=new Map(J.map((ae,P)=>[ae.skillId,P])),X=await Promise.allSettled(Z.map(ae=>fo({agentId:e.agentId,workspace:S,framework:e.framework,skill:ae}))),oe=0;for(let[ae,P]of X.entries()){let q=Z[ae];q&&(P.status==="fulfilled"?(ho(J,re,P.value),oe++):ue.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:q.skillId,skillName:q.skillName,err:String(P.reason)}))}oe>0&&(B.skills=J,ue.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:Z.length}))}return await Ue(B,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:S,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)),await vE(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(b)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&ud(e.framework))u=RE;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);ud(e.framework)&&!hs(e.framework)&&(ue.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await cr(e.framework));let f=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:f,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else{let g=e.sessions.get(i),m=Zt(e)?g?.permissionMode??J0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),m)}try{return await x.start(),await x.initialize(DE),x}catch(g){let m=x instanceof Nt?x.getStderrTail():[];throw m.length>0&&ue.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:m}),await x.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",V0(o),{cause:{reason:$0}})}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:PE}})}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",V0(r),{cause:{reason:$0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,f=dd(o);if(r.deployType==="local"){let m=await this.ensureOpenclawDefaultAgent();return new Br({command:u,cwd:m.workspace,agentId:m.id,sessionName:f})}let x=await W0(),g;if(i?.modelToken){let m=$c(o),S=Vc(i),y=`${m}/${S}`;if(!this.ensuredProviders.has(y)){let b=this.getOpenclawConfig(),I=await b.getAllowlistModelsForProvider(m),A=Qf(i,c,d,I);A&&(await b.ensureProvider(m,A),await b.addModelToAllowlist(y),this.ensuredProviders.add(y))}g=y}return new Br({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...x?{gatewayToken:x}:{},...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=$c(c),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(x){f=!1,ue.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,ue.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as th}from"node:crypto";import{promises as UE}from"node:fs";import{basename as nh}from"node:path";$e();ne();import{promises as LE}from"node:fs";import{basename as NE}from"node:path";var Y0=W("file-upload"),ME="/api/coze_claw/file/agent_upload",BE=6e4;async function X0(t,e={}){let i=`${Cr(Rr(e.handshakeBase))}${ME}`,o=e.timeoutMs??BE,c=await LE.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,x=setTimeout(()=>f.abort(),o);Y0.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}),m=g.headers.get("x-tt-logid")??"";if(!g.ok){let b=await g.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${m}: ${b.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${m}`);let y=S.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(S).slice(0,200)}`);return Y0.info("file upload ok",{uri:y,logid:m}),{uri:y}}catch(g){throw g instanceof k?g:g.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${NE(t.path)}`):new k("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}$e();ne();import{extname as FE}from"node:path";var zE={".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 Q0(t){let e=FE(t).toLowerCase();return zE[e]??"application/octet-stream"}Me();var So=W("agent-send"),eh=50*1024*1024;function rh(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 ih(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(x){u=x,f<2&&(So.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function sh(t,e){let{session:r,runtime:i}=rh(e.core,t.agentId,t.sessionId);if(!await ri(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await UE.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>eh)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${eh}`);let c=await Q0(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??nh(t.path),u;try{u=await X0({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw So.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 f={sessionUpdate:"agent_file",messageId:th(),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 ih(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),So.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 oh(t,e){let{session:r,runtime:i}=rh(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??nh(t.path),c={sessionUpdate:"group_file",messageId:th(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ih(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),So.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 ah(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}an();Jt();ne();var Bt=W("coze-cli-installer"),ch="@coze/cli@latest",qE="coze",dh="0.1.8",GE=5e3,HE=5e3,jE=9e4,lh=1e4,Hi=null,Io=!1;async function xd(t,e={}){if(Io)return;if(Hi)return Hi;let r=e.exec??zf;return Hi=(async()=>{try{let i=await WE(qE,r),o=!1;if(i){let d=await KE(r);if(d===void 0)Bt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(ah(d,dh))Bt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:dh}),o=!0;else{Bt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Io=!0;return}}let c=o?"upgrade-only":"full";Bt.info("coze-cli install start",{package:ch,mode:c});try{await r("npm",["i","-g","--prefer-online",ch],{timeout:jE,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){Io=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:lh}),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:lh}),Bt.info("coze auth login ok")}catch(d){Bt.warn("coze auth login failed",{err:String(d)});return}Io=!0}finally{Hi=null}})(),Hi}async function WE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:GE});return Pa(i)}catch{return}}async function KE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:HE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}dn();Me();var $E=10*6e4;function uh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?$E:e}function Ao(t){return dr(t??ee().configFile)}function ji(t,e){return lr(e??ee().configFile,t)}import{randomBytes as hb}from"node:crypto";sr();$e();ne();import{createReadStream as VE}from"node:fs";import{mkdir as JE,readFile as ZE,realpath as YE,stat as XE,writeFile as QE}from"node:fs/promises";import{basename as eb,dirname as pd,isAbsolute as tb,join as nb,relative as rb,resolve as fh,sep as ib}from"node:path";import{createInterface as sb}from"node:readline";var xh=W("fs-rpc"),Wi=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function ph(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Wi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Wi} bytes`);let i=await mh(t.path,e);return await JE(pd(i),{recursive:!0}),await QE(i,t.content,"utf8"),xh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function gh(t,e){let r=await mh(t.path,e),i=await XE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Wi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Wi} bytes`);let c;if(o&&i.size>Wi)c=await ob(r,t.line??1,t.limit);else{let d=await ZE(r,"utf8");if(o){let u=d.split(`
102
- `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
103
- `)}else c=d}return xh.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function ob(t,e,r){let i=sb({input:VE(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(`
104
- `)}async function mh(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([hh(fh(e)),hh(fh(t))]),o=rb(r,i);if(ab(o,ib,tb(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function ab(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function hh(t){let e=[],r=t;for(;r!==pd(r);)try{let i=await YE(r);return e.length?nb(i,...e.reverse()):i}catch{e.push(eb(r)),r=pd(r)}return t}ne();var wh=W("prompt-multimodal"),_h=10*1024*1024,cb=15e3,db=6;async function yh(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 lb(d))}}let o=Array.from({length:Math.min(db,t.length)},()=>i());return await Promise.all(o),e}function Eh(t){return t.some(e=>e.type==="image")}async function lb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Di(e.uri))return t;try{let{buf:r,contentType:i}=await fb(e.uri),o=e.mimeType||ub(i)||"application/octet-stream";return wh.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 wh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function ub(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function fb(t){let e=new AbortController,r=setTimeout(()=>e.abort(),cb);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>_h)throw new Error(`image too large: ${o.byteLength} bytes (max ${_h})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}ln();$e();ne();var V=W("core"),xb=3e4,pb=/^(boe|ppe)_[A-Za-z0-9_-]+$/,gb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",mb="\u5BA1\u6279\u5DF2\u8D85\u65F6",wb=3e4,ko=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Lr;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=uh(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(),V.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){V.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(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),V.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){V.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&V.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,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)=>{V.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Gi(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){V.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=>V.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)){V.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(po(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&&pb.test(i)?this.currentCozeEnv=i:i&&V.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):V.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Or(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Or(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Or(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):V.warn("drop unknown notification",{method:e.method})}catch(o){V.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(An(r,zi(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 x=r._meta?.cozeTriggerMsgId,g=ao(r._meta);return V.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,gb,x,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{V.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}=Mf(i);switch(r){case"session/new":{let c=_b();return V.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return V.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Zt(e)?Nf(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: ${cd(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 S=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(y){throw f.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),y}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(f.acpSessionId,x):e.activeTriggers.delete(f.acpSessionId);let g=ao(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&&Eh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let m=await yh(c.prompt);try{let S=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:m});return f.lastActiveAt=Date.now(),S}catch(S){if(S instanceof k&&S.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 b=f.acpSessionId,I=b?e.activeTriggers.get(b):void 0,A=b?e.activeGroupIds.get(b):void 0;return V.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,f,d,mb,I,A)}throw S}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let S=f.downstream;S&&(f.downstream=void 0,V.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:f.acpSessionId}),S.stop("reload-after-turn").catch(y=>V.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&&(V.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=ao(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(!Mt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${cd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let g=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),m}else V.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${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 V.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};V.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 Zt(e)&&(c.permissionMode=e.framework==="claude-code"?fd:Z0),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,wb);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(Gi(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(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(V.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),V.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){V.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),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 x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw V.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),Zt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){V.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Gi(i),this.isRuntimeBusy(e,i)){V.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)){V.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}V.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=>V.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(Dr("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(Dr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>V.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){V.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){V.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(bb(r)){V.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"&&Zt(e)){let g=d.currentModeId;Mt(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(m=>V.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof g=="string"&&!Mt(e.framework,g)&&V.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Dr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>V.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}V.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 ph(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await gh(c,o);r.respondAgentRequest(i.id,d)}}catch(o){V.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,zi(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,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let m=u?this.reverseSessionId(e,u):void 0,S=m?e.sessions.get(m):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let y={...c,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:m}),V.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Bi(o,"session/request_permission",y)).catch(b=>{this.pendingUpstream.delete(o),V.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),r.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}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?(V.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&yb(e.result,o),V.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new xo(e.error)):i.value.resolve(e.result);return}V.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 V.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=xb){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(Bi(o,e,r)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let 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&&Zt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ii(e.agentId,r,this.paths)}catch(r){V.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:Ot}}))}};function _b(){return hb(16).toString("hex")}function yb(t,e){if(!t||typeof t!="object"){V.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){V.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"){V.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&V.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var Eb=["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."],bh="Warning: ";function bb(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(bh)?i.text.slice(bh.length):i.text;return Eb.some(c=>o.startsWith(c))}dn();ne();Me();import{randomBytes as vb}from"node:crypto";import{createServer as Sb}from"node:http";var Ib=1e6,vh=W("ipc"),To=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??ee()}async start(){this.token=vb(32).toString("hex");let e=Sb((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(),vh.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 cn(this.paths.portFile,String(this.port)),await cn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Ki(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Ki(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Ab(e)}catch(u){Ki(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ki(r,200,u??{ok:!0})}catch(u){vh.error("IPC handler failed",{key:o,err:String(u)}),Ki(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Ki(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function Ab(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>Ib)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 $v=Gt(_x(),1),Vv=Gt(Bo(),1),Jv=Gt(Ur(),1),Zv=Gt(Ad(),1),Yv=Gt(Cd(),1),Xv=Gt(Nd(),1),Tx=Gt(qo(),1),Qv=Gt(kx(),1);var Cx=Tx.default;$e();ne();var{FWS:p1}=Ux(),Oe=W("upstream.frontier"),Gx="application/json",Hx="none",g1=15e3;function m1(t){class e extends Cx{constructor(i){super(i,qf,{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(Il("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 ts=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:Gf,...Sn(this.opts.ppeOverride)},r=m1(e),i=jf(this.opts.urlOverride),o={url:i,ws:r,fpID:Uf,aID:co,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Gx,force:!0},payloadEncoding:{encoding:Hx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new p1(o),d=!1,u=null,f,x,g=new Promise((y,b)=>{f=y,x=b}),m=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(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&&m();for(let b of this.connectHandlers)Promise.resolve(b({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}),m(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let S=this.opts.openTimeoutMs??g1;u=setTimeout(()=>{m(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await g}catch(y){try{c.close(1e3,"open failed")}catch(b){Oe.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,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;jx(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:Gx,payloadEncoding:Hx})}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=y1(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;jx(c)||Oe.info("frontier frame in",{logid:_1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:w1(i)}),Promise.resolve(this.handler(o)).catch(d=>Oe.warn("frontier frame handler threw",{err:String(d)}))}};function jx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Wx=2e3;function w1(t){return t.length<=Wx?t:`${t.slice(0,Wx)}...<truncated, total ${t.length} chars>`}function _1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function y1(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();ne();var zd=W("skill-publish"),E1="/api/marketplace/product/skill/publish_with_assets",b1=15e4;async function Kx(t,e={}){let i=`${Cr(Rr(e.handshakeBase))}${E1}`,o=e.timeoutMs??b1,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);zd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${y.slice(0,200)}`)}let m=await x.json();if(zd.info("skill publish response",{logid:g,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${g}`);let S={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(S.skillId=String(m.data.skill_id)),m.data?.version&&(S.version=m.data.version),zd.info("skill publish ok",{logid:g,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(f)}}ne();var Ud=W("upstream.switchable"),Zo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Ud.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 Ud.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Ud.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 qd=W("upstream"),Kr=class{handler=null;async start(){qd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){qd.info("NoopUpstream stopped",{reason:e})}async send(e){qd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};$e();ne();dn();ne();Me();import{promises as v1}from"node:fs";var $x=W("pat-token-store");async function Yo(t=ee()){try{let r=(await v1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?($x.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"&&$x.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ns(t,e=ee()){if(!t)throw new Error("writePatToken: empty patToken");await cn(e.patTokenFile,t,{mode:384})}Me();Me();import{promises as Xo}from"node:fs";import{join as S1}from"node:path";function I1(t,e){return`#!/bin/sh
104
+ `}async function W0(t){let e=IE(t,"HEARTBEAT.md"),r=await vE(e,"utf8");return kE(r)!==AE?!1:(await SE(e,TE),!0)}var se=q("agent-manager"),fd="acceptEdits",J0="full-access",Y0="read-only";function DE(t){return{INITIAL_AGENT_MODE:wo(t)}}var OE=(t,e,r,i,o,a,d,u,h,x)=>{switch(t){case"claude-code":{let g={...o?{...Vf(o),...Zf(o,d,u)}:{},...h??{},IS_SANDBOX:"1"};return new mo({cwd:r,env:g,agentId:i})}case"codex":{let g=J0;x!==void 0&&(Nt("codex",x)?g=x:se.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let w=!!o,S={...o?{...Yf(o),...Jf(o,d,u)}:{},...DE(g),...w?{NO_BROWSER:"1"}:{},...h??{}};return new _o({cwd:r,agentId:i,...Object.keys(S).length>0?{env:S}:{},...w?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Br({command:e,cwd:r,agentId:i,...a?{sessionName:dd(a)}:{}})}};function ud(t){return t==="claude-code"||t==="codex"}function LE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(NE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
105
+ `)}
106
+ `}function NE(t){if(t.includes(`
107
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var ME={path:"",version:"cloud-deployed"},$0="openclaw_gateway_unavailable",BE="openclaw_default_agent_missing";function V0(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 FE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},zE=6e4,vo=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??OE,this.createTimeoutMs=e.createTimeoutMs??zE,this.detectorFactory=e.detectorFactory??(()=>new Vn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new bo({command:r})),this.openclawConfigDir=e.openclawConfigDir??K0(PE(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{se.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=K0(e,".env");if(await RE(r).then(a=>a.isFile()).catch(()=>!1)){se.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=LE({...process.env,...od(this.paths.agentEnvFile)});await cn(r,o,{mode:384}),se.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),se.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await Te(e.agentId,this.paths).catch(()=>null),o=oo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new T("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")se.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(k=>se.warn("dispose stale agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")se.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(k=>se.warn("dispose drifted agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){se.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let k=await Te(e.agentId,this.paths).catch(()=>null);k&&(k.patToken=e.patToken,await Fe(k,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){se.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let k=await Te(e.agentId,this.paths).catch(()=>null);k&&(k.modelInfo=e.modelInfo,await Fe(k,this.paths))}return se.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ve(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",g;x&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??w??u.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&ud(e.framework)&&await cr(e.framework,_.signal);let k=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await ld(u.root,{recursive:!0}),await ld(S,{recursive:!0}),await ld(u.logs,{recursive:!0}),k(),x||await ur(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Oa(S,"cloud"):await Oa(S,"local",fd)),k();let D=i,b=Kf({model:e.model??D?.model}),C=Of(e._meta)??D?.accountId,O=e.patToken??D?.patToken,B=h==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new yo({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Ot,deployType:h,...C?{accountId:C}:{},...O?{patToken:O}:{},...B?{modelInfo:B}:{}}),I.status="ok",D?.sessions){let K=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Z,ie]of Object.entries(D.sessions)){let oe={acpSessionId:ie.acpSessionId,modelToken:ie.modelToken,tokenGeneratedAt:ie.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?ie.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",se.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Z,framework:e.framework,fallback:oe.permissionMode})):Nt(e.framework,ie.permissionMode)?oe.permissionMode=ie.permissionMode:se.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Z,framework:e.framework,value:ie.permissionMode}):ie.permissionMode!==void 0&&se.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Z,framework:e.framework,deployType:h}),ie.cozeGroupId&&(oe.cozeGroupId=ie.cozeGroupId),I.sessions.set(Z,oe)}let ne=Object.keys(D.sessions).length;ne>0&&se.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ne})}this.registry.register(I),A=!0;let N={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:b.model};if(h==="cloud"&&(N.deployType="cloud"),C&&(N.accountId=C),O&&(N.patToken=O),B&&(N.modelInfo=B),D?.skills&&(N.skills=D.skills),D?.agentName&&(N.agentName=D.agentName),D?.description&&(N.description=D.description),N.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Dt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):se.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await W0(S)&&se.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:S})}catch(K){se.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:S,err:String(K)})}}let $=e.initialSkills??[];if($.length>0){let K=[...N.skills??[]],ne=new Map(K.map((oe,R)=>[oe.skillId,R])),Z=await Promise.allSettled($.map(oe=>fo({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe}))),ie=0;for(let[oe,R]of Z.entries()){let z=$[oe];z&&(R.status==="fulfilled"?(ho(K,ne,R.value),ie++):se.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:z.skillId,skillName:z.skillName,err:String(R.reason)}))}ie>0&&(N.skills=K,se.info("initialSkills installed",{agentId:e.agentId,installed:ie,requested:$.length}))}return await Fe(N,this.paths),se.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(k){throw se.error("agent create failed, rolling back",{agentId:e.agentId,err:String(k)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await CE(u.root,{recursive:!0,force:!0}).catch(D=>se.warn("rm agent dir failed (ignored)",{err:String(D)})),k instanceof T?k:new T("AGENT_SPAWN_FAILED",String(k),{cause:k})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,r,i,o,a){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&ud(e.framework))u=ME;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);ud(e.framework)&&!hs(e.framework)&&(se.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await cr(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:r,...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:a,command:u.path});else{let g=e.sessions.get(i),w=Yt(e)?g?.permissionMode??J0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,a,this.buildBinShimPathEnv(),w)}try{return await x.start(),await x.initialize(FE),x}catch(g){let w=x instanceof Lt?x.getStderrTail():[];throw w.length>0&&se.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof T?g.code:"unknown",recentStderr:w}),await x.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 T("AGENT_ENV_NOT_READY",V0(o),{cause:{reason:$0}})}catch(o){se.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof T?i:new T("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};se.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 se.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 T("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:BE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new T("AGENT_ENV_NOT_READY",V0(r),{cause:{reason:$0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,command:u}=e,h=dd(o);if(r.deployType==="local"){let w=await this.ensureOpenclawDefaultAgent();return new Br({command:u,cwd:w.workspace,agentId:w.id,sessionName:h})}let x=await j0(),g;if(i?.modelToken){let w=$c(o),S=Vc(i),_=`${w}/${S}`;if(!this.ensuredProviders.has(_)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(w),A=Xf(i,a,d,I);A&&(await v.ensureProvider(w,A),await v.addModelToAllowlist(_),this.ensuredProviders.add(_))}g=_}return new Br({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:h,...x?{gatewayToken:x}:{},...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 a of e.sessions.keys()){let d=$c(a),u=`${d}/${o}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,se.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,se.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as th}from"node:crypto";import{promises as KE}from"node:fs";import{basename as nh}from"node:path";We();te();import{promises as UE}from"node:fs";import{basename as qE}from"node:path";var Z0=q("file-upload"),GE="/api/coze_claw/file/agent_upload",HE=6e4;async function X0(t,e={}){let i=`${Cr(Rr(e.handshakeBase))}${GE}`,o=e.timeoutMs??HE,a=await UE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Sn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);Z0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let g=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),w=g.headers.get("x-tt-logid")??"";if(!g.ok){let v=await g.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${g.status} logid=${w}: ${v.slice(0,200)}`)}let S=await g.json();if(S.code!==void 0&&S.code!==0)throw new T("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${w}`);let _=S.data?.file?.file_url;if(!_)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(S).slice(0,200)}`);return Z0.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(g){throw g instanceof T?g:g.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${qE(t.path)}`):new T("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}We();te();import{extname as jE}from"node:path";var WE={".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 Q0(t){let e=jE(t).toLowerCase();return WE[e]??"application/octet-stream"}Oe();var So=q("agent-send"),eh=50*1024*1024;function rh(t,e,r){let i=t.get(e);if(!i)throw new T("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new T("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new T("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function ih(t,e,r,i,o,a){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,h<2&&(So.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new T("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function sh(t,e){let{session:r,runtime:i}=rh(e.core,t.agentId,t.sessionId);if(!await ri(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await KE.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new T("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>eh)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${eh}`);let a=await Q0(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??nh(t.path),u;try{u=await X0({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:d,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw So.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:x instanceof T?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:th(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await ih(e,r,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),So.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function oh(t,e){let{session:r,runtime:i}=rh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new T("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??nh(t.path),a={sessionUpdate:"group_file",messageId:th(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ih(e,r,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),So.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 ah(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let a=0;a<o;a++){let d=r[a]??0,u=i[a]??0;if(d<u)return!0;if(d>u)return!1}return!1}an();Jt();te();var Mt=q("coze-cli-installer"),ch="@coze/cli@latest",$E="coze",dh="0.1.8",VE=5e3,JE=5e3,YE=9e4,lh=1e4,Hi=null,Io=!1;async function xd(t,e={}){if(Io)return;if(Hi)return Hi;let r=e.exec??Ff;return Hi=(async()=>{try{let i=await ZE($E,r),o=!1;if(i){let d=await XE(r);if(d===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(ah(d,dh))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:dh}),o=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Io=!0;return}}let a=o?"upgrade-only":"full";Mt.info("coze-cli install start",{package:ch,mode:a});try{await r("npm",["i","-g","--prefer-online",ch],{timeout:YE,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){Io=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:lh}),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 r("coze",["auth","login","--token",t.patToken],{timeout:lh}),Mt.info("coze auth login ok")}catch(d){Mt.warn("coze auth login failed",{err:String(d)});return}Io=!0}finally{Hi=null}})(),Hi}async function ZE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:VE});return Pa(i)}catch{return}}async function XE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:JE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}dn();Oe();var QE=10*6e4;function uh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?QE:e}function Ao(t){return dr(t??Q().configFile)}function ji(t,e){return lr(e??Q().configFile,t)}import{randomBytes as _b}from"node:crypto";sr();We();te();import{createReadStream as eb}from"node:fs";import{mkdir as tb,readFile as nb,realpath as rb,stat as ib,writeFile as sb}from"node:fs/promises";import{basename as ob,dirname as pd,isAbsolute as ab,join as cb,relative as db,resolve as fh,sep as lb}from"node:path";import{createInterface as ub}from"node:readline";var xh=q("fs-rpc"),Wi=$e("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function ph(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Wi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Wi} bytes`);let i=await mh(t.path,e);return await tb(pd(i),{recursive:!0}),await sb(i,t.content,"utf8"),xh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function gh(t,e){let r=await mh(t.path,e),i=await ib(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Wi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Wi} bytes`);let a;if(o&&i.size>Wi)a=await fb(r,t.line??1,t.limit);else{let d=await nb(r,"utf8");if(o){let u=d.split(`
108
+ `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;a=u.slice(h,x).join(`
109
+ `)}else a=d}return xh.info("fs/read_text_file ok",{path:r,size:a.length}),{content:a}}async function fb(t,e,r){let i=ub({input:eb(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),a=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=o&&u<a&&d.push(h),u++,u>=a)break}finally{i.close()}return d.join(`
110
+ `)}async function mh(t,e){if(typeof t!="string"||t.length===0)throw new T("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([hh(fh(e)),hh(fh(t))]),o=db(r,i);if(hb(o,lb,ab(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function hb(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function hh(t){let e=[],r=t;for(;r!==pd(r);)try{let i=await rb(r);return e.length?cb(i,...e.reverse()):i}catch{e.push(ob(r)),r=pd(r)}return t}te();var wh=q("prompt-multimodal"),_h=10*1024*1024,xb=15e3,pb=6;async function yh(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let a=r++,d=t[a];d!==void 0&&(e[a]=await gb(d))}}let o=Array.from({length:Math.min(pb,t.length)},()=>i());return await Promise.all(o),e}function Eh(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||!Di(e.uri))return t;try{let{buf:r,contentType:i}=await wb(e.uri),o=e.mimeType||mb(i)||"application/octet-stream";return wh.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 wh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function mb(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,r=setTimeout(()=>e.abort(),xb);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>_h)throw new Error(`image too large: ${o.byteLength} bytes (max ${_h})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}ln();We();te();var W=q("core"),yb=3e4,Eb=/^(boe|ppe)_[A-Za-z0-9_-]+$/,bb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",vb="\u5BA1\u6279\u5DF2\u8D85\u65F6",Sb=3e4,To=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Lr;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=uh(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(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),o.onAgentRequest(a=>{this.handleAgentRequest(e,o,a)}),o.onExit((a,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:a,signal:d}),Gi(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,a]of this.pendingUpstream)a.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let a=this.pendingUpstream.get(o);if(a){this.pendingUpstream.delete(o),this.upstream.send(An(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code: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 T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(po(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&&Eb.test(i)?this.currentCozeEnv=i:i&&W.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}`):W.warn("drop notification: extension not registered",{method:e.method});return}let a=await o(e,this);r!==null&&await this.upstream.send(Or(r,a));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Or(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Or(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(o){W.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(An(r,zi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new T("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new T("AGENT_NOT_FOUND",`agent not found: ${i}`);let a=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!a)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let h=o.sessions.get(a);if(h?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,g=ao(r._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,h,a,bb,x,g)}}let d=Date.now(),u=!1;try{let h=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,h}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Nf(i);switch(r){case"session/new":{let a=Ib();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=o,d=a.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Yt(e)?Lf(i._meta):void 0;if(u!==void 0&&!Nt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${cd(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 T("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 g=ao(i._meta);if(g?e.activeGroupIds.set(h.acpSessionId,g):e.activeGroupIds.delete(h.acpSessionId),g&&h.cozeGroupId!==g&&(h.cozeGroupId=g,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Eh(a.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await yh(a.prompt);try{let S=await h.downstream.sessionPrompt({...a,sessionId:h.acpSessionId,prompt:w});return h.lastActiveAt=Date.now(),S}catch(S){if(S instanceof T&&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 W.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,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:h.acpSessionId}),S.stop("reload-after-turn").catch(_=>W.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 T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=o,d=a.sessionId,u=a.modeId,h=ao(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Yt(e))throw e.framework==="openclaw"?new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new T("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Nt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${cd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let g=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),w}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of o){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&a.push({downstream:u,acpSessionId:h,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let h of o)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let a={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Yt(e)&&(a.permissionMode=e.framework==="claude-code"?fd:Y0),e.sessions.set(r,a),await this.persistSessionMapping(e),a}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ut.GEN_MODEL_TOKEN,i,Sb);if(!o?.modelToken)throw new T("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return o.modelToken}catch(o){throw o instanceof T&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new T("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,r,i){if(Gi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new T("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<a)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-u))/1e3)}s`);let h;try{h=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=h,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let g=await h.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Yt(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Gi(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(a=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(a)}))},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 a={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let d=e.activeTriggers.get(r.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(r.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(Dr("session/update",{sessionId:i,update:o,_meta:a}))}async synthesizePromptReply(e,r,i,o,a,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return a&&(u.cozeTriggerMsgId=a),d&&(u.cozeGroupId=d),await this.upstream.send(Dr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(kb(r)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=r.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Yt(e)){let g=d.currentModeId;Nt(e.framework,g)&&a.permissionMode!==g?(a.permissionMode=g,this.persistSessionMapping(e).catch(w=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof g=="string"&&!Nt(e.framework,g)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Dr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>W.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}W.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 a=i.params??{},d=await ph(a,o);r.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await gh(a,o);r.respondAgentRequest(i.id,d)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,zi(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"),a=i.params??{},u=a.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let g=u?e.activeGroupIds.get(u):void 0;g&&(x.cozeGroupId=g);let w=u?this.reverseSessionId(e,u):void 0,S=w?e.sessions.get(w):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...a,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Bi(o,"session/request_permission",_)).catch(v=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),r.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&Ab(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new xo(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let a=String(r),d=e.get(a);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:a}),{value:d,key:a}}}sendRequest(e,r,i=yb){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(Bi(o,e,r)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let a={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(a.acpSessionId=o.acpSessionId),o.permissionMode&&Yt(e)&&(a.permissionMode=o.permissionMode),o.cozeGroupId&&(a.cozeGroupId=o.cozeGroupId),r.set(i,a)}await ii(e.agentId,r,this.paths)}catch(r){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(An(e,{code:r,message:i,data:{bridgeVersion:Dt}}))}};function Ib(){return _b(16).toString("hex")}function Ab(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let a=i.outcome;(typeof a!="string"||a!=="selected"&&a!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var Tb=["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."],bh="Warning: ";function kb(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(bh)?i.text.slice(bh.length):i.text;return Tb.some(a=>o.startsWith(a))}dn();te();Oe();import{randomBytes as Cb}from"node:crypto";import{createServer as Rb}from"node:http";var Pb=1e6,vh=q("ipc"),ko=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??Q()}async start(){this.token=Cb(32).toString("hex");let e=Rb((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(),vh.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 cn(this.paths.portFile,String(this.port)),await cn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Ki(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){Ki(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Db(e)}catch(u){Ki(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);Ki(r,200,u??{ok:!0})}catch(u){vh.error("IPC handler failed",{key:o,err:String(u)}),Ki(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Ki(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function Db(t){let e=[],r=0;for await(let o of t){let a=o;if(r+=a.length,r>Pb)throw new Error("body too large");e.push(a)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var Qv=Gt(_x(),1),eS=Gt(Bo(),1),tS=Gt(Ur(),1),nS=Gt(Ad(),1),rS=Gt(Cd(),1),iS=Gt(Nd(),1),kx=Gt(qo(),1),sS=Gt(Tx(),1);var Cx=kx.default;We();te();var{FWS:ES}=Ux(),Re=q("upstream.frontier"),Gx="application/json",Hx="none",bS=15e3;function vS(t){class e extends Cx{constructor(i){super(i,Uf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Re.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(Sl("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let d=Buffer.from(a.slice(0,128)).toString("hex");Re.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Re.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var ts=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){Re.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:qf,...Sn(this.opts.ppeOverride)},r=vS(e),i=Hf(this.opts.urlOverride),o={url:i,ws:r,fpID:zf,aID:co,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Gx,force:!0},payloadEncoding:{encoding:Hx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new ES(o),d=!1,u=null,h,x,g=new Promise((_,v)=>{h=_,x=v}),w=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Re.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&w();for(let v of this.connectHandlers)Promise.resolve(v({initial:_})).catch(I=>Re.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=_=>{this.opened=!1,Re.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Re.warn("frontier error",{code:_.code,msg:_.message}),w(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let S=this.opts.openTimeoutMs??bS;u=setTimeout(()=>{w(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await a.connect();try{await g}catch(_){try{a.close(1e3,"open failed")}catch(v){Re.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Re.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Re.warn("frontier send refused: upstream not started",{method:i}),new T("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Re.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 T("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),a=e;jx(a)||Re.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:Gx,payloadEncoding:Hx})}catch(u){throw Re.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new T("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let 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){Re.debug("drop non-adapter frontier frame",{service:r});return}let i=AS(e);if(!i){Re.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Re.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Re.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;jx(a)||Re.info("frontier frame in",{logid:IS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:SS(i)}),Promise.resolve(this.handler(o)).catch(d=>Re.warn("frontier frame handler threw",{err:String(d)}))}};function jx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Wx=2e3;function SS(t){return t.length<=Wx?t:`${t.slice(0,Wx)}...<truncated, total ${t.length} chars>`}function IS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function AS(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}}We();te();var zd=q("skill-publish"),TS="/api/marketplace/product/skill/publish_with_assets",kS=15e4;async function Kx(t,e={}){let i=`${Cr(Rr(e.handshakeBase))}${TS}`,o=e.timeoutMs??kS,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Sn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);zd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${_.slice(0,200)}`)}let w=await x.json();if(zd.info("skill publish response",{logid:g,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${g}`);let S={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(S.skillId=String(w.data.skill_id)),w.data?.version&&(S.version=w.data.version),zd.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}catch(x){throw x instanceof T?x:x.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}te();var Ud=q("upstream.switchable"),Yo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Ud.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 Ud.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Ud.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 qd=q("upstream"),Kr=class{handler=null;async start(){qd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){qd.info("NoopUpstream stopped",{reason:e})}async send(e){qd.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)}};We();te();dn();te();Oe();import{promises as CS}from"node:fs";var $x=q("pat-token-store");async function Zo(t=Q()){try{let r=(await CS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?($x.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"&&$x.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ns(t,e=Q()){if(!t)throw new Error("writePatToken: empty patToken");await cn(e.patTokenFile,t,{mode:384})}Oe();Oe();import{promises as Xo}from"node:fs";import{join as RS}from"node:path";function PS(t,e){return`#!/bin/sh
105
111
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
106
- `}function A1(t,e){return`@echo off\r
112
+ `}function DS(t,e){return`@echo off\r
107
113
  "${e}" "${t}" %*\r
108
- `}async function Vx(t,e=ee()){let r=e.binDir;await Xo.mkdir(r,{recursive:!0});let i=S1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?A1(t,o):I1(t,o);return await Xo.readFile(i,"utf8").catch(()=>null)===c||(await Xo.writeFile(i,c,"utf8"),process.platform!=="win32"&&await Xo.chmod(i,493)),r}ne();Me();import{execSync as Jx}from"node:child_process";import{readFileSync as Zx,unlinkSync as k1}from"node:fs";import{mkdir as T1,open as C1,readFile as Yx,unlink as Gd,writeFile as R1}from"node:fs/promises";import{dirname as P1}from"node:path";var D1=W("single-instance"),O1=t=>new Promise(e=>setTimeout(e,t)),Qo=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??ee().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ui(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&&D1.warn("removing stale pid file",{stalePid:i}),await R1(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 Yx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Gd(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 Yx(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 T1(P1(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await C1(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 O1(this.claimLockIntervalMs);continue}await Gd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Gd(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=Zx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Nr)||r.includes("lib/index.js"))}catch{}try{let r=Jx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Nr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Jx(`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{Zx(this.pidFile,"utf8").trim()===String(this.selfPid)&&k1(this.pidFile)}catch{}})}};ea();ne();var er=W("daemon.upstream-watchdog"),q1=12e4,G1=9e5,H1=3e4;function jd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ta=class{constructor(e){this.opts=e;this.softMs=e.softMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",q1),this.hardMs=e.hardMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",G1),this.intervalMs=e.intervalMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",H1),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?.(),er.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&&er.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&&er.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,er.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){er.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,er.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>er.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var K=W("daemon");async function ep(){let t=ee();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){vl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Ze(P,t).logs,listAgentIds:()=>xs(t)});try{let{writeFileSync:P}=await import("node:fs");P(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
114
+ `}async function Vx(t,e=Q()){let r=e.binDir;await Xo.mkdir(r,{recursive:!0});let i=RS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,a=process.platform==="win32"?DS(t,o):PS(t,o);return await Xo.readFile(i,"utf8").catch(()=>null)===a||(await Xo.writeFile(i,a,"utf8"),process.platform!=="win32"&&await Xo.chmod(i,493)),r}te();Oe();import{execSync as Jx}from"node:child_process";import{readFileSync as Yx,unlinkSync as OS}from"node:fs";import{mkdir as LS,open as NS,readFile as Zx,unlink as Gd,writeFile as MS}from"node:fs/promises";import{dirname as BS}from"node:path";var FS=q("single-instance"),zS=t=>new Promise(e=>setTimeout(e,t)),Qo=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Q().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ui(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&&FS.warn("removing stale pid file",{stalePid:i}),await MS(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 Zx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Gd(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 Zx(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 LS(BS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await NS(r,"wx")}catch(a){if(a.code!=="EEXIST")throw a;let d=await this.readPidFrom(r);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await zS(this.claimLockIntervalMs);continue}await Gd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Gd(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=Yx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Nr)||r.includes("lib/index.js"))}catch{}try{let r=Jx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Nr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Jx(`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{Yx(this.pidFile,"utf8").trim()===String(this.selfPid)&&OS(this.pidFile)}catch{}})}};ea();te();var er=q("daemon.upstream-watchdog"),$S=12e4,VS=9e5,JS=3e4;function jd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ta=class{constructor(e){this.opts=e;this.softMs=e.softMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",$S),this.hardMs=e.hardMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",VS),this.intervalMs=e.intervalMs??jd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",JS),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?.(),er.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&&er.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&&er.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,er.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){er.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,er.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>er.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var G=q("daemon");async function ep(){let t=Q();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){bl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Ve(R,t).logs,listAgentIds:()=>xs(t)});try{let{writeFileSync:R}=await import("node:fs");R(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
109
115
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
110
116
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
111
- `)}catch{}}let e=new Qo({processTitle:Nr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Ao(),o=i??{};us({pid:process.pid}),K.info(i?"loaded bridge config":"initialized bridge config");let c=new Zo(new Kr),d=null,u=new ko({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,q,$,te)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,q,$,te)}}),f=new vo({paths:t,config:o,registry:u});d=f;let x,g,m=null,S={},y,b=null,I=null,A=null,T=new kn;function D(P,q){return T.enqueue(()=>R(P,q))}function E(){I||(I=new ta({isConnected:()=>c.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:P=>{if(process.env[rs]==="1"){K.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}K.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function R(P,q){let $=P,te=$?.privatecode;if(!te)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let et=Li($.env),me=$.handshake_url,we=$.frontier_url,At=Qx($.env,me,we);if(A=$,!q?.force&&x===te&&g===At){let Ee=await j1(t);return u.agents.size===0&&Ee?(K.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ra(t,f).catch(Te=>K.warn("connect-noop auto-revive error (ignored)",{err:String(Te)}))):K.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let gt=!!x&&x!==te,nn=g!==void 0&&g!==At,qt=gt||nn,rn=await Gc({privatecode:te,...me?{endpoint:me}:{},ppeOverride:et});if(qt){K.warn("connect config switched, resetting agents",{pcChanged:gt,envChanged:nn,previousPc:x?na(x):"",nextPc:na(te)});for(let Ee of[...u.agents.values()])await Ee.dispose("connect config switch").catch(()=>{}),u.agents.delete(Ee.agentId);u.disconnectedAgents.size>0&&(K.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"connect switch").catch(()=>{})}m=rn.deviceId,us({deviceId:m,pid:process.pid}),xd({patToken:te,env:$.env}).catch(Ee=>K.warn("coze-cli setup error (ignored)",{err:String(Ee)}));let Yr=new ts({handshake:rn,privatecode:te,...we?{urlOverride:we}:{},ppeOverride:et,getPatTokenForAgent:Ee=>u.agents.get(Ee)?.patToken});return await c.swap(Yr,"connect"),x=te,g=At,S=et,y=me,$.mock_scenario!==void 0&&(u.setMockScenario($.mock_scenario),K.info("mock scenario set",{scenario:$.mock_scenario})),b||(b=new Mi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>B.retryPending().catch(Ee=>K.warn("detailSync.retryPending failed (ignored)",{err:String(Ee)})),onAuthFailures:Z})),b.start(),E(),qt&&ra(t,f).catch(Ee=>K.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ee)})),ns(te,t).catch(Ee=>K.warn("writePatToken after /connect failed (ignored)",{err:String(Ee)})),K.info("/connect: WS established",{deviceId:m}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>f.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new uo({agents:u.agents,publishSkillToMarketplace:async P=>{let q=u.agents.get(P.agentId)?.patToken??x;if(!q)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Kx({patToken:q,zip:P.zip,...P.skillId?{skillId:P.skillId}:{},skillName:P.skillName,...P.description?{description:P.description}:{},agentId:P.agentId,...P.accountId?{accountId:P.accountId}:{}},{handshakeBase:y,ppeOverride:S})},disposeAndMarkDisconnected:async(P,q)=>{let $=u.agents.get(P);if($){await f.cleanupOpenclawSessionProviders($).catch(et=>K.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(et)}));let te=!0;try{await $.dispose(`disconnect: ${q}`)}catch(et){te=!1,K.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(et)}),$.status="error"}te&&($.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,q)=>{let $=u.agents.get(P);$&&(await f.cleanupOpenclawSessionProviders($).catch(te=>K.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(te)})),await $.dispose(`delete: ${q}`).catch(te=>K.warn("dispose during delete failed (ignored)",{agentId:P,err:String(te)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(P)},cleanupOpenclawProviders:async(P,q)=>{await f.cleanupOpenclawSessionProviders(P,q)},openclawRepair:async(P,q)=>{await f.openclawRepair(P,q)},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>F.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>F.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>F.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>F.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>F.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>F.getFileContent(P.params)),u.registerExtension("_agent/update",P=>F.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>F.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>F.switchModel(P.params)),u.registerExtension("_agent/reset",P=>F.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>F.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>F.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>F.upgradeBridge(P.params));let B=new ms({paths:t,handlers:F,agentManager:f,sendDetail:P=>u.sendRequest("_agent/detail",P)});O.ref=B;let Z=async P=>{await Promise.allSettled(P.map(async q=>{try{await F.disconnectAgent({agentId:q.agentId,reason:`auth_failure: code=${q.code} ${q.message}`}),K.info("agent disconnected due to auth failure from heartbeat response",{agentId:q.agentId,code:q.code,message:q.message})}catch($){K.warn("disconnect during authFailure handling failed (ignored)",{agentId:q.agentId,err:String($)})}}))};c.onConnect(({initial:P})=>{K.info("frontier upstream connected, triggering detail sync",{initial:P}),B.syncAll(P?"initial-connect":"reconnect").catch(q=>K.warn("detail sync top-level error (ignored)",{err:String(q)}))});let J=new To({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let P=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[rs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:m??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let q=P,$=q?.privatecode,te=q?.pairing_code;if(!$||!te)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let et=Li(q.env),me=q.handshake_url,we=q.frontier_url,At=Qx(q.env,me,we),gt=!!x&&x!==$,nn=g!==void 0&&g!==At,qt=gt||nn,rn=await Gc({privatecode:$,...me?{endpoint:me}:{},ppeOverride:et});if(qt){K.warn("pair config switched, resetting agents",{pcChanged:gt,envChanged:nn,previousPc:x?na(x):"",nextPc:na($),previousEnvKey:g??"",nextEnvKey:At});for(let Te of[...u.agents.values()])await Te.dispose("pair config switch").catch(()=>{}),u.agents.delete(Te.agentId);u.disconnectedAgents.size>0&&(K.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"pair switch").catch(()=>{})}m=rn.deviceId,us({deviceId:m,pid:process.pid}),xd({patToken:$,env:q.env}).catch(Te=>K.warn("coze-cli setup error (ignored)",{err:String(Te)}));let Yr=new ts({handshake:rn,privatecode:$,...we?{urlOverride:we}:{},ppeOverride:et,getPatTokenForAgent:Te=>u.agents.get(Te)?.patToken});await c.swap(Yr,"pair");try{let Te=new Vn;o.frameworksCache=await Te.detectAll(),await ji(o),K.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Te){K.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Te)})}let Ee=Object.keys(o.frameworksCache??{});try{let Te=await u.sendRequest("_agent/pair",{pairCode:te,patToken:$,frameworks:Ee,_meta:{cozeDeviceId:m}});K.info("_agent/pair ok",{pairResult:Te}),x=$,g=At,S=et,y=me,q.mock_scenario!==void 0&&(u.setMockScenario(q.mock_scenario),K.info("mock scenario set",{scenario:q.mock_scenario})),ns($,t).catch(Ne=>K.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),b||(b=new Mi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>B.retryPending().catch(Ne=>K.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:Z})),b.start(),E(),qt&&ra(t,f).catch(Ne=>K.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let tr;return q.agent_id&&(tr=await K1(q.agent_id,t,f,Ne=>u.sendRequest("_agent/detail",Ne),$).catch(Ne=>(K.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(Ne)}),{ok:!1,agentId:q.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...tr?{agent:tr}:{}}}catch(Te){return K.error("_agent/pair failed",{err:String(Te)}),{ok:!1,note:`pair failed: ${String(Te)}`}}}},{method:"POST",path:"/connect",handler:P=>D(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let q=P;return{ok:!0,result:await f.createAgent(q)}}},{method:"POST",path:"/agent/send",handler:async P=>{let q=P;if(!q?.agentId||!q?.sessionId||!q?.kind||!q?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let $=q;return await($.groupFile?oh:sh)($,{core:u,patToken:x,handshakeBase:y,ppeOverride:S})}catch($){if($ instanceof k)return{ok:!1,code:$.code,message:$.message};throw $}}},{method:"POST",path:"/reload",handler:async P=>{let q=P?.agent_id,$=await u.reloadAgents(q);return K.info("IPC /reload: recycled agent subprocesses",{agentId:q??"(all)",recycled:$}),{ok:!0,recycled:$}}},{method:"POST",path:"/shutdown",handler:async()=>(K.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await J.start();try{await Vx(t.libEntry,t)}catch(P){K.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),$1({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Vn().detectAll(),await ji(o),o.frameworksCache)}).catch(P=>K.warn("startup warmup error (ignored)",{err:String(P)})),Ol().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(an(),Pl));for(let q of["claude-code","codex"]){let $=await P(q);$&&K.info("acp wrapper version",{framework:q,version:$})}}).catch(P=>K.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let oe=null,ae={port:re,token:X,core:u,ipc:J,shutdown(P){return oe||(K.info("daemon shutdown",{reason:P}),oe=(async()=>{b?.stop(),I?.stop(),await u.stop(P),await J.stop(),await e.release()})(),oe)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{ae.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>k0()),process.on("unhandledRejection",P=>{K.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{K.error("uncaughtException (will exit, supervisor will restart)",{message:P.message,stack:P.stack,name:P.name});try{process.stderr.write(`FATAL uncaughtException: ${P.stack??P.message}
112
- `)}catch{}process.exit(1)}),K.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),J1({cliSpawned:process.env[rs]==="1",readPatToken:()=>Yo(t),connect:D}).catch(P=>K.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),ae}async function j1(t){return xs(t).length>0}function na(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Qx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function W1(t,e){let r=xs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(ln(),gs));for(let c of r){await o(c,t).catch(d=>K.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),K.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),K.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){K.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function K1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(ln(),gs)),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`);K.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=tp(d),m={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(m),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}K.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 x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function $1(t){let e=t.logger??K;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 W1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ra(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await V1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ra(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(()=>(ln(),gs));K.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(x){K.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){K.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){K.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{K.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=tp(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){K.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return K.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function V1(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 x0(o,t)).status==="refreshed"&&(i+=1)}catch(c){K.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&K.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function J1(t){let e=t.logger??K;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 tp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ea();Me();import{readFile as np}from"node:fs/promises";var tn=class{paths;constructor(e){this.paths=e??ee()}async probe(e=1e3){let r=await ia(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:Y1(i)}}}async request(e){let r=await ia(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:Z1(f)}}finally{clearTimeout(d)}}};async function ia(t){try{let[e,r]=await Promise.all([np(t.portFile,"utf8"),np(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 Z1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Y1(t){return t instanceof Error?t.message:String(t)}Jt();ne();sr();import{spawn as X1}from"node:child_process";import{userInfo as ip}from"node:os";var Wd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",Q1=new Set(["bash","zsh","sh","dash","ksh"]),rp=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),eS=2e3;function tS(t,e=Wd){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(`
113
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function nS(){let t=(process.env.SHELL??"").trim()||(ip().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return Q1.has(e)?t:null}function rS(t){return new Promise(e=>{let r=`printf '%s' '${Wd}'; env; printf '%s' '${Wd}'`,i;try{i=X1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ip().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(x),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"),rp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},rp+eS)})}async function Kd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=nS();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??rS)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=tS(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Me();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}}an();import{chmod as iS,copyFile as sp,mkdir as ap,readFile as ss,rename as op,rm as Jd,stat as cp,writeFile as sS}from"node:fs/promises";import{homedir as xD}from"node:os";import{dirname as oS,join as Le,resolve as Zd,sep as is}from"node:path";import{fileURLToPath as aS}from"node:url";Jt();ne();Me();function $r(t,e,r,i){rt(t.bridgeLogsDir,e,"dist-install",r,i)}function dp(){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 cS(){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 dS(t){let e=aS(t),r=oS(e),i=`${is}src${is}`;if(r.includes(i)||r.endsWith(`${is}src${is}cli`))return null;let o=Zd(r,"index.js"),c=Zd(r,"..","package.json");return{dist:o,pkgJson:c}}async function Yd(t={}){let e=t.paths??ee(),r=dS(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 b=JSON.parse(await ss(o,"utf8"));c=b.version??"unknown",d=b.dependencies??{}}catch(b){throw $r(e,"error","cannot read source package.json",{err:String(b)}),new Error(`cannot read source package.json: ${String(b)}`,{cause:b})}let u=fs.map(b=>({name:b,spec:d[b]??"latest"})),f=u.map(({name:b,spec:I})=>`${b}@${I}`),x=await Ao(e.configFile)??{},g=x.libVersion,m=await ss(e.libEntry).then(()=>!0).catch(()=>!1),S=g===c,y=await lp(e,u);if(S&&m&&y)return{kind:"already-current",libVersion:c};if(!S||!m){await ap(e.libDir,{recursive:!0}),await sp(i,e.libEntry),await sp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let b=Zd(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
114
- `;await ss(b,"utf8").catch(()=>null)!==I&&await sS(b,I)}return y||(t.installWrappers?await t.installWrappers(e,f):await fS(e,f,u)),x.libVersion=c,await ji(x,e.configFile),$r(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:c}),S&&m?{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 lp(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 ss(i,"utf8"))}catch(d){return $r(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 $r(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!lS(c,r.spec))return $r(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await up(Le(t.libDir,"node_modules"))}function lS(t,e){let r=$d(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=$d(i.slice(1));if(!c)return!0;if(Vd(r,c)<0)return!1;let d=uS(c);return Vd(r,d)<0}let o=$d(i);return o?Vd(r,o)===0:!0}function uS(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function $d(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Vd(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 fS(t,e,r){await pS(t.installLock,async()=>{if(await lp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${is}.staging-${process.pid}-${i}`,c=Le(o,"node_modules"),d=Le(t.libDir,"node_modules");try{await ap(o,{recursive:!0}),await hS(e,o),await xS(c);let u=`${d}.trash-${i}`;await op(d,u).catch(()=>{}),await op(c,d),await Jd(u,{recursive:!0,force:!0}).catch(()=>{}),$r(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Jd(o,{recursive:!0,force:!0}).catch(()=>{})}})}function hS(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 xS(t){for(let e of fs){let r=Le(t,...e.split("/")),i=JSON.parse(await ss(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 cp(c);process.platform!=="win32"&&!(d.mode&73)&&await iS(c,d.mode|73).catch(()=>{})}if(!await up(t)){let e=dp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function up(t){let e=dp(),r=cS();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=>cp(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function pS(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 Jd(t,{force:!0}).catch(()=>{})}}ka();ne();Me();import{closeSync as hp,fstatSync as xp,openSync as pp,readFileSync as gS,readSync as mS,readdirSync as wS,statSync as _S}from"node:fs";import{join as sa}from"node:path";var yS=new Set(["debug","info","warn","error"]);function gp(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,x=c.value&&yS.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),x&&(g.level=x),d.value&&(g.grep=d.value),g}function ES(t,e){return t.agentId?sa(Ze(t.agentId,e).logs,or("agent",t.date)):sa(e.bridgeLogsDir,or("bridge",t.date))}function bS(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function vS(t,e){let r;try{r=wS(t)}catch{return[]}let i=[];for(let o of r){let c=Aa(o,e);if(!c)continue;let d=0;try{d=_S(sa(t,o)).size}catch{}i.push({file:sa(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function mp(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"&&!Al(r,e.level))return!1}return!0}var fp={debug:"90",info:"36",warn:"33",error:"31"},SS=new Set(["ts","level","module","msg"]);function IS(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function wp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=IS(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&fp[o]&&(c=`\x1B[${fp[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(([x])=>!SS.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${d} ${u}${f}`}function AS(t,e,r){let c=gS(t,"utf8").split(`
115
- `).filter(d=>d.length>0).filter(d=>mp(d,{level:e.level,grep:e.grep}));for(let d of bS(c,e.lines))process.stdout.write(`${wp(d,{raw:e.raw,color:r})}
116
- `)}async function _p(t,e){let r=e.paths??ee(),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=vS(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
117
- `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
118
- `);return 0}let o=t.date??Dn(new Date),c=ES({agentId:t.agentId,date:o},r);try{AS(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
117
+ `)}catch{}}let e=new Qo({processTitle:Nr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Ao(),o=i??{};us({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let a=new Yo(new Kr),d=null,u=new To({upstream:a,paths:t,bridgeConfig:o,sessionSpawner:async(R,z,j,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(R,z,j,ee)}}),h=new vo({paths:t,config:o,registry:u});d=h;let x,g,w=null,S={},_,v=null,I=null,A=null,k=new Tn;function D(R,z){return k.enqueue(()=>C(R,z))}function b(){I||(I=new ta({isConnected:()=>a.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:R=>{if(process.env[rs]==="1"){G.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}G.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),I.start()}async function C(R,z){let j=R,ee=j?.privatecode;if(!ee)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Xe=Li(j.env),xe=j.handshake_url,pe=j.frontier_url,It=Qx(j.env,xe,pe);if(A=j,!z?.force&&x===ee&&g===It){let we=await YS(t);return u.agents.size===0&&we?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ra(t,h).catch(Ie=>G.warn("connect-noop auto-revive error (ignored)",{err:String(Ie)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let xt=!!x&&x!==ee,nn=g!==void 0&&g!==It,Ut=xt||nn,rn=await Gc({privatecode:ee,...xe?{endpoint:xe}:{},ppeOverride:Xe});if(Ut){G.warn("connect config switched, resetting agents",{pcChanged:xt,envChanged:nn,previousPc:x?na(x):"",nextPc:na(ee)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new Kr,"connect switch").catch(()=>{})}w=rn.deviceId,us({deviceId:w,pid:process.pid}),xd({patToken:ee,env:j.env}).catch(we=>G.warn("coze-cli setup error (ignored)",{err:String(we)}));let Zr=new ts({handshake:rn,privatecode:ee,...pe?{urlOverride:pe}:{},ppeOverride:Xe,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await a.swap(Zr,"connect"),x=ee,g=It,S=Xe,_=xe,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),G.info("mock scenario set",{scenario:j.mock_scenario})),v||(v=new Mi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>N.retryPending().catch(we=>G.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:$})),v.start(),b(),Ut&&ra(t,h).catch(we=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),ns(ee,t).catch(we=>G.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),G.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>h.createAgent(R.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},B=new uo({agents:u.agents,publishSkillToMarketplace:async R=>{let z=u.agents.get(R.agentId)?.patToken??x;if(!z)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Kx({patToken:z,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(R,z)=>{let j=u.agents.get(R);if(j){await h.cleanupOpenclawSessionProviders(j).catch(Xe=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(Xe)}));let ee=!0;try{await j.dispose(`disconnect: ${z}`)}catch(Xe){ee=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(Xe)}),j.status="error"}ee&&(j.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,z)=>{let j=u.agents.get(R);j&&(await h.cleanupOpenclawSessionProviders(j).catch(ee=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(ee)})),await j.dispose(`delete: ${z}`).catch(ee=>G.warn("dispose during delete failed (ignored)",{agentId:R,err:String(ee)})),u.unregister(R)),u.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(R)},cleanupOpenclawProviders:async(R,z)=>{await h.cleanupOpenclawSessionProviders(R,z)},openclawRepair:async(R,z)=>{await h.openclawRepair(R,z)},isRuntimePendingPermission:R=>u.hasPendingPermissionFor(R)});u.registerExtension("_agent/listSkills",R=>B.listSkills(R.params)),u.registerExtension("_agent/addSkills",R=>B.addSkills(R.params)),u.registerExtension("_agent/removeSkills",R=>B.removeSkills(R.params)),u.registerExtension("_agent/publishSkill",R=>B.publishSkill(R.params)),u.registerExtension("_agent/getFileTree",R=>B.getFileTree(R.params)),u.registerExtension("_agent/getFileContent",R=>B.getFileContent(R.params)),u.registerExtension("_agent/update",R=>B.updateAgent(R.params)),u.registerExtension("_agent/disconnect",R=>B.disconnectAgent(R.params)),u.registerExtension("_agent/switchModel",R=>B.switchModel(R.params)),u.registerExtension("_agent/reset",R=>B.resetAgent(R.params)),u.registerExtension("_agent/repair",R=>B.repairAgent(R.params)),u.registerExtension("_agent/delete",R=>B.deleteAgent(R.params)),u.registerExtension("_agent/upgrade",R=>B.upgradeBridge(R.params));let N=new ms({paths:t,handlers:B,agentManager:h,sendDetail:R=>u.sendRequest("_agent/detail",R)});O.ref=N;let $=async R=>{await Promise.allSettled(R.map(async z=>{try{await B.disconnectAgent({agentId:z.agentId,reason:`auth_failure: code=${z.code} ${z.message}`}),G.info("agent disconnected due to auth failure from heartbeat response",{agentId:z.agentId,code:z.code,message:z.message})}catch(j){G.warn("disconnect during authFailure handling failed (ignored)",{agentId:z.agentId,err:String(j)})}}))};a.onConnect(({initial:R})=>{G.info("frontier upstream connected, triggering detail sync",{initial:R}),N.syncAll(R?"initial-connect":"reconnect").catch(z=>G.warn("detail sync top-level error (ignored)",{err:String(z)}))});let K=new ko({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[rs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let z=R,j=z?.privatecode,ee=z?.pairing_code;if(!j||!ee)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Xe=Li(z.env),xe=z.handshake_url,pe=z.frontier_url,It=Qx(z.env,xe,pe),xt=!!x&&x!==j,nn=g!==void 0&&g!==It,Ut=xt||nn,rn=await Gc({privatecode:j,...xe?{endpoint:xe}:{},ppeOverride:Xe});if(Ut){G.warn("pair config switched, resetting agents",{pcChanged:xt,envChanged:nn,previousPc:x?na(x):"",nextPc:na(j),previousEnvKey:g??"",nextEnvKey:It});for(let Ie of[...u.agents.values()])await Ie.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ie.agentId);u.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new Kr,"pair switch").catch(()=>{})}w=rn.deviceId,us({deviceId:w,pid:process.pid}),xd({patToken:j,env:z.env}).catch(Ie=>G.warn("coze-cli setup error (ignored)",{err:String(Ie)}));let Zr=new ts({handshake:rn,privatecode:j,...pe?{urlOverride:pe}:{},ppeOverride:Xe,getPatTokenForAgent:Ie=>u.agents.get(Ie)?.patToken});await a.swap(Zr,"pair");try{let Ie=new Vn;o.frameworksCache=await Ie.detectAll(),await ji(o),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ie){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ie)})}let we=Object.keys(o.frameworksCache??{});try{let Ie=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:j,frameworks:we,_meta:{cozeDeviceId:w}});G.info("_agent/pair ok",{pairResult:Ie}),x=j,g=It,S=Xe,_=xe,z.mock_scenario!==void 0&&(u.setMockScenario(z.mock_scenario),G.info("mock scenario set",{scenario:z.mock_scenario})),ns(j,t).catch(De=>G.warn("writePatToken after /pair failed (ignored)",{err:String(De)})),v||(v=new Mi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>N.retryPending().catch(De=>G.warn("detailSync.retryPending failed (ignored)",{err:String(De)})),onAuthFailures:$})),v.start(),b(),Ut&&ra(t,h).catch(De=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(De)}));let tr;return z.agent_id&&(tr=await XS(z.agent_id,t,h,De=>u.sendRequest("_agent/detail",De),j).catch(De=>(G.error("--agent-id ensureAgent failed",{agentId:z.agent_id,err:String(De)}),{ok:!1,agentId:z.agent_id??"",note:String(De)}))),{ok:!0,note:"paired with cloud",...tr?{agent:tr}:{}}}catch(Ie){return G.error("_agent/pair failed",{err:String(Ie)}),{ok:!1,note:`pair failed: ${String(Ie)}`}}}},{method:"POST",path:"/connect",handler:R=>D(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let z=R;return{ok:!0,result:await h.createAgent(z)}}},{method:"POST",path:"/agent/send",handler:async R=>{let z=R;if(!z?.agentId||!z?.sessionId||!z?.kind||!z?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=z;return await(j.groupFile?oh:sh)(j,{core:u,patToken:x,handshakeBase:_,ppeOverride:S})}catch(j){if(j instanceof T)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async R=>{let z=R?.agent_id,j=await u.reloadAgents(z);return G.info("IPC /reload: recycled agent subprocesses",{agentId:z??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(G.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ne,token:Z}=await K.start();try{await Vx(t.libEntry,t)}catch(R){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),QS({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Vn().detectAll(),await ji(o),o.frameworksCache)}).catch(R=>G.warn("startup warmup error (ignored)",{err:String(R)})),Dl().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(an(),Rl));for(let z of["claude-code","codex"]){let j=await R(z);j&&G.info("acp wrapper version",{framework:z,version:j})}}).catch(R=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let ie=null,oe={port:ne,token:Z,core:u,ipc:K,shutdown(R){return ie||(G.info("daemon shutdown",{reason:R}),ie=(async()=>{v?.stop(),I?.stop(),await u.stop(R),await K.stop(),await e.release()})(),ie)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{oe.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>A0()),process.on("unhandledRejection",R=>{G.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{G.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
118
+ `)}catch{}process.exit(1)}),G.info("daemon ready",{port:ne,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),t1({cliSpawned:process.env[rs]==="1",readPatToken:()=>Zo(t),connect:D}).catch(R=>G.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),oe}async function YS(t){return xs(t).length>0}function na(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Qx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function ZS(t,e){let r=xs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(ln(),gs));for(let a of r){await o(a,t).catch(d=>G.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),G.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),G.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){G.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function XS(t,e,r,i,o){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(ln(),gs)),d=await a(t,e);if(d){if(d.deletedAt)throw new T("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);G.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=tp(d),w={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(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}G.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new T("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function QS(t){let e=t.logger??G;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 ZS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ra(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await e1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ra(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(()=>(ln(),gs));G.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=0;for(let u of i){let h;try{h=await o(u,t)}catch(x){G.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){G.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){G.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{G.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=tp(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),a+=1}catch(x){G.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return G.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function e1(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 h0(o,t)).status==="refreshed"&&(i+=1)}catch(a){G.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(a)})}return i>0&&G.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function t1(t){let e=t.logger??G;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 tp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ea();Oe();import{readFile as np}from"node:fs/promises";var tn=class{paths;constructor(e){this.paths=e??Q()}async probe(e=1e3){let r=await ia(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:r1(i)}}}async request(e){let r=await ia(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 a=new AbortController,d=setTimeout(()=>a.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:a.signal}),h=await u.text();return{status:u.status,body:n1(h)}}finally{clearTimeout(d)}}};async function ia(t){try{let[e,r]=await Promise.all([np(t.portFile,"utf8"),np(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 n1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function r1(t){return t instanceof Error?t.message:String(t)}Jt();te();sr();import{spawn as i1}from"node:child_process";import{userInfo as ip}from"node:os";var Wd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",s1=new Set(["bash","zsh","sh","dash","ksh"]),rp=$e("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),o1=2e3;function a1(t,e=Wd){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),a={};for(let d of o.split(`
119
+ `)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function c1(){let t=(process.env.SHELL??"").trim()||(ip().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return s1.has(e)?t:null}function d1(t){return new Promise(e=>{let r=`printf '%s' '${Wd}'; env; printf '%s' '${Wd}'`,i;try{i=i1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ip().homedir}})}catch{e(null);return}let o="",a=!1,d=g=>{try{i.pid&&process.kill(-i.pid,g)}catch{}},u=g=>{a||(a=!0,clearTimeout(h),clearTimeout(x),e(g))};i.stdout?.on("data",g=>{o+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let h=setTimeout(()=>d("SIGTERM"),rp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},rp+o1)})}async function Kd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=c1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??d1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=a1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Oe();function Rn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let a=t[o],d=!1;for(let u of e){if(a===u){i=t[o+1],o+=1,d=!0;break}if(a.startsWith(`${u}=`)){i=a.slice(u.length+1),d=!0;break}}d||r.push(a)}return{value:i,rest:r}}an();import{chmod as l1,copyFile as sp,mkdir as ap,readFile as ss,rename as op,rm as Jd,stat as cp,writeFile as u1}from"node:fs/promises";import{homedir as SD}from"node:os";import{dirname as f1,join as Pe,resolve as Yd,sep as is}from"node:path";import{fileURLToPath as h1}from"node:url";Jt();te();Oe();function $r(t,e,r,i){et(t.bridgeLogsDir,e,"dist-install",r,i)}function dp(){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 x1(){return{darwin:{arm64:Pe("vendor","aarch64-apple-darwin","bin","codex"),x64:Pe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Pe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Pe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Pe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Pe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function p1(t){let e=h1(t),r=f1(e),i=`${is}src${is}`;if(r.includes(i)||r.endsWith(`${is}src${is}cli`))return null;let o=Yd(r,"index.js"),a=Yd(r,"..","package.json");return{dist:o,pkgJson:a}}async function Zd(t={}){let e=t.paths??Q(),r=p1(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 a,d;try{let v=JSON.parse(await ss(o,"utf8"));a=v.version??"unknown",d=v.dependencies??{}}catch(v){throw $r(e,"error","cannot read source package.json",{err:String(v)}),new Error(`cannot read source package.json: ${String(v)}`,{cause:v})}let u=fs.map(v=>({name:v,spec:d[v]??"latest"})),h=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await Ao(e.configFile)??{},g=x.libVersion,w=await ss(e.libEntry).then(()=>!0).catch(()=>!1),S=g===a,_=await lp(e,u);if(S&&w&&_)return{kind:"already-current",libVersion:a};if(!S||!w){await ap(e.libDir,{recursive:!0}),await sp(i,e.libEntry),await sp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Yd(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
120
+ `;await ss(v,"utf8").catch(()=>null)!==I&&await u1(v,I)}return _||(t.installWrappers?await t.installWrappers(e,h):await w1(e,h,u)),x.libVersion=a,await ji(x,e.configFile),$r(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:a}),S&&w?{kind:"already-current",libVersion:a}:g?{kind:"version-changed",fromVersion:g,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function lp(t,e){for(let r of e){let i=Pe(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await ss(i,"utf8"))}catch(d){return $r(t,"debug","wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(d)}),!1}let a=o.version;if(!a)return $r(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!g1(a,r.spec))return $r(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:a,expected:r.spec}),!1}return!!await up(Pe(t.libDir,"node_modules"))}function g1(t,e){let r=$d(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=$d(i.slice(1));if(!a)return!0;if(Vd(r,a)<0)return!1;let d=m1(a);return Vd(r,d)<0}let o=$d(i);return o?Vd(r,o)===0:!0}function m1(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function $d(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Vd(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 w1(t,e,r){await E1(t.installLock,async()=>{if(await lp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${is}.staging-${process.pid}-${i}`,a=Pe(o,"node_modules"),d=Pe(t.libDir,"node_modules");try{await ap(o,{recursive:!0}),await _1(e,o),await y1(a);let u=`${d}.trash-${i}`;await op(d,u).catch(()=>{}),await op(a,d),await Jd(u,{recursive:!0,force:!0}).catch(()=>{}),$r(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Jd(o,{recursive:!0,force:!0}).catch(()=>{})}})}function _1(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let a=rt("npm",r,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",h=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(h)}`))}),a.once("close",h=>{clearTimeout(u),h===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function y1(t){for(let e of fs){let r=Pe(t,...e.split("/")),i=JSON.parse(await ss(Pe(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let a=Pe(t,".bin",o),d=await cp(a);process.platform!=="win32"&&!(d.mode&73)&&await l1(a,d.mode|73).catch(()=>{})}if(!await up(t)){let e=dp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function up(t){let e=dp(),r=x1();if(!e||!r)return!0;let i=Pe(t,"@openai","codex"),o=Pe(t,...e.split("/")),a=[Pe(i,"package.json"),Pe(i,"bin","codex.js"),Pe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Pe(o,"package.json"),Pe(o,r)];return(await Promise.all(a.map(u=>cp(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function E1(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(a=>setTimeout(a,500))}try{return await e()}finally{i&&await Jd(t,{force:!0}).catch(()=>{})}}Ta();te();Oe();import{closeSync as hp,fstatSync as xp,openSync as pp,readFileSync as b1,readSync as v1,readdirSync as S1,statSync as I1}from"node:fs";import{join as sa}from"node:path";var A1=new Set(["debug","info","warn","error"]);function gp(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 a=Rn(e,"--level");e=a.rest;let d=Rn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),h=Number.isInteger(u)&&u>=0?u:200,x=a.value&&A1.has(a.value)?a.value:void 0,g={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(g.agentId=r.value),i.value&&(g.date=i.value),x&&(g.level=x),d.value&&(g.grep=d.value),g}function T1(t,e){return t.agentId?sa(Ve(t.agentId,e).logs,or("agent",t.date)):sa(e.bridgeLogsDir,or("bridge",t.date))}function k1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function C1(t,e){let r;try{r=S1(t)}catch{return[]}let i=[];for(let o of r){let a=Aa(o,e);if(!a)continue;let d=0;try{d=I1(sa(t,o)).size}catch{}i.push({file:sa(t,o),date:a,size:d})}return i.sort((o,a)=>a.date.localeCompare(o.date)),i}function mp(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"&&!Il(r,e.level))return!1}return!0}var fp={debug:"90",info:"36",warn:"33",error:"31"},R1=new Set(["ts","level","module","msg"]);function P1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function wp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=P1(r.ts),o=typeof r.level=="string"?r.level:"",a=o.toUpperCase().padEnd(5);e.color&&fp[o]&&(a=`\x1B[${fp[o]}m${a}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",h=Object.entries(r).filter(([x])=>!R1.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${a} ${d} ${u}${h}`}function D1(t,e,r){let a=b1(t,"utf8").split(`
121
+ `).filter(d=>d.length>0).filter(d=>mp(d,{level:e.level,grep:e.grep}));for(let d of k1(a,e.lines))process.stdout.write(`${wp(d,{raw:e.raw,color:r})}
122
+ `)}async function _p(t,e){let r=e.paths??Q(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ve(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=C1(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
123
+ `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
124
+ `);return 0}let o=t.date??Dn(new Date),a=T1({agentId:t.agentId,date:o},r);try{D1(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
119
125
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
120
126
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
121
- `),1}return t.follow&&await CS(c,t,i),0}var kS=500;function TS(t){try{let e=pp(t,"r");try{return xp(e).size}finally{hp(e)}}catch{return 0}}async function CS(t,e,r){let i=TS(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let f=pp(t,"r");try{let x=xp(f).size;if(x>i){let g=Buffer.allocUnsafe(x-i),m=mS(f,g,0,g.length,i);u=g.subarray(0,m).toString("utf8"),i+=m}}finally{hp(f)}}catch{}if(u){let f=(o+u).split(`
122
- `);o=f.pop()??"";for(let x of f)x.length>0&&mp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${wp(x,{raw:e.raw,color:r})}
123
- `)}await new Promise(f=>setTimeout(f,kS))}}finally{process.off("SIGINT",d)}}import{basename as RS,resolve as PS}from"node:path";Me();var DS=9e4,OS={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 LS(t){return OS[t]??1}async function yp(t,e={}){let r=e.paths??ee();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>
127
+ `),1}return t.follow&&await N1(a,t,i),0}var O1=500;function L1(t){try{let e=pp(t,"r");try{return xp(e).size}finally{hp(e)}}catch{return 0}}async function N1(t,e,r){let i=L1(t),o="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let h=pp(t,"r");try{let x=xp(h).size;if(x>i){let g=Buffer.allocUnsafe(x-i),w=v1(h,g,0,g.length,i);u=g.subarray(0,w).toString("utf8"),i+=w}}finally{hp(h)}}catch{}if(u){let h=(o+u).split(`
128
+ `);o=h.pop()??"";for(let x of h)x.length>0&&mp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${wp(x,{raw:e.raw,color:r})}
129
+ `)}await new Promise(h=>setTimeout(h,O1))}}finally{process.off("SIGINT",d)}}import{basename as M1,resolve as B1}from"node:path";Oe();var F1=9e4,z1={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 U1(t){return z1[t]??1}async function yp(t,e={}){let r=e.paths??Q();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>
124
130
  `),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.
125
131
  `),3;let i=await ia(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.
126
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:PS(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 NS(i,"/agent/send",o,DS)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
127
- `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
128
- `),LS(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
- `);else{let d=t.name??RS(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})
130
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${MS(c.bytes)})
131
- `)}return 0}async function NS(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 MS(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Rp=W("cli");function Ke(t,e){let{value:r,rest:i}=Rn(t,e);return{value:r,rest:i}}function ua(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
- `)}function o2(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 a2(e.slice(1));if(e[0]==="log")return{mode:"log",...gp(e.slice(1))};if(e[0]==="connect")return c2(e.slice(1));if(e.includes("--status"))return ua("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ua("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ua("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ua("--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:x,rest:g}=Ke(r,"--handshake-url");r=g;let{value:m,rest:S}=Ke(r,"--frontier-url");r=S;let{value:y,rest:b}=Ke(r,"--mock-scenario");r=b;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),x&&(T.handshakeUrl=x),m&&(T.frontierUrl=m),y&&(T.mockScenario=y),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function a2(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:x}=Ke(i,"--agent-id");i=x;let{value:g,rest:m}=Ke(i,"--session-id");i=m;let{value:S,rest:y}=Ke(i,"--mime");i=y;let b=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),b&&(A.groupFile=!0),S&&(A.mimeType=S),A}function c2(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:x}=Ke(e,"--frontier-url");e=x;let{value:g,rest:m}=Ke(e,"--mock-scenario");e=m;let S=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),S&&(y.skipRebuildEnv=!0),y}var d2=`
132
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:B1(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},a;try{a=await q1(i,"/agent/send",o,F1)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
133
+ `),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
134
+ `),U1(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
135
+ `);else{let d=t.name??M1(o.path);if(t.groupFile){let u=a.uri.length>60?`${a.uri.slice(0,57)}...`:a.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
136
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${G1(a.bytes)})
137
+ `)}return 0}async function q1(t,e,r,i){let o=new AbortController,a=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(a)}}function G1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Rp=q("cli");function je(t,e){let{value:r,rest:i}=Rn(t,e);return{value:r,rest:i}}function ua(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
138
+ `)}function fI(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}=je(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 hI(e.slice(1));if(e[0]==="log")return{mode:"log",...gp(e.slice(1))};if(e[0]==="connect")return xI(e.slice(1));if(e.includes("--status"))return ua("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ua("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ua("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ua("--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}=je(r,"--pat-token");r=o;let{value:a,rest:d}=je(r,"--pair-code");r=d;let{value:u,rest:h}=je(r,"--env");r=h;let{value:x,rest:g}=je(r,"--handshake-url");r=g;let{value:w,rest:S}=je(r,"--frontier-url");r=S;let{value:_,rest:v}=je(r,"--mock-scenario");r=v;let{value:I}=je(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let k={mode:"pair",privatecode:i,pairingCode:a};return u&&(k.env=u),x&&(k.handshakeUrl=x),w&&(k.frontierUrl=w),_&&(k.mockScenario=_),I&&(k.agentId=I),A&&(k.skipRebuildEnv=!0),k}function hI(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:a}=je(i,"--caption");i=a;let{value:d,rest:u}=je(i,"--name");i=u;let{value:h,rest:x}=je(i,"--agent-id");i=x;let{value:g,rest:w}=je(i,"--session-id");i=w;let{value:S,rest:_}=je(i,"--mime");i=_;let v=i.includes("--group-file");i=i.filter(k=>k!=="--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),h&&(A.agentId=h),g&&(A.sessionId=g),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function xI(t){let e=t,{value:r,rest:i}=je(e,"--pat-token");e=i;let{value:o,rest:a}=je(e,"--env");e=a;let{value:d,rest:u}=je(e,"--handshake-url");e=u;let{value:h,rest:x}=je(e,"--frontier-url");e=x;let{value:g,rest:w}=je(e,"--mock-scenario");e=w;let S=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),d&&(_.handshakeUrl=d),h&&(_.frontierUrl=h),g&&(_.mockScenario=g),S&&(_.skipRebuildEnv=!0),_}var pI=`
133
139
  coze-bridge - local bridge daemon for cloud Agent Service
134
140
 
135
141
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -210,57 +216,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
210
216
 
211
217
  Internal:
212
218
  <node> <entry> --daemon daemon mode (OS supervisor only)
213
- `.trimStart();async function Pp(t=process.argv,e={}){let r=o2(t);switch(r.mode){case"help":return process.stdout.write(d2),0;case"version":return process.stdout.write(`${Ot}
214
- `),0;case"daemon":{try{await ep()}catch(i){return Rp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return l2(e);case"stop":return Op(e);case"reload":return h2(r.agentId,e);case"log":return _p(r,e);case"update":return u2(e);case"purge":return p2(e);case"service-install":return g2(e);case"service-uninstall":return m2(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),w2(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),_2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return yp({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 Dp(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 l2(t){let e=t.paths??ee(),r=new tn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
219
+ `.trimStart();async function Pp(t=process.argv,e={}){let r=fI(t);switch(r.mode){case"help":return process.stdout.write(pI),0;case"version":return process.stdout.write(`${Dt}
220
+ `),0;case"daemon":{try{await ep()}catch(i){return Rp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return gI(e);case"stop":return Op(e);case"reload":return _I(r.agentId,e);case"log":return _p(r,e);case"update":return mI(e);case"purge":return EI(e);case"service-install":return bI(e);case"service-uninstall":return vI(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),SI(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),II(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return yp({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 Dp(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 gI(t){let e=t.paths??Q(),r=new tn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
221
  `),1;if(i.kind==="stale")return await Dp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
216
222
  `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
217
223
  ${JSON.stringify(o.body,null,2)}
218
- `),0}async function Op(t){let e=t.paths??ee(),r=new tn(e),i=t.daemonSweep??(async()=>{let f=T0();return await C0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await as(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
+ `),0}async function Op(t){let e=t.paths??Q(),r=new tn(e),i=t.daemonSweep??(async()=>{let h=T0();return await k0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},a=await as(t),d=!1;if(a)try{await a.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
219
225
  `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
220
226
  `:`coze-bridge: not running
221
227
  `),0;if(u.kind==="stale")return await Dp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
222
228
  `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
223
- `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
224
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
225
- `),1)}}async function u2(t){return await Op(t),(t.spawnNpx??f2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function f2(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)}
226
- `),e(1)})})}async function h2(t,e){let r=new tn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
227
- `),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)
228
- `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
229
+ `),0}catch(h){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
230
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
231
+ `),1)}}async function mI(t){return await Op(t),(t.spawnNpx??wI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function wI(t){return new Promise(e=>{let r=rt("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)}
232
+ `),e(1)})})}async function _I(t,e){let r=new tn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
233
+ `),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 a=o.body.recycled??[];return t&&a.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
234
+ `):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
229
235
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
230
236
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
231
- `),1}}async function as(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(()=>(kp(),Ap)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Lp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??y2,c=t.paths??ee();if(r.kind==="connected"){if(!x2(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 Cp(c.pidFile,o)}let d=t.spawnDaemon??Xx,u=await as(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Tp(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 Cp(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)}
237
+ `),1}}async function as(t){if(t.supervisor){let a=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:a.platform,install:u=>a.install(d,u),uninstall:()=>a.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Tp(),Ap)),i=e(),o=r();return{platform:i.platform,install:a=>i.install(o,a),uninstall:()=>i.uninstall(o)}}async function Lp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??AI,a=t.paths??Q();if(r.kind==="connected"){if(!yI(r.body))return r;et(a.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:r.body}),await e.request({method:"POST",path:"/shutdown"}).catch(h=>et(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await Cp(a.pidFile,o)}let d=t.spawnDaemon??Xx,u=await as(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await kp(e,i,o);if(h.kind==="connected")return h;et(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){et(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}et(a.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await Cp(a.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)}
232
238
  `));return process.stdout.write(`coze-bridge: starting daemon...
233
- `),await d({paths:t.paths}),Tp(e,i,o)}function x2(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 p2(t){let e=new tn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
239
+ `),await d({paths:t.paths}),kp(e,i,o)}function yI(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 EI(t){let e=new tn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
234
240
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
235
241
  `)}await new Promise(d=>setTimeout(d,500))}let i=await as(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
236
242
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
237
- `)}let o=t.paths??ee(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
243
+ `)}let o=t.paths??Q(),{rm:a}=await import("node:fs/promises");try{await a(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
238
244
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
239
245
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
240
- `),0}async function g2(t){let e=await as(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
246
+ `),0}async function bI(t){let e=await as(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
241
247
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
242
248
  `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
243
- `),1}}async function m2(t){let e=await as(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
249
+ `),1}}async function vI(t){let e=await as(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
244
250
  `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
245
- `),1}}async function Np(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)
246
- `),rt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function w2(t,e,r,i={},o,c){let d=new tn(r.paths),u=r.paths??ee(),f=await Np(u,c,r.reconstructEnv??Kd);if(await sd(u,f).catch(m=>rt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!r.skipDistInstall){let m=await Yd({paths:r.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
247
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
251
+ `),1}}async function Np(t,e,r){if(e)return et(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(et(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(et(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)
252
+ `),et(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function SI(t,e,r,i={},o,a){let d=new tn(r.paths),u=r.paths??Q(),h=await Np(u,a,r.reconstructEnv??Kd);if(await sd(u,h).catch(w=>et(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!r.skipDistInstall){let w=await Zd({paths:r.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
253
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
248
254
  `)}let x=await Lp(r,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
249
- `),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 m=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let S=m.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
255
+ `),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 w=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let S=w.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
250
256
  `),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"
251
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
252
- `),1}catch(m){return process.stderr.write(`coze-bridge: pair failed: ${String(m)}
253
- `),1}}async function _2(t,e,r={},i){let o=e.paths??ee(),c=t??await Yo(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 Np(o,i,e.reconstructEnv??Kd);if(await sd(o,u).catch(g=>rt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await Yd({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
257
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
258
+ `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
259
+ `),1}}async function II(t,e,r={},i){let o=e.paths??Q(),a=t??await Zo(o);if(!a)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new tn(e.paths),u=await Np(o,i,e.reconstructEnv??Kd);if(await sd(o,u).catch(g=>et(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await Zd({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
254
260
  `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
255
- `)}let f=await Lp(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
256
- `),1;let x={privatecode:c};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let g=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
257
- `),t!==void 0&&await ns(c,o).catch(m=>Rp.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
261
+ `)}let h=await Lp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
262
+ `),1;let x={privatecode:a};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let g=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
263
+ `),t!==void 0&&await ns(a,o).catch(w=>Rp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
258
264
  `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
259
- `),1}}async function Tp(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 Cp(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||!Ui(u))return;await e(i)}}function y2(t){return new Promise(e=>setTimeout(e,t))}ne();function E2(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 Mp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=E2(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
+ `),1}}async function kp(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await r(200)}return t.probe(500)}async function Cp(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let a=0;a<r;a++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Ui(u))return;await e(i)}}function AI(t){return new Promise(e=>setTimeout(e,t))}te();function TI(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 Mp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=TI(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
260
266
  `),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
261
267
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
262
268
  npx -y coze-bridge@latest stop
263
269
  npx -y coze-bridge@latest connect
264
270
 
265
- `)}Mp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Sl("warn");Pp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
271
+ `)}Mp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&vl("warn");Pp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
266
272
  `),process.exit(1)});