coze-bridge 0.2.3-alpha.7 → 0.2.3-alpha.9

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 +89 -89
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var Bg=Object.create;var Oa=Object.defineProperty;var Fg=Object.getOwnPropertyDescriptor;var zg=Object.getOwnPropertyNames;var Ug=Object.getPrototypeOf,Gg=Object.prototype.hasOwnProperty;var ue=(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),La=(t,e)=>{for(var r in e)Oa(t,r,{get:e[r],enumerable:!0})},Hg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zg(e))!Gg.call(t,o)&&o!==r&&Oa(t,o,{get:()=>e[o],enumerable:!(i=Fg(e,o))||i.enumerable});return t};var Ht=(t,e,r)=>(r=t!=null?Bg(Ug(t)):{},Hg(e||!t||!t.__esModule?Oa(r,"default",{value:t,enumerable:!0}):r,t));function Ve(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ar=Qe(()=>{"use strict"});import{createWriteStream as jg,mkdirSync as qg,readdirSync as Wg,unlinkSync as Kg}from"node:fs";import{join as kl}from"node:path";function Cn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function cr(t,e){return`${t}-${e}.log`}function Na(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function $g(t,e,r){let i=c=>{let[l,u,f]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>r}function ps(t,e,r,i){let o;try{o=Wg(t)}catch{return}for(let c of o){let l=Na(c,e);if(l&&$g(l,r,i))try{Kg(kl(t,c))}catch{}}}var ri,Ma=Qe(()=>{"use strict";ri=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Cn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{qg(this.dir,{recursive:!0});let r=jg(kl(this.dir,cr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var Bg=Object.create;var Na=Object.defineProperty;var zg=Object.getOwnPropertyDescriptor;var Fg=Object.getOwnPropertyNames;var Ug=Object.getPrototypeOf,Gg=Object.prototype.hasOwnProperty;var fe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var rt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ma=(t,e)=>{for(var r in e)Na(t,r,{get:e[r],enumerable:!0})},Hg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fg(e))!Gg.call(t,o)&&o!==r&&Na(t,o,{get:()=>e[o],enumerable:!(i=zg(e,o))||i.enumerable});return t};var jt=(t,e,r)=>(r=t!=null?Bg(Ug(t)):{},Hg(e||!t||!t.__esModule?Na(r,"default",{value:t,enumerable:!0}):r,t));function Ze(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var lr=rt(()=>{"use strict"});import{createWriteStream as qg,mkdirSync as jg,readdirSync as Wg,unlinkSync as Kg}from"node:fs";import{join as Rl}from"node:path";function Nn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function ur(t,e){return`${t}-${e}.log`}function Ba(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function $g(t,e,r){let i=c=>{let[d,u,x]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,x??1)};return Math.floor((i(e)-i(t))/864e5)>r}function ms(t,e,r,i){let o;try{o=Wg(t)}catch{return}for(let c of o){let d=Ba(c,e);if(d&&$g(d,r,i))try{Kg(Rl(t,c))}catch{}}}var oi,za=rt(()=>{"use strict";oi=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Nn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{jg(this.dir,{recursive:!0});let r=qg(Rl(this.dir,ur(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&&ps(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Vg,mkdirSync as Jg}from"node:fs";import{join as Zg}from"node:path";function Rl(t){let e=t.retentionDays??Qg,r=t.clock??(()=>Cn(new Date));ms={bridgeSink:new ri(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ri(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();ps(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ps(t.agentLogsDir(o),"agent",i,e)}function em(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Pl(t){Ba=t}function Dl(t){return dr[Ba]<=dr[t]}function Cl(t,e){let r=dr[t];return r===void 0?!0:r>=dr[e]}function ws(t){Tl={...t}}function Ol(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)),l=e(o%60);return`${Cn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function ct(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Ol(new Date),level:e,module:r,msg:i,...o})}
11
- `;Jg(t,{recursive:!0}),Vg(Zg(t,cr("bridge",Cn(new Date))),c)}catch{}}function tm(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function gs(t,e,r,i,o){if(dr[t]<dr[Ba])return;let c=`${JSON.stringify({ts:Ol(new Date),level:t,module:e,msg:r,...Tl,...i})}
12
- `;if(ms){let l=tm(o,i),u=l?em(ms,l):ms.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Xg.write(c):Yg.write(c)}function G(t,e){return{debug:(r,i)=>gs("debug",t,r,i,e),info:(r,i)=>gs("info",t,r,i,e),warn:(r,i)=>gs("warn",t,r,i,e),error:(r,i)=>gs("error",t,r,i,e),child:r=>G(`${t}.${r}`,e),forAgent:r=>G(t,r)}}var dr,Ba,Yg,Xg,Tl,Qg,ms,ee=Qe(()=>{"use strict";ar();Ma();dr={debug:10,info:20,warn:30,error:40},Ba=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Yg=process.stdout,Xg=process.stderr,Tl={},Qg=Ve("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ms=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 Bl={};La(Bl,{ACP_WRAPPER_NPM_PACKAGES:()=>_s,_resetAcpInstallerForTests:()=>am,_setBinaryPathCacheForTests:()=>cm,buildAcpSpawn:()=>si,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>ys,pickWhichLine:()=>Ua,probeAcpVersion:()=>om,resolveAcpCommand:()=>Ml});import{readFileSync as Ll}from"node:fs";import{createRequire as nm}from"node:module";import{dirname as rm,resolve as im}from"node:path";function Ua(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function sm(t){let e=Nl.resolve(`${t.npmPackage}/package.json`),r=rm(e),i=JSON.parse(Ll(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 im(r,o)}async function lr(t,e){let r=za[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ii.get(t);if(i)return i;try{let o=sm(r);return ii.set(t,o),Fa.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Fa.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(o)}),new 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 om(t){let e=za[t];if(e)try{let r=Nl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Ll(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Fa.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function ys(t){return ii.get(t)}function Ml(t,e){if(e)return e;let r=ys(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 si(t,e,r){if(e)return{command:e,args:[...r]};let i=Ml(t);return{command:process.execPath,args:[i,...r]}}function am(){ii.clear()}function cm(t,e){ii.set(t,e)}var Fa,za,_s,Nl,ii,dn=Qe(()=>{"use strict";We();ee();Fa=G("agents.acp-installer"),za={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},_s=Object.values(za).filter(t=>t!==void 0).map(t=>t.npmPackage),Nl=nm(import.meta.url),ii=new Map});import{chmod as lm,mkdir as um,readFile as fm,rename as hm,rm as xm,writeFile as pm}from"node:fs/promises";import{dirname as gm}from"node:path";async function ur(t){try{let e=await fm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function dt(t,e,r){await um(gm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await pm(i,e,{encoding:"utf8",mode:r?.mode}),await hm(i,t),r?.mode!==void 0&&await lm(t,r.mode)}catch(o){throw await xm(i,{force:!0}).catch(()=>{}),o}}async function fr(t,e,r){await dt(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var jt=Qe(()=>{"use strict"});import{promises as Ul,readdirSync as mm}from"node:fs";import{homedir as wm}from"node:os";import{sep as _m,join as Te,resolve as Gl}from"node:path";function J(t){let e=t??wm(),r=Te(e,".coze"),i=Te(r,"bridge"),o=Te(i,"lib"),c=Te(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Te(o,"index.js"),binDir:Te(i,"bin"),pidFile:Te(i,"bridge.pid"),portFile:Te(i,"bridge.port"),tokenFile:Te(i,"bridge.token"),patTokenFile:Te(i,"pat-token"),agentEnvFile:Te(i,"agent-env.json"),logFile:Te(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Te(c,"daemon-stdio.log"),installLock:Te(i,"install.lock"),configFile:Te(i,"config.json"),agentsRoot:Te(r,"agents")}}function Be(t,e=J()){let r=Te(e.agentsRoot,t);return{root:r,config:Te(r,"config.json"),workspace:Te(r,"workspace"),logs:Te(r,"logs")}}function bs(t=J()){try{return mm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function oi(t,e){let r=await Ul.realpath(Gl(t)).catch(()=>null);if(!r)return!1;let i=await Ul.realpath(Gl(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+_m)}var Re=Qe(()=>{"use strict"});var vs={};La(vs,{AGENT_CONFIG_FILE_MODE:()=>Es,enforceAgentConfigMode:()=>Em,loadAgentConfig:()=>ve,persistAgentSessions:()=>ai,persistAgentSkills:()=>ci,saveAgentConfig:()=>Fe});import{chmod as ym,stat as bm}from"node:fs/promises";function ve(t,e){return ur(Be(t,e).config)}function Fe(t,e){return fr(Be(t.agentId,e).config,t,{mode:Es})}async function Em(t,e){if(process.platform==="win32")return;let r=Be(t,e).config;try{let i=await bm(r);if(!i.isFile())return;let o=i.mode&511;o!==Es&&(await ym(r,Es),Hl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Hl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ai(t,e,r){let i=await ve(t,r);i&&(i.sessions=Object.fromEntries(e),await Fe(i,r))}async function ci(t,e,r){let i=await ve(t,r);i&&(i.skills=e,await Fe(i,r))}var Hl,Es,qt=Qe(()=>{"use strict";jt();ee();Re();Hl=G("agent-config"),Es=384});var ja=ae((wI,Wl)=>{Wl.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 Is=ae($l=>{var Kl={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 Tm(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(Kl))$l[t]=Tm(Kl[t])});var Xl=ae((yI,Yl)=>{var Rm=ue("fs"),Le=ue("path"),Vl=ja(),Pm=Is(),Dm=typeof process=="object"&&process.platform==="win32",Jl=t=>typeof t=="object"&&t!==null,Zl=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Se(t){this.sep=Le.sep,this.fs=Rm,Jl(t)&&Jl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Yl.exports=Se;Se.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var l;try{l=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(l&&l.isFile())throw Pm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Se.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var l=Le.dirname(t);o.fs.existsSync(l)||o.makeDir(l);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!r)return o(!1);c.fs.stat(t,function(u,f){if(l&&f.isDirectory())return o(!1);var x=Le.dirname(t);c.fs.exists(x,function(g){g||c.makeDir(x),c.fs.open(t,"w",438,function(w,S){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Se.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let f=Le.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&l.push(Le.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(l=l.concat(r(f,o,c)))}),l}return r(t,void 0,!0)};Se.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=Le.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);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),--l||e(null,i)}):--l||e(null,i))})})})};Se.prototype.getAttributes=function(){};Se.prototype.setAttributes=function(){};Se.crc32update=function(t,e){return Zl[(t^e)&255]^t>>>8};Se.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Se.crc32update(r,t[i++]);return~r>>>0};Se.methodToString=function(t){switch(t){case Vl.STORED:return"STORED ("+t+")";case Vl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.posix.join(".",e)};Se.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Se.sanitize=function(t,e){t=Le.resolve(Le.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Le.normalize(Le.join(t,r.slice(i,o).join(Le.sep)));if(c.indexOf(t)===0)return c}return Le.normalize(Le.join(t,Le.basename(e)))};Se.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Se.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Se.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Se.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Se.isWin=Dm;Se.crcTable=Zl});var eu=ae((bI,Ql)=>{var Cm=ue("path");Ql.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=Cm.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 nu=ae((EI,tu)=>{tu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=ae((vI,xr)=>{xr.exports=Xl();xr.exports.Constants=ja();xr.exports.Errors=Is();xr.exports.FileAttr=eu();xr.exports.decoder=nu()});var iu=ae((SI,ru)=>{var ln=pr(),U=ln.Constants;ru.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,l=0,u=0,f=0,x=0,g=0,w=0,S=0,y=0,v=0;t|=ln.isWin?2560:768,r|=U.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,R=b=>Math.max(0,b)&65535,C=b=>Math.max(0,b)&255;return o=ln.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return r},set flags(b){r=b},get flags_efs(){return(r&U.FLG_EFS)>0},set flags_efs(b){b?r|=U.FLG_EFS:r&=~U.FLG_EFS},get flags_desc(){return(r&U.FLG_DESC)>0},set flags_desc(b){b?r|=U.FLG_DESC:r&=~U.FLG_DESC},get method(){return i},set method(b){switch(b){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=b},get time(){return ln.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=ln.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=A(b)},get timeHighByte(){return C(o>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return l},set compressedSize(b){l=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return f},set fileNameLength(b){f=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return 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 y},set attr(b){y=A(b)},get fileAttr(){return(y||0)>>16&4095},get offset(){return v},set offset(b){v=A(b)},get encrypted(){return(r&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+x+g},get realDataOffset(){return v+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var D=b.slice(v,v+U.LOCHDR);if(D.readUInt32LE(0)!==U.LOCSIG)throw ln.Errors.INVALID_LOC();I.version=D.readUInt16LE(U.LOCVER),I.flags=D.readUInt16LE(U.LOCFLG),I.flags_desc=(I.flags&U.FLG_DESC)>0,I.method=D.readUInt16LE(U.LOCHOW),I.time=D.readUInt32LE(U.LOCTIM),I.crc=D.readUInt32LE(U.LOCCRC),I.compressedSize=D.readUInt32LE(U.LOCSIZ),I.size=D.readUInt32LE(U.LOCLEN),I.fnameLen=D.readUInt16LE(U.LOCNAM),I.extraLen=D.readUInt16LE(U.LOCEXT);let O=v+U.LOCHDR+I.fnameLen,F=O+I.extraLen;return b.slice(O,F)},loadFromBinary:function(b){if(b.length!==U.CENHDR||b.readUInt32LE(0)!==U.CENSIG)throw ln.Errors.INVALID_CEN();t=b.readUInt16LE(U.CENVEM),e=b.readUInt16LE(U.CENVER),r=b.readUInt16LE(U.CENFLG),i=b.readUInt16LE(U.CENHOW),o=b.readUInt32LE(U.CENTIM),c=b.readUInt32LE(U.CENCRC),l=b.readUInt32LE(U.CENSIZ),u=b.readUInt32LE(U.CENLEN),f=b.readUInt16LE(U.CENNAM),x=b.readUInt16LE(U.CENEXT),g=b.readUInt16LE(U.CENCOM),w=b.readUInt16LE(U.CENDSK),S=b.readUInt16LE(U.CENATT),y=b.readUInt32LE(U.CENATX),v=b.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(U.LOCHDR);return b.writeUInt32LE(U.LOCSIG,0),b.writeUInt16LE(e,U.LOCVER),b.writeUInt16LE(r,U.LOCFLG),b.writeUInt16LE(i,U.LOCHOW),b.writeUInt32LE(o,U.LOCTIM),b.writeUInt32LE(c,U.LOCCRC),b.writeUInt32LE(l,U.LOCSIZ),b.writeUInt32LE(u,U.LOCLEN),b.writeUInt16LE(f,U.LOCNAM),b.writeUInt16LE(I.extraLen,U.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(U.CENHDR+f+x+g);return b.writeUInt32LE(U.CENSIG,0),b.writeUInt16LE(t,U.CENVEM),b.writeUInt16LE(e,U.CENVER),b.writeUInt16LE(r,U.CENFLG),b.writeUInt16LE(i,U.CENHOW),b.writeUInt32LE(o,U.CENTIM),b.writeUInt32LE(c,U.CENCRC),b.writeUInt32LE(l,U.CENSIZ),b.writeUInt32LE(u,U.CENLEN),b.writeUInt16LE(f,U.CENNAM),b.writeUInt16LE(x,U.CENEXT),b.writeUInt16LE(g,U.CENCOM),b.writeUInt16LE(w,U.CENDSK),b.writeUInt16LE(S,U.CENATT),b.writeUInt32LE(y,U.CENATX),b.writeUInt32LE(v,U.CENOFF),b},toJSON:function(){let b=function(D){return D+" bytes"};return{made:t,version:e,flags:r,method:ln.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(l),size:b(u),fileNameLength:b(f),extraLength:b(x),commentLength:b(g),diskNumStart:w,inAttr:S,attr:y,offset:v,centralHeaderSize:b(U.CENHDR+f+x+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ou=ae((II,su)=>{var gr=pr(),ye=gr.Constants;su.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return ye.ENDHDR+o},loadFromBinary:function(c){if((c.length!==ye.ENDHDR||c.readUInt32LE(0)!==ye.ENDSIG)&&(c.length<ye.ZIP64HDR||c.readUInt32LE(0)!==ye.ZIP64SIG))throw gr.Errors.INVALID_END();c.readUInt32LE(0)===ye.ENDSIG?(t=c.readUInt16LE(ye.ENDSUB),e=c.readUInt16LE(ye.ENDTOT),r=c.readUInt32LE(ye.ENDSIZ),i=c.readUInt32LE(ye.ENDOFF),o=c.readUInt16LE(ye.ENDCOM)):(t=gr.readBigUInt64LE(c,ye.ZIP64SUB),e=gr.readBigUInt64LE(c,ye.ZIP64TOT),r=gr.readBigUInt64LE(c,ye.ZIP64SIZE),i=gr.readBigUInt64LE(c,ye.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(ye.ENDHDR+o);return c.writeUInt32LE(ye.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ye.ENDSUB),c.writeUInt16LE(e,ye.ENDTOT),c.writeUInt32LE(r,ye.ENDSIZ),c.writeUInt32LE(i,ye.ENDOFF),c.writeUInt16LE(o,ye.ENDCOM),c.fill(" ",ye.ENDHDR),c},toJSON:function(){let c=function(l,u){let f=l.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Wa=ae(qa=>{qa.EntryHeader=iu();qa.MainHeader=ou()});var cu=ae((kI,au)=>{au.exports=function(t){var e=ue("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=[],l=0;o.on("data",function(u){c.push(u),l+=u.length}),o.on("end",function(){var u=Buffer.alloc(l),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 lu=ae((TI,du)=>{var Om=+(process.versions?process.versions.node:"").split(".")[0]||0;du.exports=function(t,e){var r=ue("zlib");let i=Om>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),l=[],u=0;c.on("data",function(f){l.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var g=0;g<l.length;g++){var w=l[g];w.copy(f,x),x+=w.length}o&&o(f)}),c.end(t)}}}});var pu=ae((RI,xu)=>{"use strict";var{randomFillSync:uu}=ue("crypto"),Lm=Is(),Nm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),hu=(t,e)=>Math.imul(t,e)>>>0,fu=(t,e)=>Nm[(t^e)&255]^t>>>8,di=()=>typeof uu=="function"?uu(Buffer.alloc(12)):di.node();di.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var As={genSalt:di};function ks(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])}ks.prototype.updateKeys=function(t){let e=this.keys;return e[0]=fu(e[0],t),e[1]+=e[0]&255,e[1]=hu(e[1],134775813)+1,e[2]=fu(e[2],e[1]>>>24),t};ks.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return hu(t,t^1)>>8&255};function Mm(t){let e=new ks(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 Bm(t){let e=new ks(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let l=e.next();i[o++]=c^l,e.updateKeys(c)}return i}}function Fm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Mm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Lm.WRONG_PASSWORD();return i(t.slice(12))}function zm(t){Buffer.isBuffer(t)&&t.length>=12?As.genSalt=function(){return t.slice(0,12)}:t==="node"?As.genSalt=di.node:As.genSalt=di}function Um(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Bm(r),c=As.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return o(c,l),o(t,l,12)}xu.exports={decrypt:Fm,encrypt:Um,_salter:zm}});var gu=ae(Ts=>{Ts.Deflater=cu();Ts.Inflater=lu();Ts.ZipCrypto=pu()});var $a=ae((DI,mu)=>{var ce=pr(),Gm=Wa(),Ie=ce.Constants,Ka=gu();mu.exports=function(t,e){var r=new Gm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),f=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):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function y(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let D={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==Ie.LOCSIG||e.readUInt32LE(O)==Ie.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ie.EXTSIG)D.crc=e.readUInt32LE(O+Ie.EXTCRC),D.compressedSize=e.readUInt32LE(O+Ie.EXTSIZ),D.size=e.readUInt32LE(O+Ie.EXTLEN);else if(e.readUInt16LE(O+12)===19280)D.crc=e.readUInt32LE(O+Ie.EXTCRC-4),D.compressedSize=e.readUInt32LE(O+Ie.EXTSIZ-4),D.size=e.readUInt32LE(O+Ie.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==r.compressedSize||D.size!==r.size||D.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==D.crc)return!1}return!0}function v(b,D,O){if(typeof D>"u"&&typeof b=="string"&&(O=b,b=void 0),c)return b&&D&&D(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=S();if(F.length===0)return b&&D&&D(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();F=Ka.ZipCrypto.decrypt(F,r,O)}var B=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(F.copy(B),y(B))return b&&D&&D(B),B;throw b&&D&&D(B,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var V=new Ka.Inflater(F,r.size);if(b)V.inflateAsync(function($){$.copy($,0),D&&(y($)?D($):D($,ce.Errors.BAD_CRC()))});else{if(V.inflate(B).copy(B,0),!y(B))throw ce.Errors.BAD_CRC(`"${w.decode(i)}"`);return B}break;default:throw b&&D&&D(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(b,D){if((!l||!l.length)&&Buffer.isBuffer(e))return b&&D&&D(S()),S();if(l.length&&!c){var O;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(l.length),l.copy(O),b&&D&&D(O),O;default:case ce.Constants.DEFLATED:var F=new Ka.Deflater(l);if(b)F.deflateAsync(function(V){O=Buffer.alloc(V.length),r.compressedSize=V.length,V.copy(O),D&&D(O)});else{var B=F.deflate();return r.compressedSize=B.length,B}F=null;break}}else if(b&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,D){return ce.readBigUInt64LE(b,D)}function R(b){try{for(var D=0,O,F,B;D+4<b.length;)O=b.readUInt16LE(D),D+=2,F=b.readUInt16LE(D),D+=2,B=b.slice(D,D+F),D+=F,Ie.ID_ZIP64===O&&C(B)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function C(b){var D,O,F,B;b.length>=Ie.EF_ZIP64_SCOMP&&(D=A(b,Ie.EF_ZIP64_SUNCOMP),r.size===Ie.EF_ZIP64_OR_32&&(r.size=D)),b.length>=Ie.EF_ZIP64_RHO&&(O=A(b,Ie.EF_ZIP64_SCOMP),r.compressedSize===Ie.EF_ZIP64_OR_32&&(r.compressedSize=O)),b.length>=Ie.EF_ZIP64_DSN&&(F=A(b,Ie.EF_ZIP64_RHO),r.offset===Ie.EF_ZIP64_OR_32&&(r.offset=F)),b.length>=Ie.EF_ZIP64_DSN+4&&(B=b.readUInt32LE(Ie.EF_ZIP64_DSN),r.diskNumStart===Ie.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,w.encode);var D=i[i.length-1];c=D===47||D===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,R(b)},get comment(){return w.decode(o)},set comment(b){if(o=ce.toBuffer(b,w.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var b=w.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){l=ce.toBuffer(b,ce.decoder.encode),!c&&l.length?(r.size=l.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?l:v(!1,null,b)},getDataAsync:function(b,D){r.changed?b(l):v(!0,b,D)},set attr(b){r.attr=b},get attr(){return r.attr},set header(b){r.loadFromBinary(b)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var b=r.centralHeaderToBinary(),D=ce.Constants.CENHDR;return i.copy(b,D),D+=i.length,u.copy(b,D),D+=r.extraLength,o.copy(b,D),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let D=r.localHeaderToBinary(),O=Buffer.alloc(D.length+i.length+r.extraLocalLength);return D.copy(O,b),b+=D.length,i.copy(O,b),b+=i.length,f.copy(O,b),b+=f.length,O},toJSON:function(){let b=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:b(e),data:b(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var yu=ae((CI,_u)=>{var wu=$a(),Hm=Wa(),Ke=pr();_u.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Hm.MainHeader,l=!1,u=null;let f=new Set,x=e,{noSort:g,decoder:w}=x;t?v(x.readEntries):l=!0;function S(){let A=new Set;for(let R of Object.keys(i)){let C=R.split("/");if(C.pop(),!!C.length)for(let b=0;b<C.length;b++){let D=C.slice(0,b+1).join("/")+"/";A.add(D)}}for(let R of A)if(!(R in i)){let C=new wu(x);C.entryName=R,C.attr=16,C.temporary=!0,r.push(C),i[C.entryName]=C,f.add(C)}}function y(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/Ke.Constants.CENHDR)throw Ke.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,R=0;R<r.length;R++){var C=A,b=new wu(x,t);b.header=t.slice(C,C+=Ke.Constants.CENHDR),b.entryName=t.slice(C,C+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(C,C+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(C,C+b.header.commentLength)),A+=b.header.centralHeaderSize,r[R]=b,i[b.entryName]=b}f.clear(),S()}function v(A){var R=t.length-Ke.Constants.ENDHDR,C=Math.max(0,R-65535),b=C,D=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(C=0),R;R>=b;R--)if(t[R]===80){if(t.readUInt32LE(R)===Ke.Constants.ENDSIG){O=R,F=R,D=R+Ke.Constants.ENDHDR,b=R-Ke.Constants.END64HDR;continue}if(t.readUInt32LE(R)===Ke.Constants.END64SIG){b=C;continue}if(t.readUInt32LE(R)===Ke.Constants.ZIP64SIG){O=R,D=R+Ke.readBigUInt64LE(t,R+Ke.Constants.ZIP64SIZE)+Ke.Constants.ZIP64LEAD;break}}if(O==-1)throw Ke.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,D)),c.commentLength&&(o=t.slice(F+Ke.Constants.ENDHDR)),A&&y()}function I(){r.length>1&&!g&&r.sort((A,R)=>A.entryName.toLowerCase().localeCompare(R.entryName.toLowerCase()))}return{get entries(){return l||y(),r.filter(A=>!f.has(A))},get comment(){return w.decode(o)},set comment(A){o=Ke.toBuffer(A,w.encode),c.commentLength=o.length},getEntryCount:function(){return l?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||y(),i[A]||null},setEntry:function(A){l||y(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,R=!0){l||y();let C=i[A];this.getEntryChildren(C,R).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||y();let R=i[A],C=r.indexOf(R);C>=0&&(r.splice(C,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,R=!0){if(l||y(),typeof A=="object")if(A.isDirectory&&R){let C=[],b=A.entryName;for(let D of r)D.entryName.startsWith(b)&&C.push(D);return C}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let R=this.getEntryChildren(A);return R.includes(A)?R.length-1:R.length}return 0},compressToBuffer:function(){l||y(),I();let A=[],R=[],C=0,b=0;c.size=0,c.offset=0;let D=0;for(let B of this.entries){let V=B.getCompressedData();B.header.offset=b;let $=B.packLocalHeader(),re=$.length+V.length;b+=re,A.push($),A.push(V);let Y=B.packCentralHeader();R.push(Y),c.size+=Y.length,C+=re+Y.length,D++}C+=c.mainHeaderSize,c.offset=b,c.totalEntries=D,b=0;let O=Buffer.alloc(C);for(let B of A)B.copy(O,b),b+=B.length;for(let B of R)B.copy(O,b),b+=B.length;let F=c.toBinary();return o&&o.copy(F,Ke.Constants.ENDHDR),F.copy(O,b),t=O,l=!1,O},toAsyncBuffer:function(A,R,C,b){try{l||y(),I();let D=[],O=[],F=0,B=0,V=0;c.size=0,c.offset=0;let $=function(re){if(re.length>0){let Y=re.shift(),se=Y.entryName+Y.extra.toString();C&&C(se),Y.getCompressedDataAsync(function(oe){b&&b(se),Y.header.offset=B;let P=Y.packLocalHeader(),z=P.length+oe.length;B+=z,D.push(P),D.push(oe);let H=Y.packCentralHeader();O.push(H),c.size+=H.length,F+=z+H.length,V++,$(re)})}else{F+=c.mainHeaderSize,c.offset=B,c.totalEntries=V,B=0;let Y=Buffer.alloc(F);D.forEach(function(oe){oe.copy(Y,B),B+=oe.length}),O.forEach(function(oe){oe.copy(Y,B),B+=oe.length});let se=c.toBinary();o&&o.copy(se,Ke.Constants.ENDHDR),se.copy(Y,B),t=Y,l=!1,A(Y)}};$(Array.from(this.entries))}catch(D){R(D)}}}}});var vu=ae((OI,Eu)=>{var Ee=pr(),be=ue("path"),jm=$a(),qm=yu(),On=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),bu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Wm=(...t)=>Ee.findLast(t,e=>typeof e=="function"),Km={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};Eu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Km);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=Ee.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Ee(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ee.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Ee.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw Ee.Errors.INVALID_FILENAME();let c=new qm(r,i),{canonical:l,sanitize:u,zipnamefix:f}=Ee;function x(y){if(y&&c){var v;if(typeof y=="string"&&(v=c.getEntry(be.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(v=c.getEntry(y.entryName)),v)return v}return null}function g(y){let{join:v,normalize:I,sep:A}=be.posix;return v(be.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function w(y){return y instanceof RegExp?(function(v){return function(I){return v.test(I)}})(y):typeof y!="function"?()=>!0:y}let S=(y,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",be.relative(y,v)+I};return{readFile:function(y,v){var I=x(y);return I&&I.getData(v)||null},childCount:function(y){let v=x(y);if(v)return c.getChildCount(v)},readFileAsync:function(y,v){var I=x(y);I?I.getDataAsync(v):v(null,"getEntry failed for:"+y)},readAsText:function(y,v){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(y,v,I){var A=x(y);A?A.getDataAsync(function(R,C){if(C){v(R,C);return}R&&R.length?v(R.toString(I||"utf8")):v("")}):v("")},deleteFile:function(y,v=!0){var I=x(y);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(y){var v=x(y);v&&c.deleteEntry(v.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,v){var I=x(y);I&&(I.comment=v)},getZipEntryComment:function(y){var v=x(y);return v&&v.comment||""},updateFile:function(y,v){var I=x(y);I&&I.setData(v)},addLocalFile:function(y,v,I,A){if(o.fs.existsSync(y)){v=v?g(v):"";let R=be.win32.basename(be.win32.normalize(y));v+=I||R;let C=o.fs.statSync(y),b=C.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);C.isDirectory()&&(v+=o.sep),this.addFile(v,b,A,C)}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,v){y=typeof y=="object"?y:{localPath:y};let I=be.resolve(y.localPath),{comment:A}=y,{zipPath:R,zipName:C}=y,b=this;o.fs.stat(I,function(D,O){if(D)return v(D,!1);R=R?g(R):"";let F=be.win32.basename(be.win32.normalize(I));if(R+=C||F,O.isFile())o.fs.readFile(I,function(B,V){return B?v(B,!1):(b.addFile(R,V,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return R+=o.sep,b.addFile(R,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(y,v,I){if(I=w(I),v=v?g(v):"",y=be.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),R=this;if(A.length)for(let C of A){let b=be.join(v,S(y,C));I(b)&&R.addLocalFile(C,be.dirname(b))}}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,v,I,A){A=w(A),I=I?g(I):"",y=be.normalize(y);var R=this;o.fs.open(y,"r",function(C){if(C&&C.code==="ENOENT")v(void 0,Ee.Errors.FILE_NOT_FOUND(y));else if(C)v(void 0,C);else{var b=o.findFiles(y),D=-1,O=function(){if(D+=1,D<b.length){var F=b[D],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(V,$){V&&v(void 0,V),$.isFile()?o.fs.readFile(F,function(re,Y){re?v(void 0,re):(R.addFile(I+B,Y,"",$),O())}):(R.addFile(I+B+"/",Buffer.alloc(0),"",$),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(y,v){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=be.resolve(g(y.localPath));let{zipPath:A,filter:R,namefix:C}=y;R instanceof RegExp?R=(function(O){return function(F){return O.test(F)}})(R):typeof R!="function"&&(R=function(){return!0}),A=A?g(A):"",C=="latin1"&&(C=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof C!="function"&&(C=O=>O);let b=O=>be.join(A,C(S(localPath,O))),D=O=>be.win32.basename(be.win32.normalize(C(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(F,B){if(F)return v(F);B=B.filter(V=>R(b(V))),B.length||v(void 0,!1),setImmediate(B.reverse().reduce(function(V,$){return function(re,Y){if(re||Y===!1)return setImmediate(V,re,!1);I.addLocalFileAsync({localPath:$,zipPath:be.dirname(b($)),zipName:D($)},V)}},v))})})},addLocalFolderPromise:function(y,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},v),(R,C)=>{R&&A(R),C&&I(this)})})},addFile:function(y,v,I,A){y=f(y);let R=x(y),C=R!=null;C||(R=new jm(i),R.entryName=y),R.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(R.header.time=A.mtime);var D=R.isDirectory?16:0;let O=R.isDirectory?16384:32768;return b?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=R.isDirectory?493:420,D=(D|O<<16)>>>0,R.attr=D,R.setData(v),C||c.setEntry(R),R},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,v,I,A,R,C){A=On(!1,A),R=On(!1,R),I=On(!0,I),C=bu(R,C);var b=x(y);if(!b)throw Ee.Errors.NO_ENTRY();var D=l(b.entryName),O=u(v,C&&!b.isDirectory?C:I?D:be.basename(D));if(b.isDirectory){var F=c.getEntryChildren(b);return F.forEach(function($){if($.isDirectory)return;var re=$.getData();if(!re)throw Ee.Errors.CANT_EXTRACT_FILE();var Y=l($.entryName),se=u(v,I?Y:be.basename(Y));let oe=R?$.header.fileAttr:void 0;o.writeFileTo(se,re,A,oe)}),!0}var B=b.getData(c.password);if(!B)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw Ee.Errors.CANT_OVERRIDE();let V=R?y.header.fileAttr:void 0;return o.writeFileTo(O,B,A,V),!0},test:function(y){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,v,I,A){if(I=On(!1,I),A=bu(I,A),v=On(!1,v),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(R){var C=u(y,l(R.entryName));if(R.isDirectory){o.makeDir(C);return}var b=R.getData(A);if(!b)throw Ee.Errors.CANT_EXTRACT_FILE();let D=I?R.header.fileAttr:void 0;o.writeFileTo(C,b,v,D);try{o.fs.utimesSync(C,R.header.time,R.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,v,I,A){if(A=Wm(v,I,A),I=On(!1,I),v=On(!1,v),!A)return new Promise((O,F)=>{this.extractAllToAsync(y,v,I,function(B){B?F(B):O(this)})});if(!c){A(Ee.Errors.NO_ZIP());return}y=be.resolve(y);let R=O=>u(y,be.normalize(l(O.entryName))),C=(O,F)=>new Error(O+': "'+F+'"'),b=[],D=[];c.entries.forEach(O=>{O.isDirectory?b.push(O):D.push(O)});for(let O of b){let F=R(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(C("Unable to create folder",F))}}D.reverse().reduce(function(O,F){return function(B){if(B)O(B);else{let V=be.normalize(l(F.entryName)),$=u(y,V);F.getDataAsync(function(re,Y){if(Y)O(Y);else if(!re)O(Ee.Errors.CANT_EXTRACT_FILE());else{let se=I?F.header.fileAttr:void 0;o.writeFileToAsync($,re,v,se,function(oe){oe||O(C("Unable to write file",$)),o.fs.utimes($,F.header.time,F.header.time,function(P){P?O(C("Unable to set times",$)):O()})})}})}}},A)()},writeZip:function(y,v){if(arguments.length===1&&typeof y=="function"&&(v=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((R,C)=>{!y&&i.filename&&(y=i.filename),y||C("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let D=O=>O?R(O):C("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(y,b,I,A,D)},C)})},toBufferPromise:function(){return new Promise((y,v)=>{c.toAsyncBuffer(y,v)})},toBuffer:function(y,v,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,v,I,A),null):c.compressToBuffer()}}}});import{execFile as X_,spawn as Q_,spawnSync as YA}from"node:child_process";import{promisify as ey}from"node:util";function ny(t){if(process.platform!=="win32")return!1;if(jf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(jf,"").toLowerCase();return ty.has(r)}function qf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return ny(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function nt(t,e=[],r={}){return Q_(t,e,qf(t,r))}function Wf(t,e=[],r={}){return ry(t,e,qf(t,r))}var ty,jf,ry,Yt=Qe(()=>{"use strict";ty=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),jf=/\.(cmd|bat|ps1)$/i;ry=ey(X_)});var Qt=ae((eP,Nh)=>{"use strict";var Oh=["nodebuffer","arraybuffer","fragments"],Lh=typeof Blob<"u";Lh&&Oh.push("blob");Nh.exports={BINARY_TYPES:Oh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Lh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qi=ae((tP,zo)=>{"use strict";var{EMPTY_BUFFER:UE}=Qt(),Ed=Buffer[Symbol.species];function GE(t,e){if(t.length===0)return UE;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 Ed(r.buffer,r.byteOffset,i):r}function Mh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Bh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function HE(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function vd(t){if(vd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Ed(t):ArrayBuffer.isView(t)?e=new Ed(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),vd.readOnly=!1),e}zo.exports={concat:GE,mask:Mh,toArrayBuffer:HE,toBuffer:vd,unmask:Bh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");zo.exports.mask=function(e,r,i,o,c){c<48?Mh(e,r,i,o,c):t.mask(e,r,i,o,c)},zo.exports.unmask=function(e,r){e.length<32?Bh(e,r):t.unmask(e,r)}}catch{}});var Uh=ae((nP,zh)=>{"use strict";var Fh=Symbol("kDone"),Sd=Symbol("kRun"),Id=class{constructor(e){this[Fh]=()=>{this.pending--,this[Sd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Sd]()}[Sd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fh])}}};zh.exports=Id});var jr=ae((rP,qh)=>{"use strict";var es=ue("zlib"),Gh=Qi(),jE=Uh(),{kStatusCode:Hh}=Qt(),qE=Buffer[Symbol.species],WE=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),en=Symbol("total-length"),Gr=Symbol("callback"),Tn=Symbol("buffers"),Hr=Symbol("error"),Uo,Ad=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Uo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Uo=new jE(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Gr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){Uo.add(o=>{this._decompress(e,r,(c,l)=>{o(),i(c,l)})})}compress(e,r,i){Uo.add(o=>{this._compress(e,r,(c,l)=>{o(),i(c,l)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=es.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[Go]=this,this._inflate[en]=0,this._inflate[Tn]=[],this._inflate.on("error",$E),this._inflate.on("data",jh)}this._inflate[Gr]=i,this._inflate.write(e),r&&this._inflate.write(WE),this._inflate.flush(()=>{let c=this._inflate[Hr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=Gh.concat(this._inflate[Tn],this._inflate[en]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[en]=0,this._inflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=es.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[en]=0,this._deflate[Tn]=[],this._deflate.on("data",KE)}this._deflate[Gr]=i,this._deflate.write(e),this._deflate.flush(es.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Gh.concat(this._deflate[Tn],this._deflate[en]);r&&(c=new qE(c.buffer,c.byteOffset,c.length-4)),this._deflate[Gr]=null,this._deflate[en]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};qh.exports=Ad;function KE(t){this[Tn].push(t),this[en]+=t.length}function jh(t){if(this[en]+=t.length,this[Go]._maxPayload<1||this[en]<=this[Go]._maxPayload){this[Tn].push(t);return}this[Hr]=new RangeError("Max payload size exceeded"),this[Hr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hr][Hh]=1009,this.removeListener("data",jh),this.reset()}function $E(t){if(this[Go]._inflate=null,this[Hr]){this[Gr](this[Hr]);return}t[Hh]=1007,this[Gr](t)}});var qr=ae((iP,Ho)=>{"use strict";var{isUtf8:Wh}=ue("buffer"),{hasBlob:VE}=Qt(),JE=[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 ZE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function kd(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 YE(t){return VE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ho.exports={isBlob:YE,isValidStatusCode:ZE,isValidUTF8:kd,tokenChars:JE};if(Wh)Ho.exports.isValidUTF8=function(t){return t.length<24?kd(t):Wh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");Ho.exports.isValidUTF8=function(e){return e.length<32?kd(e):t(e)}}catch{}});var Cd=ae((sP,Xh)=>{"use strict";var{Writable:XE}=ue("stream"),Kh=jr(),{BINARY_TYPES:QE,EMPTY_BUFFER:$h,kStatusCode:ev,kWebSocket:tv}=Qt(),{concat:Td,toArrayBuffer:nv,unmask:rv}=Qi(),{isValidStatusCode:iv,isValidUTF8:Vh}=qr(),jo=Buffer[Symbol.species],xt=0,Jh=1,Zh=2,Yh=3,Rd=4,Pd=5,qo=6,Dd=class extends XE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||QE[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[tv]=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 jo(i.buffer,i.byteOffset+e,i.length-e),new jo(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=r.length-e;e>=i.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new jo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case xt:this.getInfo(e);break;case Jh:this.getPayloadLength16(e);break;case Zh:this.getPayloadLength64(e);break;case Yh:this.getMask();break;case Rd:this.getData(e);break;case Pd:case qo: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[Kh.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=Jh:this._payloadLength===127?this._state=Zh: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=Yh:this._state=Rd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Rd}getData(e){let r=$h;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&&rv(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Pd,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[Kh.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 l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(l);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let l=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(l);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=Td(i,r):this._binaryType==="arraybuffer"?o=nv(Td(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=xt):(this._state=qo,setImmediate(()=>{this.emit("message",o,!0),this._state=xt,this.startLoop(e)}))}else{let o=Td(i,r);if(!this._skipUTF8Validation&&!Vh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Pd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=xt):(this._state=qo,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,$h),this.end();else{let i=e.readUInt16BE(0);if(!iv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Vh(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=qo,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 l=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(l,this.createError),l.code=c,l[ev]=o,l}};Xh.exports=Dd});var Nd=ae((aP,tx)=>{"use strict";var{Duplex:oP}=ue("stream"),{randomFillSync:sv}=ue("crypto"),{types:{isUint8Array:ov}}=ue("util"),Qh=jr(),{EMPTY_BUFFER:av,kWebSocket:cv,NOOP:dv}=Qt(),{isBlob:Wr,isValidStatusCode:lv}=qr(),{mask:ex,toBuffer:Yn}=Qi(),pt=Symbol("kByteLength"),uv=Buffer.alloc(4),Wo=8*1024,Xn,Kr=Wo,It=0,fv=1,hv=2,Od=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=dv,this[cv]=void 0}static frame(e,r){let i,o=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||uv,r.generateMask?r.generateMask(i):(Kr===Wo&&(Xn===void 0&&(Xn=Buffer.alloc(Wo)),sv(Xn,0,Wo),Kr=0),i[0]=Xn[Kr++],i[1]=Xn[Kr++],i[2]=Xn[Kr++],i[3]=Xn[Kr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||l)&&r[pt]!==void 0?u=r[pt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!l);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],l?[x,e]:o?(ex(e,i,x,c,u),[x]):(ex(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=av;else{if(typeof e!="number"||!lv(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(ov(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let l={[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,l,o]):this.sendFrame(t.frame(c,l),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Wr(e)?(o=e.size,c=!1):(e=Yn(e),o=e.length,c=Yn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Wr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==It?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Wr(e)?(o=e.size,c=!1):(e=Yn(e),o=e.length,c=Yn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Wr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==It?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let o=this._extensions[Qh.extensionName],c=r.binary?2:1,l=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Wr(e)?(u=e.size,f=!1):(e=Yn(e),u=e.length,f=Yn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=o._threshold),this._compress=l):(l=!1,c=0),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:l};Wr(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=hv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Ld,this,u,o);return}this._bufferedBytes-=i[pt];let l=Yn(c);r?this.dispatch(l,r,i,o):(this._state=It,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(xv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Qh.extensionName];this._bufferedBytes+=i[pt],this._state=fv,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Ld(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)}};tx.exports=Od;function Ld(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 xv(t,e,r){Ld(t,e,r),t.onerror(e)}});var lx=ae((cP,dx)=>{"use strict";var{kForOnEventAttribute:ts,kListener:Md}=Qt(),nx=Symbol("kCode"),rx=Symbol("kData"),ix=Symbol("kError"),sx=Symbol("kMessage"),ox=Symbol("kReason"),$r=Symbol("kTarget"),ax=Symbol("kType"),cx=Symbol("kWasClean"),tn=class{constructor(e){this[$r]=null,this[ax]=e}get target(){return this[$r]}get type(){return this[ax]}};Object.defineProperty(tn.prototype,"target",{enumerable:!0});Object.defineProperty(tn.prototype,"type",{enumerable:!0});var Qn=class extends tn{constructor(e,r={}){super(e),this[nx]=r.code===void 0?0:r.code,this[ox]=r.reason===void 0?"":r.reason,this[cx]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[nx]}get reason(){return this[ox]}get wasClean(){return this[cx]}};Object.defineProperty(Qn.prototype,"code",{enumerable:!0});Object.defineProperty(Qn.prototype,"reason",{enumerable:!0});Object.defineProperty(Qn.prototype,"wasClean",{enumerable:!0});var Vr=class extends tn{constructor(e,r={}){super(e),this[ix]=r.error===void 0?null:r.error,this[sx]=r.message===void 0?"":r.message}get error(){return this[ix]}get message(){return this[sx]}};Object.defineProperty(Vr.prototype,"error",{enumerable:!0});Object.defineProperty(Vr.prototype,"message",{enumerable:!0});var ns=class extends tn{constructor(e,r={}){super(e),this[rx]=r.data===void 0?null:r.data}get data(){return this[rx]}};Object.defineProperty(ns.prototype,"data",{enumerable:!0});var pv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[ts]&&o[Md]===e&&!o[ts])return;let i;if(t==="message")i=function(c,l){let u=new ns("message",{data:l?c:c.toString()});u[$r]=this,Ko(e,this,u)};else if(t==="close")i=function(c,l){let u=new Qn("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[$r]=this,Ko(e,this,u)};else if(t==="error")i=function(c){let l=new Vr("error",{error:c,message:c.message});l[$r]=this,Ko(e,this,l)};else if(t==="open")i=function(){let c=new tn("open");c[$r]=this,Ko(e,this,c)};else return;i[ts]=!!r[ts],i[Md]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Md]===e&&!r[ts]){this.removeListener(t,r);break}}};dx.exports={CloseEvent:Qn,ErrorEvent:Vr,Event:tn,EventTarget:pv,MessageEvent:ns};function Ko(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var $o=ae((dP,ux)=>{"use strict";var{tokenChars:rs}=qr();function Nt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function gv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,l,u,f=-1,x=-1,g=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),l===void 0)if(g===-1&&rs[x]===1)f===-1&&(f=w);else if(w!==0&&(x===32||x===9))g===-1&&f!==-1&&(g=w);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let y=t.slice(f,g);x===44?(Nt(e,y,r),r=Object.create(null)):l=y,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(g===-1&&rs[x]===1)f===-1&&(f=w);else if(x===32||x===9)g===-1&&f!==-1&&(g=w);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w),Nt(r,t.slice(f,g),!0),x===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),f=g=-1}else if(x===61&&f!==-1&&g===-1)u=t.slice(f,w),f=g=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(rs[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);f===-1?f=w:i||(i=!0),o=!1}else if(c)if(rs[x]===1)f===-1&&(f=w);else if(x===34&&f!==-1)c=!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)c=!0;else if(g===-1&&rs[x]===1)f===-1&&(f=w);else if(f!==-1&&(x===32||x===9))g===-1&&(g=w);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${w}`);g===-1&&(g=w);let y=t.slice(f,g);i&&(y=y.replace(/\\/g,""),i=!1),Nt(r,u,y),x===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),u=void 0,f=g=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=w);let S=t.slice(f,g);return l===void 0?Nt(e,S,r):(u===void 0?Nt(r,S,!0):i?Nt(r,u,S.replace(/\\/g,"")):Nt(r,u,S),Nt(e,l,r)),e}function mv(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(l=>l===!0?o:`${o}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ux.exports={format:mv,parse:gv}});var Yo=ae((fP,Sx)=>{"use strict";var wv=ue("events"),_v=ue("https"),yv=ue("http"),xx=ue("net"),bv=ue("tls"),{randomBytes:Ev,createHash:vv}=ue("crypto"),{Duplex:lP,Readable:uP}=ue("stream"),{URL:Bd}=ue("url"),Rn=jr(),Sv=Cd(),Iv=Nd(),{isBlob:Av}=qr(),{BINARY_TYPES:fx,CLOSE_TIMEOUT:kv,EMPTY_BUFFER:Vo,GUID:Tv,kForOnEventAttribute:Fd,kListener:Rv,kStatusCode:Pv,kWebSocket:je,NOOP:px}=Qt(),{EventTarget:{addEventListener:Dv,removeEventListener:Cv}}=lx(),{format:Ov,parse:Lv}=$o(),{toBuffer:Nv}=Qi(),gx=Symbol("kAborted"),zd=[8,13],nn=["CONNECTING","OPEN","CLOSING","CLOSED"],Mv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends wv{constructor(e,r,i){super(),this._binaryType=fx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Vo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),mx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){fx.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,i){let o=new Sv({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 Iv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[je]=this,c[je]=this,e[je]=this,o.on("conclude",zv),o.on("drain",Uv),o.on("error",Gv),o.on("message",Hv),o.on("ping",jv),o.on("pong",qv),c.onerror=Wv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",bx),e.on("data",Zo),e.on("end",Ex),e.on("error",vx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Rn.extensionName]&&this._extensions[Rn.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){ot(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),yx(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){Ud(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Vo,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ud(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Vo,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ud(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Rn.extensionName]||(o.compress=!1),this._sender.send(e||Vo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ot(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Fd])return e[Rv];return null},set(e){for(let r of this.listeners(t))if(r[Fd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Fd]:!0})}})});we.prototype.addEventListener=Dv;we.prototype.removeEventListener=Cv;Sx.exports=we;function mx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:kv,protocolVersion:zd[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,!zd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${zd.join(", ")})`);let c;if(e instanceof Bd)c=e;else try{c=new Bd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let l=c.protocol==="wss:",u=c.protocol==="ws+unix:",f;if(c.protocol!=="ws:"&&!l&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?f="The URL's pathname is empty":c.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;Jo(t,I);return}let x=l?443:80,g=Ev(16).toString("base64"),w=l?_v.request:yv.request,S=new Set,y;if(o.createConnection=o.createConnection||(l?Fv:Bv),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 Rn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Ov({[Rn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!Mv.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 v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,R]of Object.entries(I))i.headers[A.toLowerCase()]=R}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),v=t._req=w(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=w(o);o.timeout&&v.on("timeout",()=>{ot(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[gx]||(v=t._req=null,Jo(t,I))}),v.on("response",I=>{let A=I.headers.location,R=I.statusCode;if(A&&o.followRedirects&&R>=300&&R<400){if(++t._redirects>o.maxRedirects){ot(t,v,"Maximum redirects exceeded");return}v.abort();let C;try{C=new Bd(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);Jo(t,D);return}mx(t,C,r,i)}else t.emit("unexpected-response",v,I)||ot(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,R)=>{if(t.emit("upgrade",I),t.readyState!==we.CONNECTING)return;v=t._req=null;let C=I.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){ot(t,A,"Invalid Upgrade header");return}let b=vv("sha1").update(g+Tv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){ot(t,A,"Invalid Sec-WebSocket-Accept header");return}let D=I.headers["sec-websocket-protocol"],O;if(D!==void 0?S.size?S.has(D)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":S.size&&(O="Server sent no subprotocol"),O){ot(t,A,O);return}D&&(t._protocol=D);let F=I.headers["sec-websocket-extensions"];if(F!==void 0){if(!y){ot(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=Lv(F)}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(B);if(V.length!==1||V[0]!==Rn.extensionName){ot(t,A,"Server indicated an extension that was not requested");return}try{y.accept(B[Rn.extensionName])}catch{ot(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Rn.extensionName]=y}t.setSocket(A,R,{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 Jo(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Bv(t){return t.path=t.socketPath,xx.connect(t)}function Fv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=xx.isIP(t.host)?"":t.host),bv.connect(t)}function ot(t,e,r){t._readyState=we.CLOSING;let i=new Error(r);Error.captureStackTrace(i,ot),e.setHeader?(e[gx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Jo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ud(t,e,r){if(e){let i=Av(e)?e.size:Nv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${nn[t.readyState]})`);process.nextTick(r,i)}}function zv(t,e){let r=this[je];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[je]!==void 0&&(r._socket.removeListener("data",Zo),process.nextTick(_x,r._socket),t===1005?r.close():r.close(t,e))}function Uv(){let t=this[je];t.isPaused||t._socket.resume()}function Gv(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",Zo),process.nextTick(_x,e._socket),e.close(t[Pv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function hx(){this[je].emitClose()}function Hv(t,e){this[je].emit("message",t,e)}function jv(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,px),e.emit("ping",t)}function qv(t){this[je].emit("pong",t)}function _x(t){t.resume()}function Wv(t){let e=this[je];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,yx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bx(){let t=this[je];if(this.removeListener("close",bx),this.removeListener("data",Zo),this.removeListener("end",Ex),t._readyState=we.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",hx),t._receiver.on("finish",hx))}function Zo(t){this[je]._receiver.write(t)||this.pause()}function Ex(){let t=this[je];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function vx(){let t=this[je];this.removeListener("error",vx),this.on("error",px),t&&(t._readyState=we.CLOSING,this.destroy())}});var Tx=ae((xP,kx)=>{"use strict";var hP=Yo(),{Duplex:Kv}=ue("stream");function Ix(t){t.emit("close")}function $v(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ax(t){this.removeListener("error",Ax),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Vv(t,e){let r=!0,i=new Kv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,l){let u=!l&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Ix,i);return}let l=!1;t.once("error",function(f){l=!0,c(f)}),t.once("close",function(){l||c(o),process.nextTick(Ix,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,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,l)});return}t.send(o,l)},i.on("end",$v),i.on("error",Ax),i}kx.exports=Vv});var Gd=ae((pP,Rx)=>{"use strict";var{tokenChars:Jv}=qr();function Zv(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let l=t.charCodeAt(o);if(i===-1&&Jv[l]===1)r===-1&&(r=o);else if(o!==0&&(l===32||l===9))i===-1&&r!==-1&&(i=o);else if(l===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}Rx.exports={parse:Zv}});var Mx=ae((mP,Nx)=>{"use strict";var Yv=ue("events"),Xo=ue("http"),{Duplex:gP}=ue("stream"),{createHash:Xv}=ue("crypto"),Px=$o(),er=jr(),Qv=Gd(),eS=Yo(),{CLOSE_TIMEOUT:tS,GUID:nS,kWebSocket:rS}=Qt(),iS=/^[+/0-9A-Za-z]{22}==$/,Dx=0,Cx=1,Lx=2,Hd=class extends Yv{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:tS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:eS,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Xo.createServer((i,o)=>{let c=Xo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=sS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,l)=>{this.handleUpgrade(o,c,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Dx}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Lx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(is,this);return}if(e&&this.once("close",e),this._state!==Cx)if(this._state=Cx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(is,this):process.nextTick(is,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{is(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,o){r.on("error",Ox);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){tr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!iS.test(c)){tr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){tr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ss(r,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=Qv.parse(f)}catch{tr(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 er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Px.parse(g);y[er.extensionName]&&(S.accept(y[er.extensionName]),w[er.extensionName]=S)}catch{tr(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,v,I,A)=>{if(!y)return ss(r,v||401,I,A);this.completeUpgrade(w,c,x,e,r,i,o)});return}if(!this.options.verifyClient(S))return ss(r,401)}this.completeUpgrade(w,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[rS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Dx)return ss(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Xv("sha1").update(r+nS).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[er.extensionName]){let w=e[er.extensionName].params,S=Px.format({[er.extensionName]:[w]});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&&ms(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 Vg,mkdirSync as Jg}from"node:fs";import{join as Zg}from"node:path";function Cl(t){let e=t.retentionDays??Qg,r=t.clock??(()=>Nn(new Date));_s={bridgeSink:new oi(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new oi(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();ms(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ms(t.agentLogsDir(o),"agent",i,e)}function em(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Dl(t){Fa=t}function Ol(t){return fr[Fa]<=fr[t]}function Ll(t,e){let r=fr[t];return r===void 0?!0:r>=fr[e]}function ys(t){Pl={...t}}function Nl(t){let e=(u,x=2)=>String(u).padStart(x,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),d=e(o%60);return`${Nn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function xt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Nl(new Date),level:e,module:r,msg:i,...o})}
11
+ `;Jg(t,{recursive:!0}),Vg(Zg(t,ur("bridge",Nn(new Date))),c)}catch{}}function tm(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ws(t,e,r,i,o){if(fr[t]<fr[Fa])return;let c=`${JSON.stringify({ts:Nl(new Date),level:t,module:e,msg:r,...Pl,...i})}
12
+ `;if(_s){let d=tm(o,i),u=d?em(_s,d):_s.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Xg.write(c):Yg.write(c)}function q(t,e){return{debug:(r,i)=>ws("debug",t,r,i,e),info:(r,i)=>ws("info",t,r,i,e),warn:(r,i)=>ws("warn",t,r,i,e),error:(r,i)=>ws("error",t,r,i,e),child:r=>q(`${t}.${r}`,e),forAgent:r=>q(t,r)}}var fr,Fa,Yg,Xg,Pl,Qg,_s,te=rt(()=>{"use strict";lr();za();fr={debug:10,info:20,warn:30,error:40},Fa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Yg=process.stdout,Xg=process.stderr,Pl={},Qg=Ze("COZE_BRIDGE_LOG_RETENTION_DAYS",30),_s=null});var T,$e=rt(()=>{"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 Fl={};Ma(Fl,{ACP_WRAPPER_NPM_PACKAGES:()=>bs,_resetAcpInstallerForTests:()=>am,_setBinaryPathCacheForTests:()=>cm,buildAcpSpawn:()=>ci,ensureAcpInstalled:()=>xr,getAcpBinaryPath:()=>Es,pickWhichLine:()=>Ha,probeAcpVersion:()=>om,resolveAcpCommand:()=>zl});import{readFileSync as Ml}from"node:fs";import{createRequire as nm}from"node:module";import{dirname as rm,resolve as im}from"node:path";function Ha(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function sm(t){let e=Bl.resolve(`${t.npmPackage}/package.json`),r=rm(e),i=JSON.parse(Ml(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 im(r,o)}async function xr(t,e){let r=Ga[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ai.get(t);if(i)return i;try{let o=sm(r);return ai.set(t,o),Ua.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ua.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 om(t){let e=Ga[t];if(e)try{let r=Bl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Ml(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Ua.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function Es(t){return ai.get(t)}function zl(t,e){if(e)return e;let r=Es(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 ci(t,e,r){if(e)return{command:e,args:[...r]};let i=zl(t);return{command:process.execPath,args:[i,...r]}}function am(){ai.clear()}function cm(t,e){ai.set(t,e)}var Ua,Ga,bs,Bl,ai,fn=rt(()=>{"use strict";$e();te();Ua=q("agents.acp-installer"),Ga={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},bs=Object.values(Ga).filter(t=>t!==void 0).map(t=>t.npmPackage),Bl=nm(import.meta.url),ai=new Map});import{chmod as lm,mkdir as um,readFile as fm,rename as xm,rm as hm,writeFile as pm}from"node:fs/promises";import{dirname as gm}from"node:path";async function hr(t){try{let e=await fm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ht(t,e,r){await um(gm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await pm(i,e,{encoding:"utf8",mode:r?.mode}),await xm(i,t),r?.mode!==void 0&&await lm(t,r.mode)}catch(o){throw await hm(i,{force:!0}).catch(()=>{}),o}}async function pr(t,e,r){await ht(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var Wt=rt(()=>{"use strict"});import{promises as Hl,readdirSync as mm}from"node:fs";import{homedir as wm}from"node:os";import{sep as _m,join as Pe,resolve as ql}from"node:path";function Z(t){let e=t??wm(),r=Pe(e,".coze"),i=Pe(r,"bridge"),o=Pe(i,"lib"),c=Pe(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Pe(o,"index.js"),binDir:Pe(i,"bin"),pidFile:Pe(i,"bridge.pid"),portFile:Pe(i,"bridge.port"),tokenFile:Pe(i,"bridge.token"),patTokenFile:Pe(i,"pat-token"),agentEnvFile:Pe(i,"agent-env.json"),logFile:Pe(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Pe(c,"daemon-stdio.log"),installLock:Pe(i,"install.lock"),configFile:Pe(i,"config.json"),agentsRoot:Pe(r,"agents")}}function Fe(t,e=Z()){let r=Pe(e.agentsRoot,t);return{root:r,config:Pe(r,"config.json"),workspace:Pe(r,"workspace"),logs:Pe(r,"logs")}}function vs(t=Z()){try{return mm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function di(t,e){let r=await Hl.realpath(ql(t)).catch(()=>null);if(!r)return!1;let i=await Hl.realpath(ql(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+_m)}var Ce=rt(()=>{"use strict"});var Is={};Ma(Is,{AGENT_CONFIG_FILE_MODE:()=>Ss,enforceAgentConfigMode:()=>Em,loadAgentConfig:()=>Ie,persistAgentSessions:()=>li,persistAgentSkills:()=>ui,saveAgentConfig:()=>Ue});import{chmod as ym,stat as bm}from"node:fs/promises";function Ie(t,e){return hr(Fe(t,e).config)}function Ue(t,e){return pr(Fe(t.agentId,e).config,t,{mode:Ss})}async function Em(t,e){if(process.platform==="win32")return;let r=Fe(t,e).config;try{let i=await bm(r);if(!i.isFile())return;let o=i.mode&511;o!==Ss&&(await ym(r,Ss),jl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;jl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function li(t,e,r){let i=await Ie(t,r);i&&(i.sessions=Object.fromEntries(e),await Ue(i,r))}async function ui(t,e,r){let i=await Ie(t,r);i&&(i.skills=e,await Ue(i,r))}var jl,Ss,Kt=rt(()=>{"use strict";Wt();te();Ce();jl=q("agent-config"),Ss=384});var Wa=ce((w1,$l)=>{$l.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 ks=ce(Jl=>{var Vl={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 Tm(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(Vl))Jl[t]=Tm(Vl[t])});var eu=ce((y1,Ql)=>{var Rm=fe("fs"),Me=fe("path"),Zl=Wa(),Pm=ks(),Cm=typeof process=="object"&&process.platform==="win32",Yl=t=>typeof t=="object"&&t!==null,Xl=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 Ae(t){this.sep=Me.sep,this.fs=Rm,Yl(t)&&Yl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Ql.exports=Ae;Ae.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 Pm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ae.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Me.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ae.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,x){if(d&&x.isDirectory())return o(!1);var h=Me.dirname(t);c.fs.exists(h,function(g){g||c.makeDir(h),c.fs.open(t,"w",438,function(_,S){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(w,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ae.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 x=Me.join(i,u),h=e.fs.statSync(x);(!o||o.test(x))&&d.push(Me.normalize(x)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&c&&(d=d.concat(r(x,o,c)))}),d}return r(t,void 0,!0)};Ae.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Me.join(t,u),r.fs.stat(u,function(x,h){if(x)return e(x);h&&(i.push(Me.normalize(u)+(h.isDirectory()?r.sep:"")),h.isDirectory()?r.findFilesAsync(u,function(g,_){if(g)return e(g);i=i.concat(_),--d||e(null,i)}):--d||e(null,i))})})})};Ae.prototype.getAttributes=function(){};Ae.prototype.setAttributes=function(){};Ae.crc32update=function(t,e){return Xl[(t^e)&255]^t>>>8};Ae.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ae.crc32update(r,t[i++]);return~r>>>0};Ae.methodToString=function(t){switch(t){case Zl.STORED:return"STORED ("+t+")";case Zl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ae.canonical=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.join(".",e)};Ae.zipnamefix=function(t){if(!t)return"";let e=Me.posix.normalize("/"+t.split("\\").join("/"));return Me.posix.join(".",e)};Ae.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]};Ae.sanitize=function(t,e){t=Me.resolve(Me.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Me.normalize(Me.join(t,r.slice(i,o).join(Me.sep)));if(c.indexOf(t)===0)return c}return Me.normalize(Me.join(t,Me.basename(e)))};Ae.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ae.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ae.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)};Ae.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};Ae.isWin=Cm;Ae.crcTable=Xl});var nu=ce((b1,tu)=>{var Dm=fe("path");tu.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=Dm.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 iu=ce((E1,ru)=>{ru.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var wr=ce((v1,mr)=>{mr.exports=eu();mr.exports.Constants=Wa();mr.exports.Errors=ks();mr.exports.FileAttr=nu();mr.exports.decoder=iu()});var ou=ce((S1,su)=>{var xn=wr(),H=xn.Constants;su.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,x=0,h=0,g=0,_=0,S=0,w=0,v=0;t|=xn.isWin?2560:768,r|=H.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,R=b=>Math.max(0,b)&65535,D=b=>Math.max(0,b)&255;return o=xn.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&H.FLG_EFS)>0},set flags_efs(b){b?r|=H.FLG_EFS:r&=~H.FLG_EFS},get flags_desc(){return(r&H.FLG_DESC)>0},set flags_desc(b){b?r|=H.FLG_DESC:r&=~H.FLG_DESC},get method(){return i},set method(b){switch(b){case H.STORED:this.version=10;case H.DEFLATED:default:this.version=20}i=b},get time(){return xn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=xn.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=A(b)},get timeHighByte(){return D(o>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return d},set compressedSize(b){d=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return x},set fileNameLength(b){x=b},get extraLength(){return h},set extraLength(b){h=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return g},set commentLength(b){g=b},get diskNumStart(){return _},set diskNumStart(b){_=A(b)},get inAttr(){return S},set inAttr(b){S=A(b)},get attr(){return w},set attr(b){w=A(b)},get fileAttr(){return(w||0)>>16&4095},get offset(){return v},set offset(b){v=A(b)},get encrypted(){return(r&H.FLG_ENC)===H.FLG_ENC},get centralHeaderSize(){return H.CENHDR+x+h+g},get realDataOffset(){return v+H.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var C=b.slice(v,v+H.LOCHDR);if(C.readUInt32LE(0)!==H.LOCSIG)throw xn.Errors.INVALID_LOC();I.version=C.readUInt16LE(H.LOCVER),I.flags=C.readUInt16LE(H.LOCFLG),I.flags_desc=(I.flags&H.FLG_DESC)>0,I.method=C.readUInt16LE(H.LOCHOW),I.time=C.readUInt32LE(H.LOCTIM),I.crc=C.readUInt32LE(H.LOCCRC),I.compressedSize=C.readUInt32LE(H.LOCSIZ),I.size=C.readUInt32LE(H.LOCLEN),I.fnameLen=C.readUInt16LE(H.LOCNAM),I.extraLen=C.readUInt16LE(H.LOCEXT);let L=v+H.LOCHDR+I.fnameLen,z=L+I.extraLen;return b.slice(L,z)},loadFromBinary:function(b){if(b.length!==H.CENHDR||b.readUInt32LE(0)!==H.CENSIG)throw xn.Errors.INVALID_CEN();t=b.readUInt16LE(H.CENVEM),e=b.readUInt16LE(H.CENVER),r=b.readUInt16LE(H.CENFLG),i=b.readUInt16LE(H.CENHOW),o=b.readUInt32LE(H.CENTIM),c=b.readUInt32LE(H.CENCRC),d=b.readUInt32LE(H.CENSIZ),u=b.readUInt32LE(H.CENLEN),x=b.readUInt16LE(H.CENNAM),h=b.readUInt16LE(H.CENEXT),g=b.readUInt16LE(H.CENCOM),_=b.readUInt16LE(H.CENDSK),S=b.readUInt16LE(H.CENATT),w=b.readUInt32LE(H.CENATX),v=b.readUInt32LE(H.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(H.LOCHDR);return b.writeUInt32LE(H.LOCSIG,0),b.writeUInt16LE(e,H.LOCVER),b.writeUInt16LE(r,H.LOCFLG),b.writeUInt16LE(i,H.LOCHOW),b.writeUInt32LE(o,H.LOCTIM),b.writeUInt32LE(c,H.LOCCRC),b.writeUInt32LE(d,H.LOCSIZ),b.writeUInt32LE(u,H.LOCLEN),b.writeUInt16LE(x,H.LOCNAM),b.writeUInt16LE(I.extraLen,H.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(H.CENHDR+x+h+g);return b.writeUInt32LE(H.CENSIG,0),b.writeUInt16LE(t,H.CENVEM),b.writeUInt16LE(e,H.CENVER),b.writeUInt16LE(r,H.CENFLG),b.writeUInt16LE(i,H.CENHOW),b.writeUInt32LE(o,H.CENTIM),b.writeUInt32LE(c,H.CENCRC),b.writeUInt32LE(d,H.CENSIZ),b.writeUInt32LE(u,H.CENLEN),b.writeUInt16LE(x,H.CENNAM),b.writeUInt16LE(h,H.CENEXT),b.writeUInt16LE(g,H.CENCOM),b.writeUInt16LE(_,H.CENDSK),b.writeUInt16LE(S,H.CENATT),b.writeUInt32LE(w,H.CENATX),b.writeUInt32LE(v,H.CENOFF),b},toJSON:function(){let b=function(C){return C+" bytes"};return{made:t,version:e,flags:r,method:xn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(x),extraLength:b(h),commentLength:b(g),diskNumStart:_,inAttr:S,attr:w,offset:v,centralHeaderSize:b(H.CENHDR+x+h+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var cu=ce((I1,au)=>{var _r=wr(),be=_r.Constants;au.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 _r.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=_r.readBigUInt64LE(c,be.ZIP64SUB),e=_r.readBigUInt64LE(c,be.ZIP64TOT),r=_r.readBigUInt64LE(c,be.ZIP64SIZE),i=_r.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 x=d.toString(16).toUpperCase();for(;x.length<u;)x="0"+x;return"0x"+x};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var $a=ce(Ka=>{Ka.EntryHeader=ou();Ka.MainHeader=cu()});var lu=ce((k1,du)=>{du.exports=function(t){var e=fe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),x=0;u.fill(0);for(var h=0;h<c.length;h++){var g=c[h];g.copy(u,x),x+=g.length}i&&i(u)}),o.end(t)}}}});var fu=ce((T1,uu)=>{var Om=+(process.versions?process.versions.node:"").split(".")[0]||0;uu.exports=function(t,e){var r=fe("zlib");let i=Om>=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(x){d.push(x),u+=x.length}),c.on("end",function(){var x=Buffer.alloc(u),h=0;x.fill(0);for(var g=0;g<d.length;g++){var _=d[g];_.copy(x,h),h+=_.length}o&&o(x)}),c.end(t)}}}});var mu=ce((R1,gu)=>{"use strict";var{randomFillSync:xu}=fe("crypto"),Lm=ks(),Nm=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}),pu=(t,e)=>Math.imul(t,e)>>>0,hu=(t,e)=>Nm[(t^e)&255]^t>>>8,fi=()=>typeof xu=="function"?xu(Buffer.alloc(12)):fi.node();fi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var Ts={genSalt:fi};function Rs(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])}Rs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=hu(e[0],t),e[1]+=e[0]&255,e[1]=pu(e[1],134775813)+1,e[2]=hu(e[2],e[1]>>>24),t};Rs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return pu(t,t^1)>>8&255};function Mm(t){let e=new Rs(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 Bm(t){let e=new Rs(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 zm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Mm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Lm.WRONG_PASSWORD();return i(t.slice(12))}function Fm(t){Buffer.isBuffer(t)&&t.length>=12?Ts.genSalt=function(){return t.slice(0,12)}:t==="node"?Ts.genSalt=fi.node:Ts.genSalt=fi}function Um(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Bm(r),c=Ts.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)}gu.exports={decrypt:zm,encrypt:Um,_salter:Fm}});var wu=ce(Ps=>{Ps.Deflater=lu();Ps.Inflater=fu();Ps.ZipCrypto=mu()});var Ja=ce((C1,_u)=>{var de=wr(),Gm=$a(),ke=de.Constants,Va=wu();_u.exports=function(t,e){var r=new Gm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),x=Buffer.alloc(0),h=!0;let g=t,_=typeof g.decoder=="object"?g.decoder:de.decoder;h=_.hasOwnProperty("efs")?_.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(x=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function w(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(de.crc32(b)!==r.localHeader.crc)return!1}else{let C={},L=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(L)==ke.LOCSIG||e.readUInt32LE(L)==ke.CENSIG)throw de.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(L)==ke.EXTSIG)C.crc=e.readUInt32LE(L+ke.EXTCRC),C.compressedSize=e.readUInt32LE(L+ke.EXTSIZ),C.size=e.readUInt32LE(L+ke.EXTLEN);else if(e.readUInt16LE(L+12)===19280)C.crc=e.readUInt32LE(L+ke.EXTCRC-4),C.compressedSize=e.readUInt32LE(L+ke.EXTSIZ-4),C.size=e.readUInt32LE(L+ke.EXTLEN-4);else throw de.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==r.compressedSize||C.size!==r.size||C.crc!==r.crc)throw de.Errors.DESCRIPTOR_FAULTY();if(de.crc32(b)!==C.crc)return!1}return!0}function v(b,C,L){if(typeof C>"u"&&typeof b=="string"&&(L=b,b=void 0),c)return b&&C&&C(Buffer.alloc(0),de.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=S();if(z.length===0)return b&&C&&C(z),z;if(r.encrypted){if(typeof L!="string"&&!Buffer.isBuffer(L))throw de.Errors.INVALID_PASS_PARAM();z=Va.ZipCrypto.decrypt(z,r,L)}var M=Buffer.alloc(r.size);switch(r.method){case de.Constants.STORED:if(z.copy(M),w(M))return b&&C&&C(M),M;throw b&&C&&C(M,de.Errors.BAD_CRC()),de.Errors.BAD_CRC();case de.Constants.DEFLATED:var J=new Va.Inflater(z,r.size);if(b)J.inflateAsync(function(V){V.copy(V,0),C&&(w(V)?C(V):C(V,de.Errors.BAD_CRC()))});else{if(J.inflate(M).copy(M,0),!w(M))throw de.Errors.BAD_CRC(`"${_.decode(i)}"`);return M}break;default:throw b&&C&&C(Buffer.alloc(0),de.Errors.UNKNOWN_METHOD()),de.Errors.UNKNOWN_METHOD()}}function I(b,C){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&C&&C(S()),S();if(d.length&&!c){var L;switch(r.method){case de.Constants.STORED:return r.compressedSize=r.size,L=Buffer.alloc(d.length),d.copy(L),b&&C&&C(L),L;default:case de.Constants.DEFLATED:var z=new Va.Deflater(d);if(b)z.deflateAsync(function(J){L=Buffer.alloc(J.length),r.compressedSize=J.length,J.copy(L),C&&C(L)});else{var M=z.deflate();return r.compressedSize=M.length,M}z=null;break}}else if(b&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,C){return de.readBigUInt64LE(b,C)}function R(b){try{for(var C=0,L,z,M;C+4<b.length;)L=b.readUInt16LE(C),C+=2,z=b.readUInt16LE(C),C+=2,M=b.slice(C,C+z),C+=z,ke.ID_ZIP64===L&&D(M)}catch{throw de.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(b){var C,L,z,M;b.length>=ke.EF_ZIP64_SCOMP&&(C=A(b,ke.EF_ZIP64_SUNCOMP),r.size===ke.EF_ZIP64_OR_32&&(r.size=C)),b.length>=ke.EF_ZIP64_RHO&&(L=A(b,ke.EF_ZIP64_SCOMP),r.compressedSize===ke.EF_ZIP64_OR_32&&(r.compressedSize=L)),b.length>=ke.EF_ZIP64_DSN&&(z=A(b,ke.EF_ZIP64_RHO),r.offset===ke.EF_ZIP64_OR_32&&(r.offset=z)),b.length>=ke.EF_ZIP64_DSN+4&&(M=b.readUInt32LE(ke.EF_ZIP64_DSN),r.diskNumStart===ke.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(b){i=de.toBuffer(b,_.encode);var C=i[i.length-1];c=C===47||C===92,r.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,R(b)},get comment(){return _.decode(o)},set comment(b){if(o=de.toBuffer(b,_.encode),r.commentLength=o.length,o.length>65535)throw de.Errors.COMMENT_TOO_LONG()},get name(){var b=_.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){d=de.toBuffer(b,de.decoder.encode),!c&&d.length?(r.size=d.length,r.method=de.Constants.DEFLATED,r.crc=de.crc32(b),r.changed=!0):r.method=de.Constants.STORED},getData:function(b){return r.changed?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=de.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=x.length;let C=r.localHeaderToBinary(),L=Buffer.alloc(C.length+i.length+r.extraLocalLength);return C.copy(L,b),b+=C.length,i.copy(L,b),b+=i.length,x.copy(L,b),b+=x.length,L},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 Eu=ce((D1,bu)=>{var yu=Ja(),Hm=$a(),Ve=wr();bu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Hm.MainHeader,d=!1,u=null;let x=new Set,h=e,{noSort:g,decoder:_}=h;t?v(h.readEntries):d=!0;function S(){let A=new Set;for(let R of Object.keys(i)){let D=R.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 R of A)if(!(R in i)){let D=new yu(h);D.entryName=R,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,x.add(D)}}function w(){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,R=0;R<r.length;R++){var D=A,b=new yu(h,t);b.header=t.slice(D,D+=Ve.Constants.CENHDR),b.entryName=t.slice(D,D+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(D,D+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(D,D+b.header.commentLength)),A+=b.header.centralHeaderSize,r[R]=b,i[b.entryName]=b}x.clear(),S()}function v(A){var R=t.length-Ve.Constants.ENDHDR,D=Math.max(0,R-65535),b=D,C=t.length,L=-1,z=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(D=0),R;R>=b;R--)if(t[R]===80){if(t.readUInt32LE(R)===Ve.Constants.ENDSIG){L=R,z=R,C=R+Ve.Constants.ENDHDR,b=R-Ve.Constants.END64HDR;continue}if(t.readUInt32LE(R)===Ve.Constants.END64SIG){b=D;continue}if(t.readUInt32LE(R)===Ve.Constants.ZIP64SIG){L=R,C=R+Ve.readBigUInt64LE(t,R+Ve.Constants.ZIP64SIZE)+Ve.Constants.ZIP64LEAD;break}}if(L==-1)throw Ve.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(L,C)),c.commentLength&&(o=t.slice(z+Ve.Constants.ENDHDR)),A&&w()}function I(){r.length>1&&!g&&r.sort((A,R)=>A.entryName.toLowerCase().localeCompare(R.entryName.toLowerCase()))}return{get entries(){return d||w(),r.filter(A=>!x.has(A))},get comment(){return _.decode(o)},set comment(A){o=Ve.toBuffer(A,_.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||w(),i[A]||null},setEntry:function(A){d||w(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,R=!0){d||w();let D=i[A];this.getEntryChildren(D,R).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||w();let R=i[A],D=r.indexOf(R);D>=0&&(r.splice(D,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,R=!0){if(d||w(),typeof A=="object")if(A.isDirectory&&R){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 R=this.getEntryChildren(A);return R.includes(A)?R.length-1:R.length}return 0},compressToBuffer:function(){d||w(),I();let A=[],R=[],D=0,b=0;c.size=0,c.offset=0;let C=0;for(let M of this.entries){let J=M.getCompressedData();M.header.offset=b;let V=M.packLocalHeader(),re=V.length+J.length;b+=re,A.push(V),A.push(J);let X=M.packCentralHeader();R.push(X),c.size+=X.length,D+=re+X.length,C++}D+=c.mainHeaderSize,c.offset=b,c.totalEntries=C,b=0;let L=Buffer.alloc(D);for(let M of A)M.copy(L,b),b+=M.length;for(let M of R)M.copy(L,b),b+=M.length;let z=c.toBinary();return o&&o.copy(z,Ve.Constants.ENDHDR),z.copy(L,b),t=L,d=!1,L},toAsyncBuffer:function(A,R,D,b){try{d||w(),I();let C=[],L=[],z=0,M=0,J=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let X=re.shift(),oe=X.entryName+X.extra.toString();D&&D(oe),X.getCompressedDataAsync(function(ae){b&&b(oe),X.header.offset=M;let P=X.packLocalHeader(),G=P.length+ae.length;M+=G,C.push(P),C.push(ae);let j=X.packCentralHeader();L.push(j),c.size+=j.length,z+=G+j.length,J++,V(re)})}else{z+=c.mainHeaderSize,c.offset=M,c.totalEntries=J,M=0;let X=Buffer.alloc(z);C.forEach(function(ae){ae.copy(X,M),M+=ae.length}),L.forEach(function(ae){ae.copy(X,M),M+=ae.length});let oe=c.toBinary();o&&o.copy(oe,Ve.Constants.ENDHDR),oe.copy(X,M),t=X,d=!1,A(X)}};V(Array.from(this.entries))}catch(C){R(C)}}}}});var Iu=ce((O1,Su)=>{var ve=wr(),Ee=fe("path"),qm=Ja(),jm=Eu(),Mn=(...t)=>ve.findLast(t,e=>typeof e=="boolean"),vu=(...t)=>ve.findLast(t,e=>typeof e=="string"),Wm=(...t)=>ve.findLast(t,e=>typeof e=="function"),Km={noSort:!1,readEntries:!1,method:ve.Constants.NONE,fs:null};Su.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Km);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=ve.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ve(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ve.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ve.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw ve.Errors.INVALID_FILENAME();let c=new jm(r,i),{canonical:d,sanitize:u,zipnamefix:x}=ve;function h(w){if(w&&c){var v;if(typeof w=="string"&&(v=c.getEntry(Ee.posix.normalize(w))),typeof w=="object"&&typeof w.entryName<"u"&&typeof w.header<"u"&&(v=c.getEntry(w.entryName)),v)return v}return null}function g(w){let{join:v,normalize:I,sep:A}=Ee.posix;return v(Ee.isAbsolute(w)?"/":".",I(A+w.split("\\").join(A)+A))}function _(w){return w instanceof RegExp?(function(v){return function(I){return v.test(I)}})(w):typeof w!="function"?()=>!0:w}let S=(w,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",Ee.relative(w,v)+I};return{readFile:function(w,v){var I=h(w);return I&&I.getData(v)||null},childCount:function(w){let v=h(w);if(v)return c.getChildCount(v)},readFileAsync:function(w,v){var I=h(w);I?I.getDataAsync(v):v(null,"getEntry failed for:"+w)},readAsText:function(w,v){var I=h(w);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(w,v,I){var A=h(w);A?A.getDataAsync(function(R,D){if(D){v(R,D);return}R&&R.length?v(R.toString(I||"utf8")):v("")}):v("")},deleteFile:function(w,v=!0){var I=h(w);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(w){var v=h(w);v&&c.deleteEntry(v.entryName)},addZipComment:function(w){c.comment=w},getZipComment:function(){return c.comment||""},addZipEntryComment:function(w,v){var I=h(w);I&&(I.comment=v)},getZipEntryComment:function(w){var v=h(w);return v&&v.comment||""},updateFile:function(w,v){var I=h(w);I&&I.setData(v)},addLocalFile:function(w,v,I,A){if(o.fs.existsSync(w)){v=v?g(v):"";let R=Ee.win32.basename(Ee.win32.normalize(w));v+=I||R;let D=o.fs.statSync(w),b=D.isFile()?o.fs.readFileSync(w):Buffer.alloc(0);D.isDirectory()&&(v+=o.sep),this.addFile(v,b,A,D)}else throw ve.Errors.FILE_NOT_FOUND(w)},addLocalFileAsync:function(w,v){w=typeof w=="object"?w:{localPath:w};let I=Ee.resolve(w.localPath),{comment:A}=w,{zipPath:R,zipName:D}=w,b=this;o.fs.stat(I,function(C,L){if(C)return v(C,!1);R=R?g(R):"";let z=Ee.win32.basename(Ee.win32.normalize(I));if(R+=D||z,L.isFile())o.fs.readFile(I,function(M,J){return M?v(M,!1):(b.addFile(R,J,A,L),setImmediate(v,void 0,!0))});else if(L.isDirectory())return R+=o.sep,b.addFile(R,Buffer.alloc(0),A,L),setImmediate(v,void 0,!0)})},addLocalFolder:function(w,v,I){if(I=_(I),v=v?g(v):"",w=Ee.normalize(w),o.fs.existsSync(w)){let A=o.findFiles(w),R=this;if(A.length)for(let D of A){let b=Ee.join(v,S(w,D));I(b)&&R.addLocalFile(D,Ee.dirname(b))}}else throw ve.Errors.FILE_NOT_FOUND(w)},addLocalFolderAsync:function(w,v,I,A){A=_(A),I=I?g(I):"",w=Ee.normalize(w);var R=this;o.fs.open(w,"r",function(D){if(D&&D.code==="ENOENT")v(void 0,ve.Errors.FILE_NOT_FOUND(w));else if(D)v(void 0,D);else{var b=o.findFiles(w),C=-1,L=function(){if(C+=1,C<b.length){var z=b[C],M=S(w,z).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(z,function(J,V){J&&v(void 0,J),V.isFile()?o.fs.readFile(z,function(re,X){re?v(void 0,re):(R.addFile(I+M,X,"",V),L())}):(R.addFile(I+M+"/",Buffer.alloc(0),"",V),L())}):process.nextTick(()=>{L()})}else v(!0,void 0)};L()}})},addLocalFolderAsync2:function(w,v){let I=this;w=typeof w=="object"?w:{localPath:w},localPath=Ee.resolve(g(w.localPath));let{zipPath:A,filter:R,namefix:D}=w;R instanceof RegExp?R=(function(L){return function(z){return L.test(z)}})(R):typeof R!="function"&&(R=function(){return!0}),A=A?g(A):"",D=="latin1"&&(D=L=>L.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=L=>L);let b=L=>Ee.join(A,D(S(localPath,L))),C=L=>Ee.win32.basename(Ee.win32.normalize(D(L)));o.fs.open(localPath,"r",function(L){L&&L.code==="ENOENT"?v(void 0,ve.Errors.FILE_NOT_FOUND(localPath)):L?v(void 0,L):o.findFilesAsync(localPath,function(z,M){if(z)return v(z);M=M.filter(J=>R(b(J))),M.length||v(void 0,!1),setImmediate(M.reverse().reduce(function(J,V){return function(re,X){if(re||X===!1)return setImmediate(J,re,!1);I.addLocalFileAsync({localPath:V,zipPath:Ee.dirname(b(V)),zipName:C(V)},J)}},v))})})},addLocalFolderPromise:function(w,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:w},v),(R,D)=>{R&&A(R),D&&I(this)})})},addFile:function(w,v,I,A){w=x(w);let R=h(w),D=R!=null;D||(R=new qm(i),R.entryName=w),R.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(R.header.time=A.mtime);var C=R.isDirectory?16:0;let L=R.isDirectory?16384:32768;return b?L|=4095&A.mode:typeof A=="number"?L|=4095&A:L|=R.isDirectory?493:420,C=(C|L<<16)>>>0,R.attr=C,R.setData(v),D||c.setEntry(R),R},getEntries:function(w){return c.password=w,c?c.entries:[]},getEntry:function(w){return h(w)},getEntryCount:function(){return c.getEntryCount()},forEach:function(w){return c.forEach(w)},extractEntryTo:function(w,v,I,A,R,D){A=Mn(!1,A),R=Mn(!1,R),I=Mn(!0,I),D=vu(R,D);var b=h(w);if(!b)throw ve.Errors.NO_ENTRY();var C=d(b.entryName),L=u(v,D&&!b.isDirectory?D:I?C:Ee.basename(C));if(b.isDirectory){var z=c.getEntryChildren(b);return z.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw ve.Errors.CANT_EXTRACT_FILE();var X=d(V.entryName),oe=u(v,I?X:Ee.basename(X));let ae=R?V.header.fileAttr:void 0;o.writeFileTo(oe,re,A,ae)}),!0}var M=b.getData(c.password);if(!M)throw ve.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(L)&&!A)throw ve.Errors.CANT_OVERRIDE();let J=R?w.header.fileAttr:void 0;return o.writeFileTo(L,M,A,J),!0},test:function(w){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(w);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(w,v,I,A){if(I=Mn(!1,I),A=vu(I,A),v=Mn(!1,v),!c)throw ve.Errors.NO_ZIP();c.entries.forEach(function(R){var D=u(w,d(R.entryName));if(R.isDirectory){o.makeDir(D);return}var b=R.getData(A);if(!b)throw ve.Errors.CANT_EXTRACT_FILE();let C=I?R.header.fileAttr:void 0;o.writeFileTo(D,b,v,C);try{o.fs.utimesSync(D,R.header.time,R.header.time)}catch{throw ve.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(w,v,I,A){if(A=Wm(v,I,A),I=Mn(!1,I),v=Mn(!1,v),!A)return new Promise((L,z)=>{this.extractAllToAsync(w,v,I,function(M){M?z(M):L(this)})});if(!c){A(ve.Errors.NO_ZIP());return}w=Ee.resolve(w);let R=L=>u(w,Ee.normalize(d(L.entryName))),D=(L,z)=>new Error(L+': "'+z+'"'),b=[],C=[];c.entries.forEach(L=>{L.isDirectory?b.push(L):C.push(L)});for(let L of b){let z=R(L),M=I?L.header.fileAttr:void 0;try{o.makeDir(z),M&&o.fs.chmodSync(z,M),o.fs.utimesSync(z,L.header.time,L.header.time)}catch{A(D("Unable to create folder",z))}}C.reverse().reduce(function(L,z){return function(M){if(M)L(M);else{let J=Ee.normalize(d(z.entryName)),V=u(w,J);z.getDataAsync(function(re,X){if(X)L(X);else if(!re)L(ve.Errors.CANT_EXTRACT_FILE());else{let oe=I?z.header.fileAttr:void 0;o.writeFileToAsync(V,re,v,oe,function(ae){ae||L(D("Unable to write file",V)),o.fs.utimes(V,z.header.time,z.header.time,function(P){P?L(D("Unable to set times",V)):L()})})}})}}},A)()},writeZip:function(w,v){if(arguments.length===1&&typeof w=="function"&&(v=w,w=""),!w&&i.filename&&(w=i.filename),!!w){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(w,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(w,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((R,D)=>{!w&&i.filename&&(w=i.filename),w||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let C=L=>L?R(L):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(w,b,I,A,C)},D)})},toBufferPromise:function(){return new Promise((w,v)=>{c.toAsyncBuffer(w,v)})},toBuffer:function(w,v,I,A){return typeof w=="function"?(c.toAsyncBuffer(w,v,I,A),null):c.compressToBuffer()}}}});import{execFile as X_,spawn as Q_,spawnSync as YA}from"node:child_process";import{promisify as ey}from"node:util";function ny(t){if(process.platform!=="win32")return!1;if(Wf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Wf,"").toLowerCase();return ty.has(r)}function Kf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return ny(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function st(t,e=[],r={}){return Q_(t,e,Kf(t,r))}function $f(t,e=[],r={}){return ry(t,e,Kf(t,r))}var ty,Wf,ry,Qt=rt(()=>{"use strict";ty=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Wf=/\.(cmd|bat|ps1)$/i;ry=ey(X_)});var tn=ce((eC,zx)=>{"use strict";var Mx=["nodebuffer","arraybuffer","fragments"],Bx=typeof Blob<"u";Bx&&Mx.push("blob");zx.exports={BINARY_TYPES:Mx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Bx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ns=ce((tC,Go)=>{"use strict";var{EMPTY_BUFFER:UE}=tn(),Sd=Buffer[Symbol.species];function GE(t,e){if(t.length===0)return UE;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 Sd(r.buffer,r.byteOffset,i):r}function Fx(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Ux(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function HE(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Id(t){if(Id.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Sd(t):ArrayBuffer.isView(t)?e=new Sd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Id.readOnly=!1),e}Go.exports={concat:GE,mask:Fx,toArrayBuffer:HE,toBuffer:Id,unmask:Ux};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=fe("bufferutil");Go.exports.mask=function(e,r,i,o,c){c<48?Fx(e,r,i,o,c):t.mask(e,r,i,o,c)},Go.exports.unmask=function(e,r){e.length<32?Ux(e,r):t.unmask(e,r)}}catch{}});var qx=ce((nC,Hx)=>{"use strict";var Gx=Symbol("kDone"),Ad=Symbol("kRun"),kd=class{constructor(e){this[Gx]=()=>{this.pending--,this[Ad]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ad]()}[Ad](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Gx])}}};Hx.exports=kd});var Kr=ce((rC,$x)=>{"use strict";var rs=fe("zlib"),jx=ns(),qE=qx(),{kStatusCode:Wx}=tn(),jE=Buffer[Symbol.species],WE=Buffer.from([0,0,255,255]),qo=Symbol("permessage-deflate"),nn=Symbol("total-length"),jr=Symbol("callback"),Cn=Symbol("buffers"),Wr=Symbol("error"),Ho,Td=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ho){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new qE(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[jr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){Ho.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Ho.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?rs.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=rs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[qo]=this,this._inflate[nn]=0,this._inflate[Cn]=[],this._inflate.on("error",$E),this._inflate.on("data",Kx)}this._inflate[jr]=i,this._inflate.write(e),r&&this._inflate.write(WE),this._inflate.flush(()=>{let c=this._inflate[Wr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=jx.concat(this._inflate[Cn],this._inflate[nn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[nn]=0,this._inflate[Cn]=[],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"?rs.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=rs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[nn]=0,this._deflate[Cn]=[],this._deflate.on("data",KE)}this._deflate[jr]=i,this._deflate.write(e),this._deflate.flush(rs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=jx.concat(this._deflate[Cn],this._deflate[nn]);r&&(c=new jE(c.buffer,c.byteOffset,c.length-4)),this._deflate[jr]=null,this._deflate[nn]=0,this._deflate[Cn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};$x.exports=Td;function KE(t){this[Cn].push(t),this[nn]+=t.length}function Kx(t){if(this[nn]+=t.length,this[qo]._maxPayload<1||this[nn]<=this[qo]._maxPayload){this[Cn].push(t);return}this[Wr]=new RangeError("Max payload size exceeded"),this[Wr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Wr][Wx]=1009,this.removeListener("data",Kx),this.reset()}function $E(t){if(this[qo]._inflate=null,this[Wr]){this[jr](this[Wr]);return}t[Wx]=1007,this[jr](t)}});var $r=ce((iC,jo)=>{"use strict";var{isUtf8:Vx}=fe("buffer"),{hasBlob:VE}=tn(),JE=[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 ZE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Rd(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 YE(t){return VE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}jo.exports={isBlob:YE,isValidStatusCode:ZE,isValidUTF8:Rd,tokenChars:JE};if(Vx)jo.exports.isValidUTF8=function(t){return t.length<24?Rd(t):Vx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=fe("utf-8-validate");jo.exports.isValidUTF8=function(e){return e.length<32?Rd(e):t(e)}}catch{}});var Ld=ce((sC,th)=>{"use strict";var{Writable:XE}=fe("stream"),Jx=Kr(),{BINARY_TYPES:QE,EMPTY_BUFFER:Zx,kStatusCode:ev,kWebSocket:tv}=tn(),{concat:Pd,toArrayBuffer:nv,unmask:rv}=ns(),{isValidStatusCode:iv,isValidUTF8:Yx}=$r(),Wo=Buffer[Symbol.species],_t=0,Xx=1,Qx=2,eh=3,Cd=4,Dd=5,Ko=6,Od=class extends XE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||QE[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[tv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=_t}_write(e,r,i){if(this._opcode===8&&this._state==_t)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Wo(i.buffer,i.byteOffset+e,i.length-e),new Wo(i.buffer,i.byteOffset,e)}let 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 Wo(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 _t:this.getInfo(e);break;case Xx:this.getPayloadLength16(e);break;case Qx:this.getPayloadLength64(e);break;case eh:this.getMask();break;case Cd:this.getData(e);break;case Dd:case Ko: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[Jx.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=Xx:this._payloadLength===127?this._state=Qx: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=eh:this._state=Cd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Cd}getData(e){let r=Zx;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&&rv(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Dd,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[Jx.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===_t&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=_t;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=Pd(i,r):this._binaryType==="arraybuffer"?o=nv(Pd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=_t):(this._state=Ko,setImmediate(()=>{this.emit("message",o,!0),this._state=_t,this.startLoop(e)}))}else{let o=Pd(i,r);if(!this._skipUTF8Validation&&!Yx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Dd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=_t):(this._state=Ko,setImmediate(()=>{this.emit("message",o,!1),this._state=_t,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Zx),this.end();else{let i=e.readUInt16BE(0);if(!iv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Wo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Yx(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=_t;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=_t):(this._state=Ko,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=_t,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[ev]=o,d}};th.exports=Od});var Bd=ce((aC,ih)=>{"use strict";var{Duplex:oC}=fe("stream"),{randomFillSync:sv}=fe("crypto"),{types:{isUint8Array:ov}}=fe("util"),nh=Kr(),{EMPTY_BUFFER:av,kWebSocket:cv,NOOP:dv}=tn(),{isBlob:Vr,isValidStatusCode:lv}=$r(),{mask:rh,toBuffer:er}=ns(),yt=Symbol("kByteLength"),uv=Buffer.alloc(4),$o=8*1024,tr,Jr=$o,Rt=0,fv=1,xv=2,Nd=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=Rt,this.onerror=dv,this[cv]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||uv,r.generateMask?r.generateMask(i):(Jr===$o&&(tr===void 0&&(tr=Buffer.alloc($o)),sv(tr,0,$o),Jr=0),i[0]=tr[Jr++],i[1]=tr[Jr++],i[2]=tr[Jr++],i[3]=tr[Jr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[yt]!==void 0?u=r[yt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let x=u;u>=65536?(c+=8,x=127):u>125&&(c+=2,x=126);let h=Buffer.allocUnsafe(o?u+c:c);return h[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(h[0]|=64),h[1]=x,x===126?h.writeUInt16BE(u,2):x===127&&(h[2]=h[3]=0,h.writeUIntBE(u,4,6)),r.mask?(h[1]|=128,h[c-4]=i[0],h[c-3]=i[1],h[c-2]=i[2],h[c-1]=i[3],d?[h,e]:o?(rh(e,i,h,c,u),[h]):(rh(e,i,e,0,u),[h,e])):[h,e]}close(e,r,i,o){let c;if(e===void 0)c=av;else{if(typeof e!="number"||!lv(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(ov(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[yt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Rt?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Vr(e)?(o=e.size,c=!1):(e=er(e),o=e.length,c=er.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[yt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Vr(e)?this._state!==Rt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Rt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Vr(e)?(o=e.size,c=!1):(e=er(e),o=e.length,c=er.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[yt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Vr(e)?this._state!==Rt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Rt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[nh.extensionName],c=r.binary?2:1,d=r.compress,u,x;typeof e=="string"?(u=Buffer.byteLength(e),x=!1):Vr(e)?(u=e.size,x=!1):(e=er(e),u=e.length,x=er.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),r.fin&&(this._firstFragment=!0);let h={[yt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:x,rsv1:d};Vr(e)?this._state!==Rt?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==Rt?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[yt],this._state=xv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Md,this,u,o);return}this._bufferedBytes-=i[yt];let d=er(c);r?this.dispatch(d,r,i,o):(this._state=Rt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(hv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[nh.extensionName];this._bufferedBytes+=i[yt],this._state=fv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let x=new Error("The socket was closed while data was being compressed");Md(this,x,o);return}this._bufferedBytes-=i[yt],this._state=Rt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Rt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][yt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][yt],this._queue.push(e)}sendFrame(e,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)}};ih.exports=Nd;function Md(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 hv(t,e,r){Md(t,e,r),t.onerror(e)}});var xh=ce((cC,fh)=>{"use strict";var{kForOnEventAttribute:is,kListener:zd}=tn(),sh=Symbol("kCode"),oh=Symbol("kData"),ah=Symbol("kError"),ch=Symbol("kMessage"),dh=Symbol("kReason"),Zr=Symbol("kTarget"),lh=Symbol("kType"),uh=Symbol("kWasClean"),rn=class{constructor(e){this[Zr]=null,this[lh]=e}get target(){return this[Zr]}get type(){return this[lh]}};Object.defineProperty(rn.prototype,"target",{enumerable:!0});Object.defineProperty(rn.prototype,"type",{enumerable:!0});var nr=class extends rn{constructor(e,r={}){super(e),this[sh]=r.code===void 0?0:r.code,this[dh]=r.reason===void 0?"":r.reason,this[uh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[sh]}get reason(){return this[dh]}get wasClean(){return this[uh]}};Object.defineProperty(nr.prototype,"code",{enumerable:!0});Object.defineProperty(nr.prototype,"reason",{enumerable:!0});Object.defineProperty(nr.prototype,"wasClean",{enumerable:!0});var Yr=class extends rn{constructor(e,r={}){super(e),this[ah]=r.error===void 0?null:r.error,this[ch]=r.message===void 0?"":r.message}get error(){return this[ah]}get message(){return this[ch]}};Object.defineProperty(Yr.prototype,"error",{enumerable:!0});Object.defineProperty(Yr.prototype,"message",{enumerable:!0});var ss=class extends rn{constructor(e,r={}){super(e),this[oh]=r.data===void 0?null:r.data}get data(){return this[oh]}};Object.defineProperty(ss.prototype,"data",{enumerable:!0});var pv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[is]&&o[zd]===e&&!o[is])return;let i;if(t==="message")i=function(c,d){let u=new ss("message",{data:d?c:c.toString()});u[Zr]=this,Vo(e,this,u)};else if(t==="close")i=function(c,d){let u=new nr("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Zr]=this,Vo(e,this,u)};else if(t==="error")i=function(c){let d=new Yr("error",{error:c,message:c.message});d[Zr]=this,Vo(e,this,d)};else if(t==="open")i=function(){let c=new rn("open");c[Zr]=this,Vo(e,this,c)};else return;i[is]=!!r[is],i[zd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[zd]===e&&!r[is]){this.removeListener(t,r);break}}};fh.exports={CloseEvent:nr,ErrorEvent:Yr,Event:rn,EventTarget:pv,MessageEvent:ss};function Vo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Jo=ce((dC,hh)=>{"use strict";var{tokenChars:os}=$r();function Ft(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function gv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,x=-1,h=-1,g=-1,_=0;for(;_<t.length;_++)if(h=t.charCodeAt(_),d===void 0)if(g===-1&&os[h]===1)x===-1&&(x=_);else if(_!==0&&(h===32||h===9))g===-1&&x!==-1&&(g=_);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_);let w=t.slice(x,g);h===44?(Ft(e,w,r),r=Object.create(null)):d=w,x=g=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(g===-1&&os[h]===1)x===-1&&(x=_);else if(h===32||h===9)g===-1&&x!==-1&&(g=_);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_),Ft(r,t.slice(x,g),!0),h===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),x=g=-1}else if(h===61&&x!==-1&&g===-1)u=t.slice(x,_),x=g=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(o){if(os[h]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);x===-1?x=_:i||(i=!0),o=!1}else if(c)if(os[h]===1)x===-1&&(x=_);else if(h===34&&x!==-1)c=!1,g=_;else if(h===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(h===34&&t.charCodeAt(_-1)===61)c=!0;else if(g===-1&&os[h]===1)x===-1&&(x=_);else if(x!==-1&&(h===32||h===9))g===-1&&(g=_);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_);let w=t.slice(x,g);i&&(w=w.replace(/\\/g,""),i=!1),Ft(r,u,w),h===44&&(Ft(e,d,r),r=Object.create(null),d=void 0),u=void 0,x=g=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(x===-1||c||h===32||h===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=_);let S=t.slice(x,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 mv(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(", ")}hh.exports={format:mv,parse:gv}});var Qo=ce((fC,Ah)=>{"use strict";var wv=fe("events"),_v=fe("https"),yv=fe("http"),mh=fe("net"),bv=fe("tls"),{randomBytes:Ev,createHash:vv}=fe("crypto"),{Duplex:lC,Readable:uC}=fe("stream"),{URL:Fd}=fe("url"),Dn=Kr(),Sv=Ld(),Iv=Bd(),{isBlob:Av}=$r(),{BINARY_TYPES:ph,CLOSE_TIMEOUT:kv,EMPTY_BUFFER:Zo,GUID:Tv,kForOnEventAttribute:Ud,kListener:Rv,kStatusCode:Pv,kWebSocket:We,NOOP:wh}=tn(),{EventTarget:{addEventListener:Cv,removeEventListener:Dv}}=xh(),{format:Ov,parse:Lv}=Jo(),{toBuffer:Nv}=ns(),_h=Symbol("kAborted"),Gd=[8,13],sn=["CONNECTING","OPEN","CLOSING","CLOSED"],Mv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends wv{constructor(e,r,i){super(),this._binaryType=ph[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Zo,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]),yh(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ph.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 Sv({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 Iv(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",Fv),o.on("drain",Uv),o.on("error",Gv),o.on("message",Hv),o.on("ping",qv),o.on("pong",jv),c.onerror=Wv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",vh),e.on("data",Xo),e.on("end",Sh),e.on("error",Ih),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Dn.extensionName]&&this._extensions[Dn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){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())}),Eh(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){Hd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Zo,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){Hd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Zo,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){Hd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Dn.extensionName]||(o.compress=!1),this._sender.send(e||Zo,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(we,"CONNECTING",{enumerable:!0,value:sn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:sn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:sn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:sn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:sn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:sn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:sn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:sn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(we.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(we.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ud])return e[Rv];return null},set(e){for(let r of this.listeners(t))if(r[Ud]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Ud]:!0})}})});we.prototype.addEventListener=Cv;we.prototype.removeEventListener=Dv;Ah.exports=we;function yh(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:kv,protocolVersion:Gd[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,!Gd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Gd.join(", ")})`);let c;if(e instanceof Fd)c=e;else try{c=new Fd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",x;if(c.protocol!=="ws:"&&!d&&!u?x=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?x="The URL's pathname is empty":c.hash&&(x="The URL contains a fragment identifier"),x){let I=new SyntaxError(x);if(t._redirects===0)throw I;Yo(t,I);return}let h=d?443:80,g=Ev(16).toString("base64"),_=d?_v.request:yv.request,S=new Set,w;if(o.createConnection=o.createConnection||(d?zv:Bv),o.defaultPort=o.defaultPort||h,o.port=c.port||h,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(w=new Dn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Ov({[Dn.extensionName]:w.offer()})),r.length){for(let I of r){if(typeof I!="string"||!Mv.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 v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,R]of Object.entries(I))i.headers[A.toLowerCase()]=R}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),v=t._req=_(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=_(o);o.timeout&&v.on("timeout",()=>{dt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[_h]||(v=t._req=null,Yo(t,I))}),v.on("response",I=>{let A=I.headers.location,R=I.statusCode;if(A&&o.followRedirects&&R>=300&&R<400){if(++t._redirects>o.maxRedirects){dt(t,v,"Maximum redirects exceeded");return}v.abort();let D;try{D=new Fd(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);Yo(t,C);return}yh(t,D,r,i)}else t.emit("unexpected-response",v,I)||dt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,R)=>{if(t.emit("upgrade",I),t.readyState!==we.CONNECTING)return;v=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){dt(t,A,"Invalid Upgrade header");return}let b=vv("sha1").update(g+Tv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){dt(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],L;if(C!==void 0?S.size?S.has(C)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":S.size&&(L="Server sent no subprotocol"),L){dt(t,A,L);return}C&&(t._protocol=C);let z=I.headers["sec-websocket-extensions"];if(z!==void 0){if(!w){dt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=Lv(z)}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(M);if(J.length!==1||J[0]!==Dn.extensionName){dt(t,A,"Server indicated an extension that was not requested");return}try{w.accept(M[Dn.extensionName])}catch{dt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=w}t.setSocket(A,R,{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 Yo(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Bv(t){return t.path=t.socketPath,mh.connect(t)}function zv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=mh.isIP(t.host)?"":t.host),bv.connect(t)}function dt(t,e,r){t._readyState=we.CLOSING;let i=new Error(r);Error.captureStackTrace(i,dt),e.setHeader?(e[_h]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Yo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Hd(t,e,r){if(e){let i=Av(e)?e.size:Nv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${sn[t.readyState]})`);process.nextTick(r,i)}}function Fv(t,e){let r=this[We];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[We]!==void 0&&(r._socket.removeListener("data",Xo),process.nextTick(bh,r._socket),t===1005?r.close():r.close(t,e))}function Uv(){let t=this[We];t.isPaused||t._socket.resume()}function Gv(t){let e=this[We];e._socket[We]!==void 0&&(e._socket.removeListener("data",Xo),process.nextTick(bh,e._socket),e.close(t[Pv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function gh(){this[We].emitClose()}function Hv(t,e){this[We].emit("message",t,e)}function qv(t){let e=this[We];e._autoPong&&e.pong(t,!this._isServer,wh),e.emit("ping",t)}function jv(t){this[We].emit("pong",t)}function bh(t){t.resume()}function Wv(t){let e=this[We];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,Eh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Eh(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function vh(){let t=this[We];if(this.removeListener("close",vh),this.removeListener("data",Xo),this.removeListener("end",Sh),t._readyState=we.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[We]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",gh),t._receiver.on("finish",gh))}function Xo(t){this[We]._receiver.write(t)||this.pause()}function Sh(){let t=this[We];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function Ih(){let t=this[We];this.removeListener("error",Ih),this.on("error",wh),t&&(t._readyState=we.CLOSING,this.destroy())}});var Ph=ce((hC,Rh)=>{"use strict";var xC=Qo(),{Duplex:Kv}=fe("stream");function kh(t){t.emit("close")}function $v(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Th(t){this.removeListener("error",Th),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Vv(t,e){let r=!0,i=new Kv({...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(kh,i);return}let d=!1;t.once("error",function(x){d=!0,c(x)}),t.once("close",function(){d||c(o),process.nextTick(kh,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",$v),i.on("error",Th),i}Rh.exports=Vv});var qd=ce((pC,Ch)=>{"use strict";var{tokenChars:Jv}=$r();function Zv(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&&Jv[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}Ch.exports={parse:Zv}});var zh=ce((mC,Bh)=>{"use strict";var Yv=fe("events"),ea=fe("http"),{Duplex:gC}=fe("stream"),{createHash:Xv}=fe("crypto"),Dh=Jo(),rr=Kr(),Qv=qd(),eS=Qo(),{CLOSE_TIMEOUT:tS,GUID:nS,kWebSocket:rS}=tn(),iS=/^[+/0-9A-Za-z]{22}==$/,Oh=0,Lh=1,Mh=2,jd=class extends Yv{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:tS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:eS,...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=ea.createServer((i,o)=>{let c=ea.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=sS(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=Oh}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===Mh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(as,this);return}if(e&&this.once("close",e),this._state!==Lh)if(this._state=Lh,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(as,this):process.nextTick(as,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{as(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",Nh);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ir(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){ir(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!iS.test(c)){ir(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){ir(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){cs(r,400);return}let x=e.headers["sec-websocket-protocol"],h=new Set;if(x!==void 0)try{h=Qv.parse(x)}catch{ir(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&g!==void 0){let S=new rr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Dh.parse(g);w[rr.extensionName]&&(S.accept(w[rr.extensionName]),_[rr.extensionName]=S)}catch{ir(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,(w,v,I,A)=>{if(!w)return cs(r,v||401,I,A);this.completeUpgrade(_,c,h,e,r,i,o)});return}if(!this.options.verifyClient(S))return cs(r,401)}this.completeUpgrade(_,c,h,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[rS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Oh)return cs(c,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Xv("sha1").update(r+nS).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;_&&(h.push(`Sec-WebSocket-Protocol: ${_}`),g._protocol=_)}if(e[rr.extensionName]){let _=e[rr.extensionName].params,S=Dh.format({[rr.extensionName]:[_]});h.push(`Sec-WebSocket-Extensions: ${S}`),g._extensions=e}this.emit("headers",h,o),c.write(h.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Ox),g.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(is,this)})),u(g,o)}};Nx.exports=Hd;function sS(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function is(t){t._state=Lx,t.emit("close")}function Ox(){this.destroy()}function ss(t,e,r,i){r=r||Xo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Xo.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",Nh),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(as,this)})),u(g,o)}};Bh.exports=jd;function sS(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 as(t){t._state=Mh,t.emit("close")}function Nh(){this.destroy()}function cs(t,e,r,i){r=r||ea.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} ${ea.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 tr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,tr),t.emit("wsClientError",l,r,e)}else ss(r,i,o,c)}});var Jx=ae(Me=>{"use strict";var L=ne;(function(t,e){let r=ne,i=t();for(;;)try{if(parseInt(r(1354))/1+parseInt(r(185))/2*(-parseInt(r(1374))/3)+parseInt(r(865))/4+parseInt(r(1647))/5+parseInt(r(336))/6+parseInt(r(1599))/7+-parseInt(r(347))/8===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(sa,527038);var hS=Object[L(1117)+L(1030)],xS=Object[L(734)+L(1358)+L(941)],qx=(t,e)=>function(){return t&&(e=(0,t[xS(t)[0]])(t=0)),e},pS=(t,e)=>{for(var r in e)hS(t,r,{get:e[r],enumerable:!0})};function gS(){return zx||(zx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function mS(){let t=L;return Ux||(Ux=[IDBCursor.prototype[t(1195)],IDBCursor.prototype[t(169)],IDBCursor[t(1292)+"e"]["continue"+t(1581)+"ey"]])}function wS(t){let e=L,r={rZizD:function(o,c){return o(c)},sAzyo:function(o){return o()},yyqDk:"success",mMtfO:function(o,c){return o!==c},adFLh:"UqEGY",ZseyA:"cXjFk",sAuLC:"error"},i=new Promise((o,c)=>{let l=ne,u={nAIgC:r[l(1075)]};if(r.mMtfO(r[l(838)],r[l(488)])){let f=()=>{let w=l;t[w(765)+w(1248)+w(999)](u[w(302)],x),t[w(765)+w(1248)+w(999)](w(709),g)},x=()=>{let w=l;r.rZizD(o,r[w(1095)](Bt,t[w(1627)])),r[w(1220)](f)},g=()=>{let w=l;r[w(1095)](c,t.error),r[w(1220)](f)};t[l(1225)+"Listener"](r[l(1075)],x),t[l(1225)+l(1389)](r[l(1055)],g)}else return this[l(1404)+"s"][this["currentI"+l(729)]]});return i[e(1496)](o=>{o instanceof IDBCursor&&qd.set(o,t)})[e(663)](()=>{}),ra[e(1041)](i,t),i}function _S(t){let e=L,r={dsjmK:e(868),wWVYu:function(o){return o()},gNOyn:function(o,c){return o(c)},oCXuO:e(752)+"or",fuDJo:e(709),ldhyL:e(1465)};if(na[e(1069)](t))return;let i=new Promise((o,c)=>{let l=e,u={PRMuH:function(w){return r[ne(1142)](w)},TnNOa:function(w,S){return r[ne(1065)](w,S)},qFUaa:r[l(1365)]},f=()=>{let w=l;t["removeEv"+w(1248)+w(999)](r[w(276)],x),t["removeEv"+w(1248)+w(999)]("error",g),t[w(765)+w(1248)+w(999)](w(1465),g)},x=()=>{let w=l;u.PRMuH(o),u[w(396)](f)},g=()=>{let w=l;u.TnNOa(c,t[w(709)]||new DOMException(u[w(1080)],u[w(1080)])),f()};t[l(1225)+l(1389)](r[l(276)],x),t["addEvent"+l(1389)](r.fuDJo,g),t[l(1225)+"Listener"](r[l(423)],g)});na[e(1041)](t,i)}function yS(t){ia=t(ia)}function bS(t){let e=L,r={dKGyl:function(i,o){return i(o)},jEgUR:function(i,o){return i(o)},inAtH:function(i,o,c,l){return i(o,c,l)},gJwHI:e(1130)+e(1133),aTVSr:function(i,o,c,l){return i(o,c,l)},cltJY:"x_frontier_qos_ack",siRRX:e(1130)+e(159)+"k",Rjbwb:function(i,o,c){return i(o,c)},oUIkY:e(1130)+e(1450)+e(670),GWnKs:function(i,o){return i===o},QzkyO:"QpexV",OkJoT:function(i,o){return i(o)},DphCd:function(i,o){return i(o)},ifDHz:function(i,o){return i in o},WylSH:e(715)+e(308),sDRiT:function(i){return i()}};return t===IDBDatabase[e(1292)+"e"][e(593)+"ion"]&&!r.ifDHz(r[e(1059)],IDBTransaction[e(1292)+"e"])?function(i,...o){let c=e,l=t[c(725)](r[c(1364)](os,this),i,...o);return jd[c(1041)](l,i.sort?i[c(444)]():[i]),r[c(1357)](Bt,l)}:r.sDRiT(mS)[e(983)](t)?function(...i){let o=e;if(r.GWnKs(r[o(222)],r[o(222)]))return t[o(666)](r[o(1357)](os,this),i),r[o(853)](Bt,qd[o(873)](this));{let c=!!this[o(1045)][o(152)+"S"];if(!c)return{enabled:c,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=r[o(741)](_0x152597,_0x49c7ad.message[o(688)],r[o(1620)],"2"),u=l&&r[o(545)](_0x1d3773,_0x2d3f70[o(1645)].headers,r[o(1286)],"1"),f=l&&r[o(741)](_0x5ad51e,_0x2f8beb[o(1645)].headers,r[o(880)],"1"),x=f?r[o(466)](_0x356c6f,_0x566524.message[o(688)],r[o(735)])?.split(",").filter(_0x33cf33)||[]:[];return{enabled:c,isQoSMessage:l,isQoSAck:u,isAckCleanupMessage:f,ackMsgIds:x}}}:function(...i){let o=e;return Bt(t[o(666)](r[o(1372)](os,this),i))}}function ES(t){let e=L,r={NLDui:e(271),fUCnF:function(i,o){return i instanceof o},gcWTR:function(i,o){return i(o)}};return typeof t===r[e(1640)]?bS(t):(r.fUCnF(t,IDBTransaction)&&r[e(542)](_S,t),Wx(t,gS())?new Proxy(t,ia):t)}function Bt(t){let e=L,r={HSwfb:function(o,c){return o instanceof c},MJNjl:function(o,c){return o===c},uYjGU:"done",TqQDH:"store",MIIZY:function(o,c){return o in c},jiNGb:function(o,c){return o instanceof c},MGbwD:function(o,c){return o(c)},fiXtD:function(o,c){return o(c)},xOmKe:function(o,c){return o!==c},hAmDf:e(1580)};if(r.jiNGb(t,IDBRequest))return r[e(1649)](wS,t);if(ea[e(1069)](t))return ea.get(t);let i=r.fiXtD(ES,t);if(r[e(667)](i,t)){if(r.xOmKe(r[e(491)],r[e(491)]))return r[e(1025)](_0x1f8f8d,_0x4741ac)&&(r.MJNjl(_0x1bdb7f,r[e(801)])||r[e(1228)](_0x53ce4f,r[e(877)]))?!0:r.MIIZY(_0x93c6ac,_0x42216f);ea[e(1041)](t,i),ra.set(i,t)}return i}var Wx,zx,Ux,qd,na,jd,ea,ra,ia,os,Gx=qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=L,e={sOvba:function(r,i){return r!==i},ksoDC:t(835),adPbN:function(r,i){return r instanceof i},qrZbn:function(r,i){return r===i},DeePg:t(419),XjoBO:t(715)+t(308),ROlki:"store",MBloj:function(r,i){return r(i)},pWGhm:function(r,i){return r(i)},gNZEd:t(757),xMnGu:function(r,i){return r===i},tZDXT:function(r,i){return r in i}};Wx=(r,i)=>i[t(218)](o=>r instanceof o),qd=new WeakMap,na=new WeakMap,jd=new WeakMap,ea=new WeakMap,ra=new WeakMap,ia={get(r,i,o){let c=t;if(e.sOvba(e.ksoDC,e[c(1525)]))this._qosDB?.[c(1081)](),this._qosDB=void 0;else{if(e[c(399)](r,IDBTransaction)){if(e[c(1219)](i,e[c(1275)]))return na[c(873)](r);if(e[c(1219)](i,e[c(829)]))return r[c(715)+c(308)]||jd[c(873)](r);if(e.qrZbn(i,e[c(1533)]))return o[c(715)+"oreNames"][1]?void 0:o["objectSt"+c(1086)](o[c(715)+c(308)][0])}return e[c(1063)](Bt,r[i])}},set(r,i,o){let c=t;return c(1462)===e[c(1258)]?e[c(1554)](_0x3260e7,e[c(1063)](_0x13ffac,_0x3c6c24)):(r[i]=o,!0)},has(r,i){let o=t;return r instanceof IDBTransaction&&(e[o(180)](i,e[o(1275)])||i===e[o(1533)])?!0:e[o(360)](i,r)}},os=r=>ra[t(873)](r)}}),Kx={};pS(Kx,{deleteDB:()=>SS,openDB:()=>vS,unwrap:()=>os,wrap:()=>Bt});function sa(){let t=["rgX2zLG","Dg9mB3DLCKm","ALPVqLO","vLDUqvy","wur6uLK","y3HpwK8","yM9L","CuXqvfe","zw5fDMvUDa","yxnL","tufyx1jfvfi","rKDIEue","Dgv4DfbHEwW","ihrYEsbYzwm","tgLZDgvUzxi","yLnqrgW","BgvUz3rO","wengvhu","AvztENq","C2vUzf9Hy2S","q3nKCgS","zgDmvM8","x2nSzwfYugK","q0HszvK","wM9uwwy","CNHerNO","BwHMv1e","u3bsyvC","x3nLCuLK","zw5KCg9PBNq","zfL6D20","CMvUDevUzha","yxnZAwDU","ywnR","C2LXC1C","DfjxsLO","zxrTtfu","AxnbCNjHEq","ywXSB2nvBNm","uKXgvhO","BvvYBfC","z1rPBwvVDxq","DfP6uMG","v1byD1e","DMvY","su5tvefova","C2XqsKC","y29UBMvJDfm","AwjVr0e","DMPAt2S","y3vYC29Yx2y","uvviyvG","AxLRywG","yNntAgK","B2nRzxq","DMfSDwvZ","wenKwu0","ywzL","qw1VDw50","tw9KDwXL","D2zTBgO","ywrK","ELzPAwy","C3bSAxq","CLDiDhm","ENjWtM0","rhHkC2S","qvfbqvC","CYbWyxjHBxm","CgfNzxnOB3C","yxGGCMv0CMK","BNbYqve","uMTPzg8","wgr0DwW","qxDYzLu","zxjFywnRx20","CNjVCK1LC3m","Dxvsy1G","yLjbtKq","qvbmvxa","z1Dxvhe","quLiyuq","sMz4v3q","uMjRr24","vNrRr1q","vvjyB3y","zgvS","B1H1DM8","D3jPDgu","x2HHBMrSzu8","ywjVCNq","C2XerMC","ihn1y2nLC3m","y2uGBM90igK","D0nht1m","mxW4Fdj8nNW","zxjHDg9Y","CNfzs0y","u0XYEhK","vKPqtNy","rMrAB0K","verZuKm","y2XLyxi","x19LC01Vzhu","C3zIr0y","AK9nBLK","DhLWzq","DMfS","zNPHEwG","C0rpzhm","EM5OD08","uxjkEva","x2nVBM5Ly3q","ANHcALu","rNjVBNrPzxi","AgvKtwf4uMu","r25bqKG","rxzLBNq","AMDRwMW","EvjLy29UBMu","x3bHDgHlzxK","DgHLBG","yxKSig5LDhC","Aenht3y","C2Dhteu","CMvZzxrdB3u","yw5ZzM9YBvq","EsbJBg9Zzwq","wg5dBKq","rMDoD2i","rfrXvNu","wLHAug4","yNfUB2i","v0TIBgK","y2jRrhG","Bwf4uMv0CMK","x2DLBMvYyxq","sLnptLa","l3DZl3yY","vNP0C28","yMnKEKm","u2Xtrxu","qwHIqui","y29UC3rYDwm","ywWGy3vYC28","B25LCNjVCG","Cgf5Bg9Hzeu","AgDKzKO","z21frKO","sKz6BvO","A3nVrem","C0XPC3rLBMu","D05YyKS","vNHQsw8","EerPyMW","sKLcDKq","t2HMs20","DxbNCMfKzw4","uK9SA2K","x29UugfNzu4","EfvZzuvUDG","tMfTzq","t3bLBKv2zw4","DhjPzxmGCMu","zw5HyMXLqxu","DeLUDgvYy2u","BLLfswO","EKfAtwS","DgvZDa","t2rLEfC","C0DzAgO","z2vtEw5J","CMvJB25Uzwm","tLHeuhu","whjWBhe","igzHAwWSig0","Cgv0s3u","Au9ir08","AefTEK0","CfDhAg0","x3fVC0rc","B25tDgfYDfi","s0vZEfC","rxr5B1e","Dev2zw50","B25fCNjVCG","mxWWFdr8m3W","y3jLyxrLt2i","Chv0","ignVzgu6ia","CgfNzwHPzgu","yxKSihrYEsa","igzPzwXKoIa","vKToy0W","nNW4Fdb8m3W","x2vUzhbVAw4","CMvXDwLYzwq","q1jvDMS","x2LUAxq","yNzoENC","vK9xqLK","Aw5N","CNzHBa","BgLZDgvUtMu","zNbStMu","EK9PCNq","uhjPBwfYEuS","vffIyxK","v2Xuq0q","rgLVCee","z2vY","DhjPzxm","BMv3vMvYC2K","y3vYC29Yx24","zxf1ywXZ","x29UrxjYB3i","A3nTCgS","rLzAtNO","vhrnz0G","y3vZDg9Tshq","rhjczMq","zxf6wMu","C3rLBMvYCW","CgvYC2LZDgu","mJa3ndy2menUrhrIzG","C2vYDMLJzs0","AgLNAa","BuTjyNi","EgTPy1i","uuLJuKu","s0nlv1i","v1risxC","yM9KEq","Bgvmuhy","zw1PDa","zwDTv0u","zgvzy24","u1jVv0q","y3jLyxrLrxi","o2nOyxjZzxq","y2HnyxHdB3u","s3ndEKu","EMTIteS","y29UBMvJDca","Cu10tg0","z0P3seK","q3zpDLa","Bg9NsurozxC","uKTrCeG","CvLRuuq","D2vI","zuPXEwW","CMvZDwX0","AfnWr2q","zcWGDw5RBM8","Dvjjqve","q09otKvdveK","B2HWEg0","v0rlDhq","ExzXvfK","ELfhuMO","B25pCgvU","yNvMzMvYzwq","tw5lsLa","C3PTvwe","tKXeDwK","zw5JB2rLrNi","x3vYBa","yNL0zu9MzNm","zw50","BwvZC2fNzq","zv90Aw1LB3u","mty4ote4mgTrt2nWDG","B3jRig9MzMW","tuDID0q","BeLyBuG","CvDMDgW","zMDzAKS","CgLUz0LUDgu","ChPZC2i","r3jTu00","zxjYtM8","zLncrM8","t1H6Euq","ze1Vuvq","CfvWDM0","wM9Lzg8","zw5HyMXLuw8","y3jLyxrLt3a","BM93","x2rLC3rYB3K","BKDHC2q","vu1MDeG","mxW1Fdj8nNW","zxjFAxnFywm","Aw5KzxGGB3u","yxbWBgLJyxq","uxvLDwu","y3jLyxrLtwu","CgLUz19VBMm","shLbDuy","CMfNzvn5BMm","yxzYthu","Cg9PBNrbBMq","y29UDgLUDwu","C2v0y3vYC28","zufJAW","vvLJvg4","CM92AwrLigi","y3jLyxrLq2W","v3zbtNK","Aw47y2HHCNm","DcbSAw1PDa","y3r4","vgzxBuK","Ee1Ur3u","yKHwD3O","BgLTAxq","ywX3yxLZ","yMLUyxj5vhK","mJa5ndHpEw9kz1K","r3DjzwW","C2fNzq","tMHYCve","AxnrB1nnzxm","t295qKK","wvjqC1q","vMTcv3i","vKXqvgS","zLnuvee","qMLqrKG","vhjRvfa","zMXVB3i","C2vUDa","EhHUz3q","yxHKCei","AKDnBuy","veX3q2m","wxz0zNK","C0nVDw50zxi","BM5Ly3q","rgjdu2K","shjyzxy","m3WYFdr8mhW","x2LZtwLUAvq","vNLkrNG","x2rItMfTzq","y29Kzq","q291BNq","rvnSv1C","tefys3G","qM1cv00","wgjHA2u","C29Tzq","uKXSyKO","quD4s1e","tMDut0e","uxPREu8","DMvYC2LVBMm","ANfbCxu","u2HPt0O","EKzAtMW","r2HWq2y","C3D3sfe","CMvHzg9UBhK","AuLQwfq","CNnVCL92ywW","rKDhsva","yxvHr2G","BfrPBwvVDxq","AK5JBwy","x2n1CNnVCK4","v2vPEgLUsLm","te9OCfC","Dg9iyxnO","uM1vDwC","q29UzMLN","qMjkB3q","wuv4tuC","yuTeCu0","A3b1z0m","uuvYBxO","u09Jqxe","DhbizwfKzxi","wu5bqMu","Aw50zwDLCIa","ywnRx2LK","zuTVA0W","EKj3t3e","rxfdvuW","rMThtwy","vunQDuO","weD6t1y","CLzHBhvLCW","zMLSzw5HBwu","r0Xmy04","twLouMe","AwPIAeO","vxLytNG","C3vIyxjYyxK","wxr5Agq","q2fMB2q","B3v0sw50zxi","y3jLyxrLuMu","suvrvgO","ENzxDuK","zNvUy3rPB24","v3zrs1K","yNH2r0G","z0LMwKW","EgXfB28","zhnQBuS","zNjHBwvuExa","x1fVu01HBMe","vhr5Cfm","uu5Vzvu","nhWZ","te1Jq2u","z1DMy28","AevYCM9Yrxy","BwLUzW","twXlqxe","B25szwnLAxy","u0jtzfq","yw5Nzq","x3bPBMC","y2HHCKnVzgu","rKDOuxy","Aw5KzxG","uKDXzhm","C3LQDMW","CMvHC29U","Efftuhe","DhvMzfm","sundz0K","v3njA1i","z1jzBg0","BKfjz0m","DuzIvLy","v0LXtvK","x2zVCM1HDeu","Aw1LCYbPBIa","zgXcuxG","B3jLtMfTzxm","Dw5RBM93BIa","ven1tLe","x29Uq2XVC2u","rfnrvxu","Ahr0Chm6","s2XuAhG","yNvMzMvY","refKr2i","A0r3yvq","BLzzBui","B3jRzxjhBg8","B25TzxnZywC","ExDmCNm","u2vYDMLJzvC","qu9ewfy","CgrWtNi","A2L3tgu","uxL5B0C","qNzise8","lcbOB3n0BMe","B1jRz0m","yNL0zuXLBMC","AejfvwS","zsbHihn0CMK","EKPZtgG","uNzVBxy","rvH3Euu","mJi3mZu3ng1bywLPBW","vfbZtfi","tvrpu3i","yw5Hz2vY","zgLZywjSzue","sMfkwgK","BujvDui","CMrfwu0","A2v0ignVBNm","x2XPC3rLBMu","D1DtsNC","mZyXntGWmhzjzw5xEG","CMTLCKDSB2i","BMDLza","uM9eEei","vfLSAKy","AwXK","wMXgtg0","BwLZzq","y3LPvei","sxzMq0C","yMPgtvy","uuz0C2W","BMriuNG","DfPewfq","Afrhq1y","Dgv4Dc9Qyxy","ywnRDxbfBMq","DgfouM4","mNWWFdr8mxW","CwvHAxy","z2HTvMC","tw1QvMu","C2nmuNm","AhbwCfG","tKLwDeO","v2vIu29JA2u","zwXhuLK","BhrPCgXLihq","z2v0sxrLBq","q01Huvu","Bu1lshO","z3bAtMC","uKPbqNe","Evjlsgy","jMPZy2fSBgi","r0jjqvC","wgfRyxm","zMzmAw5L","Cun2u0C","DevHsgu","sM1gruu","yw1L","y09fs0q","zxq9DxrMltG","wMLgCe0","Dxrjza","yvvOB3O","Be9tuu4","AxnAzxjV","ufjnDuG","thrszgS","Be9orKO","ywrqyK4","uhnly3i","CNvZuLi","B25tDg9Wsw0","ExbL","wvLOBKq","q2rIBhq","vhDtAgC","zNjVBu51Bwi","AxmGDw5Kzwy","zM9Yy2u","y09Wzw4","Agzvrxu","wKLYsxy","sLjTuLC","m3W1","Ec1TC2CTCw8","Bgv2zgK","q256u0e","DK9ICu8","zg9Uzq","rvn1yLK","zNDZxZeUmc4","AgvHzgvY","BgrOEuW","DxbKyxrLq3u","Bwf4tg9ZC0m","C3vIC3rYAw4","t3bqqLy","DMflC3q","y3jMAuK","z2vjBMzVu3K","A1fJtwW","ugriD0W","CeLdwKC","y0Pmy3i","zv9ZDwnJzxm","B3jpBMXPBMu","CMfUzg9T","tg9Nsuq","Bg9Nsurhzw4","BgvY","ChbL","Ag9gs1u","tKHPruO","C29YDa","vMPftuG","BIWGAg9ZDg4","x2rYB3bhBg8","t1vyC3u","EuXMzuy","x2rPC2nVBM4","zNPwCfK","tg9WAvi","Dg9oDw1Izxi","DuzctuK","Aw5Lza","zNjVBujPDhm","we1qsgi","rLfgBLm","B2XKvMvYC2K","BMP1EhC","CufKrhK","q0Xpu0ve","C2vUza","vKPgq1G","BuLZrve","uMPID2i","qM11rM4","x3jLy29UBMu","ChrVCG","r1P3zxO","rLHTAvi","s3vzz1m","n3WXmhW5Fde","mhWZFdj8nhW","Cw1gCuG","tfDmv2C","Afbhzxq","y2HLy2TdDxi","AxjLza","B2nRzxrtDwm","serZvNy","x2LZv29YA2u","ugX0wgO","tNfwruy","rxzOthC","m3WXFdb8mNW","B3bLBKrc","wNnLEue","ue1nswu","DhjPBq","AefTrgy","wuvRy0G","DKfJu0W","s0Hhzvm","rvnIrKi","CKXWq1e","x2HHBMrSzva","wMzRsLm","wKPyrgG","CgnJBeq","BwrcyK4","Dg9cExrLC0i","zufpvM8","z29PBMCGyxC","Ceryt1m","Exrezhm","CxPHq0W","x0vysvnu","DxPUwhG","reiGzMfPBgu","BwvZC2fNzv8","BgLUzw5V","y2DkyuC","Dg9tDhjPBMC","lcbTyxGGCMu","BMvJDa","wwvkChC","vvjKCxu","u3Lhzei","t2LHrfi","t2PuDeO","wfjfBLm","swLNvhe","ihzHBgLKigq","s1DivhC","r3rczKy","y1v5D0m","rML0swK","BeHHBMrSzxi","zNjVBuHHC2G","vxbKyxrLq28","tvnADNi","CMvWBgfJzq","rhzqqMC","wgL5CuS","ywDLu2HVDW","uuDPthm","igXHCMDLCIa","y291BNq","wMfZBha","q3vZDg9Trxi","z2nxvfi","De9StxK","BNncz2i","yvrwu3i","rNrMBeS","vuPnwhO","Dw5fwgm","shDpBfm","yMrFzgLK","q2n0sMO","DgLLCKPtt04","rLLbu2G","wfvUq2q","qwX5Ahu","BMXtruq","thjfB0S","wwjvsxu","Bwv0Ag9K","DeXYzwu","uMXgEM8","tg9NsurozxC","BxnNsuq","C2jzAge","EeLfrxa","zvLUqxC","Eg1cwwy","EMPMuxG","Bg9N","CMDHrMC","nhWYFdb8m3W","wxn5BK4","zu9JD0i","rvniswm","BK95Bee","zu5IBu0","z2v0qwXS","rwvdvMO","zw5HyMXLvhi","yxbWzw5Kq2G","y0TSA2O","C1zsvM8","BMnVzgLUzW","vxDjruC","DK1iwem","ufbuq2G","Bg9IywXty28","Aw9U","C3rYAw5N","BKTftfq","AwXLx25HBwu","mhWZFdH8nhW","DhjHBNnHy3q","tKLcq1K","DgLUzYbZzxi","C3bSAwnL","yMLUza","ruf3te4","vePjt2S","x3bPBMDqB24","twLZC2LUzYa","zgPtrwm","sNDtAKO","uxbcwei","Ae9Wzw5fDMu","ywrKq291BNq","ysbTDxn0igi","zxHWB3j0CW","Bhm6ia","rhnsDNq","C3v0zuS","Axnby2TdBgu","zxrxB3jRq2G","r2XLuxa","zffgzum","uKD0t3C","yMfSrxzLBNq","BwvKAwf0zwW","x2LZtwLUAvC","BhfYyuy","DejTyLi","C2vYDMLJzq","v2LUzg93","aaaaaaaaaaa","vw1gzee","sfzAu3C","BM9Uzv9UB24","x3nVy2TLDa","y2PoAei","BwPqs1C","yLfSsfi","ywnOzwqSihC","s0L2y3y","B25VCgvU","r3D3ugC","pxv0zI04","rhH4yLK","zxvmCKe","zgv2AwnLx2K","rMDLDMu","DhzdwMq","tg9JAW","x3DZ","uKvPyxC","x3jLBw92zvC","DgvmB2Djre4","qvDOBMq","CgLUz09Uy2u","x29Ut3bLBG","Cw9Zx18","ue1vtxG","DhDvAxy","B25mAw5L","rg9tsK0","B3bLBG","ExnXC24","v2rXEMS","vMrHvxu","zLjuDvy","CMfTzq","Bg93","D0v5sxe","y2f0y2G","uK1XsNu","t25Sr3C","yxbWBhK","Ee9Ts2u","BezSDxnO","zxH0ugf5Bg8","C2DPza","B0nVBhi","zgvSzxrL","BMrWB2LUDca","x2jPBMfYEvq","tvLgyvK","t1bftL9fuLi","Ehbiwui","vw5PBxbSzw0","suLirhK","runPDLK","zML3rgu","t0v2Dwi","zMLmALq","sKDQr3O","A1jqug4","ufnsq0K","BKXPBMu","AgvHzgvYCW","BeP3rNG","twPTuKm","ywDLrxzLBNq","ALfRA2e","tMHIAwO","tvDJteC","sMXJq2W","CgfYC2u","vwnItKu","BNruCMLLC0m","uNzduuq","r1fpv0u","BMCGzMfPBgu","s3bUAfC","uMvHzcbWyxm","twjAAfO","zhbAz0u","yw1LoIa","rLvet0e","EePYuwO","zxjYB3i","DgHHBIbSB2m","CLffufC","t3nPzvC","surjBgW","BwPjrMK","B2jQzwn0u3q","x2HHBMrSzvi","x2LUAxrhBg8","zNvvtMK","uLjpuG","BwvY","ruf4teO","zMLNBgG","EunREfa","C2Prqw4","y2fSBa","r0vJugW","C2v0u3rVCMe","tuvtu0fhrv8","BMrLEa","vuP0zxq","x2fKzfDZtgK","mtb8nhW5Fda","CwTPA1e","z2v0t3DUuhi","B1vjA1K","v3fwB0q","C3rYAw5NAwy","u3rYyxrLz3K","nxWYFdy","y3ruAw1LB3u","Aw5bDeG","z092svy","r2rAwfC","CNzHBfzHBhu","AunRv3G","Cw1tvwG","ruf4r0W","yKzuuxa","x2LUAxrqCM8","B2zM","DhDVCMTdAge","qwjVCNrfCNi","wwLyruy","ywXSq3vYC28","C0Xf","zfH1tNC","sgTVzhG","svvksfq","v0jvuMC","EMfus1C","Bg1KvuS","txDHB0S","rMD2u3i","v2TiAfu","CMvTB3zLrxy","BMfTzq","Ce9gyM4","x25HDMLNyxq","yxP0CKm","wuTutfO","x3DHAxq","vgzRvuy","C3rVCcbPBw0","zxjFCw9Zx2e","BwvZC2fNztO","zfzMEwO","mNWX","ALDJzxu","Dfvgt1O","v2HxAu0","vKzty2S","DMvUDa","tu5pEM4","BNrfBMrWB2K","sNjHyMS","rLDt","De1HBMfNzxi","mdaWmdaWmda","C2v0zgi","AhryCu0","qKLxuuK","C3nHz2vfDMu","zMzLCG","Bhvkr1q","mhW0Fdj8mxW","vNjptNK","CfnAy0K","DLzeBMG","vvrYruW","zgvSzxrLrge","DvLQr1u","r1DiAxi","C3bfvNu","zxjYtxnN","ALjHDNy","sfnouMC","veHAq1q","CMvZzxruCMK","zxH0zw5ZAw8","ue13r2O","sxjxuwq","ExbuC0K","tKDFrvjst1i","oxWXFdeXFdC","D3jPDgvvAw4","AuPkseS","Dg9cExrLC0W","yLj3ywy","uu5vs3u","twzSzei","q0zkCwC","wKPKAvK","Bergyvu","DgTTvge","z2v0qwXSs2u","ExfLr0u","id4G","Dw5ZAwDUzwq","wgPVqK8","tLnntg0","qMjTt3G","ALfSr0O","sKz1uMq","yxv0B21HDgK","DMvczhC","x3nLBMrby2S","yLLADgy","ywrgtgG","BxHWwu0","C3vJy2vZCW","CIb0DhDjra","yMXVy2TLza","CwPNENu","CMvHzfvjBNq","icSG","t2jZthO","ENbjue4","ywnOzwq","Cgf5Bg9Hza","AwXSihvZzsa","x29UtwvZC2e","A2v5CW","t2TkB1q","C3jJ","D2TrENa","yLjNrgq","B2zMC2v0","q21Qy3i","zw5XDwv1zq","x194x21Zz18","ANnbEMe","zMLSDgvY","CvbeB1K","Ec1TC2CTy3u","nJeWmZzLAvjOD2e","DxjS","v1zPvKS","y29TCgXLDgu","Ag9vAKO","Dw50","qMDgBgK","s0jnsuy","z2v0","z0D6wKq","CMvZzxrfBMq","DxrMofDYAxq","vhfrreG","y3vYC29Y","uwHks0q","C2LsuLG","vhnxAhm","DujhtvG","s1biAwe","DxnLCKLW","yKfdDNu","x0rctMfTzq","D250weG","uLjMzKe","B3vUDa","BNrbBMrvCgq","sMLmvu0","qKPrA0S","CgXLyxnLiha","DeHyyvC","t2rewLa","BNvTyMvY","DuDeDfq","yu53qKm","tufPD1G","ig1LC3nHz2u","yw1Lu3bHy2u","BgLJzuu","EePkvLm","n3WWFdn8mNW","zMLN","q0Xpu0LorW","B1jhAMG","ruDuzuy","BKvbyuO","zgL5B3m","ueLcwwC","qvHYrNm","x29UvgLTzw8","vgLTzw91Da","twvZC2fNzuu","uefZt3m","CgLUz1rPBwu","EgDLuhe","CMvHzhLtDge","y21Yyuy","Dg9cExrLCW","vhPly3i","vuXRDwu","CM9YrxzLBNq","t2jQzwn0","B0DWBvG","tfPUCxG","yxP5v2u","BLnMu0S","q1zntfu","ANretLO","zKXdrhq","whbctgG","D0XQsKi","AuXqq2q","u0PzrgC","x2rLyNvN","DMLVsuK","Aw9UvgLTzw8","vvrSwfi","BwvZ","ueDntxa","Egzgs3m","x21LC3nHz2u","ze9yDMy","Dw5KzwzPBMu","DKHTzMu","z2v0q3vYC28","tKDmzuK","Du9dExG","CxjfD0u","BfDQwKC","C2nYAxb0","BeXNDgK","sffqEuS","qKT1BxK","ENnJvKS","rNjotvO","vgD3wK8","DgLTzw91Da","Ce9gCNa","wLzmy0q","uuTqqu8","C3bcyxe","r0XswKq","tu92qKi","r1PcteS","qxDTvMK","A1n0yxr1C0m","rLH0DuK","s2jyz0i","AwTHrhi","FdD8nxWX","zM5crKm","yLnkwem","ign1CNnVCIa","yMLUyxj5","BvnPChG","x3jLywr5q2W","nxWZFdj8mhW","t1bftG","zxjFDhrS","Aw5JBhvKzxm","AxnszwfKEq","tvvWBw0","DwDmBeW","zfHcDvu","rNnJDu0","DhPPBvC","BwfUDwfSihi","rxjYB3jdB2q","A0PZswW","ANnwu3i","ExPAtwS","yNLL","AwDHDg9Yt24","vLLSrve","BgLUzq","BMvY","y3vYCMvUDeu","CwLcv3u","tKfKsgK","x2nYzwf0zvm","uMvJB25Uzwm","Ahr0Ca","vezJuLu","ywDLsgLKzq","DMzisLq","DgfIyxnL","D216y1O","B3nLrxzLBNq","vhHkCvK","tujPzKu","y29UBMvJDgK","CK12qvG","ugPUz3a","y3juAuO","zhDWDxC","uNLXA1m","x2LUDgvYDMe","x3DZsw5ZDge","s3P2weC","C2vYDMvYvgK","DMvYC2LVBG","sfn3zMi","tvPMsNO","Cg93","vvPZD1y","Ae1LC3nHz2u","B3bLCNr5","C0PhCKC","CNnVCKzPBgu","AwroqKO","x2DLDeLUDgu","x2n1CNnVCK0","nxWXFdz8na","q09oveLovuu","AwDJD2u","C2XPy2u","B2nRzxrgywK","C2v0","BKzxD0S","wuHguuK","Aw5PDcbrB1m","x29WDgLVBNm","z1nQD1q","zfDVCMTLCKC","DxrVuMvJB24","ExrYCLe","DcbVzIbYyw4","tKfusvzfx0u","q3vZDg9Tq2W","x2n1CNnVCKy","suvtx0vsuK8","C0f1tem","Dgv4Dc9WBge","rvjst1i","B2zMBgLUzq","v3LSu0G","wvr3EM0","uwXjENi","y2HnyxHuCMK","tujSB2O","B25SAw5L","z05pEw4","BKnWCLe","ywDps28","BMDuAw1LCG","AgfZ","D3nZoI8V","uK5JAKO","zNjVBunOyxi","y09kteW","zwnVBM5Ly3q","ExLXrgS","vMTAyLC","u0fLD1C","AeXKq0i","vunpuvq","Cuzvywe","y2XVC2u","Cg9W","CLnMzMS","nhWWFdn8mxW","vKT2s2y","B3jL","zwrPyxrLBhK","x3bYzwzPEa","B2XACg0","zwvKzwq","z3bKr2O","vxLcD08","B2jWvve","q3n1D2m","CLPPEKq","EezUyKW","zNjVBNrPzxi","D0rzEKG","BwLUAvbYB2C","yxLIreG","CKnbyK4","ywXcrK8","uhLgCu4","vgfN","Dg9VigXHCMC","r3fJDfO","tvrly3e","A3zUqve","mdaWma","AxnrB1nby2S","sLLhwKW","AKLfEwW","BfPRwfO","B25JBg9Zzq","sKjMrwO","y29SBM8","zgvMAw5Luhi","zMfqB2G","B2fK","tfbkuxy","C0jf","D2XiBwK","zgvJB2rLzey","u2vXsuq","vePvBKS","x2LZtM9Kzq","wuvNAxK","qK5Tu0G","zMLUza","Ef9MCM9UDgK","zw5JB2rPBMC","B25dBg9Zzq","zxjFCw9Z","ExLjBe0","qNjPzgDL","AgfZt3DUuhi","ChjVDg9JB2W","tKziqxC","z2v0u3rVCMe","AwrI","D0rouMe","D1Dwwxu","EMvpyMq","D0XOvw0","EgPHAxe","BejoEhi","yxrHlcbKyxq","ihrPBwvVDxq","y3vYCMvUDeK","y2vZC0HHBMq","A2v5","ihbYB3rVy28","q29Kzq","yurLC08","ugjbB0O","CMvHzhDYAxq","sgDYzhG","tLHMDMq","tg5wDKq","wwffDwq","z1LAtxu","AMvJDfn0B3i","quDYvLu","CMvZB2X2zq","D3PnD2e","Dfn4u0u","AMzLuw4","tgH2v1a","twPtrei","vuvurve","BuzOD2O","DxDfyuW","DeXxufe","EKLSB1m","AenSB3nLrxy","q09Xzge","yNL0zxm","D3m6lY8","ufzQBLC","ywDL","BMrWB2LUDfq","rgvKAwnHDgu","zMzMzG","Dg9hzw5LCMe","D25OrxC","Cur0vxa","nhWWFdeXFdm","Bvnuy04","DxPyD28","zvvYBa","q0XNzLa","DhLUywi","u05At2S","BvrrAe8","ywr2yw5Jzq","DeTVBeq","Bxbjz1a","sNDpz1a","tffyBM8","y2X1rhC","zxjFBxnNAwq","v0TXCKe","Duv2A2C","u1f5uLK","vvPwtge","zej0zw8","z2v0q3vYCMu","Dg9Y","rLv6zMq","BMfizey","DKjjvhK","Ae9oC28","ywXty29Wzq","EKXLuwi","vMfHq2K","mNWXFdr8mhW","AefJA01LC3m","x21PBMLoyxy","CxjAyM4","C0f6Ew8","igfYCMf5yNu","C3rVCMu","v2HTA2W","CMv0CNLdB3u","ywrKrxzLBNq","CMvJzwL2zwq","Dwr3uvi","tuPoAMW","Eurvsu8","ChHIB28","BMvLzf9Hy2S","y2HLy2Tszwe","m3WWFdv8nhW","zMvY","x3bPBMDmB3m","CK5JAgC","DfjlC0q","s0XUBeK","C2v0q3vYC28","x3bYB3rVy28","zMX1C2HfEha","x2TLEvbHDgG","B2LUDfjLywm","D1LOqNG","zfPMr1u","Dhj1y3rVCIa","zgvIDwC","zw50tgLZDgu","CYbPBNn0yw4","Bwu6ia","Cg9PBNrdB24","t1zlEeq","D3D4ChK","zwn0","sgXzDgu","BunqC2O","EMPrzvu","z05Arwq","BxzrB2y","rKLmrv9ot1q","Efrurw52","DgLTzw91DcW","AM9PBG","qLfVuMe","Eenxse8","ChjVy2vZCW","yxnJCMLWDa","vMDrwMC","tuLQD0q","qxbJA3y","zxj2AwnL","Bur0B2m","ChvZAa","CKz5A3C","rgvLugC","suvkDxm","ELjNCMW","zNjVBuj5Dgu","DeLK","AxnmB25N","rw1kDeK","DeDbAwO","D3zvCfe","zgf0yq","zxbZEuO","y2X0sLK","C2v0sxrLBq","y2XVC2veqG","C3rHCNq","wwTxrgS","x2rPC3bHDgm","ChjVDg90Exa","Cgu6ia","ihjLy29UBMu","y2XLyxjtDg8","y3jLyxrLrwW","y2XVC2uSihC","ELvKBuW","BNnvy1u","CMvTB3zLq2G","Cgjguva","Aw5L","Eg9xEw4","Cuvcs1i","AgfUz2u","x2nSzwfYvgK","wxDIC1e","DhPSseq","Fdn8mNW2FdG","Cgf5Bg9Hzfq","AeD2ue4","se95yvi","CMvWBgfJzui","BNnbrNa","CMLLC0nVDw4","DMfSDwu","BNrLCG","A01Pv24","C0Tmrxq","CM92AwrLihy","tg1Quhu","D0j4Dve","sgzQshu","sK1zCxK","D24GCMvHC28","ihrVihjLDhi","quXm","D0z3ANq","EMDduM8","uuLiChq","u3rwwMC","D2PSqxu","zM9YrwfJAa","yw51Ce1LC3m","B3nLza","BML0AwfSAxO","CLvLEK8","y2znBvi","whvZufm","ExzpvfC","CgDKtwW","x2LZqNjVD3m","x2LZsw5PDa","CMHtruC","y2rytLK","zw50zwqGDhK","yu5Jsu0","sg9Wtgm","u3n4tw0","AwXLtMfTzq","y29Uy2f0","BxnN","D2fZq2XLyw4","ndiXotm5A3nzAeTm","DKzcrgq","u01hDgS","AKvNvvi","B3bLCNr5tMe","uuXdELm","rMr5yuy","y29UBMvJDeu","DuvPEMG","yxrLq291BNq","zeThEwW","B0nyDu8","Aw9Ul2PZB24","Aw5KzxHpzG","zxmGCMvHy2G","v3DdrMy","z1bdswK","r2Tkt3G","rhbOq2q","DKPJwxa","mtm1uM9LuLzn"];return sa=function(){return t},sa()}function vS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let l=L,u={ytrrQ:function(g,w,S,y,v){return g(w,S,y,v)},UYcTn:function(g,w){return g(w)},woAPE:function(g,w){return g(w)},nZIMG:"close",nsUcU:l(1532)+l(1090),DoUgH:l(842)},f=indexedDB[l(655)](t,e),x=Bt(f);return i&&f[l(1225)+l(1389)](u[l(1299)],g=>{let w=l;u[w(1049)](i,u[w(172)](Bt,f[w(1627)]),g.oldVersion,g[w(1587)+"on"],u.woAPE(Bt,f[w(593)+w(588)]))}),r&&f["addEvent"+l(1389)](u.DoUgH,()=>r()),x[l(1496)](g=>{let w=l;c&&g.addEventListener(u.nZIMG,()=>c()),o&&g[w(1225)+"Listener"](w(223)+w(1305),()=>o())}).catch(()=>{}),x}function ne(t,e){t=t-147;let r=sa(),i=r[t];if(ne.QizJRe===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",w="";for(let S=0,y,v,I=0;v=f.charAt(I++);~v&&(y=S%4?y*64+v:v,S++%4)?g+=String.fromCharCode(255&y>>(-2*S&6)):0)v=x.indexOf(v);for(let S=0,y=g.length;S<y;S++)w+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(w)};ne.sSXlSy=o,ne.cKkElg={},ne.QizJRe=!0}let c=r[0],l=t+c,u=ne.cKkElg[l];return u?i=u:(i=ne.sSXlSy(i),ne.cKkElg[l]=i),i}function SS(t,{blocked:e}={}){let r=L,i={JwSjJ:function(c,l){return c(l)}},o=indexedDB[r(800)+"tabase"](t);return e&&o[r(1225)+r(1389)]("blocked",()=>e()),i[r(603)](Bt,o)[r(1496)](()=>{})}function Hx(t,e){let r=L,i={DTqVu:"blocked",DSQUu:function(f,x){return f(x)},kaZTZ:function(f,x){return f!==x},XnCnD:r(371),uTDBY:r(1156)+"e",QUHaX:r(229),TDsRC:function(f,x){return f instanceof x},VFSck:function(f,x){return f in x},UmFdA:function(f,x){return f===x},Sdvyy:r(589)};if(!(i[r(1476)](t,IDBDatabase)&&!i[r(781)](e,t)&&i[r(625)](typeof e,i.Sdvyy)))return;if(ta[r(873)](e))return ta.get(e);let o=e[r(533)](/FromIndex$/,""),c=e!==o,l=Vx[r(983)](o);if(!i[r(781)](o,(c?IDBIndex:IDBObjectStore).prototype)||!(l||$x[r(983)](o)))return;let u=async function(f,...x){let g=r,w={idWNP:i[g(1505)],qzaCL:function(S,y){return i[g(312)](S,y)}};if(i.kaZTZ(i[g(1503)],i[g(1503)])){let S=_0x40de3a[g(800)+g(1009)](_0x19991e);return _0x46b07b&&S["addEvent"+g(1389)](ntSkIx.idWNP,()=>_0x3c9fe5()),ntSkIx[g(507)](_0x5d8362,S)[g(1496)](()=>{})}else{let S=this[g(593)+g(588)](f,l?i.uTDBY:i[g(1426)]),y=S[g(1222)];return c&&(y=y[g(293)](x.shift())),(await Promise.all([y[o](...x),l&&S[g(419)]]))[0]}};return ta[r(1041)](e,u),u}var $x,Vx,ta,IS=qx({"node_modules/idb/build/index.js"(){let t=L,e={bjFMV:t(980)+"1|4",ZPlSF:t(1563),PMUMx:"add",gWWTq:t(672),zeObd:t(873),gaLTe:"getKey",UyBwO:t(825)+"ys",tfWtV:t(539),kQySo:function(o,c){return o(c)},aauQe:function(o){return o()}},r=e[t(357)].split("|"),i=0;for(;;){switch(r[i++]){case"0":Vx=[e.ZPlSF,e[t(651)],e[t(1455)],t(1477)];continue;case"1":ta=new Map;continue;case"2":$x=[e[t(1143)],e.gaLTe,t(577),e[t(1092)],e.tfWtV];continue;case"3":Gx();continue;case"4":e.kQySo(yS,o=>({...o,get:(c,l,u)=>Hx(c,l)||o[t(873)](c,l,u),has:(c,l)=>!!Hx(c,l)||o.has(c,l)}));continue;case"5":e.aauQe(Gx);continue}break}}}),AS={idb:function(t){let e=L;t.exports=Promise[e(1164)]()[e(1496)](()=>(IS(),Kx))[e(1496)](function(r){return r})}},jx={};function Mt(t){let e=L,r={GrmSM:e(474)+"1",WvQKY:function(u,f){return u!==f}},i=r[e(1655)][e(1438)]("|"),o=0;for(;;){switch(i[o++]){case"0":var c=jx[t];continue;case"1":return l.exports;case"2":var l=jx[t]={exports:{}};continue;case"3":if(r[e(272)](void 0,c))return c[e(608)];continue;case"4":AS[t](l,l[e(608)],Mt);continue}break}}(()=>{let t=L,e={GwwPg:function(r,i){return r|i},VWnAV:function(r,i){return r&i},fiLjT:function(r,i){return r<<i},aWNaA:function(r,i){return r<i},wntXH:function(r,i){return r>i},uWbMM:function(r,i,o){return r(i,o)},ESubY:function(r,i){return r+i},PEuLN:t(1339)};Mt.d=(r,i)=>{let o=t,c={NhrqQ:function(u,f){return u|f},NqVEF:function(u,f){return e[ne(635)](u,f)},JlcCl:function(u,f){return u<<f},FGbyA:function(u,f){return e[ne(1378)](u,f)},EXwyE:function(u,f){return e[ne(683)](u,f)},dVfyj:function(u,f){return e.aWNaA(u,f)},TyEwg:function(u,f){return e[ne(887)](u,f)},ShiOJ:function(u,f,x){return e.uWbMM(u,f,x)},OoyBI:function(u,f){return e[ne(420)](u,f)}};if(o(1339)===e.PEuLN)for(var l in i)Mt.o(i,l)&&!Mt.o(r,l)&&Object[o(1117)+o(1030)](r,l,{enumerable:!0,get:i[l]});else _0x4cb033=c[o(188)](c[o(484)](c[o(695)](c[o(1386)](7,_0x5a7afe),18),c[o(335)](c[o(1386)](63,_0x2d7730),12)),c[o(335)](c[o(1386)](63,_0x219a02),6))|63&_0x5e6a81,c[o(776)](_0x16544a,65536)||c.TyEwg(_0x1ea76e,1114111)?_0x3c7b25+=_0xc60345:(_0x3e038c-=65536,_0x8bcc34+=c[o(225)](_0x23cc19,c[o(190)](_0x3f5778>>10,55296),(1023&_0x44fffd)+56320),_0x12dfce+=3)}})(),(()=>{let t=L;Mt.o=(e,r)=>Object.prototype[t(1136)+t(1030)][t(725)](e,r)})(),(()=>{let t=L,e={thjza:t(946)+"d",cbkDx:"__esModule"};Mt.r=r=>{let i=t;e.thjza!=typeof Symbol&&Symbol[i(514)+i(1104)]&&Object[i(1117)+i(1030)](r,Symbol["toString"+i(1104)],{value:i(1434)}),Object[i(1117)+"operty"](r,e[i(1509)],{value:!0})}})();var De={};(()=>{let t=L,e={kMiWn:function(a,n){return a(n)},FUzfd:function(a,n){return a+n},Xdtul:function(a,n){return a+n},iJJHK:function(a,n){return a*n},wjlAu:function(a,n){return a*n},ECivY:function(a,n,s){return a(n,s)},hONso:function(a,n){return a+n},IvfCG:function(a,n){return a(n)},QNUKu:function(a,n){return a+n},pOFbn:function(a,n){return a(n)},hfUEu:function(a,n){return a+n},xxngt:t(1109),StVZg:t(1183),cOEKD:function(a,n){return a===n},YbUIu:function(a,n){return a>>>n},BNmSH:function(a,n){return a|n},jsAza:function(a,n){return a<<n},tSxSE:function(a,n){return a|n},jtDNZ:function(a,n){return a|n},RKQpH:function(a,n){return a|n},bRwaf:function(a,n){return a(n)},IYyiA:t(788)+t(788)+t(788)+t(788),aybDH:function(a,n){return a>>n},EVBLa:function(a,n){return a==n},JMYqy:function(a,n){return a>n},ghmVg:function(a,n){return a>n},ZVLcD:function(a,n){return a===n},egmWE:t(280),EVBqr:"jbCZH",svbGF:function(a,n){return a<n},NgTOA:function(a,n){return a<n},nVYmB:function(a,n){return a!==n},kiwLe:function(a,n){return a===n},EGTeF:t(498),Yvtfy:function(a,n){return a-n},wmzcZ:function(a,n){return a!==n},ikaDr:"auaWj",EyCII:function(a,n){return a-n},AQAAW:function(a,n){return a<n},Hgrdx:function(a,n){return a<n},spEVu:t(220),UETEQ:t(1551),HfjHu:t(179),gWfco:function(a,n,s){return a(n,s)},VYlEQ:function(a,n,s){return a(n,s)},UMftH:function(a,n){return a!==n},ULkue:function(a,n,s){return a(n,s)},qjgzu:function(a,n){return a&n},mDtoc:function(a,n){return a<<n},BIWQI:function(a,n){return a&n},jxBjU:function(a,n){return a&n},qxZUg:function(a,n){return a&n},WlTCD:function(a,n){return a<<n},EtyoQ:function(a,n){return a&n},HlYte:t(614),EAxLJ:function(a,n){return a(n)},cmraF:function(a,n){return a(n)},wDNRa:function(a,n){return a(n)},hCGOv:function(a,n){return a(n)},bACvu:function(a,n,s){return a(n,s)},JwOgP:function(a,n){return a===n},yvOTW:"Missing "+t(1571)+t(1567)+t(1316),WBURg:function(a,n){return a===n},PSRCI:t(949),rJbfB:t(724),OjTtJ:function(a,n,s){return a(n,s)},xCWHO:function(a,n,s){return a(n,s)},sJGrG:"qos",mzPlE:t(511)+"id",uuRcX:t(1256),MjmRC:t(1446),cgJaG:function(a,n){return a===n},PpvnJ:t(567),JaJXi:function(a,n,s){return a(n,s)},fSBFo:function(a,n,s){return a(n,s)},SAewW:function(a,n){return a(n)},nsBgb:t(1517),AXrFs:function(a,n){return a!==n},QFtsl:function(a){return a()},PMMIe:function(a,n,s){return a(n,s)},KsCzE:function(a,n,s){return a(n,s)},YwbsQ:function(a,n,s){return a(n,s)},avrLu:function(a,n,s){return a(n,s)},IEJus:function(a,n){return a!==n},rxDFz:function(a,n,s){return a(n,s)},KPHia:function(a,n){return a!==n},tkmTa:function(a,n,s){return a(n,s)},tLree:function(a,n){return a!==n},GkJOx:function(a,n,s){return a(n,s)},PltXj:function(a,n){return a(n)},yRKHf:t(571)+"1",cluDw:function(a,n){return a+n},zViif:function(a,n){return a+n},RLFTz:function(a,n,s,d){return a(n,s,d)},bWfPW:function(a,n){return a!==n},obpUQ:t(350),Vztso:t(1474),YRPsT:function(a,n){return a(n)},ZXZPn:t(464),TCuNQ:function(a,n){return a(n)},wzMwa:function(a,n,s){return a(n,s)},wYhBx:function(a,n){return a(n)},PdHwL:function(a,n,s){return a(n,s)},rCAbN:function(a,n,s){return a(n,s)},AlQiw:function(a,n,s){return a(n,s)},NAdHi:function(a,n,s){return a(n,s)},ygOei:function(a,n){return a(n)},zpIPN:function(a,n,s){return a(n,s)},OhfKm:function(a,n){return a&n},hSpGd:t(601)+"required"+t(1567)+t(1124),bvNzw:function(a,n){return a===n},KEsxW:t(601)+t(1571)+t(1567)+t(438),DlvfX:function(a,n){return a===n},MlKAq:t(601)+t(1571)+t(1567)+t(622),crfiI:t(601)+t(1571)+" field: "+t(559),wnhEw:function(a,n){return a&n},figlh:function(a,n,s){return a(n,s)},mFhwj:t(678)+t(1346)+t(1293),FGGIP:t(492),mBUuB:function(a,n){return a>=n},bxvGH:function(a,n){return a+n},GtBfF:function(a,n){return a|n},NHiEJ:function(a,n){return a<<n},GZBLK:function(a,n){return a&n},YaEud:function(a,n){return a!==n},tGAij:t(548),uznXx:"BrBGx",vaKst:"ZHtDG",jIEyl:"Skip pas"+t(177),mhfWQ:function(a,n){return a>=n},NqBYW:function(a,n){return a>n},tRKsD:function(a,n){return a+n},BmuFn:t(703)+t(177),MWcLG:function(a,n){return a+n},Alyhu:t(709),xJrQj:t(1608),PPTCh:function(a,n,s){return a(n,s)},bHVwz:function(a,n){return a+n},OXzyD:function(a,n){return a===n},qCvSG:function(a,n){return a&n},ARuFn:function(a,n){return a(n)},uGCSe:function(a,n){return a===n},TzKcr:function(a,n){return a!==n},ESHIc:function(a,n){return a|n},GhpCf:function(a,n){return a<<n},ytDds:function(a,n){return a+n},bcdzC:function(a,n){return a!==n},dYzwm:function(a,n){return a&n},qYkQD:function(a,n){return a|n},cKlkj:function(a,n){return a|n},GLRZD:function(a,n){return a&n},YTwzm:function(a,n){return a<<n},cJLcr:function(a,n){return a<n},BKumy:function(a,n){return a(n)},FQFnS:function(a,n){return a==n},hRVcT:function(a,n){return a>=n},pOFrp:function(a,n){return a+n},TFcRU:function(a,n){return a+n},bSPDl:function(a,n){return a&n},OdexW:function(a,n){return a|n},PVjnW:function(a,n){return a<<n},tOlMy:function(a,n){return a|n},fzVpY:function(a,n){return a&n},Cafod:function(a,n){return a<<n},Fgeve:function(a,n){return a>>n},njuxw:function(a,n){return a+n},aztrC:t(1081),NSMLm:function(a,n,s){return a(n,s)},JFzmZ:function(a,n){return a<=n},hBEUk:function(a,n){return a<n},hLdCB:function(a,n){return a-n},DAdGb:function(a,n){return a+n},bYZtf:function(a,n){return a<<n},oRkgC:function(a,n){return a<n},PGMMp:function(a,n,s){return a(n,s)},tynab:function(a,n){return a<n},nsAFp:function(a,n){return a<n},OEvub:function(a,n){return a===n},KzvXG:t(1638),vJcYp:t(1611),mjPKW:function(a,n){return a<n},mdBbN:function(a,n){return a&n},wEyIq:function(a,n){return a!==n},XCFTu:t(1424),XKzsS:function(a,n){return a&n},mSTcN:function(a,n){return a>>n},cyiTB:function(a,n){return a&n},JaCdV:function(a,n,s){return a(n,s)},UcbNE:function(a,n){return a<n},QyyoG:function(a,n){return a+n},OdDZP:function(a,n){return a&n},vMHXC:function(a,n){return a>=n},VkZbW:function(a,n){return a===n},nEAaJ:t(1191),SpRaW:t(954),ZoTYf:function(a,n,s){return a(n,s)},aRdNn:function(a,n){return a&n},qmSUh:function(a,n,s){return a(n,s)},MAiwX:function(a,n,s){return a(n,s)},SMGtk:function(a,n){return a&n},Gygjm:function(a,n){return a&n},xFnbL:function(a,n){return a&n},ObsLz:t(1046),jgkZl:t(1012),Xrplq:function(a,n){return a(n)},yvqTY:function(a,n){return a&n},WKbli:function(a,n){return a<<n},slDFg:function(a,n){return a&n},gPkPf:function(a,n){return a!==n},OpPBV:function(a,n){return a<<n},kRPPn:function(a,n){return a(n)},HyAuF:function(a,n){return a&n},lOSQN:function(a,n){return a&n},xgePq:function(a,n){return a<<n},SBSdT:function(a,n){return a&n},THZCT:function(a,n){return a|n},Whmkl:function(a,n){return a>>>n},cfMmR:function(a,n){return a>>>n},lqraF:function(a,n){return a<<n},HwOlS:function(a,n){return a>>>n},HOyaR:function(a,n){return a<n},Jrabk:function(a,n){return a<n},ZJXDh:function(a,n){return a<n},qiBWu:function(a,n,s){return a(n,s)},XCdYM:function(a,n){return a&n},EvhLw:function(a,n){return a>>>n},rNNWD:function(a,n){return a&n},LOhpW:function(a,n){return a!==n},qPDoY:function(a,n){return a|n},WTHIw:function(a,n){return a|n},hTGCV:function(a,n){return a&n},AwmVi:function(a,n){return a>>>n},zQGRj:function(a,n){return a!==n},Rvomv:function(a,n){return a!==n},GQOWE:function(a,n){return a>>>n},VxjIo:function(a,n){return a>>>n},azyWe:function(a,n){return a|n},diyos:function(a,n){return a>>>n},jGMmF:function(a,n){return a&n},GLLcN:function(a,n){return a|n},mKIbr:function(a,n){return a===n},KCKWR:function(a,n){return a|n},ndHRx:function(a,n){return a<<n},XREnS:function(a,n){return a|n},zaTKW:function(a,n){return a|n},mIsEQ:function(a,n){return a|n},nSfSK:function(a,n){return a===n},tvCZd:function(a,n){return a>>>n},UJtet:function(a,n){return a|n},WIqMY:function(a,n){return a|n},jRavv:function(a,n){return a<<n},mUrlW:function(a,n){return a<<n},APLUp:function(a,n){return a|n},lnOlT:t(496),tEaHe:function(a,n){return a&n},iboGA:function(a,n){return a instanceof n},ugLlL:t(161)+"ion/json",gmEFJ:t(233),pxboo:t(373),NXDPu:function(a,n){return a>=n},AwrfU:function(a,n){return a%n},gOvIV:function(a,n){return a|n},zjfQx:function(a,n){return a/n},faPoh:function(a,n){return a+n},oGpmX:function(a,n){return a+n},XUiyF:t(888),alBFO:function(a,n){return a>>>n},CFJqg:function(a,n){return a>>>n},IIHDy:function(a,n){return a&n},KbXgB:function(a,n){return a>>>n},lJwFx:function(a,n){return a>>>n},ZiFpM:function(a,n){return a+n},taNRn:function(a,n){return a+n},OeyUp:function(a,n){return a<<n},ysqsn:function(a,n){return a<<n},CvOvP:function(a,n){return a===n},TgwZO:function(a,n){return a+n},WKqrA:function(a,n){return a&n},nlSED:function(a,n){return a&n},MfWpK:function(a,n){return a&n},Nhbij:function(a,n){return a&n},cxOZO:function(a,n){return a&n},LhvWP:function(a,n){return a>>>n},iIjXT:function(a,n){return a>>>n},KWHTw:function(a,n){return a&n},ohpxm:function(a,n){return a&n},YNABe:"MESSAGE_"+t(1057),euLrA:"NATIVE_E"+t(719),xQSPq:t(676)+"OR",YEgiy:"MAX_RETRIES_ERROR",ScZUM:t(1084)+t(739),fplNe:function(a,n){return a&n},IpRdZ:function(a,n){return a&n},dCbhk:t(1435),mvQof:t(1362),qeaiv:t(1569)+t(814)+"|5|10|4|2",LrEoK:function(a,n){return a<n},cOJLL:function(a,n){return a>>>n},wDYzH:function(a,n){return a<n},zvWuI:function(a,n){return a|n},MwaoK:t(500),PAsOs:function(a,n){return a>=n},LMcCe:function(a,n){return a===n},luJGT:function(a,n){return a===n},FYASh:function(a,n){return a>n},Zaslp:function(a,n){return a===n},qDtUp:function(a,n){return a+n},slPJG:t(655),BiPFH:t(1645),mpRUe:function(a,n,s){return a(n,s)},vHmfe:function(a,n,s){return a(n,s)},dlBQx:function(a,n){return a|n},TPsLR:t(1568),ijbhJ:function(a,n){return a+n},BbJot:t(417),HExsQ:"gpZNg",SyGdB:function(a,n){return a||n},yqeGE:function(a,n){return a!=n},gPCIi:"undefined",EeCVj:t(365)+"3",LopiR:function(a,n){return a(n)},JIBvD:function(a,n){return a(n)},WGxyB:t(1019),sgGLE:function(a,n){return a<=n},JGjGz:"next() called mu"+t(374)+t(306)+t(1266),eYnAw:function(a,n){return a===n},MSZvr:function(a,n){return a(n)},WViVK:function(a,n){return a<<n},agOKo:function(a,n){return a&n},nFWwK:function(a,n){return a<<n},Bxwip:function(a,n){return a&n},mMKHz:function(a,n){return a>>n},TFqPN:function(a,n){return a===n},rMvAX:function(a,n){return a===n},TrkTP:t(192),oRGjh:t(840),tufdS:function(a,n){return a===n},jqAqu:t(150),MiNRa:t(1145),uGDtT:function(a,n){return a<n},ZJdiY:function(a,n){return a-n},Rkido:function(a,n){return a<n},eAOVo:function(a,n){return a>=n},iOHGO:function(a,n){return a<n},jOMnY:function(a,n){return a&n},VenVH:function(a,n){return a&n},QKPAO:function(a,n){return a<<n},TUgTJ:function(a,n){return a|n},FgvSr:function(a,n){return a|n},QIcRE:function(a,n){return a|n},CVMLU:function(a,n){return a&n},RGtOw:function(a,n){return a===n},dZfGU:t(1233)+t(777),TYljF:function(a,n){return a|n},SJYDg:function(a,n){return a&n},htXqM:function(a,n){return a>>n},FVZNz:function(a,n){return a+n},RNcjJ:function(a,n){return a>>n},bSJXC:function(a,n){return a|n},VrONy:function(a,n){return a>>n},vKMWG:function(a,n){return a&n},xwmWl:function(a,n){return a|n},fnBFC:function(a,n){return a-n},qLPTQ:"string",jNcmf:function(a,n){return a instanceof n},NJPgl:function(a,n){return a!=n},FrNMZ:function(a,n){return a instanceof n},wvUpQ:function(a,n){return a!=n},zBwOq:function(a,n){return a==n},MDhpN:t(1344),dQFeC:t(1381),Pjngp:t(441),VOWBY:function(a,n){return a(n)},ICCgI:function(a,n){return a+n},fSTTA:function(a,n){return a+n},kJsIl:t(1396),LPJQv:function(a,n){return a!=n},zkbLK:t(1434),LtRdk:t(1478)+"le",vCMFI:t(254),DoSJM:function(a,n){return a(n)},VHIYx:t(309)+t(296),WqVoD:t(953),olZpm:t(1005),QGiLs:t(419),HoeBn:function(a,n){return a===n},DvPBg:t(715)+t(308),wCGOS:function(a,n){return a===n},jxOkN:t(1222),MTOSr:function(a,n){return a!==n},MUpmm:t(1572),mxpYM:function(a,n){return a>=n},xpHYB:function(a,n){return a/n},BGvBO:function(a,n){return a===n},FdyaF:"QADSu",nGasd:t(1140),nCprQ:function(a,n){return a>n},EAwLN:function(a,n){return a+n},FtflK:function(a,n){return a>>n},VdaUu:function(a,n){return a|n},syjvl:function(a,n){return a&n},QhJKD:function(a,n){return a&n},uRIAQ:function(a,n){return a+n},UTlXR:function(a,n){return a|n},LBAlQ:function(a,n){return a&n},iVSzt:function(a,n){return a|n},eqzZe:function(a,n){return a&n},NkdMd:function(a,n){return a&n},LWLWg:function(a,n){return a!==n},FgNwb:"dCEse",AUAZX:t(379),JBfEj:function(a,n){return a(n)},lBNxr:t(752)+"or",wLhUm:"iyrZr",NIBCY:function(a,n){return a+n},pgKOk:function(a,n){return a+n},HDsVv:function(a,n){return a+n},pgdMl:function(a,n){return a&n},zgCRo:function(a,n){return a&n},pdpNr:function(a,n){return a>n},IigTq:function(a,n){return a+n},KFrTF:function(a,n){return a+n},OVKxD:"UFZlt",UwIEG:t(1154),eJqyl:function(a,n){return a||n},Dlncr:t(1044)+t(510)+"d",epsyJ:t(904)+t(1036),qAdDy:t(1297)+t(1249)+t(1468)+t(1336)+"ed",TLwCc:t(1297)+"s alread"+t(1502),zAZMk:"bUTrZ",ZGdjt:"fBJWd",BvHHO:t(950),wKoMn:function(a,n){return a+n},WvANy:function(a,n,s){return a(n,s)},TtypS:function(a,n){return a!==n},znhwO:"GlQVH",MYFaY:function(a,n){return a!==n},YxKVK:"WBFsj",LmjPu:t(704),GwIel:"nPEVV",LAXKx:function(a,n){return a===n},tzlHD:t(894),FKWUH:function(a,n,s,d){return a(n,s,d)},JRmRW:t(1130)+t(1133),COqda:function(a,n,s,d){return a(n,s,d)},WDKtt:t(1130)+"er_is_ack",HVZSw:function(a,n,s){return a(n,s)},GnABH:function(a,n,s,d){return a(n,s,d)},ESbFB:"is_ack",hoUjJ:function(a,n){return a&&n},hoFKU:t(251),tKolD:function(a,n){return a||n},BQoRa:"ack_code",XiyqK:function(a){return a()},lNkaW:t(1226),djSEc:function(a,n){return a(n)},OiaDR:function(a,n){return a instanceof n},WhWiM:function(a,n){return a instanceof n},MZfJz:"text/pla"+t(176)+"et=utf-8",zLeQb:t(161)+t(1366)+t(1614)+t(636),fLCDt:t(627)+"e",crTiJ:"binary",XMPHb:function(a,n,s,d){return a(n,s,d)},bsShi:function(a,n){return a!==n},vAcSL:t(832),XGzOV:function(a,n){return a>n},GZwez:function(a,n){return a>n},NFHAw:function(a,n){return a(n)},KpnhW:function(a,n){return a||n},gpdGj:function(a,n){return a>>>n},ShlQU:function(a,n){return a(n)},pzssb:function(a,n){return a+n},gXlhD:function(a,n){return a+n},TJIOk:t(160)+t(1050)+"ge: ",wkQzp:t(845),rQEPW:t(827),IEQTj:function(a,n){return a>n},IDIll:function(a,n){return a+n},NdZXa:function(a,n,s){return a(n,s)},uzXwo:function(a,n){return a>>>n},DbCSi:t(208)+"1",PwVhN:function(a,n){return a+n},etmLU:function(a,n,s,d){return a(n,s,d)},zFZNl:function(a,n){return a<n},suteK:function(a,n){return a+n},lWjZG:function(a,n,s,d){return a(n,s,d)},YeJpw:function(a,n){return a+n},fyjar:function(a,n){return a|n},SLrxy:function(a,n){return a<<n},MFNnq:function(a,n){return a<<n},fyeCi:function(a,n){return a+n},WPXwQ:function(a,n){return a|n},ODYfP:function(a,n){return a+n},vObqO:function(a,n){return a<<n},WwCFf:function(a,n){return a&n},levdi:function(a,n){return a&n},dXuNw:function(a,n){return a>>>n},FscuM:function(a,n){return a+n},fRTuV:function(a,n){return a>>>n},qMtLm:function(a,n){return a&n},twUiv:function(a,n){return a&n},MIjwD:function(a,n){return a+n},sKZcO:function(a,n){return a&n},Xwwlm:t(158)+t(592)+t(473)+"1",DxoZm:function(a,n){return a|n},diFzF:function(a,n){return a<<n},qkikQ:function(a,n){return a>>>n},DiopA:function(a,n){return a<<n},BmBWM:function(a,n){return a|n},SlSEu:function(a,n){return a|n},FGhQv:function(a,n){return a&n},hpVpX:function(a,n){return a|n},VgQZg:function(a,n){return a<<n},wBxuQ:function(a,n){return a|n},yyIlM:t(368),KmZuI:t(732)+t(1309)+t(973),ksmpk:t(622),yCkxP:t(422),SOcAq:"cursor.s"+t(1271),zjQeU:"cursor_file_name",XpBLh:t(505),GiCOs:t(1274),wlHmi:function(a,n,s){return a(n,s)},VKvKf:function(a,n,s){return a(n,s)},Lqyjr:function(a,n,s,d){return a(n,s,d)},rgaFg:t(1260)+t(508),MjSDB:t(1262)+t(1388)+"onnecting",RlFzo:t(1125),RPuxR:"xsSPS",dwpuw:t(1327),hwJZT:t(1420),LnVvD:t(1037),lEcJP:function(a,n,s,d){return a(n,s,d)},uEvkg:function(a,n){return a===n},yzZMk:"datWa",KuYgS:function(a,n){return a!==n},TsWhs:"nSTos",MOvBB:function(a,n){return a||n},uFBMI:"TjSiy",sVRVo:"code",gYZMu:t(1130)+t(1201),xTurG:function(a,n){return a(n)},YiXEF:t(1130)+t(982),HrXev:function(a,n,s,d){return a(n,s,d)},SsxMm:t(415)+"s",WsIkR:t(864)+"rsor_name",qNCTk:function(a,n){return a(n)},YkWDk:function(a){return a()},FitIi:function(a,n){return a>n},igcwe:function(a,n){return a+n},rUezO:function(a){return a()},udwQR:function(a,n){return a===n},GqctZ:function(a,n){return a===n},PsKcr:function(a){return a()},OnlGw:function(a,n,s){return a(n,s)},IrWQd:function(a){return a()},exjBE:function(a,n){return a!==n},dMhip:function(a){return a()},jZoBZ:function(a,n){return a!==n},fzayh:function(a,n){return a!==n},KHGeS:function(a,n){return a-n},NJmRm:"sBRlp",RhoqE:function(a,n,s){return a(n,s)},tLWPQ:function(a,n,s){return a(n,s)},HQPyK:t(798),OgvEk:function(a,n,s,d){return a(n,s,d)},JiLUM:function(a,n,s){return a(n,s)},sKLEt:function(a,n){return a(n)},jQkka:t(183),qrEwE:"auto",QpBXB:t(164)+"e_success",mpIgP:function(a,n){return a!==n},Xbake:"QyNJS",NZtGm:"XWBaX",QLCzS:function(a,n,s){return a(n,s)},dFdPK:function(a,n){return a!==n},ZlFLm:t(1205),OUXsu:function(a,n,s){return a(n,s)},CctJj:"pbbp2",zRgrl:function(a,n){return a==n},QErmz:function(a,n){return a===n},fgYjK:t(893)+t(1320)+"alid url",UCjuJ:function(a,n,s){return a(n,s)},Yjmcq:function(a,n,s,d){return a(n,s,d)},DxJsk:function(a,n,s){return a(n,s)},plvRz:function(a,n){return a===n},HopLc:t(572),tZzRh:t(1064),sDOds:t(1565),qWftl:"pageshow",Xakas:t(1281),aNcIM:t(1058),yLfeF:t(387),wNrbK:t(313),YHFQI:t(1070),RvCQD:"ttwid",AGrVU:t(893)+t(173)+"ddID, deviceID o"+t(841),QIHpt:t(1625),bgTxJ:t(1470)+t(1187)+"|5|9|10|7",xkicR:function(a,n){return a|n},glNHC:function(a,n){return a&n},VxiaX:function(a,n){return a>>>n},UaXVu:function(a,n){return a<<n},bRgDd:function(a,n){return a&n},CHReY:function(a,n){return a|n},xlEoo:function(a,n){return a&n},Csuwc:function(a,n){return a|n},Cmjcr:function(a,n){return a<n},DsRvt:function(a,n){return a<<n},XSNaE:function(a,n){return a&n},nYEIj:function(a,n){return a===n},ypTsI:t(705),vPzMc:t(412),yFHcu:function(a,n,s){return a(n,s)},EAxGL:function(a,n){return a!==n},RyQXJ:function(a,n,s){return a(n,s)},LZnqx:function(a,n,s){return a(n,s)},Csdpk:t(1547)+"t",tUFOZ:t(1289),axdpB:function(a,n){return a===n},CefJg:function(a,n,s){return a(n,s)},dMoQT:t(164)+t(1646)+"t",gGzZD:t(960),TwShg:function(a,n){return a|n},MdpSS:function(a,n){return a|n},eOcwB:function(a,n){return a|n},HONbx:function(a,n){return a<<n},GBIAW:t(993),mjIFi:t(433),zscVK:t(504)+t(1566)+t(1547)+t(595)+t(1419),kpugC:function(a,n,s){return a(n,s)},iCkWx:t(964),EOQVs:function(a,n){return a(n)},PIBYg:t(1394),YkaQE:t(935),UVGAP:function(a,n,s){return a(n,s)},UpYKu:function(a,n,s){return a(n,s)},rusRR:function(a,n){return a===n},hAmzM:t(564),uFbVV:t(323),QrJyP:t(1408),hdSHw:function(a,n){return a!==n},PbAoJ:t(1236),khuZG:function(a,n,s,d){return a(n,s,d)},AIHaD:t(1231),Wdqzk:function(a,n,s,d){return a(n,s,d)},nOylA:function(a){return a()},VjEMH:t(405),dBteo:"NGMbl",lIXmH:function(a,n){return a===n},hxwvH:"FSCbq",cdXNY:function(a,n){return a==n},REiaw:t(893)+"rovide a"+t(524)+t(1147)+t(607)+t(332)+"ng or an"+t(1221)+t(793),bqnob:"please provide a valid s"+t(1271),OVIEc:function(a,n){return a instanceof n},DxxbY:function(a,n){return a===n},uBGMX:t(198),XojFy:t(859),TQbay:function(a,n){return a||n},uGSSU:t(990)+t(1074)+t(1576),gIfZL:function(a,n){return a!==n},klWLQ:t(1439),VyJFx:"kRByU",PuLUl:function(a,n){return a===n},ceBpl:t(623),MNOzn:t(925),JfxWt:function(a,n){return a===n},PMwGj:function(a,n){return a!=n},YKTLZ:function(a,n){return a!=n},PyFqN:"Dedicate"+t(1047)+t(587)+"pe",jeFAd:"SharedWo"+t(348)+t(1213),zJsLh:function(a,n){return a===n},lONFJ:t(322)+t(319)+"balScope",tRWJZ:function(a,n){return a!=n},iykah:function(a,n){return a!=n},RMqJu:function(a,n){return a!=n}};Mt.r(De),Mt.d(De,{FWS:()=>Og,CustomErrorEvent:()=>ul,createCloseEvent:()=>mt,ReconnectEvent:()=>ll,createErrorEvent:()=>at,decodedFrame:()=>sn,createOpenEvent:()=>ml,CustomCloseEvent:()=>fl,createReconnectEvent:()=>Ea,FrontierMessageEvent:()=>xl,encodeFrame:()=>zt,createMessageEvent:()=>gl,OpenEvent:()=>pl,ErrorCode:()=>an,Event:()=>ir,MessageEvent:()=>hl});let r="";function i(a=""){let n=t,s="02",d=""+Date[n(154)](),h=r||(r=e.kMiWn(f,a)),p=Math[n(437)]()[n(514)](16)[n(1039)](-6);return e[n(1209)](e[n(1448)](e[n(1209)](s,d),h),p)}function o(){let a=t;return e[a(816)](1e4,Date[a(154)]())+Math[a(197)](e[a(1332)](1e4,Math[a(437)]()))}function c(a){let n=t;return e[n(1209)](Array(8)[n(1263)]("0"),e[n(680)](parseInt,a,10)[n(514)](2))[n(1039)](-8)}function l(a){let n=t;return e.hONso(e.IvfCG(Array,4).join("0"),parseInt(a,2)[n(514)](16)).slice(-4)}function u(a){let n=t,s=a.split(/\./).map(p=>c(p)),d=[];return d[0]=e.IvfCG(l,e[n(819)](s[0],s[1])),d[1]=e[n(767)](l,e[n(411)](s[2],s[3])),[e[n(199)],e.xxngt,e[n(199)],e.xxngt,e.xxngt,e[n(1331)],d[0],d[1]][n(1263)]("")}function f(a){let n=t;if(e[n(389)]("mzCFy",n(671)))return e[n(389)](_0xdcf804,_0x355da4)?_0x53c3dd:new _0x4118ee(e[n(558)](e[n(1128)](e[n(1128)](e[n(1128)](_0xb1e2d7[n(725)](_0x47dbde,0),e[n(861)](_0x63af15[n(725)](_0x4a5bb5,1),8)),e[n(861)](_0x162a58[n(725)](_0x5e00ca,2),16)),_0x58db10[n(725)](_0x41f0e5,3)<<24),0),e[n(558)](e.tSxSE(e[n(931)](e[n(1623)](_0x4f3074[n(725)](_0x2dfb91,4),_0x8ce752[n(725)](_0x8a2c7d,5)<<8),e[n(861)](_0x1aaaab[n(725)](_0x2570d4,6),16)),e[n(861)](_0x4fc834[n(725)](_0x1f6fb6,7),24)),0),!0);{let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1543)](a),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(1543)](a);return s?e.kMiWn(u,a):d?e[n(818)](x,a):e.IYyiA}}function x(a){let n=t,s={FXmiR:function(k,N){return e[ne(1100)](k,N)},YExMG:function(k,N){return e.EVBLa(k,N)},swwHQ:function(k,N){return e[ne(1324)](k,N)}},d="",h=[],p=0,E=0,_=!0,m=e[n(199)];if(e[n(367)](a[n(1367)]("::"),-1)){if(e[n(962)](e[n(1610)],e.EVBqr))return _0x31a188|=0,{low:_0x2b89db,high:s[n(471)](_0x11e0ba,31),unsigned:_0x351b8b>=0};{let k=a[n(1438)]("::");for(let M=0;e.svbGF(M,k[n(1391)]);M++){let K=k[M];if(e[n(1324)](K[n(1367)](":"),0)){let W=K.split(":");_&&(p=W[n(1391)]),E+=W[n(1391)];for(let he=0;e[n(221)](he,W.length);he++)if(e.nVYmB(4,W[he][n(1391)]))if(e.kiwLe(e[n(908)],e[n(908)])){let wt=m.substring(0,e[n(203)](4,W[he][n(1391)])),Ut=wt.concat(W[he]);h[n(1273)](Ut)}else return s[n(243)](this["currentI"+n(729)],this[n(1404)+"s"][n(1391)])?!0:s[n(228)](this[n(1e3)+n(1181)+"riesCount"],this[n(1510)+"es"]);else h.push(W[he]);_=!1}else{if(e[n(1010)](4,K[n(1391)]))if(e[n(318)](n(718),e[n(972)])){let W=m[n(426)+"g"](0,e.EyCII(4,K[n(1391)])),he=W[n(1351)](K);h[n(1273)](he)}else return 0;else h.push(K);_&&(p+=1),E+=1,_=!1}}let N="";for(let M=0;e[n(1442)](M,e[n(203)](8,E));M++)N=N[n(1351)](m);for(let M=0;e[n(1157)](M,h[n(1391)]);M++)e[n(962)](M,p)?(d=d[n(1351)](N),d=d.concat(h[M])):d=d[n(1351)](h[M]);return d}}{let k=a[n(1438)](":");for(let N=0;e[n(221)](N,k[n(1391)]);N++)if(e[n(1010)](e[n(803)],e[n(1170)])){let M=k[N];if(k[N][n(1391)]!==4){let K=m[n(426)+"g"](0,e[n(203)](4,k[N][n(1391)])),W=K[n(1351)](M);d=d.concat(W)}else d=d[n(1351)](M)}else return this[n(1555)]?.del(_0x211459);return d}}function g(a,n){let s=t,d=a[s(1151)];if(d!==void 0)if(e[s(1323)]===e.HfjHu)e[s(283)](pe,n,10),e[s(997)](z,n,d);else return new _0x55e01a(_0xb93796,_0x2f19b2,_0x50bb40);let h=a.value;e.UMftH(void 0,h)&&(e[s(283)](pe,n,18),e[s(923)](z,n,h))}function w(a){let n=t;if(e[n(389)](n(970),e[n(1255)]))_0x275501=e[n(818)](_0x535ce6,_0x47e788),_0x42518c|=e[n(861)](e[n(843)](127,_0x30650c),14),128&_0x5c8d9d&&(_0x461f44=_0x21946b(_0x2da485),_0x577aa9|=e.mDtoc(e[n(843)](127,_0x4c10cf),21),e[n(791)](128,_0x1cf09f)&&(_0x21139c=_0x368cde(_0x5a133e),_0x2b6fe3=e[n(1488)](127,_0x2e716f),e.qxZUg(128,_0xe2b854)&&(_0x500e6e=e[n(356)](_0x31ac36,_0x505588),_0xf2fee3|=e[n(1583)](e[n(1558)](127,_0x4cb03a),7))));else{let s={};e:for(;!e.EAxLJ($,a);){let d=e[n(920)](xe,a);switch(e[n(558)](d,3)){case 0:break e;case 1:s[n(1151)]=e[n(283)](P,a,e[n(1141)](xe,a));break;case 2:s.value=P(a,e.hCGOv(xe,a));break;default:e[n(885)](R,a,e[n(1488)](7,d))}}if(e[n(389)](void 0,s[n(1151)]))throw new Error(n(601)+n(1571)+n(1567)+n(1151));if(e[n(1198)](void 0,s[n(1316)]))throw new Error(e[n(1340)]);return s}}function S(a){let n=t;if(e.WBURg(e[n(686)],e.rJbfB))e[n(680)](_0x2126c7,_0x30576d,16),e[n(283)](_0x158391,_0x5a35c0,_0x318eaa);else{let s=D();return e[n(521)](y,a,s),e[n(920)](B,s)}}function y(a,n){let s=t,d={UCOQT:function(Ut,Gt,xs){return e.xCWHO(Ut,Gt,xs)},wLjJB:e[s(1031)],tzimW:e.mzPlE},h=a[s(1124)];h!==void 0&&(e[s(1452)]!==e[s(690)]?(e.gWfco(pe,n,8),gt(n,h)):(this[s(1020)+s(234)+"Id"]=null,this[s(1020)+"l"]=36e5,this[s(1555)]=d[s(1079)](_0x2277be,d[s(934)],d[s(989)])));let p=a[s(438)];e.UMftH(void 0,p)&&(pe(n,16),gt(n,p));let E=a[s(622)];if(E!==void 0)if(e[s(513)](s(567),e.PpvnJ))e[s(341)](pe,n,24),e.fSBFo(gt,n,e[s(1077)](C,E));else return this["currentE"+s(1181)+s(1315)+"t"]=1,this[s(1149)+s(729)]++,this.endpoints[this[s(1149)+s(729)]];let _=a[s(559)];e.UMftH(void 0,_)&&(e.nVYmB(s(647),e[s(544)])?(pe(n,32),e[s(341)](gt,n,e.bRwaf(C,_))):_0x1b3f80[s(569)](_0x332068));let m=a[s(688)];if(e[s(912)](void 0,m))for(let Ut of m){e.ECivY(pe,n,42);let Gt=e.QFtsl(D);g(Ut,Gt),e[s(489)](pe,n,Gt[s(182)]),e[s(1616)](H,n,Gt),O(Gt)}let k=a[s(1521)+s(583)];k!==void 0&&(e[s(147)](pe,n,50),e[s(1307)](z,n,k));let N=a[s(1310)+s(403)];e[s(912)](void 0,N)&&(e[s(167)](pe,n,58),z(n,N));let M=a.payload;e[s(1276)](void 0,M)&&(e[s(923)](pe,n,66),e[s(489)](pe,n,M[s(1391)]),e.bACvu(oe,n,M));let K=a[s(562)];e[s(1276)](void 0,K)&&(e[s(1400)](pe,n,74),e[s(997)](z,n,K));let W=a[s(1023)+s(285)];e.KPHia(void 0,W)&&(e.OjTtJ(pe,n,82),e.YwbsQ(z,n,W));let he=a[s(563)];e[s(1276)](void 0,he)&&(e[s(824)](pe,n,90),z(n,he));let wt=a[s(277)+"e"];e[s(560)](void 0,wt)&&(e[s(997)](pe,n,96),e[s(1371)](gt,n,C(wt)))}function v(a){let n=t;return e[n(1077)](I,e[n(483)](F,a))}function I(a){let n=t,s={VtkGT:function(d,h){return e[ne(759)](d,h)},IUJHT:function(d,h){return d<h},HZGOk:function(d,h){return e[ne(1198)](d,h)}};if(e.bWfPW(e[n(1093)],e[n(1514)])){let d={};e:for(;!e[n(191)]($,a);)if(e[n(560)](e.ZXZPn,e[n(1506)])){if(s[n(1459)](void 0,_0x1885be))this[n(345)+"rs"]={};else if(s[n(1459)](void 0,_0x535725))this[n(345)+"rs"][_0x281e88]=null;else{let h=this[n(345)+"rs"][_0x6e0899];if(h)for(let p=0;s[n(758)](p,h[n(1391)]);)s.HZGOk(h[p].fn,_0x47fdf5)?h[n(596)](p,1):++p}return this}else{let h=e[n(310)](xe,a);switch(h>>>3){case 0:break e;case 1:d.SeqID=e[n(1165)](At,a,!0);break;case 2:d.LogID=At(a,!0);break;case 3:d.service=xe(a);break;case 4:d[n(559)]=e[n(1244)](xe,a);break;case 5:{let p=e.SAewW(A,a);(d[n(688)]||(d.headers=[]))[n(1273)](e[n(1498)](w,a)),a[n(182)]=p;break}case 6:d[n(1521)+n(583)]=e[n(432)](P,a,xe(a));break;case 7:d[n(1310)+n(403)]=e[n(1101)](P,a,xe(a));break;case 8:d.payload=se(a,xe(a));break;case 9:d.LogIDNew=e.xCWHO(P,a,xe(a));break;case 10:d.serverTiming=e.AlQiw(P,a,e[n(1141)](xe,a));break;case 11:d[n(563)]=e[n(1002)](P,a,e.ygOei(xe,a));break;case 12:d.frameType=e[n(721)](xe,a);break;default:e[n(847)](R,a,e[n(1531)](7,h))}}if(d[n(1124)]===void 0)throw new Error(e[n(1628)]);if(e[n(1574)](void 0,d[n(438)]))throw new Error(e[n(1557)]);if(e[n(1375)](void 0,d.service))throw new Error(e[n(286)]);if(e[n(1198)](void 0,d[n(559)]))throw new Error(e[n(429)]);return d}else{let d=e[n(380)][n(1438)]("|"),h=0;for(;;){switch(d[h++]){case"0":if(_0x56e331[n(876)+"e"])return e[n(1200)](_0x494835[n(876)+"e"](_0x5c2c76,_0x2917c0),_0x1f713f);continue;case"1":return _0x2fdcc2(_0x59c72f,_0xd5b895,_0x15596c)+_0x534dc7;case"2":if(_0x25c2b5.length<40)return e[n(1437)](e.RLFTz(_0x1eb868,_0x26e0ab,_0x8255e8,_0x55eec4),_0x1188d6);continue;case"3":if(_0x2c841b[n(1463)])return e[n(1448)](_0x48f841[n(1463)](_0x1fcd63,_0xb1a900),_0x563cc1);continue;case"4":if(!_0x443aaa)return _0x4a0c40;continue}break}}}function A(a){let n=t,s=e[n(1077)](xe,a),d=a[n(182)];return a.limit=a.offset+s,d}function R(a,n){let s=t;switch(n){case 0:for(;e[s(1185)](128,Q(a)););break;case 2:V(a,e[s(1141)](xe,a));break;case 5:e[s(847)](V,a,4);break;case 1:e.figlh(V,a,8);break;default:throw new Error(e.zViif(e[s(1171)],n))}}function C(a){let n=t;return e[n(232)]!==n(554)?(a|=0,{low:a,high:e[n(1100)](a,31),unsigned:e[n(342)](a,0)}):_0x4a3a7d[n(715)+n(308)][1]?void 0:_0x3095fa[n(715)+n(1086)](_0x13e704[n(715)+n(308)][0])}let b=[];function D(){let a=t,n=b[a(1082)]();return n?(n.offset=n[a(182)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){b[t(1273)](a)}function F(a){let n=t;if(e[n(1160)]("fUYtR",e[n(1282)]))return{bytes:a,offset:0,limit:a.length};_0x22ff02=_0x91d359[e[n(1448)](e[n(273)](_0x68c998,_0x25d2d0),1)],e[n(157)](192&_0x4fb650,128)?_0x534185+=_0xf775d8:(_0x57a2bf=e[n(526)](e[n(443)](31&_0x4bb68e,6),e[n(967)](63,_0x5c617d)),e[n(1157)](_0x2ff28e,128)?_0x493988+=_0x55899c:(_0x28eb15+=_0x3ab85f(_0x11145c),_0x3229d1++))}function B(a){let n=t,s=a[n(1177)],d=a[n(182)];return e[n(962)](s[n(1391)],d)?s:s.subarray(0,d)}function V(a,n){let s=t;if(e[s(883)](e[s(509)],e[s(428)])){if(a[s(857)]+n>a.limit)throw new Error(e[s(1112)]);a.offset+=n}else{let d=_0x43ee18.substring(0,4-_0x2659d2[_0x59cc3f][s(1391)]),h=d[s(1351)](_0x54dbf4[_0x5c513c]);_0x5b2a4b[s(1273)](h)}}function $(a){return e[t(1401)](a.offset,a.limit)}function re(a,n){let s=t,d=a[s(1177)],h=a[s(857)],p=a[s(182)],E=h+n;if(e.NqBYW(E,d[s(1391)])){let _=new Uint8Array(2*E);_[s(1041)](d),a[s(1177)]=_}return a[s(857)]=E,E>p&&(a[s(182)]=E),h}function Y(a,n){let s=t,d=a[s(857)];if(e[s(1324)](e[s(1237)](d,n),a[s(182)]))throw new Error(e.BmuFn);return a[s(857)]+=n,d}function se(a,n){let s=t,d=Y(a,n);return a[s(1177)][s(264)](d,e[s(694)](d,n))}function oe(a,n){let s=t;if(e[s(708)]!==s(1608))this[s(1609)](e[s(555)],_0x5b4e99(e[s(555)],{message:this[s(305)+s(1451)+s(1180)](_0x5eb8c6)}));else{let d=re(a,n[s(1391)]);a[s(1177)][s(1041)](n,d)}}function P(a,n){let s=t,d=e[s(586)](Y,a,n),h=String[s(1072)+s(1153)],p=a[s(1177)],E="\uFFFD",_="";for(let m=0;m<n;m++){let k=p[e[s(181)](m,d)],N,M,K,W;e[s(148)](e[s(385)](128,k),0)?_+=e.ARuFn(h,k):e.uGCSe(224&k,192)?e[s(819)](m,1)>=n?_+=E:(N=p[e[s(1200)](e[s(1448)](m,d),1)],e[s(922)](e[s(1558)](192,N),128)?_+=E:(W=e[s(574)](e.GhpCf(31&k,6),e[s(1185)](63,N)),W<128?_+=E:(_+=e[s(721)](h,W),m++))):e.EVBLa(e[s(1531)](240,k),224)?e[s(1401)](e[s(506)](m,2),n)?_+=E:(N=p[m+d+1],M=p[e[s(819)](m,d)+2],e[s(1515)](e[s(1405)](e[s(1624)](N,e[s(443)](M,8)),49344),32896)?_+=E:(W=e[s(581)](e[s(1166)](e[s(965)](15,k)<<12,e[s(1060)](e[s(843)](63,N),6)),e[s(967)](63,M)),e[s(434)](W,2048)||W>=55296&&W<=57343?_+=E:(_+=e[s(956)](h,W),m+=2))):e[s(458)](e[s(843)](248,k),240)?e.hRVcT(e.tRKsD(m,3),n)?_+=E:(N=p[e[s(961)](e.hfUEu(m,d),1)],M=p[e[s(1212)](e[s(1006)](m,d),2)],K=p[e[s(1212)](e.QNUKu(m,d),3)],e[s(1010)](e[s(1390)](e.qYkQD(e[s(1544)](N,M<<8),e[s(1179)](K,16)),12632256),8421504)?_+=E:(W=e[s(1166)](e[s(543)](e[s(443)](e[s(451)](7,k),18),e.EtyoQ(63,N)<<12)|e[s(266)](e[s(1405)](63,M),6),63&K),e[s(1479)](W,65536)||e[s(367)](W,1114111)?_+=E:(W-=65536,_+=h(e.bxvGH(e[s(640)](W,10),55296),e.njuxw(1023&W,56320)),m+=3))):_+=E}return _}function z(a,n){let s=t,d={Apckv:function(m,k,N){return e[ne(830)](m,k,N)},pbFQP:e.Alyhu},h=n[s(1391)],p=0;for(let m=0;m<h;m++){let k=n[s(291)+"At"](m);e.mhfWQ(k,55296)&&e[s(1524)](k,56319)&&e[s(331)](m+1,h)&&(k=e[s(1078)](e[s(316)](e[s(837)](k,10),n.charCodeAt(++m)),56613888)),p+=k<128?1:e[s(329)](k,2048)?2:e[s(329)](k,65536)?3:4}e[s(942)](pe,a,p);let E=e[s(586)](re,a,p),_=a[s(1177)];for(let m=0;e.tynab(m,h);m++){let k=n.charCodeAt(m);if(e[s(1401)](k,55296)&&e.JFzmZ(k,56319)&&e[s(329)](m+1,h)&&(k=e[s(961)](k<<10,n.charCodeAt(++m))-56613888),k<128)_[E++]=k;else{if(e[s(1314)](k,2048))_[E++]=e[s(1544)](e[s(1185)](e[s(1100)](k,6),31),192);else if(e[s(682)](e[s(1022)],e[s(1373)])){let N={sGYhj:function(M,K,W){return d[s(1270)](M,K,W)},wFwjt:d[s(1301)],szmUa:s(1081)};_0x4660ab[s(1164)]()[s(1496)](()=>{let M=s,K=N[M(1545)](_0x1874eb,N.wFwjt,{message:this[M(305)+M(1451)+"age"](_0x557e92)});this[M(1609)](N[M(1328)],K);let W=N[M(1545)](_0x4fdcac,N[M(1639)],{reason:this[M(305)+"rrorMess"+M(1180)](_0x1231a2)});this[M(1609)](N[M(1639)],W)})}else{if(e[s(630)](k,65536))_[E++]=e[s(501)](e[s(640)](k,12),15)|224;else if(e[s(662)](e[s(1392)],s(1409)))_[E++]=e[s(581)](e[s(1390)](e.aybDH(k,18),7),240),_[E++]=e.XKzsS(e[s(1188)](k,12),63)|128;else{let N=_0x5b6546(e[s(555)],{message:this[s(305)+s(1451)+s(1180)](_0x54bf62)});this[s(1609)](e[s(555)],N);let M=_0x23e5ae("close",{reason:this[s(305)+s(1451)+s(1180)](_0x39f60d)});this.emit(e[s(769)],M)}_[E++]=e[s(355)](e[s(1100)](k,6),63)|128}_[E++]=e[s(931)](e.jxBjU(63,k),128)}}}function H(a,n){let s=t,d=e.JaCdV(re,a,n.limit),h=a[s(1177)],p=n.bytes;for(let E=0,_=n[s(182)];e.UcbNE(E,_);E++)h[e[s(326)](E,d)]=p[E]}function Q(a){return a.bytes[e.NSMLm(Y,a,1)]}function $e(a,n){let s=t,d=e[s(824)](re,a,1);a.bytes[d]=n}function xe(a){let n=t,s=0,d=0,h;do h=Q(a),s<32&&(d|=e.GhpCf(e[n(895)](127,h),s)),s+=7;while(e[n(1558)](128,h));return d}function pe(a,n){let s=t;for(n>>>=0;e[s(342)](n,128);){if(e.VkZbW(e[s(909)],e[s(1402)]))return e[s(585)](_0x5ef639[s(857)],_0x471def[s(182)]);e.ZoTYf($e,a,e[s(1624)](e.aRdNn(127,n),128)),n>>>=7}e[s(746)]($e,a,n)}function At(a,n){let s=t,d={LQXno:function(m,k,N){return m(k,N)},eNbmM:function(m,k,N){return e[ne(899)](m,k,N)},bQlHR:s(709)},h=0,p=0,E=0,_;if(_=Q(a),h=e[s(1356)](127,_),e.Gygjm(128,_)&&(_=e[s(1498)](Q,a),h|=(127&_)<<7,e[s(1096)](128,_)&&(_=e.ygOei(Q,a),h|=e.mDtoc(127&_,14),e.aRdNn(128,_))))if(e[s(846)]!==e[s(1493)]){if(_=Q(a),h|=e[s(501)](127,_)<<21,128&_&&(_=e[s(1549)](Q,a),p=127&_,e[s(1634)](128,_)&&(_=e[s(1549)](Q,a),p|=e[s(1508)](e[s(1096)](127,_),7),128&_&&(_=e[s(483)](Q,a),p|=e.YTwzm(e[s(1466)](127,_),14),e.bSPDl(128,_)))))if(e.gPkPf(s(565),s(987)))_=e[s(1498)](Q,a),p|=e.OpPBV(127&_,21),128&_&&(_=e[s(685)](Q,a),E=e[s(165)](127,_),e[s(394)](128,_)&&(_=e[s(956)](Q,a),E|=e[s(918)](e[s(288)](127,_),7)));else{this[s(1397)+s(1068)](),this[s(600)+s(1416)+"Id"]=d[s(1199)](_0x501a65,this[s(290)][s(597)](this),this[s(1045)][s(1653)+s(1577)]);return}}else{let m="connect "+_0x19c779+(s(1550)+s(1445)+s(1368)+"ed");this[s(1291)+s(284)+"ent"](d[s(576)](_0x518d68,d[s(631)],{message:m,code:_0x3f7ad5[s(1385)+s(1054)+"R"],error:_0x21b341}));return}return{low:e[s(807)](h,e[s(1060)](p,28)),high:e[s(1128)](e[s(1223)](p,4),e[s(1179)](E,24)),unsigned:n}}function gt(a,n){let s=t,d=e[s(1338)](n[s(661)],0),h=(e[s(1338)](n.low,28)|e[s(620)](n[s(1601)],4))>>>0,p=e[s(549)](n[s(1601)],24),E=e[s(682)](0,p)?e[s(759)](0,h)?e[s(1157)](d,16384)?e[s(1312)](d,128)?1:2:e[s(329)](d,2097152)?3:4:e[s(785)](h,16384)?e[s(499)](h,128)?5:6:e.tynab(h,2097152)?7:8:e[s(1192)](p,128)?9:10,_=e.qiBWu(re,a,E),m=a[s(1177)];switch(E){case 10:m[e.hfUEu(_,9)]=p>>>7&1;case 9:m[e[s(1006)](_,8)]=E!==9?128|p:e[s(1431)](127,p);case 8:m[e.TFcRU(_,7)]=e[s(1276)](8,E)?e[s(526)](e[s(485)](h,21),128):e.rNNWD(e.HwOlS(h,21),127);case 7:m[e[s(316)](_,6)]=e[s(238)](7,E)?e[s(863)](h>>>14,128):e.GLRZD(e[s(1223)](h,14),127);case 6:m[e[s(316)](_,5)]=e.wmzcZ(6,E)?e[s(1606)](h>>>7,128):e[s(361)](e[s(968)](h,7),127);case 5:m[e[s(181)](_,4)]=e.zQGRj(5,E)?e.cKlkj(128,h):e.wnhEw(127,h);case 4:m[_+3]=e[s(334)](4,E)?e[s(700)](d,21)|128:e[s(1405)](e.VxjIo(d,21),127);case 3:m[e[s(819)](_,2)]=e[s(318)](3,E)?e[s(928)](d>>>14,128):e[s(910)](d,14)&127;case 2:m[_+1]=e[s(912)](2,E)?e.diyos(d,7)|128:e[s(843)](d>>>7,127);case 1:m[_]=e[s(334)](1,E)?128|d:e[s(201)](127,d)}}function sn(a){return v(a)}function zt(a){return e[t(356)](S,a)}let on=65536,ei=t(624),_e=e[t(1332)](on,on),ke=_e*_e,rr=e[t(568)](ke,2),Oe=String[t(1292)+"e"][t(291)+"At"];class fe{constructor(n,s,d){let h=t;this[h(1280)]=!0,this[h(661)]=e[h(260)](0,n),this[h(1601)]=e[h(574)](0,s),this[h(828)]=!!d}static[t(1280)](n){let s=t;return n&&e[s(1602)](!0,n[s(1280)])}static[t(456)](n,s,d){return new fe(n,s,d)}static fromBytes(n,s,d){let h=t;return d?fe[h(1278)+h(755)](n,s):fe[h(1278)+h(1121)](n,s)}static[t(1278)+t(755)](n,s){let d=t;return new fe(e.KCKWR(n[0],n[1]<<8)|n[2]<<16|e[d(359)](n[3],24),e[d(581)](e[d(807)](n[4],n[5]<<8),e[d(1508)](n[6],16))|e.bYZtf(n[7],24),s)}static[t(1278)+t(1121)](n,s){let d=t;return new fe(e[d(1606)](e[d(522)](e[d(359)](n[4],24),n[5]<<16)|n[6]<<8,n[7]),e[d(760)](e.ESHIc(e[d(465)](e.jsAza(n[0],24),e[d(1583)](n[1],16)),e[d(1508)](n[2],8)),n[3]),s)}static[t(530)](n){let s=t;return e[s(929)](n,ei)?dl:new fe(e[s(641)](e[s(730)](e[s(304)](Oe[s(725)](n,0),e[s(805)](Oe[s(725)](n,1),8))|e[s(266)](Oe[s(725)](n,2),16),e.mUrlW(Oe.call(n,3),24)),0),e[s(760)](e[s(1605)](e[s(1454)](Oe[s(725)](n,4),e[s(1272)](Oe[s(725)](n,5),8)),e[s(1179)](Oe[s(725)](n,6),16)),Oe[s(725)](n,7)<<24)>>>0,!0)}[t(239)](){let n=t;if(n(496)!==e.lnOlT)this[n(1291)+"hMessage"+n(1492)](_0x3bc736),_0x2129f[n(1041)](_0x5e7f1a,_0x556720,_0x27c31c.message.service);else return String[n(1072)+"Code"](e[n(386)](255,this.low),this.low>>>8&255,e[n(501)](e[n(558)](this[n(661)],16),255),e.GQOWE(this[n(661)],24),e[n(361)](255,this[n(1601)]),e[n(843)](this[n(1601)]>>>8,255),e.rNNWD(e[n(1223)](this[n(1601)],16),255),e[n(700)](this[n(1601)],24))}static[t(407)+"er"](n,s=!0){let d=t,h={sOdAz:function(p,E){return p instanceof E},mSipx:function(p,E){return e.iboGA(p,E)},vBITy:e[d(986)],zrpNm:"string",DrBfd:d(977),JexZr:function(p,E,_,m){return e[d(1414)](p,E,_,m)}};if(e[d(483)](isNaN,n))return s?Wp:dl;if(s){if(e[d(342)](n,ke))return $p}else if(e[d(1523)]!==e[d(1230)]){if(e[d(1524)](n,-rr))return Vp;if(e[d(1548)](n+1,rr))return Kp}else if(_0x1ea73d[d(849)]instanceof _0x539a74){let p=h.sOdAz(this[d(1045)][d(1521)+"ncoding"],_0x28c7eb)?{force:!!this._options["payloadE"+d(583)][d(409)],encoding:this[d(1045)]["payloadE"+d(583)][d(1131)]?this[d(1045)]["payloadE"+d(583)][d(1131)][d(533)](/\s/g,"")[d(1376)+"ase"]():""}:{force:!1,encoding:this[d(1045)][d(1521)+d(583)]?this[d(1045)][d(1521)+"ncoding"][d(533)](/\s/g,"")[d(1376)+d(1384)]():""},E=_0x30f16f["payloadE"+d(583)]?_0x12fea7[d(1521)+"ncoding"][d(533)](/\s/g,"")[d(1376)+"ase"]():"",_=h[d(978)](this._options[d(1310)+d(403)],_0x383218)?{force:!!this[d(1045)][d(1310)+d(403)][d(409)],type:this[d(1045)][d(1310)+d(403)][d(1481)]?this[d(1045)][d(1310)+d(403)][d(1481)][d(533)](/\s/g,"")[d(1376)+d(1384)]():""}:{force:!1,type:this[d(1045)][d(1310)+d(403)]?this[d(1045)][d(1310)+"ype"][d(533)](/\s/g,"")["toLowerC"+d(1384)]():""},m=_0x4dfe6d.payloadType?_0x5c0ce2[d(1310)+d(403)][d(533)](/\s/g,"")[d(1376)+d(1384)]():"",k=_[d(409)]?_[d(1481)]:m||_.type,N=p[d(409)]?p[d(1131)]:E||p[d(1131)],M=[d(1056)+"in;charset=utf-8",h[d(1211)],"applicat"+d(1366)+d(1614)+"=utf-8",h[d(1440)]],K=[d(627)+"e",h[d(1595)]];this._options[d(579)+d(1501)+d(669)+"ad"]&&M[d(983)](k)&&(!N||K[d(983)](N))?_0x45b936[d(1387)+d(1119)]=h.JexZr(_0x486d9c,_0x2b07b2.payload,0,_0x5bc405[d(849)][d(330)+"th"]):_0x131691[d(1387)+"oad"]=""}else _0x283665.textPayload="";return fe.fromBits(e[d(260)](e[d(1449)](n,_e),0),e.gOvIV(e[d(568)](n,_e),0),s)}[t(453)](){let n=t;return this[n(828)]?e[n(1118)](e.iJJHK(this[n(1601)]>>>0,_e),e.tvCZd(this.low,0)):e[n(926)](e[n(816)](this[n(1601)],_e),e[n(1528)](this[n(661)],0))}[t(395)](){let n=t;if(e.XUiyF===n(888))return this[n(1601)]===0&&e[n(389)](0,this.low);_0x4d6cb6(_0x290e20,90),e[n(1001)](_0x388964,_0x5e6359,_0x5ee667)}[t(1436)](n){let s=t;fe.isLong(n)||(n=fe.fromNumber(n));let d=e[s(1102)](this.high,16),h=e[s(843)](65535,this[s(1601)]),p=e[s(821)](this.low,16),E=e[s(1356)](65535,this[s(661)]),_=e[s(821)](n[s(1601)],16),m=e.IIHDy(65535,n.high),k=e.EvhLw(n[s(661)],16),N=e.fzVpY(65535,n[s(661)]),M=0,K=0,W=0,he=0;return he+=E+N,W+=e[s(971)](he,16),he&=65535,W+=e[s(460)](p,k),K+=e[s(689)](W,16),W&=65535,K+=e[s(391)](h,m),M+=e[s(700)](K,16),K&=65535,M+=e[s(364)](d,_),M&=65535,fe.fromBits(e[s(730)](e.OeyUp(W,16),he),e[s(760)](e[s(656)](M,16),K),this[s(828)])}[t(1589)](n){let s=t;return fe.isLong(n)||(n=fe[s(407)+"er"](n)),e[s(1635)](this.unsigned,n[s(828)])&&e[s(700)](this.high,31)===1&&e[s(1621)](n[s(1601)]>>>31,1)?!1:this.high===n[s(1601)]&&this.low===n[s(661)]}addOne(){let n=t;return e[n(1198)](-1,this[n(661)])&&this[n(1601)]===-1?fe[n(456)](0,0,this[n(828)]):e.uGCSe(-1,this[n(661)])?fe.fromBits(0,e[n(959)](this[n(1601)],1),this[n(828)]):fe[n(456)](e[n(364)](this[n(661)],1),this[n(1601)],this[n(828)])}[t(921)](n){return n?this[t(817)+"E"]():this.toBytesBE()}[t(817)+"E"](){let n=t,s=this.high,d=this[n(661)];return[e[n(288)](255,d),e[n(1202)](d>>>8,255),e[n(556)](d>>>16,255),e[n(971)](d,24),e.MfWpK(255,s),e[n(693)](e[n(558)](s,8),255),e[n(1380)](e[n(1223)](s,16),255),e[n(1168)](s,24)]}[t(502)+"E"](){let n=t,s=this[n(1601)],d=this.low;return[e[n(558)](s,24),s>>>16&255,e[n(288)](e[n(230)](s,8),255),e[n(525)](255,s),e[n(689)](d,24),e[n(895)](d>>>16,255),e[n(679)](e[n(485)](d,8),255),e[n(1632)](255,d)]}}let dl=new fe(0,0,!1),Wp=new fe(0,0,!0),Kp=fe.fromBits(-1,2147483647,!1),$p=fe.fromBits(-1,-1,!0),Vp=fe[t(456)](0,-2147483648,!1);var an=(function(a){let n=t,s=("2|1|5|0|"+n(281))[n(1438)]("|"),d=0;for(;;){switch(s[d++]){case"0":a[a[e[n(249)]]=5004]=e[n(249)];continue;case"1":a[a[n(1631)+n(813)]=5002]=n(1631)+n(813);continue;case"2":a[a[e[n(638)]]=5001]=e.euLrA;continue;case"3":return a;case"4":a[a[e[n(297)]]=5005]=e[n(297)];continue;case"5":a[a[e[n(1127)]]=5003]=e.YEgiy;continue}break}})({});class ir{constructor(n){let s=t;this[s(1481)]=n,this.target=null}}class ll extends ir{constructor(n,s){let d=t;super(n),this.message=s&&s[d(1645)]||null}}class ul extends ir{constructor(n,s){let d=t,h=e.ScZUM[d(1438)]("|"),p=0;for(;;){switch(h[p++]){case"0":this[d(709)]=s&&s[d(709)]||null;continue;case"1":this[d(259)]=s&&s.filename||"";continue;case"2":this[d(1645)]=s&&s[d(1645)]||"";continue;case"3":this[d(1116)]=s&&s.colno||0;continue;case"4":super(n);continue;case"5":this.lineno=s&&s[d(512)]||0;continue;case"6":this[d(212)]=s&&s[d(212)]||5001;continue}break}}}class fl extends ir{constructor(n,s){let d=t,h={GEcPl:function(p,E){return e[ne(689)](p,E)},jWceu:function(p,E){return e[ne(1579)](p,E)},kDwaT:function(p,E){return p>>>E},liceE:function(p,E){return p>>>E},MfldB:function(p,E){return p>>>E},TtMgH:function(p,E){return e.IpRdZ(p,E)},cUywC:function(p,E){return p&E}};if(e[d(513)](e.dCbhk,e[d(1259)])){let p=this[d(1601)],E=this[d(661)];return[YTIOjt[d(726)](p,24),YTIOjt[d(778)](YTIOjt.kDwaT(p,16),255),YTIOjt[d(778)](YTIOjt[d(902)](p,8),255),YTIOjt.jWceu(255,p),YTIOjt.MfldB(E,24),YTIOjt[d(1593)](YTIOjt[d(820)](E,16),255),YTIOjt[d(527)](YTIOjt[d(317)](E,8),255),255&E]}else{let p=(d(1561)+"2")[d(1438)]("|"),E=0;for(;;){switch(p[E++]){case"0":this.code=s&&s.code||0;continue;case"1":super(n);continue;case"2":this["willReco"+d(205)]=s&&s["willReco"+d(205)]||!1;continue;case"3":this[d(1353)]=s&&s[d(1353)]||!1;continue;case"4":this[d(296)]=s&&s.reason||"";continue}break}}}}class hl extends ir{constructor(n,s){let d=t,h={FUDOA:e[d(366)],FdZoI:function(p,E){return p>>>E},KlThx:function(p,E){return e[d(1128)](p,E)},nKELT:function(p,E){return e.jRavv(p,E)},lmdUK:function(p,E){return e[d(394)](p,E)},rSffk:function(p,E){return e[d(557)](p,E)},yDUIO:function(p,E){return e[d(221)](p,E)},aKDqM:function(p,E){return p>E},qEBKR:function(p,E,_,m){return e[d(1414)](p,E,_,m)},JYGZL:function(p,E){return e[d(1073)](p,E)},Zoedo:function(p,E){return e[d(266)](p,E)},GWHir:function(p,E){return e[d(1098)](p,E)},KBMIF:function(p,E){return p>>>E},TfkUF:function(p,E){return e[d(270)](p,E)},eKokL:function(p,E){return p<E},ZBIEQ:function(p,E){return p|E},idNBJ:function(p,E){return e[d(359)](p,E)}};if(e[d(762)]!==e[d(762)]){let p=4294967295;return function(E,_,m=!0){let k=d,N=h[k(707)].split("|"),M=0;for(;;){switch(N[M++]){case"0":p=h[k(1475)](h.KlThx(p,h[k(590)](h[k(761)](127,E[_]),7)),0);continue;case"1":if(h[k(1083)](E[_++],128))return{value:m?p:0|p,offset:_};continue;case"2":return{value:m?p:0|p,offset:_};case"3":if(h[k(1229)](E[_++],128))return{value:m?p:0|p,offset:_};continue;case"4":if(h[k(244)](_+=5,E[k(1391)]))throw _=E[k(1391)],h[k(1304)](_0x2abad4,_,10,E[k(1391)]);continue;case"5":p=h[k(1111)](p|h[k(151)](15&E[_],28),0);continue;case"6":p=h.JYGZL(h[k(761)](127,E[_]),0);continue;case"7":if(h[k(802)](E[_++],128))return{value:m?p:h[k(314)](0,p),offset:_};continue;case"8":if(E[_++]<128)return{value:m?p:h.KlThx(0,p),offset:_};continue;case"9":p=h[k(872)](h.TfkUF(p,(127&E[_])<<14),0);continue;case"10":if(h[k(252)](E[_++],128))return{value:m?p:h[k(772)](0,p),offset:_};continue;case"11":p=h.ZBIEQ(p,h[k(1033)](h[k(761)](127,E[_]),21))>>>0;continue}break}}}else super(n),this[d(1284)]=s&&s[d(1284)]||null}}class xl extends hl{constructor(n,s){let d=t;super(n),this[d(1284)]=s&&s.data||null,this[d(1645)]=s&&s[d(1645)]||null}}class pl extends ir{constructor(n,s){let d=t;super(n),this.data=s&&s[d(1284)]||null}}function at(a,{message:n,code:s,error:d}){return new ul(a,{message:n,code:s,error:d})}function mt(a,{code:n,reason:s,wasClean:d,willReconnect:h}){return new fl(a,{code:n,reason:s,wasClean:d,willReconnect:h})}function gl(a,{data:n,message:s}){return new xl(a,{data:n,message:s})}function ml(a,{data:n}){return new pl(a,{data:n})}function Ea(a,{message:n}){return new ll(a,{message:n})}class wl{constructor(n,s){let d=t;this[d(1404)+"s"]=n,this.maxRetries=s,this[d(1149)+"ndex"]=0,this[d(1e3)+d(1181)+"riesCount"]=0}[t(875)+t(1251)+t(905)](){let n=t;this[n(1149)+"ndex"]=0,this[n(1e3)+n(1181)+n(1315)+"t"]=0}[t(808)+"es"](){let n=t;this[n(1e3)+"ndpointT"+n(1315)+"t"]=0}[t(1207)+t(784)+"nt"](){let n=t;return this[n(1404)+"s"][this[n(1149)+"ndex"]]}[t(1207)+t(784)+t(698)+"ount"](){let n=t;return this[n(1e3)+n(1181)+n(1315)+"t"]}["checkRea"+t(1062)+"es"](){let n=t;return!!(e[n(916)](this.currentIndex,this[n(1404)+"s"][n(1391)])||e[n(282)](this[n(1149)+n(729)],e.EyCII(this[n(1404)+"s"][n(1391)],1))&&e[n(794)](this["currentE"+n(1181)+"riesCount"],this[n(1510)+"es"]))}[t(478)+t(1406)+t(1243)+t(1490)+t(1586)](){let n=t;return this[n(1149)+"ndex"]==this[n(1404)+"s"][n(1391)]?!0:e[n(553)](this[n(1e3)+"ndpointTriesCount"],this[n(1510)+"es"])}[t(1313)+t(363)+t(168)+t(531)+t(870)](){let n=t;return this["currentE"+n(1181)+n(1315)+"t"]=1,this[n(1149)+n(729)]++,this.endpoints[this[n(1149)+n(729)]]}[t(1207)+t(784)+"ntAndUpdateCount"](){let n=t;return this[n(1e3)+n(1181)+n(1315)+"t"]++,this[n(1207)+n(784)+"nt"]()}}let sr=(e[t(826)](e.gPCIi,typeof globalThis)&&e.PuLUl(e.ceBpl,globalThis[t(1518)+t(1208)][t(766)])||e[t(1370)]!=typeof window&&t(623)===window[t(1518)+"tor"][t(766)])&&e[t(1120)]("undefined",typeof document),Dn=e[t(826)](e[t(1370)],typeof globalThis)&&(e.rusRR(e[t(783)],globalThis[t(1518)+"tor"][t(766)])||e[t(1457)](t(1182)+t(1047)+"lobalScope",globalThis["construc"+t(1208)][t(766)]))&&e[t(1370)]!=typeof tt,ti=(e[t(810)](e[t(1370)],typeof globalThis)&&e[t(325)](e[t(783)],globalThis[t(1518)+"tor"][t(766)])||e[t(253)](t(946)+"d",typeof globalThis)||e[t(1283)](t(946)+"d",typeof globalThis)&&!!globalThis[t(237)+t(1135)])&&e[t(770)](t(946)+"d",typeof wx),ni=e.YKTLZ(e.gPCIi,typeof globalThis)&&(e[t(759)](e[t(1103)],globalThis[t(1518)+"tor"][t(766)])||e[t(513)](e.jeFAd,globalThis[t(1518)+t(1208)][t(766)])||e[t(333)](e[t(398)],globalThis[t(1518)+"tor"].name))&&e[t(1410)](e[t(1370)],typeof self),Jp=e[t(1427)](e[t(1370)],typeof globalThis)&&t(925)===globalThis[t(1518)+t(1208)][t(766)]&&e[t(664)](e[t(1370)],typeof global)&&e[t(389)](e[t(783)],global["construc"+t(1208)][t(766)])&&e.gPCIi!=typeof process&&!!process[t(1024)];class va{constructor(){let n=t;this[n(345)+"rs"]={}}[t(1609)](n,...s){let d=t,h=this[d(345)+"rs"][n];if(h)h[d(1039)]().forEach(p=>p.fn[d(666)](p[d(178)],s));else if(e[d(540)](e[d(555)],n)&&!this[d(1520)]){let p=s.length&&s[0];if(e[d(1423)](p,Error))throw p;let E=new Error(e[d(1186)]("Unhandled error.",p?e.tRKsD(e[d(1118)](" (",p[d(1645)]),")"):""));throw E.context=p,p}return this}off(n,s){let d=t;if(e[d(513)](void 0,n))this[d(345)+"rs"]={};else if(e[d(1076)](void 0,s))this[d(345)+"rs"][n]=null;else{let h=this[d(345)+"rs"][n];if(h)for(let p=0;e[d(697)](p,h[d(1391)]);)e[d(1076)](h[p].fn,s)?h[d(596)](p,1):++p}return this}on(n,s,d){let h=t;return(this[h(345)+"rs"][n]||(this[h(345)+"rs"][n]=[]))[h(1273)]({fn:s,ctx:d||this}),this}}class Zp extends va{[t(305)+"rrorMessage"](n){let s=t;return n.errMsg||n[s(1656)]?(s(775)+" "+(n[s(804)]||"")+s(1564)+(n[s(1656)]||""))[s(490)]():JSON[s(737)+"y"](n)}constructor(n,s,d){let h=t;super(),this._socket=null,ti&&wx[h(1422)+h(1429)]&&(this[h(628)]=wx[h(1422)+h(1429)]({url:n,protocols:s,header:d,fail:this[h(1003)+h(1040)+"lHandler"].bind(this),success:this["_createS"+h(480)+h(1150)+"ler"][h(597)](this)})),Dn&&tt[h(1422)+"ocket"]&&(this._socket=tt[h(1422)+"ocket"]({url:n,protocols:s,header:d,fail:this[h(1003)+h(1040)+h(529)][h(597)](this),success:this[h(1003)+h(480)+"cessHand"+h(440)][h(597)](this)}))}[t(1003)+t(480)+t(1150)+t(440)](){let n=t;Promise[n(1164)]().then(()=>{this["_addWsLi"+n(1597)]()})}["_createS"+t(1040)+t(529)](n){let s=t,d={zIloS:e[s(555)],SNZOk:function(h,p,E){return h(p,E)},UTrEL:e[s(769)]};Promise[s(1164)]()[s(1496)](()=>{let h=s,p=at(d[h(1174)],{message:this[h(305)+h(1451)+"age"](n)});this[h(1609)](d[h(1174)],p);let E=d[h(1193)](mt,d[h(799)],{reason:this[h(305)+h(1451)+h(1180)](n)});this.emit(h(1081),E)})}[t(731)+t(1597)](){let n=t,s={ywLrs:e.Alyhu,aNwBC:function(d,h,p){return e.mpRUe(d,h,p)}};this[n(628)][n(1636)](d=>{let h=n;this[h(1609)](h(655),e[h(586)](ml,e[h(1421)],{...d,data:d[h(804)]||""}))}),this[n(628)][n(1132)](d=>{let h=n;this[h(1609)](h(1081),e.ULkue(mt,h(1081),{...d}))}),this[n(628)].onMessage(d=>{let h=n;this[h(1609)](h(1645),gl(e[h(195)],{...d}))}),this[n(628)][n(1560)](d=>{let h=n;this.emit(s.ywLrs,s[h(898)](at,s[h(321)],{...d,message:d[h(804)]||""}))})}[t(463)](n){let s=t,d={pxblb:function(h,p){return h>=p},kQcMl:function(h,p){return e[ne(307)](h,p)},vFBDd:function(h,p){return e[ne(1579)](h,p)},rdEYM:function(h,p){return h===p},dOXvf:e[s(337)],bRAND:e[s(555)],wFdPM:function(h,p,E){return h(p,E)}};if(n instanceof Uint8Array){let h=n[s(315)][s(1039)](n[s(1643)+"et"],e[s(262)](n[s(330)+"th"],n[s(1643)+"et"]));this[s(628)]&&this._socket.send({data:h,fail:p=>{let E=s;this[E(1609)]("error",e[E(947)](at,E(709),{message:this[E(305)+E(1451)+E(1180)](p)}))}})}else this[s(628)]&&this._socket[s(463)]({data:n,fail:h=>{let p=s;if(d[p(343)](d[p(945)],p(1568)))this[p(1609)](d[p(1453)],d.wFdPM(at,p(709),{message:this[p(305)+p(1451)+"age"](h)}));else{for(_0x1f5ebb>>>=0;KAwXpt.pxblb(_0x46b4b9,128);)_0x6d5136(_0x2bd878,KAwXpt[p(431)](KAwXpt[p(1355)](127,_0x38e675),128)),_0x29e016>>>=7;_0x2caa6f(_0x2dfde9,_0x242025)}}})}[t(1081)](n,s){let d=t;this[d(628)]&&this._socket[d(1081)]({code:n,reason:s})}["addEvent"+t(1389)](n,s){let d=t,h={WkHhU:function(p,E,_,m,k){return p(E,_,m,k)},uwEaL:d(1532)+d(1090)};if(e[d(540)](d(748),e[d(242)])){let p={mJYYa:function(E,_,m,k,N){let M=d;return TExStX[M(764)](E,_,m,k,N)},qmFqH:function(E,_){return E(_)}};_0xebe538[d(1225)+"Listener"](TExStX[d(1172)],E=>{let _=d;p.mJYYa(_0x8a65cc,p[_(475)](_0x28678a,_0x3d6499[_(1627)]),E[_(459)+"on"],E[_(1587)+"on"],p[_(475)](_0x38e06c,_0x341e1e[_(593)+_(588)]))})}else this.on(n,s)}["removeEv"+t(1248)+t(999)](n,s){let d=t;e.Zaslp(e.HExsQ,d(378))?this[d(750)](n,s):(this[d(236)+"ameSpace"]=_0x4d6bcd,this[d(1053)+d(1350)]=_0x1501dd,this[d(944)+"Strategy"]=_0x53c1a2,this[d(1555)]=_0x463a1d(this[d(236)+d(901)],d(1588)+"ame"))}get[t(919)+"te"](){let n=t;return this[n(628)][n(919)+"te"]}get[t(184)+"pe"](){let n=t;return this[n(628)][n(184)+"pe"]}set[t(184)+"pe"](n){}get[t(866)](){let n=t;return this[n(628)][n(866)]}get[t(1137)](){let n=t;return this[n(628)][n(1137)]}get[t(809)+"ns"](){let n=t;return this._socket[n(809)+"ns"]}get[t(1637)+"Amount"](){return 0}}function Yp(a,n){let s=t;if(n)return new n(a[s(866)],a[s(1137)]);if(e[s(519)](ti,Dn))return new Zp(a[s(866)],a.protocol,a[s(688)]);if((sr||ni)&&e.yqeGE(e[s(1370)],typeof WebSocket)&&WebSocket)return new WebSocket(a[s(866)],a.protocols)}function Xp(a){let n=t,s=e[n(578)][n(1438)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(ti&&wx[n(1422)+n(1429)])return!0;continue;case"1":if(e[n(519)](sr,ni)&&e[n(826)](e[n(1370)],typeof WebSocket)&&WebSocket)return!0;continue;case"2":if(a)return!0;continue;case"3":return!1;case"4":if(Dn&&tt[n(1422)+n(1429)])return!0;continue}break}}function _l(a,n,s){let d=t,h={sqDZJ:function(_,m){return e[ne(452)](_,m)},QlIzr:function(_,m){return e[ne(1530)](_,m)},RbkGn:e.WGxyB,aUhoz:function(_,m){return e[ne(1499)](_,m)},YDzRY:e[d(684)],UJMXz:function(_,m){return e.eYnAw(_,m)},MugNJ:function(_,m){return e.zViif(_,m)}},p=-1;async function E(_){let m=d;return h[m(1458)]!==h.RbkGn?(_0xac6396.apply(PvriEU.sqDZJ(_0x43bdca,this),_0x268636),PvriEU[m(1061)](_0x40532b,_0x5e3e83[m(873)](this))):h[m(393)](_,p)?Promise.reject(new Error(h[m(1379)])):(p=_,h[m(547)](_,s[m(1391)])?Promise.resolve():s[_].bind(a)(n,E[m(597)](null,h.MugNJ(_,1))))}e[d(532)](E,0)}function yl(a){let n=t,s=0,d=0;for(let h=0;e[n(1098)](h,a[n(1391)]);++h)if(d=a[n(291)+"At"](h),e[n(557)](d,128))s+=1;else if(e[n(1442)](d,2048))s+=2;else if(e.TFqPN(e[n(1356)](64512,d),55296)&&e.bvNzw(e[n(1067)](64512,a[n(291)+"At"](h+1)),56320))if(e[n(1015)](e[n(196)],e[n(196)]))++h,s+=4;else{let p=(e[n(1624)](e[n(867)](e[n(1067)](7,_0x271ee1),18)|e[n(1042)](63&_0x153a62[_0x58e10d++],12),e.Bxwip(63,_0x3a2da1[_0x76d03e++])<<6)|e.qCvSG(63,_0x4ab547[_0x585791++]))-65536;_0x2128a8+=_0x18edeb["fromChar"+n(1153)](e[n(959)](55296,e[n(377)](p,10))),_0x1c942a+=_0x2b17c9[n(1072)+n(1153)](e[n(1118)](56320,1023&p))}else s+=3;return s}function bl(a,n,s){let d=t,h={RGqds:e[d(907)],sQQQY:e[d(555)]};if(e[d(298)](e[d(224)],e[d(261)]))_0x41a386[d(765)+d(1248)+d(999)](KBydMX[d(294)],_0x56760e),_0x56dc50[d(765)+d(1248)+d(999)](KBydMX.sQQQY,_0x2506af);else{if(e[d(897)](e[d(822)](s,n),1))return"";let p="";for(let E=n;e[d(1447)](E,s);){let _=a[E++];if(e.JFzmZ(_,127))p+=String[d(1072)+d(1153)](_);else if(e.eAOVo(_,192)&&e[d(1552)](_,224))p+=String["fromChar"+d(1153)](e[d(807)](e[d(1583)](e.wnhEw(31,_),6),e[d(1480)](63,a[E++])));else if(_>=224&&_<240)p+=String[d(1072)+d(1153)](e.VenVH(15,_)<<12|e[d(963)](63&a[E++],6)|e.SMGtk(63,a[E++]));else if(_>=240){let m=e.Yvtfy(e[d(1605)](e.TUgTJ(e[d(807)](e.jxBjU(7,_)<<18,(63&a[E++])<<12),e[d(227)](e.agOKo(63,a[E++]),6)),63&a[E++]),65536);p+=String[d(1072)+d(1153)](e[d(506)](55296,m>>10)),p+=String["fromChar"+d(1153)](e.faPoh(56320,1023&m))}}return p}}function Sa(a,n,s){let d=t,h=s,p,E;for(let _=0;e.wDYzH(_,a.length);++_)if(p=a[d(291)+"At"](_),e[d(499)](p,128))n[s++]=p;else if(e.nsAFp(p,2048))n[s++]=e[d(763)](e[d(1188)](p,6),192),n[s++]=e[d(1604)](e[d(1096)](63,p),128);else if(e[d(566)](e[d(930)](64512,p),55296)&&e[d(616)](e[d(1531)](64512,E=a[d(291)+"At"](_+1)),56320)){let m=e[d(1245)][d(1438)]("|"),k=0;for(;;){switch(m[k++]){case"0":++_;continue;case"1":n[s++]=e.TYljF(e[d(936)](63,p),128);continue;case"2":n[s++]=e[d(351)](e[d(790)](p,6)&63,128);continue;case"3":p=e[d(1592)](e[d(506)](65536,e[d(1272)](e[d(1405)](1023,p),10)),e[d(165)](1023,E));continue;case"4":n[s++]=e.RNcjJ(p,12)&63|128;continue;case"5":n[s++]=e[d(1071)](p,18)|240;continue}break}}else n[s++]=e.bSJXC(e[d(796)](p,12),224),n[s++]=e[d(465)](e.vKMWG(p>>6,63),128),n[s++]=e.xwmWl(63&p,128);return e[d(974)](s,h)}async function El(a){let n=t;if(e[n(1382)]==typeof a){let s=new Uint8Array(e[n(818)](yl,a));return Sa(a,s,0),s}return e[n(235)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(315)],a[n(1643)+"et"],a[n(330)+"th"])}function Qp(a){let n=t;try{return e.NJPgl(e.qLPTQ,typeof a)&&(e[n(958)](a,ArrayBuffer)||a[n(315)]&&e.FrNMZ(a.buffer,ArrayBuffer))||e[n(1283)](e[n(1382)],typeof a)?"":(JSON[n(696)](a),e[n(986)])}catch{return e[n(253)](e.qLPTQ,typeof a)?"text/pla"+n(176)+n(390):""}}let eg=(a,n)=>{let s=t,d={EdYik:function(h,p){return h===p}};if(e[s(1602)](s(943),e.MDhpN))return _0x538532&&majifP.EdYik(!0,_0x3c56eb[s(1280)]);switch(a){case e[s(615)]:case e[s(1016)]:return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class tg{constructor(n){let s=t;this[s(425)+s(889)]=n,this.count=0}addCount(){let n=t;if(e.kJsIl!==e[n(992)]){let d=""+_0x3587ea[n(154)](),h=_0x164283||(_0x4b5737=e[n(1575)](_0x18a8fc,_0x54e873)),p=_0x1a1792[n(437)]()[n(514)](16)[n(1039)](-6);return e[n(299)](e[n(194)]("02"+d,h),p)}else this[n(539)]++}["checkRea"+t(1615)+"nt"](){let n=t;if(e[n(883)](e.vCMFI,n(254)))JnLZEK[n(1120)](JnLZEK[n(1370)],typeof _0x29d2a4)&&_0x514ec2[n(514)+n(1104)]&&_0x157274["definePr"+n(1030)](_0x15b15c,_0x3120a9["toString"+n(1104)],{value:JnLZEK[n(1617)]}),_0x4f2ccc[n(1117)+n(1030)](_0x27d240,JnLZEK[n(397)],{value:!0});else return this[n(539)]>=this[n(425)+n(889)]}["resetCou"+t(1317)](n=0){let s=t;this[s(425)+"ount"]=n,this[s(539)]=0}}async function ng(a){let n=t,s={OsieW:function(d,h){return e[ne(654)](d,h)},xJJVS:e.VHIYx,NXfvd:e[n(736)],kvnAQ:n(362)+n(1267),lZkXZ:function(d,h){return d+h},CMaQU:e[n(1089)]};return new Promise(d=>{let h=n;if(!sr)return d(s[h(903)]);try{let p=document[h(1296)+"ement"](s[h(1158)]);window[h(1097)+"JSONP"]=E=>{let _=h;document[_(1607)]["removeCh"+_(352)](p),window.frontierJSONP=void 0,s[_(712)](d,E&&E[_(1352)]||s[_(903)])},p.type=s[h(1108)],p[h(854)]=s[h(1113)](a[h(533)](/^ws/,s[h(376)]),h(381)+"ack=fron"+h(552)+"P");try{document[h(1607)][h(580)+"ild"](p)}catch{document[h(1607)][h(1300)+h(352)](p)}}catch{window["frontier"+h(1512)]=void 0,s.OsieW(d,s[h(903)])}})}function cn(a,n,s){let d=t;if(e[d(338)](d(629),e[d(985)]))return!!a?.[d(1129)](h=>h[d(1151)]===n&&h[d(1316)]===s);if(_0x1e9d2d===JnLZEK[d(537)])return _0x31e845[d(873)](_0x51ad2c);if(JnLZEK.HoeBn(_0x450ac8,JnLZEK[d(534)]))return _0x429ea0[d(715)+d(308)]||_0x4312c0[d(873)](_0x1fd3bb);if(JnLZEK[d(1469)](_0xe46bcb,JnLZEK.jxOkN))return _0x488298["objectSt"+d(308)][1]?void 0:_0x4b6ce6.objectStore(_0x31abda[d(715)+d(308)][0])}function or(a,n){let s=t;if(e.BGvBO(e[s(1360)],e.FdyaF))return a?.[s(1129)](d=>d[s(1151)]===n)?.value;if(e[s(452)](_0x47a636,_0x2023eb))return _0x1976df?_0x53fca2:_0x887826;if(_0x46506a){if(e[s(839)](_0x4c14e6,_0x57a237))return _0xbf0667}else{if(_0x5e41a3<=-_0x141924)return _0x3d7f1c;if(e[s(194)](_0x111591,1)>=_0x4b2314)return _0x1f2b5b}return _0x469709[s(456)](e[s(1449)](_0x29a6d8,_0x4ee74f)|0,e.bSJXC(e[s(677)](_0x36583e,_0x5b3fe5),0),_0x4e0e65)}let Ia=null;async function rg(){let a=t;return Ia||(Ia=Promise[a(1164)]()[a(1496)](Mt[a(597)](Mt,e[a(156)]))),Ia}class ig extends va{constructor(n,s){let d=t;super(),this._dbName=n,this[d(1242)]=s,this[d(1555)]=void 0,this[d(749)+d(354)]=null}async[t(487)](){await this[t(1573)]()}async _init(){let n=t;if(!this[n(1555)]){if(this[n(749)+n(354)])return this[n(749)+n(354)];try{if(e[n(476)](e[n(1504)],e.FgNwb)){let s=_0x41d567[n(857)];if(e[n(1066)](e[n(598)](s,_0x246906),_0x579432[n(182)]))throw new _0x5226fa(e[n(467)]);return _0x1c7873[n(857)]+=_0x2d9327,s}else{let s=this[n(211)],d=this[n(1242)];this["_initPro"+n(354)]=(async()=>{let h=n,{openDB:p}=await e[h(358)](rg);this[h(1555)]=await p(h(1097)+"_"+s,1,{upgrade(E){let _=h;E[_(1562)+_(1162)+"e"](s,{keyPath:d})}})})(),await this[n(749)+"mise"]}}catch(s){console[n(569)](s)}finally{if(n(379)===e.AUAZX)this[n(749)+n(354)]=null;else if(_0x2fbb91=_0xab9e13[n(291)+"At"](_0x186829),e[n(434)](_0x5f548a,128))_0x4cb6c1[_0x1ceb4f++]=_0x3d1ce2;else if(_0xe2d31a<2048)_0x39ea66[_0x4de5e7++]=e[n(546)](_0x11e0f,6)|192,_0x5c518f[_0x149d43++]=e[n(658)](e[n(295)](63,_0x271f4c),128);else if(e.Zaslp(e[n(879)](64512,_0x102df3),55296)&&(64512&(_0x509002=_0x148b51[n(291)+"At"](e[n(1630)](_0x208c2e,1))))===56320){let s=(n(1216)+n(414))[n(1438)]("|"),d=0;for(;;){switch(s[d++]){case"0":_0x464d62[_0x3881e6++]=e[n(940)](e[n(936)](e[n(546)](_0x392e5b,12),63),128);continue;case"1":++_0x4f5094;continue;case"2":_0x2f0d87=e[n(598)](65536+e[n(805)](e.LBAlQ(1023,_0x206e23),10),1023&_0x365c5c);continue;case"3":_0x540f83[_0x4f34bb++]=e.OdexW(e.mSTcN(_0x4a2ba8,6)&63,128);continue;case"4":_0x31c2fc[_0x48438c++]=e[n(1393)](e[n(377)](_0x14eba7,18),240);continue;case"5":_0x2464c4[_0x14280a++]=e[n(1623)](e[n(1596)](63,_0x5328d8),128);continue}break}}else _0x3cbd10[_0xd7697b++]=e[n(522)](_0x5ca353>>12,224),_0x113518[_0x2030e1++]=e[n(760)](e[n(936)](_0x5f351d>>6,63),128),_0x565a9d[_0x22dd3f++]=e[n(742)](e.NkdMd(63,_0x59c13f),128)}}}async get(n){let s=t;try{return await this._init(),this[s(1555)]?.[s(873)](this[s(211)],n)}catch(d){console[s(569)](d)}}async set(n,s){let d=t;return await this._init(),this[d(1555)]?.[d(1563)](this[d(211)],n)}async[t(1461)](n){let s=t;try{return await this[s(1573)](),this[s(1555)]?.[s(672)](this[s(211)],n)}catch(d){console[s(569)](d)}}async[t(1477)](){let n=t;try{return await this[n(1573)](),this[n(1555)]?.[n(1477)](this._dbName)}catch(s){console.log(s)}}async keys(){let n=t;return await this[n(1573)](),this[n(1555)]?.[n(825)+"ys"](this[n(211)])}async[t(577)](){let n=t;return await this[n(1573)](),this[n(1555)]?.getAll(this[n(211)])}async[t(1288)](){let n=t;try{this._qosDB?.close(),this[n(1555)]=void 0}catch(s){console.log(s)}}get[t(984)](){let n=t;try{if(e[n(922)](e[n(1144)],n(477)))return!!this[n(1555)];JnLZEK[n(1115)](_0x38f8dd,_0x1b213f[n(709)]||new _0x2e6341(JnLZEK.lBNxr,JnLZEK[n(1146)])),_0x549a7f()}catch(s){return console[n(569)](s),!1}}}class sg{constructor(n,s){let d=t;this[d(886)]=n,this[d(1495)]=s,this[d(1555)]=localStorage}async[t(487)](){}get[t(1088)](){return"frontier_"+this[t(886)]}async[t(873)](n){let s=t,d=this[s(1555)][s(375)](this[s(1088)]);return JSON.parse(e[s(519)](d,"{}"))[n]}async[t(1041)](n,s){let d=t;if(d(806)===d(301))this[d(1020)+d(668)]();else{let h=this[d(1555)][d(375)](this[d(1088)]),p=JSON[d(696)](e[d(519)](h,"{}"));return p[s||n[this[d(1495)]]]=n,this[d(1555)][d(1287)](this[d(1088)],JSON.stringify(p)),s||n[this[d(1495)]]}}async[t(1461)](n){let s=t,d=this._qosDB[s(375)](this[s(1088)]),h=JSON[s(696)](e.SyGdB(d,"{}"));return h[n]=void 0,this[s(1555)][s(1287)](this[s(1088)],JSON[s(737)+"y"](h))}async[t(1477)](){return this._qosDB.clear()}async[t(852)](){let n=t,s=this[n(1555)].getItem(this._prefix),d=JSON.parse(s||"{}");return Object.keys(d)}async[t(577)](){let n=t,s=this[n(1555)][n(375)](this._prefix),d=JSON[n(696)](e[n(519)](s,"{}"));return Object[n(1430)](d)}[t(1288)](){return Promise[t(1164)]()}get[t(984)](){return!!this[t(1555)]}}class og{constructor(n,s){let d=t;this._DBName=n,this[d(1495)]=s,this[d(1555)]=Dn?tt:ti?wx:null}async[t(487)](){}get[t(1088)](){return"frontier_"+this._DBName}async get(n){let s=t,d=this[s(1555)][s(1139)+s(1546)](this[s(1088)]);return JSON.parse(e[s(519)](d,"{}"))[n]}async set(n,s){let d=t,h=this[d(1555)][d(1139)+d(1546)](this[d(1088)]),p=JSON.parse(e[d(519)](h,"{}"));return p[s||n[this[d(1495)]]]=n,this[d(1555)][d(727)+d(1546)](this[d(1088)],JSON[d(737)+"y"](p)),s||n[this[d(1495)]]}async[t(1461)](n){let s=t;if(e.DlvfX(e[s(1252)],e[s(584)]))_0xd1034c=_0x47f834[e[s(594)](e[s(959)](_0x32d791,_0x2b19ac),1)],_0x2ad6ba=_0x27b566[e[s(460)](e.pgKOk(_0x2f5271,_0x1af3e7),2)],_0x4f677c=_0xecf220[e.HDsVv(e[s(262)](_0x5c69cd,_0x293b93),3)],e[s(1341)](e[s(1128)](_0x83d08|_0x5e0604<<8,e.OpPBV(_0x22452b,16)),12632256)!==8421504?_0x168359+=_0xf4d938:(_0x21027f=e[s(351)](e[s(928)](e[s(863)](e[s(427)](7&_0x574fff,18),(63&_0x552d00)<<12),e[s(936)](63,_0x3cb272)<<6),e[s(1329)](63,_0x2c9c3d)),e[s(1479)](_0x50fe38,65536)||e.pdpNr(_0x4d5f1c,1114111)?_0x20d763+=_0x521db2:(_0x1fed56-=65536,_0x1e7587+=e[s(1307)](_0x25b06a,e[s(523)](e[s(1071)](_0x187428,10),55296),e.KFrTF(1023&_0x288d7c,56320)),_0x14ff7c+=3));else{let d=this[s(1555)][s(1139)+"geSync"](this[s(1088)]),h=JSON[s(696)](e[s(1626)](d,"{}"));return h[n]=void 0,this[s(1555)][s(727)+s(1546)](this[s(1088)],JSON[s(737)+"y"](h))}}async[t(1477)](){let n=t;return this._qosDB[n(1295)+n(166)]()}async[t(852)](){let n=t,s=this._qosDB[n(1139)+"geInfoSync"](this[n(1088)]),d=JSON[n(696)](s||"{}");return Object[n(852)](d)}async[t(577)](){let n=t,s=this[n(1555)][n(1139)+n(430)+"nc"](this[n(1088)]),d=JSON[n(696)](s||"{}");return Object[n(1430)](d)}[t(1288)](){return Promise[t(1164)]()}get[t(984)](){return!!this[t(1555)]}}function vl(a,n){let s=t;if(e.SyGdB(Dn,Dn))return new og(a,n);if((sr||ni)&&e[s(1370)]!=typeof indexedDB)return new ig(a,n);if((sr||ni)&&e.LPJQv(s(946)+"d",typeof localStorage))return new sg(a,n);throw new Error(e.Dlncr)}class ag{constructor(){let n=t,s={nEZrD:e[n(1285)],lDFaU:e[n(461)],MTKcq:function(d,h){return d===h},zUdmL:function(d,h){return e[n(298)](d,h)},JFuRd:e[n(202)]};if(e[n(1635)](e[n(1542)],e.ZGdjt))this[n(1020)+n(234)+"Id"]=null,this[n(1020)+"l"]=36e5,this[n(1555)]=vl(e[n(1031)],e.mzPlE);else{let d=s.nEZrD[n(1438)]("|"),h=0;for(;;){switch(d[h++]){case"0":this[n(1306)+n(720)]();continue;case"1":if(!this[n(643)])return void this._debug(s[n(823)]);continue;case"2":this["_dropGlo"+n(617)+n(1389)]();continue;case"3":this[n(1397)+n(1068)]();continue;case"4":this[n(155)+n(372)+"t"](_0x2f46e7,_0x4dc55f);continue;case"5":this[n(278)+n(1585)]?.[n(1288)]();continue;case"6":if(s[n(1107)](this[n(643)][n(919)+"te"],this[n(462)])||s[n(1298)](this[n(643)][n(919)+"te"],this[n(906)]))return void this[n(937)](s[n(833)]);continue;case"7":this["_readyCl"+n(1335)]=!0;continue}break}}}async _intervalFlush(){let n=t;e[n(1318)](clearInterval,this[n(1020)+n(234)+"Id"]),this[n(1020)+"lTimeoutId"]=e[n(1399)](setInterval,()=>{this[n(1241)+"ired"]()},this[n(1020)+"l"])}async[t(487)](){let n=t,s={YzoSa:function(d,h){return e.wKoMn(d,h)},scLRs:function(d,h){return e.cmraF(d,h)},wwxpy:function(d,h,p){return e[ne(175)](d,h,p)}};if(e[n(279)](e[n(1485)],e.znhwO))return ZSxePV.YzoSa(ZSxePV[n(369)](_0x4c84aa,8)[n(1263)]("0"),ZSxePV[n(1253)](_0x1f7336,_0x28b2ef,10)[n(514)](2))[n(1039)](-8);await this._qosDB[n(487)]()[n(1496)](()=>{let d=n,h={VaaCi:function(p,E){return e[ne(1332)](p,E)}};if(e[d(327)]==="pycsv"){let p=new _0x278e61(Zgyshm[d(1215)](2,_0x3aba74));p[d(1041)](_0x1ece4e),_0x46b5bf[d(1177)]=p}else this[d(1020)+d(668)]()})}async[t(1241)+t(479)](){let n=t;(await this[n(1555)]?.[n(577)]()||[])[n(862)](({timestamp:h})=>h<Date[n(154)]())[n(1333)](h=>{let p=n;this._qosDB?.[p(1461)](h[p(511)+"id"])})}async[t(1461)](n){let s=t;return this[s(1555)]?.[s(1461)](n)}async[t(1041)](n,s){let d=t;return e[d(675)](e.YxKVK,e[d(1321)])?this[d(1555)]?.[d(1041)]({message_id:n,timestamp:s}):_0x393a5a?.[d(1129)](h=>h[d(1151)]===_0x5ac7af)?.[d(1316)]}async[t(873)](n){return this[t(1555)]?.get(n)}async[t(1288)](){let n=t;clearInterval(this[n(1020)+n(234)+"Id"]),await this._qosDB?.[n(1288)]()}get isReady(){let n=t;return e[n(186)]!=="nPEVV"?!!this[n(1555)]:this[n(1555)]?.[n(984)]}}function Aa(a){let n=t;if(e[n(215)](e[n(1308)],e.tzlHD)){let s=!!this[n(1045)][n(152)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let d=e.FKWUH(cn,a[n(1645)][n(688)],e[n(413)],"2"),h=d&&cn(a[n(1645)][n(688)],n(1130)+n(774)+"ck","1"),p=d&&e[n(1176)](cn,a[n(1645)][n(688)],e[n(1633)],"1"),E=p?e[n(626)](or,a[n(1645)][n(688)],n(1130)+n(1450)+"sgid")?.[n(1438)](",")[n(862)](Boolean)||[]:[];return{enabled:s,isQoSMessage:d,isQoSAck:h,isAckCleanupMessage:p,ackMsgIds:E}}else this[n(425)+"ount"]=_0x44b723,this.count=0}async function Sl(){let a=t;return this[a(278)+a(1585)]||(this[a(278)+a(1585)]=new ag),this[a(278)+a(1585)][a(984)]||await this._QoSManager.openDB(),this[a(278)+a(1585)]}async function cg(a,n){let s=t,{enableAutoAck:d}=this._options,h=cn(a.message[s(688)],"need_ack","1"),p=e[s(1491)](cn,a.message[s(688)],e[s(495)],"1"),E=Aa.call(this,a);if(e[s(869)](d,h)){let{SeqID:_,LogID:m,service:k,LogIDNew:N,method:M}=a[s(1645)];this._sendAck({SeqID:_,LogID:m,LogIDNew:N,service:k,method:M,headers:[{key:e[s(495)],value:"1"},{key:e[s(442)],value:e[s(1196)](N,"")},{key:e[s(1264)],value:"0"}]})}p&&!E[s(1110)]&&this[s(1291)+s(1217)+"ageEvent"](a),e[s(535)](n)}async function dg(a,n){let s=t;this[s(937)](e.lNkaW,a[s(1645)]),n()}async function lg(a,n){let s=t,d=e[s(602)](sn,await e.kRPPn(El,a.data));try{if(e[s(1423)](d[s(849)],Uint8Array)){let h=e[s(520)](this[s(1045)][s(1521)+s(583)],Object)?{force:!!this._options["payloadE"+s(583)].force,encoding:this[s(1045)][s(1521)+s(583)][s(1131)]?this[s(1045)]["payloadE"+s(583)].encoding[s(533)](/\s/g,"")[s(1376)+s(1384)]():""}:{force:!1,encoding:this[s(1045)][s(1521)+s(583)]?this[s(1045)][s(1521)+s(583)].replace(/\s/g,"")[s(1376)+s(1384)]():""},p=d[s(1521)+s(583)]?d.payloadEncoding.replace(/\s/g,"")[s(1376)+s(1384)]():"",E=e[s(780)](this[s(1045)][s(1310)+s(403)],Object)?{force:!!this[s(1045)][s(1310)+s(403)].force,type:this[s(1045)][s(1310)+s(403)][s(1481)]?this._options[s(1310)+"ype"][s(1481)][s(533)](/\s/g,"")[s(1376)+s(1384)]():""}:{force:!1,type:this[s(1045)][s(1310)+s(403)]?this[s(1045)][s(1310)+s(403)][s(533)](/\s/g,"")[s(1376)+"ase"]():""},_=d[s(1310)+s(403)]?d[s(1310)+"ype"][s(533)](/\s/g,"")["toLowerC"+s(1384)]():"",m=E[s(409)]?E.type:_||E[s(1481)],k=h[s(409)]?h[s(1131)]:p||h[s(1131)],N=[e[s(1026)],e[s(986)],e[s(1214)],e[s(1382)]],M=[e[s(932)],e[s(1017)]];this._options[s(579)+"ansformT"+s(669)+"ad"]&&N.includes(m)&&(!k||M[s(983)](k))?d[s(1387)+s(1119)]=e[s(457)](bl,d[s(849)],0,d[s(849)][s(330)+"th"]):d[s(1387)+s(1119)]=""}else d[s(1387)+s(1119)]=""}catch(h){d[s(1387)+s(1119)]="",console[s(569)](h)}a[s(1645)]=d,e[s(535)](n)}function ug(a,n,s){let d=t,h=e[d(702)](s,8192),p=e[d(1091)](h,1),E=null,_=h;return function(m){let k=d;if(e[k(1428)](e[k(493)],e[k(493)]))this[k(749)+k(354)]=null;else{if(m<1||e[k(257)](m,p))return a(m);e[k(470)](e[k(1437)](_,m),h)&&(E=e[k(1138)](a,h),_=0);let N=n[k(725)](E,_,_+=m);return e[k(1202)](7,_)&&(_=e[k(522)](7,_)+1),N}}}let fg=4294967295;function hg(a,n,s){let d=t;return e.ShlQU(RangeError,e[d(481)](e[d(1654)](e.gXlhD(e[d(599)],a),e[d(855)]),e[d(519)](n,1))+e[d(711)]+s)}function xg(a,n,s){let d=t;if(e[d(269)](s,fg))throw new Error(d(250)+d(1105)+"e");let h=3;for(;e[d(503)](h,0);){let p=e[d(1067)](255,s);Ta(p,a,e[d(1200)](n,h)),s>>>=8,h--}return n+4}function pg(a,n){let s=t,d=0,h=n,p=e[s(713)](n,4);for(;h<p;){let{value:E,offset:_}=e.NdZXa(ka,a,h);h=_,d=e[s(1189)](e[s(1272)](d,8),0),d+=E}return{value:d,offset:p}}function gg(a,n,s){let d=t,h=e[d(206)].split("|"),p=0;for(;;){switch(h[p++]){case"0":if(n.write)return n[d(1463)](a,s)+s;continue;case"1":return e.PwVhN(e[d(1411)](Sa,a,n,s),s);case"2":if(e[d(226)](a.length,40))return e[d(611)](e[d(952)](Sa,a,n,s),s);continue;case"3":if(!a)return s;continue;case"4":if(n.utf8Write)return e[d(517)](n.utf8Write(a,s),s);continue}break}}function mg(a,n){let s=t,d=new fe(e.fyjar(e[s(543)](e[s(1473)](a[e[s(273)](n,4)],24),e.MFNnq(a[e[s(506)](n,5)],16))|e[s(1473)](a[e.EAwLN(n,6)],8),a[e.fyeCi(n,7)]),e[s(940)](e[s(1418)](a[e[s(1209)](n,0)]<<24,e[s(1415)](a[e.ODYfP(n,1)],16))|e[s(418)](a[e.pzssb(n,2)],8),a[n+3]),!0);return n+=8,{value:d,offset:e[s(316)](n,8)}}function wg(a,n,s){let d=t,h=a[d(661)],p=a[d(1601)];return n[s]=p>>>24,n[e.gXlhD(s,1)]=e[d(968)](p,16)&255,n[e[d(1654)](s,2)]=e[d(1380)](e[d(821)](p,8),255),n[e.gXlhD(s,3)]=e[d(1369)](255,p),n[s+4]=e[d(1091)](h,24),n[s+5]=e[d(416)](e[d(756)](h,16),255),n[e[d(988)](s,6)]=e[d(1329)](e[d(659)](h,8),255),n[s+7]=e[d(1619)](255,h),s+=8,s}function ka(a,n){let s=t;return a[s(844)+"8"]?{value:a[s(844)+"8"](n),offset:e.pOFrp(n,1)}:{value:e[s(652)](255,a[n]),offset:e[s(1269)](n,1)}}function Ta(a,n,s){let d=t;return n[d(815)+"t8"]?n[d(815)+"t8"](a,s):n[s]=e.sKZcO(255,a),s+1}let _g=function(a){return new Uint8Array(a)},yg=e[t(1370)]!=typeof Buffer?Buffer[t(1413)+t(1432)]:e[t(923)](ug,_g,Uint8Array[t(1292)+"e"][t(264)]);(()=>{let a=t;if(e[a(1602)](e[a(1134)],e.yyIlM)){let n=4294967295;return function(s,d,h=!0){let p=a,E=e.Xwwlm[p(1438)]("|"),_=0;for(;;){switch(E[_++]){case"0":n=e.DxoZm(n,e.diFzF(e[p(967)](127,s[d]),14))>>>0;continue;case"1":n=(127&s[d])>>>0;continue;case"2":n=e[p(733)](n|e[p(1584)](127&s[d],7),0);continue;case"3":if(e[p(221)](s[d++],128))return{value:h?n:e[p(975)](0,n),offset:d};continue;case"4":if(e[p(226)](s[d++],128))return{value:h?n:e[p(216)](0,n),offset:d};continue;case"5":if(e[p(221)](s[d++],128))return{value:h?n:e[p(1516)](0,n),offset:d};continue;case"6":if(e[p(221)](s[d++],128))return{value:h?n:0|n,offset:d};continue;case"7":n=e[p(971)](n|e[p(620)](e[p(292)](15,s[d]),28),0);continue;case"8":n=e[p(370)](n,e[p(1268)](127&s[d],21))>>>0;continue;case"9":if((d+=5)>s[p(1391)])throw d=s[p(1391)],e[p(952)](hg,d,10,s[p(1391)]);continue;case"10":if(e.AQAAW(s[d++],128))return{value:h?n:e.wBxuQ(0,n),offset:d};continue;case"11":return{value:h?n:0|n,offset:d}}break}}}else return _0x4c395d+=_0x1bad94&&_0x5b3a2b[a(330)+"th"]||0,_0x2643b9})();let bg=16,Ra=32;function Eg(a){let n=t,s=0,d={};for(let h=0;h<a[n(1391)];h++)d[a[h][n(1588)+"ame"]]=e.MSZvr(yl,a[h]["cursor_n"+n(388)]),s+=e[n(1237)](14,d[a[h][n(1588)+n(388)]]);return[s,d]}function Il(a,n,s){let d=t,[h,p]=e.ARuFn(Eg,a),E=e[d(1077)](yg,h),_=0;return a[d(1333)](m=>{let k=d,N=e.KmZuI[k(1438)]("|"),M=0;for(;;){switch(N[M++]){case"0":_=e[k(1414)](xg,E,_,m.service||0);continue;case"1":console[k(569)]("curvalue",_);continue;case"2":_=e.RLFTz(Ta,p[m[k(1588)+k(388)]],E,_);continue;case"3":console[k(569)](e[k(1591)],_);continue;case"4":_=Ta(0,E,_);continue;case"5":_=e[k(952)](wg,fe[k(407)+"er"](m[k(878)]||n),E,_);continue;case"6":console[k(569)](k(1600)+k(766),_);continue;case"7":console[k(569)]("name",_);continue;case"8":_=e[k(1414)](gg,m[k(1588)+k(388)],E,_);continue;case"9":console.log(e[k(723)],_);continue;case"10":console.log(e[k(247)],m,m[k(622)]);continue}break}}),{frameType:Ra,headers:[{key:e[d(1257)],value:s}],payload:E}}function vg(a){let n=t;if(e[n(1602)](n(871),e[n(933)]))_0x128f09&&this[n(1035)+n(339)][n(424)+n(1032)+"Name"](_0x1bedb5);else{let s=0,d=[];for(;s<a[n(330)+"th"];)if(e[n(1010)](e.GiCOs,n(1274)))this.on(_0x280a54,_0x207226);else{let{offset:h}=e[n(1122)](ka,a,s);s=h;let p={cursor_name:"",cursor:0,service:0},{value:E,offset:_}=pg(a,s);p[n(622)]=E,s=_;let{value:m,offset:k}=e[n(1085)](ka,a,s);s=k,p.cursor_name=e.Lqyjr(bl,a,s,s+m),s+=m;let{value:N,offset:M}=e[n(167)](mg,a,s);p[n(878)]=N[n(453)](),s=M,d.push(p)}return d}}function Sg(){let a=t;return{frameType:Ra,headers:[{key:e[a(1257)],value:e[a(570)]}],payload:void 0}}class Ig{constructor(n,s,d){let h=t;if(e[h(389)](e[h(561)],e.RPuxR)){let p=this[h(1570)+h(787)]?.["getCurre"+h(784)+"nt"]();this._debug(h(1618)+p+" timeout"),this[h(450)+h(1254)](1001,e.MjSDB,!0)}else this[h(236)+"ameSpace"]=n,this[h(1053)+h(1350)]=s,this["_message"+h(738)]=d,this[h(1555)]=e[h(1616)](vl,this[h(236)+h(901)],"cursor_n"+h(388))}async[t(487)](){await this[t(1555)].openDB()}async getCursors(){let n=t;if(!this._qosDB.isReady)return;let s=this[n(944)+n(738)],d=await this._qosDB[n(577)]();switch(console[n(569)](n(754)+n(258),d),s){case e[n(1018)]:return d&&d.length?Il(d,0,this[n(1053)+n(1350)]):void 0;case e.hwJZT:return;case e[n(1159)]:return d&&d[n(1391)]?e.lEcJP(Il,d,0,this["_cursorF"+n(1350)]):Sg()}}async[t(1041)](n,s,d){let h=t;return console[h(569)](h(789),n,s,d),this[h(1555)].set({cursor_name:n,cursor:s,service:d})}async[t(1239)+"rs"](n){let s=t,d={xDibl:function(h,p){return h+p}};if(e[s(1203)](e[s(994)],s(633))){let h=_0x5589bb(_0x248eba),p=_0x3c6c22.limit;return _0xb29509[s(182)]=TIhorW[s(1529)](_0x46db4b[s(857)],h),p}else{let h=vg(n);for(let p of h)console[s(569)](s(170)+"r",h),await this[s(1555)][s(1041)](p)}}async[t(873)](n){let s=t;return(await this._qosDB[s(873)](n))?.[s(878)]}async[t(1288)](){let n=t;if(e[n(472)](e[n(881)],e[n(881)]))return(this[n(345)+"rs"][_0x5c60e6]||(this[n(345)+"rs"][_0x239f32]=[]))[n(1273)]({fn:_0x16f534,ctx:_0x4f9b44||this}),this;await this[n(1555)][n(1288)]()}[t(424)+t(1032)+t(1536)](n){let s=t;this[s(1053)+s(1350)]=n}get[t(984)](){let n=t;return this._qosDB[n(984)]}}let Ag=t(860)+t(650);async function Al(a){let n=t;if(!this[n(1045)][n(152)+"S"])return null;let{aID:s,fpID:d,messageStrategy:h}=this[n(1045)],p=e[n(966)](a,Ag);try{return this[n(1035)+n(339)]?a&&this[n(1035)+n(339)][n(424)+n(1032)+n(1536)](a):this[n(1035)+"anager"]=new Ig(d+"_"+s+"_"+p,p,h),this[n(1035)+"anager"][n(984)]||await this["_cursorM"+n(339)][n(487)](),this[n(1035)+"anager"]}catch{if(e[n(1428)](e[n(454)],n(346)))return null;{let E=_0x20613b(_0x364061,_0x568b74[n(1391)]);_0x49fffe.bytes[n(1041)](_0x4953f4,E)}}}async function kg(a,n){let s=t,d=e[s(1411)](cn,a[s(1645)][s(688)],e[s(582)],"-1"),h=cn(a[s(1645)][s(688)],e[s(495)],"1"),p=e.NSMLm(or,a[s(1645)][s(688)],e[s(1161)]),E=e.xTurG(Number,or(a[s(1645)][s(688)],e[s(753)]))||0,_=Aa.call(this,a),m=e[s(207)](cn,a[s(1645)][s(688)],e[s(1349)],"2"),k=or(a.message[s(688)],e[s(300)]),N=e.qNCTk(Number,or(a[s(1645)][s(688)],s(864)+s(231)+"ue"));if(_[s(1110)])return e[s(1290)](n);let M=_[s(189)+s(187)]?await Sl[s(725)](this):null;if(e[s(528)](a[s(1645)][s(622)],0)&&h&&!d||e[s(324)](a[s(1645)][s(622)],0)){if(p&&_[s(189)+s(187)]&&M)return!!!await M[s(873)](p)&&(this[s(1291)+"hMessage"+s(1492)](a),await M.set(p,e[s(1038)](Date[s(154)](),E))),e[s(358)](n);if(m){let K=await Al[s(725)](this);if(!K)return this[s(1291)+s(1029)+"Event"](a),e[s(1337)](n);let W=await K[s(873)](k)??-1;if(e[s(1192)](W,N))this["_dispatc"+s(1029)+s(1492)](a),K.set(k,N,a[s(1645)][s(622)]);else throw new Error("recevied"+s(900)+s(976)+N+(s(538)+s(710)+s(1519)+"r ")+W);return e.rUezO(n)}return this[s(1291)+s(1029)+"Event"](a),e.rUezO(n)}}async function Tg(a,n){let s=t,d=Aa[s(725)](this,a);if(!d[s(189)+s(187)])return n();let h=await Sl[s(725)](this);if(d[s(612)+s(1334)+"age"]&&d.ackMsgIds.length)for(let p of d.ackMsgIds)await h[s(1461)](p);n()}async function Rg(a,n){let s=t,d=e[s(1227)](a[s(1645)][s(277)+"e"],bg),h=e.GqctZ(a[s(1645)][s(277)+"e"],Ra);if(!d&&!h)return e.PsKcr(n);let p=e[s(665)](or,a[s(1645)][s(688)],s(1425)+s(591));if(!p)return e[s(400)](n);let E=await Al[s(725)](this,p);if(!E)return n();if(d){let _=await E[s(948)+"rs"](),m={frameType:_?.[s(277)+"e"],SeqID:fe.fromNumber(this._seqId++),LogID:fe[s(407)+"er"](this._options[s(439)+"erator"]()),service:9e3,method:5,headers:_?.[s(688)],payload:_?.[s(849)]},k=S(m);this[s(643)]&&this[s(643)][s(919)+"te"]&&this._ws[s(463)](k)}if(h){let _=a[s(1645)][s(849)];_&&E.setCursors(_)}}let Pg=async function(a,n){let s=t;this._isInit=!1,e[s(1244)](clearTimeout,this[s(1487)+s(939)+s(392)]),e[s(811)](n)},Dg=async function(a,n){let s=t;if(!this[s(643)]||e.exjBE(this[s(643)][s(919)+"te"],this.OPEN))return e.dMhip(n);let{pingInterval:d}=this[s(1045)];this[s(1570)+s(787)]?.[s(875)+s(1251)+s(905)]();for(let p=0;p<this[s(944)+s(162)][s(1391)];p++){let E=this["_message"+s(162)][p];if(this[s(643)][s(919)+"te"]===this[s(981)]&&e[s(1377)](null,E))this._ws&&this._ws[s(463)](E),this[s(944)+"Queue"][p]=null;else break}this[s(944)+s(162)]=this[s(944)+s(162)].filter(p=>!!p),this._pingPongTimeoutId=e[s(626)](setTimeout,()=>this[s(290)](),d),this[s(1291)+s(605)+"nt"](a),this._isBrowser&&this[s(643)]&&(this[s(643)][s(184)+"pe"]=this[s(674)+"ype"]);let h=this[s(1570)+"tManager"]?.[s(1207)+"ntEndpoint"]();this[s(937)]("open "+h+s(1467)),e.XiyqK(n)},Cg=async function(a,n){let s=t;if(s(1311)!==e.NJmRm){let d=this["_endpoin"+s(787)]?.[s(1207)+s(784)+"nt"]();this[s(937)]("open "+d),e.dMhip(n)}else{let d=_0xd060a7.split(":");_0x222537&&(_0x598c98=d[s(1391)]),_0x1ede87+=d[s(1391)];for(let h=0;h<d[s(1391)];h++)if(e[s(1483)](4,d[h][s(1391)])){let p=_0x19758e[s(426)+"g"](0,e[s(494)](4,d[h].length)),E=p[s(1351)](d[h]);_0x4a746e[s(1273)](E)}else _0x403b8f.push(d[h]);_0x56e885=!1}};class Og extends va{constructor(n){let s=t,d={BbmOx:e[s(955)],naHdF:function(_,m,k,N){return e.OgvEk(_,m,k,N)},SmiTj:function(_,m,k){return e[s(891)](_,m,k)},UyXNx:e[s(555)],GdZXW:function(_,m){return e[s(1319)](_,m)},SRoWD:function(_,m){return e.TFqPN(_,m)},Ragbk:function(_,m){return e[s(1106)](_,m)},Ytyhd:e[s(692)],VLPTk:e[s(951)],ESlWW:e[s(604)],xoWyn:function(_,m,k){return _(m,k)},SQyRY:function(_,m){return e[s(1197)](_,m)},RLlbJ:e[s(217)],UZswV:function(_,m,k){return _(m,k)},fiwDe:function(_){return e[s(1290)](_)},KLnlI:function(_,m){return e.LWLWg(_,m)},MBifE:e.NZtGm,URXov:function(_,m,k){return e[s(1359)](_,m,k)},vfHJT:e[s(769)],YYhnD:function(_,m){return _!==m},PJNWP:function(_,m){return e.dFdPK(_,m)},OHoqD:e[s(353)],mefrI:function(_,m){return e[s(1138)](_,m)},XYNwG:function(_,m,k){return e[s(448)](_,m,k)},ZJdcy:function(_,m,k){return _(m,k)}};super(),this[s(1218)+s(996)+s(998)]=!0,this._isBrowser=sr,this[s(1126)]=Jp,this[s(209)+"T"]=Dn,this._isMiniWX=ti,this[s(482)+"r"]=ni,this[s(944)+s(162)]=[],this[s(1570)+s(787)]=null,this[s(979)+s(1335)]=!1,this[s(674)+s(403)]="arraybuf"+s(1234),this[s(1487)+s(642)]=!1,this["_connect"+s(939)+s(392)]=null,this[s(468)+"ctTimeou"+s(1279)]=null,this["_pingPon"+s(1416)+"Id"]=null,this[s(1403)]=0,this[s(1343)]=!1,this[s(1642)]="",this[s(278)+s(1585)]=null,this["_cursorM"+s(339)]=null,this[s(1235)+s(204)]=null,this[s(1240)+"ls"]=e[s(551)],this[s(462)]=3,this[s(1631)+"NG"]=0,this[s(981)]=1,this[s(906)]=2,this[s(649)]=_=>{let m=s;try{d[m(831)]!==d[m(831)]?this[m(1053)+"ileName"]=_0x5db396:d[m(1210)](_l,this,_,[Pg,Dg,Cg])}catch(k){let N=d.SmiTj(at,d[m(263)],{message:k[m(1645)],code:an[m(676)+"OR"],error:k});this[m(1291)+m(284)+m(1644)](N)}},this[s(851)+"ge"]=async _=>{let m=s,{pingInterval:k,pingFrequency:N}=this[m(1045)];if((d[m(1612)]("hi",_[m(1284)])&&d.Ragbk(d[m(265)],N)||d[m(193)]===N)&&(this[m(1397)+m(1068)](),this[m(1609)](d[m(214)],"success"),this["_pingPon"+m(1416)+"Id"]=d[m(1303)](setTimeout,this[m(290)][m(597)](this),k)),!d[m(1612)]("hi",_.data))try{d[m(1204)](d[m(219)],d.RLlbJ)?(_0x510042=EaAqVS[m(743)](_0x2543bc,_0x5f3eba),_0x8f061e=0):_l(this,_,[lg,cg,Tg,Rg,kg,dg])}catch(M){let K=d.UZswV(at,d.UyXNx,{message:M.message,code:an[m(728)+"ERROR"],error:M});this[m(1291)+m(284)+"ent"](K)}},this[s(1590)]=_=>{let m=s,k=this[m(1570)+m(787)]?.[m(1232)+m(1062)+"es"](),N=this[m(1570)+m(787)]?.["getCurre"+m(784)+"nt"]();if(k&&!_[m(1645)]){let M=m(1618)+N+(m(1550)+m(1445)+m(1368)+"ed");this[m(1291)+"hErrorEvent"](e.RhoqE(at,e[m(555)],{message:M,code:an[m(1385)+m(1054)+"R"],error:_}));return}this[m(643)]&&this[m(643)][m(919)+"te"]===this.OPEN&&this[m(450)+"ect"](),this[m(1291)+m(284)+m(1644)](e[m(1173)](at,"error",{message:_[m(1645)],code:an["NATIVE_E"+m(719)],error:_}))},this[s(311)]=async _=>{let m=s,k={omwoW:function(M){return d[ne(681)](M)}};this[m(1306)+"mer"](),this[m(1397)+m(1068)](),this[m(645)+m(1526)+"rs"](),this._ws=null,this[m(1487)+m(642)]=!1;let N=this["_endpoin"+m(787)]?.["checkRea"+m(1062)+"es"]();if(!N&&this[m(768)+m(436)]()&&!this[m(979)+m(1335)])if(d[m(1238)](d[m(1013)],d[m(1013)]))lhxCiL.omwoW(_0x23246b),lhxCiL.omwoW(_0x116754);else{let M=this["_endpoin"+m(787)]?.["getCurre"+m(784)+"nt"](),K=this._options[m(1547)+"tInterce"+m(469)](_[m(212)],_[m(296)]);this["_dispatc"+m(1175)+m(1644)](d[m(1460)](mt,d[m(1008)],{code:1006,reason:_[m(296)]||m(1014)+"ng faile"+m(1629)+m(1325)+m(446)+m(706)+M,willReconnect:K})),K&&this[m(1487)]();return}if(_[m(212)]!==1e3&&this[m(979)+m(1335)]){this[m(1291)+"hCloseEvent"](d[m(1028)](mt,d[m(1008)],{code:1e3,reason:m(995)})),this["_endpoin"+m(787)]?.[m(875)+"pointConfig"](),this[m(1235)+m(204)]?.["resetCou"+m(1317)]();return}if(d[m(404)](1e3,_[m(212)])&&N)if(d.PJNWP(d.OHoqD,m(240))){let M=this[m(1570)+m(787)]?.["getCurre"+m(784)+"nt"](),K=_[m(296)];K||(K=await d.mefrI(ng,this[m(1642)])),K=m(1014)+"ng failed, "+K+(m(328)+m(1250))+M+(m(515)+m(1538)+m(848)),this[m(1291)+m(1175)+"ent"](mt(d[m(1008)],{code:_[m(212)],reason:K}));let W=m(1618)+M+(m(1550)+m(1445)+"es reached");this["_dispatc"+m(284)+m(1644)](d.XYNwG(at,d.UyXNx,{message:W,code:an[m(1385)+m(1054)+"R"]})),this[m(1570)+m(787)]?.[m(875)+m(1251)+m(905)](),this[m(1235)+"sCounter"]?.[m(1500)+"nter"]();return}else return this._ws?this[m(643)].protocol:"";if(d[m(1238)](1e3,_[m(212)])&&!_[m(296)]){let M=this[m(1570)+m(787)]?.[m(1207)+m(784)+"nt"]();this[m(1291)+m(1175)+m(1644)](d.ZJdcy(mt,d[m(1008)],{code:_[m(212)],reason:m(1014)+m(701)+m(1629)+m(1325)+"n, hostn"+m(706)+M})),this[m(1570)+m(787)]?.[m(875)+"pointCon"+m(905)](),this._pingLossCounter?.[m(1500)+"nter"]();return}this[m(1291)+"hCloseEv"+m(1644)](_),this._endpointManager?.["resetEnd"+m(1251)+m(905)](),this[m(1235)+m(204)]?.["resetCou"+m(1317)]()},this.onclose=null,this[s(1520)]=null,this[s(320)+"e"]=null,this[s(634)]=null,this[s(1556)+s(1074)]=null,this[s(287)+"eAck"]=null,this[s(402)+s(618)+s(1494)+"ct"]=null,this._handleOnLine=this[s(1464)+"nLine"][s(597)](this),this[s(1464)+s(384)]=this[s(1464)+s(384)][s(597)](this),this["_handleP"+s(1007)]=this[s(497)+s(1007)].bind(this),this._handlePageShow=this[s(497)+s(536)][s(597)](this),this[s(1045)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(677)](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(951)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1159)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:p}=n,E=Array.isArray(h)?h:e.zRgrl(e.qLPTQ,typeof h)?[h]:[];if(!E||e[s(246)](0,E[s(1391)]))throw new Error(e[s(1652)]);if(!Xp(p))throw new Error(s(893)+"rovide w"+s(1443)+", WebSoc"+s(344)+s(1246)+s(408)+s(455));Object[s(1407)](this[s(1045)],n),this[s(1570)+s(787)]=new wl(E,this._options.maxRetries),this[s(1235)+"sCounter"]=new tg(this[s(1045)]["pingLoss"+s(213)]),this._options[s(834)+s(410)]&&(this[s(1343)]=!0,this._connect()),this._options["listenNetworkCha"+s(349)]&&(this[s(209)+"T"]||this[s(619)+"X"]?this["_onPageN"+s(613)+s(289)]():this[s(1342)+"er"]&&this[s(717)+s(617)+s(1389)]())}[t(1464)+t(687)](){let n=t;this._options[n(340)+"utoRecon"+n(516)]||this["_readyCl"+n(1335)]||this["_handleR"+n(1074)]()}["_handleO"+t(384)](){let n=t;if(e.plvRz(n(255),e[n(1348)])){let{offset:s}=e[n(256)](_0x56ade2,_0x17b512,_0x1a0b96);_0x4c1b83=s;let d={cursor_name:"",cursor:0,service:0},{value:h,offset:p}=_0x3b485c(_0x5611df,_0x5ea094);d[n(622)]=h,_0x4cc7c5=p;let{value:E,offset:_}=_0x16321e(_0x3e61e7,_0x32528d);_0x3ade30=_,d[n(1588)+"ame"]=e.Yjmcq(_0x2b1d14,_0x4a45aa,_0x65487a,e[n(926)](_0x40f6ec,E)),_0x22f508+=E;let{value:m,offset:k}=e.DxJsk(_0x298bc8,_0x5c3581,_0x4f90ab);d.cursor=m[n(453)](),_0x40d5ae=k,_0x47555c[n(1273)](d)}else{this[n(155)+n(372)+"t"]();let s=Ea(n(1547)+"t",{message:n(773)+n(1087)+n(1294)+"ct"});this[n(402)+n(618)+n(1494)+"ct"]&&this["onStopIm"+n(618)+n(1494)+"ct"](s)}}[t(717)+t(617)+t(1389)](){let n=t;this[n(1342)+"er"]&&window[n(1225)+n(1389)](e[n(1417)],this[n(1464)+"nLine"]),this[n(1342)+"er"]&&window[n(1225)+"Listener"](n(1058),this[n(1464)+n(384)]),this._isBrowser&&window[n(1225)+n(1389)](e[n(1484)],this._handlePageHide),this[n(1342)+"er"]&&window[n(1225)+n(1389)](e[n(1651)],this[n(497)+"ageShow"])}[t(447)+t(617)+t(1389)](){let n=t;if(n(1281)!==e[n(383)]){if(this[n(1045)][n(340)+n(1048)+n(516)]||this[n(979)+n(1335)])return;this["_handleR"+n(1074)]()}else this[n(1342)+"er"]&&window[n(765)+n(1248)+n(999)](n(1064),this._handleOnLine),this[n(1342)+"er"]&&window[n(765)+n(1248)+"ner"](e[n(1347)],this["_handleO"+n(384)]),this[n(1342)+"er"]&&window[n(765)+n(1248)+n(999)](e[n(1484)],this["_handleP"+n(1007)]),this[n(1342)+"er"]&&window[n(765)+n(1248)+n(999)](e[n(1651)],this._handlePageShow)}[t(497)+"ageHide"](n){let s=t;!n[s(1598)+"d"]&&(this[s(1342)+"er"]&&window[s(765)+s(1248)+s(999)](s(1565),this[s(497)+s(1007)]),this[s(1342)+"er"]&&window["removeEv"+s(1248)+s(999)](s(1444),this[s(497)+s(536)]),this[s(1081)]()),this[s(1342)+"er"]&&window["removeEv"+s(1248)+s(999)](e[s(1417)],this[s(1464)+"nLine"]),this[s(1342)+"er"]&&window[s(765)+s(1248)+s(999)](e[s(1347)],this[s(1464)+s(384)])}["_handleP"+t(536)](n){let s=t;n[s(1598)+"d"]&&(e[s(449)]!==e[s(449)]?_0xbb4fa[s(569)](_0x4d69f6):(this[s(768)+s(436)]()&&(!this[s(643)]||e[s(472)](this[s(643)][s(919)+"te"],this[s(981)])||this[s(643)][s(919)+"te"]!==this.CONNECTING)&&this[s(1464)+"nLine"](),this[s(1342)+"er"]&&window[s(1225)+s(1389)](e[s(1417)],this[s(1464)+"nLine"]),this[s(1342)+"er"]&&window[s(1225)+s(1389)](e[s(1347)],this[s(1464)+s(384)])))}async["_generat"+t(1190)](n){let s=t,{fpID:d,deviceID:h,bddID:p,ttwID:E,accessKey:_,aID:m,customParams:k={},enableAutoAck:N,enableQoS:M,QoSLevel:K,env:W}=this[s(1045)],he,wt,Ut;this._isBrowser||this[s(619)+"X"]||this[s(209)+"T"]?(he=location&&e[s(458)](e[s(1527)],location.protocol)?e[s(1043)]:s(1178),wt=n[s(533)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),Ut=/^wss(.*:\/\/)/[s(1543)](n)?n:""+he+wt):(he=e[s(1043)],wt=n.replace(/(^http)((?:[s]*:\/\/))/,""),Ut=/(^ws)((?:[s]*:\/\/))/[s(1543)](wt)?wt:""+he+wt);let Gt=p?s(550):E?e[s(699)]:s(639)+"d",xs=p||E||h;if(e[s(1626)](!xs,!Gt))throw new Error(e[s(1163)]);let Lg=typeof k=="function"?await k():k,Ng=W?eg(W[s(1535)],W[s(1261)]):{},Pa=Object[s(1407)]({device_platform:e[s(1330)],version_code:s(421)+"0",access_key:_,fpid:d,aid:m,[Gt]:xs,xsack:N?1:0,xaack:N?1:0,xsqos:M?1:0,qos_level:M?K:void 0,qos_sdk_version:2,...Ng},Lg),Mg=Object[s(852)](Pa).reduce((Da,Ca)=>Pa[Ca]!==void 0?""+Da+(Da?"&":"?")+Ca+"="+Pa[Ca]:Da,"");return Ut+s(1513)+Mg}async _connect(){let n=t;if(e[n(1541)](e[n(812)],e.vPzMc)){let s=e.bgTxJ[n(1438)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(e.oRkgC(_0x22a845[_0x42f36f++],128))return{value:_0x4fed06?_0x151a3a:e[n(1603)](0,_0x19d9da),offset:_0x3a6527};continue;case"1":_0x1fbeac=e.AwmVi(e.glNHC(127,_0xce6979[_0x4698ad]),0);continue;case"2":_0x37d5a4=e.VxiaX(e[n(581)](_0x5bedcb,e.UaXVu(e[n(856)](127,_0x9ad454[_0x7ba2f8]),7)),0);continue;case"3":if(e.mjPKW(_0x64f58c[_0x81c925++],128))return{value:_0x2abe3f?_0x97e209:e[n(1322)](0,_0x365fa7),offset:_0x2fe7fe};continue;case"4":_0x6d9a4b=(_0x50ef09|(127&_0x1d4871[_0x3751de])<<14)>>>0;continue;case"5":_0xc88ac=e[n(1398)](_0xf02361,e.DiopA(e[n(275)](15,_0xcd6a80[_0x5ad0f7]),28))>>>0;continue;case"6":if(_0x34d61d[_0x351eb4++]<128)return{value:_0x2d2473?_0x3cc772:e[n(1603)](0,_0xcb3073),offset:_0x20af17};continue;case"7":return{value:_0x59c134?_0x2ab871:e.UTlXR(0,_0xe0a32d),offset:_0x53577f};case"8":if(_0x13ee3b[_0x290da5++]<128)return{value:_0x3eaae5?_0x4d5a04:e[n(1094)](0,_0x43e74f),offset:_0x17f705};continue;case"9":if(e[n(858)](_0x531253[_0x24a560++],128))return{value:_0x118256?_0x4ac3ec:e[n(1624)](0,_0x1342a0),offset:_0xa819f5};continue;case"10":if((_0x133708+=5)>_0x11c0cf[n(1391)])throw _0x1f0734=_0x21ece2[n(1391)],e.Yjmcq(_0x39301d,_0x42ccca,10,_0x2fa2b1.length);continue;case"11":_0x302390=e[n(968)](_0x5289d2|e[n(610)](e.XSNaE(127,_0x3d2113[_0x3e658a]),21),0);continue}break}}else{if(this[n(1487)+"Lock"]||this[n(979)+n(1335)])return;this[n(1487)+n(642)]=!0;try{let s=this[n(1570)+n(787)]?.[n(478)+n(1406)+"ointReac"+n(1490)+n(1586)](),{timeoutInterval:d}=this[n(1045)];if(s){let p=this[n(1570)+n(787)]?.[n(1207)+n(784)+"nt"](),E=this["_endpoin"+n(787)]?.[n(1313)+n(363)+"pointAnd"+n(531)+n(870)](),_=this[n(1570)+"tManager"]?.[n(1207)+n(784)+n(698)+n(889)]();if(E){let m="connect "+p+(n(1148)+n(515)+n(1538)+n(632)+n(850)+"backup e"+n(673))+E+(n(1326)+"y"),k=e.yFHcu(at,n(709),{message:m,code:an[n(1385)+"IES_ERROR"]});this[n(937)](m),this["_dispatc"+n(284)+"ent"](k),this[n(1642)]=await this[n(1511)+"eUrl"](E),this[n(937)](n(1618)+E+" "+_+" times"),this["_removeW"+n(1526)+"rs"]()}else if(e[n(747)](n(518),n(518)))this[n(1609)](e[n(195)],_0x3ec9dc),this[n(320)+"e"]&&this[n(320)+"e"](_0x42fc89);else{let m=n(1618)+p+(n(1148)+n(515)+n(1538)+n(848));this[n(937)](m),this[n(1291)+"hErrorEv"+n(1644)](e.RyQXJ(at,e[n(555)],{message:m,code:an[n(1385)+"IES_ERROR"]}));return}}else{let p=this[n(1570)+n(787)]?.[n(1207)+n(784)+n(890)+n(1363)](),E=this[n(1570)+"tManager"]?.["getCurre"+n(784)+n(698)+n(889)]();this[n(1642)]=await this[n(1511)+n(1190)](p||""),this[n(937)](n(1618)+p+" "+E+" times"),this[n(645)+n(1526)+"rs"]()}if(this[n(1343)])this[n(1343)]=!1;else{let p=e[n(927)](Ea,e[n(1395)],{message:e[n(779)]});this[n(1556)+n(1074)]&&this["onStartR"+n(1074)](p)}let h=this[n(1570)+n(787)]?.[n(1207)+n(784)+n(698)+n(889)]()||0;e.FitIi(h,1)&&await this._wait(h-1),this[n(937)](n(1014)+"ng url: "+this[n(1642)]+(n(1152)+n(609))+this[n(1240)+"ls"]),this[n(643)]=Yp({url:this._url,protocols:[this[n(1240)+"ls"]],headers:this[n(1045)][n(1099)+"ramParams"][n(1594)+n(248)]},this[n(1045)].ws),(this[n(1342)+"er"]||this[n(482)+"r"])&&this[n(643)]&&(this[n(643)][n(184)+"pe"]=this[n(674)+n(403)]),this[n(731)+n(1597)](),this["_connect"+n(939)+n(392)]=e[n(1441)](setTimeout,this[n(913)+"ut"][n(597)](this),d)}catch(s){throw this[n(1487)+n(642)]=!1,s}}}["_clearTi"+t(720)](){let n=t;e[n(483)](clearTimeout,this[n(1487)+"ionTimeo"+n(392)]),this[n(1487)+n(939)+n(392)]=null}[t(1397)+"ngTimer"](){let n=t;clearTimeout(this[n(600)+n(1416)+"Id"]),e[n(1244)](clearTimeout,this[n(468)+n(740)+"tId"]),this[n(600)+n(1416)+"Id"]=null,this[n(468)+n(740)+n(1279)]=null}[t(937)](...n){let s=t;this[s(1045)][s(1247)]&&console[s(569)].apply(console,["FRONTIER>",...n])}[t(1034)+t(744)+"e"](n){let s=t,{initReconnectInterval:d,maxReconnectInterval:h,reconnectIntervalGrowFactor:p}=this[s(1045)],E=e.iJJHK(d,Math[s(1027)](p,e[s(203)](n,1)));return e[s(553)](E,h)?h:E}[t(290)](){let n=t;if(this[n(643)]&&e[n(200)](this[n(643)][n(919)+"te"],this[n(1631)+"NG"])){this[n(1397)+n(1068)](),this[n(600)+n(1416)+"Id"]=setTimeout(this._ping[n(597)](this),this[n(1045)][n(1653)+"rval"]);return}if(!this[n(643)]||e[n(1515)](this[n(643)][n(919)+"te"],this[n(981)]))return void this[n(716)+n(1074)]();this[n(643)]&&this[n(643)].send("hi"),this["_reconne"+n(740)+n(1279)]=e.CefJg(setTimeout,this["_handleR"+n(1074)+n(914)][n(597)](this),this._options[n(917)+n(267)+n(1482)])}[t(716)+t(1074)+"Timeout"](){let n=t;this[n(1235)+n(204)]?.[n(606)](),this.emit(e.dMoQT,e[n(874)]),this._pingLossCounter?.["checkRea"+n(1615)+"nt"]()?this[n(716)+"econnect"]():this[n(290)]()}["_navigat"+t(436)](){let n=t;return this[n(209)+"T"]||this[n(619)+"X"]?this[n(1218)+n(996)+n(998)]:(this[n(1342)+"er"]||this[n(482)+"r"])&&this[n(1045)][n(1578)+n(751)+"nged"]?navigator[n(653)]:!0}[t(716)+"econnect"](){let n=t;if(e[n(382)]!==e[n(714)]){if(!this[n(768)+"orOnline"]()||this["_readyCl"+n(1335)])return;this[n(1570)+n(787)]?.[n(875)+n(1251)+n(905)](),this[n(1235)+"sCounter"]?.["resetCou"+n(1317)](),this[n(643)]?this[n(450)+n(1254)](1001,e[n(957)],!0):this[n(1487)]()}else return new _0x1ebdce(e[n(406)](e[n(658)](e.MdpSS(e[n(1268)](_0x1e1662[4],24),_0x16f12a[5]<<16),_0xdbfc14[6]<<8),_0x317e91[7]),e[n(573)](e[n(1603)](e[n(260)](e.HONbx(_0x4b13bb[0],24),e[n(1415)](_0x354009[1],16)),_0x155f60[2]<<8),_0x466390[3]),_0x468b1e)}[t(1534)+t(613)+"ange"](){let n=t;this[n(209)+"T"]?tt["onNetwor"+n(969)+n(1305)](({isConnected:s})=>{let d=n;this[d(1218)+d(996)+d(998)]=s,s?this["_handleO"+d(687)]():this["_handleO"+d(384)]()}):this[n(619)+"X"]&&wx["onNetwor"+n(969)+n(1305)](({isConnected:s})=>{let d=n;this[d(1218)+"igatorOn"+d(998)]=s,s?this._handleOnLine():this[d(1464)+d(384)]()})}[t(771)](n){let s=t;if(e[s(157)](e[s(745)],s(964))){let d=this[s(1570)+s(787)]?.[s(1207)+s(784)+"nt"]();this[s(1291)+s(1175)+s(1644)](e[s(245)](_0x2ba5a5,e[s(769)],{code:1006,reason:s(1618)+d+(s(1148)+s(515)+"tries re"+s(848)),wasClean:!0}))}else return new Promise(d=>{let h=s;e[h(722)](setTimeout,d,this["_getInte"+h(744)+"e"](n))})}[t(450)+t(1254)](n=1e3,s="",d=!1){let h=t;this[h(643)]&&this["_destroy"+h(372)+"t"](n,s,d)}[t(913)+"ut"](){let n=t,s=this["_endpoin"+n(787)]?.[n(1207)+n(784)+"nt"]();this[n(937)](n(1618)+s+n(1148)),this[n(450)+n(1254)](1001,e[n(1169)],!0)}[t(836)](n){let s=t,d=e.EOQVs(zt,n);this[s(643)]&&e.plvRz(this._ws.readyState,this[s(981)])&&(this._ws&&this[s(643)].send(d),this[s(937)](e[s(911)],n))}["_removeW"+t(1526)+"rs"](){let n=t,s=(n(795)+"3")[n(1438)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(!this[n(643)])return;continue;case"1":this[n(643)][n(765)+n(1248)+n(999)](e[n(195)],this._onMessage);continue;case"2":this[n(643)][n(765)+n(1248)+n(999)](e[n(769)],this._onClose);continue;case"3":this._ws.removeEventListener(e[n(555)],this[n(1590)]);continue;case"4":this[n(643)]["removeEv"+n(1248)+n(999)](e.slPJG,this[n(649)]);continue}break}}[t(731)+"steners"](){let n=t;this[n(643)]&&(this._ws[n(1225)+n(1389)](e.slPJG,this._onOpen),this._ws[n(1225)+n(1389)](e[n(769)],this._onClose),this[n(643)][n(1225)+"Listener"](e.BiPFH,this[n(851)+"ge"]),this._ws[n(1225)+n(1389)](e.Alyhu,this[n(1590)]))}[t(1021)+"nceClose"](n=1e3,s=""){let d=t;try{this[d(643)]&&this[d(643)].close(n,s)}catch{}}_destroyWebSocket(n=1e3,s="",d=!1){let h=t;if(this["_clearPi"+h(1068)](),this[h(1306)+h(720)](),this._removeWsListeners(),this[h(1021)+"nceClose"](1e3,s),this[h(1487)+"Lock"]=!1,d&&this[h(768)+"orOnline"]()&&!this._readyClosed){if(this["_endpoin"+h(787)]?.[h(1232)+h(1062)+"es"]()){let E=this[h(1570)+h(787)]?.[h(1207)+"ntEndpoint"]();this["_dispatc"+h(1175)+h(1644)](e.NdZXa(mt,h(1081),{code:1006,reason:h(1618)+E+(h(1148)+h(515)+h(1538)+h(848)),wasClean:!0}))}else if(e[h(389)](h(1167),e.YkaQE))this[h(1609)](h(655),_0x1aa4d7),this.onopen&&this[h(634)](_0x32383b);else{let E=this[h(1045)][h(1547)+h(1540)+h(469)](n,s);this[h(1291)+h(1175)+h(1644)](e.UVGAP(mt,e[h(769)],{code:n,reason:s,wasClean:!0,willReconnect:E})),E&&this[h(1487)]()}return}this[h(768)+h(436)]()||this[h(979)+"osed"]?this[h(1291)+h(1175)+h(1644)](e.UpYKu(mt,e[h(769)],{code:n,reason:"bye"})):this[h(1291)+"hCloseEv"+h(1644)](e[h(256)](mt,e[h(769)],{code:1006,reason:h(504)+h(1497)+h(1648)+h(1302)})),this[h(643)]=null,this[h(1570)+h(787)]?.[h(875)+"pointCon"+h(905)](),this[h(1235)+"sCounter"]?.[h(1500)+"nter"]()}["_dispatc"+t(605)+"nt"](n){let s=t,d={tBmbR:function(h,p,E){return e[ne(626)](h,p,E)},pUBpQ:e[s(555)],adGFn:function(h,p){return e[s(401)](h,p)}};if(e[s(325)](e[s(1553)],e[s(303)])){let h=this["_endpoin"+s(787)]?.["checkRea"+s(1062)+"es"](),p=this[s(1570)+s(787)]?.[s(1207)+s(784)+"nt"]();if(h&&!_0x3cb522[s(1645)]){let E=s(1618)+p+(" fail, max retri"+s(1368)+"ed");this[s(1291)+s(284)+"ent"](HMllLj[s(621)](_0x206f08,HMllLj.pUBpQ,{message:E,code:_0x36b843[s(1385)+s(1054)+"R"],error:_0x1251ee}));return}this[s(643)]&&HMllLj.adGFn(this[s(643)][s(919)+"te"],this.OPEN)&&this[s(450)+"ect"](),this[s(1291)+s(284)+s(1644)](_0x5823b7("error",{message:_0x6e2874[s(1645)],code:_0x279aec[s(1051)+"RROR"],error:_0x1dfb16}))}else this[s(1609)](e[s(1421)],n),this[s(634)]&&this.onopen(n)}[t(1291)+t(1029)+t(1492)](n){let s=t;this[s(1609)](s(1645),n),this[s(320)+"e"]&&this[s(320)+"e"](n)}["_dispatc"+t(1217)+t(691)](n){let s=t;this[s(1609)](e[s(1486)],n),this[s(287)+s(171)]&&this[s(287)+"eAck"](n)}["_dispatchErrorEv"+t(1644)](n){let s=t;this.emit(s(709),n),this[s(1520)]&&this[s(1520)](n)}[t(1291)+"hCloseEv"+t(1644)](n){let s=t;this[s(1609)](e[s(769)],n),this[s(1114)]&&this.onclose(n)}get[t(184)+"pe"](){let n=t;return this[n(643)]?this._ws[n(184)+"pe"]:this[n(674)+"ype"]}set binaryType(n){let s=t;e.hdSHw(e.PbAoJ,e[s(1155)])?e[s(1307)](_0x530636,_0x48a74d,this[s(1034)+s(744)+"e"](_0x98acb4)):(this[s(674)+"ype"]=n,this._ws&&(this._ws.binaryType=n))}get[t(1224)+"nt"](){let n=t;return this["_endpoin"+n(787)]?.[n(1207)+n(784)+n(698)+n(889)]()||0}get[t(1637)+t(1433)](){let n=t;if(e[n(246)](e[n(445)],e[n(1206)])){let{enableAutoAck:s}=this._options,d=e.khuZG(_0x3e3ff7,_0x3f29b4[n(1645)][n(688)],e[n(1456)],"1"),h=e[n(657)](_0x581e03,_0x1c3a87[n(1645)][n(688)],"is_ack","1"),p=_0x144e31[n(725)](this,_0x4ccb79);if(e[n(869)](s,d)){let{SeqID:E,LogID:_,service:m,LogIDNew:k,method:N}=_0x31983e[n(1645)];this._sendAck({SeqID:E,LogID:_,LogIDNew:k,service:m,method:N,headers:[{key:e.ESbFB,value:"1"},{key:e[n(442)],value:k||""},{key:e[n(1264)],value:"0"}]})}h&&!p.isQoSAck&&this["_dispatc"+n(1217)+n(691)](_0x3b0421),e[n(575)](_0x258ebd)}else{let s=this[n(944)+n(162)].reduce((d,h)=>(d+=h&&h[n(330)+"th"]||0,d),0);return e[n(364)](s,this._ws?this[n(643)][n(1637)+"Amount"]:0)}}get[t(809)+"ns"](){let n=t;return this[n(643)]?this._ws[n(809)+"ns"]:""}get protocol(){let n=t;return this._ws?this[n(643)].protocol:""}get[t(919)+"te"](){let n=t;return this[n(643)]?this[n(643)][n(919)+"te"]:this._options[n(834)+n(410)]?this[n(1631)+"NG"]:this.CLOSED}get[t(866)](){let n=t;return this[n(643)]?this[n(643)][n(866)]:this[n(1642)]}[t(1081)](n=1e3,s){let d=t;if(e[d(1650)](e.hxwvH,"eQhWx")){let{url:h}=e[d(519)](_0x573b77,{}),p=_0x21e5cc.isArray(h)?h:e[d(1277)](d(589),typeof h)?[h]:[];_0x5306a5&&_0x149f99[d(1407)](this[d(1045)],_0x137fc0),p&&p[d(1391)]?this["_endpoin"+d(787)]=new _0x1b79bb(p,this[d(1045)][d(1510)+"es"]):this[d(1570)+d(787)]?.[d(875)+d(1251)+d(905)](),this[d(1235)+d(204)]?.[d(1500)+d(1317)](this[d(1045)].pingLossCount),this[d(979)+"osed"]=!1,this._ws&&this[d(643)][d(919)+"te"]!==this[d(462)]?this[d(450)+"ect"](1e3,d(990)+d(1074)+d(1576),!0):(this[d(1343)]=!0,this[d(1487)]())}else{if(this[d(979)+"osed"]=!0,this[d(1306)+d(720)](),this["_clearPi"+d(1068)](),this[d(447)+d(617)+"Listener"](),this[d(278)+"ger"]?.[d(1288)](),!this[d(643)])return void this._debug(d(1297)+"s instan"+d(1468)+d(1336)+"ed");if(e[d(1602)](this[d(643)][d(919)+"te"],this[d(462)])||e[d(401)](this[d(643)][d(919)+"te"],this[d(906)]))return void this[d(937)](e[d(202)]);this[d(155)+d(372)+"t"](n,s)}}async[t(463)](n,s){let d=t;if(e[d(1345)](null,n))throw new Error(e[d(644)]);d(896)==typeof n&&(n=JSON[d(737)+"y"](n)),e[d(1120)](e[d(1382)],typeof n)&&!e.FrNMZ(n,ArrayBuffer)&&!(n[d(315)]&&e[d(780)](n[d(315)],ArrayBuffer))&&(n=JSON[d(737)+"y"](n));let h=await e.IvfCG(El,n),p=Qp(n),{method:E=0,service:_=this[d(1045)][d(622)],logID:m=this[d(1045)]["logIDGen"+d(1471)](),headers:k=this._options.headers,payloadEncoding:N=this[d(1045)]["payloadE"+d(583)],payloadType:M=this[d(1045)][d(1310)+d(403)],logIDNew:K=this._options[d(1622)+d(241)][d(1539)+d(1184)+d(646)+"ew"]?e[d(1077)](i,this[d(1045)][d(1622)+d(241)][d(884)]):""}=e[d(1626)](s,{});if(!_)throw new Error(e[d(1507)]);let W={SeqID:fe.fromNumber(this[d(1403)]++),LogID:fe[d(407)+"er"](m),service:_,method:E,headers:k,payloadEncoding:e.OVIEc(N,Object)?N[d(1131)]?N[d(1131)]:"":N,payloadType:M instanceof Object?M.type?M[d(1481)]:p:M||p,payload:h,LogIDNew:K},he=e[d(452)](zt,W);return this[d(643)]&&e[d(637)](this._ws[d(919)+"te"],this[d(981)])?(this[d(643)]&&this[d(643)][d(463)](he),this._debug(e[d(882)],W)):this[d(944)+d(162)][d(1391)]<this[d(1045)].maxMessageQueueLength?(this["_message"+d(162)][d(1273)](he),this[d(937)](e.XojFy,W)):(this["_message"+d(162)].shift(),this[d(944)+d(162)][d(1273)](he)),{seqID:this[d(1403)],logID:m,logIDNew:K}}async[t(1547)+"t"](n){let s=t,{url:d}=e[s(1582)](n,{}),h=Array[s(1412)](d)?d:e[s(1382)]==typeof d?[d]:[];n&&Object[s(1407)](this[s(1045)],n),h&&h[s(1391)]?this[s(1570)+s(787)]=new wl(h,this[s(1045)].maxRetries):this[s(1570)+s(787)]?.["resetEnd"+s(1251)+s(905)](),this[s(1235)+s(204)]?.[s(1500)+s(1317)](this._options.pingLossCount),this._readyClosed=!1,this[s(643)]&&this._ws[s(919)+"te"]!==this[s(462)]?this["_disconn"+s(1254)](1e3,e.uGSSU,!0):(this[s(1343)]=!0,this._connect())}async connect(){let n=t;if(!this["_connect"+n(642)])if(e[n(274)](n(1194),e.klWLQ)){let s=(n(486)+"4")[n(1438)]("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(979)+n(1335)]=!1;continue;case"1":this[n(1235)+"sCounter"]?.[n(1500)+n(1317)]();continue;case"2":this._isInit=!0;continue;case"3":this[n(1570)+n(787)]?.[n(875)+n(1251)+n(905)]();continue;case"4":this._connect();continue}break}}else return!!this._qosDB}[t(1225)+"Listener"](n,s){this.on(n,s)}["dispatch"+t(1492)](n){let s=t,{type:d}=n;this[s(1609)](d,n)}["removeEventListe"+t(999)](n,s){this[t(750)](n,s)}[t(648)](){let n=t,s={JThbE:e[n(907)],vioII:n(164)+n(435)+"s",hgdfJ:e[n(149)],BJQkK:function(d,h){return e[n(401)](d,h)},gQqNi:e[n(210)],rqYKF:"mEBXs",pSZcI:function(d,h,p){return e[n(1265)](d,h,p)}};return new Promise((d,h)=>{let p=n;if(s[p(892)](s.gQqNi,s[p(1472)]))_0x56691e[p(1607)]["removeCh"+p(352)](_0x4d4098);else{this._clearPingTimer(),this[p(600)+p(1416)+"Id"]=s[p(797)](setTimeout,this._ping[p(597)](this),this._options[p(1653)+p(1577)]);let E=()=>{let m=p;d(s.JThbE),this[m(750)](s[m(938)],E),this[m(750)](s[m(1522)],_)},_=()=>{let m=p;h("timeout"),this[m(750)](s.vioII,E),this.off(s[m(1522)],_)};this.on(s[p(938)],E),this.on(p(164)+p(1646)+"t",_),this._ping()}})}}})(),Me[L(1052)+L(1011)]=De["CustomCl"+L(1011)],Me["CustomEr"+L(924)]=De[L(541)+L(924)],Me[L(991)+"e"]=De[L(991)+"e"],Me[L(1492)]=De.Event,Me[L(786)]=De[L(786)],Me[L(1489)+L(915)+L(782)]=De[L(1489)+"MessageE"+L(782)],Me[L(915)+L(782)]=De["MessageE"+L(782)],Me[L(1537)+"t"]=De[L(1537)+"t"],Me.ReconnectEvent=De[L(1004)+L(1559)],Me["createCl"+L(1011)]=De["createCl"+L(1011)],Me.createErrorEvent=De["createEr"+L(924)],Me[L(163)+"ssageEvent"]=De[L(163)+L(792)+"nt"],Me[L(153)+L(1383)]=De[L(153)+L(1383)],Me[L(268)+L(1361)+L(782)]=De[L(268)+L(1361)+L(782)],Me[L(1123)+L(660)]=De[L(1123)+L(660)],Me[L(1641)+L(388)]=De[L(1641)+L(388)];for(Qo in De)[L(1052)+L(1011),L(541)+L(924),L(991)+"e",L(1492),"FWS",L(1489)+L(915)+L(782),L(915)+L(782),L(1537)+"t",L(1004)+"tEvent",L(174)+L(1011),L(1613)+"rorEvent","createMe"+L(792)+"nt","createOp"+L(1383),L(268)+L(1361)+L(782),L(1123)+L(660),L(1641)+"ame"].indexOf(Qo)===-1&&(Me[Qo]=De[Qo]);var Qo;Object[L(1117)+L(1030)](Me,L(1478)+"le",{value:!0})});import{existsSync as $S,openSync as VS}from"node:fs";import{mkdir as JS}from"node:fs/promises";import{dirname as ZS}from"node:path";import{fileURLToPath as YS}from"node:url";function QS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Jd(t=J()){return $S(t.libEntry)?t.libEntry:YS(new URL("../index.ts",import.meta.url))}async function ap(t={}){let e=t.paths??J(),r=t.entryOverride??Jd(e),i=QS(e,process.env.COZE_BRIDGE_LOG_MODE);await JS(ZS(i),{recursive:!0});let o=VS(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=nt(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[ds]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return XS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var XS,ds,la=Qe(()=>{"use strict";Yt();ee();Re();XS=G("spawn-daemon"),ds="COZE_BRIDGE_DAEMON"});import{spawn as J1}from"node:child_process";import{mkdir as Z1,unlink as Y1,writeFile as X1}from"node:fs/promises";import{dirname as Q1,join as e2}from"node:path";function Xr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function t2(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Xr(r)}</key>
21
- <string>${Xr(i)}</string>`).join(`
20
+ `+r)}function ir(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,ir),t.emit("wsClientError",d,r,e)}else cs(r,i,o,c)}});var Yh=ce(ze=>{"use strict";var B=W;(function(t,e){let r=W,i=t();for(;;)try{if(-parseInt(r(1247))/1+parseInt(r(1925))/2+parseInt(r(1471))/3+-parseInt(r(1381))/4*(parseInt(r(1562))/5)+-parseInt(r(586))/6+-parseInt(r(1684))/7+parseInt(r(1423))/8*(parseInt(r(463))/9)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(aa,350236);var xS=Object[B(1737)+B(1866)],hS=Object[B(1332)+B(781)+B(1392)],Kh=(t,e)=>function(){return t&&(e=(0,t[hS(t)[0]])(t=0)),e},pS=(t,e)=>{let r=B,i={Wpelf:function(c,d,u,x){return c(d,u,x)}};for(var o in e)i[r(1400)](xS,t,o,{get:e[o],enumerable:!0})};function gS(){return Gh||(Gh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function mS(){let t=B;return Hh||(Hh=[IDBCursor[t(1771)+"e"].advance,IDBCursor[t(1771)+"e"].continue,IDBCursor.prototype[t(1391)+t(1097)+"ey"]])}function wS(t){let e=B,r={XxuTv:function(o,c){return o(c)},BDnOe:function(o){return o()},iNcHe:e(1690),QKCMV:"success",qPdiI:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let d=e,u={mDcUL:r[d(1962)],PEkKE:function(_,S){return _(S)}},x=()=>{let _=d;t["removeEv"+_(488)+_(1937)](_(1406),h),t[_(1561)+_(488)+_(1937)](u[_(876)],g)},h=()=>{let _=d;o(r.XxuTv(Gt,t[_(1019)])),r[_(507)](x)},g=()=>{u[d(1603)](c,t.error),x()};t[d(831)+d(1169)](r[d(1318)],h),t[d(831)+d(1169)](d(1690),g)});return i[e(1403)](o=>{let c=e;r[c(1418)](o,IDBCursor)&&Kd[c(646)](o,t)})[e(844)](()=>{}),sa[e(646)](i,t),i}function _S(t){let e=B,r={lduVu:function(o,c){return o>>c},OAscU:function(o,c){return o|c},EXKmo:"AbRQv",uUPRY:e(949),NXcuj:e(627),zyNvv:e(1690),BoVFc:e(736),FOfvK:function(o,c){return o===c},HSAHk:e(1734),kTuHt:function(o){return o()},uyVZK:function(o,c){return o(c)},bNeaJ:e(1996)+"or"};if(ia[e(1422)](t))return;let i=new Promise((o,c)=>{let d=e,u=()=>{let g=W,_={CVuOd:function(S,w){return r.lduVu(S,w)},ZHzAy:function(S,w){return r[W(721)](S,w)},eaJnj:function(S,w){return S&w}};r[g(583)]===r[g(981)]?(_0x16f9a8[_0x1a22be++]=_.CVuOd(_0x296eee,12)|224,_0x3b88dd[_0x38d2e9++]=_.ZHzAy(_.eaJnj(_0xcea1f7>>6,63),128),_0x1c2c46[_0x25e235++]=_[g(1031)](63,_0x34b3e5)|128):(t["removeEv"+g(488)+"ner"](r[g(1222)],x),t["removeEv"+g(488)+"ner"](r.zyNvv,h),t[g(1561)+g(488)+g(1937)](r[g(567)],h))},x=()=>{let g=W;if(r[g(1404)](r[g(1837)],r.HSAHk))r[g(1908)](o),u();else{let _=this._listeners[_0x3db519];if(_)for(let S=0;S<_[g(1994)];)_[S].fn===_0x54add5?_.splice(S,1):++S}},h=()=>{let g=W;r[g(871)](c,t[g(1690)]||new DOMException(g(1996)+"or",r.bNeaJ)),u()};t.addEventListener(d(627),x),t["addEvent"+d(1169)](d(1690),h),t[d(831)+"Listener"](r[d(567)],h)});ia[e(646)](t,i)}function W(t,e){t=t-458;let r=aa(),i=r[t];if(W.bmaksn===void 0){var o=function(x){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",g="",_="";for(let S=0,w,v,I=0;v=x.charAt(I++);~v&&(w=S%4?w*64+v:v,S++%4)?g+=String.fromCharCode(255&w>>(-2*S&6)):0)v=h.indexOf(v);for(let S=0,w=g.length;S<w;S++)_+="%"+("00"+g.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(_)};W.jINBQS=o,W.IhbWIu={},W.bmaksn=!0}let c=r[0],d=t+c,u=W.IhbWIu[d];return u?i=u:(i=W.jINBQS(i),W.IhbWIu[d]=i),i}function yS(t){oa={DjSVZ:function(i,o){return i(o)}}[B(1141)](t,oa)}function bS(t){let e=B,r={qEIez:function(i,o){return i-o},ThtDm:function(i,o){return i!==o},qtQyd:e(1984),uSYlp:function(i,o){return i(o)},rAGAx:function(i,o){return i(o)},iwPAZ:function(i,o){return i&o},pxVtr:e(1308),NtjwZ:e(1368),LKxJB:function(i,o){return i(o)},OJWxF:function(i,o){return i===o},ZAksl:function(i,o){return i in o},xtrnH:e(768)+e(940),FvRIA:function(i){return i()}};return r.OJWxF(t,IDBDatabase.prototype[e(1411)+e(1816)])&&!r[e(775)](r[e(502)],IDBTransaction[e(1771)+"e"])?function(i,...o){let c=e;if(r[c(1644)](c(1894),r[c(532)])){let d=t.call(r.uSYlp(ds,this),i,...o);return Wd[c(646)](d,i[c(1076)]?i[c(1076)]():[i]),r.uSYlp(Gt,d)}else{let d=_0x430727.substring(0,r[c(1888)](4,_0x5c4109[c(1994)])),u=d.concat(_0x398799);_0x23feba[c(468)](u)}}:r[e(1050)](mS)[e(553)](t)?function(...i){let o=e;return t.apply(r.rAGAx(ds,this),i),Gt(Kd[o(798)](this))}:function(...i){let o=e,c={QBeDh:function(d,u){return r[W(1764)](d,u)},TAPfL:function(d,u){return r[W(1199)](d,u)},GBVIl:function(d,u){return d(u)},VERSG:function(d,u){return d<<u},HaZfB:function(d,u){return d&u},ORiza:function(d,u){return d&u}};if(r[o(1644)](r[o(1037)],r[o(667)]))return Gt(t[o(703)](r[o(547)](ds,this),i));_0x278c3f=c.QBeDh(_0xa1ed23,_0xcfd0a1),_0x52e4a6|=c[o(1273)](127,_0x2269cf)<<14,c.TAPfL(128,_0xf063c6)&&(_0x58a1e6=c.GBVIl(_0xd38ba5,_0x2f1384),_0x1812b8|=c[o(869)](127&_0x144cd6,21),c[o(1025)](128,_0xe0983e)&&(_0x380807=_0x59132c(_0x478167),_0x2546c6=c[o(1025)](127,_0xc1a1de),c[o(1634)](128,_0x4dfdbc)&&(_0x5399de=_0x2c035a(_0x17e8cc),_0x10c23e|=(127&_0x4170b3)<<7)))}}function ES(t){let e=B,r={vdtVC:function(i,o){return i===o},BTybv:function(i,o){return i(o)},Ivluw:function(i,o){return i(o)},CxpWM:function(i){return i()}};return r.vdtVC(typeof t,e(720))?r.BTybv(bS,t):(t instanceof IDBTransaction&&r[e(1921)](_S,t),$h(t,r.CxpWM(gS))?new Proxy(t,oa):t)}function Gt(t){let e=B,r={bvVgJ:function(o,c){return o instanceof c},zzSUW:function(o,c){return o(c)},JwEnJ:function(o,c){return o!==c}};if(r[e(1495)](t,IDBRequest))return r.zzSUW(wS,t);if(na[e(1422)](t))return na[e(798)](t);let i=ES(t);return r[e(537)](i,t)&&(na[e(646)](t,i),sa[e(646)](i,t)),i}var $h,Gh,Hh,Kd,ia,Wd,na,sa,oa,ds,qh=Kh({"node_modules/idb/build/wrap-idb-value.js"(){let t=B,e={nyQnE:function(r,i){return r===i},QksnH:t(768)+t(940),UPOXa:t(947),syXyK:"cursor_file_name",GnKgU:t(723)+t(986),eCrQE:t(1272),LaNsU:function(r,i){return r instanceof i},BXKhe:function(r,i){return r===i},mqWbE:function(r,i){return r===i}};$h=(r,i)=>i[t(1150)](o=>r instanceof o),Kd=new WeakMap,ia=new WeakMap,Wd=new WeakMap,na=new WeakMap,sa=new WeakMap,oa={get(r,i,o){let c=t;if(r instanceof IDBTransaction){if(e[c(920)](i,c(1336)))return ia.get(r);if(i===e[c(1358)])return r["objectSt"+c(940)]||Wd[c(798)](r);if(e[c(920)](i,e[c(845)]))return o.objectStoreNames[1]?void 0:o[c(768)+c(674)](o[c(768)+c(940)][0])}return Gt(r[i])},set(r,i,o){let c=t;return e[c(1995)]==="jswwD"?{frameType:_0x3847f3,headers:[{key:e[c(552)],value:e.GnKgU}],payload:void 0}:(r[i]=o,!0)},has(r,i){let o=t;return e[o(1317)](r,IDBTransaction)&&(e[o(1045)](i,o(1336))||e[o(939)](i,e[o(845)]))?!0:i in r}},ds=r=>sa[t(798)](r)}}),Vh={};pS(Vh,{deleteDB:()=>SS,openDB:()=>vS,unwrap:()=>ds,wrap:()=>Gt});function vS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=B,u={mokyy:function(g,_,S,w,v){return g(_,S,w,v)},xTqbI:function(g,_){return g(_)},ramDL:d(1709),RLtan:d(472)+d(1733),SMzdy:d(561)+"eeded",vuKaN:d(1568)},x=indexedDB.open(t,e),h=Gt(x);return i&&x[d(831)+d(1169)](u.SMzdy,g=>{let _=d;u[_(1129)](i,Gt(x[_(1019)]),g[_(1417)+"on"],g[_(1527)+"on"],u[_(953)](Gt,x[_(1411)+"ion"]))}),r&&x[d(831)+d(1169)](u[d(620)],()=>r()),h[d(1403)](g=>{let _=d;c&&g[_(831)+_(1169)](u[_(610)],()=>c()),o&&g[_(831)+"Listener"](u[_(1335)],()=>o())}).catch(()=>{}),h}function SS(t,{blocked:e}={}){let r=B,i={gXluJ:r(1568),luCNY:function(c,d){return c(d)}},o=indexedDB[r(1213)+r(659)](t);return e&&o[r(831)+r(1169)](i.gXluJ,()=>e()),i[r(1005)](Gt,o).then(()=>{})}function jh(t,e){let r=B,i={HuQOK:r(1709),OLAAA:"bye",uLexk:function(x,h){return x===h},ttqIb:r(1903),dGnFP:r(783),YvyCb:function(x,h){return x in h},WJdhG:function(x,h){return x===h},cqBpn:r(616),cUxOT:function(x,h){return x!==h},nwuJP:r(1876)};if(!(t instanceof IDBDatabase&&!i.YvyCb(e,t)&&i.WJdhG(typeof e,i[r(1226)])))return;if(ra[r(798)](e))return ra[r(798)](e);let o=e[r(1208)](/FromIndex$/,""),c=i[r(1288)](e,o),d=Zh[r(553)](o);if(!i[r(1651)](o,(c?IDBIndex:IDBObjectStore).prototype)||!(d||Jh.includes(o)))if(i.nwuJP!==i.nwuJP)this[r(1530)]&&this[r(1530)][r(1940)](_0x40a8d2),this[r(697)+r(934)][_0x4da909]=null;else return;let u=async function(x,...h){let g=r,_={jdgHs:i[g(1274)],ViJbk:i.OLAAA};if(i[g(1843)]("WMWda",i[g(644)])){this[g(692)+"hCloseEv"+g(958)](_0x1509c8(_[g(1675)],{code:1e3,reason:_[g(1765)]})),this[g(1e3)+g(1982)]?.[g(1349)+g(1753)+g(1284)](),this[g(458)+g(1716)]?.[g(1572)+g(1354)]();return}else{let S=this[g(1411)+g(1816)](x,d?g(1157)+"e":i[g(717)]),w=S[g(947)];return c&&(w=w[g(589)](h[g(899)]())),(await Promise[g(1686)]([w[o](...h),d&&S.done]))[0]}};return ra[r(646)](e,u),u}var Jh,Zh,ra,IS=Kh({"node_modules/idb/build/index.js"(){let t=B,e={pfQSa:t(641)+t(739),dmlkK:t(870),WjJat:"clear",yBAdq:function(o){return o()},vgmgR:function(o,c){return o(c)},yqCAv:"get",nysME:"getKey",Ttosy:"getAll",MXkXJ:"getAllKeys",Jtsgq:"count",EpPZs:function(o){return o()}},r=e[t(1992)][t(479)]("|"),i=0;for(;;){switch(r[i++]){case"0":Zh=["put",e[t(1507)],t(1315),e[t(1303)]];continue;case"1":e.yBAdq(qh);continue;case"2":ra=new Map;continue;case"3":e[t(1983)](yS,o=>({...o,get:(c,d,u)=>jh(c,d)||o[t(798)](c,d,u),has:(c,d)=>!!jh(c,d)||o[t(1422)](c,d)}));continue;case"4":Jh=[e[t(1255)],e[t(1981)],e[t(1494)],e[t(660)],e[t(1470)]];continue;case"5":e[t(1649)](qh);continue}break}}}),AS={idb:function(t){let e=B;t.exports=Promise[e(1329)]()[e(1403)](()=>(IS(),Vh))[e(1403)](function(r){return r})}},Wh={};function Ut(t){let e=B,r={mEmxW:e(1108)+"1",vYhob:function(u,x){return u!==x}},i=r.mEmxW[e(479)]("|"),o=0;for(;;){switch(i[o++]){case"0":var c=Wh[t];continue;case"1":return d.exports;case"2":var d=Wh[t]={exports:{}};continue;case"3":if(r[e(1386)](void 0,c))return c[e(1969)];continue;case"4":AS[t](d,d.exports,Ut);continue}break}}function aa(){let t=["x3bYzwzPEa","Cgz6zLu","yxbWzw5Kq2G","B2Ltvwy","yM9KEq","vfnhr1y","y2HLy2Tszwe","EfzSAeC","C0jf","zw5HyMXLqxu","zw5HyMXLvhi","CuvjzxO","ihrPBwvZ","B2fK","Aw1LCYbPBIa","ruPAy0i","zfHnD1y","ELzXvfm","C2XPy2u","zwnVBM5Ly3q","zMX1C2HfEha","y29UC3rYDwm","BwLUAvbYB2C","x29UrxjYB3i","AfHZqLu","CM92AwrLige","v1nPCuu","DMvY","C2vYDMLJzq","Bgn0EuW","BMDWwwK","A1r1shq","A2v5","tKr3q2K","x3vYBa","tffOwuq","z3z5yLy","AxnAzxjV","sxrUseS","AxnmB25N","Dg9VigXHCMC","CgfNzxnOB3C","shr0zgG","r2DSz3K","sxzSDxC","vvrrww8","BfjOu2u","rfP6CK4","mZm2otq0ufLJDgTk","rhLwAe8","uvvLAwG","EgnMueu","ihrYEsbYzwm","D2DdyNa","vxHSsfu","Cgf5Bg9Hza","y29Uy2f0","BvbtreK","rMzXAhK","BwfUDwfSihi","BMvY","igXHCMDLCIa","DvDgseO","C2vUza","C2LlrM4","vNDbv2e","we92tui","D2Tltge","zxjFywnRx20","swjewMK","Dw50","zxjFCw9Z","y3jLyxrLq2W","z2vJBhi","ywXPzcb1CMW","zgDysvG","B25tDgfYDfi","x2TLEvbHDgG","BwvZC2fNzq","zxmGCMvHy2G","nhWXFdn8mNW","B2nRzxrtDwm","zhzPzKu","vLrbsNa","tuPpy1G","Au5Jsgu","B2nRzxq","yNvMzMvY","zLjHELe","vvvZv3O","DxjS","C0jYzuy","zxHWB3j0CW","BhDoBhG","yw9RrwG","u3P4u3K","weruwxi","zhnpv2C","yMLUza","x2nVBM5Ly3q","sNP2De0","zxH0ugf5Bg8","DeLK","ugzPqwm","BNLZtuu","De1HBMfNzxi","DMDTz1i","qKPACvi","whDJuKe","CK1NsM8","DM5qAuK","v095BwW","CMfZyxC","DgvmB2Djre4","C2vYDMLJzs0","Cgzru2e","vNzgCey","BgvUz3rO","zunYuuu","qwjVCNrfCNi","v2Przwy","D3jYtLO","r0Ddrwq","tvvqBK4","y3vYCMvUDeu","AxnrB1nby2S","zsbHihn0CMK","sg53yNm","BNrbBMrvCgq","EeDorfq","x3bPBMDmB3m","vwvyt2q","yxrcyMG","yw1Lu3bHy2u","BwPeENu","otmZmdm5ouLXqvbbzG","Chb6rha","AuDMENC","q3vZDg9Tq2W","AwXSihvZzsa","ChvZAa","v0rot3i","qMTvBvi","ywnRx2LK","DMvYC2LVBMm","t2fozNC","yxnL","Aw5N","u3D0thC","t0XqtwS","x2HHBMrSzu8","C3bSAxq","q291BNq","zxDIs08","D3LXv3a","EgrpA04","Cg16BvC","A1LrA1K","C0zrzue","DKPYvha","zw50tgLZDgu","ywnOzwq","x2LZqNjVD3m","wLf0ELK","AwXLx25HBwu","B3jRzxjhBg8","vMr6q2m","nNW0FdeWFdK","AfjUwgy","weDmvwm","CKLiEKC","rfPYwge","rKjru00","yM5LAMK","EhrYBKG","x0rctMfTzq","s3vsr2W","x19LC01Vzhu","Bwv0Ag9K","qKrUt2u","r1vTEM0","tfvusKG","x2nSzwfYugK","vNPzy3a","t29zvwC","rhf4zeK","sMfmBxm","A3nLAeC","zePqv3m","sgTsv1e","ze5Rz1u","Dg9tDhjPBMC","D3jPDgvvAw4","zNzhsMS","EgzQqwq","r3j1DMO","zfr1wLe","zefYA2m","D3rIEgm","Dg9cExrLC0i","zMzmAw5L","q0Xpu0LorW","yKvVvgO","r3LZAvq","CxrrEwq","BgrSteW","DNvvD04","uMLNzha","yMvkA3O","sNDfBKO","BM9Uzv9UB24","tefuAfK","CYbHBhjLywq","AuHdqLe","uwrIvfi","yNL0zu9MzNm","tfrjB3e","C3PksNq","ywrKt25L","teT4sKi","Dg9Y","q0PqyKK","z2fLtvK","AefSAwG","C3LyEuS","Aw5JBhvKzxm","Aw5KzxHpzG","x29Ut3bLBG","rKrYBNa","qLLIs1y","t09uyMG","z2u6ia","Axnby2TdBgu","DxbNCMfKzw4","BfrPBwvVDxq","D1juBvK","AxnrB1nnzxm","B25ozxr3B3i","B3jpBMXPBMu","qM9wrMm","DhbizwfKzxi","sxfnrKW","DePcvuO","wejfBKC","x21PBMLoyxy","Dhb5ENC","qKT4uMe","ywnOzwqSihC","Bwf4tg9ZC0m","BIWGAg9ZDg4","reiGzMfPBgu","DLHHCK0","DMPfAxK","CfL2r1y","x3bYB3rVy28","rvHlBw8","shH0vfq","z3DXtM0","nda2otuZnNHcvxv3sa","t3LTD2u","Dhjdugm","Aw5KzxG","uNHIvwO","AenSB3nLrxy","Ag9Pwfm","Dw5ZAwDUzwq","A2jUt3K","BwLZzq","sM1LveC","zxfbCM4","Aw5KzxGGB3u","tgnewMG","wxvWy0W","v01uChG","tMjWEgC","zgnnA08","rKLKsKe","D1jYzfu","ig1LC3nHz2u","CgzbEwG","vKPNuM8","tu1YvNe","CMfTreW","B3nLza","x2LUAxq","veT1B1a","su1TBM8","x3nVy2TLDa","C3rYAw5N","yxv0BW","zxjFCw9Zx2e","zNPmBee","DNvlyu4","DNfPEeu","Dw5KzwzPBMu","Dgv4Dc9WBge","ihbYB3rVy28","ywXSzwqGBxu","vM9XAKi","y29TCgXLDgu","zNjVBujPDhm","DgLuDMW","rNvPqLC","D1rdEfe","rgTUBNi","zeTcC3K","sKHkzxy","AefJA01LC3m","zxH0zw5ZAw8","CKjxzgW","yNL0zuXLBMC","EwP0rfi","x29UtwvZC2e","nxWXFdr8mhW","B1Hyqui","ENPzz3u","DhrXswi","x3fVC0rc","C2v0","zwn0","tKDFrvjst1i","DhDVCMTdAge","CgLUz19VBMm","BMDLza","DNbZCNK","q1n2u1m","zNHJvKS","z2v0u3rVCMe","zKrky0e","tg1uqMm","Cg1RA1m","DgfIyxnL","tvHRweO","uvv6z2O","uwf1v0W","ueXqtvu","vfbzsK8","vgfN","DvvWyxm","tNrQD1O","AuLSs1y","v0jYzLe","wMLOy0q","rgvKAwnHDgu","r3nuCxC","yKrjDwG","B3jL","uhjIv1q","Aw47y2HHCNm","qMTVAhy","ywDLu2HVDW","Evf1v2i","zNjHBwvuExa","zxf1ywXZ","zvPIB1a","rwPIzMm","BMv4DcGPigm","EKv5AMG","Bwz1C0y","ywDLsgLKzq","C2fNzq","CMfUzg9T","CLjYufm","BML0AwfSAxO","x2rPC3bHDgm","BxnN","D2HfyxG","r1bMyxe","x2nYzwf0zvm","x21LC3nHz2u","zhzMyvy","Dw5MC1y","uxbgrNC","y3vYDMfSDwu","ChPqCM4","yxbWBhK","y3jLyxrLrxi","BLHkt2m","refgvxe","aaaaaaaaaaa","B2DLBuy","uuzbzwu","zwvdruy","uuv6q28","AgP5Aw8","v2vPEgLUsLm","AvDrsLy","yvbUEgK","DMfSDwvZ","zeDUrLa","tuvxrey","ywnRpwzYB24","zNvUy3rPB24","t0fZy1u","CMvHzhLtDge","rKLmrv9ot1q","x2rLC3rYB3K","su9OveK","CM1yB00","zfvjD2m","v3niEvK","CMvHC29U","x2LZsw5PDa","AgvHzgvY","CIb0DhDjra","DefLu0m","x25HDMLNyxq","yxzxBuu","ywjVCNq","r1LfsLm","suXns2i","mNWZ","yNfcvKi","Aw9Ul2PZB24","CfHgCLK","tuvtu0fhrv8","tgzHv3a","tNbJA1q","BwvZC2fNzv8","AKfrsuu","yw1L","AhvLB2i","BwPXzMe","D2zyvfK","x2LZtwLUAvC","CeLlwxm","y1PXteW","zxfMDKu","uK9Nzgq","A3rxzuG","t1bftL9fuLi","x2HHBMrSzva","wfbLzxm","wLPdEu8","zwDYBfu","vxbKyxrLq28","Dg9cExrLC0W","CNjVCK1LC3m","tMfOt0m","EMzxAwS","B2jQzwn0u3q","vuXYvg4","shLJv1G","u3rYyxrLz3K","D21hr0O","suTutM8","wM1MBhu","wKfRC2W","qvnNBMi","v1HZzMC","rMjStMG","CgLjwhi","Agvmswu","B3bLCNr5tMe","vw5Oyw5KBgu","CMvHzg9UBhK","DhjPzxm","y2vZC0HHBMq","BK1Uz0y","sfbAEwW","B25VCgvU","s3POAeS","zvvYBa","Dgv4DfbHEwW","C2v0u3rVCMe","CM92AwrLihC","sLLTrey","EuXyqMO","o2nOyxjZzxq","thnMuhq","z2v0","m3WWFdf8mNW","x3bPBMC","zxvYB3G","CNnpqxC","t0ThzgC","z0ruv0i","zeDjzhm","A2zntfe","Cfjjte0","uMPiqva","s3LLDM4","ufDNwNu","B3v0sw50zxi","B0TTwfC","CfbOzeG","B3vUDa","DxvXDvG","ANvWEKe","z0P5Cue","EMjZDvu","yxjYyxLIDwy","C0DeAe0","q2vytxq","z2v0qwXSs2u","u2vYDMLJzvC","zgvJB2rLzey","s3z2tuK","u1jmyNe","suXNu3e","B09zwNm","DxrVuMvJB24","CgLUz0LUDgu","ywrKrxzLBNq","CMvQzwn0","AujNqva","zNjVBuj5Dgu","AM5pCvi","DMfSDwu","D2vNB1y","rw1KugW","x2rYB3bhBg8","y2XLyxi","quXm","AevYCM9Yrxy","CefeywK","y2f0y2G","vvbpwge","C3nWzgu","ELv5zMC","uxzRwNm","C3rHCNq","t3rIC2q","uxz5ALi","CeneDxa","yxGGCMv0CMK","CeTHDwi","Defhwg8","uwv4veq","wuDduuK","ugjIC0S","uufbuvi","vM9Suuy","u2vXsuq","DMLJzuLeig8","ywXty29Wzq","zxjYtxnN","y3vYC29Yx2y","BNjWvwm","zuLquLi","CgfNzwHPzgu","vKvsu0C","ywrK","DxLwwKS","BwXyrKW","zw5fDMvUDa","y1n4C24","twT6Dw4","BurJvuW","u1LlEfq","rxjYB3jdB2q","BgLUzw5V","zcbLCNjVCI4","C2TNDLO","z2v0q3vYCMu","z2vjBMzVu3K","A2v5CW","qw1VDw50","zxrxB3jRq2G","DLfhAeO","DMfsrNy","CYbWyxjHBxm","rvHMreW","zw5JB2rLrNi","wuHKCfO","r212tvO","BgLUzq","u0fiquO","r0nSs2e","x29UugfNzu4","uxvRyMK","C2HPzNq","wujHzLi","BNruCMLLC0m","uwzuzNu","y29UBMvJDgK","tg9NsurozxC","zMfhwK4","q0Xpu0ve","AKPvAwW","A1LMCLe","v3jpDMm","EMfsq3i","x2n1CNnVCKy","rxnLv1O","tNPTyKC","D0XgzwW","qLfzCeq","EKX4wMO","vMfqzMW","wKfxD1y","D3jPDgu","BNLrBKu","yxbWBgLJyxq","x2fKzfDZtgK","zv90Aw1LB3u","zKL5vhe","Eezft2C","BeHHBMrSzxi","qMriA2u","rg1HCvm","wePWsuG","u3r0DxC","BKXsAwi","AKzptKe","zgvIDwC","uxvLDwu","AgvKtwf4uMu","uMvHzcbWyxm","C3rYAw5NAwy","wfDeyxO","BxfxyKu","B3jLtMfTzxm","rgzVwKm","Dwv5AKm","vezsAxe","BwDWwuu","zKzpAfC","vKjkwvq","C3rVCMu","DgLTzw91DcW","vuXqwKi","y3vZDg9Tshq","ywnRtxnNswq","qu1ns1m","EfrXyKK","t09LEg4","quTrA2G","tvPcwg8","x2LZv29YA2u","zw50","DKTWse4","zuz0C2S","C2v0zgi","CMD0wKW","y29UBMvJDca","ANbKBuC","BMfTzq","y3r4","DhjPzxmGCMu","Cg9W","uLfIshK","whbvwxa","y2XLyxjtDg8","uvnZwMS","s3HLtLq","AxjLza","Bgn4D3i","zuHTANa","vfPjqKu","zMDer1i","zhL0sfG","zgLZywjSzue","DvvquLK","vxnhA0m","Bg9Nsurhzw4","BhfJsfi","uMvJB25Uzwm","x0vysvnu","DxvrBLO","s1j5DKe","q3LQsKO","wg1NBNm","q29UzMLN","A1n0yxr1C0m","zxq9DxrMltG","quvmsK4","y3vYC29Y","thrqDMC","swnZEvy","y3PWqvu","A3Hwv3e","x2vUzhbVAw4","Bhm6ia","veTuAM0","C05fA0q","Aw5PDcbrB1m","BhvdtLK","Ec1TC2CTy3u","C1DSuum","tw9dq3y","rNzQCum","AwXLtMfTzq","CMvJzwL2zwq","EM5Pz2C","zv9ZDwnJzxm","y2HnyxHuCMK","BMnLq2XVC2u","uKDkCKe","zMLSDgvY","AxnFywnR","CMvZDwX0","rNbnDxy","zKDfzhG","Dg92zxu","zMPdD1O","CvP6r2q","sgfAzKi","BNvjvvO","zfDVCMTLCKC","AxnszwfKEq","AMzLEgm","yNLKq2u","zwfkBMO","BgjTEvy","BxL5CvO","B25JBg9Zzq","wwjoyLG","uNPcveq","ChHwDhi","yxnJCMLWDa","m3W0Fdf8nNW","mdaWma","zKvyzMu","DgLTzw91Da","quHbqwe","C3nHz2vfDMu","qLHlAgu","s2DuEM0","qNjPzgDL","ChbL","x3bPBMDqB24","rNzssue","r05cthu","EuPSsuG","tg5AwvK","uvPIENm","EsbJBg9Zzwq","x2nSzwfYvgK","Cxb6Dgq","t1bftG","zxj2AwnL","Bg93","DMDUthG","rhvkvLu","BMvLzf9Hy2S","CwjbtgG","id4G","vLH5B1q","y3vYCMvUDeK","EvD2wK0","DejmqvG","Bwf4uMv0CMK","z2v0sxrLBq","sLHYExq","tg9JAW","tufyx1jfvfi","A053wKy","C29YDa","ihn1y2nLC3m","B25fCNjVCG","jMPZy2fSBgi","BwvwC04","z2LhvK0","ChnSC0O","CMvTB3zLq2G","q09oveLovuu","EgjbEhi","l3DZl3yY","vwjisg8","s3jpyxy","zfjfy0O","Chv0","C3vIC3rYAw4","Bw9iEMq","yxPNA1u","vhPqweq","wxPZwuy","D24GCMvHC28","uhjPBwfYEuS","vgv0BuO","BMnVzgLUzW","Aw9UvgLTzw8","yuv0rwq","tMfTzq","qxrZtMy","tuPdz0S","BNrfBMrWB2K","ANLksLK","ww5wrvy","mhWZFdj8nhW","zgf0yq","EMXWt1K","ihrPBwvVDxq","vfH1wKG","vuPPAxi","ugfXqwG","igzPzwXKoIa","q29Kzq","EufPswO","u1DLENe","Ec11C2uT","uLDrq3K","vhvUwMS","sLr6s0y","q21YtvK","q0jgCKK","x2zVCM1HDeu","BK50zhe","EKnoCg4","u3Dssve","Bw9RExK","m3WYFdv8ohW","tM1WCNa","ign1CNnVCIa","se1NDKu","rgDZuue","ueXIELq","wePktK8","rLDpDhi","x1fVu01HBMe","t1PAvvq","CMrOChy","rgPtvLO","wurPz0i","rgT5Cuy","rKPXAwq","yw5ZzM9YBvq","A2rWufi","BwvKAwf0zwW","DKr5s0S","yNzUyNG","C29Tzq","sgruwM4","vK9Mu1q","ELjLvxK","C3rVCcbPBw0","teDiEKO","zMj2AhG","CMvHzhDYAxq","A1bxEum","DxrfAfe","s0fVwhO","CwDTs0S","qxfWCgO","v3HOBNu","A0jvu1G","CgzrEhq","shfnBgG","vM9WquC","qNbmreu","tgLZDgvUzxi","ExbL","DhvYBhi","t2n3rxG","EuXNDKq","rwrWB1i","uMzoC1O","AgLNAa","x2LUAxrhBg8","AgDNueu","uKXsD3m","C2DPza","s2frBuG","txzqu0O","veTyAgu","BKv5A0i","x2n1CNnVCK4","Be5ez0y","BuPYA1q","A3v6txK","uNjtAgW","wwHHAxO","nxWZFdr8mxW","rMXqA0y","ywnR","B1zJCuS","ALPqDgO","AKH1A2u","AvLPqNq","AvfkAMW","AxDqqvO","q2vfq1G","sMz5AKK","Dev2zw50","t3bLBKv2zw4","twLZC2LUzYa","zw1PDa","zM9YrwfJAa","ExzZD1y","CMvWBgfJzq","BM93","B25szwnLAxy","Cun1vxG","tvzssuC","zgvSzxrLrge","rujpEhG","ywXSq3vYC28","sufcs2m","EhvItKC","sg52tKS","CgLUz1rPBwu","EfvyDKO","yu5XAKC","tLHJDwO","wgfUAfm","CgvYC2LZDgu","wKzequu","y3fcCg4","x2rItMfTzq","seXHv1K","rLDt","y3jLyxrLtwu","Dg9cExrLCW","z3PIwvq","CNzHBa","Exb6v1G","vwvuyKe","C2nYAxb0","x3DHAxq","rM56v1K","ywWGy3vYC28","CvbOzeS","zLfmD3K","zgDSD1G","yMfSu2nVCgu","s05YquO","uhvNrLG","Bxzxzvi","mtq1nZy5y05ztxHQ","zgzdtNG","BNvTyMvY","C3zKte0","mNWWFdH8mxW","EgTmt1u","B2LUDfjLywm","CMvJB25Uzwm","Exfdqxy","EgPcr0i","x29WDgLVBNm","y3ruAw1LB3u","yLfqz3a","Aw5Lza","A1LUsxa","swXLuKS","zxjFDhrS","D0f6D0O","A2Djsge","yKv6DMS","zw5XDwv1zq","t0LeDha","wuzmtwS","rLvJt1G","t0r2z3G","A2fuve8","vefqzKW","shvrt0S","z2r0Bhm","Dg9hzw5LCMe","zw50zwqGDhK","uLHJuhO","y3jLyxrLuMu","rfb2r00","C2vYDMvYvgK","CuTevgG","sKzUyxO","zMLN","C2Lhs28","BM5vCxm","twLXqwm","y1v4t1q","CfDwAxa","DMzHuMS","s0LgCxG","DNLIDxK","x29Uq2XVC2u","Awvgqwe","v3zeAM0","tNvQAuS","AgDAAfu","sgLtuMm","DLnUCg0","z1juq00","zwL2rxa","tu1fuuq","v2Pkyxq","zufJAW","x2rLyNvN","ywTurum","zwzYEgG","rMLOvLm","Eu9gtw4","BMrLEa","u1DvBKC","zM9Yy2u","BgLTAxq","B25LCNjVCG","zgvSzxrL","Bhj5t3i","tgfoC1u","uuTdtvy","BwfOzwG","EKDUCLq","sM1hAxy","u1z3EM4","Cun1u3e","wgfOtMK","q2Dvy2i","y2fSBa","BwLdtMW","rg9vq3u","CMvZB2X2zq","B0jpCxa","zMHqrem","z2v0t3DUuhi","whvjuhq","DerlsLy","uKX0yw4","zg9Uzq","z2v0q3vYC28","AgvHzgvYCW","ywXSB2nvBNm","BMrWB2LUDfq","twX4CLG","zcWGDw5RBM8","Dg9oDw1Izxi","B25Uzwn0Aw4","D2TVDuW","EePLsha","DhHMshq","wNDQywm","CMvZzxrfBMq","BMDuAw1LCG","yw51Ce1LC3m","A0fbwgm","Cw9Z","BNrLCG","zw1LBNq","C0PXtu0","ywDLrxzLBNq","uwTZBKG","zw5HyMXLuw8","sgnsyMm","zKLIBLm","yxrHlcbKyxq","ENzpDge","x2XPC3rLBMu","Ew1vr3G","t29PsKq","y2HHCKnVzgu","wgXsthm","u1jkv0W","tKDWuNG","B2rsBhq","x194x21Zz18","y291BNq","Dxrjza","zwDYAK8","yLPgqNa","zxnuzhi","CM9YrxzLBNq","zMfhCgG","Cgf5Bg9Hzeu","ndbKshrsA08","CfDxChK","C0XPC3rLBMu","y2HLy2TdDxi","D2LSBfjLy28","DLLOB2i","tw9KDwXL","uenOCMi","Ae1LC3nHz2u","CgfYC2u","y29UDgLUDwu","BwvZ","zKDku1C","sePnt2K","AxnbCNjHEq","uMvmAMe","yxnZAwDU","ANbKCNu","y29UBMvJDfm","v3bLBgy","v3n2yve","vLDyEKq","DgHLBG","rK9MDKS","BwfW","C3vJy2vZCW","yxKSihrYEsa","Chv6ENe","s2Hryu8","BhrPCgXLihq","DhjHBNnHy3q","zNjVBu51Bwi","u09hChG","CgrwrNa","uLnwtvu","t3fTwfe","B2XKvMvYC2K","CvbKAuK","sgjsv2W","BM5Ly3q","v2vIu29JA2u","AgfZ","ogP3wMjYBq","tw5uzvq","svvTtMu","Bwu6ia","x3jLy29UBMu","zgrxD1O","q2Hkugu","Dw9zrLC","AgfZt3DUuhi","Ahr0rxi","CYbPBNn0yw4","u1bouhy","B2zMC2v0","CMLwEgK","AM9PBG","CM92AwrLigi","q0fVENq","DhjPBq","ChnmvKy","rhHAAuS","DNfvqLm","y29SBM8","AhvSvxa","vg9YBMq","x2HHBMrSzvi","qNDcBwW","C3HPB1O","yxHqzxK","Ef9MCM9UDgK","A1vmteW","B25TzxnZywC","CMvJzxzPzwq","CMvXDwLYzwq","zw5JB2rPBMC","yxv0B21HDgK","Bu9Kv0e","D3m6lY8","zxzirhq","suvtx0vsuK8","yNPny1y","y3jLyxrLt3a","sfnHv2i","EMTgsKG","Ec1TC2CTCw8","y29ktvy","tg9Nsuq","A1PKEfe","sNrZz3e","mtu1oda3mvLhrKn5Bq","wNzWBxu","zfzmyKC","uLjpuG","x3jLBw92zvC","sevNu1q","D0ryrMK","rvrMAeG","zw5KCg9PBNq","ihzHBgLKihm","y2XVC2veqG","zgrjrcWGzgu","ANjms1O","te1rrgW","qK50wLG","DMfdzLu","EgHmqMm","AeDnCw4","DcbSAw1PDa","DMvUDa","zxjHDg9Y","B2zM","yunJA2C","vhrVC3K","yNzwz0O","CNzHBfzHBhu","ChjVDg9JB2W","EvjLy29UBMu","CgjICdi","wwvrq1a","x3nLCuLK","BufLDuK","CMfTzq","AwXK","tKLetem","BMvxwMy","zg1SA0S","CMfTugfYyw0","yMvoCuy","B3bLBKrc","D2vI","x29UvgLTzw8","wgzODgW","B2nOteO","B2nRzxrgywK","yMLUyxj5vhK","rNjVBNrPzxi","BePtAxG","A1fRD24","zgDTsfi","ugDUDNO","A09AEuC","sgDVCg4","yKvOAKu","qLjiA0K","qwTHrgm","BMv3vMvYC2K","tgLwDwu","y05Xv1u","x3DZ","ihzHBgLKigq","r3HRDMW","yw5Hz2vY","ve52DwS","DxbKyxrLq3u","EKz0yvC","whPVvhy","q0PTBfy","wxHUz2m","DgLLCKPtt04","u0H2zxm","x2n1CNnVCK0","A0vgt1e","DxPOtwu","DxrMofDYAxq","vfjRB0u","B3bLBIa","CMvtEgS","B0zIBKy","wezPuNe","q2Pztfm","rKTfAK4","CgXLyxnLiha","sgD1wgS","igzHAwWSig0","weXUwNK","C3Dcz20","swnhwvm","EhnsDwO","CgHfsvy","CMvTB3zLrxy","mJqWoteWr21dwhjt","svnoEvi","u2vTEKe","B25tDg9Wsw0","CLzHBhvLCW","B25dBg9Zzq","yMXVy2TLza","EKfrD0O","B3DSwLm","z1jiCKm","CMvZzxrdB3u","BK9bAfO","lcbTyxGGCMu","AffyBNu","tejdCLG","sujxuuy","tg9yEw0","shDxsvG","Bg9N","EuvZwvm","shjluwG","x3nLBMrby2S","Efrurw52","x2jPBMfYEvq","Bwf4twvZC2e","wKf3q2G","BLPMv1q","D1HWy1e","wxLNs2W","y29Kzq","CNnVCKzPBgu","BMvgBfi","uK91uMO","sM9tEMu","BKXPBMu","ChjVy2vZCW","Cxjbr3K","q0nXA2q","tuzRzNu","BMf3DNO","werTwhO","uevRs0u","q09otKvdveK","B3nLrxzLBNq","CMTpr0S","DvjuD0O","C2v0y3vYC28","DKLnu0O","qMHZtge","rKfyzeG","vxfrzNe","D2fZq2XLyw4","Cg9PBNrbBMq","BuzPyvC","x3DZsw5ZDge","v05jrg8","A2v0ignVBNm","s2X1BKW","y2HnyxHdB3u","C3bSAwnL","yNvMzMvYzwq","C0z1r00","zNvMvwG","yMfSrxzLBNq","r215teu","zNnsyM4","uvjzwe8","vxDRqve","C0Xf","BMrWB2LUDca","B25SAw5L","sfHHCNy","t1jPEMe","C1fQEKq","DhLWzq","BMCGzMfPBgu","uK9zqLm","DgvZDa","uw5oy1O","yw5Nzq","AwnyD0S","C2r4CMu","vgH0rg0","rLPSDwG","vMTUwwC","wuP2y2O","CgLUz0XVC3m","rxbqwNm","r0Hzrei","wxz5q2i","BLLdEgi","tgnYvfi","yu1ss2G","C2rIBeS","zMvY","Eujnzgq","A1zSzwq","mhWYFdf8m3W","A2TVq3m","twrRt2O","BezSDxnO","z29PBMCGyxC","mdaWmdaWmda","sgLxt0e","tNHrwMK","s01JBNO","qKTIvKW","Dgv4Dc9Qyxy","DeLUDgvYy2u","rvjst1i","CMfzAfa","u2TPCcbWyxm","uwnlEwW","AMrNshm","CLLJqve","zvrXv2i","z3Hmqwu","Cfrqt3C","B25pCgvU","wunIBuW","su1wuKu","EwjVtwq","ndC5mJeZrgztt3H3","BxnNsuq","ywXS","yw1LoIa","Dg9mB3DLCKm","AfbRELe","zxjYB3i","x3bHDgHlzxK","A05dAvO","BunrrhG","CerWBK8","y3vYC29Yx24","t2jQzwn0","Bgzzt0W","zfnlDNG","vNzMr0W","BMHjAfG","rLbjwvC","z2vY","y3jLyxrLt2i","wuLbt28","AMTZAuW","zerIzLG","DMvYC2LVBG","zuzJzK8","y2XVC2u","sKv4Bgu","C09tueC","sMnlAKC","CMTLCKDSB2i","yKfnvMy","y2XVC2uSihC","C0nVDw50zxi","Ae9Wzw5fDMu","tu5hDg0","ugnPBeC","AxziEhq","vgLTzw91Da","zenvq3G","Eg9JBvi","x2DLBMvYyxq","BwvY","x2LUDgvYDMe","AwDHDg9Yt24","su5tvefova","C3rLBMvYCW","zgvS","qMTLyLq","v3jAvva","AgfUz2u","qxHqrwS","sLzAtfq","yNPjq2m","zgvMAw5Luhi","qLrNu0i","Dhj1y3rVCIa","u2r5sLm","x2LUAxrqCM8","z2vtEw5J","wgHxsKe","r0X6yw8","tvfct3u","DeTtEMm","u0TNtK8","C2v0sxrLBq","x3jLywr5q2W","uvzyDKy","DNb6B3a","EfvZzuvUDG","Cg9PBNrdB24","uKrzruu","AuvZyuq","zNjVBunOyxi","C2vUzf9Hy2S","BwvZC2fNztO","ChrVCG","uLHws2m","Cu1tuLa","CMvKDwnL","CMLLC0nVDw4","CKfhqxG","vMLkyMS","C3vIyxjYyxK","tNLfwg4","DwnLBNe","Bg9IywXty28","q3vZDg9Trxi","ChjVDg90Exa","mxW2Fdr8mhW","zgLZCgf0y2G","ANnxy0e","ywDL","B25nzxnZywC","uKzquuS","y29UBMvJDeu","yxrLq291BNq","sLnptLa","Dhr3Awq","thbvD1q","zxPmyMO","Fdv8n3WZ","yNLL","zwDRsMC","x2rPC2nVBM4","qLfJtg0","t2jSCgm","CgHUrhu","wezuyvu","twvZC2fNzuu","rfDXsg8","vLHZDxa","AeD0EKe","zMLUza","zMLSzw5HBwu","uKXItNC","teXmz08","zw1dzeS","B3bLBG","yNL0zxm","qwDbAKW","vMDyD0W","v1Hkv1C","qLzHtwy","vuvqy04","r1z5tem","Evnqwxm","Cgf5Bg9Hzfq","z2v0qwXS","rxzLBNq","D3fJwxG","tu1uvfG","CeTzwKe","Aw9U","y29UBMvJDa","CMr3r00","mNW1Fda","qMXWwwS","t2LrBgS","wgfkrKC","DwzOrMy","q2DPzNa","AK96vNe","zKvWy3O","wLHot2C","CgLUz09Uy2u","ChPJBvm","yMLUyxj5","rxfOtuK","ignVzgu6ia","zNjywKe","CMv0CNLdB3u","zMXVB3i","uxzVtLm","sfnbsgS","ve5Vrg8","vuvqyxC","zhztzwy","wuzXAee","vNnQue4","DuXLEgS","C2v0q3vYC28","tKzAEKW","rwnPt2S","s0rIDhC","zNDZxZeUmc4","EgHLy1G","q2vizgC","ywf4wKG","BgvY","sujNqva","AxfOCNO","y09Wzw4","zvD0wMu","y1fsy0W","twTLCwC","t0n0zg0","ywnRDxbfBMq","CLb5AuO","x2LZtwLUAvq","wvvxt0G","D0jxAvi","Dw5RBM93BIa","B3bLCNr5","zgv2AwnLx2K","D2n3tLG","z1rPBwvVDxq","EgPWBhe","yxKSig5LDhC","zNjVBNrPzxi","tKfusvzfx0u","Dgn2rNa","CM92AwrLihy","wNLcBxy"];return aa=function(){return t},aa()}Ut.d=(t,e)=>{let r=W;for(var i in e)Ut.o(e,i)&&!Ut.o(t,i)&&Object[r(1737)+r(1866)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=B;Ut.o=(e,r)=>Object[t(1771)+"e"][t(1431)+t(1866)][t(1326)](e,r)})(),(()=>{let t=B,e={HrKQh:function(r,i){return r!=i},SKgNO:t(1387),tBLAX:t(505)+"le"};Ut.r=r=>{let i=t;e[i(1582)](i(622)+"d",typeof Symbol)&&Symbol[i(519)+i(665)]&&Object[i(1737)+i(1866)](r,Symbol[i(519)+i(665)],{value:e[i(1747)]}),Object[i(1737)+i(1866)](r,e[i(1069)],{value:!0})}})();var Oe={};(()=>{let t=B,e={OcwEx:function(a,n,s){return a(n,s)},Cgifp:function(a,n){return a!==n},WXsfg:t(631),pRILM:function(a,n){return a(n)},GNBLu:function(a,n){return a+n},pmkkS:function(a,n){return a+n},yJlIH:function(a,n){return a*n},yOFMn:function(a,n){return a(n)},nXJOc:function(a,n){return a===n},XuIPt:t(1241),jnOqR:"rDeyU",ngpYi:function(a,n){return a(n)},XPees:function(a,n){return a(n)},oVcqK:t(1040),OCtdm:"ffff",mfusF:t(1251)+t(495)+t(1784),svdLM:function(a,n,s,l){return a(n,s,l)},Nmprp:"cursor.s"+t(1059),PyqXo:t(701),BRHkI:function(a,n,s,l){return a(n,s,l)},mPSDI:t(965),gxLAe:t(1905),wtbxc:t(731),sdblK:t(1114),SWezq:function(a,n){return a(n)},NyEXn:t(1690),BKxRa:function(a,n){return a||n},Zvpmu:function(a,n){return a>n},KUfdU:t(1081),nawvz:function(a,n){return a<n},QvkZs:function(a,n){return a===n},fjCwZ:t(1085),cZqLL:function(a,n){return a-n},ochLJ:function(a,n){return a-n},CSvSS:function(a,n){return a===n},aEipl:function(a,n){return a<n},qKDTh:function(a,n){return a!==n},XJpIH:function(a,n,s){return a(n,s)},jHuke:function(a,n,s){return a(n,s)},dArkc:function(a,n){return a!==n},Pgnvz:function(a,n,s){return a(n,s)},RXcPz:function(a,n){return a(n)},Gruvj:function(a,n,s){return a(n,s)},dgmHR:function(a,n){return a&n},TunZk:t(1204)+"required"+t(1115)+t(1909),dgXIX:"Missing "+t(1455)+" field: "+t(836),Gglgy:function(a){return a()},ULrTn:function(a,n){return a(n)},eurox:function(a,n){return a!==n},bDIuh:function(a,n,s){return a(n,s)},VsjPN:t(1434),turlr:function(a,n){return a!==n},czpAU:function(a,n,s){return a(n,s)},CBFrI:function(a,n,s){return a(n,s)},rPyiJ:t(1699),rkOGK:function(a,n,s){return a(n,s)},wRTmY:function(a,n,s){return a(n,s)},ksehG:function(a,n){return a(n)},WBrfQ:function(a,n,s){return a(n,s)},TKXhe:function(a,n,s){return a(n,s)},KlunL:function(a,n,s){return a(n,s)},YygKl:function(a,n){return a!==n},RfNsZ:function(a,n,s){return a(n,s)},RFPQK:function(a,n,s){return a(n,s)},MGzDm:function(a,n){return a!==n},lcxwr:function(a,n,s){return a(n,s)},vDyKK:t(932),fFOhW:t(1961),vaCfU:function(a,n){return a(n)},zvOta:function(a,n){return a(n)},PugFX:function(a,n){return a>>>n},EdpoR:function(a,n){return a(n)},RQbHy:function(a,n,s){return a(n,s)},NpckT:function(a,n){return a(n)},DyVhO:function(a,n,s){return a(n,s)},sJqMM:function(a,n){return a(n)},XpUYp:function(a,n){return a(n)},KFPpu:function(a,n,s){return a(n,s)},wAzwJ:function(a,n){return a===n},OKGdg:t(1204)+t(1455)+t(1115)+t(1468),vfaRk:function(a,n){return a===n},miCNl:t(1204)+t(1455)+" field: service",dUIwc:function(a,n){return a===n},NIDLC:"Missing "+t(1455)+t(1115)+t(506),HycWX:function(a,n){return a(n)},TetmJ:function(a,n){return a&n},zSCbz:function(a,n){return a(n)},HnvNK:function(a,n){return a(n)},tCyDC:function(a,n,s){return a(n,s)},qPhdK:function(a,n,s){return a(n,s)},qnHwQ:"Unimplem"+t(1277)+"pe: ",BCADH:function(a,n){return a>>n},dfCNx:function(a,n){return a>=n},emCdK:t(1673)+t(1489),LvmCK:function(a,n){return a>=n},BkUmR:function(a,n){return a>n},rsOAw:function(a,n){return a>n},xhecX:t(936)+"t limit",JXryt:function(a,n){return a!==n},QzPdf:t(1782),ILMKb:function(a,n){return a<n},VXyoT:function(a,n){return a+n},fGJSW:function(a,n){return a&n},PDiPR:t(1789),BKbVL:t(890),YGCQI:function(a,n){return a|n},GmyLE:function(a,n){return a<<n},IMVRE:function(a,n){return a&n},vpzop:function(a,n){return a&n},gdtls:function(a,n){return a>=n},mgpYE:function(a,n){return a+n},qCuSq:function(a,n){return a+n},VknYg:function(a,n){return a+n},lbmyV:function(a,n){return a<<n},sWlQC:function(a,n){return a&n},fvGJk:function(a,n){return a>=n},PWgZu:function(a,n){return a<=n},uPOGU:function(a,n){return a==n},HXarv:function(a,n){return a+n},xcfPE:function(a,n){return a+n},JYmDF:function(a,n){return a!==n},hPkzQ:function(a,n){return a|n},fgDGR:function(a,n){return a<<n},LLLgO:function(a,n){return a&n},jrLKZ:function(a,n){return a&n},hGtzA:function(a,n){return a<<n},XhWJA:function(a,n){return a&n},xocmR:function(a,n){return a+n},VaPfl:function(a,n){return a>>n},ISNyR:function(a,n){return a+n},AMMKS:function(a,n){return a&n},ZQtzY:function(a,n,s){return a(n,s)},avWmE:"ping_onc"+t(923)+"t",sdxre:function(a,n){return a(n)},eeCEF:function(a,n){return a(n)},cPBtM:t(1042),AHAAa:function(a,n){return a<=n},IBgAP:function(a,n){return a<n},XJJNO:function(a,n){return a<n},WOyml:function(a,n,s){return a(n,s)},RXVKc:t(1791),MZBXo:t(1554),BrjEJ:function(a,n){return a>=n},evHDt:function(a,n){return a<n},rRrPS:function(a,n){return a<n},fGEdx:function(a,n){return a>>n},Otbsd:function(a,n){return a|n},OoiJD:function(a,n){return a>>n},FWOtr:function(a,n){return a|n},qqKfM:function(a,n){return a&n},FJqid:function(a,n){return a&n},HSaWb:function(a,n,s){return a(n,s)},pIKYs:function(a,n){return a+n},FuiBW:function(a,n){return a(n)},qMSRP:function(a,n){return a&n},YJvcj:function(a,n){return a||n},xUXvJ:function(a,n){return a!=n},FDrnp:"undefined",YzsYF:function(a,n){return a===n},sGDhM:t(1311),fzLlA:function(a,n){return a>=n},ewbKO:function(a,n,s){return a(n,s)},vqixE:function(a,n){return a&n},gzbYT:function(a,n,s){return a(n,s)},SHves:function(a,n){return a-n},VvFpF:function(a,n){return a+n},uNSuB:function(a,n){return a*n},gvybV:function(a,n){return a+n},ZUkPb:t(1698),FUcOX:t(1030),AgAjL:function(a,n){return a&n},rMgJo:function(a,n){return a&n},nrpUc:function(a,n){return a&n},Yxngc:function(a,n){return a<<n},vHGqq:function(a,n){return a&n},ckaqS:function(a,n){return a<<n},PcilG:function(a,n){return a&n},NGpRx:function(a,n){return a&n},sxioZ:function(a,n){return a&n},UwkAQ:function(a,n){return a&n},UUsWz:function(a,n){return a<<n},BlpYk:function(a,n){return a&n},gahpc:"sXTcS",pTPOw:function(a,n){return a(n)},gzCzb:function(a,n){return a&n},kOZyG:function(a,n){return a&n},hgZhU:function(a,n){return a<<n},LcrTR:function(a,n){return a|n},kZdxQ:function(a,n){return a>>>n},rgtZL:function(a,n){return a>>>n},XDmXz:function(a,n){return a>>>n},mCQDx:function(a,n){return a===n},VocrE:function(a,n){return a===n},JVZLT:function(a,n){return a<n},zCNpn:function(a,n){return a<n},XOvMB:function(a,n){return a<n},VOfST:function(a,n){return a<n},IqMFL:function(a,n){return a|n},wkouL:function(a,n){return a&n},oFbnF:function(a,n){return a>>>n},jsWcA:function(a,n){return a+n},zaRCr:function(a,n){return a!==n},YBafR:function(a,n){return a&n},kbnOy:function(a,n){return a!==n},pfAyh:function(a,n){return a&n},MnTeT:function(a,n){return a+n},eqArn:function(a,n){return a!==n},HcRbc:function(a,n){return a|n},OOTbh:function(a,n){return a>>>n},wRrdU:function(a,n){return a&n},uuquX:function(a,n){return a>>>n},MdkOj:function(a,n){return a|n},pWVip:function(a,n){return a>>>n},hXsBU:function(a,n){return a!==n},dXMwV:function(a,n){return a|n},fEpcz:function(a,n){return a!==n},BTgSB:function(a,n){return a|n},heLIe:function(a,n){return a|n},TFRiq:function(a,n){return a===n},YKkBM:"AvZhk",mvWeR:function(a,n){return a|n},CCqkd:function(a,n){return a|n},CgUcb:function(a,n){return a<<n},GRoMT:function(a,n){return a<<n},nnUqs:function(a,n){return a<<n},Zmflu:function(a,n){return a<<n},CJPbI:"TBsJl",fufUh:function(a,n){return a|n},ReLja:function(a,n){return a|n},xexcC:function(a,n){return a<<n},iYiBt:function(a,n){return a<<n},tJBUJ:function(a,n){return a|n},CmrMY:function(a,n){return a<<n},PLPMU:function(a,n){return a<<n},Sttuw:function(a,n){return a>>>n},dDbfX:function(a,n){return a|n},lRhSe:function(a,n){return a|n},WPZAN:function(a,n){return a>>>n},vjEiy:function(a,n){return a|n},jOzVq:function(a,n){return a|n},Zwjac:function(a,n){return a<<n},VWXzD:function(a,n){return a<<n},TzPXD:function(a,n){return a&n},VJgRo:function(a,n){return a>>>n},chaLS:function(a,n){return a&n},wXpcQ:function(a,n){return a>>>n},VoqjB:function(a,n){return a>=n},swBgm:function(a,n){return a%n},SRJWL:function(a,n){return a*n},DxZiK:function(a,n){return a===n},CAozt:function(a,n){return a&n},mybJo:function(a,n){return a&n},otHjT:function(a,n){return a&n},LmTBc:function(a,n){return a>>>n},vaRFv:function(a,n){return a+n},kBUSX:function(a,n){return a>>>n},lqcHR:function(a,n){return a|n},HxtTT:function(a,n){return a<<n},SemzA:function(a,n){return a===n},KvvMI:t(1576),PLbzT:function(a,n){return a&n},kVZoK:function(a,n){return a>>>n},lSDlr:function(a,n){return a>>>n},QZbzs:function(a,n){return a|n},BwBml:function(a,n){return a===n},whEax:function(a,n){return a>>>n},yWvZM:function(a,n){return a===n},eWtZe:function(a,n){return a===n},FZluh:function(a,n){return a===n},MJCgK:function(a,n){return a&n},QUzgj:function(a,n){return a&n},VzYcp:function(a,n){return a&n},OqmXQ:function(a,n){return a>>>n},CCPGV:function(a,n){return a>>>n},YCbmL:function(a,n){return a&n},nOAhZ:function(a,n){return a&n},YbNbX:t(1191)+"2|0",tpyzw:t(758)+"OR",egkJg:"CONNECTI"+t(648),gLiJv:t(1074)+"IES_ERROR",IOhTI:t(1873)+t(1474),iWQJV:t(1039)+t(1819),Kyevn:t(1957)+"0",ifxfI:function(a,n){return a(n)},LTIoq:function(a,n){return a!==n},odRlt:t(1181),hggPE:t(1012),atBbh:function(a,n){return a===n},hiSHG:function(a,n){return a>>>n},efrxh:t(1365),qCuUx:t(545),cNqWU:"hoDTO",PfbTj:t(979),xhfJB:function(a,n){return a>=n},LoXym:function(a,n){return a===n},wLFel:function(a,n){return a instanceof n},dvfaV:t(782)+t(880),ZXNOg:function(a,n){return a===n},yLXBj:function(a,n){return a===n},RSVMU:function(a,n){return a===n},MMEQD:"DzZIG",dREcJ:function(a,n){return a===n},HdTZn:"EAUXU",tcvFp:"close",kcWAg:t(1506),GYEJS:"fFvmq",FblNh:function(a,n,s){return a(n,s)},gDTWB:t(1801),zfWik:function(a,n,s){return a(n,s)},DuJVU:function(a,n){return a===n},Ejbfc:t(1113),mJrkT:function(a,n,s){return a(n,s)},IcsyV:function(a,n,s,l){return a(n,s,l)},FnzWY:t(1018),UsGkC:function(a,n){return a&&n},jyJJY:t(471),HLaWY:function(a,n){return a||n},icXwK:"ack_code",bZFBp:t(1242),nhIhX:t(1851),yLgvD:t(1919),dvSef:t(868),vIMSJ:t(1918),kYQkY:"bttOj",qwhCC:function(a,n){return a||n},HiSRc:function(a,n){return a!=n},UeXOd:t(684)+t(625)+"ltiple t"+t(1891)+"process",Wvlks:t(1352),VxRry:t(1538),mjqfa:function(a,n){return a&n},EseWZ:function(a,n){return a&n},DPvGM:function(a,n){return a<n},UxlHU:function(a,n){return a>=n},tAeSC:function(a,n){return a&n},QcKyl:function(a,n){return a>=n},ddWwZ:function(a,n){return a|n},AKQkh:function(a,n){return a<<n},WMTpx:function(a,n){return a&n},tAGXo:function(a,n){return a+n},yQuWb:function(a,n){return a&n},pKaub:function(a,n){return a||n},qZzGd:function(a,n){return a||n},ezLbj:function(a,n){return a<n},OvHVe:function(a,n){return a<n},JTzKF:function(a,n){return a|n},yhrfr:function(a,n){return a&n},WNIDo:function(a,n){return a!==n},STjlG:t(1207),rMQVA:function(a,n){return a&n},FKEjN:function(a,n){return a>>n},pslsJ:function(a,n){return a|n},BQcLm:function(a,n){return a&n},kuzMy:function(a,n){return a&n},kULLL:function(a,n){return a!==n},YFqhA:"roerh",sFuGM:function(a,n){return a|n},ZHyMI:function(a,n){return a==n},ktWeH:t(616),neFlR:function(a,n){return a===n},ZZCyO:t(1301),zbsuU:function(a,n,s,l){return a(n,s,l)},ssjOp:function(a,n){return a instanceof n},QSsZk:function(a,n,s){return a(n,s)},TRkoE:function(a,n,s){return a(n,s)},QFAee:function(a,n,s){return a(n,s)},KAoXz:"gEiXe",MNGtm:function(a,n){return a instanceof n},xdOkN:function(a,n){return a!=n},meVsN:t(921)+t(741),oXXAB:"CNitl",dvifE:function(a,n){return a==n},uoYFW:"boe",BVaMf:t(1048),NFZzL:function(a,n){return a>=n},QVXvF:function(a,n){return a!==n},zBacm:function(a,n){return a(n)},QUeih:"YuZoj",xsRuj:t(1669)+t(1038),TZIBE:t(1079)+t(719)+t(1540)+"P",puzzq:t(1836),IBWQF:t(1865)+"reason",IUmNe:t(533),fIbnS:function(a,n){return a===n},VdzCc:t(1336),dCUCx:function(a,n){return a(n)},ueyjC:function(a,n){return a!==n},tKSzc:"ePEYO",vJAtA:"idb",Ntxtm:function(a,n,s,l){return a(n,s,l)},uTdUl:function(a,n){return a+n},vQGhJ:function(a,n){return a(n)},nLRib:function(a,n){return a===n},ZihcD:t(749),MiqAc:t(702),TKuoP:"EUuzi",zUyfg:function(a,n){return a>>n},sgSVv:function(a,n){return a&n},ybuUm:t(465),OIDtp:"DCPxb",WDNOr:function(a,n){return a||n},dcMkO:function(a,n){return a||n},pBHhm:function(a,n){return a||n},KDbtw:function(a,n,s){return a(n,s)},nNtdq:function(a,n){return a===n},egZuX:t(1009),vgnLx:function(a,n){return a||n},FlPkF:function(a,n){return a||n},axPey:"store",FIdJA:function(a,n){return a===n},kpXJg:t(1306),XIzZo:function(a,n){return a!=n},frXZA:"init QoS"+t(578)+"d",HrSSb:t(1353),CeXMt:"message_id",DAFUq:t(838),vecqG:"kitud",MvPSJ:function(a,n){return a<<n},rYcAQ:function(a,n){return a<n},GLwoj:function(a,n){return a|n},IhGGb:function(a,n){return a<<n},myyqZ:function(a,n){return a-n},FPIYW:function(a,n){return a|n},wfXTY:function(a,n){return a|n},rasaw:function(a,n){return a<<n},wrrNZ:function(a,n){return a<<n},ItnHK:function(a,n){return a&n},uZusn:function(a,n){return a+n},HkRWQ:t(1570),RGJrA:function(a,n,s,l){return a(n,s,l)},aokEh:function(a,n){return a(n)},yEsYS:t(865)+t(492),rIHzG:t(1020),QiImW:function(a,n){return a(n)},Ukcib:t(1451)+t(1948),wDXFi:"x_fronti"+t(618)+"ck",XFiRq:t(1451)+"er_is_ack",RzBTD:t(1451)+t(1945)+t(1180),XUXaC:function(a,n,s){return a(n,s)},DfoZC:function(a,n,s,l){return a(n,s,l)},XwuGi:function(a,n,s){return a(n,s)},YHvPb:t(1063),piIXr:t(590),lJSix:function(a,n){return a||n},srzUh:t(1011),lctyL:function(a){return a()},pCDup:t(623)+t(676)+t(993),bAMVf:t(921)+t(741)+";charset=utf-8",BhsLa:t(1830),toveu:function(a,n){return a(n)},nuIUZ:function(a,n){return a===n},ROuRj:t(538)+"e",UeTbA:function(a){return a()},NnPvc:function(a,n){return a(n)},DgsQA:function(a,n){return a>n},wegoV:function(a,n){return a(n)},kVled:function(a,n){return a!==n},kNCiZ:t(1316),dVLbG:function(a,n){return a>>>n},RWQCy:function(a,n){return a+n},NujiK:"integer "+t(1917)+"e",QexTD:function(a,n){return a>=n},EciOk:function(a,n){return a&n},qbALh:function(a,n){return a+n},maheh:function(a,n){return a!==n},vJrTp:t(514),Ffqhy:function(a,n){return a>>>n},UbHHo:t(1108)+"1",DmaqS:function(a,n,s,l){return a(n,s,l)},CyjJJ:function(a,n){return a+n},LsfPt:function(a,n){return a<<n},LQhYD:function(a,n){return a<<n},UEPaw:function(a,n){return a<<n},WsvaQ:function(a,n){return a+n},qomWE:function(a,n){return a|n},SYKxT:function(a,n){return a<<n},sOSPG:function(a,n){return a+n},sOCXK:function(a,n){return a+n},fhPDC:function(a,n){return a>>>n},zLxZj:function(a,n){return a&n},bEhjE:function(a,n){return a+n},RLbNw:function(a,n){return a&n},xqWgo:function(a,n){return a+n},eqfvE:function(a,n){return a>>>n},uUpas:function(a,n){return a+n},mAeuI:function(a,n){return a&n},Wxhnu:function(a,n){return a+n},KgTzm:function(a,n){return a+n},DWqHo:function(a,n){return a&n},EIrDE:function(a,n){return a+n},XahNi:function(a,n){return a&n},TPYJO:function(a,n){return a>>>n},FBQSM:function(a,n){return a&n},ujxvQ:function(a,n){return a>>>n},iqhrz:"DNgLV",yCUqE:function(a,n){return a<n},vpsry:function(a,n){return a|n},QZarG:function(a,n){return a<<n},xkLOU:function(a,n){return a|n},tiTvl:function(a,n){return a<<n},pfQxt:function(a,n){return a|n},ypzWX:function(a,n){return a&n},nTaQM:"nNqfq",EDUcZ:"LGLGU",lNDgF:t(1991)+t(965),nMngF:function(a,n){return a(n)},ILgSq:function(a,n,s){return a(n,s)},mjDzu:function(a,n,s,l){return a(n,s,l)},egrlU:"FILE_NOT_EXIST",TSGGV:function(a,n,s){return a(n,s)},dsOWg:t(1445),ogemF:"njhBA",IABKc:function(a,n,s){return a(n,s)},zzYgu:function(a,n,s){return a(n,s)},WvDjm:"nYCxb",VolQF:t(1728),eTqWb:t(1084),uTfHl:function(a){return a()},hoiXS:t(961),fbvhx:function(a,n){return a(n)},rBWdl:t(1608)+"r",OLPMk:function(a,n){return a!==n},FHMRU:t(1587),LnZYY:t(1672),KMcnz:t(1757),wDHdA:t(1591),pYvGV:"x_frontier_msgid",MQBOu:function(a,n){return a(n)},LPaOu:function(a,n,s,l){return a(n,s,l)},SRLbq:function(a,n,s){return a(n,s)},oBOqp:t(1006)+"rsor_name",fEXfe:t(1006)+"rsor_value",hjyio:t(588),GGCEd:t(1189),GPfaq:function(a,n){return a+n},gaeMY:function(a){return a()},tAuzi:function(a){return a()},httEr:function(a,n){return a===n},xFEOg:function(a,n){return a===n},nyvPM:function(a){return a()},YFLMk:function(a,n,s){return a(n,s)},VgXwL:t(1868),YHdpZ:function(a,n){return a(n)},qrAGy:function(a,n){return a===n},XzoTv:function(a,n){return a+n},Osbck:t(2006),HEgST:t(633),EbnJV:function(a,n,s){return a(n,s)},LcDZh:"reconnect",eZboP:t(849),qpztd:"ZRyUW",bzICc:t(1807),gRdhI:function(a,n,s){return a(n,s)},NxQZi:t(1785),XWDaz:t(1419),gJyqA:t(1977),dbvjF:function(a,n,s){return a(n,s)},coJMV:function(a,n,s){return a(n,s)},xjBGB:"aCUle",CeECX:t(650)+t(1013)+"s",NzmbG:function(a,n,s){return a(n,s)},geclr:function(a,n){return a===n},kEFOQ:function(a,n){return a!==n},LfaWp:t(1140),pKYZA:function(a,n,s,l){return a(n,s,l)},DCrVO:t(819)+t(1656),uWFHJ:"auto",CeHdg:function(a,n){return a==n},hAlih:function(a,n){return a===n},OwrPm:t(1553)+t(1875)+t(1951),NrmxQ:function(a,n){return a(n)},UTbXq:"please p"+t(793)+t(889)+", WebSoc"+t(1618)+t(1739)+"is undef"+t(1260),beNqF:t(1708),OiQlk:t(1117),SOGpx:t(1154)+"ediately reconnect",bEzvk:t(1632),pADai:"offline",XLnZy:function(a,n){return a!==n},FAXdH:"https:",vKpHN:"wss://",Bkohv:"bd_did",dTuZQ:t(1781),QRYXO:function(a,n){return a==n},RDYEE:function(a,n,s){return a(n,s)},HrvjT:t(1511),AkaDc:t(1848)+"0",jJUil:t(1465),zReUy:t(872),KxeNT:"CdYGh",sTrpu:t(496),QfTfu:function(a,n){return a-n},VwAWa:function(a,n){return a(n)},jZPtj:function(a,n){return a>>>n},mOdWA:function(a,n){return a(n)},Tornd:"iABJn",PwNWv:t(1088),KzhhK:function(a,n){return a(n)},nmBas:t(1794),PdxBx:"FRONTIER>",siGKo:function(a,n){return a-n},wBWiR:function(a,n){return a===n},MMrVq:t(513),xJKQO:t(1805),ieFAa:"LVLmH",BJCec:t(799)+"4",kkoCs:"message",DxpUy:function(a,n){return a<n},HwWIX:function(a,n){return a(n)},jfexc:function(a,n){return a(n)},pdVFp:function(a,n){return a&n},tttuv:function(a,n){return a+n},EJZcB:function(a,n){return a|n},LUTJH:t(1600),SzxSy:"gZupl",xVlhG:function(a,n,s){return a(n,s)},riVxi:function(a,n,s){return a(n,s)},kYfrQ:function(a,n,s){return a(n,s)},JUwGJ:t(1193),cSxsn:t(662),hlarG:t(486),HqMlh:function(a,n){return a|n},NgIlg:function(a,n){return a&n},ZFDAE:function(a,n){return a&n},zEyjh:function(a,n){return a&n},FWGez:function(a,n){return a>>n},WzGGR:function(a,n){return a!==n},BpXau:t(812),aNqjG:function(a,n){return a!==n},Mkeqg:t(1375),MoCCv:t(1910),qJApx:t(1715)+t(1433)+"ce not i"+t(691)+"ed",Oymwe:function(a,n){return a===n},yAarF:"close, w"+t(540)+t(1055),DCkSe:function(a,n){return a>>>n},fDJcA:function(a,n){return a>>>n},MUPnN:function(a,n){return a<n},Jacik:function(a,n,s){return a(n,s)},dNkgU:function(a,n){return a+n},ppzDp:function(a,n){return a&n},aCckg:function(a,n){return a!==n},iHCBQ:function(a,n){return a+n},DzYiy:function(a,n){return a>>>n},NRyPA:function(a,n){return a>>>n},kYnIp:function(a,n){return a+n},XGLUc:function(a,n){return a!==n},lwNlx:function(a,n){return a>>>n},ASgnb:function(a,n){return a&n},MVRIG:function(a,n){return a+n},SNekn:function(a,n){return a>>>n},BpLDE:function(a,n){return a+n},cvWca:function(a,n){return a!==n},gXnFQ:function(a,n){return a|n},Qukbi:function(a,n){return a+n},XBEnG:function(a,n){return a|n},zGnrT:function(a,n){return a>>>n},JHJev:function(a,n){return a&n},YIAOo:function(a,n){return a+n},QAAQR:function(a,n){return a+n},TNvuk:function(a,n){return a!==n},CjYLS:function(a,n){return a&n},ivHxt:function(a,n){return a|n},kdpPR:function(a,n){return a==n},beJkz:t(1553)+t(1902)+t(1531)+t(1362)+"a must b"+t(2003)+"ng or an arraybuffer",pWWpy:function(a,n){return a==n},aMRKh:function(a,n){return a!=n},BdHke:function(a,n){return a instanceof n},cYVvN:function(a,n){return a instanceof n},bbcVV:function(a,n){return a(n)},HPZyl:function(a,n){return a(n)},oOYZs:t(1553)+"rovide a"+t(1480)+t(1059),yjtDR:function(a,n){return a instanceof n},GsTqw:function(a,n){return a===n},svYXi:function(a,n){return a!==n},SVwzn:t(1640),KuRGl:"sent",nEykB:t(1267),eHmjp:function(a,n){return a!==n},bQPgp:t(1936)+"econnect"+t(475),YnVEV:t(1190),OOexn:t(1532),pUZPI:t(987),PcVLs:function(a,n){return a!==n},unfsV:t(1334),XanhS:t(707),moHzd:function(a,n){return a*n},XJjey:function(a,n){return a*n},iQJjl:function(a,n){return a/n},uzhMe:"Window",siKFn:t(1696),IleRK:t(671)+t(1027)+t(1769)+"pe",nZfWT:function(a,n){return a!=n},dGIds:function(a,n){return a==n},Rigdp:function(a,n){return a!=n},SAHAJ:function(a,n){return a===n},gwfSC:"SharedWo"+t(1713)+t(863),MlxrX:t(823)+t(493)+t(1243),snAEr:function(a,n){return a===n},SwtLw:function(a,n){return a!=n},xjplq:t(1372)+"qos__"};Ut.r(Oe),Ut.d(Oe,{FWS:()=>Ng,CustomErrorEvent:()=>xl,createCloseEvent:()=>Et,ReconnectEvent:()=>fl,createErrorEvent:()=>lt,decodedFrame:()=>an,createOpenEvent:()=>_l,CustomCloseEvent:()=>hl,createReconnectEvent:()=>Sa,FrontierMessageEvent:()=>gl,encodeFrame:()=>qt,createMessageEvent:()=>wl,OpenEvent:()=>ml,ErrorCode:()=>dn,Event:()=>ar,MessageEvent:()=>pl});let r="";function i(a=""){let n=t,s={kQkwn:function(l,f,m){return e.OcwEx(l,f,m)},KTTvw:n(1690)};if(e[n(1824)](e[n(777)],e.WXsfg))this[n(1205)](n(1690),s[n(1519)](_0x126a23,s.KTTvw,{..._0x316e19,message:_0x109573[n(864)]||""}));else{let f=""+Date[n(1209)](),m=r||(r=e[n(807)](x,a)),y=Math[n(689)]()[n(519)](16)[n(1895)](-6);return e[n(1051)](e[n(1051)](e.GNBLu("02",f),m),y)}}function o(){let a=t;return e[a(658)](1e4*Date[a(1209)](),Math[a(1835)](e[a(1052)](1e4,Math[a(689)]())))}function c(a){let n=t;return e[n(658)](e.yOFMn(Array,8)[n(1437)]("0"),e[n(1172)](parseInt,a,10).toString(2))[n(1895)](-8)}function d(a){let n=t;if(e.nXJOc(e[n(1333)],e[n(835)]))_0x1224b5.body[n(1879)+"ild"](_0x4235cf);else return(e[n(1907)](Array,4)[n(1437)]("0")+parseInt(a,2)[n(519)](16))[n(1895)](-4)}function u(a){let n=t,s=a[n(479)](/\./)[n(1405)](m=>c(m)),l=[];return l[0]=e[n(760)](d,s[0]+s[1]),l[1]=e[n(1907)](d,e[n(658)](s[2],s[3])),[e.oVcqK,e[n(1194)],e.oVcqK,e[n(1194)],e[n(1194)],e.OCtdm,l[0],l[1]][n(1437)]("")}function x(a){let n=t,s={XaJFG:e[n(686)],vXarM:function(l,f,m,y){return e[n(1250)](l,f,m,y)},LMQDl:e[n(1131)],vnPiI:e.PyqXo,ySPYs:function(l,f,m,y){return e[n(1525)](l,f,m,y)},pmzmW:e[n(1934)],UTQYo:e[n(1678)],ufhFf:function(l,f,m,y){return l(f,m,y)},JoSze:e.wtbxc,WrZUP:n(1991)+n(965)};if(e[n(705)](e[n(1655)],e[n(1655)])){let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1639)](a),f=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(a);return l?e[n(1118)](u,a):f?e[n(1118)](h,a):n(1664)+n(1664)+n(1664)+n(1664)}else{let l=s[n(1822)].split("|"),f=0;for(;;){switch(l[f++]){case"0":_0x52f76b=_0x46c819(0,_0x17a58e,_0x140664);continue;case"1":_0x1f999d=s[n(579)](_0x1aa30b,_0x1e8ff2,_0x3268da,_0x30c893[n(1905)]||0);continue;case"2":_0x5cfdaf[n(1580)](s[n(1484)],_0x155363,_0x11acca[n(1905)]);continue;case"3":_0x38cbdc[n(1580)](s[n(1987)],_0x509562);continue;case"4":_0x5a8e2=s[n(1809)](_0x3f9a0c,_0x5510b2[_0x278578[n(1695)+n(748)]],_0x24c215,_0x9b9bb7);continue;case"5":_0xcd8db2[n(1580)](s[n(484)],_0x4fe424);continue;case"6":_0x5ec833[n(1580)](s[n(1922)],_0x3974fc);continue;case"7":_0x41cc38=s[n(1823)](_0x4275a5,_0x335612[n(1412)+"er"](_0x4cf9b7[n(995)]||_0x3a7c66),_0x24f97c,_0x368521);continue;case"8":_0x374ed3.log(s[n(1595)],_0x39088b);continue;case"9":_0x28f332=s[n(1809)](_0x4a93ef,_0x3c7594[n(1695)+n(748)],_0x3158f6,_0x15666d);continue;case"10":_0x48c434.log(s[n(1732)],_0x2a88f3);continue}break}}}function h(a){let n=t,s={faGZN:function(k,O){return e[W(574)](k,O)}},l="",f=[],m=0,y=0,E=!0,p=e[n(1194)];if(e.Zvpmu(a[n(554)]("::"),-1)){let k=a[n(479)]("::");for(let N=0;N<k[n(1994)];N++)if(n(1081)!==e.KUfdU){let F=this._qosDB[n(1071)](this[n(1877)]),U=_0x5b0e81[n(1390)](s[n(905)](F,"{}"));return U[_0x11dd6d||_0x1d996c[this[n(1691)]]]=_0xc8d1a4,this[n(645)][n(1748)](this._prefix,_0x3a3b57[n(937)+"y"](U)),_0x495967||_0x4d7092[this[n(1691)]]}else{let F=k[N];if(e[n(1472)](F[n(554)](":"),0)){let U=F.split(":");E&&(m=U[n(1994)]),y+=U.length;for(let ie=0;e.nawvz(ie,U[n(1994)]);ie++)if(e[n(1824)](4,U[ie][n(1994)]))if(e.QvkZs(e.fjCwZ,e[n(1023)])){let Se=p.substring(0,e[n(754)](4,U[ie][n(1994)])),ye=Se.concat(U[ie]);f[n(468)](ye)}else this.emit(e[n(1767)],_0x1004f9),this.onerror&&this[n(1314)](_0x5e432e);else f[n(468)](U[ie]);E=!1}else{if(e[n(1824)](4,F[n(1994)])){let U=p.substring(0,e[n(1514)](4,F.length)),ie=U.concat(F);f[n(468)](ie)}else f[n(468)](F);E&&(m+=1),y+=1,E=!1}}let O="";for(let N=0;e[n(1601)](N,e[n(754)](8,y));N++)O=O[n(1933)](p);for(let N=0;e.nawvz(N,f[n(1994)]);N++)e[n(653)](N,m)&&(l=l[n(1933)](O)),l=l[n(1933)](f[N]);return l}{let k=a[n(479)](":");for(let O=0;e.aEipl(O,k.length);O++){let N=k[O];if(e[n(1824)](4,k[O][n(1994)])){let F=p[n(1091)+"g"](0,4-k[O][n(1994)]),U=F[n(1933)](N);l=l.concat(U)}else l=l[n(1933)](N)}return l}}function g(a,n){let s=t,l=a[s(1909)];e[s(1282)](void 0,l)&&(e.XJpIH(ge,n,10),e[s(1196)](G,n,l));let f=a.value;e[s(525)](void 0,f)&&(e[s(1521)](ge,n,18),e[s(1521)](G,n,f))}function _(a){let n=t,s={};e:for(;!e[n(760)](V,a);){let l=e[n(1278)](pe,a);switch(l>>>3){case 0:break e;case 1:s.key=e[n(523)](P,a,e[n(1309)](pe,a));break;case 2:s.value=e[n(1172)](P,a,pe(a));break;default:e.Pgnvz(R,a,e[n(1520)](7,l))}}if(s[n(1909)]===void 0)throw new Error(e[n(1121)]);if(s[n(836)]===void 0)throw new Error(e[n(1952)]);return s}function S(a){let n=t,s=e[n(1920)](C);return w(a,s),e[n(769)](M,s)}function w(a,n){let s=t,l=a.SeqID;e[s(801)](void 0,l)&&(e[s(673)](ge,n,8),bt(n,l));let f=a[s(1468)];if(e[s(1282)](void 0,f))if(e[s(1842)]===s(1434))e[s(1196)](ge,n,16),bt(n,f);else return _0x10f0ea.log(_0x29934e),!1;let m=a.service;e[s(1171)](void 0,m)&&(e[s(998)](ge,n,24),bt(n,e.RXcPz(D,m)));let y=a[s(506)];e.eurox(void 0,y)&&(e[s(1124)](ge,n,32),e[s(1172)](bt,n,D(y)));let E=a.headers;if(E!==void 0)for(let Se of E)if(e[s(848)](e.rPyiJ,e[s(1861)])){e.rkOGK(ge,n,42);let ye=e[s(1920)](C);e[s(563)](g,Se,ye),ge(n,ye[s(1313)]),e[s(1606)](j,n,ye),e[s(515)](L,ye)}else this[s(697)+s(934)][s(899)](),this[s(697)+"Queue"][s(468)](_0x55a57c);let p=a["payloadE"+s(1099)];e[s(801)](void 0,p)&&(e.WBrfQ(ge,n,50),e[s(1183)](G,n,p));let k=a["payloadT"+s(1170)];k!==void 0&&(e.KlunL(ge,n,58),e.czpAU(G,n,k));let O=a[s(1932)];e[s(1590)](void 0,O)&&(e[s(523)](ge,n,66),ge(n,O[s(1994)]),e[s(1124)](ae,n,O));let N=a[s(904)];e.Cgifp(void 0,N)&&(e.wRTmY(ge,n,74),e[s(1175)](G,n,N));let F=a[s(1281)+"ming"];F!==void 0&&(e[s(1777)](ge,n,82),e[s(673)](G,n,F));let U=a.msgID;e.MGzDm(void 0,U)&&(ge(n,90),e[s(975)](G,n,U));let ie=a[s(680)+"e"];e[s(801)](void 0,ie)&&(e[s(848)](e[s(1148)],e[s(945)])?this.on(_0x5dce1d,_0x126a88):(ge(n,96),e[s(1521)](bt,n,e[s(515)](D,ie))))}function v(a){let n=t;return e[n(1486)](I,e[n(1486)](z,a))}function I(a){let n=t,s={};e:for(;!V(a);){let l=e[n(1363)](pe,a);switch(e[n(1245)](l,3)){case 0:break e;case 1:s.SeqID=e[n(1183)](Pt,a,!0);break;case 2:s.LogID=Pt(a,!0);break;case 3:s[n(1905)]=e[n(1174)](pe,a);break;case 4:s[n(506)]=e.EdpoR(pe,a);break;case 5:{let f=A(a);(s.headers||(s[n(1338)]=[]))[n(468)](e[n(1907)](_,a)),a[n(1313)]=f;break}case 6:s[n(1380)+n(1099)]=e[n(969)](P,a,e[n(745)](pe,a));break;case 7:s[n(1810)+"ype"]=e[n(1926)](P,a,pe(a));break;case 8:s.payload=e[n(975)](oe,a,e[n(1356)](pe,a));break;case 9:s.LogIDNew=P(a,e[n(745)](pe,a));break;case 10:s[n(1281)+"ming"]=e.OcwEx(P,a,pe(a));break;case 11:s[n(1685)]=e.Gruvj(P,a,e[n(1907)](pe,a));break;case 12:s[n(680)+"e"]=e[n(970)](pe,a);break;default:e.KFPpu(R,a,e[n(1520)](7,l))}}if(e.CSvSS(void 0,s[n(861)]))throw new Error("Missing "+n(1455)+n(1115)+n(861));if(e[n(1264)](void 0,s.LogID))throw new Error(e[n(803)]);if(e[n(1290)](void 0,s[n(1905)]))throw new Error(e[n(1327)]);if(e[n(727)](void 0,s[n(506)]))throw new Error(e[n(1505)]);return s}function A(a){let n=t,s=e[n(770)](pe,a),l=a[n(1313)];return a[n(1313)]=e[n(658)](a[n(1435)],s),l}function R(a,n){let s=t;switch(n){case 0:for(;e[s(1098)](128,e.zSCbz(ee,a)););break;case 2:e.KlunL(J,a,e[s(1218)](pe,a));break;case 5:e.tCyDC(J,a,4);break;case 1:e[s(1240)](J,a,8);break;default:throw new Error(e.qnHwQ+n)}}function D(a){return a|=0,{low:a,high:e.BCADH(a,31),unsigned:e.dfCNx(a,0)}}let b=[];function C(){let a=t,n=b[a(968)]();return n?(n[a(1435)]=n[a(1313)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function L(a){b[t(468)](a)}function z(a){return{bytes:a,offset:0,limit:a.length}}function M(a){let n=t,s=a.bytes,l=a[n(1313)];return s.length===l?s:s.subarray(0,l)}function J(a,n){let s=t;if(a.offset+n>a[s(1313)])throw new Error(e[s(1800)]);a[s(1435)]+=n}function V(a){let n=t;return e.LvmCK(a.offset,a[n(1313)])}function re(a,n){let s=t,l=a[s(1802)],f=a[s(1435)],m=a[s(1313)],y=e[s(658)](f,n);if(e[s(470)](y,l[s(1994)])){let E=new Uint8Array(e[s(1052)](2,y));E[s(646)](l),a[s(1802)]=E}return a.offset=y,e.rsOAw(y,m)&&(a[s(1313)]=y),f}function X(a,n){let s=t,l=a[s(1435)];if(e[s(1051)](l,n)>a[s(1313)])throw new Error(e[s(1849)]);return a.offset+=n,l}function oe(a,n){let s=t;if(e[s(1072)](e.QzPdf,s(512))){let l=e[s(1172)](X,a,n);return a[s(1802)][s(1766)](l,e[s(1051)](l,n))}else{let l=_0x125c83[s(1955)][s(1932)];l&&_0x9f17ab[s(1844)+"rs"](l)}}function ae(a,n){let s=t,l=re(a,n[s(1994)]);a[s(1802)].set(n,l)}function P(a,n){let s=t,l=e[s(1196)](X,a,n),f=String[s(1756)+s(1116)],m=a[s(1802)],y="\uFFFD",E="";for(let p=0;e[s(738)](p,n);p++){let k=m[e.pmkkS(p,l)],O,N,F,U;e[s(705)](128&k,0)?E+=f(k):e[s(1520)](224,k)===192?e[s(1248)](e[s(658)](p,1),n)?E+=y:(O=m[e[s(1051)](e[s(1066)](p,l),1)],e[s(1393)](192,O)!==128?E+=y:e.PDiPR===e[s(1668)]?(_0xe071c8+=_0x388cef(_0x3a6dab),_0x2adeb2++):(U=e[s(857)](e.GmyLE(e[s(1393)](31,k),6),e.IMVRE(63,O)),e[s(1601)](U,128)?E+=y:(E+=e[s(745)](f,U),p++))):e[s(1751)](240,k)==224?e[s(1275)](e[s(944)](p,2),n)?E+=y:(O=m[e[s(1323)](p,l)+1],N=m[e[s(944)](e[s(1646)](p,l),2)],e[s(801)]((O|e.lbmyV(N,8))&49344,32896)?E+=y:(U=e[s(1032)](e.fGJSW(15,k),12)|e[s(1007)](63,O)<<6|e[s(1682)](63,N),e.ILMKb(U,2048)||e[s(521)](U,55296)&&e.PWgZu(U,57343)?E+=y:(E+=e.SWezq(f,U),p+=2))):e.uPOGU(e[s(1751)](248,k),240)?e[s(1248)](e.HXarv(p,3),n)?E+=y:(O=m[e[s(1633)](p+l,1)],N=m[e[s(1928)](e[s(1051)](p,l),2)],F=m[e[s(1323)](e[s(1323)](p,l),3)],e[s(794)](e.fGJSW(e[s(857)](e[s(1689)](O,e[s(978)](N,8)),e[s(1032)](F,16)),12632256),8421504)?E+=y:(U=e.hPkzQ(e[s(1032)](e[s(1799)](7,k),18)|e[s(1483)](63,O)<<12,e[s(1795)](e[s(1743)](63,N),6))|e[s(1743)](63,F),U<65536||e[s(802)](U,1114111)?E+=y:(U-=65536,E+=f(e.xocmR(e[s(917)](U,10),55296),e[s(1563)](e[s(952)](1023,U),56320)),p+=3))):E+=y}return E}function G(a,n){let s=t,l={TNoDo:function(p,k){return e[W(1643)](p,k)},Fjkpv:s(1406),SdyJS:s(650)+s(1013)+"s",IbDZi:e[s(735)],ODvgx:function(p,k){return e[s(710)](p,k)},YUWOH:e.cPBtM},f=n[s(1994)],m=0;for(let p=0;e[s(738)](p,f);p++){let k=n[s(1367)+"At"](p);k>=55296&&e[s(1043)](k,56319)&&p+1<f&&(k=e[s(1066)](e[s(1795)](k,10),n[s(1367)+"At"](++p))-56613888),m+=e[s(1853)](k,128)?1:e[s(1136)](k,2048)?2:k<65536?3:4}e[s(1988)](ge,a,m);let y=e[s(1606)](re,a,m),E=a[s(1802)];for(let p=0;e.aEipl(p,f);p++)if(e.dUIwc(e[s(1760)],e[s(956)])){this[s(510)+s(1350)](),this[s(1049)+s(1869)+"Id"]=e[s(491)](_0x56177c,this[s(800)].bind(this),this._options[s(830)+s(1233)]);let k=()=>{let N=s;l[N(1838)](_0x30100c,l.Fjkpv),this[N(1492)](l[N(1740)],k),this[N(1492)](l[N(1946)],O)},O=()=>{let N=s;l[N(1271)](_0x973122,l[N(1863)]),this[N(1492)](l[N(1740)],k),this[N(1492)](N(650)+N(923)+"t",O)};this.on(s(650)+s(1013)+"s",k),this.on(e.avWmE,O),this[s(800)]()}else{let k=n[s(1367)+"At"](p);e.BrjEJ(k,55296)&&e.AHAAa(k,56319)&&e[s(658)](p,1)<f&&(k=(k<<10)+n[s(1367)+"At"](++p)-56613888),e[s(1460)](k,128)?E[y++]=k:(e[s(690)](k,2048)?E[y++]=e[s(1799)](e[s(1021)](k,6),31)|192:(e[s(690)](k,65536)?E[y++]=e[s(850)](e[s(1743)](e[s(1366)](k,12),15),224):(E[y++]=e.XhWJA(k>>18,7)|240,E[y++]=e[s(1137)](e.qqKfM(k>>12,63),128)),E[y++]=e[s(1689)](e[s(1799)](k>>6,63),128)),E[y++]=e[s(1144)](63,k)|128)}}function j(a,n){let s=t,l=e[s(1464)](re,a,n[s(1313)]),f=a[s(1802)],m=n[s(1802)];for(let y=0,E=n.limit;e[s(1460)](y,E);y++)f[e[s(753)](y,l)]=m[y]}function ee(a){return a[t(1802)][e.RQbHy(X,a,1)]}function Je(a,n){let s=t,l=re(a,1);a[s(1802)][l]=n}function pe(a){let n=t,s=0,l=0,f;do f=e[n(630)](ee,a),s<32&&(l|=e[n(978)](127&f,s)),s+=7;while(e[n(1761)](128,f));return l}function ge(a,n){let s=t;if(e[s(1095)](e[s(820)],"SWUnG")){for(n>>>=0;e[s(619)](n,128);)e[s(481)](Je,a,e[s(621)](127,n)|128),n>>>=7;e[s(1232)](Je,a,n)}else{if(_0x471e07)return new _0xf1501a(_0x253c0d[s(1967)],_0x2b8f70.protocol);if(e.BKxRa(_0x2164e4,_0x462297))return new _0x2bd245(_0x16c40d[s(1967)],_0x4cb77b[s(1497)],_0x11e056[s(1338)]);if(e[s(1647)](_0x3d0e7d,_0x1e72e6)&&e.xUXvJ(e[s(556)],typeof _0x2d910e)&&_0xec905e)return new _0x484c1a(_0x241762[s(1967)],_0x508e1a[s(1497)+"s"])}}function Pt(a,n){let s=t,l={xLLZI:function(f,m){return f!==m},MEWDF:function(f,m){return e[W(1541)](f,m)},XVmGi:function(f,m){return e.VvFpF(f,m)},kNwZF:function(f,m){return e.uNSuB(f,m)},Xmgns:function(f,m){return f>>>m},ROYBS:function(f,m){return e[W(1913)](f,m)},skgvZ:function(f,m){return e[W(1245)](f,m)}};if(e.ZUkPb===e[s(1270)]){let f=_0x5e9fd4[s(479)](":");_0x177c0f&&(_0x36433f=f[s(1994)]),_0x40a2a3+=f[s(1994)];for(let m=0;m<f.length;m++)if(Vznqvo.xLLZI(4,f[m][s(1994)])){let y=_0x29b629[s(1091)+"g"](0,Vznqvo[s(718)](4,f[m][s(1994)])),E=y[s(1933)](f[m]);_0xa9dbc7[s(468)](E)}else _0x46358a.push(f[m]);_0x404dc6=!1}else{let f=0,m=0,y=0,E;if(E=ee(a),f=e[s(1803)](127,E),e[s(1986)](128,E)&&(E=e[s(769)](ee,a),f|=e[s(1626)](e.AMMKS(127,E),7),e[s(866)](128,E)&&(E=e[s(1309)](ee,a),f|=e[s(1539)](e[s(1751)](127,E),14),e.vHGqq(128,E)&&(E=ee(a),f|=e.ckaqS(e[s(1719)](127,E),21),128&E&&(E=e[s(807)](ee,a),m=e.AgAjL(127,E),e[s(1520)](128,E)&&(E=ee(a),m|=e[s(1370)](127,E)<<7,128&E&&(E=e[s(1174)](ee,a),m|=e.sxioZ(127,E)<<14,e.UwkAQ(128,E)&&(E=e[s(1486)](ee,a),m|=e.UUsWz(127&E,21),e[s(1820)](128,E))))))))){if(e.gahpc!==e.gahpc)return this[s(593)]?l.XVmGi(l[s(1075)](l[s(990)](this.high,0),_0x378ce8),l.Xmgns(this[s(1060)],0)):l[s(1638)](this[s(1176)]*_0x3fec10,l[s(881)](this[s(1060)],0));E=e.pTPOw(ee,a),y=e.gzCzb(127,E),e[s(1522)](128,E)&&(E=e.RXcPz(ee,a),y|=e[s(1297)](e[s(1629)](127,E),7))}return{low:e[s(1137)](f,e[s(978)](m,28)),high:e[s(1653)](e[s(1245)](m,4),e.hgZhU(y,24)),unsigned:n}}}function bt(a,n){let s=t,l=e.kZdxQ(n[s(1060)],0),f=e[s(962)](e.FWOtr(e[s(1602)](n[s(1060)],28),n[s(1176)]<<4),0),m=n[s(1176)]>>>24,y=e[s(1693)](0,m)?e.VocrE(0,f)?e[s(1735)](l,16384)?e[s(1601)](l,128)?1:2:e[s(1127)](l,2097152)?3:4:e[s(1943)](f,16384)?e[s(1152)](f,128)?5:6:e[s(1601)](f,2097152)?7:8:e.ILMKb(m,128)?9:10,E=e[s(1124)](re,a,y),p=a[s(1802)];switch(y){case 10:p[e[s(1913)](E,9)]=e[s(1761)](m>>>7,1);case 9:p[E+8]=e[s(1590)](9,y)?e[s(569)](128,m):e[s(1345)](127,m);case 8:p[e.VknYg(E,7)]=y!==8?e[s(1653)](f>>>21,128):e[s(1469)](f,21)&127;case 7:p[e.qCuSq(E,6)]=y!==7?e[s(1549)](f,14)|128:e[s(1549)](f,14)&127;case 6:p[e[s(1774)](E,5)]=e[s(910)](6,y)?e.YGCQI(e[s(1469)](f,7),128):e[s(900)](e[s(1602)](f,7),127);case 5:p[E+4]=e[s(594)](5,y)?e[s(857)](128,f):e.pfAyh(127,f);case 4:p[e.MnTeT(E,3)]=e[s(597)](4,y)?e[s(1360)](e.OOTbh(l,21),128):e[s(605)](e[s(815)](l,21),127);case 3:p[e[s(1723)](E,2)]=e[s(910)](3,y)?e[s(1661)](e[s(1289)](l,14),128):e[s(621)](e[s(1289)](l,14),127);case 2:p[e.qCuSq(E,1)]=e[s(1901)](2,y)?e[s(1893)](e[s(558)](l,7),128):e[s(1469)](l,7)&127;case 1:p[E]=e[s(1826)](1,y)?e[s(850)](128,l):e[s(1449)](127,l)}}function an(a){return e[t(1356)](v,a)}function qt(a){return e.RXcPz(S,a)}let cn=65536,ri=e[t(1223)],_e=e[t(1092)](cn,cn),Re=e.XJjey(_e,_e),or=e[t(1198)](Re,2),Ne=String.prototype[t(1367)+"At"];class he{constructor(n,s,l){let f=t;this[f(1916)]=!0,this[f(1060)]=e[f(1738)](0,n),this[f(1176)]=e[f(780)](0,s),this[f(593)]=!!l}static[t(1916)](n){let s=t;return n&&e[s(943)](!0,n[s(1916)])}static[t(628)](n,s,l){return e[t(1171)](e.YKkBM,e.YKkBM)?_0x2f0a11||(_0x3fe8cd=[_0xda93a4,_0x398cba,_0x159546,_0x5559ae,_0x2046ad]):new he(n,s,l)}static[t(834)+"s"](n,s,l){return l?he[t(834)+"sLE"](n,s):he.fromBytesBE(n,s)}static["fromByte"+t(1630)](n,s){let l=t;return new he(e[l(1246)](e[l(1661)](e[l(1599)](n[0],e[l(978)](n[1],8)),e[l(1626)](n[2],16)),e[l(1325)](n[3],24)),e[l(1893)](e[l(1689)](n[4],e.GRoMT(n[5],8))|e[l(1286)](n[6],16),e[l(774)](n[7],24)),s)}static[t(834)+t(1885)](n,s){let l=t;if(e[l(727)](e[l(549)],e[l(549)]))return new he(e[l(1137)](e.fufUh(e.ReLja(e.xexcC(n[4],24),e.Zmflu(n[5],16)),e[l(1197)](n[6],8)),n[7]),e[l(570)](e[l(1661)](e[l(1246)](e[l(1123)](n[0],24),e[l(663)](n[1],16)),n[2]<<8),n[3]),s);this[l(615)]&&this[l(615)][l(1709)]({code:_0x24b760,reason:_0x460aa5})}static fromHash(n){let s=t;return e[s(653)](n,ri)?ul:new he(e[s(930)](e.dDbfX(e[s(1923)](Ne.call(n,0),e[s(1966)](Ne[s(1326)](n,1),8))|Ne.call(n,2)<<16,Ne.call(n,3)<<24),0),e.WPZAN(e[s(580)](e[s(1825)](Ne[s(1326)](n,4)|e.lbmyV(Ne[s(1326)](n,5),8),e[s(1348)](Ne[s(1326)](n,6),16)),e[s(1402)](Ne[s(1326)](n,7),24)),0),!0)}toHash(){let n=t;return String[n(1756)+n(1116)](255&this[n(1060)],e[n(1602)](this[n(1060)],8)&255,e[n(1094)](this[n(1060)]>>>16,255),e[n(608)](this[n(1060)],24),e.AMMKS(255,this.high),e.chaLS(e.kZdxQ(this[n(1176)],8),255),this[n(1176)]>>>16&255,e[n(1589)](this[n(1176)],24))}static fromNumber(n,s=!0){let l=t;if(e.vaCfU(isNaN,n))return s?$p:ul;if(s){if(e[l(626)](n,Re))return Jp}else{if(e[l(1043)](n,-or))return Zp;if(n+1>=or)return Vp}return he[l(628)](e[l(1661)](e[l(1557)](n,_e),0),e[l(580)](n/_e,0),s)}toNumber(){let n=t;return this[n(593)]?e[n(1993)](e[n(1369)](this[n(1176)]>>>0,_e),e[n(962)](this.low,0)):e[n(1563)](e[n(1052)](this.high,_e),this[n(1060)]>>>0)}[t(1914)](){let n=t;return e[n(705)](0,this[n(1176)])&&e[n(1442)](0,this[n(1060)])}[t(870)](n){let s=t;if(e[s(1564)](e[s(825)],"LBCrX")){he[s(1916)](n)||(n=he.fromNumber(n));let l=e[s(608)](this[s(1176)],16),f=e[s(1135)](65535,this[s(1176)]),m=e.kVZoK(this[s(1060)],16),y=65535&this.low,E=n[s(1176)]>>>16,p=e.pfAyh(65535,n[s(1176)]),k=n[s(1060)]>>>16,O=65535&n[s(1060)],N=0,F=0,U=0,ie=0;return ie+=e[s(944)](y,O),U+=e.Sttuw(ie,16),ie&=65535,U+=e[s(888)](m,k),F+=e.lSDlr(U,16),U&=65535,F+=f+p,N+=F>>>16,F&=65535,N+=e[s(1993)](l,E),N&=65535,he[s(628)](e[s(1054)](e[s(1197)](U,16),ie),e[s(1396)](e[s(1286)](N,16),F),this[s(593)])}else{_0x3c3c7c[s(1916)](_0x312632)||(_0x3d0e19=_0x39d24e.fromNumber(_0xedb131));let l=e[s(930)](this[s(1176)],16),f=e.CAozt(65535,this.high),m=e[s(815)](this[s(1060)],16),y=e.mybJo(65535,this[s(1060)]),E=e[s(608)](_0x2da1f3[s(1176)],16),p=e.otHjT(65535,_0x443931.high),k=e[s(657)](_0x3ca552[s(1060)],16),O=65535&_0x34fc38[s(1060)],N=0,F=0,U=0,ie=0;return ie+=e[s(753)](y,O),U+=e[s(1602)](ie,16),ie&=65535,U+=e[s(888)](m,k),F+=e[s(558)](U,16),U&=65535,F+=e.HXarv(f,p),N+=e[s(1164)](F,16),F&=65535,N+=e[s(888)](l,E),N&=65535,_0x704601[s(628)](e[s(984)](e[s(1197)](U,16),ie),e[s(780)](e[s(584)](N,16),F),this[s(593)])}}[t(681)](n){let s=t;return he[s(1916)](n)||(n=he.fromNumber(n)),e[s(597)](this[s(593)],n[s(593)])&&e[s(653)](this[s(1176)]>>>31,1)&&e[s(1448)](e[s(694)](n[s(1176)],31),1)?!1:e[s(1068)](this[s(1176)],n[s(1176)])&&e[s(1856)](this.low,n[s(1060)])}[t(546)](){let n=t;return e[n(848)](-1,this[n(1060)])&&this[n(1176)]===-1?he.fromBits(0,0,this[n(593)]):e.FZluh(-1,this[n(1060)])?he.fromBits(0,this[n(1176)]+1,this[n(593)]):he[n(628)](e[n(888)](this[n(1060)],1),this.high,this[n(593)])}[t(1231)](n){let s=t;return n?this[s(764)+"E"]():this[s(527)+"E"]()}[t(764)+"E"](){let n=t,s=this[n(1176)],l=this[n(1060)];return[e[n(1104)](255,l),e[n(661)](e.lSDlr(l,8),255),l>>>16&255,e[n(1164)](l,24),e[n(1986)](255,s),s>>>8&255,e[n(511)](e[n(1416)](s,16),255),e.CCPGV(s,24)]}toBytesBE(){let n=t,s=this.high,l=this[n(1060)];return[e[n(1469)](s,24),e[n(1393)](s>>>16,255),e[n(1439)](s>>>8,255),e[n(1681)](255,s),l>>>24,e[n(1098)](e.lSDlr(l,16),255),e[n(1573)](l>>>8,255),e[n(1761)](255,l)]}}let ul=new he(0,0,!1),$p=new he(0,0,!0),Vp=he[t(628)](-1,2147483647,!1),Jp=he[t(628)](-1,-1,!0),Zp=he[t(628)](0,-2147483648,!1);var dn=(function(a){let n=t,s=e[n(1035)].split("|"),l=0;for(;;){switch(s[l++]){case"0":return a;case"1":a[a[n(743)+n(1671)]=5004]=n(743)+n(1671);continue;case"2":a[a[e[n(573)]]=5005]=e[n(573)];continue;case"3":a[a[e[n(1786)]]=5002]=n(1604)+n(648);continue;case"4":a[a[e.gLiJv]=5003]=n(1074)+"IES_ERROR";continue;case"5":a[a[n(1873)+n(1474)]=5001]=e[n(725)];continue}break}})({});class ar{constructor(n){this.type=n,this.target=null}}class fl extends ar{constructor(n,s){let l=t;super(n),this.message=s&&s[l(1955)]||null}}class xl extends ar{constructor(n,s){let l=t,f=e[l(714)][l(479)]("|"),m=0;for(;;){switch(f[m++]){case"0":this.code=s&&s[l(1591)]||5001;continue;case"1":this[l(1444)]=s&&s[l(1444)]||0;continue;case"2":this.lineno=s&&s[l(879)]||0;continue;case"3":super(n);continue;case"4":this[l(1690)]=s&&s[l(1690)]||null;continue;case"5":this.message=s&&s.message||"";continue;case"6":this[l(1797)]=s&&s[l(1797)]||"";continue}break}}}class hl extends ar{constructor(n,s){let l=t,f=e[l(809)][l(479)]("|"),m=0;for(;;){switch(f[m++]){case"0":this[l(1385)+l(1420)]=s&&s[l(1385)+"nnect"]||!1;continue;case"1":this[l(1591)]=s&&s[l(1591)]||0;continue;case"2":this[l(1613)]=s&&s[l(1613)]||!1;continue;case"3":this[l(729)]=s&&s[l(729)]||"";continue;case"4":super(n);continue}break}}}class pl extends ar{constructor(n,s){let l=t;super(n),this.data=s&&s[l(1109)]||null}}class gl extends pl{constructor(n,s){let l=t;e[l(544)](e[l(1371)],l(602))?(super(n),this[l(1109)]=s&&s[l(1109)]||null,this[l(1955)]=s&&s[l(1955)]||null):(_0x3a7829[l(1881)]["removeCh"+l(1504)](_0x443853),_0x1d43fc[l(1872)+l(1780)]=void 0,e.ifxfI(_0x598de0,_0x31e7ca&&_0x1a19eb[l(693)]||l(1865)+l(729)))}}class ml extends ar{constructor(n,s){let l=t;super(n),this[l(1109)]=s&&s[l(1109)]||null}}function lt(a,{message:n,code:s,error:l}){return new xl(a,{message:n,code:s,error:l})}function Et(a,{code:n,reason:s,wasClean:l,willReconnect:f}){return new hl(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function wl(a,{data:n,message:s}){return new gl(a,{data:n,message:s})}function _l(a,{data:n}){let s=t;if(s(1012)===e[s(1178)])return new ml(a,{data:n});this[s(645)]?.[s(1730)](_0x1d8c69.message_id)}function Sa(a,{message:n}){return new fl(a,{message:n})}class yl{constructor(n,s){let l=t;e[l(460)](l(668),l(668))?(this[l(1479)+"s"]=n,this.maxRetries=s,this[l(1067)+"ndex"]=0,this[l(2001)+l(1340)+l(1763)+"t"]=0):_0x1b79f6[l(1969)]=_0x46e3cf[l(1329)]()[l(1403)](()=>(_0x57476d(),_0x5c42e7))[l(1403)](function(f){return f})}["resetEnd"+t(1753)+"fig"](){let n=t;this[n(1067)+"ndex"]=0,this[n(2001)+"ndpointT"+n(1763)+"t"]=0}resetTries(){let n=t;this["currentEndpointT"+n(1763)+"t"]=0}[t(882)+t(1105)+"nt"](){let n=t,s={vSnpm:function(l,f){return l&f},KIFqx:function(l,f){return l+f},zFtaW:function(l,f){return e.hiSHG(l,f)},pfzfU:function(l,f){return l>>>f},Hnwbs:function(l,f){return l&f},yBMdd:function(l,f){return e.jsWcA(l,f)},phEIV:function(l,f){return l&f}};if(e[n(1645)](e[n(1307)],e[n(1211)])){let l=_0x249f2d[n(1060)],f=_0x459fbb.high;return _0x309262[_0x11b8ae]=f>>>24,_0x1f384b[_0x18c66d+1]=s.vSnpm(f>>>16,255),_0x18d873[s[n(1291)](_0x2fcee0,2)]=s.vSnpm(s[n(1536)](f,8),255),_0x3e5b6f[_0x2887de+3]=s[n(1299)](255,f),_0x1676d8[s[n(1291)](_0x2ef6ba,4)]=s[n(1878)](l,24),_0x4b7c2c[s[n(1291)](_0x30b5d2,5)]=s[n(2004)](s.pfzfU(l,16),255),_0x3b980e[s[n(1291)](_0x38b221,6)]=l>>>8&255,_0x784908[s[n(1657)](_0x1c95b0,7)]=s[n(1560)](255,l),_0x9199d6+=8,_0x29d528}else return this[n(1479)+"s"][this["currentI"+n(1310)]]}[t(882)+t(1105)+"ntTriesCount"](){return this.currentEndpointTriesCount}checkReachMaxTries(){let n=t;if(e[n(1529)]!==e.PfbTj)return!!(e.xhfJB(this[n(1067)+n(1310)],this[n(1479)+"s"].length)||e[n(705)](this[n(1067)+n(1310)],this.endpoints[n(1994)]-1)&&e[n(1578)](this[n(2001)+"ndpointT"+n(1763)+"t"],this[n(1070)+"es"]));e[n(929)](_0x5014e1,_0x4abc8a,50),e[n(969)](_0x5dcf99,_0x127a60,_0x165878)}[t(1384)+"rentEndp"+t(1253)+t(935)+t(784)](){let n=t;return this[n(1067)+n(1310)]==this[n(1479)+"s"][n(1994)]?!0:e[n(802)](this[n(2001)+"ndpointTriesCount"],this.maxRetries)}["replaceB"+t(1860)+t(1614)+t(763)+t(1947)](){let n=t;return this[n(2001)+n(1340)+"riesCount"]=1,this[n(1067)+n(1310)]++,this[n(1479)+"s"][this[n(1067)+n(1310)]]}["getCurre"+t(1105)+t(2005)+t(1779)](){let n=t;return this[n(2001)+n(1340)+n(1763)+"t"]++,this[n(882)+n(1105)+"nt"]()}}let cr=(typeof globalThis<"u"&&e[t(1564)](e[t(1544)],globalThis[t(1898)+"tor"][t(965)])||e.xUXvJ(e[t(556)],typeof window)&&e.uzhMe===window["construc"+t(548)][t(965)])&&t(622)+"d"!=typeof document,Ln=e[t(556)]!=typeof globalThis&&(e[t(1941)]===globalThis[t(1898)+t(548)][t(965)]||e[t(1068)](e[t(1262)],globalThis[t(1898)+t(548)][t(965)]))&&e[t(1220)](e[t(556)],typeof tt),ii=(e[t(1588)](e[t(556)],typeof globalThis)&&e[t(1062)](e[t(1941)],globalThis["construc"+t(548)][t(965)])||e[t(805)](e[t(556)],typeof globalThis)||e[t(535)](t(622)+"d",typeof globalThis)&&!!globalThis[t(713)+t(1047)])&&e[t(1588)](t(622)+"d",typeof wx),si=e[t(1654)](e.FDrnp,typeof globalThis)&&(e[t(1598)](e[t(1262)],globalThis[t(1898)+t(548)][t(965)])||e[t(895)](e.gwfSC,globalThis[t(1898)+"tor"].name)||e[t(1341)]===globalThis["construc"+t(548)].name)&&e[t(556)]!=typeof self,Yp=typeof globalThis<"u"&&e[t(1448)](e[t(1941)],globalThis[t(1898)+"tor"][t(965)])&&t(622)+"d"!=typeof global&&e.snAEr(t(1696),global[t(1898)+t(548)].name)&&e[t(556)]!=typeof process&&!!process[t(1707)];class Ia{constructor(){let n=t;this[n(1364)+"rs"]={}}emit(n,...s){let l=t,f=this._listeners[n];if(f)f.slice()[l(1206)](m=>m.fn[l(703)](m[l(966)],s));else if(e[l(1767)]===n&&!this[l(1314)]){let m=s[l(1994)]&&s[0];if(e[l(914)](m,Error))throw m;let y=new Error(e[l(1723)](e[l(698)],m?e[l(1913)](" (",m.message)+")":""));throw y.context=m,m}return this}[t(1492)](n,s){let l=t;if(e[l(1827)](void 0,n))this._listeners={};else if(e[l(795)](void 0,s))this[l(1364)+"rs"][n]=null;else{let f=this[l(1364)+"rs"][n];if(f)for(let m=0;m<f[l(1994)];)e[l(1415)](f[m].fn,s)?f[l(1621)](m,1):++m}return this}on(n,s,l){let f=t,m={jpdmG:function(y,E){return e[W(754)](y,E)}};if(e.wAzwJ(e[f(1302)],e[f(1302)]))return(this._listeners[n]||(this[f(1364)+"rs"][n]=[]))[f(468)]({fn:s,ctx:l||this}),this;{let y=_0x3b337a.substring(0,yMPBxp[f(964)](4,_0x41df8e[_0x29fb73][f(1994)])),E=y[f(1933)](_0x2e5a88);_0x3b1188=_0x45d7a4.concat(E)}}}class Xp extends Ia{[t(1125)+t(765)+t(1775)](n){let s=t;if(e[s(1089)](e[s(1151)],e.HdTZn))return n[s(864)]||n.errNo?(s(1758)+" "+(n[s(864)]||"")+s(1832)+(n.errNo||""))[s(1440)]():JSON[s(937)+"y"](n);_0x1239db=_0x2ba99a(_0x1402b7)}constructor(n,s,l){let f=t;super(),this[f(615)]=null,ii&&wx[f(1399)+f(1963)]&&(this[f(615)]=wx["connectS"+f(1963)]({url:n,protocols:s,header:l,fail:this[f(696)+f(1515)+f(926)].bind(this),success:this[f(696)+f(1958)+f(785)+f(1852)][f(1975)](this)})),Ln&&tt[f(1399)+f(1963)]&&(this[f(615)]=tt["connectS"+f(1963)]({url:n,protocols:s,header:l,fail:this[f(696)+f(1515)+"lHandler"].bind(this),success:this["_createS"+f(1958)+f(785)+f(1852)][f(1975)](this)}))}[t(696)+t(1958)+t(785)+"ler"](){let n=t;Promise[n(1329)]().then(()=>{let s=n;this[s(922)+s(1729)]()})}[t(696)+"ocketFai"+t(926)](n){let s=t;Promise[s(1329)]().then(()=>{let l=s,f=e[l(1232)](lt,l(1690),{message:this[l(1125)+"rrorMess"+l(1775)](n)});this[l(1205)](e.NyEXn,f);let m=Et(e.tcvFp,{reason:this[l(1125)+"rrorMess"+l(1775)](n)});this[l(1205)](e[l(1874)],m)})}[t(922)+t(1729)](){let n=t,s={dJPWs:function(l,f,m){return e[W(767)](l,f,m)},jpdru:n(1709),VopAG:n(1690)};this[n(615)][n(1680)](l=>{let f=n;e.SemzA(e.kcWAg,e[f(737)])?this[f(1897)+f(974)]():this[f(1205)](f(1801),e.FblNh(_l,e.gDTWB,{...l,data:l[f(864)]||""}))}),this[n(615)][n(1567)](l=>{let f=n;this[f(1205)](f(1709),s.dJPWs(Et,s[f(1398)],{...l}))}),this[n(615)][n(1776)+"e"](l=>{let f=n;this[f(1205)](f(1955),e[f(523)](wl,f(1955),{...l}))}),this[n(615)][n(1078)](l=>{let f=n;this.emit(s[f(1167)],s[f(516)](lt,s[f(1167)],{...l,message:l.errMsg||""}))})}[t(1940)](n){let s=t,l={ROgdd:function(f,m,y,E){return e.IcsyV(f,m,y,E)},eJtDw:e[s(1238)],GmvMZ:function(f,m){return e[s(982)](f,m)},Dknnr:e[s(1106)],xubNG:function(f,m){return e.HLaWY(f,m)},zAeZQ:e.icXwK,QpFFw:function(f){return e[s(1920)](f)},mFiaW:e[s(1767)],xNelg:function(f,m,y){return f(m,y)}};if(e[s(914)](n,Uint8Array))if(e[s(795)](e[s(1376)],s(1201))){let{enableAutoAck:f}=this[s(1257)],m=l[s(756)](_0x57cd99,_0x2e19f1[s(1955)][s(1338)],"need_ack","1"),y=l[s(756)](_0x42de6e,_0x32cd02.message.headers,l.eJtDw,"1"),E=_0x1d7841.call(this,_0x5965c7);if(l[s(893)](f,m)){let{SeqID:p,LogID:k,service:O,LogIDNew:N,method:F}=_0xe7ad31[s(1955)];this[s(1583)]({SeqID:p,LogID:k,LogIDNew:N,service:O,method:F,headers:[{key:l.eJtDw,value:"1"},{key:l[s(632)],value:l[s(1217)](N,"")},{key:l.zAeZQ,value:"0"}]})}y&&!E[s(2002)]&&this[s(692)+s(635)+s(1357)](_0x76d5e6),l[s(700)](_0x348d1f)}else{let f=n.buffer[s(1895)](n[s(543)+"et"],n[s(638)+"th"]+n[s(543)+"et"]);this._socket&&this._socket[s(1940)]({data:f,fail:m=>{let y=s;this[y(1205)](l[y(1615)],l.xNelg(lt,l.mFiaW,{message:this[y(1125)+y(765)+y(1775)](m)}))}})}else this[s(615)]&&this[s(615)].send({data:n,fail:f=>{let m=s,y={KjKKZ:m(948)+" try rec"+m(1344)+"g"};if(e.DuJVU(e[m(683)],m(596))){let E=this[m(1e3)+m(1982)]?.["getCurre"+m(1105)+"nt"]();this._debug("connect "+E+m(1111)),this["_disconn"+m(647)](1001,y.KjKKZ,!0)}else this[m(1205)](e[m(1767)],e[m(1187)](lt,"error",{message:this["_formatErrorMess"+m(1775)](f)}))}})}[t(1709)](n,s){let l=t;this[l(615)]&&this[l(615)][l(1709)]({code:n,reason:s})}[t(831)+t(1169)](n,s){this.on(n,s)}["removeEv"+t(488)+"ner"](n,s){this.off(n,s)}get[t(722)+"te"](){return this[t(615)].readyState}get[t(1516)+"pe"](){let n=t;if(e[n(1700)]!=="aaxZH")try{return!!this[n(645)]}catch(s){return _0x3ebe64[n(1580)](s),!1}else return this[n(615)][n(1516)+"pe"]}set[t(1516)+"pe"](n){}get[t(1967)](){let n=t;return e[n(1173)]!==n(508)?this._socket.url:(this[n(2001)+n(1340)+n(1763)+"t"]=1,this[n(1067)+"ndex"]++,this[n(1479)+"s"][this[n(1067)+n(1310)]])}get[t(1497)](){return this._socket.protocol}get[t(636)+"ns"](){let n=t;return this[n(615)][n(636)+"ns"]}get["buffered"+t(885)](){return 0}}function Qp(a,n){let s=t;if(e[s(485)]==="bttOj"){if(n)return new n(a[s(1967)],a[s(1497)]);if(e.qwhCC(ii,Ln))return new Xp(a[s(1967)],a[s(1497)],a[s(1338)]);if((cr||si)&&e.FDrnp!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(1967)],a[s(1497)+"s"])}else this[s(490)+"er"]&&_0xd98326[s(1561)+s(488)+s(1937)](e.dvSef,this[s(759)+"ageHide"]),this[s(490)+"er"]&&_0x3e3a1f[s(1561)+s(488)+"ner"](e[s(1609)],this[s(759)+s(678)]),this[s(1709)]()}function eg(a){let n=t;return!!(a||ii&&wx[n(1399)+n(1963)]||Ln&&tt[n(1399)+n(1963)]||(cr||si)&&e.HiSRc(e[n(556)],typeof WebSocket)&&WebSocket)}function bl(a,n,s){let l=t,f={wmGGJ:e[l(459)],lfYOL:function(E,p){return e[l(1089)](E,p)}},m=-1;async function y(E){let p=l;return E<=m?Promise[p(832)](new Error(f[p(772)])):(m=E,f[p(1697)](E,s[p(1994)])?Promise.resolve():s[E][p(1975)](a)(n,y[p(1975)](null,E+1)))}e[l(1356)](y,0)}function El(a){let n=t,s=0,l=0;for(let f=0;f<a[n(1994)];++f)if(e[n(910)](e.Wvlks,e.VxRry))l=a.charCodeAt(f),e[n(1601)](l,128)?s+=1:e[n(690)](l,2048)?s+=2:e[n(1564)](e[n(750)](64512,l),55296)&&e[n(912)](64512,a[n(1367)+"At"](f+1))===56320?(++f,s+=4):s+=3;else try{this[n(1530)]&&this[n(1530)][n(1709)](_0x31f5ca,_0x55f91f)}catch{}return s}function vl(a,n,s){let l=t;if(e[l(1541)](s,n)<1)return"";let f="";for(let m=n;e[l(1280)](m,s);){let y=a[m++];if(e[l(810)](y,127))f+=String[l(1756)+l(1116)](y);else if(e[l(1931)](y,192)&&y<224)f+=String[l(1756)+l(1116)](e.dDbfX(e[l(774)](e[l(733)](31,y),6),e[l(1094)](63,a[m++])));else if(y>=224&&e.XJJNO(y,240))f+=String[l(1756)+l(1116)](e.IqMFL(e.GmyLE(e.vqixE(15,y),12),e[l(584)](e[l(900)](63,a[m++]),6))|e[l(952)](63,a[m++]));else if(e[l(1674)](y,240)){let E=e[l(754)](e[l(1396)](e[l(1428)](e[l(1348)](7&y,18),e[l(1123)](e.qMSRP(63,a[m++]),12))|e[l(955)](63&a[m++],6),e[l(601)](63,a[m++])),65536);f+=String[l(1756)+l(1116)](e[l(855)](55296,e[l(917)](E,10))),f+=String[l(1756)+l(1116)](e[l(1913)](56320,e[l(679)](1023,E)))}}return f}function Aa(a,n,s){let l=t,f=s,m,y;for(let E=0;e[l(1601)](E,a[l(1994)]);++E)if(m=a[l(1367)+"At"](E),e[l(1783)](m,128))n[s++]=m;else if(e.OvHVe(m,2048))n[s++]=m>>6|192,n[s++]=e[l(1122)](e.YBafR(63,m),128);else if(e.eWtZe(e.yhrfr(64512,m),55296)&&e.yhrfr(64512,y=a[l(1367)+"At"](e[l(1563)](E,1)))===56320)if(e[l(1617)](e.STjlG,l(1443)))m=e[l(1633)](e[l(1774)](65536,e[l(1325)](1023&m,10)),e.rMQVA(1023,y)),++E,n[s++]=e[l(1552)](m,18)|240,n[s++]=e[l(1624)](e[l(1098)](e[l(917)](m,12),63),128),n[s++]=e[l(1082)](e[l(1788)](e.FKEjN(m,6),63),128),n[s++]=e[l(1188)](63,m)|128;else return _0x5f3cbb?this[l(764)+"E"]():this[l(527)+"E"]();else if(e[l(1452)](e[l(1841)],e[l(1841)])){if(e[l(1228)](_0x3eeff5,_0x29c0fb))return new _0x4ce410(_0xd6d27c,_0x315f7b);if(e[l(854)](_0x107a89,_0x4621b6)&&e[l(1298)](e[l(556)],typeof _0x1b2198))return new _0x921273(_0x4964c4,_0x57394e);if(e[l(1024)](_0x3c56a7,_0x44f13c)&&e[l(1298)](e[l(556)],typeof _0x2e2b5c))return new _0x5553d4(_0x532ebd,_0x2d7bc3);throw new _0x777b54(l(1004)+l(578)+"d")}else n[s++]=e[l(1893)](m>>12,224),n[s++]=e.MdkOj(m>>6&63,128),n[s++]=e.sFuGM(e[l(679)](63,m),128);return s-f}async function Sl(a){let n=t;if(e.ZHyMI(e[n(757)],typeof a))if(e[n(1593)](e[n(761)],e[n(761)])){let s=new Uint8Array(e.sJqMM(El,a));return e[n(818)](Aa,a,s,0),s}else _0x5f395e[n(468)](_0x7d7c8f);return e.ssjOp(a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(1964)],a[n(543)+"et"],a.byteLength)}function tg(a){let n=t,s={PChrb:function(l,f,m){return e[W(972)](l,f,m)},kgIHa:e.tcvFp,DZrXa:function(l,f,m){return e[W(1546)](l,f,m)},hGMqn:function(l,f,m){return e[W(709)](l,f,m)}};if(e.RSVMU(e[n(1160)],e[n(1160)]))try{return e.HiSRc(e[n(757)],typeof a)&&(e[n(1718)](a,ArrayBuffer)||a[n(1964)]&&a[n(1964)]instanceof ArrayBuffer)||e[n(483)](e[n(757)],typeof a)?"":(JSON[n(1390)](a),e[n(1080)])}catch{if(e.oXXAB===e[n(642)])return e.dvifE(e[n(757)],typeof a)?n(623)+n(676)+n(993):"";if(this[n(1e3)+n(1982)]?.[n(1883)+"chMaxTries"]()){let f=this[n(1e3)+n(1982)]?.[n(882)+"ntEndpoint"]();this[n(692)+"hCloseEvent"](s[n(1388)](_0x3ac2a1,s[n(1265)],{code:1006,reason:n(963)+f+(n(1111)+n(1574)+n(967)+n(489)),wasClean:!0}))}else{let f=this[n(1257)].reconnectInterceptor(_0x5251de,_0x2bf2d8);this["_dispatc"+n(591)+n(958)](s[n(499)](_0x8216d6,s.kgIHa,{code:_0x2d6a3d,reason:_0xb37034,wasClean:!0,willReconnect:f})),f&&this[n(1976)]()}return}else{let l=this[n(1257)][n(1254)+n(1670)+"ptor"](_0x1ba6a0,_0x170b45);this[n(692)+n(591)+n(958)](s[n(1488)](_0x2366e3,"close",{code:_0x5a8f00,reason:_0x202582,wasClean:!0,willReconnect:l})),l&&this[n(1976)]()}}let ng=(a,n)=>{let s=t;switch(a){case e[s(1430)]:case e[s(1806)]:return{[s(1119)+a]:1,"x-tt-env":n};default:return{}}};class rg{constructor(n){let s=t;this[s(576)+"ount"]=n,this[s(1373)]=0}addCount(){let n=t;this[n(1373)]++}[t(1883)+"chMaxCount"](){let n=t;return e[n(1845)](this[n(1373)],this["maxLossC"+n(814)])}["resetCou"+t(1354)](n=0){let s=t;this[s(576)+s(814)]=n,this.count=0}}async function ig(a){let n=t,s={HMgvE:function(l,f){return e[W(1750)](l,f)},Xfhtl:function(l,f){return e.zBacm(l,f)},Hgopn:function(l,f){return e[W(1645)](l,f)},GLzao:e[n(1927)],KhQaO:e[n(1559)],AKewB:function(l,f){return e[n(1774)](l,f)},jksiL:e[n(977)],EBOxx:function(l,f){return e[n(1072)](l,f)},LAThY:e[n(1408)],iEsaD:e[n(1577)]};return new Promise(l=>{let f=n,m={BNtZX:function(y,E){return s[W(1133)](y,E)},vybuy:function(y,E){return s[W(1513)](y,E)},esTdr:function(y,E){return y(E)},pDpnO:function(y,E){return s[W(1133)](y,E)}};if(s[f(1523)]("wqQGY",s[f(1744)]))return this[f(645)]?.get(_0x437ebb);if(!cr)return s.Xfhtl(l,"unknown "+f(729));try{let y=document["createEl"+f(1355)](f(1236));window["frontier"+f(1780)]=E=>{let p=f;if(m[p(1485)]("vuUwN",p(534)))return null;document[p(1881)].removeChild(y),window[p(1872)+"JSONP"]=void 0,l(E&&E[p(693)]||"unknown "+p(729))},y[f(1636)]=s[f(1409)],y.src=s.AKewB(a[f(1208)](/^ws/,"http"),s[f(1705)]);try{document[f(1881)][f(1879)+f(1504)](y)}catch{document.body[f(1083)+"ild"](y)}}catch{if(s[f(1214)](f(1836),s[f(539)])){if(_0x32e7a9 instanceof _0x1c0596)return ikrBZJ[f(1292)](_0x57f021,_0x2017eb);if(_0x2628b0[f(1422)](_0x2b0231))return _0xcc8d68.get(_0x349b59);let y=ikrBZJ[f(1377)](_0x169277,_0x343ffd);return ikrBZJ[f(1694)](y,_0x96f2c2)&&(_0x8f9d86[f(646)](_0x2b7627,y),_0x33b96a[f(646)](y,_0x1141f3)),y}else window[f(1872)+f(1780)]=void 0,s[f(1513)](l,s[f(1755)])}})}function ln(a,n,s){let l=t,f={WsHyY:function(m,y,E){return m(y,E)}};if(e[l(1415)](e[l(1425)],e[l(1425)]))return!!a?.[l(1796)](m=>m[l(1909)]===n&&m[l(836)]===s);ibNTMJ[l(728)](_0x596e0c,_0x53109c,24),_0x12a5f9(_0x3f9eb6,_0x3c9d59(_0x751518))}function dr(a,n){let s=t;return a?.[s(1796)](l=>l[s(1909)]===n)?.[s(836)]}let ka=null;async function sg(){let a=t,n={gwqNm:function(s,l){return e[W(1361)](s,l)},pzcmS:e[a(494)],ZFEud:a(768)+a(940),KRyvA:function(s,l){return e[a(1645)](s,l)},wqcYx:a(947),WjQef:function(s,l){return e[a(1722)](s,l)}};if(e[a(942)](e.tKSzc,e[a(1746)])){if(_0x315e6f instanceof _0x56f44d){if(raErWN[a(585)](_0x1c4732,raErWN[a(1829)]))return _0x296daa.get(_0x2f555c);if(_0x2e7b42===raErWN.ZFEud)return _0x363c96["objectSt"+a(940)]||_0x5c4156[a(798)](_0x38d612);if(raErWN[a(988)](_0x10df73,raErWN[a(1813)]))return _0x1e8a15[a(768)+a(940)][1]?void 0:_0x465e0d[a(768)+a(674)](_0xab9b6[a(768)+a(940)][0])}return raErWN[a(1997)](_0xe841ac,_0x1b249c[_0x29ad08])}else return ka||(ka=Promise[a(1329)]()[a(1403)](Ut[a(1975)](Ut,e.vJAtA))),ka}class og extends Ia{constructor(n,s){let l=t;super(),this[l(1227)]=n,this[l(1954)]=s,this[l(645)]=void 0,this._initPromise=null}async openDB(){await this[t(612)]()}async[t(612)](){let n=t,s={sQjzD:function(l,f){return l(f)},ChJPe:function(l,f){return e.uTdUl(l,f)},pyUOZ:function(l,f){return e[W(887)](l,f)},yboMd:e[n(1194)],jAQIE:e[n(1859)]};if(!this[n(645)]){if(this["_initPro"+n(595)])return this[n(1741)+n(595)];try{let l=this._dbName,f=this[n(1954)];this._initPromise=(async()=>{let m=n,{openDB:y}=await e.Gglgy(sg);this[m(645)]=await e.Ntxtm(y,m(1872)+"_"+l,1,{upgrade(E){E[m(1703)+"jectStore"](l,{keyPath:f})}})})(),await this[n(1741)+"mise"]}catch(l){console[n(1580)](l)}finally{if(e[n(931)](e[n(670)],e.ZihcD))this[n(1741)+"mise"]=null;else{let l=_0x2cb165[n(479)](/\./)[n(1405)](y=>_0x29a03d(y)),f=[];return f[0]=GYclIB[n(1635)](_0x54e135,GYclIB[n(1429)](l[0],l[1])),f[1]=GYclIB.pyUOZ(_0x46b1bf,l[2]+l[3]),[n(1040),GYclIB[n(1683)],GYclIB.yboMd,GYclIB[n(1683)],GYclIB[n(1683)],GYclIB[n(747)],f[0],f[1]][n(1437)]("")}}}}async[t(798)](n){let s=t;try{return await this[s(612)](),this[s(645)]?.[s(798)](this[s(1227)],n)}catch(l){console[s(1580)](l)}}async[t(646)](n,s){let l=t;return await this[l(612)](),this[l(645)]?.[l(1090)](this._dbName,n)}async del(n){let s=t;if(e[s(1171)](s(1143),e[s(1287)]))try{return await this[s(612)](),this[s(645)]?.delete(this[s(1227)],n)}catch(l){console[s(1580)](l)}else this[s(645)]?.[s(1709)](),this[s(645)]=void 0}async[t(840)](){let n=t;try{return await this[n(612)](),this[n(645)]?.[n(840)](this._dbName)}catch(s){console[n(1580)](s)}}async[t(884)](){let n=t;return await this._init(),this[n(645)]?.[n(822)+"ys"](this[n(1227)])}async[t(1811)](){let n=t;return await this[n(612)](),this[n(645)]?.[n(1811)](this[n(1227)])}async closeDB(){let n=t,s={PrbWT:function(l,f,m,y){return l(f,m,y)}};try{e.VocrE(e[n(613)],e[n(613)])?(this[n(645)]?.[n(1709)](),this[n(645)]=void 0):s[n(675)](_0xee7adf,this,_0x587b2f,[_0x20ea9f,_0x4c51c3,_0x51d788,_0x1c938f,_0x4b30c8,_0x4d090a])}catch(l){console[n(1580)](l)}}get isReady(){let n=t;if(e.ybuUm!==e[n(1268)])try{return!!this[n(645)]}catch(s){return console[n(1580)](s),!1}else _0x3c5978[_0x17cf5f++]=e[n(847)](_0x733f35,6)|192,_0x49280b[_0x164f89++]=e[n(1653)](e.sgSVv(63,_0x13bedb),128)}}class ag{constructor(n,s){let l=t;this._DBName=n,this._pathKey=s,this[l(645)]=localStorage}async[t(1510)](){}get[t(1877)](){return"frontier_"+this[t(503)]}async[t(798)](n){let s=t,l=this[s(645)][s(1071)](this._prefix);return JSON[s(1390)](e[s(574)](l,"{}"))[n]}async set(n,s){let l=t,f=this[l(645)].getItem(this[l(1877)]),m=JSON[l(1390)](f||"{}");return m[s||n[this[l(1691)]]]=n,this[l(645)].setItem(this[l(1877)],JSON[l(937)+"y"](m)),s||n[this._pathKey]}async[t(1730)](n){let s=t,l=this[s(645)][s(1071)](this[s(1877)]),f=JSON.parse(e[s(469)](l,"{}"));return f[n]=void 0,this[s(645)].setItem(this[s(1877)],JSON[s(937)+"y"](f))}async[t(840)](){let n=t;return this._qosDB[n(840)]()}async[t(884)](){let n=t,s=this._qosDB.getItem(this[n(1877)]),l=JSON.parse(e[n(603)](s,"{}"));return Object.keys(l)}async[t(1811)](){let n=t,s=this[n(645)].getItem(this[n(1877)]),l=JSON.parse(e.pBHhm(s,"{}"));return Object[n(716)](l)}closeDB(){return Promise[t(1329)]()}get[t(1028)](){return!!this[t(645)]}}class cg{constructor(n,s){let l=t;this._DBName=n,this[l(1691)]=s,this[l(645)]=Ln?tt:ii?wx:null}async[t(1510)](){}get[t(1877)](){return t(1872)+"_"+this._DBName}async[t(798)](n){let s=t,l=this[s(645)][s(655)+"geSync"](this._prefix);return JSON.parse(e[s(469)](l,"{}"))[n]}async set(n,s){let l=t;if(e.nNtdq(e.egZuX,l(1009))){let f=this[l(645)][l(655)+l(1742)](this._prefix),m=JSON[l(1390)](e[l(1061)](f,"{}"));return m[s||n[this[l(1691)]]]=n,this._qosDB[l(792)+l(1742)](this[l(1877)],JSON[l(937)+"y"](m)),s||n[this[l(1691)]]}else{let f=e[l(1847)](_0x479716,e[l(1767)],{message:_0x32a8f3[l(1955)],code:_0xb8d8[l(758)+"OR"],error:_0x109b47});this["_dispatc"+l(842)+l(958)](f)}}async[t(1730)](n){let s=t,l=this[s(645)]["getStora"+s(1742)](this[s(1877)]),f=JSON[s(1390)](e.WDNOr(l,"{}"));return f[n]=void 0,this._qosDB[s(792)+s(1742)](this[s(1877)],JSON[s(937)+"y"](f))}async clear(){let n=t;return this[n(645)][n(971)+"rageSync"]()}async[t(884)](){let n=t,s=this[n(645)]["getStora"+n(883)+"nc"](this._prefix),l=JSON[n(1390)](e[n(1192)](s,"{}"));return Object[n(884)](l)}async getAll(){let n=t,s=this[n(645)]["getStora"+n(883)+"nc"](this[n(1877)]),l=JSON[n(1390)](e[n(469)](s,"{}"));return Object[n(716)](l)}closeDB(){return Promise.resolve()}get isReady(){let n=t,s={bzMcV:function(l,f){return l===f},feVrJ:function(l,f){return e[W(1448)](l,f)},faGph:n(768)+n(940),OZZUT:e[n(1450)]};if(e[n(604)]("UOoGr",e.kpXJg)){if(AVWkxU[n(1462)](_0x38b4d1,"done"))return _0x4af64a[n(798)](_0x171e74);if(AVWkxU.feVrJ(_0x4a55b5,AVWkxU[n(1379)]))return _0x50f18a[n(768)+"oreNames"]||_0x1adddb[n(798)](_0x5a3f88);if(AVWkxU[n(1462)](_0x177f92,AVWkxU[n(1139)]))return _0xe3ce61["objectSt"+n(940)][1]?void 0:_0x48f9dd[n(768)+n(674)](_0x2d4030["objectSt"+n(940)][0])}else return!!this[n(645)]}}function Il(a,n){let s=t;if(e.qZzGd(Ln,Ln))return new cg(a,n);if(e.dcMkO(cr,si)&&e[s(1220)](e[s(556)],typeof indexedDB))return new og(a,n);if((cr||si)&&e.XIzZo(e[s(556)],typeof localStorage))return new ag(a,n);throw new Error(e[s(1833)])}class dg{constructor(){let n=t;this["_interva"+n(562)+"Id"]=null,this[n(1726)+"l"]=36e5,this[n(645)]=Il(e.HrSSb,e[n(821)])}async["_interva"+t(1662)](){let n=t;clearInterval(this._intervalTimeoutId),this[n(1726)+"lTimeoutId"]=e.FblNh(setInterval,()=>{let s=n;this[s(1897)+s(974)]()},this._interval)}async[t(1510)](){let n=t;e[n(706)]===e.vecqG?(this[n(730)]=!0,this[n(1976)]()):await this[n(645)][n(1510)]().then(()=>{this[n(1726)+"lFlush"]()})}async[t(1897)+t(974)](){let n=t;if(n(1768)===e[n(517)]){let s=_0xb6012d[_0x5239c0++];if(s<=127)_0x354f04+=_0x5ede6e[n(1756)+"Code"](s);else if(e.VoqjB(s,192)&&s<224)_0x4e96e1+=_0x4db458[n(1756)+n(1116)](e[n(1182)](31&s,6)|63&_0x575d95[_0x3957ab++]);else if(s>=224&&e[n(1676)](s,240))_0x27dd38+=_0x4d6fea["fromChar"+n(1116)](e.GLwoj(e[n(1689)](e[n(1402)](e.pfAyh(15,s),12),e.IhGGb(e[n(1986)](63,_0x3b0232[_0x3024a7++]),6)),e[n(1439)](63,_0x3ccf6c[_0x4ecee0++])));else if(s>=240){let l=e[n(1033)](e.FPIYW(e[n(857)](e[n(751)](e[n(1989)](e[n(607)](7,s),18),e[n(1998)](63&_0x4c74b3[_0xb02809++],12)),e[n(955)](e.AgAjL(63,_0x4d1611[_0xaf742++]),6)),e[n(1915)](63,_0x186d52[_0x30dd26++])),65536);_0x4dad81+=_0x922d7a[n(1756)+n(1116)](e.uZusn(55296,e[n(1021)](l,10))),_0x30153e+=_0x4a1d23[n(1756)+"Code"](e[n(1646)](56320,e[n(1188)](1023,l)))}}else(await this[n(645)]?.getAll()||[]).filter(({timestamp:f})=>f<Date.now())[n(1206)](f=>{let m=n;this[m(645)]?.[m(1730)](f[m(746)+"id"])})}async[t(1730)](n){let s=t;return this[s(645)]?.[s(1730)](n)}async[t(646)](n,s){return this._qosDB?.set({message_id:n,timestamp:s})}async[t(798)](n){let s=t,l={cTkmN:e.Nmprp,oNTJm:e.wtbxc,nzJVw:function(f,m,y,E){return f(m,y,E)},ogDbb:function(f,m,y,E){return e[W(997)](f,m,y,E)},YeQCP:function(f,m,y,E){return e[W(1016)](f,m,y,E)},pXFrY:s(701),XDTYr:function(f,m){return e[s(1971)](f,m)},psLVF:e[s(1581)]};if(e[s(1617)](e.rIHzG,e[s(498)])){let f={BQYpD:l.cTkmN,HiWOA:l.oNTJm,cahWg:function(k,O,N,F){return l.nzJVw(k,O,N,F)},RjHAP:function(k,O,N,F){return l.ogDbb(k,O,N,F)},TGALU:"service-"+s(965),bvnbx:function(k,O,N,F){return l[s(1500)](k,O,N,F)},bneji:l[s(742)]},[m,y]=l[s(1973)](_0x453e31,_0x51a84a),E=_0x481492(m),p=0;return _0x424432[s(1206)](k=>{let O=s;_0x4eb8a6.log(f[O(915)],k,k[O(1905)]),p=_0x13354d(0,E,p),_0x443356.log(f[O(1665)],p),p=f.cahWg(_0x18e2ac,E,p,k.service||0),_0xa75cee[O(1580)](O(1905),p),p=f.RjHAP(_0x265185,y[k["cursor_n"+O(748)]],E,p),_0x47c780[O(1580)](f.TGALU,p),p=f[O(1149)](_0x4b6ddf,k[O(1695)+"ame"],E,p),_0xbe9604[O(1580)](O(965),p),p=f[O(808)](_0x1ff5cd,_0xb3f0a5[O(1412)+"er"](k[O(995)]||_0x53aedf),E,p),_0x26eec5[O(1580)](f[O(501)],p)}),{frameType:_0x20eeac,headers:[{key:l[s(1441)],value:_0xaac38c}],payload:E}}else return this[s(645)]?.[s(798)](n)}async closeDB(){let n=t;e.QiImW(clearInterval,this[n(1726)+"lTimeoutId"]),await this[n(645)]?.closeDB()}get[t(1028)](){let n=t;return this[n(645)]?.[n(1028)]}}function Ta(a){let n=t,s=!!this[n(1257)][n(1359)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=ln(a[n(1955)][n(1338)],e.Ukcib,"2"),f=l&&e[n(818)](ln,a[n(1955)][n(1338)],e[n(1477)],"1"),m=l&&e[n(997)](ln,a[n(1955)][n(1338)],e[n(1550)],"1"),y=m?e[n(998)](dr,a.message.headers,e[n(1036)])?.split(",")[n(1017)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:m,ackMsgIds:y}}async function Al(){let a=t;return this[a(1138)+"ger"]||(this[a(1138)+a(1702)]=new dg),this["_QoSMana"+a(1702)][a(1028)]||await this["_QoSMana"+a(1702)][a(1510)](),this[a(1138)+a(1702)]}async function lg(a,n){let s=t,{enableAutoAck:l}=this[s(1257)],f=ln(a[s(1955)].headers,e.YHvPb,"1"),m=e[s(1525)](ln,a[s(1955)][s(1338)],e[s(1238)],"1"),y=Ta.call(this,a);if(e[s(982)](l,f))if(e[s(1826)](e[s(779)],e[s(779)])){let{offset:E}=e.XUXaC(_0x2589bb,_0x40eb21,_0x2d9cc7);_0x3634a9=E;let p={cursor_name:"",cursor:0,service:0},{value:k,offset:O}=_0x2348ea(_0x27e8bd,_0x1789c3);p.service=k,_0xeda242=O;let{value:N,offset:F}=e[s(1606)](_0x4dbe74,_0x27e70f,_0x35da80);_0x322b34=F,p[s(1695)+s(748)]=e.DfoZC(_0xe2da62,_0x4b4ef0,_0x1ebef4,e[s(944)](_0x6d922b,N)),_0x31dd04+=N;let{value:U,offset:ie}=e.XwuGi(_0x57708d,_0x5137e7,_0x105ff6);p[s(995)]=U.toNumber(),_0x446067=ie,_0x260dce[s(468)](p)}else{let{SeqID:E,LogID:p,service:k,LogIDNew:O,method:N}=a[s(1955)];this[s(1583)]({SeqID:E,LogID:p,LogIDNew:O,service:k,method:N,headers:[{key:e[s(1238)],value:"1"},{key:e.jyJJY,value:e[s(1518)](O,"")},{key:e[s(1642)],value:"0"}]})}m&&!y[s(2002)]&&this[s(692)+s(635)+"ageEvent"](a),n()}async function ug(a,n){let s=t;this[s(1305)](e.srzUh,a[s(1955)]),e[s(1906)](n)}async function fg(a,n){let s=t,l={Aqppj:function(m,y){return e[W(1718)](m,y)},sspde:e[s(852)],vcpzx:s(921)+s(741),GClKa:e[s(1714)],uRTwJ:e.ktWeH,kxVWq:"none_none",TXuZH:e[s(1610)],wgCbp:function(m,y,E,p){return e.IcsyV(m,y,E,p)}},f=e.vaCfU(an,await e[s(1022)](Sl,a[s(1109)]));try{if(e[s(1026)]("xJeHp",s(1346)))if(f[s(1932)]instanceof Uint8Array){let m=e[s(914)](this._options["payloadE"+s(1099)],Object)?{force:!!this._options[s(1380)+"ncoding"][s(1312)],encoding:this[s(1257)].payloadEncoding[s(1456)]?this[s(1257)][s(1380)+s(1099)][s(1456)][s(1208)](/\s/g,"")[s(1688)+s(474)]():""}:{force:!1,encoding:this[s(1257)][s(1380)+s(1099)]?this[s(1257)][s(1380)+s(1099)].replace(/\s/g,"")[s(1688)+s(474)]():""},y=f[s(1380)+s(1099)]?f[s(1380)+s(1099)][s(1208)](/\s/g,"")[s(1688)+"ase"]():"",E=this[s(1257)]["payloadT"+s(1170)]instanceof Object?{force:!!this[s(1257)][s(1810)+s(1170)][s(1312)],type:this[s(1257)][s(1810)+s(1170)][s(1636)]?this[s(1257)][s(1810)+s(1170)][s(1636)][s(1208)](/\s/g,"")[s(1688)+"ase"]():""}:{force:!1,type:this[s(1257)]["payloadT"+s(1170)]?this[s(1257)][s(1810)+s(1170)][s(1208)](/\s/g,"")[s(1688)+s(474)]():""},p=f[s(1810)+s(1170)]?f["payloadT"+s(1170)][s(1208)](/\s/g,"")[s(1688)+s(474)]():"",k=E[s(1312)]?E[s(1636)]:p||E[s(1636)],O=m[s(1312)]?m[s(1456)]:y||m[s(1456)],N=[e[s(852)],e[s(1080)],s(921)+s(741)+s(796)+"=utf-8",e.ktWeH],F=[e[s(1594)],e[s(1610)]];this._options[s(1887)+"ansformTextPayload"]&&N.includes(k)&&(!O||F[s(553)](O))?f[s(791)+s(1890)]=vl(f[s(1932)],0,f[s(1932)][s(638)+"th"]):f[s(791)+s(1890)]=""}else f[s(791)+s(1890)]="";else if(_0x34110d.payload instanceof _0x8f5dc8){let m=l[s(1162)](this[s(1257)]["payloadE"+s(1099)],_0x2e8442)?{force:!!this[s(1257)][s(1380)+s(1099)].force,encoding:this[s(1257)][s(1380)+s(1099)][s(1456)]?this[s(1257)]["payloadE"+s(1099)][s(1456)][s(1208)](/\s/g,"")[s(1688)+s(474)]():""}:{force:!1,encoding:this[s(1257)][s(1380)+s(1099)]?this[s(1257)][s(1380)+s(1099)].replace(/\s/g,"")[s(1688)+"ase"]():""},y=_0x1a4b24[s(1380)+s(1099)]?_0x4ff11e[s(1380)+s(1099)][s(1208)](/\s/g,"")[s(1688)+s(474)]():"",E=this[s(1257)][s(1810)+s(1170)]instanceof _0x54da13?{force:!!this[s(1257)][s(1810)+s(1170)][s(1312)],type:this[s(1257)][s(1810)+"ype"][s(1636)]?this[s(1257)]["payloadT"+s(1170)].type[s(1208)](/\s/g,"")[s(1688)+"ase"]():""}:{force:!1,type:this[s(1257)]["payloadT"+s(1170)]?this[s(1257)][s(1810)+s(1170)][s(1208)](/\s/g,"")[s(1688)+s(474)]():""},p=_0x37883a[s(1810)+s(1170)]?_0x1c4a91[s(1810)+"ype"][s(1208)](/\s/g,"").toLowerCase():"",k=E[s(1312)]?E[s(1636)]:p||E[s(1636)],O=m[s(1312)]?m[s(1456)]:y||m[s(1456)],N=[l[s(846)],l.vcpzx,l[s(896)],l[s(1607)]],F=[l[s(999)],l[s(1112)]];this[s(1257)][s(1887)+s(1145)+s(1978)+"ad"]&&N.includes(k)&&(!O||F[s(553)](O))?_0x44dc34[s(791)+"oad"]=l[s(1930)](_0x501c27,_0x2f9a02[s(1932)],0,_0x3394bd[s(1932)][s(638)+"th"]):_0x57bf19[s(791)+"oad"]=""}else _0x39df24[s(791)+"oad"]=""}catch(m){s(1880)===s(1880)?(f["textPayl"+s(1890)]="",console[s(1580)](m)):(_0x189267+=_0x3372b3(_0x9e37d7),_0x139367+=2)}a[s(1955)]=f,e[s(1235)](n)}function xg(a,n,s){let l=t,f={VzNwb:function(k,O){return e.NnPvc(k,O)},pPhdH:function(k,O){return e[W(1051)](k,O)},QdbTR:function(k,O){return e[W(1134)](k,O)},UfOtz:function(k,O){return e[W(837)](k,O)},YupcL:function(k,O){return e[W(1658)](k,O)},YxrJh:e[l(1692)],gRHrC:function(k,O){return e[l(1393)](k,O)},BYbKV:function(k,O){return e[l(1323)](k,O)},UqQfq:function(k,O){return e.MdkOj(k,O)}},m=e[l(603)](s,8192),y=e[l(1473)](m,1),E=null,p=m;return function(k){let O=l;if(k<1||f[O(542)](k,y))return f.UfOtz(a,k);f[O(542)](f[O(813)](p,k),m)&&(f[O(600)](f.YxrJh,O(1316))?(_0x508318[_0x2202a8[_0x59c688][O(1695)+O(748)]]=f.VzNwb(_0x43fd24,_0x209712[_0x93579f][O(1695)+O(748)]),_0x158d50+=f.pPhdH(14,_0x1fe03d[_0x4f00dc[_0x565517].cursor_name])):(E=a(m),p=0));let N=n.call(E,p,p+=k);return f[O(1571)](7,p)&&(p=f[O(557)](f[O(1612)](7,p),1)),N}}let hg=4294967295;function pg(a,n,s){let l=t;return e[l(1679)](RangeError,e[l(1913)](e.GNBLu(e.RWQCy(l(598)+"t of ran"+l(559)+a," + "),e[l(469)](n,1)),l(1065))+s)}function gg(a,n,s){let l=t;if(e[l(1472)](s,hg))throw new Error(e[l(1296)]);let f=3;for(;e[l(856)](f,0);){let m=e[l(1846)](255,s);e[l(941)](Pa,m,a,n+f),s>>>=8,f--}return e[l(1064)](n,4)}function mg(a,n){let s=t,l={xhLBc:function(E){return e.Gglgy(E)}},f=0,m=n,y=n+4;for(;m<y;)if(e[s(1319)](e[s(487)],e[s(487)]))pgaKgu[s(1487)](_0x4ce73a),pgaKgu[s(1487)](_0x42b0fd);else{let{value:E,offset:p}=e[s(481)](Ra,a,m);m=p,f=e[s(1935)](e[s(1998)](f,8),0),f+=E}return{value:f,offset:y}}function wg(a,n,s){let l=t,f=e[l(1087)][l(479)]("|"),m=0;for(;;){switch(f[m++]){case"0":if(!a)return s;continue;case"1":return e[l(928)](Aa,a,n,s)+s;case"2":if(n[l(1545)+"e"])return n[l(1545)+"e"](a,s)+s;continue;case"3":if(e[l(738)](a[l(1994)],40))return Aa(a,n,s)+s;continue;case"4":if(n[l(919)])return e[l(989)](n[l(919)](a,s),s);continue}break}}function _g(a,n){let s=t,l=new he(e[s(1738)](e[s(1706)](e[s(797)](a[e[s(1424)](n,4)],24),e[s(1912)](a[n+5],16))|e[s(1839)](a[e.pmkkS(n,6)],8),a[e[s(1401)](n,7)]),e.CCqkd(e[s(1653)](e.qomWE(e[s(877)](a[e[s(1711)](n,0)],24),e[s(584)](a[e[s(1928)](n,1)],16)),e.PLPMU(a[e.sOCXK(n,2)],8)),a[n+3]),!0);return n+=8,{value:l,offset:n+8}}function yg(a,n,s){let l=t,f=a[l(1060)],m=a[l(1176)];return n[s]=e[l(1331)](m,24),n[e[l(1323)](s,1)]=e[l(916)](e[l(608)](m,16),255),n[e[l(1524)](s,2)]=e.RLbNw(m>>>8,255),n[e.xqWgo(s,3)]=e[l(750)](255,m),n[s+4]=e.eqfvE(f,24),n[e[l(1323)](s,5)]=e[l(657)](f,16)&255,n[e[l(666)](s,6)]=e[l(815)](f,8)&255,n[s+7]=e[l(1502)](255,f),s+=8,s}function Ra(a,n){let s=t;return a.readUInt8?{value:a.readUInt8(n),offset:e[s(1163)](n,1)}:{value:255&a[n],offset:e[s(1046)](n,1)}}function Pa(a,n,s){let l=t;return n[l(520)+"t8"]?n[l(520)+"t8"](a,s):n[s]=e[l(1793)](255,a),e.EIrDE(s,1)}let bg=function(a){let n=t,s={zAQwJ:function(l,f){return e[W(1324)](l,f)},sNEkD:function(l,f){return e[W(664)](l,f)},JFnaz:function(l,f){return l>>>f},jupzA:function(l,f){return e[W(1799)](l,f)},aPnxi:function(l,f){return e[W(500)](l,f)},bqBVB:function(l,f){return e[W(815)](l,f)},TKTjm:function(l,f){return e.ujxvQ(l,f)}};return e[n(1089)](e[n(1854)],e[n(1854)])?new Uint8Array(a):_0x83a93e.fromCharCode(255&this[n(1060)],InDjxA[n(1569)](this[n(1060)]>>>8,255),InDjxA[n(1003)](this.low,16)&255,InDjxA[n(1283)](this[n(1060)],24),InDjxA[n(816)](255,this[n(1176)]),InDjxA[n(715)](InDjxA[n(740)](this[n(1176)],8),255),InDjxA[n(1569)](InDjxA[n(1002)](this[n(1176)],16),255),InDjxA[n(1283)](this[n(1176)],24))},Eg=e[t(476)](e[t(556)],typeof Buffer)?Buffer[t(1339)+"afe"]:e[t(767)](xg,bg,Uint8Array[t(1771)+"e"][t(1766)]);(()=>{let a=t,n={DZzrN:a(1130)+"7|10|11|"+a(1772)+"9",RLRws:function(l,f){return e.yCUqE(l,f)},hQXnu:function(l,f){return l>>>f},eIPRR:function(l,f){return l&f},wkKLa:function(l,f){return l<f},LGHzJ:function(l,f){return e[a(652)](l,f)},LtPvg:function(l,f){return e.QZarG(l,f)},PfiAc:function(l,f){return e[a(1798)](l,f)},azgkU:function(l,f){return e[a(1935)](l,f)},GBvaD:function(l,f){return e[a(1252)](l,f)},ZAWwV:function(l,f){return e[a(629)](l,f)},QEzCo:function(l,f){return e[a(1783)](l,f)},QvyjR:function(l,f){return e[a(1165)](l,f)},MMTTX:function(l,f){return l|f},lSRQV:function(l,f){return l<<f},YDigB:function(l,f){return e[a(1234)](l,f)}},s=4294967295;return function(l,f,m=!0){let y=a,E=n[y(1924)][y(479)]("|"),p=0;for(;;){switch(E[p++]){case"0":if((f+=5)>l[y(1994)])throw f=l[y(1994)],pg(f,10,l.length);continue;case"1":if(l[f++]<128)return{value:m?s:0|s,offset:f};continue;case"2":if(n[y(1179)](l[f++],128))return{value:m?s:0|s,offset:f};continue;case"3":s=n[y(1575)](n[y(867)](127,l[f]),0);continue;case"4":if(n[y(1944)](l[f++],128))return{value:m?s:n[y(1155)](0,s),offset:f};continue;case"5":s=(s|n[y(996)](n[y(1980)](127,l[f]),7))>>>0;continue;case"6":s=n[y(1093)](n[y(1155)](s,n[y(1980)](15,l[f])<<28),0);continue;case"7":s=n.azgkU(n.GBvaD(s,n[y(918)](n[y(1980)](127,l[f]),14)),0);continue;case"8":if(n[y(711)](l[f++],128))return{value:m?s:n[y(851)](0,s),offset:f};continue;case"9":return{value:m?s:n[y(1814)](0,s),offset:f};case"10":if(n[y(711)](l[f++],128))return{value:m?s:n.MMTTX(0,s),offset:f};continue;case"11":s=n[y(1575)](s|n.lSRQV(n[y(1142)](127,l[f]),21),0);continue}break}}})();let vg=16,Ca=32;function Sg(a){let n=t,s=0,l={};for(let f=0;f<a[n(1994)];f++)l[a[f][n(1695)+"ame"]]=e[n(1486)](El,a[f]["cursor_n"+n(748)]),s+=e[n(1913)](14,l[a[f]["cursor_n"+n(748)]]);return[s,l]}function kl(a,n,s){let l=t,[f,m]=e[l(786)](Sg,a),y=e[l(970)](Eg,f),E=0;return a[l(1206)](p=>{let k=l;e.zaRCr(e.nTaQM,e.EDUcZ)?(console[k(1580)](e[k(1131)],p,p[k(1905)]),E=Pa(0,y,E),console[k(1580)](e[k(526)],E),E=gg(y,E,p[k(1905)]||0),console[k(1580)](k(1905),E),E=Pa(m[p[k(1695)+k(748)]],y,E),console[k(1580)](e[k(1186)],E),E=e[k(1250)](wg,p[k(1695)+k(748)],y,E),console[k(1580)](k(965),E),E=yg(he[k(1412)+"er"](p.cursor||n),y,E),console.log(k(701),E)):_0x4e05ac[k(1703)+"jectStore"](_0x3271d7,{keyPath:_0x2dc1de})}),{frameType:Ca,headers:[{key:e[l(1581)],value:s}],payload:y}}function Ig(a){let n=t,s=0,l=[];for(;e.ILMKb(s,a[n(638)+"th"]);){let{offset:f}=e.DyVhO(Ra,a,s);s=f;let m={cursor_name:"",cursor:0,service:0},{value:y,offset:E}=e[n(1464)](mg,a,s);m[n(1905)]=y,s=E;let{value:p,offset:k}=e[n(827)](Ra,a,s);s=k,m[n(1695)+"ame"]=e.mjDzu(vl,a,s,e[n(1120)](s,p)),s+=p;let{value:O,offset:N}=e[n(669)](_g,a,s);m.cursor=O[n(1343)](),s=N,l[n(468)](m)}return l}function Ag(){let a=t;return{frameType:Ca,headers:[{key:e[a(1581)],value:e[a(762)]}],payload:void 0}}class kg{constructor(n,s,l){let f=t;if(e.VocrE(e[f(1974)],e[f(708)])){let m=this[f(1e3)+f(1982)]?.[f(882)+"ntEndpoint"]();this[f(692)+"hCloseEv"+f(958)](e[f(1882)](_0xbc796d,e[f(1874)],{code:1006,reason:f(963)+m+(f(1111)+f(1574)+f(967)+f(489)),wasClean:!0}))}else this["_cursorN"+f(461)]=n,this[f(911)+f(1010)]=s,this[f(697)+f(771)]=l,this[f(645)]=e[f(1216)](Il,this[f(1185)+"ameSpace"],f(1695)+"ame")}async[t(1510)](){let n=t;e.yWvZM(e[n(1295)],n(1652))?await this[n(645)][n(1510)]():(e[n(643)](_0x5bdbdb,_0x2d79d4,74),_0xbc3b42(_0x497e73,_0x1a6e4e))}async getCursors(){let n=t;if(!this._qosDB[n(1028)])return;let s=this[n(697)+n(771)],l=await this[n(645)].getAll();switch(console[n(1580)](n(1215)+n(1566),l),s){case n(841):return l&&l[n(1994)]?kl(l,0,this["_cursorF"+n(1010)]):void 0;case e[n(860)]:return;case e.eTqWb:return l&&l[n(1994)]?e[n(1250)](kl,l,0,this[n(911)+n(1010)]):e.uTfHl(Ag)}}async[t(646)](n,s,l){let f=t;return console[f(1580)](e[f(592)],n,s,l),this[f(645)][f(646)]({cursor_name:n,cursor:s,service:l})}async[t(1844)+"rs"](n){let s=t,l=e[s(1156)](Ig,n);for(let f of l)console.log(e[s(637)],l),await this[s(645)].set(f)}async[t(798)](n){let s=t;return(await this._qosDB[s(798)](n))?.[s(995)]}async[t(1481)](){let n=t;e.OLPMk(e.FHMRU,e[n(1053)])?await this[n(645)][n(1481)]():this[n(2001)+n(1340)+n(1763)+"t"]=0}["updateCursorFile"+t(1102)](n){let s=t;this[s(911)+s(1010)]=n}get[t(1028)](){let n=t;return this._qosDB[n(1028)]}}let Tg=e[t(1870)];async function Tl(a){let n=t;if(!this._options[n(1359)+"S"])return null;let{aID:s,fpID:l,messageStrategy:f}=this[n(1257)],m=a||Tg;try{return this[n(1542)+n(1533)]?a&&this[n(1542)+n(1533)][n(1535)+n(1592)+n(1102)](a):this[n(1542)+n(1533)]=new kg(l+"_"+s+"_"+m,m,f),this[n(1542)+"anager"][n(1028)]||await this["_cursorM"+n(1533)][n(1510)](),this[n(1542)+n(1533)]}catch{return null}}async function Rg(a,n){let s=t,l=ln(a[s(1955)][s(1338)],e.wDHdA,"-1"),f=e[s(997)](ln,a[s(1955)].headers,e.FnzWY,"1"),m=e[s(1240)](dr,a.message[s(1338)],e[s(581)]),y=e[s(1745)](Number,e[s(1606)](dr,a[s(1955)][s(1338)],s(1451)+s(1263)))||0,E=Ta[s(1326)](this,a),p=e.LPaOu(ln,a[s(1955)][s(1338)],s(1466)+"s","2"),k=e[s(826)](dr,a[s(1955)][s(1338)],e[s(1330)]),O=Number(e[s(1619)](dr,a.message[s(1338)],e[s(1041)]));if(E[s(2002)])return e.lctyL(n);let N=E[s(564)+s(688)]?await Al[s(1326)](this):null;if(e[s(470)](a.message.service,0)&&f&&!l||a[s(1955)].service>0){if(m&&E["isQoSMes"+s(688)]&&N){if(!!!await N[s(798)](m))if(e[s(594)](e[s(712)],e[s(1999)]))this[s(692)+s(1389)+s(1812)](a),await N[s(646)](m,e.GPfaq(Date.now(),y));else{let U=e.ULrTn(_0x3e7cda,_0x8feee1);this[s(1530)]&&e[s(1095)](this[s(1530)][s(722)+"te"],this[s(1058)])&&(this[s(1530)]&&this[s(1530)][s(1940)](U),this[s(1305)](e[s(1667)],_0x77cd2b))}return e.gaeMY(n)}if(p){let F=await Tl.call(this);if(!F)return this["_dispatc"+s(1389)+s(1812)](a),e.lctyL(n);let U=await F[s(798)](k)??-1;if(e[s(1601)](U,O))this[s(692)+s(1389)+s(1812)](a),F[s(646)](k,O,a[s(1955)].service);else throw new Error(s(1454)+s(606)+s(1132)+O+(s(1938)+"than loc"+s(1239)+"r ")+U);return e.tAuzi(n)}return this[s(692)+"hMessage"+s(1812)](a),e[s(1235)](n)}}async function Pg(a,n){let s=t,l=Ta.call(this,a);if(!l[s(564)+s(688)])return e[s(550)](n);let f=await Al.call(this);if(l[s(560)+s(1351)+s(1775)]&&l[s(951)+"s"].length)for(let m of l[s(951)+"s"])await f.del(m);n()}async function Cg(a,n){let s=t,l=e.httEr(a.message[s(680)+"e"],vg),f=e.xFEOg(a[s(1955)].frameType,Ca);if(e[s(982)](!l,!f))return e.nyvPM(n);let m=e[s(1269)](dr,a[s(1955)][s(1338)],e[s(1581)]);if(!m)return n();let y=await Tl[s(1326)](this,m);if(!y)return n();if(l)if(e[s(1804)]==="ziajo")this[s(1205)](s(1193),_0x60cfe8),this[s(1210)+s(1304)]&&this[s(1210)+s(1304)](_0x33e0c9);else{let E=await y[s(1337)+"rs"](),p={frameType:E?.["frameType"],SeqID:he[s(1412)+"er"](this[s(1501)]++),LogID:he.fromNumber(this._options[s(983)+s(1491)]()),service:9e3,method:5,headers:E?.headers,payload:E?.[s(1932)]},k=e[s(1278)](S,p);this[s(1530)]&&this[s(1530)][s(722)+"te"]&&this[s(1530)][s(1940)](k)}if(f){let E=a[s(1955)][s(1932)];E&&y.setCursors(E)}}let Dg=async function(a,n){let s=t;this[s(730)]=!1,e[s(892)](clearTimeout,this[s(1976)+s(1100)+s(1374)]),n()},Og=async function(a,n){let s=t;if(!this._ws||e[s(477)](this[s(1530)][s(722)+"te"],this[s(1058)]))return e[s(1906)](n);let{pingInterval:l}=this._options;this[s(1e3)+"tManager"]?.["resetEnd"+s(1753)+s(1284)]();for(let m=0;e.DPvGM(m,this[s(697)+s(934)].length);m++){let y=this[s(697)+s(934)][m];if(e[s(1432)](this._ws[s(722)+"te"],this[s(1058)])&&y!==null)this._ws&&this[s(1530)][s(1940)](y),this[s(697)+s(934)][m]=null;else break}this[s(697)+s(934)]=this[s(697)+s(934)][s(1017)](m=>!!m),this[s(1049)+"gTimeoutId"]=e[s(1269)](setTimeout,()=>this._ping(),l),this[s(692)+s(1717)+"nt"](a),this._isBrowser&&this[s(1530)]&&(this._ws[s(1516)+"pe"]=this[s(1585)+"ype"]);let f=this._endpointManager?.["getCurre"+s(1105)+"nt"]();this._debug(s(1547)+f+s(1077)),n()},Lg=async function(a,n){let s=t;if(e.Osbck!==e[s(1476)]){let l=this[s(1e3)+s(1982)]?.[s(882)+s(1105)+"nt"]();this[s(1305)]("open "+l),e[s(550)](n)}else return e[s(1043)](_0x1ced8e,_0x5b27dd)?_0x1a213f.reject(new _0x50c241(s(684)+"alled mu"+s(1410)+s(1891)+s(1597))):(_0x489f75=_0x11a66f,e[s(1598)](_0x2623a3,_0x404ff8[s(1994)])?_0x4fbec8[s(1329)]():_0xea26bd[_0x12e34a][s(1975)](_0x112648)(_0x5b6fae,_0x3063bc[s(1975)](null,e[s(1537)](_0x590d5c,1))))};class Ng extends Ia{constructor(n){let s=t,l={utEhQ:function(E){return e[W(1920)](E)},sBreF:function(E,p){return E!=p},kvMeb:s(616),phnDu:function(E,p){return E==p},OaNfw:e[s(852)],zlpOY:function(E,p){return e[s(653)](E,p)},GHYDB:s(617),fRazQ:e[s(1256)],hwien:e[s(1200)],bEoTj:function(E,p,k){return e[s(913)](E,p,k)},VTAJp:function(E,p){return e[s(1950)](E,p)},SwRIQ:function(E,p){return e[s(1543)](E,p)},wyqWp:e[s(744)],sFPiU:function(E,p,k,O){return e[s(1815)](E,p,k,O)},JExle:e[s(1767)]};super(),this[s(572)+s(1727)+s(894)]=!0,this[s(490)+"er"]=cr,this._isNode=Yp,this._isMiniTT=Ln,this[s(752)+"X"]=ii,this[s(957)+"r"]=si,this[s(697)+s(934)]=[],this[s(1e3)+"tManager"]=null,this._readyClosed=!1,this[s(1585)+s(1170)]=e.DCrVO,this[s(1976)+s(1073)]=!1,this[s(1976)+"ionTimeo"+s(1374)]=null,this[s(1427)+s(1258)+s(1979)]=null,this[s(1049)+s(1869)+"Id"]=null,this._seqId=0,this[s(730)]=!1,this._url="",this[s(1138)+s(1702)]=null,this[s(1542)+s(1533)]=null,this[s(458)+s(1716)]=null,this[s(582)+"ls"]=s(1499),this[s(906)]=3,this[s(1604)+"NG"]=0,this.OPEN=1,this[s(529)]=2,this._onOpen=E=>{let p=s,k={KNrAJ:function(O,N,F){return e.EbnJV(O,N,F)},qPtRf:e[p(599)],ALYBz:e[p(682)]};if(e[p(1057)]!==e.qpztd){let O=k[p(1244)](_0x904988,k.qPtRf,{message:k.ALYBz});this[p(1953)+"econnect"]&&this[p(1953)+p(1896)](O)}else try{e[p(462)](bl,this,E,[Dg,Og,Lg])}catch(O){let N=e[p(1464)](lt,"error",{message:O[p(1955)],code:dn[p(758)+"OR"],error:O});this[p(692)+p(842)+p(958)](N)}},this._onMessage=async E=>{let p=s,k={fxcVK:function(F,U){return F(U)},IKTNo:function(F){return l[W(1159)](F)},fsRbn:function(F,U){return l[W(1968)](F,U)},rmXoM:l.kvMeb,GVyLC:function(F,U){return F instanceof U},iBgAP:p(921)+"ion/json",kfMLQ:function(F,U){return l[p(1790)](F,U)},eFtsk:l[p(473)]},{pingInterval:O,pingFrequency:N}=this._options;if((l[p(1110)]("hi",E.data)&&l[p(1110)]("always",N)||l[p(1650)]===N)&&(l[p(1110)](l.fRazQ,l[p(1965)])?(this["_clearPi"+p(1350)](),this[p(1205)](l.hwien,p(1406)),this["_pingPon"+p(1869)+"Id"]=l[p(530)](setTimeout,this[p(800)].bind(this),O)):(mLMIpF[p(654)](_0x19cc55,_0x33fdf8(_0x38dd5f[p(1019)])),mLMIpF[p(773)](_0x4af1bd))),!l[p(1960)]("hi",E[p(1109)]))try{if(l[p(1128)](l[p(482)],l[p(482)]))try{return mLMIpF[p(1627)](mLMIpF[p(726)],typeof _0x5606ce)&&(mLMIpF[p(1808)](_0x5a9bea,_0x3a9647)||_0x2a56be.buffer&&_0x22ac02[p(1964)]instanceof _0x25454d)||p(616)!=typeof _0x512814?"":(_0x396eba.parse(_0x4f6ec0),mLMIpF[p(833)])}catch{return mLMIpF[p(806)](mLMIpF[p(726)],typeof _0x32378f)?mLMIpF[p(960)]:""}else l.sFPiU(bl,this,E,[fg,lg,Pg,Cg,Rg,ug])}catch(F){let U=l.bEoTj(lt,l[p(1710)],{message:F[p(1955)],code:dn[p(743)+"ERROR"],error:F});this[p(692)+p(842)+"ent"](U)}},this[s(1900)]=E=>{let p=s,k=this[p(1e3)+p(1982)]?.[p(1883)+p(1014)+"es"](),O=this[p(1e3)+p(1982)]?.[p(882)+"ntEndpoint"]();if(k&&!E[p(1955)]){let N="connect "+O+(" fail, m"+p(853)+p(1956)+"ed");this[p(692)+p(842)+p(958)](l[p(530)](lt,l[p(1710)],{message:N,code:dn[p(1074)+"IES_ERROR"],error:E}));return}this[p(1530)]&&this._ws[p(722)+"te"]===this[p(1058)]&&this[p(1787)+p(647)](),this[p(692)+p(842)+p(958)](l.bEoTj(lt,p(1690),{message:E[p(1955)],code:dn[p(1873)+"RROR"],error:E}))},this[s(1293)]=async E=>{let p=s,k={kPWyC:function(N,F){return e[W(1126)](N,F)}};this[p(1056)+p(1725)](),this[p(510)+"ngTimer"](),this["_removeW"+p(1383)+"rs"](),this[p(1530)]=null,this[p(1976)+p(1073)]=!1;let O=this[p(1e3)+p(1982)]?.[p(1883)+p(1014)+"es"]();if(!O&&this[p(734)+p(566)]()&&!this[p(1749)+p(611)])if(e.bzICc===e[p(1736)]){let N=this[p(1e3)+p(1982)]?.[p(882)+"ntEndpoint"](),F=this[p(1257)]["reconnec"+p(1670)+"ptor"](E[p(1591)],E[p(729)]);this["_dispatc"+p(591)+p(958)](e.gRdhI(Et,e.tcvFp,{code:1006,reason:E[p(729)]||p(903)+"ng faile"+p(1342)+p(1096)+p(577)+p(1687)+N,willReconnect:F})),F&&this._connect();return}else return _0x5e17aa&&CcNHME[p(1158)](!0,_0x5e055d[p(1916)]);if(E[p(1591)]!==1e3&&this[p(1749)+"osed"]){this["_dispatc"+p(591)+p(958)](Et(p(1709),{code:1e3,reason:e[p(1666)]})),this[p(1e3)+p(1982)]?.[p(1349)+p(1753)+p(1284)](),this[p(458)+"sCounter"]?.[p(1572)+p(1354)]();return}if(E[p(1591)]!==1e3&&O)if(e.yWvZM(e[p(938)],e[p(817)]))_0x196fbd[p(791)+p(1890)]="",_0x43b14d[p(1580)](_0x400465);else{let N=this["_endpoin"+p(1982)]?.[p(882)+"ntEndpoint"](),F=E[p(729)];F||(F=await e[p(769)](ig,this[p(1911)])),F="connecti"+p(1637)+"d, "+F+(", hostna"+p(1426))+N+(p(1574)+p(967)+p(489)),this[p(692)+p(591)+p(958)](e.dbvjF(Et,p(1709),{code:E[p(1591)],reason:F}));let U=p(963)+N+(p(1555)+"ax retri"+p(1956)+"ed");this[p(692)+"hErrorEv"+p(958)](e[p(1172)](lt,e[p(1767)],{message:U,code:dn.MAX_RETRIES_ERROR})),this._endpointManager?.[p(1349)+p(1753)+p(1284)](),this["_pingLos"+p(1716)]?.[p(1572)+"nter"]();return}if(e.fEpcz(1e3,E[p(1591)])&&!E.reason){let N=this["_endpoin"+p(1982)]?.[p(882)+p(1105)+"nt"]();this[p(692)+"hCloseEv"+p(958)](e[p(1467)](Et,p(1709),{code:E[p(1591)],reason:p(903)+p(1637)+"d, unkno"+p(1096)+p(577)+p(1687)+N})),this[p(1e3)+"tManager"]?.[p(1349)+p(1753)+p(1284)](),this[p(458)+p(1716)]?.[p(1572)+p(1354)]();return}this[p(692)+p(591)+p(958)](E),this[p(1e3)+p(1982)]?.[p(1349)+p(1753)+p(1284)](),this["_pingLos"+p(1716)]?.[p(1572)+p(1354)]()},this[s(1034)]=null,this[s(1314)]=null,this[s(1453)+"e"]=null,this[s(788)]=null,this[s(1953)+s(1896)]=null,this[s(1210)+s(1304)]=null,this[s(1565)+"mediatel"+s(1498)+"ct"]=null,this[s(478)+"nLine"]=this[s(478)+s(1596)][s(1975)](this),this[s(478)+s(528)]=this[s(478)+s(528)][s(1975)](this),this[s(759)+"ageHide"]=this["_handleP"+s(687)].bind(this),this[s(759)+"ageShow"]=this[s(759)+"ageShow"][s(1975)](this),this[s(1257)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength: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(1939)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1677)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:m}=n,y=Array[s(1395)](f)?f:e[s(1850)](e[s(757)],typeof f)?[f]:[];if(!y||e[s(551)](0,y[s(1994)]))throw new Error(e.OwrPm);if(!e.NrmxQ(eg,m))throw new Error(e.UTbXq);Object.assign(this._options,n),this[s(1e3)+s(1982)]=new yl(y,this[s(1257)][s(1070)+"es"]),this[s(458)+"sCounter"]=new rg(this._options[s(1648)+s(480)]),this._options[s(1457)+s(1855)]&&(this[s(730)]=!0,this[s(1976)]()),this[s(1257)]["listenNe"+s(649)+"nged"]&&(this[s(1862)+"T"]||this._isMiniWX?this["_onPageN"+s(886)+"ange"]():this[s(490)+"er"]&&this[s(1177)+s(1625)+s(1169)]())}[t(478)+t(1596)](){let n=t;this[n(1257)][n(980)+n(829)+"nect"]||this[n(1749)+"osed"]||this[n(1447)+n(1896)]()}[t(478)+"ffLine"](){let n=t;if(e[n(1509)]!==e[n(1821)]){this[n(724)+n(1421)+"t"]();let s=Sa(e[n(599)],{message:e[n(1413)]});this[n(1565)+n(1147)+n(1498)+"ct"]&&this[n(1565)+n(1147)+n(1498)+"ct"](s)}else return _0x40dac9[_0x31b274]=_0x16a314,!0}["_initGlobalEvent"+t(1169)](){let n=t;this._isBrowser&&window[n(831)+n(1169)](e.bEzvk,this[n(478)+n(1596)]),this[n(490)+"er"]&&window[n(831)+n(1169)](e[n(843)],this[n(478)+n(528)]),this._isBrowser&&window[n(831)+n(1169)](n(868),this[n(759)+n(687)]),this[n(490)+"er"]&&window[n(831)+n(1169)](e.vIMSJ,this[n(759)+"ageShow"])}[t(839)+t(1625)+t(1169)](){let n=t;this[n(490)+"er"]&&window["removeEv"+n(488)+"ner"](e[n(1266)],this[n(478)+n(1596)]),this._isBrowser&&window[n(1561)+n(488)+"ner"](e[n(843)],this[n(478)+n(528)]),this[n(490)+"er"]&&window[n(1561)+n(488)+"ner"](n(868),this[n(759)+n(687)]),this[n(490)+"er"]&&window[n(1561)+"entListe"+n(1937)](n(1918),this[n(759)+n(678)])}[t(759)+t(687)](n){let s=t;!n[s(1224)+"d"]&&(this[s(490)+"er"]&&window[s(1561)+s(488)+s(1937)](e[s(1840)],this[s(759)+s(687)]),this[s(490)+"er"]&&window["removeEv"+s(488)+"ner"](e[s(1609)],this["_handleP"+s(678)]),this.close()),this[s(490)+"er"]&&window["removeEv"+s(488)+s(1937)](s(1632),this[s(478)+s(1596)]),this[s(490)+"er"]&&window[s(1561)+s(488)+s(1937)](e.pADai,this["_handleO"+s(528)])}[t(759)+t(678)](n){let s=t;n.persisted&&(this[s(734)+"orOnline"]()&&(!this._ws||this[s(1530)][s(722)+"te"]!==this[s(1058)]||e[s(1556)](this[s(1530)][s(722)+"te"],this[s(1604)+"NG"]))&&this[s(478)+"nLine"](),this._isBrowser&&window[s(831)+s(1169)](e.bEzvk,this[s(478)+"nLine"]),this[s(490)+"er"]&&window["addEvent"+s(1169)](e[s(843)],this[s(478)+"ffLine"]))}async[t(1724)+t(790)](n){let s=t,{fpID:l,deviceID:f,bddID:m,ttwID:y,accessKey:E,aID:p,customParams:k={},enableAutoAck:O,enableQoS:N,QoSLevel:F,env:U}=this._options,ie,Se,ye;this[s(490)+"er"]||this[s(752)+"X"]||this[s(1862)+"T"]?(ie=location&&e[s(1959)](e[s(1611)],location[s(1497)])?"wss://":s(1459),Se=n[s(1208)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ye=/^wss(.*:\/\/)/[s(1639)](n)?n:""+ie+Se):(ie=e[s(959)],Se=n[s(1208)](/(^http)((?:[s]*:\/\/))/,""),ye=/(^ws)((?:[s]*:\/\/))/[s(1639)](Se)?Se:""+ie+Se);let un=m?e[s(677)]:y?e[s(524)]:s(1867)+"d",nt=m||y||f;if(e.dcMkO(!nt,!un))throw new Error(s(1553)+s(1438)+s(1482)+s(862)+s(732));let ut=e[s(1628)](s(720),typeof k)?await k():k,ft=U?e[s(1754)](ng,U[s(1752)],U[s(1584)]):{},Da=Object.assign({device_platform:e.HrvjT,version_code:e[s(1526)],access_key:E,fpid:l,aid:p,[un]:nt,xsack:O?1:0,xaack:O?1:0,xsqos:N?1:0,qos_level:N?F:void 0,qos_sdk_version:2,...ft},ut),Mg=Object[s(884)](Da)[s(1762)]((Oa,La)=>Da[La]!==void 0?""+Oa+(Oa?"&":"?")+La+"="+Da[La]:Oa,"");return ye+s(1086)+Mg}async[t(1976)](){let n=t;if(!(this._connectLock||this[n(1749)+n(611)])){this[n(1976)+"Lock"]=!0;try{if(e[n(907)]===e[n(1153)])this[n(1067)+n(1310)]=0,this[n(2001)+n(1340)+n(1763)+"t"]=0;else{let s=this["_endpoin"+n(1982)]?.[n(1384)+"rentEndpointReac"+n(935)+n(784)](),{timeoutInterval:l}=this[n(1257)];if(s){let m=this[n(1e3)+n(1982)]?.[n(882)+n(1105)+"nt"](),y=this[n(1e3)+n(1982)]?.["replaceB"+n(1860)+n(1614)+"UpdateCo"+n(1947)](),E=this["_endpoin"+n(1982)]?.[n(882)+n(1105)+n(901)+"ount"]();if(y)if(e[n(1089)](e[n(973)],e.sTrpu)){let p=this[n(645)].getItem(this[n(1877)]),k=_0x40e999.parse(e[n(1228)](p,"{}"));return _0x1dc25e.keys(k)}else{let p=n(963)+m+(n(1111)+n(1574)+n(967)+n(575)+n(467)+"backup e"+n(1631))+y+" to retry",k=e.QFAee(lt,e[n(1767)],{message:p,code:dn.MAX_RETRIES_ERROR});this[n(1305)](p),this[n(692)+n(842)+"ent"](k),this._url=await this[n(1724)+n(790)](y),this[n(1305)](n(963)+y+" "+E+n(1889)),this["_removeW"+n(1383)+"rs"]()}else{let p="connect "+m+(n(1111)+n(1574)+"tries reached");this[n(1305)](p),this[n(692)+"hErrorEv"+n(958)](e[n(523)](lt,e.NyEXn,{message:p,code:dn[n(1074)+n(1461)+"R"]}));return}}else{let m=this[n(1e3)+n(1982)]?.[n(882)+n(1105)+n(2005)+n(1779)](),y=this[n(1e3)+n(1982)]?.[n(882)+n(1105)+"ntTriesC"+n(814)]();this[n(1911)]=await this[n(1724)+"eUrl"](m||""),this._debug(n(963)+m+" "+y+" times"),this[n(1475)+n(1383)+"rs"]()}if(this[n(730)])this[n(730)]=!1;else{let m=e.rkOGK(Sa,e[n(599)],{message:e[n(682)]});this[n(1953)+n(1896)]&&this[n(1953)+n(1896)](m)}let f=this["_endpoin"+n(1982)]?.[n(882)+"ntEndpoi"+n(901)+n(814)]()||0;e[n(470)](f,1)&&await this[n(1237)](e[n(902)](f,1)),this[n(1305)](n(903)+"ng url: "+this[n(1911)]+(n(624)+n(1001))+this[n(582)+"ls"]),this[n(1530)]=e[n(975)](Qp,{url:this._url,protocols:[this[n(582)+"ls"]],headers:this[n(1257)][n(1899)+n(1508)+"s"][n(950)+n(568)]},this[n(1257)].ws),(this[n(490)+"er"]||this._isWorker)&&this[n(1530)]&&(this[n(1530)][n(1516)+"pe"]=this[n(1585)+"ype"]),this[n(922)+"steners"](),this["_connectionTimeo"+n(1374)]=setTimeout(this[n(1512)+"ut"][n(1975)](this),l)}}catch(s){throw this["_connect"+n(1073)]=!1,s}}}_clearTimer(){let n=t;e[n(1942)](clearTimeout,this[n(1976)+n(1100)+"utId"]),this["_connect"+n(1100)+"utId"]=null}[t(510)+t(1350)](){let n=t,s={IcGYS:function(l,f){return e[W(1134)](l,f)},BkebT:function(l,f){return e[W(1458)](l,f)},aEtEd:function(l,f){return e[W(695)](l,f)},RQGms:function(l,f){return l&f},GZHDd:function(l,f){return e[W(1623)](l,f)}};if(e[n(931)](e[n(1446)],e.PwNWv)){let l=e[n(1024)](_0x232817,8192),f=e[n(1195)](l,1),m=null,y=l;return function(E){let p=n;if(E<1||HoSTpQ[p(1558)](E,f))return HoSTpQ.BkebT(_0x335699,E);HoSTpQ[p(1101)](y,E)>l&&(m=HoSTpQ[p(1731)](_0x40b419,l),y=0);let k=_0x154e6f[p(1326)](m,y,y+=E);return HoSTpQ.RQGms(7,y)&&(y=HoSTpQ[p(1101)](HoSTpQ.GZHDd(7,y),1)),k}}else e[n(786)](clearTimeout,this[n(1049)+n(1869)+"Id"]),clearTimeout(this[n(1427)+"ctTimeou"+n(1979)]),this[n(1049)+n(1869)+"Id"]=null,this[n(1427)+n(1258)+"tId"]=null}[t(1305)](...n){let s=t,l={fIyTq:function(f,m,y){return e[W(972)](f,m,y)},XwcRA:function(f,m){return e[W(789)](f,m)}};e[s(1826)](s(614),e.nmBas)?this[s(1257)][s(933)]&&console.log.apply(console,[e.PdxBx,...n]):(_0x500c1b(_0x223623,96),ZKVfou[s(924)](_0x255b81,_0x594a15,ZKVfou[s(1985)](_0x34dbf2,_0x3c2d70)))}["_getInte"+t(1496)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:m}=this._options,y=l*Math.pow(m,e[s(1285)](n,1));return y>f?f:y}[t(800)](){let n=t;if(this[n(1530)]&&e[n(925)](this[n(1530)][n(722)+"te"],this[n(1604)+"NG"])){this[n(510)+n(1350)](),this["_pingPon"+n(1869)+"Id"]=e[n(1882)](setTimeout,this[n(800)][n(1975)](this),this[n(1257)][n(830)+n(1233)]);return}if(!this[n(1530)]||e[n(1750)](this._ws.readyState,this.OPEN))return void this["_handleR"+n(1896)]();this[n(1530)]&&this._ws.send("hi"),this[n(1427)+n(1258)+n(1979)]=e.KlunL(setTimeout,this["_handleR"+n(1896)+n(1721)][n(1975)](this),this._options[n(1219)+n(811)+"val"])}_handleReconnectTimeout(){let n=t;e[n(1864)](n(1831),e[n(609)])?(this[n(1585)+"ype"]=_0x33b6b9,this._ws&&(this[n(1530)][n(1516)+"pe"]=_0x40ddbd)):(this["_pingLos"+n(1716)]?.addCount(),this[n(1205)]("ping_once_timeout",n(1042)),this[n(458)+"sCounter"]?.[n(1883)+n(1620)+"nt"]()?this[n(1447)+n(1896)]():this[n(800)]())}[t(734)+"orOnline"](){let n=t;return this._isMiniTT||this[n(752)+"X"]?this[n(572)+n(1727)+n(894)]:(this._isBrowser||this[n(957)+"r"])&&this[n(1257)]["listenNe"+n(649)+n(651)]?navigator.onLine:!0}[t(1447)+t(1896)](){let n=t;!this[n(734)+"orOnline"]()||this._readyClosed||(this[n(1e3)+n(1982)]?.[n(1349)+n(1753)+n(1284)](),this[n(458)+n(1716)]?.[n(1572)+"nter"](),this[n(1530)]?this["_disconn"+n(647)](1001,"going aw"+n(1407)+n(1254)+"ting ser"+n(1904),!0):this[n(1976)]())}[t(897)+"etWorkCh"+t(1641)](){let n=t,s={PbbsK:function(l,f,m){return e[W(778)](l,f,m)},AELJN:e[n(1767)],LiVue:function(l,f){return e.mCQDx(l,f)},HJMOi:e.xJKQO,reSxk:e[n(1294)]};this[n(1862)+"T"]?tt["onNetwor"+n(992)+n(1733)](({isConnected:l})=>{let f=n;this[f(572)+f(1727)+"line"]=l,l?this[f(478)+f(1596)]():this[f(478)+"ffLine"]()}):this[n(752)+"X"]&&wx[n(565)+n(992)+n(1733)](({isConnected:l})=>{let f=n,m={gRTCM:function(y,E,p){return s[W(858)](y,E,p)},AtsNf:s[f(994)]};if(s[f(1528)](s[f(1394)],s[f(1548)])){let y=this[f(1e3)+"tManager"]?.[f(1883)+f(1014)+"es"](),E=this[f(1e3)+"tManager"]?.[f(882)+"ntEndpoint"]();if(y&&!_0x58db51[f(1955)]){let p="connect "+E+(f(1555)+"ax retri"+f(1956)+"ed");this[f(692)+f(842)+f(958)](LldDol[f(1300)](_0x5e5008,LldDol.AtsNf,{message:p,code:_0x7aded8[f(1074)+f(1461)+"R"],error:_0x3d0533}));return}this._ws&&this._ws.readyState===this.OPEN&&this[f(1787)+f(647)](),this[f(692)+"hErrorEv"+f(958)](_0x954e54(LldDol[f(1103)],{message:_0x1fd621[f(1955)],code:_0x2b1317[f(1873)+f(1474)],error:_0x3b8092}))}else this[f(572)+f(1727)+f(894)]=l,l?this[f(478)+f(1596)]():this[f(478)+f(528)]()})}[t(1237)](n){return new Promise(s=>{let l=W;e.IABKc(setTimeout,s,this["_getInte"+l(1496)+"e"](n))})}[t(1787)+"ect"](n=1e3,s="",l=!1){let f=t;this[f(1530)]&&this[f(724)+"WebSocket"](n,s,l)}[t(1512)+"ut"](){let n=t,s=this._endpointManager?.[n(882)+n(1105)+"nt"]();this[n(1305)](n(963)+s+n(1111)),this[n(1787)+n(647)](1001,n(948)+n(1929)+n(1344)+"g",!0)}[t(1583)](n){let s=t,l=e.toveu(qt,n);this[s(1530)]&&e[s(1026)](this[s(1530)][s(722)+"te"],this[s(1058)])&&(this[s(1530)]&&this._ws[s(1940)](l),this[s(1305)](e.KMcnz,n))}["_removeW"+t(1383)+"rs"](){let n=t,s=(n(1659)+"4")[n(479)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[n(1530)])return;continue;case"1":this[n(1530)][n(1561)+n(488)+n(1937)](e[n(1874)],this._onClose);continue;case"2":this[n(1530)][n(1561)+n(488)+n(1937)](e[n(804)],this[n(555)]);continue;case"3":this[n(1530)][n(1561)+n(488)+"ner"](n(1955),this[n(640)+"ge"]);continue;case"4":this[n(1530)]["removeEv"+n(488)+"ner"]("error",this[n(1900)]);continue}break}}["_addWsLi"+t(1729)](){let n=t,s=e.BJCec[n(479)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(1530)][n(831)+"Listener"](n(1801),this[n(555)]);continue;case"1":this[n(1530)][n(831)+n(1169)](e[n(1874)],this._onClose);continue;case"2":this[n(1530)][n(831)+n(1169)](e[n(1660)],this._onMessage);continue;case"3":if(!this[n(1530)])return;continue;case"4":this._ws["addEvent"+n(1169)](e.NyEXn,this._onError);continue}break}}[t(1616)+t(1015)](n=1e3,s=""){let l=t,f={xfjAd:function(m,y){return e.DxpUy(m,y)},JcKjG:function(m,y){return m>y},WrOvc:function(m,y){return e[W(1579)](m,y)},rdwGM:function(m,y){return m>y},RIbOh:function(m,y){return e[W(1993)](m,y)},VRtAp:function(m,y){return e[W(1029)](m,y)},GysiT:function(m,y){return e[W(1414)](m,y)},VBJYT:function(m,y){return e.tttuv(m,y)},Mkzun:function(m,y){return e[W(1892)](m,y)}};if(l(1857)===e[l(509)]){if(gEUIgz[l(522)](_0x2cde51,1)||gEUIgz[l(1712)](_0x1d2dc5,_0x29f1bc))return gEUIgz[l(909)](_0x3a1fc9,_0x5a53c5);gEUIgz[l(1818)](gEUIgz.RIbOh(_0x4e00d9,_0x48b410),_0x3cb8f3)&&(_0x710609=gEUIgz.VRtAp(_0x4d3f6e,_0x343d16),_0x506b34=0);let m=_0x3ccb8b[l(1326)](_0xa2c078,_0x1f861e,_0x3fae91+=_0x1719b2);return gEUIgz[l(531)](7,_0xf2a118)&&(_0x2c5af9=gEUIgz[l(946)](gEUIgz[l(875)](7,_0x41bdf7),1)),m}else try{this[l(1530)]&&this[l(1530)][l(1709)](n,s)}catch{}}[t(724)+t(1421)+"t"](n=1e3,s="",l=!1){let f=t;if(this[f(510)+f(1350)](),this[f(1056)+f(1725)](),this["_removeW"+f(1383)+"rs"](),this[f(1616)+f(1015)](1e3,s),this["_connect"+f(1073)]=!1,l&&this[f(734)+f(566)]()&&!this[f(1749)+f(611)]){if(e[f(477)](e.SzxSy,e[f(1972)]))return _0x40f5c6[f(768)+"oreNames"]||_0x2c11aa[f(798)](_0x3962f5);if(this[f(1e3)+f(1982)]?.[f(1883)+f(1014)+"es"]()){let y=this[f(1e3)+"tManager"]?.[f(882)+f(1105)+"nt"]();this[f(692)+f(591)+f(958)](e.czpAU(Et,e[f(1874)],{code:1006,reason:f(963)+y+(" timeout"+f(1574)+f(967)+f(489)),wasClean:!0}))}else{let y=this[f(1257)][f(1254)+f(1670)+f(1759)](n,s);this[f(692)+"hCloseEvent"](e[f(1884)](Et,"close",{code:n,reason:s,wasClean:!0,willReconnect:y})),y&&this[f(1976)]()}return}this[f(734)+f(566)]()||this[f(1749)+f(611)]?this[f(692)+f(591)+f(958)](e[f(1436)](Et,f(1709),{code:n,reason:e[f(1666)]})):this["_dispatc"+f(591)+"ent"](e[f(908)](Et,e[f(1874)],{code:1006,reason:f(1663)+f(1871)+"ork offline"})),this._ws=null,this[f(1e3)+"tManager"]?.["resetEnd"+f(1753)+f(1284)](),this[f(458)+f(1716)]?.[f(1572)+"nter"]()}[t(692)+t(1717)+"nt"](n){let s=t;this[s(1205)](e[s(804)],n),this[s(788)]&&this[s(788)](n)}["_dispatc"+t(1389)+t(1812)](n){let s=t;this[s(1205)](e[s(1660)],n),this.onmessage&&this[s(1453)+"e"](n)}[t(692)+t(635)+t(1357)](n){let s=t;this[s(1205)](e.JUwGJ,n),this[s(1210)+"eAck"]&&this[s(1210)+s(1304)](n)}["_dispatc"+t(842)+t(958)](n){let s=t,l={cVhqe:function(f,m){return e[W(1401)](f,m)},WVfDY:function(f,m){return f<m},JmGiv:function(f,m){return f>>>m}};if(e[s(795)](e[s(874)],e[s(874)]))this[s(1205)]("error",n),this[s(1314)]&&this[s(1314)](n);else{let f=0,m=_0x9c8b44,y=TjTwLR.cVhqe(_0x488590,4);for(;TjTwLR.WVfDY(m,y);){let{value:E,offset:p}=_0x5cdc03(_0x420bbe,m);m=p,f=TjTwLR[s(1321)](f<<8,0),f+=E}return{value:f,offset:y}}}["_dispatchCloseEv"+t(958)](n){let s=t;this[s(1205)](s(1709),n),this[s(1034)]&&this[s(1034)](n)}get[t(1516)+"pe"](){let n=t;if(e[n(1556)](e.hlarG,"sFQeA"))_0x18e1ec[n(1580)](_0x485716);else return this[n(1530)]?this[n(1530)][n(1516)+"pe"]:this[n(1585)+n(1170)]}set binaryType(n){let s=t;this[s(1585)+s(1170)]=n,this._ws&&(this[s(1530)][s(1516)+"pe"]=n)}get[t(1834)+"nt"](){let n=t;return this[n(1e3)+n(1982)]?.[n(882)+"ntEndpoi"+n(901)+n(814)]()||0}get[t(1622)+"Amount"](){let n=t,s=this[n(697)+n(934)][n(1762)]((l,f)=>(l+=f&&f[n(638)+"th"]||0,l),0);return e[n(1064)](s,this[n(1530)]?this[n(1530)].bufferedAmount:0)}get[t(636)+"ns"](){let n=t;return this[n(1530)]?this[n(1530)][n(636)+"ns"]:""}get[t(1497)](){let n=t;if(e.WzGGR(n(766),e.BpXau))return this[n(1530)]?this[n(1530)].protocol:"";e[n(1127)](_0x56713d,65536)?_0x5cbf2a[_0x955292++]=e[n(1166)](e.NgIlg(_0x51ba01>>12,15),224):(_0xfebdcd[_0x120442++]=e[n(1225)](e[n(847)](_0x56e5fe,18),7)|240,_0x2013c5[_0x579627++]=e[n(1166)](e[n(912)](e[n(917)](_0x53843c,12),63),128)),_0x33ecbc[_0x13c770++]=e[n(1701)](e[n(685)](e.FWGez(_0x2c9568,6),63),128)}get[t(722)+"te"](){let n=t;return e[n(1221)](e[n(1858)],e[n(1008)])?this[n(1530)]?this[n(1530)][n(722)+"te"]:this[n(1257)][n(1457)+n(1855)]?this[n(1604)+"NG"]:this[n(906)]:(_0x4b62ce+=_0x132a33&&_0x549c02[n(638)+"th"]||0,_0x40f3a4)}get[t(1967)](){let n=t;return this[n(1530)]?this[n(1530)][n(1967)]:this._url}[t(1709)](n=1e3,s){let l=t;if(this[l(1749)+l(611)]=!0,this[l(1056)+l(1725)](),this[l(510)+"ngTimer"](),this["_dropGlobalEvent"+l(1169)](),this[l(1138)+l(1702)]?.[l(1481)](),!this._ws)return void this[l(1305)](e.qJApx);if(e[l(587)](this._ws[l(722)+"te"],this[l(906)])||e[l(1026)](this[l(1530)][l(722)+"te"],this[l(529)]))return void this[l(1305)](e.yAarF);this[l(724)+l(1421)+"t"](n,s)}async[t(1940)](n,s){let l=t;if(e[l(1146)](null,n))throw new Error(e[l(536)]);e[l(1382)](l(1249),typeof n)&&(n=JSON[l(937)+"y"](n)),e[l(1654)](e[l(757)],typeof n)&&!e[l(927)](n,ArrayBuffer)&&!(n[l(1964)]&&e.cYVvN(n.buffer,ArrayBuffer))&&(n=JSON[l(937)+"y"](n));let f=await Sl(n),m=e.bbcVV(tg,n),{method:y=0,service:E=this._options.service,logID:p=this[l(1257)][l(983)+l(1491)](),headers:k=this._options[l(1338)],payloadEncoding:O=this[l(1257)][l(1380)+l(1099)],payloadType:N=this._options[l(1810)+l(1170)],logIDNew:F=this[l(1257)]["logIDNew"+l(991)][l(1886)+l(1276)+l(1990)+"ew"]?e[l(787)](i,this._options["logIDNew"+l(991)].userIp):""}=s||{};if(!E)throw new Error(e[l(828)]);let U={SeqID:he[l(1412)+"er"](this._seqId++),LogID:he.fromNumber(p),service:E,method:y,headers:k,payloadEncoding:e[l(927)](O,Object)?O[l(1456)]?O.encoding:"":O,payloadType:e[l(639)](N,Object)?N[l(1636)]?N.type:m:N||m,payload:f,LogIDNew:F},ie=e[l(1722)](qt,U);if(this[l(1530)]&&e[l(672)](this[l(1530)][l(722)+"te"],this[l(1058)]))if(e.svYXi(e.SVwzn,e[l(1322)])){let Se=_0x54ccc1.low>>>0,ye=e.DCkSe(e[l(656)](_0xb691d0[l(1060)],28)|e[l(797)](_0x59a9b0[l(1176)],4),0),un=e[l(694)](_0x28d8f6.high,24),nt=un===0?e[l(653)](0,ye)?Se<16384?e[l(1152)](Se,128)?1:2:e.JVZLT(Se,2097152)?3:4:e.zCNpn(ye,16384)?e[l(2e3)](ye,128)?5:6:ye<2097152?7:8:e[l(738)](un,128)?9:10,ut=e.Jacik(_0x20364a,_0x8f21c8,nt),ft=_0x14dcca[l(1802)];switch(nt){case 10:ft[e[l(518)](ut,9)]=e[l(464)](e.wXpcQ(un,7),1);case 9:ft[e[l(1323)](ut,8)]=e[l(1493)](9,nt)?128|un:127&un;case 8:ft[e[l(541)](ut,7)]=nt!==8?e[l(1166)](e.DzYiy(ye,21),128):e[l(1144)](e.NRyPA(ye,21),127);case 7:ft[e[l(1261)](ut,6)]=e[l(497)](7,nt)?e[l(1653)](e[l(1970)](ye,14),128):e[l(776)](ye>>>14,127);case 6:ft[e[l(1212)](ut,5)]=e.kVled(6,nt)?e.SNekn(ye,7)|128:e.OOTbh(ye,7)&127;case 5:ft[e[l(1168)](ut,4)]=e.cvWca(5,nt)?e.gXnFQ(128,ye):127&ye;case 4:ft[e[l(898)](ut,3)]=nt!==4?e[l(571)](e[l(1320)](Se,21),128):e[l(634)](e.dVLbG(Se,21),127);case 3:ft[e[l(1704)](ut,2)]=e[l(477)](3,nt)?Se>>>14|128:e[l(755)](Se,14)&127;case 2:ft[e[l(859)](ut,1)]=e[l(1534)](2,nt)?Se>>>7|128:e[l(1551)](Se>>>7,127);case 1:ft[ut]=e.JXryt(1,nt)?e[l(1720)](128,Se):e.vqixE(127,Se)}}else this[l(1530)]&&this[l(1530)][l(1940)](ie),this[l(1305)](e[l(504)],U);else e[l(2e3)](this[l(697)+"Queue"][l(1994)],this._options[l(1586)+"geQueueLength"])?(this[l(697)+"Queue"][l(468)](ie),this[l(1305)](e[l(1184)],U)):(this[l(697)+l(934)][l(899)](),this._messageQueue[l(468)](ie));return{seqID:this[l(1501)],logID:p,logIDNew:F}}async[t(1254)+"t"](n){let s=t,{url:l}=e[s(1024)](n,{}),f=Array[s(1395)](l)?l:e.ktWeH==typeof l?[l]:[];if(n&&Object[s(1397)](this[s(1257)],n),f&&f[s(1994)]?this[s(1e3)+s(1982)]=new yl(f,this[s(1257)][s(1070)+"es"]):this["_endpoin"+s(1982)]?.["resetEnd"+s(1753)+"fig"](),this[s(458)+s(1716)]?.[s(1572)+s(1354)](this._options[s(1648)+s(480)]),this[s(1749)+s(611)]=!1,this[s(1530)]&&e[s(976)](this[s(1530)][s(722)+"te"],this[s(906)]))this["_disconn"+s(647)](1e3,e[s(1259)],!0);else{if(e[s(1107)]===e[s(954)])return;this._isInit=!0,this[s(1976)]()}}async[t(1817)](){let n=t;!this[n(1976)+n(1073)]&&(this[n(1e3)+n(1982)]?.[n(1349)+"pointCon"+n(1284)](),this["_pingLos"+n(1716)]?.[n(1572)+n(1354)](),this[n(1749)+n(611)]=!1,this[n(730)]=!0,this[n(1976)]())}["addEvent"+t(1169)](n,s){let l=t;if(l(987)===e.pUZPI)this.on(n,s);else try{this[l(645)]?.[l(1709)](),this[l(645)]=void 0}catch(f){_0x119de5.log(f)}}[t(1773)+t(1812)](n){let s=t;if(e.PcVLs(e[s(699)],e.unfsV))this[s(1530)]&&this[s(1530)][s(1709)](_0x3b485c,_0x3f0389);else{let{type:l}=n;this[s(1205)](l,n)}}[t(1561)+t(488)+t(1937)](n,s){this[t(1492)](n,s)}[t(1828)](){let n=t,s={ETfhH:e[n(1200)],qgmKK:e[n(735)]};return new Promise((l,f)=>{let m=n,y={DoUCu:function(k,O){return k(O)},xTgfw:e[m(1200)],txfHt:m(650)+m(923)+"t"};this[m(510)+"ngTimer"](),this._pingPongTimeoutId=e[m(563)](setTimeout,this[m(800)].bind(this),this[m(1257)][m(830)+m(1233)]);let E=()=>{let k=m;y[k(1328)](l,k(1406)),this[k(1492)](y.xTgfw,E),this[k(1492)](y[k(1347)],p)},p=()=>{let k=m;f(k(1042)),this[k(1492)](s[k(1478)],E),this[k(1492)](s[k(1161)],p)};this.on(e[m(1200)],E),this.on(e[m(735)],p),this[m(800)]()})}}})(),ze[B(466)+B(1605)]=Oe[B(466)+"oseEvent"],ze[B(1770)+B(1378)]=Oe[B(1770)+B(1378)],ze[B(878)+"e"]=Oe.ErrorCode,ze[B(1812)]=Oe.Event,ze[B(1229)]=Oe[B(1229)],ze[B(1517)+B(1792)+B(1490)]=Oe["FrontierMessageE"+B(1490)],ze[B(1792)+"vent"]=Oe[B(1792)+"vent"],ze[B(1203)+"t"]=Oe.OpenEvent,ze[B(985)+"tEvent"]=Oe[B(985)+B(1202)],ze[B(1949)+B(1605)]=Oe[B(1949)+"oseEvent"],ze[B(704)+B(1378)]=Oe[B(704)+"rorEvent"],ze[B(1230)+B(1044)+"nt"]=Oe["createMe"+B(1044)+"nt"],ze["createOp"+B(873)]=Oe[B(1463)+B(873)],ze[B(1279)+"connectE"+B(1490)]=Oe["createRe"+B(1778)+B(1490)],ze[B(824)+B(1503)]=Oe[B(824)+"rame"],ze[B(891)+B(748)]=Oe[B(891)+"ame"];for(ta in Oe)["CustomCl"+B(1605),B(1770)+"rorEvent","ErrorCode","Event",B(1229),B(1517)+B(1792)+B(1490),B(1792)+"vent",B(1203)+"t",B(985)+B(1202),"createCl"+B(1605),B(704)+B(1378),B(1230)+B(1044)+"nt",B(1463)+"enEvent",B(1279)+B(1778)+"vent",B(824)+B(1503),"encodeFr"+B(748)][B(554)](ta)===-1&&(ze[ta]=Oe[ta]);var ta;Object["definePr"+B(1866)](ze,"__esModule",{value:!0})});import{existsSync as $S,openSync as VS}from"node:fs";import{mkdir as JS}from"node:fs/promises";import{dirname as ZS}from"node:path";import{fileURLToPath as YS}from"node:url";function QS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Yd(t=Z()){return $S(t.libEntry)?t.libEntry:YS(new URL("../index.ts",import.meta.url))}async function dp(t={}){let e=t.paths??Z(),r=t.entryOverride??Yd(e),i=QS(e,process.env.COZE_BRIDGE_LOG_MODE);await JS(ZS(i),{recursive:!0});let o=VS(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,[fs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return XS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var XS,fs,fa=rt(()=>{"use strict";Qt();te();Ce();XS=q("spawn-daemon"),fs="COZE_BRIDGE_DAEMON"});import{spawn as J2}from"node:child_process";import{mkdir as Z2,unlink as Y2,writeFile as X2}from"node:fs/promises";import{dirname as Q2,join as eI}from"node:path";function ti(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function tI(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${ti(r)}</key>
21
+ <string>${ti(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function n2(t,e){return new Promise((r,i)=>{let o=J1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Yr,fs,ga,sl,Rp=Qe(()=>{"use strict";ee();Yr=G("supervisor.launchd"),fs="ai.coze.bridge",ga=n2,sl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function nI(t,e){return new Promise((r,i)=>{let o=J2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ei,ps,wa,al,Cp=rt(()=>{"use strict";te();ei=q("supervisor.launchd"),ps="ai.coze.bridge",wa=nI,al={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
29
29
  <dict>
30
30
  <key>Label</key>
31
- <string>${fs}</string>
31
+ <string>${ps}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Xr(t.nodeBin)}</string>
35
- <string>${Xr(t.entry)}</string>
34
+ <string>${ti(t.nodeBin)}</string>
35
+ <string>${ti(t.entry)}</string>
36
36
  <string>--daemon</string>
37
37
  </array>
38
38
  <key>RunAtLoad</key>
@@ -42,13 +42,13 @@ ${e}
42
42
  <key>ThrottleInterval</key>
43
43
  <integer>10</integer>
44
44
  <key>StandardOutPath</key>
45
- <string>${Xr(t.logFile)}</string>
45
+ <string>${ti(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Xr(t.logFile)}</string>${t2(t.env)}
47
+ <string>${ti(t.logFile)}</string>${tI(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return e2(t.homeDir,"Library","LaunchAgents",`${fs}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await Z1(Q1(i),{recursive:!0}),await X1(i,this.renderConfig(t),"utf8"),Yr.info("plist written",{plistPath:i,activate:r}),!r)return;await ga("launchctl",["unload","-w",i]).catch(c=>Yr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ga("launchctl",["load","-w",i]),Yr.info("launchd job loaded",{label:fs});let o=process.getuid?.()??0;await ga("launchctl",["kickstart","-k",`gui/${o}/${fs}`]),Yr.info("launchd job kickstarted",{label:fs,uid:o})},async uninstall(t){let e=this.configPath(t);await ga("launchctl",["unload","-w",e]).catch(r=>Yr.warn("launchctl unload failed (ignored)",{err:String(r)})),await Y1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Yr.info("launchd job removed",{plistPath:e})}}});import{spawn as r2}from"node:child_process";import{mkdir as i2,unlink as s2,writeFile as o2}from"node:fs/promises";import{dirname as a2,join as Pp}from"node:path";function wa(t,e){return t.isRoot?e:["--user",...e]}function d2(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function _a(t,e){return new Promise((r,i)=>{let o=r2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ma,Qr,c2,ol,Dp=Qe(()=>{"use strict";ee();ma=G("supervisor.systemd"),Qr="coze-bridge.service",c2="/etc/systemd/system";ol={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return eI(t.homeDir,"Library","LaunchAgents",`${ps}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await Z2(Q2(i),{recursive:!0}),await X2(i,this.renderConfig(t),"utf8"),ei.info("plist written",{plistPath:i,activate:r}),!r)return;await wa("launchctl",["unload","-w",i]).catch(c=>ei.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await wa("launchctl",["load","-w",i]),ei.info("launchd job loaded",{label:ps});let o=process.getuid?.()??0;await wa("launchctl",["kickstart","-k",`gui/${o}/${ps}`]),ei.info("launchd job kickstarted",{label:ps,uid:o})},async uninstall(t){let e=this.configPath(t);await wa("launchctl",["unload","-w",e]).catch(r=>ei.warn("launchctl unload failed (ignored)",{err:String(r)})),await Y2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),ei.info("launchd job removed",{plistPath:e})}}});import{spawn as rI}from"node:child_process";import{mkdir as iI,unlink as sI,writeFile as oI}from"node:fs/promises";import{dirname as aI,join as Dp}from"node:path";function ya(t,e){return t.isRoot?e:["--user",...e]}function dI(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function ba(t,e){return new Promise((r,i)=>{let o=rI(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 _a,ni,cI,cl,Op=rt(()=>{"use strict";te();_a=q("supervisor.systemd"),ni="coze-bridge.service",cI="/etc/systemd/system";cl={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
- ${d2(t.env)}
62
+ ${dI(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Pp(c2,Qr):Pp(t.homeDir,".config","systemd","user",Qr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await i2(a2(i),{recursive:!0}),await o2(i,this.renderConfig(t),"utf8"),ma.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await _a("systemctl",wa(t,["daemon-reload"])),await _a("systemctl",wa(t,r?["enable","--now",Qr]:["enable",Qr])),ma.info("systemd unit enabled",{unitName:Qr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await _a("systemctl",wa(t,["disable","--now",Qr])).catch(r=>ma.warn("systemctl disable failed (ignored)",{err:String(r)})),await s2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await _a("systemctl",wa(t,["daemon-reload"])).catch(()=>{}),ma.info("systemd unit removed",{unitPath:e})}}});import{spawn as l2}from"node:child_process";import{join as u2}from"node:path";function Cp(t,e){return new Promise((r,i)=>{let o=l2(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var al,ya,cl,Op=Qe(()=>{"use strict";ee();al=G("supervisor.taskscheduler"),ya="CozeBridge",cl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Dp(cI,ni):Dp(t.homeDir,".config","systemd","user",ni)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await iI(aI(i),{recursive:!0}),await oI(i,this.renderConfig(t),"utf8"),_a.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await ba("systemctl",ya(t,["daemon-reload"])),await ba("systemctl",ya(t,r?["enable","--now",ni]:["enable",ni])),_a.info("systemd unit enabled",{unitName:ni,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await ba("systemctl",ya(t,["disable","--now",ni])).catch(r=>_a.warn("systemctl disable failed (ignored)",{err:String(r)})),await sI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ba("systemctl",ya(t,["daemon-reload"])).catch(()=>{}),_a.info("systemd unit removed",{unitPath:e})}}});import{spawn as lI}from"node:child_process";import{join as uI}from"node:path";function Lp(t,e){return new Promise((r,i)=>{let o=lI(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 dl,Ea,ll,Np=rt(()=>{"use strict";te();dl=q("supervisor.taskscheduler"),Ea="CozeBridge",ll={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,55 +86,55 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return u2(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 Cp("schtasks",["/Create","/SC","ONLOGON","/TN",ya,"/TR",r,"/RU",t.userName,"/F"]),al.info("task scheduler entry created",{task:ya,logFile:t.logFile})},async uninstall(t){await Cp("schtasks",["/Delete","/TN",ya,"/F"]).catch(e=>al.warn("schtasks /Delete failed (ignored)",{err:String(e)})),al.info("task scheduler entry removed",{task:ya})}}});var Lp={};La(Lp,{buildContext:()=>m2,getSupervisor:()=>x2,launchdSupervisor:()=>sl,systemdSupervisor:()=>ol,taskSchedulerSupervisor:()=>cl});import{homedir as f2,userInfo as h2}from"node:os";function x2(t=process.platform){switch(t){case"darwin":return sl;case"linux":return ol;case"win32":return cl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function g2(){let t={};for(let e of p2){let r=process.env[e];r&&(t[e]=r)}return t}function m2(){let t=J();return{nodeBin:process.execPath,entry:Jd(t),logFile:t.logFile,homeDir:f2(),userName:h2().username,isRoot:process.getuid?.()===0,env:g2()}}var p2,Np=Qe(()=>{"use strict";Re();la();Rp();Dp();Op();p2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ee();dn();var Fl=G("acp-installer-warmup"),dm=["claude-code","codex"];async function zl(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(dm.map(async o=>{let c=await e(o);Fl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Fl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}qt();ee();import{readdir as Im}from"node:fs/promises";import{mkdir as jl,readFile as vm,writeFile as ql}from"node:fs/promises";import{join as Ga}from"node:path";var Sm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function hr(t,e,r){await jl(t,{recursive:!0});let i=Sm[e],o=Ga(t,i);return await ql(o,r??"","utf8"),o}async function Ha(t,e,r){let i=Ga(t,".claude");await jl(i,{recursive:!0});let o=Ga(i,"settings.local.json"),c={};try{let u=await vm(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}catch{}let l=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=r)}return c.permissions=l,await ql(o,JSON.stringify(c,null,2),"utf8"),o}var Ze=G("agent-detail-sync"),Am=6e4,km=5*6e4,Ss=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Im(r)}catch(o){Ze.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Ze.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await ve(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Ze.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){Ze.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),Ze.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){Ze.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Ze.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await ve(e,this.opts.paths);if(!i){Ze.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){Ze.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,km):Am;this.retryQueue.set(e,{dueAt:Date.now()+g,currentDelay:g});return}if(o.agentId&&o.agentId!==e){Ze.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,l=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,l=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Ze.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Ze.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Ze.debug("detail sync: no diff",{agentId:e});return}await Fe(i,this.opts.paths),Ze.info("detail sync: config updated",{agentId:e,identityChanged:l,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Ze.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await hr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var fd=Ht(vu(),1);import{createHash as xy}from"node:crypto";import{lstat as sd,mkdir as od,readFile as yo,readdir as x0,rm as ad,stat as p0,writeFile as cd}from"node:fs/promises";import{homedir as py}from"node:os";import{dirname as gy,join as me,normalize as my,relative as ud,resolve as dd,sep as g0}from"node:path";import{Readable as m0}from"node:stream";import{pipeline as w0}from"node:stream/promises";import Jm from"events";import et from"fs";import{EventEmitter as Gc}from"node:events";import sf from"node:stream";import{StringDecoder as Zm}from"node:string_decoder";import cf from"node:path";import Ir from"node:fs";import{dirname as dw,parse as lw}from"path";import{EventEmitter as ww}from"events";import Ec from"assert";import{Buffer as jn}from"buffer";import*as Tu from"zlib";import _w from"zlib";import{posix as wr}from"node:path";import{basename as Kw}from"node:path";import no from"fs";import Pt from"fs";import Nu from"path";import{win32 as i_}from"node:path";import Hu from"path";import vf from"node:fs";import b_ from"node:assert";import{randomBytes as Sf}from"node:crypto";import ie from"node:fs";import Ne from"node:path";import If from"fs";import fo from"node:fs";import ki from"node:path";import st from"node:fs";import T_ from"node:fs/promises";import so from"node:path";import{join as Mf}from"node:path";import it from"node:fs";import zf from"node:path";var $m=Object.defineProperty,Vm=(t,e)=>{for(var r in e)$m(t,r,{get:e[r],enumerable:!0})},Su=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ym=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof sf||Xm(t)||Qm(t)),Xm=t=>!!t&&typeof t=="object"&&t instanceof Gc&&typeof t.pipe=="function"&&t.pipe!==sf.Writable.prototype.pipe,Qm=t=>!!t&&typeof t=="object"&&t instanceof Gc&&typeof t.write=="function"&&typeof t.end=="function",Wt=Symbol("EOF"),Kt=Symbol("maybeEmitEnd"),un=Symbol("emittedEnd"),Rs=Symbol("emittingEnd"),li=Symbol("emittedError"),Ps=Symbol("closed"),Iu=Symbol("read"),Ds=Symbol("flush"),Au=Symbol("flushChunk"),_t=Symbol("encoding"),mr=Symbol("decoder"),ze=Symbol("flowing"),ui=Symbol("paused"),Er=Symbol("resume"),Ue=Symbol("buffer"),Ye=Symbol("pipes"),Ge=Symbol("bufferLength"),Va=Symbol("bufferPush"),Cs=Symbol("bufferShift"),Je=Symbol("objectMode"),Ae=Symbol("destroyed"),Ja=Symbol("error"),Za=Symbol("emitData"),ku=Symbol("emitEnd"),Ya=Symbol("emitEnd2"),kt=Symbol("async"),Xa=Symbol("abort"),Os=Symbol("aborted"),fi=Symbol("signal"),Ln=Symbol("dataListeners"),rt=Symbol("discarded"),hi=t=>Promise.resolve().then(t),ew=t=>t(),tw=t=>t==="end"||t==="finish"||t==="prefinish",nw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,rw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),of=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Er](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},iw=class extends of{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)}},sw=t=>!!t.objectMode,ow=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Gc{[ze]=!1;[ui]=!1;[Ye]=[];[Ue]=[];[Je];[_t];[kt];[mr];[Wt]=!1;[un]=!1;[Rs]=!1;[Ps]=!1;[li]=null;[Ge]=0;[Ae]=!1;[fi];[Os]=!1;[Ln]=0;[rt]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");sw(e)?(this[Je]=!0,this[_t]=null):ow(e)?(this[_t]=e.encoding,this[Je]=!1):(this[Je]=!1,this[_t]=null),this[kt]=!!e.async,this[mr]=this[_t]?new Zm(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ue]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ye]});let{signal:r}=e;r&&(this[fi]=r,r.aborted?this[Xa]():r.addEventListener("abort",()=>this[Xa]()))}get bufferLength(){return this[Ge]}get encoding(){return this[_t]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Je]}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}[Xa](){this[Os]=!0,this.emit("abort",this[fi]?.reason),this.destroy(this[fi]?.reason)}get aborted(){return this[Os]}set aborted(t){}write(t,e,r){if(this[Os])return!1;if(this[Wt])throw new Error("write after end");if(this[Ae])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[kt]?hi:ew;if(!this[Je]&&!Buffer.isBuffer(t)){if(rw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(nw(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[Ge]!==0&&this[Ds](!0),this[ze]?this.emit("data",t):this[Va](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[ze]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[mr].write(t)),this[ze]&&this[Ge]!==0&&this[Ds](!0),this[ze]?this.emit("data",t):this[Va](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[ze]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[ze])}read(t){if(this[Ae])return null;if(this[rt]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[Kt](),null;this[Je]&&(t=null),this[Ue].length>1&&!this[Je]&&(this[Ue]=[this[_t]?this[Ue].join(""):Buffer.concat(this[Ue],this[Ge])]);let e=this[Iu](t||null,this[Ue][0]);return this[Kt](),e}[Iu](t,e){if(this[Je])this[Cs]();else{let r=e;t===r.length||t===null?this[Cs]():typeof r=="string"?(this[Ue][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[Ue][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[Ue].length&&!this[Wt]&&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[Wt]=!0,this.writable=!1,(this[ze]||!this[ui])&&this[Kt](),this}[Er](){this[Ae]||(!this[Ln]&&!this[Ye].length&&(this[rt]=!0),this[ui]=!1,this[ze]=!0,this.emit("resume"),this[Ue].length?this[Ds]():this[Wt]?this[Kt]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[ze]=!1,this[ui]=!0,this[rt]=!1}get destroyed(){return this[Ae]}get flowing(){return this[ze]}get paused(){return this[ui]}[Va](t){this[Je]?this[Ge]+=1:this[Ge]+=t.length,this[Ue].push(t)}[Cs](){return this[Je]?this[Ge]-=1:this[Ge]-=this[Ue][0].length,this[Ue].shift()}[Ds](t=!1){do;while(this[Au](this[Cs]())&&this[Ue].length);!t&&!this[Ue].length&&!this[Wt]&&this.emit("drain")}[Au](t){return this.emit("data",t),this[ze]}pipe(t,e){if(this[Ae])return t;this[rt]=!1;let r=this[un];return e=e||{},t===Su.stdout||t===Su.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Ye].push(e.proxyErrors?new iw(this,t,e):new of(this,t,e)),this[kt]?hi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[Ye].find(r=>r.dest===t);e&&(this[Ye].length===1?(this[ze]&&this[Ln]===0&&(this[ze]=!1),this[Ye]=[]):this[Ye].splice(this[Ye].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[rt]=!1,this[Ln]++,!this[Ye].length&&!this[ze]&&this[Er]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(tw(t)&&this[un])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[li]){let i=e;this[kt]?hi(()=>i.call(this,this[li])):i.call(this,this[li])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[rt]&&!this[Ye].length&&(this[ze]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[rt]&&!this[Ye].length&&(this[ze]=!1)),e}get emittedEnd(){return this[un]}[Kt](){!this[Rs]&&!this[un]&&!this[Ae]&&this[Ue].length===0&&this[Wt]&&(this[Rs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ps]&&this.emit("close"),this[Rs]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ae&&this[Ae])return!1;if(t==="data")return!this[Je]&&!r?!1:this[kt]?(hi(()=>this[Za](r)),!0):this[Za](r);if(t==="end")return this[ku]();if(t==="close"){if(this[Ps]=!0,!this[un]&&!this[Ae])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[li]=r,super.emit(Ja,r);let o=!this[fi]||this.listeners("error").length?super.emit("error",r):!1;return this[Kt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Kt](),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[Kt](),i}[Za](t){for(let r of this[Ye])r.dest.write(t)===!1&&this.pause();let e=this[rt]?!1:super.emit("data",t);return this[Kt](),e}[ku](){return this[un]?!1:(this[un]=!0,this.readable=!1,this[kt]?(hi(()=>this[Ya]()),!0):this[Ya]())}[Ya](){if(this[mr]){let e=this[mr].end();if(e){for(let r of this[Ye])r.dest.write(e);this[rt]||super.emit("data",e)}}for(let e of this[Ye])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[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ae,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[rt]=!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[Wt])return e();let i,o,c=x=>{this.off("data",l),this.off("end",u),this.off(Ae,f),e(),o(x)},l=x=>{this.off("error",c),this.off("end",u),this.off(Ae,f),this.pause(),i({value:x,done:!!this[Wt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(Ae,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(Ae,f),this.once("error",c),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[rt]=!1;let t=!1,e=()=>(this.pause(),this.off(Ja,e),this.off(Ae,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Ja,e),this.once(Ae,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ae])return t?this.emit("error",t):this.emit(Ae),this;this[Ae]=!0,this[rt]=!0,this[Ue].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Ps]&&e.close(),t?this.emit("error",t):this.emit(Ae),this}static get isStream(){return Ym}},aw=et.writev,bn=Symbol("_autoClose"),vt=Symbol("_close"),xi=Symbol("_ended"),de=Symbol("_fd"),Qa=Symbol("_finished"),Zt=Symbol("_flags"),ec=Symbol("_flush"),yc=Symbol("_handleChunk"),bc=Symbol("_makeBuf"),Ii=Symbol("_mode"),Ls=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),tc=Symbol("_onread"),vr=Symbol("_onwrite"),En=Symbol("_open"),Et=Symbol("_path"),gn=Symbol("_pos"),Tt=Symbol("_queue"),Sr=Symbol("_read"),nc=Symbol("_readSize"),Jt=Symbol("_reading"),pi=Symbol("_remain"),rc=Symbol("_size"),qs=Symbol("_write"),Nn=Symbol("_writing"),Ws=Symbol("_defaultFlag"),Hn=Symbol("_errored"),Hc=class extends Kn{[Hn]=!1;[de];[Et];[nc];[Jt]=!1;[rc];[pi];[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[Hn]=!1,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Et]=t,this[nc]=e.readSize||16*1024*1024,this[Jt]=!1,this[rc]=typeof e.size=="number"?e.size:1/0,this[pi]=this[rc],this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[Sr]():this[En]()}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")}[En](){et.open(this[Et],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[de]=e,this.emit("open",e),this[Sr]())}[bc](){return Buffer.allocUnsafe(Math.min(this[nc],this[pi]))}[Sr](){if(!this[Jt]){this[Jt]=!0;let t=this[bc]();if(t.length===0)return process.nextTick(()=>this[tc](null,0,t));et.read(this[de],t,0,t.length,null,(e,r,i)=>this[tc](e,r,i))}}[tc](t,e,r){this[Jt]=!1,t?this[kr](t):this[yc](e,r)&&this[Sr]()}[vt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Jt]=!0,this[vt](),this.emit("error",t)}[yc](t,e){let r=!1;return this[pi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[pi]<=0)&&(r=!1,this[vt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[Sr](),!1;case"error":return this[Hn]?!1:(this[Hn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},cw=class extends Hc{[En](){let t=!0;try{this[Tr](null,et.openSync(this[Et],"r")),t=!1}finally{t&&this[vt]()}}[Sr](){let t=!0;try{if(!this[Jt]){this[Jt]=!0;do{let e=this[bc](),r=e.length===0?0:et.readSync(this[de],e,0,e.length,null);if(!this[yc](r,e))break}while(!0);this[Jt]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.closeSync(t),this.emit("close")}}},oo=class extends Jm{readable=!1;writable=!0;[Hn]=!1;[Nn]=!1;[xi]=!1;[Tt]=[];[Ls]=!1;[Et];[Ii];[bn];[de];[Ws];[Zt];[Qa]=!1;[gn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Ii]=e.mode===void 0?438:e.mode,this[gn]=typeof e.start=="number"?e.start:void 0,this[bn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[gn]!==void 0?"r+":"w";this[Ws]=e.flags===void 0,this[Zt]=e.flags===void 0?r:e.flags,this[de]===void 0&&this[En]()}emit(t,...e){if(t==="error"){if(this[Hn])return!1;this[Hn]=!0}return super.emit(t,...e)}get fd(){return this[de]}get path(){return this[Et]}[kr](t){this[vt](),this[Nn]=!0,this.emit("error",t)}[En](){et.open(this[Et],this[Zt],this[Ii],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[Ws]&&this[Zt]==="r+"&&t&&t.code==="ENOENT"?(this[Zt]="w",this[En]()):t?this[kr](t):(this[de]=e,this.emit("open",e),this[Nn]||this[ec]())}end(t,e){return t&&this.write(t,e),this[xi]=!0,!this[Nn]&&!this[Tt].length&&typeof this[de]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[xi]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[Nn]||this[Tt].length?(this[Tt].push(t),this[Ls]=!0,!1):(this[Nn]=!0,this[qs](t),!0)}[qs](t){et.write(this[de],t,0,t.length,this[gn],(e,r)=>this[vr](e,r))}[vr](t,e){t?this[kr](t):(this[gn]!==void 0&&typeof e=="number"&&(this[gn]+=e),this[Tt].length?this[ec]():(this[Nn]=!1,this[xi]&&!this[Qa]?(this[Qa]=!0,this[vt](),this.emit("finish")):this[Ls]&&(this[Ls]=!1,this.emit("drain"))))}[ec](){if(this[Tt].length===0)this[xi]&&this[vr](null,0);else if(this[Tt].length===1)this[qs](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],aw(this[de],t,this[gn],(e,r)=>this[vr](e,r))}}[vt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},af=class extends oo{[En](){let t;if(this[Ws]&&this[Zt]==="r+")try{t=et.openSync(this[Et],this[Zt],this[Ii])}catch(e){if(e?.code==="ENOENT")return this[Zt]="w",this[En]();throw e}else t=et.openSync(this[Et],this[Zt],this[Ii]);this[Tr](null,t)}[vt](){if(this[bn]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,et.closeSync(t),this.emit("close")}}[qs](t){let e=!0;try{this[vr](null,et.writeSync(this[de],t,0,t.length,this[gn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},uw=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"]]),fw=t=>!!t.sync&&!!t.file,hw=t=>!t.sync&&!!t.file,xw=t=>!!t.sync&&!t.file,pw=t=>!t.sync&&!t.file,gw=t=>!!t.file,mw=t=>uw.get(t)||t,jc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=mw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Li=(t,e,r,i,o)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let f=jc(c);if(o?.(f,l),fw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,l)}else if(hw(f)){let x=e(f,l);return u?x.then(()=>u(),u):x}else if(xw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(f,l)}else if(pw(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),yw=_w.constants||{ZLIB_VERNUM:4736},Ct=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},yw)),bw=jn.concat,Ru=Object.getOwnPropertyDescriptor(jn,"concat"),Ew=t=>t,ic=Ru?.writable===!0||Ru?.set!==void 0?t=>{jn.concat=t?Ew:bw}:t=>{},qn=Symbol("_superWrite"),Ns=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},sc=Symbol("flushFlag"),qc=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 Tu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Tu[e](t)}catch(r){throw new Ns(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 Ns(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Ec(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(jn.alloc(0),{[sc]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[qn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=jn.from(t,e)),this.#e)return;Ec(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},ic(!0);let l;try{let f=typeof t[sc]=="number"?t[sc]:this.#r;l=this.#t._processChunk(t,f),ic(!1)}catch(f){ic(!1),this.#o(new Ns(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 Ns(f,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let f=l[0];u=this[qn](jn.from(f));for(let x=1;x<l.length;x++)u=this[qn](l[x])}else u=this[qn](jn.from(l));return r&&r(),u}},df=class extends qc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ct.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ct.Z_FINISH,t.fullFlushFlag=Ct.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(Ct.Z_SYNC_FLUSH),Ec(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},vw=class extends df{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[qn](t){return this.#e?(this.#e=!1,t[9]=255,super[qn](t)):super[qn](t)}},Sw=class extends df{constructor(t){super(t,"Unzip")}},lf=class extends qc{constructor(t,e){t=t||{},t.flush=t.flush||Ct.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ct.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ct.BROTLI_OPERATION_FLUSH,super(t,e)}},Iw=class extends lf{constructor(t){super(t,"BrotliCompress")}},Aw=class extends lf{constructor(t){super(t,"BrotliDecompress")}},uf=class extends qc{constructor(t,e){t=t||{},t.flush=t.flush||Ct.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ct.ZSTD_e_end,t.fullFlushFlag=Ct.ZSTD_e_flush,super(t,e)}},kw=class extends uf{constructor(t){super(t,"ZstdCompress")}},Tw=class extends uf{constructor(t){super(t,"ZstdDecompress")}},Rw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Dw(t,e):Pw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Pw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Dw=(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]=ff(o):o===0?e[i-1]=0:(r=!0,e[i-1]=hf(o))}},Cw=t=>{let e=t[0],r=e===128?Lw(t.subarray(1,t.length)):e===255?Ow(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},Ow=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),l;i?l=ff(c):c===0?l=c:(i=!0,l=hf(c)),l!==0&&(r-=l*Math.pow(256,e-o-1))}return r},Lw=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},ff=t=>(255^t)&255,hf=t=>(255^t)+1&255,Nw={};Vm(Nw,{code:()=>Wc,isCode:()=>Ks,isName:()=>Mw,name:()=>ao,normalFsTypes:()=>xf});var Ks=t=>ao.has(t),Mw=t=>Wc.has(t),xf=new Set(["0","","1","2","3","4","5","6","7","D"]),ao=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Wc=new Map(Array.from(ao).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=xf.has(o),l=c?r:void 0,u=c?i:void 0;if(this.path=l?.path??Mn(t,e,100),this.mode=l?.mode??u?.mode??mn(t,e+100,8),this.uid=l?.uid??u?.uid??mn(t,e+108,8),this.gid=l?.gid??u?.gid??mn(t,e+116,8),this.size=l?.size??u?.size??mn(t,e+124,12),this.mtime=l?.mtime??u?.mtime??oc(t,e+136,12),this.cksum=mn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),Ks(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Mn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=l?.uname??u?.uname??Mn(t,e+265,32),this.gname=l?.gname??u?.gname??Mn(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??mn(t,e+329,8)??0,this.devmin=l?.devmin??u?.devmin??mn(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??oc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??oc(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=Bw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Bn(t,e,100,o)||this.needPax,this.needPax=wn(t,e+100,8,this.mode)||this.needPax,this.needPax=wn(t,e+108,8,this.uid)||this.needPax,this.needPax=wn(t,e+116,8,this.gid)||this.needPax,this.needPax=wn(t,e+124,12,this.size)||this.needPax,this.needPax=ac(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Bn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Bn(t,e+265,32,this.uname)||this.needPax,this.needPax=Bn(t,e+297,32,this.gname)||this.needPax,this.needPax=wn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=wn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Bn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Bn(t,e+345,155,c)||this.needPax:(this.needPax=Bn(t,e+345,130,c)||this.needPax,this.needPax=ac(t,e+476,12,this.atime)||this.needPax,this.needPax=ac(t,e+488,12,this.ctime)||this.needPax);let l=256;for(let u=e;u<e+148;u++)l+=t[u];for(let u=e+156;u<e+512;u++)l+=t[u];return this.cksum=l,wn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ao.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Wc.get(t));if(Ks(e)||e==="Unsupported")this.#e=e;else if(Ks(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Bw=(t,e)=>{let r=t,i="",o,c=wr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=wr.dirname(r),r=wr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=wr.join(wr.basename(i),r),i=wr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Mn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),oc=(t,e,r)=>Fw(mn(t,e,r)),Fw=t=>t===void 0?void 0:new Date(t*1e3),mn=(t,e,r)=>Number(t[e])&128?Cw(t.subarray(e,e+r)):Uw(t,e,r),zw=t=>isNaN(t)?void 0:t,Uw=(t,e,r)=>zw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Gw={12:8589934591,8:2097151},wn=(t,e,r,i)=>i===void 0?!1:i>Gw[r]||i<0?(Rw(i,t.subarray(e,e+r)),!0):(Hw(t,e,r,i),!1),Hw=(t,e,r,i)=>t.write(jw(i,r),e,r,"ascii"),jw=(t,e)=>qw(Math.floor(t).toString(8),e),qw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",ac=(t,e,r,i)=>i===void 0?!1:wn(t,e,r,i.getTime()/1e3),Ww=new Array(156).join("\0"),Bn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Ww,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),to=class pf{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/"+Kw(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),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,r,i=!1){return new pf($w(Vw(e),r),i)}},$w=(t,e)=>e?Object.assign({},e,t):t,Vw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(Jw,Object.create(null)),Jw=(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"),l=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},Zw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,X=Zw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Yw=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))))}},co=(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))},Xw=1024*1024,vc=Buffer.from([31,139]),Sc=Buffer.from([40,181,47,253]),Qw=Math.max(vc.length,Sc.length),lt=Symbol("state"),Fn=Symbol("writeEntry"),$t=Symbol("readEntry"),cc=Symbol("nextEntry"),Pu=Symbol("processEntry"),Rt=Symbol("extendedHeader"),gi=Symbol("globalExtendedHeader"),fn=Symbol("meta"),Du=Symbol("emitMeta"),ge=Symbol("buffer"),Vt=Symbol("queue"),hn=Symbol("ended"),dc=Symbol("emittedEnd"),zn=Symbol("emit"),Pe=Symbol("unzip"),Ms=Symbol("consumeChunk"),Bs=Symbol("consumeChunkSub"),lc=Symbol("consumeBody"),Cu=Symbol("consumeMeta"),Ou=Symbol("consumeHeader"),mi=Symbol("consuming"),uc=Symbol("bufferConcat"),Fs=Symbol("maybeEnd"),_r=Symbol("writing"),xn=Symbol("aborted"),zs=Symbol("onDone"),Un=Symbol("sawValidEntry"),Us=Symbol("sawNullBlock"),Gs=Symbol("sawEOF"),Lu=Symbol("closeStream"),e_=()=>!0,Oi=class extends ww{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Vt]=[];[ge];[$t];[Fn];[lt]="begin";[fn]="";[Rt];[gi];[hn]=!1;[Pe];[xn]=!1;[Un];[Us]=!1;[Gs]=!1;[_r]=!1;[mi]=!1;[dc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(zs,()=>{(this[lt]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(zs,t.ondone):this.on(zs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Xw,this.filter=typeof t.filter=="function"?t.filter:e_;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[Lu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){co(this,t,e,r)}[Ou](t,e){this[Un]===void 0&&(this[Un]=!1);let r;try{r=new Wn(t,e,this[Rt],this[gi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Us]?(this[Gs]=!0,this[lt]==="begin"&&(this[lt]="header"),this[zn]("eof")):(this[Us]=!0,this[zn]("nullBlock"));else if(this[Us]=!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 Yw(r,this[Rt],this[gi]);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[lt]="ignore",o.resume()):o.size>0&&(this[fn]="",o.on("data",c=>this[fn]+=c),this[lt]="meta"):(this[Rt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[lt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[lt]="body":(this[lt]="header",o.end()),this[$t]?this[Vt].push(o):(this[Vt].push(o),this[cc]())))}}}[Lu](){queueMicrotask(()=>this.emit("close"))}[Pu](t){let e=!0;if(!t)this[$t]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[$t]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[cc]()),e=!1);return e}[cc](){do;while(this[Pu](this[Vt].shift()));if(this[Vt].length===0){let t=this[$t];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[lc](t,e){let r=this[Fn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[lt]="header",this[Fn]=void 0,r.end()),o.length}[Cu](t,e){let r=this[Fn],i=this[lc](t,e);return!this[Fn]&&r&&this[Du](r),i}[zn](t,e,r){this[Vt].length===0&&!this[$t]?this.emit(t,e,r):this[Vt].push([t,e,r])}[Du](t){switch(this[zn]("meta",this[fn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Rt]=to.parse(this[fn],this[Rt],!1);break;case"GlobalExtendedHeader":this[gi]=to.parse(this[fn],this[gi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Rt]??Object.create(null);this[Rt]=e,e.path=this[fn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Rt]||Object.create(null);this[Rt]=e,e.linkpath=this[fn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[xn]=!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[xn])return r?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<Qw)return this[ge]=t,r?.(),!0;for(let l=0;this[Pe]===void 0&&l<vc.length;l++)t[l]!==vc[l]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<Sc.length;l++)if(t[l]!==Sc[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Pe]===!1&&c)if(t.length<512)if(this[hn])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[Pe]===void 0||this[Pe]===!1&&(this.brotli||o)){let l=this[hn];this[hn]=!1,this[Pe]=this[Pe]===void 0?new Sw({}):o?new Tw({}):new Aw({}),this[Pe].on("data",f=>this[Ms](f)),this[Pe].on("error",f=>this.abort(f)),this[Pe].on("end",()=>{this[hn]=!0,this[Ms]()}),this[_r]=!0;let u=!!this[Pe][l?"end":"write"](t);return this[_r]=!1,r?.(),u}}this[_r]=!0,this[Pe]?this[Pe].write(t):this[Ms](t),this[_r]=!1;let i=this[Vt].length>0?!1:this[$t]?this[$t].flowing:!0;return!i&&this[Vt].length===0&&this[$t]?.once("drain",()=>this.emit("drain")),r?.(),i}[uc](t){t&&!this[xn]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Fs](){if(this[hn]&&!this[dc]&&!this[xn]&&!this[mi]){this[dc]=!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](zs)}}[Ms](t){if(this[mi]&&t)this[uc](t);else if(!t&&!this[ge])this[Fs]();else if(t){if(this[mi]=!0,this[ge]){this[uc](t);let e=this[ge];this[ge]=void 0,this[Bs](e)}else this[Bs](t);for(;this[ge]&&this[ge]?.length>=512&&!this[xn]&&!this[Gs];){let e=this[ge];this[ge]=void 0,this[Bs](e)}this[mi]=!1}(!this[ge]||this[hn])&&this[Fs]()}[Bs](t){let e=0,r=t.length;for(;e+512<=r&&!this[xn]&&!this[Gs];)switch(this[lt]){case"begin":case"header":this[Ou](t,e),e+=512;break;case"ignore":case"body":e+=this[lc](t,e);break;case"meta":e+=this[Cu](t,e);break;default:throw new Error("invalid state: "+this[lt])}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[xn]||(this[Pe]?(t&&this[Pe].write(t),this[Pe].end()):(this[hn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Fs]())),this}},Ai=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},t_=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},gf=(t,e)=>{let r=new Map(e.map(c=>[Ai(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||lw(c).root||".",f;if(c===u)f=!1;else{let x=r.get(c);f=x!==void 0?x:o(dw(c),u)}return r.set(c,f),f};t.filter=i?(c,l)=>i(c,l)&&o(Ai(c)):c=>o(Ai(c))},n_=t=>{let e=new Oi(t),r=t.file,i;try{i=Ir.openSync(r,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=Ir.readSync(i,l,0,o.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<o.size;){let f=Ir.readSync(i,u,0,c,l);if(f===0)break;l+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Ir.closeSync(i)}catch{}}},r_=(t,e)=>{let r=new Oi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),Ir.stat(o,(u,f)=>{if(u)l(u);else{let x=new Hc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Rr=Li(n_,r_,t=>new Oi(t),t=>new Oi(t),(t,e)=>{e?.length&&gf(t,e),t.noResume||t_(t)}),mf=(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:s_,parse:Mu}=i_,Kc=t=>{let e="",r=Mu(t);for(;s_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Mu(t)}return[e,t]},lo=["|","<",">","?",":"],$c=lo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),o_=new Map(lo.map((t,e)=>[t,$c[e]])),a_=new Map($c.map((t,e)=>[t,lo[e]])),Bu=t=>lo.reduce((e,r)=>e.split(r).join(o_.get(r)),t),c_=t=>$c.reduce((e,r)=>e.split(r).join(a_.get(r)),t),wf=(t,e)=>e?(t=X(t).replace(/^\.(\/|$)/,""),Ai(e)+"/"+t):X(t),d_=16*1024*1024,Fu=Symbol("process"),zu=Symbol("file"),Uu=Symbol("directory"),Ic=Symbol("symlink"),Gu=Symbol("hardlink"),wi=Symbol("header"),$s=Symbol("read"),Ac=Symbol("lstat"),Vs=Symbol("onlstat"),kc=Symbol("onread"),Tc=Symbol("onreadlink"),Rc=Symbol("openfile"),Pc=Symbol("onopenfile"),_n=Symbol("close"),ro=Symbol("mode"),Dc=Symbol("awaitDrain"),fc=Symbol("ondrain"),Dt=Symbol("prefix"),_f=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=jc(e);super(),this.path=X(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||d_,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[c,l]=Kc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=c_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=X(r.absolute||Nu.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[Vs](o):this[Ac]()}warn(t,e,r={}){return co(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Ac](){Pt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Vs](e)})}[Vs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=f_(t),this.emit("stat",t),this[Fu]()}[Fu](){switch(this.type){case"File":return this[zu]();case"Directory":return this[Uu]();case"SymbolicLink":return this[Ic]();default:return this.end()}}[ro](t){return mf(t,this.type==="Directory",this.portable)}[Dt](t){return wf(t,this.prefix)}[wi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Wn({path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this[ro](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 to({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Uu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[wi](),this.end()}[Ic](){Pt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Tc](e)})}[Tc](t){this.linkpath=X(t),this[wi](),this.end()}[Gu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=X(Nu.relative(this.cwd,t)),this.stat.size=0,this[wi](),this.end()}[zu](){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[Gu](e);this.linkCache.set(t,this.absolute)}if(this[wi](),this.stat.size===0)return this.end();this[Rc]()}[Rc](){Pt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Pc](e)})}[Pc](t){if(this.fd=t,this.#e)return this[_n]();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[$s]()}[$s](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Pt.read(t,e,r,i,o,(c,l)=>{if(c)return this[_n](()=>this.emit("error",c));this[kc](l)})}[_n](t=()=>{}){this.fd!==void 0&&Pt.close(this.fd,t)}[kc](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[_n](()=>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[_n](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[fc]():this[Dc](()=>this[fc]())}[Dc](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[fc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[_n](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[$s]()}},l_=class extends _f{sync=!0;[Ac](){this[Vs](Pt.lstatSync(this.absolute))}[Ic](){this[Tc](Pt.readlinkSync(this.absolute))}[Rc](){this[Pc](Pt.openSync(this.absolute,"r"))}[$s](){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 l=Pt.readSync(e,r,i,o,c);this[kc](l),t=!1}finally{if(t)try{this[_n](()=>{})}catch{}}}[Dc](t){t()}[_n](t=()=>{}){this.fd!==void 0&&Pt.closeSync(this.fd),t()}},u_=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 co(this,t,e,r)}constructor(t,e={}){let r=jc(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[ro](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[l,u]=Kc(this.path);l&&typeof u=="string"&&(this.path=u,o=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Wn({path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),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 to({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Dt](t){return wf(t,this.prefix)}[ro](t){return mf(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}},f_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",h_=class Ar{tail;head;length=0;static create(e=[]){return new Ar(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)p_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)g_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new Ar;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new Ar;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let l=0;o&&l<e;l++)o=o.next;let c=[];for(let l=0;o&&l<r;l++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let l of i)o=x_(this,o,l);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 x_(t,e,r){let i=e,o=e?e.next:t.head,c=new Vc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function p_(t,e){t.tail=new Vc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function g_(t,e){t.head=new Vc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Vc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},ju=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},qu=Buffer.alloc(1024),Js=Symbol("onStat"),_i=Symbol("ended"),yt=Symbol("queue"),yi=Symbol("pendingLinks"),pn=Symbol("current"),Gn=Symbol("process"),bi=Symbol("processing"),Hs=Symbol("processJob"),bt=Symbol("jobs"),hc=Symbol("jobDone"),Zs=Symbol("addFSEntry"),Wu=Symbol("addTarEntry"),Cc=Symbol("stat"),Oc=Symbol("readdir"),Ys=Symbol("onreaddir"),Xs=Symbol("pipe"),Ku=Symbol("entry"),xc=Symbol("entryOpt"),Qs=Symbol("writeEntryClass"),yf=Symbol("write"),pc=Symbol("ondrain"),uo=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Qs];onWriteEntry;[yt];[yi]=new Map;[bt]=0;[bi]=!1;[_i]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=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[Qs]=_f,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 vw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Iw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new kw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[pc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[pc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[yt]=new h_,this[bt]=0,this.jobs=Number(t.jobs)||4,this[bi]=!1,this[_i]=!1}[yf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[_i]=!0,this[Gn](),r&&r(),this}write(t){if(this[_i])throw new Error("write after end");return typeof t=="string"?this[Zs](t):this[Wu](t),this.flowing}[Wu](t){let e=X(Hu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new ju(t.path,e);r.entry=new u_(t,this[xc](r)),r.entry.on("end",()=>this[hc](r)),this[bt]+=1,this[yt].push(r)}this[Gn]()}[Zs](t){let e=X(Hu.resolve(this.cwd,t));this[yt].push(new ju(t,e)),this[Gn]()}[Cc](t){t.pending=!0,this[bt]+=1;let e=this.follow?"stat":"lstat";no[e](t.absolute,(r,i)=>{t.pending=!1,this[bt]-=1,r?this.emit("error",r):this[Js](t,i)})}[Js](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[pn])this[Hs](t);else{let r=`${e.dev}:${e.ino}`,i=this[yi].get(r);i?i.push(t):this[yi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[Gn]()}[Oc](t){t.pending=!0,this[bt]+=1,no.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[bt]-=1,e)return this.emit("error",e);this[Ys](t,r)})}[Ys](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Gn]()}[Gn](){if(!this[bi]){this[bi]=!0;for(let t=this[yt].head;t&&this[bt]<this.jobs;t=t.next)if(this[Hs](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[bi]=!1,this[_i]&&this[yt].length===0&&this[bt]===0&&(this.zip?this.zip.end(qu):(super.write(qu),super.end()))}}get[pn](){return this[yt]&&this[yt].head&&this[yt].head.value}[hc](t){this[yt].shift(),this[bt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[yi].get(r);if(i){this[yi].delete(r);for(let o of i)o.pending=!1,this[Hs](o)}}this[Gn]()}[Hs](t){if(t.pending&&t.pendingLink&&t===this[pn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[pn]&&!t.piped&&this[Xs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Js](t,e):this[Cc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Ys](t,e):this[Oc](t),!t.readdir)return}if(t.entry=this[Ku](t),!t.entry){t.ignore=!0;return}t===this[pn]&&!t.piped&&this[Xs](t)}}}[xc](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}}[Ku](t){this[bt]+=1;try{return new this[Qs](t.path,this[xc](t)).on("end",()=>this[hc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[pc](){this[pn]&&this[pn].entry&&this[pn].entry.resume()}[Xs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Zs](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={}){co(this,t,e,r)}},Jc=class extends uo{sync=!0;constructor(t){super(t),this[Qs]=l_}pause(){}resume(){}[Cc](t){let e=this.follow?"statSync":"lstatSync";this[Js](t,no[e](t.absolute))}[Oc](t){this[Ys](t,no.readdirSync(t.absolute))}[Xs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Zs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[yf](i)})}},m_=(t,e)=>{let r=new Jc(t),i=new af(t.file,{mode:t.mode||438});r.pipe(i),bf(r,e)},w_=(t,e)=>{let r=new uo(t),i=new oo(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,l)=>{i.on("error",l),i.on("close",c),r.on("error",l)});return Ef(r,e).catch(c=>r.emit("error",c)),o},bf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Rr({file:cf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},Ef=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Rr({file:cf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},__=(t,e)=>{let r=new Jc(t);return bf(r,e),r},y_=(t,e)=>{let r=new uo(t);return Ef(r,e).catch(i=>r.emit("error",i)),r},QI=Li(m_,w_,__,y_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),E_=process.env.__FAKE_PLATFORM__||process.platform,Af=E_==="win32",{O_CREAT:kf,O_NOFOLLOW:$u,O_TRUNC:Tf,O_WRONLY:Rf}=If.constants,Pf=Number(process.env.__FAKE_FS_O_FILENAME__)||If.constants.UV_FS_O_FILEMAP||0,v_=Af&&!!Pf,S_=512*1024,I_=Pf|Tf|kf|Rf,Vu=!Af&&typeof $u=="number"?$u|Tf|kf|Rf:null,Df=Vu!==null?()=>Vu:v_?t=>t<S_?I_:"w":()=>"w",Lc=(t,e,r)=>{try{return fo.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},io=(t,e,r,i)=>{fo.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},A_=(t,e,r,i,o)=>{if(e.isDirectory())Cf(ki.resolve(t,e.name),r,i,c=>{if(c)return o(c);let l=ki.resolve(t,e.name);io(l,r,i,o)});else{let c=ki.resolve(t,e.name);io(c,r,i,o)}},Cf=(t,e,r,i)=>{fo.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 io(t,e,r,i);let l=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--l===0)return io(t,e,r,i)}};for(let x of c)A_(t,x,e,r,f)})},k_=(t,e,r,i)=>{e.isDirectory()&&Of(ki.resolve(t,e.name),r,i),Lc(ki.resolve(t,e.name),r,i)},Of=(t,e,r)=>{let i;try{i=fo.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Lc(t,e,r);throw c}for(let o of i)k_(t,o,e,r);return Lc(t,e,r)},Lf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},ho=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},R_=(t,e)=>{st.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Lf(t,r?.code||"ENOTDIR")),e(r)})},P_=(t,e,r)=>{t=X(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,f=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),x=e.preserve,g=e.unlink,w=X(e.cwd),S=(v,I)=>{v?r(v):I&&f?Cf(I,l,u,A=>S(A)):c?st.chmod(t,o,r):r()};if(t===w)return R_(t,S);if(x)return T_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let y=X(so.relative(w,t)).split("/");Nc(w,y,o,g,w,void 0,S)},Nc=(t,e,r,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),f=X(so.resolve(t+"/"+u));st.mkdir(f,r,Nf(f,e,r,i,o,c,l))},Nf=(t,e,r,i,o,c,l)=>u=>{u?st.lstat(t,(f,x)=>{if(f)f.path=f.path&&X(f.path),l(f);else if(x.isDirectory())Nc(t,e,r,i,o,c,l);else if(i)st.unlink(t,g=>{if(g)return l(g);st.mkdir(t,r,Nf(t,e,r,i,o,c,l))});else{if(x.isSymbolicLink())return l(new ho(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Nc(t,e,r,i,o,c,l))},D_=t=>{let e=!1,r;try{e=st.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Lf(t,r??"ENOTDIR")}},C_=(t,e)=>{t=X(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),f=e.preserve,x=e.unlink,g=X(e.cwd),w=v=>{v&&u&&Of(v,c,l),o&&st.chmodSync(t,i)};if(t===g)return D_(g),w();if(f)return w(st.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=X(so.relative(g,t)).split("/"),y;for(let v=S.shift(),I=g;v&&(I+="/"+v);v=S.shift()){I=X(so.resolve(I));try{st.mkdirSync(I,i),y=y||I}catch{let A=st.lstatSync(I);if(A.isDirectory())continue;if(x){st.unlinkSync(I),st.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new ho(I,I+"/"+S.join("/"))}}return w(y)},gc=Object.create(null),Ju=1e4,yr=new Set,O_=t=>{yr.has(t)?yr.delete(t):gc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=gc[t],r=yr.size-Ju;if(r>Ju/10){for(let i of yr)if(yr.delete(i),delete gc[i],--r<=0)break}return e},L_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,N_=L_==="win32",M_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Mf(i,r)),e.push(r||"/"),e},[]),B_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=N_?["win32 parallelization disabled"]:t.map(i=>Ai(Mf(O_(i))));let r=new Set(t.map(i=>M_(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 l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let c of i){let l=this.#e.get(c),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(c);continue}else if(u.size===1){l.shift();let f=l[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},F_=()=>process.umask(),Zu=Symbol("onEntry"),Mc=Symbol("checkFs"),Yu=Symbol("checkFs2"),Bc=Symbol("isReusable"),ut=Symbol("makeFs"),Fc=Symbol("file"),zc=Symbol("directory"),eo=Symbol("link"),Xu=Symbol("symlink"),Qu=Symbol("hardlink"),Si=Symbol("ensureNoSymlink"),ef=Symbol("unsupported"),tf=Symbol("checkPath"),mc=Symbol("stripAbsolutePath"),yn=Symbol("mkdir"),He=Symbol("onError"),js=Symbol("pending"),nf=Symbol("pend"),br=Symbol("unpend"),wc=Symbol("ended"),_c=Symbol("maybeClose"),Uc=Symbol("skip"),Ti=Symbol("doChown"),Ri=Symbol("uid"),Pi=Symbol("gid"),Di=Symbol("checkedCwd"),z_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ci=z_==="win32",U_=1024,G_=(t,e)=>{if(!Ci)return ie.unlink(t,e);let r=t+".DELETE."+Sf(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},H_=t=>{if(!Ci)return ie.unlinkSync(t);let e=t+".DELETE."+Sf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},rf=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Zc=class extends Oi{[wc]=!1;[Di]=!1;[js]=0;reservations=new B_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[wc]=!0,this[_c]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:U_,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:F_():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[Zu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[_c](){this[wc]&&this[js]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[mc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Kc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Ci&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Ne.posix.dirname(t.path),f=Ne.posix.normalize(Ne.posix.join(u,l.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}[tf](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[mc](t,"path")||!this[mc](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+Bu(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Bu(t.path.slice(o.length))}return!0}[Zu](t){if(!this[tf](t))return t.resume();switch(b_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Mc](t);default:return this[ef](t)}}[He](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[yn](t,e,r){P_(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)}[Ti](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ri](t){return rf(this.uid,t.uid,this.processUid)}[Pi](t){return rf(this.gid,t.gid,this.processGid)}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new oo(String(t.absolute),{flags:Df(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[He](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[He](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,f=>{f?this[He](f,t):this[br](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,g=t.mtime;ie.futimes(f,x,g,w=>w?ie.utimes(u,x,g,S=>c(S&&w)):c())}if(typeof f=="number"&&this[Ti](t)){o++;let x=this[Ri](t),g=this[Pi](t);typeof x=="number"&&typeof g=="number"&&ie.fchown(f,x,g,w=>w?ie.chown(u,x,g,S=>c(S&&w)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[He](u,t),e()}),t.pipe(l)),l.pipe(i)}[zc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[yn](String(t.absolute),r,i=>{if(i){this[He](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ti](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ri](t)),Number(this[Pi](t)),c)),c()})}[ef](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Xu](t,e){let r=X(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Si](t,this.cwd,r,()=>this[eo](t,String(t.linkpath),"symlink",e),i=>{this[He](i,t),e()})}[Qu](t,e){let r=X(Ne.resolve(this.cwd,String(t.linkpath))),i=X(String(t.linkpath)).split("/");this[Si](t,this.cwd,i,()=>this[eo](t,r,"link",e),o=>{this[He](o,t),e()})}[Si](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Ne.resolve(e,c);ie.lstat(l,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new ho(l,Ne.resolve(l,r.join("/"))));this[Si](t,l,r,i,o)})}[nf](){this[js]++}[br](){this[js]--,this[_c]()}[Uc](t){this[br](),t.resume()}[Bc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ci}[Mc](t){this[nf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Yu](t,r))}[Yu](t,e){let r=l=>{e(l)},i=()=>{this[yn](this.cwd,this.dmode,l=>{if(l){this[He](l,t),r();return}this[Di]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=X(Ne.dirname(String(t.absolute)));if(l!==this.cwd)return this[yn](l,this.dmode,u=>{if(u){this[He](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Uc](t),r();return}if(l||this[Bc](t,u))return this[ut](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=g=>this[ut](g??null,t,r);return f?ie.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),f=>this[ut](f??null,t,r))}if(t.absolute===this.cwd)return this[ut](null,t,r);G_(String(t.absolute),f=>this[ut](f??null,t,r))})};this[Di]?o():i()}[ut](t,e,r){if(t){this[He](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Fc](e,r);case"Link":return this[Qu](e,r);case"SymbolicLink":return this[Xu](e,r);case"Directory":case"GNUDumpDir":return this[zc](e,r)}}[eo](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[He](o,t):(this[br](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},Bf=class extends Zc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[Mc](t){if(!this[Di]){let o=this[yn](this.cwd,this.dmode);if(o)return this[He](o,t);this[Di]=!0}if(t.absolute!==this.cwd){let o=X(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[yn](o,this.dmode);if(c)return this[He](c,t)}}let[e,r]=Ei(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Uc](t);if(e||this[Bc](t,r))return this[ut](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?Ei(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](l,t)}let[o]=Ei(()=>ie.rmdirSync(String(t.absolute)));this[ut](o,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>H_(String(t.absolute)));this[ut](i,t)}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{ie.closeSync(o)}catch(f){u=f}(l||u)&&this[He](l||u,t),e()},o;try{o=ie.openSync(String(t.absolute),Df(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[He](l,t)),t.pipe(c)),c.on("data",l=>{try{ie.writeSync(o,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{ie.futimesSync(o,u,f)}catch(x){try{ie.utimesSync(String(t.absolute),u,f)}catch{l=x}}}if(this[Ti](t)){let u=this[Ri](t),f=this[Pi](t);try{ie.fchownSync(o,Number(u),Number(f))}catch(x){try{ie.chownSync(String(t.absolute),Number(u),Number(f))}catch{l=l||x}}}i(l)})}[zc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[yn](String(t.absolute),r);if(i){this[He](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ti](t))try{ie.chownSync(String(t.absolute),Number(this[Ri](t)),Number(this[Pi](t)))}catch{}e(),t.resume()}[yn](t,e){try{return C_(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}}[Si](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Ne.resolve(c,l);let[u,f]=Ei(()=>ie.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new ho(c,Ne.resolve(e,r.join("/"))))}i()}[eo](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[He](c,t)}}},j_=t=>{let e=new Bf(t),r=t.file,i=vf.statSync(r),o=t.maxReadSize||16*1024*1024;new cw(r,{readSize:o,size:i.size}).pipe(e)},q_=(t,e)=>{let r=new Zc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),vf.stat(o,(u,f)=>{if(u)l(u);else{let x=new Hc(o,{readSize:i,size:f.size});x.on("error",l),x.pipe(r)}})})},Ff=Li(j_,q_,t=>new Bf(t),t=>new Zc(t),(t,e)=>{e?.length&&gf(t,e)}),W_=(t,e)=>{let r=new Jc(t),i=!0,o,c;try{try{o=it.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=it.openSync(t.file,"w+");else throw f}let l=it.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let g=0,w=0;g<512;g+=w){if(w=it.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(!w)break e}let f=new Wn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(c+x+512>l.size)break;c+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,K_(t,r,c,o,e)}finally{if(i)try{it.closeSync(o)}catch{}}},K_=(t,e,r,i,o)=>{let c=new af(t.file,{fd:i,start:r});e.pipe(c),V_(e,o)},$_=(t,e)=>{e=Array.from(e);let r=new uo(t),i=(o,c,l)=>{let u=(S,y)=>{S?it.close(o,v=>l(S)):l(null,y)},f=0;if(c===0)return u(null,0);let x=0,g=Buffer.alloc(512),w=(S,y)=>{if(S||y===void 0)return u(S);if(x+=y,x<512&&y)return it.read(o,g,x,g.length-x,f+x,w);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 v=new Wn(g);if(!v.cksumValid)return u(null,f);let I=512*Math.ceil((v.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,it.read(o,g,0,512,f,w)};it.read(o,g,0,512,f,w)};return new Promise((o,c)=>{r.on("error",c);let l="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&l==="r+")return l="w+",it.open(t.file,l,u);if(f||!x)return c(f);it.fstat(x,(g,w)=>{if(g)return it.close(x,()=>c(g));i(x,w.size,(S,y)=>{if(S)return c(S);let v=new oo(t.file,{fd:x,start:y});r.pipe(v),v.on("error",c),v.on("close",o),J_(r,e)})})};it.open(t.file,l,u)})},V_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Rr({file:zf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},J_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Rr({file:zf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},vi=Li(W_,$_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!gw(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")}),xA=Li(vi.syncFile,vi.asyncFile,vi.syncNoFile,vi.asyncNoFile,(t,e=[])=>{vi.validate?.(t,e),Z_(t)}),Z_=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))};qt();var ft={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function xo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Uf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function po(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Gf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Hf(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}Yt();We();ee();Re();We();function Pr(t,e){if(xo(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ni(t){return t.startsWith("http://")||t.startsWith("https://")}function Dr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as sk}from"node:fs";import{dirname as ak,join as ck}from"node:path";import{fileURLToPath as lk}from"node:url";var Ot="0.2.3-alpha.7";import{mkdir as fy,rm as a0}from"node:fs/promises";import{join as Ui}from"node:path";jt();import{readFileSync as iy}from"node:fs";var sy=384;async function Yc(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await fr(t.agentEnvFile,r,{mode:sy})}function Mi(t){try{let e=JSON.parse(iy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Kf(t,e,r={},i=o=>o){return{...i({...t,...Mi(e)}),...r}}jt();function Bi(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(oy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return uI(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 Lp("schtasks",["/Create","/SC","ONLOGON","/TN",Ea,"/TR",r,"/RU",t.userName,"/F"]),dl.info("task scheduler entry created",{task:Ea,logFile:t.logFile})},async uninstall(t){await Lp("schtasks",["/Delete","/TN",Ea,"/F"]).catch(e=>dl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),dl.info("task scheduler entry removed",{task:Ea})}}});var Mp={};Ma(Mp,{buildContext:()=>mI,getSupervisor:()=>hI,launchdSupervisor:()=>al,systemdSupervisor:()=>cl,taskSchedulerSupervisor:()=>ll});import{homedir as fI,userInfo as xI}from"node:os";function hI(t=process.platform){switch(t){case"darwin":return al;case"linux":return cl;case"win32":return ll;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function gI(){let t={};for(let e of pI){let r=process.env[e];r&&(t[e]=r)}return t}function mI(){let t=Z();return{nodeBin:process.execPath,entry:Yd(t),logFile:t.logFile,homeDir:fI(),userName:xI().username,isRoot:process.getuid?.()===0,env:gI()}}var pI,Bp=rt(()=>{"use strict";Ce();fa();Cp();Op();Np();pI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();fn();var Ul=q("acp-installer-warmup"),dm=["claude-code","codex"];async function Gl(t={}){let e=t.ensure??xr,i=(await Promise.allSettled(dm.map(async o=>{let c=await e(o);Ul.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Ul.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}Kt();te();import{readdir as Im}from"node:fs/promises";import{mkdir as Wl,readFile as vm,writeFile as Kl}from"node:fs/promises";import{join as qa}from"node:path";var Sm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function gr(t,e,r){await Wl(t,{recursive:!0});let i=Sm[e],o=qa(t,i);return await Kl(o,r??"","utf8"),o}async function ja(t,e,r){let i=qa(t,".claude");await Wl(i,{recursive:!0});let o=qa(i,"settings.local.json"),c={};try{let u=await vm(o,"utf8"),x=JSON.parse(u);typeof x=="object"&&x!==null&&!Array.isArray(x)&&(c=x)}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 Kl(o,JSON.stringify(c,null,2),"utf8"),o}var Xe=q("agent-detail-sync"),Am=6e4,km=5*6e4,As=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Im(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 Ie(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 Ie(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(x){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(x)});let h=this.retryQueue.get(e),g=h?Math.min(h.currentDelay*2,km):Am;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 gr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var hd=jt(Iu(),1);import{createHash as hy}from"node:crypto";import{lstat as ad,mkdir as cd,readFile as Eo,readdir as g0,rm as dd,stat as m0,writeFile as ld}from"node:fs/promises";import{homedir as py}from"node:os";import{dirname as gy,join as xe,normalize as my,relative as xd,resolve as ud,sep as w0}from"node:path";import{Readable as _0}from"node:stream";import{pipeline as y0}from"node:stream/promises";import Jm from"events";import it from"fs";import{EventEmitter as qc}from"node:events";import af from"node:stream";import{StringDecoder as Zm}from"node:string_decoder";import lf from"node:path";import Tr from"node:fs";import{dirname as dw,parse as lw}from"path";import{EventEmitter as ww}from"events";import Sc from"assert";import{Buffer as Kn}from"buffer";import*as Pu from"zlib";import _w from"zlib";import{posix as br}from"node:path";import{basename as Kw}from"node:path";import io from"fs";import Lt from"fs";import Bu from"path";import{win32 as i_}from"node:path";import ju from"path";import If from"node:fs";import b_ from"node:assert";import{randomBytes as Af}from"node:crypto";import se from"node:fs";import Be from"node:path";import kf from"fs";import ho from"node:fs";import Pi from"node:path";import ct from"node:fs";import T_ from"node:fs/promises";import ao from"node:path";import{join as zf}from"node:path";import at from"node:fs";import Gf from"node:path";var $m=Object.defineProperty,Vm=(t,e)=>{for(var r in e)$m(t,r,{get:e[r],enumerable:!0})},Au=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ym=t=>!!t&&typeof t=="object"&&(t instanceof Jn||t instanceof af||Xm(t)||Qm(t)),Xm=t=>!!t&&typeof t=="object"&&t instanceof qc&&typeof t.pipe=="function"&&t.pipe!==af.Writable.prototype.pipe,Qm=t=>!!t&&typeof t=="object"&&t instanceof qc&&typeof t.write=="function"&&typeof t.end=="function",$t=Symbol("EOF"),Vt=Symbol("maybeEmitEnd"),hn=Symbol("emittedEnd"),Cs=Symbol("emittingEnd"),xi=Symbol("emittedError"),Ds=Symbol("closed"),ku=Symbol("read"),Os=Symbol("flush"),Tu=Symbol("flushChunk"),vt=Symbol("encoding"),yr=Symbol("decoder"),Ge=Symbol("flowing"),hi=Symbol("paused"),Ir=Symbol("resume"),He=Symbol("buffer"),Qe=Symbol("pipes"),qe=Symbol("bufferLength"),Za=Symbol("bufferPush"),Ls=Symbol("bufferShift"),Ye=Symbol("objectMode"),Te=Symbol("destroyed"),Ya=Symbol("error"),Xa=Symbol("emitData"),Ru=Symbol("emitEnd"),Qa=Symbol("emitEnd2"),Ct=Symbol("async"),ec=Symbol("abort"),Ns=Symbol("aborted"),pi=Symbol("signal"),Bn=Symbol("dataListeners"),ot=Symbol("discarded"),gi=t=>Promise.resolve().then(t),ew=t=>t(),tw=t=>t==="end"||t==="finish"||t==="prefinish",nw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,rw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),cf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Ir](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},iw=class extends cf{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)}},sw=t=>!!t.objectMode,ow=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Jn=class extends qc{[Ge]=!1;[hi]=!1;[Qe]=[];[He]=[];[Ye];[vt];[Ct];[yr];[$t]=!1;[hn]=!1;[Cs]=!1;[Ds]=!1;[xi]=null;[qe]=0;[Te]=!1;[pi];[Ns]=!1;[Bn]=0;[ot]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");sw(e)?(this[Ye]=!0,this[vt]=null):ow(e)?(this[vt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[vt]=null),this[Ct]=!!e.async,this[yr]=this[vt]?new Zm(this[vt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:r}=e;r&&(this[pi]=r,r.aborted?this[ec]():r.addEventListener("abort",()=>this[ec]()))}get bufferLength(){return this[qe]}get encoding(){return this[vt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ct]}set async(t){this[Ct]=this[Ct]||!!t}[ec](){this[Ns]=!0,this.emit("abort",this[pi]?.reason),this.destroy(this[pi]?.reason)}get aborted(){return this[Ns]}set aborted(t){}write(t,e,r){if(this[Ns])return!1;if(this[$t])throw new Error("write after end");if(this[Te])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[Ct]?gi:ew;if(!this[Ye]&&!Buffer.isBuffer(t)){if(rw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(nw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[Ge]&&this[qe]!==0&&this[Os](!0),this[Ge]?this.emit("data",t):this[Za](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[Ge]):t.length?(typeof t=="string"&&!(e===this[vt]&&!this[yr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[vt]&&(t=this[yr].write(t)),this[Ge]&&this[qe]!==0&&this[Os](!0),this[Ge]?this.emit("data",t):this[Za](t),this[qe]!==0&&this.emit("readable"),r&&i(r),this[Ge]):(this[qe]!==0&&this.emit("readable"),r&&i(r),this[Ge])}read(t){if(this[Te])return null;if(this[ot]=!1,this[qe]===0||t===0||t&&t>this[qe])return this[Vt](),null;this[Ye]&&(t=null),this[He].length>1&&!this[Ye]&&(this[He]=[this[vt]?this[He].join(""):Buffer.concat(this[He],this[qe])]);let e=this[ku](t||null,this[He][0]);return this[Vt](),e}[ku](t,e){if(this[Ye])this[Ls]();else{let r=e;t===r.length||t===null?this[Ls]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[qe]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[qe]-=t)}return this.emit("data",e),!this[He].length&&!this[$t]&&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[$t]=!0,this.writable=!1,(this[Ge]||!this[hi])&&this[Vt](),this}[Ir](){this[Te]||(!this[Bn]&&!this[Qe].length&&(this[ot]=!0),this[hi]=!1,this[Ge]=!0,this.emit("resume"),this[He].length?this[Os]():this[$t]?this[Vt]():this.emit("drain"))}resume(){return this[Ir]()}pause(){this[Ge]=!1,this[hi]=!0,this[ot]=!1}get destroyed(){return this[Te]}get flowing(){return this[Ge]}get paused(){return this[hi]}[Za](t){this[Ye]?this[qe]+=1:this[qe]+=t.length,this[He].push(t)}[Ls](){return this[Ye]?this[qe]-=1:this[qe]-=this[He][0].length,this[He].shift()}[Os](t=!1){do;while(this[Tu](this[Ls]())&&this[He].length);!t&&!this[He].length&&!this[$t]&&this.emit("drain")}[Tu](t){return this.emit("data",t),this[Ge]}pipe(t,e){if(this[Te])return t;this[ot]=!1;let r=this[hn];return e=e||{},t===Au.stdout||t===Au.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Qe].push(e.proxyErrors?new iw(this,t,e):new cf(this,t,e)),this[Ct]?gi(()=>this[Ir]()):this[Ir]()),t}unpipe(t){let e=this[Qe].find(r=>r.dest===t);e&&(this[Qe].length===1?(this[Ge]&&this[Bn]===0&&(this[Ge]=!1),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[ot]=!1,this[Bn]++,!this[Qe].length&&!this[Ge]&&this[Ir]();else if(t==="readable"&&this[qe]!==0)super.emit("readable");else if(tw(t)&&this[hn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[xi]){let i=e;this[Ct]?gi(()=>i.call(this,this[xi])):i.call(this,this[xi])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Bn]=this.listeners("data").length,this[Bn]===0&&!this[ot]&&!this[Qe].length&&(this[Ge]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Bn]=0,!this[ot]&&!this[Qe].length&&(this[Ge]=!1)),e}get emittedEnd(){return this[hn]}[Vt](){!this[Cs]&&!this[hn]&&!this[Te]&&this[He].length===0&&this[$t]&&(this[Cs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ds]&&this.emit("close"),this[Cs]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Te&&this[Te])return!1;if(t==="data")return!this[Ye]&&!r?!1:this[Ct]?(gi(()=>this[Xa](r)),!0):this[Xa](r);if(t==="end")return this[Ru]();if(t==="close"){if(this[Ds]=!0,!this[hn]&&!this[Te])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[xi]=r,super.emit(Ya,r);let o=!this[pi]||this.listeners("error").length?super.emit("error",r):!1;return this[Vt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Vt](),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[Vt](),i}[Xa](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[Vt](),e}[Ru](){return this[hn]?!1:(this[hn]=!0,this.readable=!1,this[Ct]?(gi(()=>this[Qa]()),!0):this[Qa]())}[Qa](){if(this[yr]){let e=this[yr].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[vt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Te,()=>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[$t])return e();let i,o,c=h=>{this.off("data",d),this.off("end",u),this.off(Te,x),e(),o(h)},d=h=>{this.off("error",c),this.off("end",u),this.off(Te,x),this.pause(),i({value:h,done:!!this[$t]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Te,x),e(),i({done:!0,value:void 0})},x=()=>c(new Error("stream destroyed"));return new Promise((h,g)=>{o=g,i=h,this.once(Te,x),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(Ya,e),this.off(Te,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(Ya,e),this.once(Te,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Te])return t?this.emit("error",t):this.emit(Te),this;this[Te]=!0,this[ot]=!0,this[He].length=0,this[qe]=0;let e=this;return typeof e.close=="function"&&!this[Ds]&&e.close(),t?this.emit("error",t):this.emit(Te),this}static get isStream(){return Ym}},aw=it.writev,Sn=Symbol("_autoClose"),kt=Symbol("_close"),mi=Symbol("_ended"),le=Symbol("_fd"),tc=Symbol("_finished"),Xt=Symbol("_flags"),nc=Symbol("_flush"),Ec=Symbol("_handleChunk"),vc=Symbol("_makeBuf"),Ti=Symbol("_mode"),Ms=Symbol("_needDrain"),Pr=Symbol("_onerror"),Cr=Symbol("_onopen"),rc=Symbol("_onread"),Ar=Symbol("_onwrite"),In=Symbol("_open"),At=Symbol("_path"),_n=Symbol("_pos"),Dt=Symbol("_queue"),kr=Symbol("_read"),ic=Symbol("_readSize"),Yt=Symbol("_reading"),wi=Symbol("_remain"),sc=Symbol("_size"),Ks=Symbol("_write"),zn=Symbol("_writing"),$s=Symbol("_defaultFlag"),Wn=Symbol("_errored"),jc=class extends Jn{[Wn]=!1;[le];[At];[ic];[Yt]=!1;[sc];[wi];[Sn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Wn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[At]=t,this[ic]=e.readSize||16*1024*1024,this[Yt]=!1,this[sc]=typeof e.size=="number"?e.size:1/0,this[wi]=this[sc],this[Sn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[kr]():this[In]()}get fd(){return this[le]}get path(){return this[At]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[In](){it.open(this[At],"r",(t,e)=>this[Cr](t,e))}[Cr](t,e){t?this[Pr](t):(this[le]=e,this.emit("open",e),this[kr]())}[vc](){return Buffer.allocUnsafe(Math.min(this[ic],this[wi]))}[kr](){if(!this[Yt]){this[Yt]=!0;let t=this[vc]();if(t.length===0)return process.nextTick(()=>this[rc](null,0,t));it.read(this[le],t,0,t.length,null,(e,r,i)=>this[rc](e,r,i))}}[rc](t,e,r){this[Yt]=!1,t?this[Pr](t):this[Ec](e,r)&&this[kr]()}[kt](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Pr](t){this[Yt]=!0,this[kt](),this.emit("error",t)}[Ec](t,e){let r=!1;return this[wi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[wi]<=0)&&(r=!1,this[kt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[kr](),!1;case"error":return this[Wn]?!1:(this[Wn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},cw=class extends jc{[In](){let t=!0;try{this[Cr](null,it.openSync(this[At],"r")),t=!1}finally{t&&this[kt]()}}[kr](){let t=!0;try{if(!this[Yt]){this[Yt]=!0;do{let e=this[vc](),r=e.length===0?0:it.readSync(this[le],e,0,e.length,null);if(!this[Ec](r,e))break}while(!0);this[Yt]=!1}t=!1}finally{t&&this[kt]()}}[kt](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}},co=class extends Jm{readable=!1;writable=!0;[Wn]=!1;[zn]=!1;[mi]=!1;[Dt]=[];[Ms]=!1;[At];[Ti];[Sn];[le];[$s];[Xt];[tc]=!1;[_n];constructor(t,e){e=e||{},super(e),this[At]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Ti]=e.mode===void 0?438:e.mode,this[_n]=typeof e.start=="number"?e.start:void 0,this[Sn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[_n]!==void 0?"r+":"w";this[$s]=e.flags===void 0,this[Xt]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[In]()}emit(t,...e){if(t==="error"){if(this[Wn])return!1;this[Wn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[At]}[Pr](t){this[kt](),this[zn]=!0,this.emit("error",t)}[In](){it.open(this[At],this[Xt],this[Ti],(t,e)=>this[Cr](t,e))}[Cr](t,e){this[$s]&&this[Xt]==="r+"&&t&&t.code==="ENOENT"?(this[Xt]="w",this[In]()):t?this[Pr](t):(this[le]=e,this.emit("open",e),this[zn]||this[nc]())}end(t,e){return t&&this.write(t,e),this[mi]=!0,!this[zn]&&!this[Dt].length&&typeof this[le]=="number"&&this[Ar](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[mi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[zn]||this[Dt].length?(this[Dt].push(t),this[Ms]=!0,!1):(this[zn]=!0,this[Ks](t),!0)}[Ks](t){it.write(this[le],t,0,t.length,this[_n],(e,r)=>this[Ar](e,r))}[Ar](t,e){t?this[Pr](t):(this[_n]!==void 0&&typeof e=="number"&&(this[_n]+=e),this[Dt].length?this[nc]():(this[zn]=!1,this[mi]&&!this[tc]?(this[tc]=!0,this[kt](),this.emit("finish")):this[Ms]&&(this[Ms]=!1,this.emit("drain"))))}[nc](){if(this[Dt].length===0)this[mi]&&this[Ar](null,0);else if(this[Dt].length===1)this[Ks](this[Dt].pop());else{let t=this[Dt];this[Dt]=[],aw(this[le],t,this[_n],(e,r)=>this[Ar](e,r))}}[kt](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},df=class extends co{[In](){let t;if(this[$s]&&this[Xt]==="r+")try{t=it.openSync(this[At],this[Xt],this[Ti])}catch(e){if(e?.code==="ENOENT")return this[Xt]="w",this[In]();throw e}else t=it.openSync(this[At],this[Xt],this[Ti]);this[Cr](null,t)}[kt](){if(this[Sn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,it.closeSync(t),this.emit("close")}}[Ks](t){let e=!0;try{this[Ar](null,it.writeSync(this[le],t,0,t.length,this[_n])),e=!1}finally{if(e)try{this[kt]()}catch{}}}},uw=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"]]),fw=t=>!!t.sync&&!!t.file,xw=t=>!t.sync&&!!t.file,hw=t=>!!t.sync&&!t.file,pw=t=>!t.sync&&!t.file,gw=t=>!!t.file,mw=t=>uw.get(t)||t,Wc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=mw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Bi=(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 x=Wc(c);if(o?.(x,d),fw(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(x,d)}else if(xw(x)){let h=e(x,d);return u?h.then(()=>u(),u):h}else if(hw(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(x,d)}else if(pw(x)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(x,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),yw=_w.constants||{ZLIB_VERNUM:4736},Mt=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},yw)),bw=Kn.concat,Cu=Object.getOwnPropertyDescriptor(Kn,"concat"),Ew=t=>t,oc=Cu?.writable===!0||Cu?.set!==void 0?t=>{Kn.concat=t?Ew:bw}:t=>{},$n=Symbol("_superWrite"),Bs=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"}},ac=Symbol("flushFlag"),Kc=class extends Jn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Pu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Pu[e](t)}catch(r){throw new Bs(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 Bs(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Sc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Kn.alloc(0),{[ac]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[$n](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Kn.from(t,e)),this.#e)return;Sc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},oc(!0);let d;try{let x=typeof t[ac]=="number"?t[ac]:this.#r;d=this.#t._processChunk(t,x),oc(!1)}catch(x){oc(!1),this.#o(new Bs(x,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",x=>this.#o(new Bs(x,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let x=d[0];u=this[$n](Kn.from(x));for(let h=1;h<d.length;h++)u=this[$n](d[h])}else u=this[$n](Kn.from(d));return r&&r(),u}},uf=class extends Kc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Mt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Mt.Z_FINISH,t.fullFlushFlag=Mt.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(Mt.Z_SYNC_FLUSH),Sc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},vw=class extends uf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[$n](t){return this.#e?(this.#e=!1,t[9]=255,super[$n](t)):super[$n](t)}},Sw=class extends uf{constructor(t){super(t,"Unzip")}},ff=class extends Kc{constructor(t,e){t=t||{},t.flush=t.flush||Mt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Mt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Mt.BROTLI_OPERATION_FLUSH,super(t,e)}},Iw=class extends ff{constructor(t){super(t,"BrotliCompress")}},Aw=class extends ff{constructor(t){super(t,"BrotliDecompress")}},xf=class extends Kc{constructor(t,e){t=t||{},t.flush=t.flush||Mt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Mt.ZSTD_e_end,t.fullFlushFlag=Mt.ZSTD_e_flush,super(t,e)}},kw=class extends xf{constructor(t){super(t,"ZstdCompress")}},Tw=class extends xf{constructor(t){super(t,"ZstdDecompress")}},Rw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Cw(t,e):Pw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Pw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Cw=(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]=hf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=pf(o))}},Dw=t=>{let e=t[0],r=e===128?Lw(t.subarray(1,t.length)):e===255?Ow(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},Ow=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=hf(c):c===0?d=c:(i=!0,d=pf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},Lw=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},hf=t=>(255^t)&255,pf=t=>(255^t)+1&255,Nw={};Vm(Nw,{code:()=>$c,isCode:()=>Vs,isName:()=>Mw,name:()=>lo,normalFsTypes:()=>gf});var Vs=t=>lo.has(t),Mw=t=>$c.has(t),gf=new Set(["0","","1","2","3","4","5","6","7","D"]),lo=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),$c=new Map(Array.from(lo).map(t=>[t[1],t[0]])),Vn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,i){Buffer.isBuffer(t)?this.decode(t,e||0,r,i):t&&this.#n(t)}decode(t,e,r,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Fn(t,e+156,1),c=gf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Fn(t,e,100),this.mode=d?.mode??u?.mode??yn(t,e+100,8),this.uid=d?.uid??u?.uid??yn(t,e+108,8),this.gid=d?.gid??u?.gid??yn(t,e+116,8),this.size=d?.size??u?.size??yn(t,e+124,12),this.mtime=d?.mtime??u?.mtime??cc(t,e+136,12),this.cksum=yn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Vs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Fn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Fn(t,e+265,32),this.gname=d?.gname??u?.gname??Fn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??yn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??yn(t,e+337,8)??0,t[e+475]!==0){let h=Fn(t,e+345,155);this.path=h+"/"+this.path}else{let h=Fn(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=r?.atime??i?.atime??cc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??cc(t,e+488,12)}let x=256;for(let h=e;h<e+148;h++)x+=t[h];for(let h=e+156;h<e+512;h++)x+=t[h];this.cksumValid=x===this.cksum,this.cksum===void 0&&x===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="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=Bw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Un(t,e,100,o)||this.needPax,this.needPax=bn(t,e+100,8,this.mode)||this.needPax,this.needPax=bn(t,e+108,8,this.uid)||this.needPax,this.needPax=bn(t,e+116,8,this.gid)||this.needPax,this.needPax=bn(t,e+124,12,this.size)||this.needPax,this.needPax=dc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Un(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Un(t,e+265,32,this.uname)||this.needPax,this.needPax=Un(t,e+297,32,this.gname)||this.needPax,this.needPax=bn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=bn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Un(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Un(t,e+345,155,c)||this.needPax:(this.needPax=Un(t,e+345,130,c)||this.needPax,this.needPax=dc(t,e+476,12,this.atime)||this.needPax,this.needPax=dc(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,bn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:lo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String($c.get(t));if(Vs(e)||e==="Unsupported")this.#e=e;else if(Vs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Bw=(t,e)=>{let r=t,i="",o,c=br.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=br.dirname(r),r=br.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=br.join(br.basename(i),r),i=br.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Fn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),cc=(t,e,r)=>zw(yn(t,e,r)),zw=t=>t===void 0?void 0:new Date(t*1e3),yn=(t,e,r)=>Number(t[e])&128?Dw(t.subarray(e,e+r)):Uw(t,e,r),Fw=t=>isNaN(t)?void 0:t,Uw=(t,e,r)=>Fw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Gw={12:8589934591,8:2097151},bn=(t,e,r,i)=>i===void 0?!1:i>Gw[r]||i<0?(Rw(i,t.subarray(e,e+r)),!0):(Hw(t,e,r,i),!1),Hw=(t,e,r,i)=>t.write(qw(i,r),e,r,"ascii"),qw=(t,e)=>jw(Math.floor(t).toString(8),e),jw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",dc=(t,e,r,i)=>i===void 0?!1:bn(t,e,r,i.getTime()/1e3),Ww=new Array(156).join("\0"),Un=(t,e,r,i)=>i===void 0?!1:(t.write(i+Ww,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),ro=class mf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),i=512*Math.ceil(1+r/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new Vn({path:("PaxHeader/"+Kw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+o}static parse(e,r,i=!1){return new mf($w(Vw(e),r),i)}},$w=(t,e)=>e?Object.assign({},e,t):t,Vw=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(Jw,Object.create(null)),Jw=(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},Zw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=Zw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Yw=class extends Jn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},uo=(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))},Xw=1024*1024,Ic=Buffer.from([31,139]),Ac=Buffer.from([40,181,47,253]),Qw=Math.max(Ic.length,Ac.length),pt=Symbol("state"),Gn=Symbol("writeEntry"),Jt=Symbol("readEntry"),lc=Symbol("nextEntry"),Du=Symbol("processEntry"),Ot=Symbol("extendedHeader"),_i=Symbol("globalExtendedHeader"),pn=Symbol("meta"),Ou=Symbol("emitMeta"),me=Symbol("buffer"),Zt=Symbol("queue"),gn=Symbol("ended"),uc=Symbol("emittedEnd"),Hn=Symbol("emit"),De=Symbol("unzip"),zs=Symbol("consumeChunk"),Fs=Symbol("consumeChunkSub"),fc=Symbol("consumeBody"),Lu=Symbol("consumeMeta"),Nu=Symbol("consumeHeader"),yi=Symbol("consuming"),xc=Symbol("bufferConcat"),Us=Symbol("maybeEnd"),Er=Symbol("writing"),mn=Symbol("aborted"),Gs=Symbol("onDone"),qn=Symbol("sawValidEntry"),Hs=Symbol("sawNullBlock"),qs=Symbol("sawEOF"),Mu=Symbol("closeStream"),e_=()=>!0,Mi=class extends ww{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[Zt]=[];[me];[Jt];[Gn];[pt]="begin";[pn]="";[Ot];[_i];[gn]=!1;[De];[mn]=!1;[qn];[Hs]=!1;[qs]=!1;[Er]=!1;[yi]=!1;[uc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Gs,()=>{(this[pt]==="begin"||this[qn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Gs,t.ondone):this.on(Gs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Xw,this.filter=typeof t.filter=="function"?t.filter:e_;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[Mu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){uo(this,t,e,r)}[Nu](t,e){this[qn]===void 0&&(this[qn]=!1);let r;try{r=new Vn(t,e,this[Ot],this[_i])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Hs]?(this[qs]=!0,this[pt]==="begin"&&(this[pt]="header"),this[Hn]("eof")):(this[Hs]=!0,this[Hn]("nullBlock"));else if(this[Hs]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[Gn]=new Yw(r,this[Ot],this[_i]);if(!this[qn])if(o.remain){let c=()=>{o.invalid||(this[qn]=!0)};o.on("end",c)}else this[qn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Hn]("ignoredEntry",o),this[pt]="ignore",o.resume()):o.size>0&&(this[pn]="",o.on("data",c=>this[pn]+=c),this[pt]="meta"):(this[Ot]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Hn]("ignoredEntry",o),this[pt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[pt]="body":(this[pt]="header",o.end()),this[Jt]?this[Zt].push(o):(this[Zt].push(o),this[lc]())))}}}[Mu](){queueMicrotask(()=>this.emit("close"))}[Du](t){let e=!0;if(!t)this[Jt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[lc]()),e=!1);return e}[lc](){do;while(this[Du](this[Zt].shift()));if(this[Zt].length===0){let t=this[Jt];!t||t.flowing||t.size===t.remain?this[Er]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[fc](t,e){let r=this[Gn];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[pt]="header",this[Gn]=void 0,r.end()),o.length}[Lu](t,e){let r=this[Gn],i=this[fc](t,e);return!this[Gn]&&r&&this[Ou](r),i}[Hn](t,e,r){this[Zt].length===0&&!this[Jt]?this.emit(t,e,r):this[Zt].push([t,e,r])}[Ou](t){switch(this[Hn]("meta",this[pn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ot]=ro.parse(this[pn],this[Ot],!1);break;case"GlobalExtendedHeader":this[_i]=ro.parse(this[pn],this[_i],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ot]??Object.create(null);this[Ot]=e,e.path=this[pn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ot]||Object.create(null);this[Ot]=e,e.linkpath=this[pn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[mn]=!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[mn])return r?.(),!1;if((this[De]===void 0||this.brotli===void 0&&this[De]===!1)&&t){if(this[me]&&(t=Buffer.concat([this[me],t]),this[me]=void 0),t.length<Qw)return this[me]=t,r?.(),!0;for(let d=0;this[De]===void 0&&d<Ic.length;d++)t[d]!==Ic[d]&&(this[De]=!1);let o=!1;if(this[De]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Ac.length;d++)if(t[d]!==Ac[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[De]===!1&&c)if(t.length<512)if(this[gn])this.brotli=!0;else return this[me]=t,r?.(),!0;else try{new Vn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[De]===void 0||this[De]===!1&&(this.brotli||o)){let d=this[gn];this[gn]=!1,this[De]=this[De]===void 0?new Sw({}):o?new Tw({}):new Aw({}),this[De].on("data",x=>this[zs](x)),this[De].on("error",x=>this.abort(x)),this[De].on("end",()=>{this[gn]=!0,this[zs]()}),this[Er]=!0;let u=!!this[De][d?"end":"write"](t);return this[Er]=!1,r?.(),u}}this[Er]=!0,this[De]?this[De].write(t):this[zs](t),this[Er]=!1;let i=this[Zt].length>0?!1:this[Jt]?this[Jt].flowing:!0;return!i&&this[Zt].length===0&&this[Jt]?.once("drain",()=>this.emit("drain")),r?.(),i}[xc](t){t&&!this[mn]&&(this[me]=this[me]?Buffer.concat([this[me],t]):t)}[Us](){if(this[gn]&&!this[uc]&&!this[mn]&&!this[yi]){this[uc]=!0;let t=this[Gn];if(t&&t.blockRemain){let e=this[me]?this[me].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[me]&&t.write(this[me]),t.end()}this[Hn](Gs)}}[zs](t){if(this[yi]&&t)this[xc](t);else if(!t&&!this[me])this[Us]();else if(t){if(this[yi]=!0,this[me]){this[xc](t);let e=this[me];this[me]=void 0,this[Fs](e)}else this[Fs](t);for(;this[me]&&this[me]?.length>=512&&!this[mn]&&!this[qs];){let e=this[me];this[me]=void 0,this[Fs](e)}this[yi]=!1}(!this[me]||this[gn])&&this[Us]()}[Fs](t){let e=0,r=t.length;for(;e+512<=r&&!this[mn]&&!this[qs];)switch(this[pt]){case"begin":case"header":this[Nu](t,e),e+=512;break;case"ignore":case"body":e+=this[fc](t,e);break;case"meta":e+=this[Lu](t,e);break;default:throw new Error("invalid state: "+this[pt])}e<r&&(this[me]=this[me]?Buffer.concat([t.subarray(e),this[me]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[mn]||(this[De]?(t&&this[De].write(t),this[De].end()):(this[gn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Us]())),this}},Ri=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},t_=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},wf=(t,e)=>{let r=new Map(e.map(c=>[Ri(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||lw(c).root||".",x;if(c===u)x=!1;else{let h=r.get(c);x=h!==void 0?h:o(dw(c),u)}return r.set(c,x),x};t.filter=i?(c,d)=>i(c,d)&&o(Ri(c)):c=>o(Ri(c))},n_=t=>{let e=new Mi(t),r=t.file,i;try{i=Tr.openSync(r,"r");let o=Tr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Tr.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 x=Tr.readSync(i,u,0,c,d);if(x===0)break;d+=x,e.write(u.subarray(0,x))}e.end()}}finally{if(typeof i=="number")try{Tr.closeSync(i)}catch{}}},r_=(t,e)=>{let r=new Mi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Tr.stat(o,(u,x)=>{if(u)d(u);else{let h=new jc(o,{readSize:i,size:x.size});h.on("error",d),h.pipe(r)}})})},Dr=Bi(n_,r_,t=>new Mi(t),t=>new Mi(t),(t,e)=>{e?.length&&wf(t,e),t.noResume||t_(t)}),_f=(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:s_,parse:zu}=i_,Vc=t=>{let e="",r=zu(t);for(;s_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=zu(t)}return[e,t]},fo=["|","<",">","?",":"],Jc=fo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),o_=new Map(fo.map((t,e)=>[t,Jc[e]])),a_=new Map(Jc.map((t,e)=>[t,fo[e]])),Fu=t=>fo.reduce((e,r)=>e.split(r).join(o_.get(r)),t),c_=t=>Jc.reduce((e,r)=>e.split(r).join(a_.get(r)),t),yf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ri(e)+"/"+t):Q(t),d_=16*1024*1024,Uu=Symbol("process"),Gu=Symbol("file"),Hu=Symbol("directory"),kc=Symbol("symlink"),qu=Symbol("hardlink"),bi=Symbol("header"),Js=Symbol("read"),Tc=Symbol("lstat"),Zs=Symbol("onlstat"),Rc=Symbol("onread"),Pc=Symbol("onreadlink"),Cc=Symbol("openfile"),Dc=Symbol("onopenfile"),En=Symbol("close"),so=Symbol("mode"),Oc=Symbol("awaitDrain"),hc=Symbol("ondrain"),Nt=Symbol("prefix"),bf=class extends Jn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Wc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||d_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Q(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Q(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Vc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=c_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||Bu.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[Zs](o):this[Tc]()}warn(t,e,r={}){return uo(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Tc](){Lt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Zs](e)})}[Zs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=f_(t),this.emit("stat",t),this[Uu]()}[Uu](){switch(this.type){case"File":return this[Gu]();case"Directory":return this[Hu]();case"SymbolicLink":return this[kc]();default:return this.end()}}[so](t){return _f(t,this.type==="Directory",this.portable)}[Nt](t){return yf(t,this.prefix)}[bi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Vn({path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](this.linkpath):this.linkpath,mode:this[so](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 ro({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[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](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)}[Hu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[bi](),this.end()}[kc](){Lt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Pc](e)})}[Pc](t){this.linkpath=Q(t),this[bi](),this.end()}[qu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Bu.relative(this.cwd,t)),this.stat.size=0,this[bi](),this.end()}[Gu](){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[qu](e);this.linkCache.set(t,this.absolute)}if(this[bi](),this.stat.size===0)return this.end();this[Cc]()}[Cc](){Lt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Dc](e)})}[Dc](t){if(this.fd=t,this.#e)return this[En]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Js]()}[Js](){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");Lt.read(t,e,r,i,o,(c,d)=>{if(c)return this[En](()=>this.emit("error",c));this[Rc](d)})}[En](t=()=>{}){this.fd!==void 0&&Lt.close(this.fd,t)}[Rc](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[En](()=>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[En](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[hc]():this[Oc](()=>this[hc]())}[Oc](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[hc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[En](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Js]()}},l_=class extends bf{sync=!0;[Tc](){this[Zs](Lt.lstatSync(this.absolute))}[kc](){this[Pc](Lt.readlinkSync(this.absolute))}[Cc](){this[Dc](Lt.openSync(this.absolute,"r"))}[Js](){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=Lt.readSync(e,r,i,o,c);this[Rc](d),t=!1}finally{if(t)try{this[En](()=>{})}catch{}}}[Oc](t){t()}[En](t=()=>{}){this.fd!==void 0&&Lt.closeSync(this.fd),t()}},u_=class extends Jn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return uo(this,t,e,r)}constructor(t,e={}){let r=Wc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[so](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Vc(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Vn({path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](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 ro({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[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](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)}[Nt](t){return yf(t,this.prefix)}[so](t){return _f(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}},f_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",x_=class Rr{tail;head;length=0;static create(e=[]){return new Rr(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++)p_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)g_(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 Rr;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 Rr;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 Rr;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 Rr;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=h_(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 h_(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 p_(t,e){t.tail=new Zc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function g_(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}},Wu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Ku=Buffer.alloc(1024),Ys=Symbol("onStat"),Ei=Symbol("ended"),St=Symbol("queue"),vi=Symbol("pendingLinks"),wn=Symbol("current"),jn=Symbol("process"),Si=Symbol("processing"),js=Symbol("processJob"),It=Symbol("jobs"),pc=Symbol("jobDone"),Xs=Symbol("addFSEntry"),$u=Symbol("addTarEntry"),Lc=Symbol("stat"),Nc=Symbol("readdir"),Qs=Symbol("onreaddir"),eo=Symbol("pipe"),Vu=Symbol("entry"),gc=Symbol("entryOpt"),to=Symbol("writeEntryClass"),Ef=Symbol("write"),mc=Symbol("ondrain"),xo=class extends Jn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[to];onWriteEntry;[St];[vi]=new Map;[It]=0;[Si]=!1;[Ei]=!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[to]=bf,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 vw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Iw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new kw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[mc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[mc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[St]=new x_,this[It]=0,this.jobs=Number(t.jobs)||4,this[Si]=!1,this[Ei]=!1}[Ef](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[Ei]=!0,this[jn](),r&&r(),this}write(t){if(this[Ei])throw new Error("write after end");return typeof t=="string"?this[Xs](t):this[$u](t),this.flowing}[$u](t){let e=Q(ju.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Wu(t.path,e);r.entry=new u_(t,this[gc](r)),r.entry.on("end",()=>this[pc](r)),this[It]+=1,this[St].push(r)}this[jn]()}[Xs](t){let e=Q(ju.resolve(this.cwd,t));this[St].push(new Wu(t,e)),this[jn]()}[Lc](t){t.pending=!0,this[It]+=1;let e=this.follow?"stat":"lstat";io[e](t.absolute,(r,i)=>{t.pending=!1,this[It]-=1,r?this.emit("error",r):this[Ys](t,i)})}[Ys](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[wn])this[js](t);else{let r=`${e.dev}:${e.ino}`,i=this[vi].get(r);i?i.push(t):this[vi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[jn]()}[Nc](t){t.pending=!0,this[It]+=1,io.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[It]-=1,e)return this.emit("error",e);this[Qs](t,r)})}[Qs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[jn]()}[jn](){if(!this[Si]){this[Si]=!0;for(let t=this[St].head;t&&this[It]<this.jobs;t=t.next)if(this[js](t.value),t.value.ignore){let e=t.next;this[St].removeNode(t),t.next=e}this[Si]=!1,this[Ei]&&this[St].length===0&&this[It]===0&&(this.zip?this.zip.end(Ku):(super.write(Ku),super.end()))}}get[wn](){return this[St]&&this[St].head&&this[St].head.value}[pc](t){this[St].shift(),this[It]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[vi].get(r);if(i){this[vi].delete(r);for(let o of i)o.pending=!1,this[js](o)}}this[jn]()}[js](t){if(t.pending&&t.pendingLink&&t===this[wn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[wn]&&!t.piped&&this[eo](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ys](t,e):this[Lc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Qs](t,e):this[Nc](t),!t.readdir)return}if(t.entry=this[Vu](t),!t.entry){t.ignore=!0;return}t===this[wn]&&!t.piped&&this[eo](t)}}}[gc](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[Vu](t){this[It]+=1;try{return new this[to](t.path,this[gc](t)).on("end",()=>this[pc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[mc](){this[wn]&&this[wn].entry&&this[wn].entry.resume()}[eo](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Xs](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){uo(this,t,e,r)}},Yc=class extends xo{sync=!0;constructor(t){super(t),this[to]=l_}pause(){}resume(){}[Lc](t){let e=this.follow?"statSync":"lstatSync";this[Ys](t,io[e](t.absolute))}[Nc](t){this[Qs](t,io.readdirSync(t.absolute))}[eo](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Xs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[Ef](i)})}},m_=(t,e)=>{let r=new Yc(t),i=new df(t.file,{mode:t.mode||438});r.pipe(i),vf(r,e)},w_=(t,e)=>{let r=new xo(t),i=new co(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 Sf(r,e).catch(c=>r.emit("error",c)),o},vf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Dr({file:lf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},Sf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Dr({file:lf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},__=(t,e)=>{let r=new Yc(t);return vf(r,e),r},y_=(t,e)=>{let r=new xo(t);return Sf(r,e).catch(i=>r.emit("error",i)),r},Q1=Bi(m_,w_,__,y_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),E_=process.env.__FAKE_PLATFORM__||process.platform,Tf=E_==="win32",{O_CREAT:Rf,O_NOFOLLOW:Ju,O_TRUNC:Pf,O_WRONLY:Cf}=kf.constants,Df=Number(process.env.__FAKE_FS_O_FILENAME__)||kf.constants.UV_FS_O_FILEMAP||0,v_=Tf&&!!Df,S_=512*1024,I_=Df|Pf|Rf|Cf,Zu=!Tf&&typeof Ju=="number"?Ju|Pf|Rf|Cf:null,Of=Zu!==null?()=>Zu:v_?t=>t<S_?I_:"w":()=>"w",Mc=(t,e,r)=>{try{return ho.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},oo=(t,e,r,i)=>{ho.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},A_=(t,e,r,i,o)=>{if(e.isDirectory())Lf(Pi.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Pi.resolve(t,e.name);oo(d,r,i,o)});else{let c=Pi.resolve(t,e.name);oo(c,r,i,o)}},Lf=(t,e,r,i)=>{ho.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return oo(t,e,r,i);let d=c.length,u=null,x=h=>{if(!u){if(h)return i(u=h);if(--d===0)return oo(t,e,r,i)}};for(let h of c)A_(t,h,e,r,x)})},k_=(t,e,r,i)=>{e.isDirectory()&&Nf(Pi.resolve(t,e.name),r,i),Mc(Pi.resolve(t,e.name),r,i)},Nf=(t,e,r)=>{let i;try{i=ho.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Mc(t,e,r);throw c}for(let o of i)k_(t,o,e,r);return Mc(t,e,r)},Mf=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"}},po=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"}},R_=(t,e)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Mf(t,r?.code||"ENOTDIR")),e(r)})},P_=(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,x=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),h=e.preserve,g=e.unlink,_=Q(e.cwd),S=(v,I)=>{v?r(v):I&&x?Lf(I,d,u,A=>S(A)):c?ct.chmod(t,o,r):r()};if(t===_)return R_(t,S);if(h)return T_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let w=Q(ao.relative(_,t)).split("/");Bc(_,w,o,g,_,void 0,S)},Bc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),x=Q(ao.resolve(t+"/"+u));ct.mkdir(x,r,Bf(x,e,r,i,o,c,d))},Bf=(t,e,r,i,o,c,d)=>u=>{u?ct.lstat(t,(x,h)=>{if(x)x.path=x.path&&Q(x.path),d(x);else if(h.isDirectory())Bc(t,e,r,i,o,c,d);else if(i)ct.unlink(t,g=>{if(g)return d(g);ct.mkdir(t,r,Bf(t,e,r,i,o,c,d))});else{if(h.isSymbolicLink())return d(new po(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Bc(t,e,r,i,o,c,d))},C_=t=>{let e=!1,r;try{e=ct.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Mf(t,r??"ENOTDIR")}},D_=(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),x=e.preserve,h=e.unlink,g=Q(e.cwd),_=v=>{v&&u&&Nf(v,c,d),o&&ct.chmodSync(t,i)};if(t===g)return C_(g),_();if(x)return _(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=Q(ao.relative(g,t)).split("/"),w;for(let v=S.shift(),I=g;v&&(I+="/"+v);v=S.shift()){I=Q(ao.resolve(I));try{ct.mkdirSync(I,i),w=w||I}catch{let A=ct.lstatSync(I);if(A.isDirectory())continue;if(h){ct.unlinkSync(I),ct.mkdirSync(I,i),w=w||I;continue}else if(A.isSymbolicLink())return new po(I,I+"/"+S.join("/"))}}return _(w)},wc=Object.create(null),Yu=1e4,vr=new Set,O_=t=>{vr.has(t)?vr.delete(t):wc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),vr.add(t);let e=wc[t],r=vr.size-Yu;if(r>Yu/10){for(let i of vr)if(vr.delete(i),delete wc[i],--r<=0)break}return e},L_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,N_=L_==="win32",M_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=zf(i,r)),e.push(r||"/"),e},[]),B_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=N_?["win32 parallelization disabled"]:t.map(i=>Ri(zf(O_(i))));let r=new Set(t.map(i=>M_(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 x of u)o.add(x)}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 x=d[0];typeof x=="function"&&o.add(x)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},z_=()=>process.umask(),Xu=Symbol("onEntry"),zc=Symbol("checkFs"),Qu=Symbol("checkFs2"),Fc=Symbol("isReusable"),gt=Symbol("makeFs"),Uc=Symbol("file"),Gc=Symbol("directory"),no=Symbol("link"),ef=Symbol("symlink"),tf=Symbol("hardlink"),ki=Symbol("ensureNoSymlink"),nf=Symbol("unsupported"),rf=Symbol("checkPath"),_c=Symbol("stripAbsolutePath"),vn=Symbol("mkdir"),je=Symbol("onError"),Ws=Symbol("pending"),sf=Symbol("pend"),Sr=Symbol("unpend"),yc=Symbol("ended"),bc=Symbol("maybeClose"),Hc=Symbol("skip"),Ci=Symbol("doChown"),Di=Symbol("uid"),Oi=Symbol("gid"),Li=Symbol("checkedCwd"),F_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ni=F_==="win32",U_=1024,G_=(t,e)=>{if(!Ni)return se.unlink(t,e);let r=t+".DELETE."+Af(16).toString("hex");se.rename(t,r,i=>{if(i)return e(i);se.unlink(r,e)})},H_=t=>{if(!Ni)return se.unlinkSync(t);let e=t+".DELETE."+Af(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},of=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Xc=class extends Mi{[yc]=!1;[Li]=!1;[Ws]=0;reservations=new B_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[yc]=!0,this[bc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&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:U_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ni,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Be.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:z_():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[Xu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[bc](){this[yc]&&this[Ws]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[_c](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Vc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Ni&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Be.posix.dirname(t.path),x=Be.posix.normalize(Be.posix.join(u,d.join("/")));if(x.startsWith("../")||x==="..")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}[rf](t){let e=Q(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[_c](t,"path")||!this[_c](t,"linkpath"))return!1;if(t.absolute=Be.isAbsolute(t.path)?Q(Be.resolve(t.path)):Q(Be.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Be.win32.parse(String(t.absolute));t.absolute=i+Fu(String(t.absolute).slice(i.length));let{root:o}=Be.win32.parse(t.path);t.path=o+Fu(t.path.slice(o.length))}return!0}[Xu](t){if(!this[rf](t))return t.resume();switch(b_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[zc](t);default:return this[nf](t)}}[je](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Sr](),e.resume())}[vn](t,e,r){P_(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)}[Ci](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}[Di](t){return of(this.uid,t.uid,this.processUid)}[Oi](t){return of(this.gid,t.gid,this.processGid)}[Uc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new co(String(t.absolute),{flags:Of(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,x=>{x?this[je](x,t):this[Sr](),e()})};i.on("finish",()=>{let u=String(t.absolute),x=i.fd;if(typeof x=="number"&&t.mtime&&!this.noMtime){o++;let h=t.atime||new Date,g=t.mtime;se.futimes(x,h,g,_=>_?se.utimes(u,h,g,S=>c(S&&_)):c())}if(typeof x=="number"&&this[Ci](t)){o++;let h=this[Di](t),g=this[Oi](t);typeof h=="number"&&typeof g=="number"&&se.fchown(x,h,g,_=>_?se.chown(u,h,g,S=>c(S&&_)):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)}[Gc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[vn](String(t.absolute),r,i=>{if(i){this[je](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[Sr](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ci](t)&&(o++,se.chown(String(t.absolute),Number(this[Di](t)),Number(this[Oi](t)),c)),c()})}[nf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[ef](t,e){let r=Q(Be.relative(this.cwd,Be.resolve(Be.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[ki](t,this.cwd,r,()=>this[no](t,String(t.linkpath),"symlink",e),i=>{this[je](i,t),e()})}[tf](t,e){let r=Q(Be.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[ki](t,this.cwd,i,()=>this[no](t,r,"link",e),o=>{this[je](o,t),e()})}[ki](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Be.resolve(e,c);se.lstat(d,(u,x)=>{if(u)return i();if(x?.isSymbolicLink())return o(new po(d,Be.resolve(d,r.join("/"))));this[ki](t,d,r,i,o)})}[sf](){this[Ws]++}[Sr](){this[Ws]--,this[bc]()}[Hc](t){this[Sr](),t.resume()}[Fc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ni}[zc](t){this[sf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Qu](t,r))}[Qu](t,e){let r=d=>{e(d)},i=()=>{this[vn](this.cwd,this.dmode,d=>{if(d){this[je](d,t),r();return}this[Li]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Be.dirname(String(t.absolute)));if(d!==this.cwd)return this[vn](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[Hc](t),r();return}if(d||this[Fc](t,u))return this[gt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let x=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=g=>this[gt](g??null,t,r);return x?se.chmod(String(t.absolute),Number(t.mode),h):h()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),x=>this[gt](x??null,t,r))}if(t.absolute===this.cwd)return this[gt](null,t,r);G_(String(t.absolute),x=>this[gt](x??null,t,r))})};this[Li]?o():i()}[gt](t,e,r){if(t){this[je](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Uc](e,r);case"Link":return this[tf](e,r);case"SymbolicLink":return this[ef](e,r);case"Directory":case"GNUDumpDir":return this[Gc](e,r)}}[no](t,e,r,i){se[r](e,String(t.absolute),o=>{o?this[je](o,t):(this[Sr](),t.resume()),i()})}},Ii=t=>{try{return[null,t()]}catch(e){return[e,null]}},Ff=class extends Xc{sync=!0;[gt](t,e){return super[gt](t,e,()=>{})}[zc](t){if(!this[Li]){let o=this[vn](this.cwd,this.dmode);if(o)return this[je](o,t);this[Li]=!0}if(t.absolute!==this.cwd){let o=Q(Be.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[vn](o,this.dmode);if(c)return this[je](c,t)}}let[e,r]=Ii(()=>se.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Hc](t);if(e||this[Fc](t,r))return this[gt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?Ii(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[gt](d,t)}let[o]=Ii(()=>se.rmdirSync(String(t.absolute)));this[gt](o,t)}let[i]=t.absolute===this.cwd?[]:Ii(()=>H_(String(t.absolute)));this[gt](i,t)}[Uc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(o)}catch(x){u=x}(d||u)&&this[je](d||u,t),e()},o;try{o=se.openSync(String(t.absolute),Of(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,x=t.mtime;try{se.futimesSync(o,u,x)}catch(h){try{se.utimesSync(String(t.absolute),u,x)}catch{d=h}}}if(this[Ci](t)){let u=this[Di](t),x=this[Oi](t);try{se.fchownSync(o,Number(u),Number(x))}catch(h){try{se.chownSync(String(t.absolute),Number(u),Number(x))}catch{d=d||h}}}i(d)})}[Gc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[vn](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[Ci](t))try{se.chownSync(String(t.absolute),Number(this[Di](t)),Number(this[Oi](t)))}catch{}e(),t.resume()}[vn](t,e){try{return D_(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}}[ki](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Be.resolve(c,d);let[u,x]=Ii(()=>se.lstatSync(c));if(u)return i();if(x.isSymbolicLink())return o(new po(c,Be.resolve(e,r.join("/"))))}i()}[no](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)}}},q_=t=>{let e=new Ff(t),r=t.file,i=If.statSync(r),o=t.maxReadSize||16*1024*1024;new cw(r,{readSize:o,size:i.size}).pipe(e)},j_=(t,e)=>{let r=new Xc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),If.stat(o,(u,x)=>{if(u)d(u);else{let h=new jc(o,{readSize:i,size:x.size});h.on("error",d),h.pipe(r)}})})},Uf=Bi(q_,j_,t=>new Ff(t),t=>new Xc(t),(t,e)=>{e?.length&&wf(t,e)}),W_=(t,e)=>{let r=new Yc(t),i=!0,o,c;try{try{o=at.openSync(t.file,"r+")}catch(x){if(x?.code==="ENOENT")o=at.openSync(t.file,"w+");else throw x}let d=at.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let g=0,_=0;g<512;g+=_){if(_=at.readSync(o,u,g,u.length-g,c+g),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!_)break e}let x=new Vn(u);if(!x.cksumValid)break;let h=512*Math.ceil((x.size||0)/512);if(c+h+512>d.size)break;c+=h,t.mtimeCache&&x.mtime&&t.mtimeCache.set(String(x.path),x.mtime)}i=!1,K_(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},K_=(t,e,r,i,o)=>{let c=new df(t.file,{fd:i,start:r});e.pipe(c),V_(e,o)},$_=(t,e)=>{e=Array.from(e);let r=new xo(t),i=(o,c,d)=>{let u=(S,w)=>{S?at.close(o,v=>d(S)):d(null,w)},x=0;if(c===0)return u(null,0);let h=0,g=Buffer.alloc(512),_=(S,w)=>{if(S||w===void 0)return u(S);if(h+=w,h<512&&w)return at.read(o,g,h,g.length-h,x+h,_);if(x===0&&g[0]===31&&g[1]===139)return u(new Error("cannot append to compressed archives"));if(h<512)return u(null,x);let v=new Vn(g);if(!v.cksumValid)return u(null,x);let I=512*Math.ceil((v.size??0)/512);if(x+I+512>c||(x+=I+512,x>=c))return u(null,x);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),h=0,at.read(o,g,0,512,x,_)};at.read(o,g,0,512,x,_)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(x,h)=>{if(x&&x.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(x||!h)return c(x);at.fstat(h,(g,_)=>{if(g)return at.close(h,()=>c(g));i(h,_.size,(S,w)=>{if(S)return c(S);let v=new co(t.file,{fd:h,start:w});r.pipe(v),v.on("error",c),v.on("close",o),J_(r,e)})})};at.open(t.file,d,u)})},V_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Dr({file:Gf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},J_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Dr({file:Gf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},Ai=Bi(W_,$_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!gw(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")}),hA=Bi(Ai.syncFile,Ai.asyncFile,Ai.syncNoFile,Ai.asyncNoFile,(t,e=[])=>{Ai.validate?.(t,e),Z_(t)}),Z_=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))};Kt();var mt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function go(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Hf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function mo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function qf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function jf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Zn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Qt();$e();te();Ce();$e();function Or(t,e){if(go(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function zi(t){return t.startsWith("http://")||t.startsWith("https://")}function Lr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as sk}from"node:fs";import{dirname as ak,join as ck}from"node:path";import{fileURLToPath as lk}from"node:url";var Bt="0.2.3-alpha.9";import{mkdir as fy,rm as d0}from"node:fs/promises";import{join as qi}from"node:path";Wt();import{readFileSync as iy}from"node:fs";var sy=384;async function Qc(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await pr(t.agentEnvFile,r,{mode:sy})}function Fi(t){try{let e=JSON.parse(iy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Vf(t,e,r={},i=o=>o){return{...i({...t,...Fi(e)}),...r}}Wt();function Ui(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(oy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
92
92
  `)}
93
93
  `}function oy(t){if(t.includes(`
94
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ee();Re();import{homedir as dy}from"node:os";import{join as ly}from"node:path";We();ee();var go="1008033",$f="1289";var Vf="pbbp2",Jf="https://www.coze.cn",Zf="/api/coze_claw/resource/get_frontier_key",ay="https://www.coze.cn",cy="wss://frontier.coze.cn";function Cr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??ay}function Yf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??cy}function vn(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function zi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Fi=G("handshake");async function Xc(t){let e=Cr(t.endpoint),r=t.timeoutMs??1e4,i=`${Dr(e)}${Zf}?aid=${encodeURIComponent(go)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...vn(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),r);Fi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),f=u.headers.get("x-tt-logid")??"",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=${f}: ${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=${f}`);let w=g.data??{},S=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,y=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!S||!y){let v=JSON.stringify(g).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${v}`)}return Fi.info("handshake ok",{remoteDeviceId:y,logid:f,traceId:x}),{accessKey:S,deviceId:y}}catch(u){if(u instanceof T)throw Fi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Fi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Fi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var wo=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",St="auto",mo=15e4;function Qf(t){return{model:Qc(t.model)??St,...t.modelToken?{modelToken:t.modelToken}:{}}}function e0(t){return!t||t===St}var uy=new Set(["auto","\u81EA\u52A8"]);function Qc(t){let e=t?.trim();if(e)return uy.has(e.toLowerCase())?St:e}function t0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=wo,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||St;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))}else e0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function n0(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||St}"`):e0(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${wo}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let r=t.modelInfo?.contextWindow??mo;e.push("-c",`model_context_window=${r}`)}return e}function r0(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function _o(t,e){let{ttEnv:r,usePpe:i}=zi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function i0(t,e,r){if(!t.modelToken)return{};let i=_o(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
95
- `)}}function ed(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function td(t){return t.model||St}function Xf(t,e,r){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:r,maxTokens:8192,api:"openai-completions"}}function s0(t,e,r,i){if(!t.modelToken)return null;let o=td(t),c=_o(e,r),l=["text"];t.modelInfo?.capabilities?.image===!0&&l.push("image");let u=[Xf(o,l,t.modelInfo?.contextWindow??mo)],f=new Set([o]);for(let g of i??[])!g||f.has(g)||(f.add(g),u.push(Xf(g,["text"],mo)));let x={baseUrl:`${wo}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(x.headers=c),x}function o0(t,e,r){if(!t.modelToken)return[];let i=_o(e,r),o=[];for(let[c,l]of Object.entries(i))o.push("-c",`model_providers.coze.http_headers.${c}="${l}"`);return o}function nd(t,e,r){let i=_o(e,r),o=t.modelInfo?.contextWindow??mo,l=["model:"," provider: custom",` default: ${t.model||St}`,` base_url: ${wo}/v1`,` context_length: ${o}`];if(t.modelToken&&l.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){l.push(" default_headers:");for(let[u,f]of Object.entries(i))l.push(` ${u}: ${JSON.stringify(f)}`)}return l.push("skills:"),l.push(" external_dirs:"),l.push(` - ${ly(dy(),".hermes","skills")}`),`${l.join(`
94
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();Ce();import{homedir as dy}from"node:os";import{join as ly}from"node:path";$e();te();var wo="1008033",Jf="1289";var Zf="pbbp2",Yf="https://www.coze.cn",Xf="/api/coze_claw/resource/get_frontier_key",ay="https://www.coze.cn",cy="wss://frontier.coze.cn";function Nr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??ay}function Qf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??cy}function An(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Hi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Gi=q("handshake");async function ed(t){let e=Nr(t.endpoint),r=t.timeoutMs??1e4,i=`${Lr(e)}${Xf}?aid=${encodeURIComponent(wo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...An(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Gi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),x=u.headers.get("x-tt-logid")??"",h=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=${x}: ${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=${x}`);let _=g.data??{},S=typeof _.access_key=="string"&&_.access_key||typeof _.accessKey=="string"&&_.accessKey||void 0,w=typeof _.device_id=="string"&&_.device_id||typeof _.deviceId=="string"&&_.deviceId||void 0;if(!S||!w){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=${x}: ${v}`)}return Gi.info("handshake ok",{remoteDeviceId:w,logid:x,traceId:h}),{accessKey:S,deviceId:w}}catch(u){if(u instanceof T)throw Gi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Gi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let x=u.cause;throw Gi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:x?.code,syscall:x?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var yo=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Tt="auto",_o=15e4;function t0(t){return{model:td(t.model)??Tt,...t.modelToken?{modelToken:t.modelToken}:{}}}function n0(t){return!t||t===Tt}var uy=new Set(["auto","\u81EA\u52A8"]);function td(t){let e=t?.trim();if(e)return uy.has(e.toLowerCase())?Tt:e}function r0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=yo,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Tt;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))}else n0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function i0(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Tt}"`):n0(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${yo}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let r=t.modelInfo?.contextWindow??_o;e.push("-c",`model_context_window=${r}`)}return e}function s0(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function bo(t,e){let{ttEnv:r,usePpe:i}=Hi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function o0(t,e,r){if(!t.modelToken)return{};let i=bo(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
95
+ `)}}function nd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function rd(t){return t.model||Tt}function e0(t,e,r){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:r,maxTokens:8192,api:"openai-completions"}}function a0(t,e,r,i){if(!t.modelToken)return null;let o=rd(t),c=bo(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[e0(o,d,t.modelInfo?.contextWindow??_o)],x=new Set([o]);for(let g of i??[])!g||x.has(g)||(x.add(g),u.push(e0(g,["text"],_o)));let h={baseUrl:`${yo}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(h.headers=c),h}function c0(t,e,r){if(!t.modelToken)return[];let i=bo(e,r),o=[];for(let[c,d]of Object.entries(i))o.push("-c",`model_providers.coze.http_headers.${c}="${d}"`);return o}function id(t,e,r){let i=bo(e,r),o=t.modelInfo?.contextWindow??_o,d=["model:"," provider: custom",` default: ${t.model||Tt}`,` base_url: ${yo}/v1`,` context_length: ${o}`];if(t.modelToken&&d.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){d.push(" default_headers:");for(let[u,x]of Object.entries(i))d.push(` ${u}: ${JSON.stringify(x)}`)}return d.push("skills:"),d.push(" external_dirs:"),d.push(` - ${ly(dy(),".hermes","skills")}`),`${d.join(`
96
96
  `)}
97
- `}var Vn=G("hermes-config"),c0="dont_ask",d0="default";function Jn(t,e){return Ui(Be(t,e).root,"hermes-home")}async function hy(t){let e=Jn(t.agentId,t.paths);await fy(e,{recursive:!0,mode:448});let r=Bi({...process.env,...Mi(t.paths.agentEnvFile)});await dt(Ui(e,".env"),r,{mode:384});let i=nd(t.modelConfig,t.cozeEnv,t.mockScenario);await dt(Ui(e,"config.yaml"),i,{mode:384}),Vn.debug("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:r.length,yamlBytes:i.length})}async function l0(t){let e=Jn(t.agentId,t.paths),r=Ui(e,"state.db"),i=Ui(e,"config.yaml");Vn.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:r,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
- `).slice(1,6).join(" | ")}),await a0(r,{force:!0}).catch(c=>Vn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=nd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await dt(i,o,{mode:384}).catch(c=>Vn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(c)})),Vn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function id(t,e){let r=Jn(t,e);Vn.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:r,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
- `).slice(1,6).join(" | ")}),await a0(r,{recursive:!0,force:!0}).catch(i=>Vn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var rd=new Map;function u0(t){let e=rd.get(t.agentId);if(e)return e;let r=hy(t).finally(()=>rd.delete(t.agentId));return rd.set(t.agentId,r),r}var te=G("agent-handlers"),f0=5*1024*1024,wy=1,_y=6,yy=new Set(["node_modules",".git",".coze","dist","build",".next"]),by=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ey=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,vy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Sy(t){let e=t?.trim();return e?vy.test(e)||Ey.test(e)?e:(te.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Iy(t){return new Promise((e,r)=>{let i=nt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=l=>{o||(o=!0,l?r(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}var bo=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??J()}async listSkills(e){e._meta;let r=$n(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Be(r,this.paths).workspace,c=i?.framework??"claude-code",l=i?.skills??[],{base:u}=Lr(c,r,o,this.paths),f=[],x=new Set;for(let g of l){let w=me(u,g.relPath,"SKILL.md");await p0(w).then(y=>y.isFile()).catch(()=>!1)&&(f.push(Dy(g)),x.add(g.relPath))}if(e.scanLocal){let g=await ky(r,o,c,this.paths),w=await Ty(r,c);for(let S of[...g,...w])x.has(S.relPath)||(x.add(S.relPath),f.push(S.skill))}return{skills:f}}async addSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await Eo({agentId:r,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});vo(c,l,x),u.push(f)}return await ci(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],l=[],{base:u}=Lr(i.framework,r,i.workspace,this.paths);for(let f of c){if(!o.has(f.skillId)){l.push(f);continue}let x=me(u,f.relPath);te.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:r,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:x}),await ad(x,{recursive:!0,force:!0}),te.info("skill removed",{agentId:r,skillId:f.skillId,relPath:f.relPath})}return await ci(r,l),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");te.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??Be(r,this.paths).workspace,c=i?.framework??"claude-code",l=e.isGlobal??!1,u=_0(e.skillName),f=await Ay(r,o,c,u,l,this.paths);if(!f){let C=l?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${C}: ${e.skillName} (${u})`)}let{absDir:x,relPath:g}=f,w=me(x,"SKILL.md"),S=new fd.default;S.addLocalFolder(x,u);let y=S.toBuffer();if(y.length>h0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${h0}`);let v=await yo(w,{encoding:"utf8"}).then(C=>E0(C).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):te.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let A=I.version??"v1.0",R=I.skillId??e.skillId??b0(r,g);if(i&&!l){let C=i.skills??[],b=C.find(D=>D.relPath===g);b?(b.version=A,b.skillId=R):C.push({skillId:R,skillName:e.skillName,relPath:g,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await ci(r,C)}return te.info("skill published",{agentId:r,skillName:e.skillName,relPath:g,zipBytes:y.length,skillId:R,version:A}),{ok:!0,skillId:R,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 l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,te.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let f=c.downstream;c.downstream=void 0,te.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l}),f.stop(r).catch(x=>te.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 te.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await ve(r);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return te.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await hr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw te.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),te.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 ve(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Ni(e.registry)&&o.push(`--registry=${e.registry}`);let c=Sy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&by.test(l)&&o.push("--env",l);let u=await Iy(o);return te.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 T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await ve(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Fe(i),te.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}):(te.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",`${ft.DELETE}: missing agentId`);te.warn("[AUDIT] deleteAgent handler entry",{agentId:r,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
- `).slice(1,6).join(" | ")});let i=await ve(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let l=Be(r);return c==="cloud"?(te.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:r,path:l.root,deployType:c,reason:e.reason??""}),await ad(l.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Fe(i)),te.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Pr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Qc(e.model)??St,i=await ve(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),te.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return te.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;if(o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>te.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)})),o.framework==="hermes"){let u=[];for(let[f,x]of o.allSessionQueues())u.push(x.enqueue(async()=>{let g=o.sessions.get(f);if(!(!g?.downstream||!g.acpSessionId))try{await g.downstream.setSessionModel?.({sessionId:g.acpSessionId,modelId:r})}catch(w){te.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:f,acpId:g.acpSessionId,err:String(w)})}}));return await Promise.all(u),te.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:r,cloudSessions:u.length}),{ok:!0}}let l=[];for(let[u,f]of o.allSessionQueues())l.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(l),te.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:l.length}),{ok:!0}}async resetAgent(e){if(Pr(e._meta,ft.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ft.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ft.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(r=>te.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(r)})),await this.runDetailSync(e.agentId,ft.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),te.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,l]of i.sessions)o.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt,permissionMode:l.permissionMode,cozeGroupId:l.cozeGroupId});await ai(e,o)}async clearPersistedAcpSessionIds(e){let r=await ve(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Fe(r)}async repairAgent(e){if(Pr(e._meta,ft.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${ft.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){te.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ft.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){te.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){te.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Pr(e._meta,"_agent/getFileTree");let r=e._meta,i=$n(r),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await sd(l).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await oi(l,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=jy(e.depth);return u.isDirectory()?{tree:await Hy(o,l,c,f)}:{tree:[{name:qy(c),path:A0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Pr(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),c=await sd(o).catch(()=>null);if(!c||!c.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await oi(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>f0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${f0})`);let l=await yo(o);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await ve(e).catch(()=>null))?.workspace??Be(e).workspace}safeJoin(e,r){let i=dd(e,r||"."),o=ud(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${g0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return ve(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function _0(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 Lr(t,e,r,i){switch(t){case"claude-code":return{base:r,subdir:me(".claude","skills")};case"codex":case"openclaw":return{base:r,subdir:me(".agents","skills")};case"hermes":return{base:Jn(e,i??J()),subdir:"skills"}}}function y0(t){let e=py();return t==="claude-code"?[me(e,".claude","skills")]:t==="codex"?[me(e,".agents","skills"),me(e,".codex","skills")]:t==="openclaw"?[me(e,".agents","skills"),me(e,".openclaw","skills")]:t==="hermes"?[me(e,".hermes","skills")]:[]}async function Ay(t,e,r,i,o,c){let l=async u=>p0(me(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=Lr(r,t,e,c),x=me(f,i),g=me(u,x);return await l(g)?{absDir:g,relPath:x}:null}for(let u of y0(r)){let f=me(u,i);if(await l(f))return{absDir:f,relPath:f}}return null}function b0(t,e){return(xy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function E0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
97
+ `}var Yn=q("hermes-config"),l0="dont_ask",u0="default";function Xn(t,e){return qi(Fe(t,e).root,"hermes-home")}async function xy(t){let e=Xn(t.agentId,t.paths);await fy(e,{recursive:!0,mode:448});let r=Ui({...process.env,...Fi(t.paths.agentEnvFile)});await ht(qi(e,".env"),r,{mode:384});let i=id(t.modelConfig,t.cozeEnv,t.mockScenario);await ht(qi(e,"config.yaml"),i,{mode:384}),Yn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:r.length,yamlBytes:i.length})}async function f0(t){let e=Xn(t.agentId,t.paths),r=qi(e,"state.db"),i=qi(e,"config.yaml");Yn.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:r,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
+ `).slice(1,6).join(" | ")}),await d0(r,{force:!0}).catch(c=>Yn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=id({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ht(i,o,{mode:384}).catch(c=>Yn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(c)})),Yn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function od(t,e){let r=Xn(t,e);Yn.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:r,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
+ `).slice(1,6).join(" | ")}),await d0(r,{recursive:!0,force:!0}).catch(i=>Yn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var sd=new Map;function x0(t){let e=sd.get(t.agentId);if(e)return e;let r=xy(t).finally(()=>sd.delete(t.agentId));return sd.set(t.agentId,r),r}var ne=q("agent-handlers"),h0=5*1024*1024,wy=1,_y=6,yy=new Set(["node_modules",".git",".coze","dist","build",".next"]),by=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ey=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,vy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Sy(t){let e=t?.trim();return e?vy.test(e)||Ey.test(e)?e:(ne.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Iy(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 vo=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let r=Zn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Fe(r,this.paths).workspace,c=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Br(c,r,o,this.paths),x=[],h=new Set;for(let g of d){let _=xe(u,g.relPath,"SKILL.md");await m0(_).then(w=>w.isFile()).catch(()=>!1)&&(x.push(Cy(g)),h.add(g.relPath))}if(e.scanLocal){let g=await ky(r,o,c,this.paths),_=await Ty(r,c);for(let S of[...g,..._])h.has(S.relPath)||(h.add(S.relPath),x.push(S.skill))}return{skills:x}}async addSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((x,h)=>[x.skillId,h])),u=[];for(let x of o){let h=await So({agentId:r,workspace:i.workspace,framework:i.framework,skill:x,paths:this.paths});Io(c,d,h),u.push(x)}return await ui(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],d=[],{base:u}=Br(i.framework,r,i.workspace,this.paths);for(let x of c){if(!o.has(x.skillId)){d.push(x);continue}let h=xe(u,x.relPath);ne.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:r,skillId:x.skillId,relPath:x.relPath,skillBase:u,absDir:h}),await dd(h,{recursive:!0,force:!0}),ne.info("skill removed",{agentId:r,skillId:x.skillId,relPath:x.relPath})}return await ui(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Zn(e._meta);if(!e.skillName)throw new T("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ne.info("_agent/publishSkill start",{agentId:r,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(r),o=i?.workspace??Fe(r,this.paths).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=b0(e.skillName),x=await Ay(r,o,c,u,d,this.paths);if(!x){let D=d?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${D}: ${e.skillName} (${u})`)}let{absDir:h,relPath:g}=x,_=xe(h,"SKILL.md"),S=new hd.default;S.addLocalFolder(h,u);let w=S.toBuffer();if(w.length>p0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${w.length} bytes exceeds limit ${p0}`);let v=await Eo(_,{encoding:"utf8"}).then(D=>S0(D).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:w,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ne.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let A=I.version??"v1.0",R=I.skillId??e.skillId??v0(r,g);if(i&&!d){let D=i.skills??[],b=D.find(C=>C.relPath===g);b?(b.version=A,b.skillId=R):D.push({skillId:R,skillName:e.skillName,relPath:g,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await ui(r,D)}return ne.info("skill published",{agentId:r,skillName:e.skillName,relPath:g,zipBytes:w.length,skillId:R,version:A}),{ok:!0,skillId:R,version:A}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,ne.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let x=c.downstream;c.downstream=void 0,ne.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),x.stop(r).catch(h=>ne.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(h)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ne.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Ie(r);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return ne.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await gr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw ne.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Ue(i),ne.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Ie(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&zi(e.registry)&&o.push(`--registry=${e.registry}`);let c=Sy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&by.test(d)&&o.push("--env",d);let u=await Iy(o);return ne.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Ie(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ue(i),ne.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(ne.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new T("IPC_BAD_REQUEST",`${mt.DELETE}: missing agentId`);ne.warn("[AUDIT] deleteAgent handler entry",{agentId:r,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
+ `).slice(1,6).join(" | ")});let i=await Ie(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let d=Fe(r);return c==="cloud"?(ne.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:r,path:d.root,deployType:c,reason:e.reason??""}),await dd(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ue(i)),ne.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Or(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=td(e.model)??Tt,i=await Ie(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 Ue(i),ne.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return ne.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;if(o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>ne.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)})),o.framework==="hermes"){let u=[];for(let[x,h]of o.allSessionQueues())u.push(h.enqueue(async()=>{let g=o.sessions.get(x);if(!(!g?.downstream||!g.acpSessionId))try{await g.downstream.setSessionModel?.({sessionId:g.acpSessionId,modelId:r})}catch(_){ne.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:x,acpId:g.acpSessionId,err:String(_)})}}));return await Promise.all(u),ne.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:r,cloudSessions:u.length}),{ok:!0}}let d=[];for(let[u,x]of o.allSessionQueues())d.push(x.enqueue(async()=>{let h=o.sessions.get(u);h?.downstream&&(await h.downstream.stop(`switchModel: ${r}`).catch(()=>{}),h.downstream=void 0)}));return await Promise.all(d),ne.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Or(e._meta,mt.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${mt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,mt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(r=>ne.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(r)})),await this.runDetailSync(e.agentId,mt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),ne.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await li(e,o)}async clearPersistedAcpSessionIds(e){let r=await Ie(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(Or(e._meta,mt.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${mt.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${mt.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){ne.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,mt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){ne.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){ne.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Or(e._meta,"_agent/getFileTree");let r=e._meta,i=Zn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await ad(d).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await di(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let x=qy(e.depth);return u.isDirectory()?{tree:await Hy(o,d,c,x)}:{tree:[{name:jy(c),path:T0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Or(e._meta,"_agent/getFileContent");let r=Zn(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),c=await ad(o).catch(()=>null);if(!c||!c.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await di(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>h0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${h0})`);let d=await Eo(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 Ie(e).catch(()=>null))?.workspace??Fe(e).workspace}safeJoin(e,r){let i=ud(e,r||"."),o=xd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${w0}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Ie(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 b0(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 Br(t,e,r,i){switch(t){case"claude-code":return{base:r,subdir:xe(".claude","skills")};case"codex":case"openclaw":return{base:r,subdir:xe(".agents","skills")};case"hermes":return{base:Xn(e,i??Z()),subdir:"skills"}}}function E0(t){let e=py();if(t==="claude-code")return[xe(e,".claude","skills")];if(t==="codex")return[xe(e,".agents","skills"),xe(e,".codex","skills")];if(t==="openclaw")return[xe(e,".agents","skills"),xe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA||xe(e,"AppData","Local");return[xe(r,"hermes","skills"),xe(e,".hermes","skills")]}return[xe(e,".hermes","skills")]}return[]}async function Ay(t,e,r,i,o,c){let d=async u=>m0(xe(u,"SKILL.md")).then(x=>x.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:x}=Br(r,t,e,c),h=xe(x,i),g=xe(u,h);return await d(g)?{absDir:g,relPath:h}:null}for(let u of E0(r)){let x=xe(u,i);if(await d(x))return{absDir:x,relPath:x}}return null}function v0(t,e){return(hy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function S0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
101
  ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
102
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let l=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function v0(t,e,r,i){let o=await x0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let l of o){if(!l.isDirectory())continue;let u=l.name,f=me(r,u),x=me(e,u,"SKILL.md"),g=await yo(x,{encoding:"utf8"}).catch(()=>null);if(g===null)continue;let w=E0(g);c.push({relPath:f,skill:{skillId:b0(t,f),skillName:w.name||u,...w.description?{description:w.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function ky(t,e,r,i){let{base:o,subdir:c}=Lr(r,t,e,i);return v0(t,me(o,c),c,!1)}async function Ty(t,e){let r=[],i=new Set;for(let o of y0(e)){let c=await v0(t,o,o,!0);for(let l of c)i.has(l.relPath)||(i.add(l.relPath),r.push(l))}return r}var Ry=3e4,Py=50*1024*1024,h0=10*1024*1024,Or=3e4;async function Eo(t){let{agentId:e,workspace:r,framework:i,skill:o,paths:c}=t;if(!o.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let l=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!l&&!u)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=_0(o.skillName),{base:x,subdir:g}=Lr(i,e,r,c),w=me(g,f),S=me(x,w);if(await od(S,{recursive:!0}),l){let v=Buffer.from(o.content,"utf8");Gi(v.length),await cd(me(S,"SKILL.md"),v,"utf8")}else{let v=await Oy(o.downloadUrl);Ny(v)?await zy(v,S):My(v)?await By(v,S):await cd(me(S,"SKILL.md"),v.toString("utf8"),"utf8")}let y={skillId:o.skillId,skillName:o.skillName,relPath:w,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return te.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:w,source:l?"content":"downloadUrl"}),y}function vo(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 Dy(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 Cy(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 S0(t,e){let r=await ve(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Ot,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 c=[...r.skills??[]],l=new Map(c.map((w,S)=>[w.skillId,S])),u=c.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Fe(r,e),{status:"noop",count:0};let f=0,x=0,{base:g}=Lr(r.framework,t,r.workspace,e);te.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:r.framework,prev:o,current:i,skillBase:g,builtinCount:u.length,builtinRelPaths:u.map(w=>w.relPath)});for(let w of u)try{let S=me(g,w.relPath);te.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:S}),await ad(S,{recursive:!0,force:!0});let y=await Eo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Cy(w),...e?{paths:e}:{}});vo(c,l,y),f+=1}catch(S){x+=1,te.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(S)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Fe(r,e),te.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function Oy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Gi(e);let r=Ly(t);return Gi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await yo(e);return Gi(r.length),r}if(Ni(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Ry);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 Gi(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 Gi(t){if(t>Py)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Ly(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 Ny(t){return t.length>=2&&t[0]===31&&t[1]===139}function My(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function ld(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function By(t,e){let r,i;try{r=new fd.default(t),i=r.getEntries()}catch(l){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||ld(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 f=l.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Fy(i),c=dd(e);for(let l of i){if(ld(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=dd(e,u),x=ud(c,f);if(x.startsWith("..")||x==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await od(f,{recursive:!0});continue}await od(gy(f),{recursive:!0});let g;try{g=l.getData()}catch(w){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${w.message}`,{cause:w})}await cd(f,g)}}function Fy(t){let e;for(let r of t){let i=r.entryName;if(!i||ld(i))continue;let o=i.indexOf("/");if(o<=0)return;let c=i.slice(0,o+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function zy(t,e){await Uy(t);let r=Ff({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`))},Or);try{await w0(m0.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Uy(t){let e=[],r=Rr({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await w0(m0.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Gy=5e3;async function Hy(t,e,r,i){return I0(t,e,r,i,{count:0})}async function I0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await x0(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(yy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Gy){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=me(e,u.name),x=my(me(r,u.name)),g=null;try{g=await sd(f)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let w={name:u.name,path:A0(ud(t,f)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(w.children=await I0(t,f,x,i-1,o)),l.push(w)}return l.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),l}function jy(t){return!t||t<=0?wy:Math.min(t,_y)}function qy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function A0(t){return t.split(g0).join("/")}ee();var Sn=G("agent-health-reporter"),Wy=1e4,Ky=3,Hi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Wy,this.livenessFailureThreshold=e.livenessFailureThreshold??Ky}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()}),Sn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Sn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Sn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Sn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let l of this.opts.core.agents.values()){let u=$y(l);if(!u)continue;let f={agentId:l.agentId,status:u};l.patToken&&(f.patToken=l.patToken),l.accountId&&(f.accountId=l.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(l){this.consecutiveFailures+=1,Sn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(Sn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(l=>l.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(l){Sn.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){Sn.warn("onTickEnd hook failed",{err:String(r)})}}};function $y(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}qt();import{mkdir as gd,rm as Fb,stat as zb}from"node:fs/promises";import{homedir as Ub}from"node:os";import{join as nh}from"node:path";dn();import{existsSync as ib}from"node:fs";import{release as sb}from"node:os";import{basename as ob,isAbsolute as ab}from"node:path";function ji(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Nr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Mr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function In(t,e){return{jsonrpc:"2.0",id:t,error:e}}We();var So=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)}},Z={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 k0(t){return"method"in t&&"id"in t&&t.id!==void 0}function T0(t){return"method"in t&&!("id"in t)}function Io(t){return!("method"in t)&&"id"in t}var Vy={AGENT_NOT_FOUND:Z.AGENT_NOT_FOUND,AGENT_BUSY:Z.AGENT_BUSY,AGENT_DISCONNECTED:Z.AGENT_DISCONNECTED,AGENT_TIMEOUT:Z.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Z.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Z.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Z.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Z.INTERNAL_ERROR,BRIDGE_INTERNAL:Z.INTERNAL_ERROR,IPC_AUTH_FAILED:Z.INTERNAL_ERROR,IPC_BAD_REQUEST:Z.INVALID_REQUEST,METHOD_NOT_FOUND:Z.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Z.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Z.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Z.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Z.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Z.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Z.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Z.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Z.FILE_TOO_LARGE,UNSUPPORTED_MIME:Z.UNSUPPORTED_MIME,UPLOAD_FAILED:Z.UPLOAD_FAILED,UPSTREAM_NOT_READY:Z.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Z.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Z.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Z.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Z.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Z.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Z.SKILL_ZIP_TOO_LARGE};function Jy(t){if(t!=null)return t instanceof Error?{name:t.name,message:qi(t.message)}:typeof t=="string"?qi(t):typeof t=="object"?Yy(t):t}var Zy=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function qi(t){let e=t;for(let[r,i]of Zy)e=e.replace(r,i);return e}function Yy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=qi(i):e[r]=i;return e}function Wi(t){if(t instanceof T){let e=Jy(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:Vy[t.code]??Z.INTERNAL_ERROR,message:qi(t.message),data:r}}return{code:Z.INTERNAL_ERROR,message:qi(t instanceof Error?t.message:String(t))}}function R0(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:l,...u}=e;c=u}return new T(r,o,{retriable:e?.retriable??!1,cause:c})}function D0(t){return`${JSON.stringify(t)}
103
- `}var P0=10*1024*1024,Ao=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>P0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${P0} bytes`)}),[]}let r=this.buffer.split(`
104
- `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var O0={"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"},uT=Object.fromEntries(Object.entries(O0).map(([t,e])=>[e,t])),Xy={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Br=class{seq=0;next(e,r){this.seq+=1;let i=O0[e]??Qy(e),o=Xy[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(f=>C0(r?.[f]??"")),u=eb(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>C0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function Qy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function C0(t){return t.replace(/[:_\s]+/g,"-")}function eb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Yt();ar();We();ee();Re();import{execFileSync as tb,spawnSync as nb}from"node:child_process";function Ki(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function $i(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),nb("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var hd=new Set;function L0(t){typeof t=="number"&&t>0&&hd.add(t)}function N0(t){typeof t=="number"&&hd.delete(t)}function M0(){for(let t of hd)$i(t,"SIGKILL")}var Fr="coze-bridge-daemon";function B0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return tb("pgrep",["-U",String(o),"-f",Fr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
105
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function F0(t,e){if(t.length===0)return;let r=e?.killFn??$i,i=e?.isAliveFn??Ki,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(f=>i(f));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var rb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/]claude-agent-acp|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function z0(t,e){if(!e)return null;for(let r of rb)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function U0(t,e){return z0(t,e)}function G0(t,e){return z0(t,e)}function zr(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function H0(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:zr(g,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:zr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:zr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:zr(c,!1,e)}}var j0=Ve("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),cb=200,db=40,lb=Ve("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),ub=Ve("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),fb=Ve("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),hb=Ve("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),xb=Ve("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),pb=Ve("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),q0=500;function gb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=q0?t:`${e.slice(0,q0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function mb(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 W0(t){try{return ib(t)}catch{return}}function wb(t,e){return{platform:process.platform,osRelease:sb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:ab(e.command)?W0(e.command):void 0,cwd:e.cwd,cwdExists:W0(e.cwd),envKeys:e.envKeys}}function _b(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${ob(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var ht=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Ao({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Br;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=Kf(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=nt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,L0(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>cb&&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,N0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,l=wb(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:l}),this.failAllPending(new T("AGENT_SPAWN_FAILED",_b(c,l),{cause:l}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));$i(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||$i(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:xb,phase2GateMs:lb,livenessWindowMs:ub,absoluteMaxMs:fb,approvalMaxMs:pb,suspendThresholdMs:hb,...r};return this.call("session/prompt",e,j0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Nr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Mr(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(In(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=j0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=ji(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let 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 w=this.now(),S={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:zr(0,!1,o),sessionId:u};g.promptTimeout=S;let y=()=>{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=H0(v,S.cfg,I),R=C=>{S.armedAt=I,S.expectedIntervalMs=C,g.timer=setTimeout(y,C)};if(A.action==="suspend"){S.suspendedMs+=A.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),R(A.rearmMs);return}if(A.action==="continue"){R(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 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:c,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(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 T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(l)}catch(w){g.timer&&clearTimeout(g.timer),this.pending.delete(c),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(D0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(Io(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:gb(e.result)}),r.resolve(e.result));return}if(T0(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(k0(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 l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(In(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(In(e.id,Wi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=R0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=G0(this.framework,mb(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(db).join(`
106
- `),o=U0(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 yb(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 ko=class extends ht{framework="claude-code";constructor(e){let{command:r,args:i}=si("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return yb(e)}};dn();import{mkdtempSync as bb,rmSync as Eb}from"node:fs";import{tmpdir as vb}from"node:os";import{join as Sb}from"node:path";var To=class extends ht{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=si("codex",e.command,i),l=e.isolateCodexHome?bb(Sb(vb(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}:e.env,f={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(f),this.authMethodId=e.authMethodId,this.codexHomeDir=l}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Eb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};ee();var Ib=G("hermes-downstream"),Ro=class extends ht{framework="hermes";modelId;constructor(e){let r={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(r),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(r){Ib.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(r)})}}};We();var Ab=3e4,Ur=class extends ht{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}`}]},Ab))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var K0=["default","acceptEdits","plan","auto","bypassPermissions"],$0=["read-only","auto","full-access"],V0=["default","accept_edits","dont_ask"];function An(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return K0.includes(e);case"codex":return $0.includes(e);case"hermes":return V0.includes(e);case"openclaw":return!1}}function xd(t){switch(t){case"claude-code":return K0.join("/");case"codex":return $0.join("/");case"hermes":return V0.join("/");case"openclaw":return""}}jt();We();ee();Re();function pd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}dn();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 Po=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new kn,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,i]of this.sessions)Vi(i),i.downstream&&(r.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Vi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Xt(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Yt();ee();import{constants as J0}from"node:fs";import{access as kb,readFile as Tb}from"node:fs/promises";import{delimiter as Rb,dirname as Pb,join as Z0}from"node:path";var Xe=G("framework-detector"),Y0={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Db=[".exe",".cmd",".bat",".ps1"],Zn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??nt,access:e.access??kb,readFile:e.readFile??Tb}}async detect(e){let r=Y0[e],i=await this.which(r);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return Xe.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,l]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(Y0).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(Rb).filter(Boolean),i=this.env.platform==="win32"?["",...Db]:[""];for(let o of r)for(let c of i){let l=Z0(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?J0.F_OK:J0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let r;try{r=await this.env.readFile(e,"utf8")}catch(l){return Xe.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(l)}),null}let o=r.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return Xe.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let c=Z0(Pb(o),"hermes-acp");return await this.isExecutable(c)?(Xe.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:c}),c):(Xe.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:c}),null)}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return Xe.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return Xe.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 Xe.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 Xe.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(Xe.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}:(Xe.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return Xe.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 Xe.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||Xe.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 l=JSON.parse(c[0]);typeof l.gateway?.port=="number"&&(o.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(o.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(o.detail=l.rpc.error)}catch(l){Xe.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(Ob(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,l,u=f=>{c||(c=!0,l&&clearTimeout(l),i(f))};try{let f=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});l=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)}})}},Cb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Ob(t){return t.replace(Cb,"")}import{homedir as Lb}from"node:os";import{join as Nb}from"node:path";jt();Yt();ar();We();ee();async function eh(){let t=Nb(Lb(),".openclaw/openclaw.json");return ur(t)}async function th(){return(await eh())?.gateway?.auth?.token??""}var X0=G("openclaw.config"),Mb=[0,5e3,5e3],Bb=Ve("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),Q0="models.providers.",Do="agents.defaults.models",Co=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Mb,this.cliTimeoutMs=e.cliTimeoutMs??Bb}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(l=>setTimeout(l,c));try{return await r()}catch(l){i=l,X0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}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=nt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=x=>{l||(l=!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.runCli(["config","unset",r])))}catch(i){X0.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",`${Q0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Q0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Do}[${e}]`,()=>this.runCli(["config","set",Do,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Do}[${e}]`,`${Do}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await eh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,c=[];for(let l of Object.keys(i))l.startsWith(o)&&c.push(l.slice(o.length));return c}ensureAgent(e,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 le=G("agent-manager"),wd="acceptEdits",sh="full-access",oh="read-only";function Gb(t){switch(t){case"read-only":return["-c",'sandbox_mode="read-only"',"-c",'approval_policy="on-request"'];case"auto":return["-c",'sandbox_mode="workspace-write"',"-c",'approval_policy="on-failure"'];case"full-access":return["-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"']}}var Hb=(t,e,r,i,o,c,l,u,f,x)=>{switch(t){case"claude-code":{let g={...o?{...t0(o),...i0(o,l,u)}:{},...f??{},IS_SANDBOX:"1"};return new ko({cwd:r,env:g,agentId:i})}case"codex":{let g=o?[...n0(o),...o0(o,l,u)]:[],w=sh;x!==void 0&&(An("codex",x)?w=x:le.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let S=[...g,...Gb(w)],y={...o?r0(o):{},...f??{}},v=!!o;return new To({cwd:r,agentId:i,...S.length>0?{extraArgs:S}:{},...Object.keys(y).length>0?{env:y}:{},...v?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ur({command:e,cwd:r,agentId:i,...c?{sessionName:pd(c)}:{}});case"hermes":return new Ro({command:e,cwd:r,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model?{modelId:o.model}:{}})}};function md(t){return t==="claude-code"||t==="codex"}var jb={path:"",version:"cloud-deployed"},rh="openclaw_gateway_unavailable",qb="openclaw_default_agent_missing";function ih(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 Wb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Kb=6e4,Oo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Hb,this.createTimeoutMs=e.createTimeoutMs??Kb,this.detectorFactory=e.detectorFactory??(()=>new Zn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Co({command:r})),this.openclawConfigDir=e.openclawConfigDir??nh(Ub(),".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=>{le.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=nh(e,".env");if(await zb(r).then(c=>c.isFile()).catch(()=>!1)){le.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Bi({...process.env,...Mi(this.paths.agentEnvFile)});await dt(r,o,{mode:384}),le.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),le.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 ve(e.agentId,this.paths).catch(()=>null),o=xo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new T("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")le.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(R=>le.warn("dispose stale agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")le.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(R=>le.warn("dispose drifted agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){le.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let R=await ve(e.agentId,this.paths).catch(()=>null);R&&(R.patToken=e.patToken,await Fe(R,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){le.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let R=await ve(e.agentId,this.paths).catch(()=>null);R&&(R.modelInfo=e.modelInfo,await Fe(R,this.paths))}return le.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework]){let C=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${C}`)}let u=Be(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 w=g??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??w??u.workspace,y=new AbortController,v=setTimeout(()=>y.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&md(e.framework)&&await lr(e.framework,y.signal);let R=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await gd(u.root,{recursive:!0}),await gd(S,{recursive:!0}),await gd(u.logs,{recursive:!0}),R(),x||await hr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Ha(S,"cloud"):await Ha(S,"local",wd)),R();let C=i,b=Qf({model:e.model??C?.model}),D=Uf(e._meta)??C?.accountId,O=e.patToken??C?.patToken,F=f==="cloud"?e.modelInfo??C?.modelInfo:void 0;if(I=new Po({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??St,deployType:f,...D?{accountId:D}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),I.status="ok",C?.sessions){let $=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,se]of Object.entries(C.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};$?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",le.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Y,framework:e.framework,fallback:oe.permissionMode})):An(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:le.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&le.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:f}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(Y,oe)}let re=Object.keys(C.sessions).length;re>0&&le.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:C?.createdAt??Date.now(),sessions:C?.sessions??{},model:b.model};f==="cloud"&&(B.deployType="cloud"),D&&(B.accountId=D),O&&(B.patToken=O),F&&(B.modelInfo=F),C?.skills&&(B.skills=C.skills),C?.agentName&&(B.agentName=C.agentName),C?.description&&(B.description=C.description),B.skillsRefreshedForVersion=C?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):le.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let V=e.initialSkills??[];if(V.length>0){let $=[...B.skills??[]],re=new Map($.map((oe,P)=>[oe.skillId,P])),Y=await Promise.allSettled(V.map(oe=>Eo({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe,paths:this.paths}))),se=0;for(let[oe,P]of Y.entries()){let z=V[oe];z&&(P.status==="fulfilled"?(vo($,re,P.value),se++):le.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:z.skillId,skillName:z.skillName,err:String(P.reason)}))}se>0&&(B.skills=$,le.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:V.length}))}return await Fe(B,this.paths),le.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(R){throw le.error("agent create failed, rolling back",{agentId:e.agentId,err:String(R)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),le.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:r?.revive===!0,framework:e.framework,errStack:R instanceof Error?R.stack:String(R)}),await Fb(u.root,{recursive:!0,force:!0}).catch(C=>le.warn("rm agent dir failed (ignored)",{err:String(C)})),R instanceof T?R:new T("AGENT_SPAWN_FAILED",String(R),{cause:R})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&md(e.framework))u=jb;else throw e.framework==="hermes"?new T("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);md(e.framework)&&!ys(e.framework)&&(le.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(e.framework));let f=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:f,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else if(e.framework==="hermes"){let g={...this.buildBinShimPathEnv()};f&&(await u0({paths:this.paths,agentId:e.agentId,modelConfig:f,cozeEnv:o,mockScenario:c}),g.HERMES_HOME=Jn(e.agentId,this.paths)),x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,g)}else{let g=e.sessions.get(i),w=Xt(e)?g?.permissionMode??sh:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),w)}try{return await x.start(),await x.initialize(Wb),x}catch(g){let w=x instanceof ht?x.getStderrTail():[];throw w.length>0&&le.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",ih(o),{cause:{reason:rh}})}catch(o){le.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};le.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 le.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:qb}})}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",ih(r),{cause:{reason:rh}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,f=pd(o);if(r.deployType==="local"){let w=await this.ensureOpenclawDefaultAgent();return new Ur({command:u,cwd:w.workspace,agentId:w.id,sessionName:f})}let x=await th(),g;if(i?.modelToken){let w=ed(o),S=td(i),y=`${w}/${S}`;if(!this.ensuredProviders.has(y)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(w),A=s0(i,c,l,I);A&&(await v.ensureProvider(w,A),await v.addModelToAllowlist(y),this.ensuredProviders.add(y))}g=y}return new Ur({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 l=ed(c),u=`${l}/${o}`,f=!0;try{await i.removeProvider(l)}catch(x){f=!1,le.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:l,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,le.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as uh}from"node:crypto";import{promises as Qb}from"node:fs";import{basename as fh}from"node:path";We();ee();import{promises as $b}from"node:fs";import{basename as Vb}from"node:path";var ah=G("file-upload"),Jb="/api/coze_claw/file/agent_upload",Zb=6e4;async function ch(t,e={}){let i=`${Dr(Cr(e.handshakeBase))}${Jb}`,o=e.timeoutMs??Zb,c=await $b.readFile(t.path),l=new FormData;l.append("agent_id",t.agentId),l.append("session_id",t.sessionId),l.append("file_name",t.name),l.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...vn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);ah.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:l,signal:f.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 y=S.data?.file?.file_url;if(!y)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(S).slice(0,200)}`);return ah.info("file upload ok",{uri:y,logid:w}),{uri:y}}catch(g){throw g instanceof T?g:g.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Vb(t.path)}`):new T("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(x)}}We();ee();import{extname as Yb}from"node:path";var Xb={".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 dh(t){let e=Yb(t).toLowerCase();return Xb[e]??"application/octet-stream"}Re();var Lo=G("agent-send"),lh=50*1024*1024;function hh(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 xh(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&&(Lo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(g=>setTimeout(g,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function ph(t,e){let{session:r,runtime:i}=hh(e.core,t.agentId,t.sessionId);if(!await oi(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await Qb.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>lh)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${lh}`);let c=await dh(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let l=t.name??fh(t.path),u;try{u=await ch({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Lo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof T?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:uh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:l,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await xh(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Lo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function gh(t,e){let{session:r,runtime:i}=hh(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??fh(t.path),c={sessionUpdate:"group_file",messageId:uh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await xh(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Lo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function mh(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 l=r[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}Yt();ee();dn();var Lt=G("coze-cli-installer"),wh="@coze/cli@latest",eE="coze",_h="0.1.8",tE=5e3,nE=5e3,rE=9e4,yh=1e4,Ji=null,No=!1;async function yd(t,e={}){if(No)return;if(Ji)return Ji;let r=e.exec??Wf;return Ji=(async()=>{try{let i=await iE(eE,r),o=!1;if(i){let l=await sE(r);if(l===void 0)Lt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(mh(l,_h))Lt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:_h}),o=!0;else{Lt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),No=!0;return}}let c=o?"upgrade-only":"full";Lt.info("coze-cli install start",{package:wh,mode:c});try{await r("npm",["i","-g","--prefer-online",wh],{timeout:rE,maxBuffer:10*1024*1024}),Lt.info("coze-cli install ok")}catch(l){Lt.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(o){No=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:yh}),Lt.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Lt.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:yh}),Lt.info("coze auth login ok")}catch(l){Lt.warn("coze auth login failed",{err:String(l)});return}No=!0}finally{Ji=null}})(),Ji}async function iE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:tE});return Ua(i)}catch{return}}async function sE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:nE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}qt();jt();Re();var oE=10*6e4;function bh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?oE:e}function Mo(t){return ur(t??J().configFile)}function Zi(t,e){return fr(e??J().configFile,t)}import{randomBytes as AE}from"node:crypto";ar();We();ee();import{createReadStream as aE}from"node:fs";import{mkdir as cE,readFile as dE,realpath as lE,stat as uE,writeFile as fE}from"node:fs/promises";import{basename as hE,dirname as bd,isAbsolute as xE,join as pE,relative as gE,resolve as Eh,sep as mE}from"node:path";import{createInterface as wE}from"node:readline";var Sh=G("fs-rpc"),Yi=Ve("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Ih(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Yi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Yi} bytes`);let i=await kh(t.path,e);return await cE(bd(i),{recursive:!0}),await fE(i,t.content,"utf8"),Sh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Ah(t,e){let r=await kh(t.path,e),i=await uE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Yi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Yi} bytes`);let c;if(o&&i.size>Yi)c=await _E(r,t.line??1,t.limit);else{let l=await dE(r,"utf8");if(o){let u=l.split(`
107
- `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
108
- `)}else c=l}return Sh.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function _E(t,e,r){let i=wE({input:aE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let f of i)if(u>=o&&u<c&&l.push(f),u++,u>=c)break}finally{i.close()}return l.join(`
109
- `)}async function kh(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([vh(Eh(e)),vh(Eh(t))]),o=gE(r,i);if(yE(o,mE,xE(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function yE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function vh(t){let e=[],r=t;for(;r!==bd(r);)try{let i=await lE(r);return e.length?pE(i,...e.reverse()):i}catch{e.push(hE(r)),r=bd(r)}return t}ee();var Th=G("prompt-multimodal"),Rh=10*1024*1024,bE=15e3,EE=6;async function Ph(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,l=t[c];l!==void 0&&(e[c]=await vE(l))}}let o=Array.from({length:Math.min(EE,t.length)},()=>i());return await Promise.all(o),e}function Dh(t){return t.some(e=>e.type==="image")}async function vE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ni(e.uri))return t;try{let{buf:r,contentType:i}=await IE(e.uri),o=e.mimeType||SE(i)||"application/octet-stream";return Th.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 Th.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function SE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function IE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),bE);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>Rh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Rh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}qt();We();ee();var q=G("core"),kE=3e4,TE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,RE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",PE="\u5BA1\u6279\u5DF2\u8D85\u65F6",DE=3e4,Bo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Br;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=bh(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(),q.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){q.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(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),q.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){q.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&q.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,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,l)=>{q.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),Vi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){q.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(In(o,{code:Z.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(l=>q.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Z.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){q.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Z.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(Io(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&&TE.test(i)?this.currentCozeEnv=i:i&&q.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,Z.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):q.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Mr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Mr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Mr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Z.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):q.warn("drop unknown notification",{method:e.method})}catch(o){q.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(In(r,Wi(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 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=po(r._meta);return q.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,RE,x,g)}}let l=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,f}finally{q.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Hf(i);switch(r){case"session/new":{let c=CE();return q.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return q.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,l=c.sessionId;if(!l)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Xt(e)?Gf(i._meta):void 0;if(u!==void 0&&!An(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${xd(e.framework)}`);let f=await this.ensureRuntime(e,l);if(u!==void 0&&f.permissionMode===void 0&&(f.permissionMode=u,await this.persistSessionMapping(e)),f.replySeq=0,await this.ensureDownstream(e,l,f),!f.downstream||!f.acpSessionId)throw new T("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=po(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&&Dh(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await Ph(c.prompt);try{let S=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:w});return f.lastActiveAt=Date.now(),S}catch(S){if(S instanceof T&&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 v=f.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):void 0;return q.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,f,l,PE,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,q.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:f.acpSessionId}),S.stop("reload-after-turn").catch(y=>q.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(y)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,l,f)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let f=e.getSessionQueue(l);f.size>0&&(q.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:f.size}),f.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,l=c.sessionId,u=c.modeId,f=po(i._meta);if(!l)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Xt(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(!An(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${xd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(l)??await this.ensureRuntime(e,l);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 q.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[l,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(o.length===0)return q.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};q.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,f=l.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,oldMode:l.oldMode,runtime:l.runtime})}for(let l of c)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let 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 Xt(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?c0:d0:c.permissionMode=e.framework==="claude-code"?wd:oh),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(ft.GEN_MODEL_TOKEN,i,DE);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(Vi(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,c=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let f;try{f=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(q.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}),q.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){q.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 q.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),Xt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){q.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Vi(i),this.isRuntimeBusy(e,i)){q.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)){q.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}q.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=>q.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 l=e.activeTriggers.get(r.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Nr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Nr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>q.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){q.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){q.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(NE(r)){q.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=r.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Xt(e)){let g=l.currentModeId;An(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(w=>q.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof g=="string"&&!An(e.framework,g)&&q.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(Nr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>q.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}q.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:Z.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??{},l=await Ih(c,o);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await Ah(c,o);r.respondAgentRequest(i.id,l)}}catch(o){q.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Wi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);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 y={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),q.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(ji(o,"session/request_permission",y)).catch(v=>{this.pendingUpstream.delete(o),q.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),r.respondAgentRequestError(i.id,{code:Z.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?(q.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&OE(e.result,o),q.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new So(e.error)):i.value.resolve(e.result);return}q.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),l=e.get(c);if(l)return q.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=kE){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(ji(o,e,r)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),l(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&&Xt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ai(e.agentId,r,this.paths)}catch(r){q.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(In(e,{code:r,message:i,data:{bridgeVersion:Ot}}))}};function CE(){return AE(16).toString("hex")}function OE(t,e){if(!t||typeof t!="object"){q.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){q.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"){q.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&q.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var LE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function NE(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{text:o}=i;return LE.some(c=>o.startsWith(c))}jt();ee();Re();import{randomBytes as ME}from"node:crypto";import{createServer as BE}from"node:http";var FE=1e6,Ch=G("ipc"),Fo=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??J()}async start(){this.token=ME(32).toString("hex");let e=BE((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(),Ch.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 dt(this.paths.portFile,String(this.port)),await dt(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Xi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Xi(r,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await zE(e)}catch(u){Xi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);Xi(r,200,u??{ok:!0})}catch(u){Ch.error("IPC handler failed",{key:o,err:String(u)}),Xi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Xi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function zE(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>FE)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 oS=Ht(Tx(),1),aS=Ht($o(),1),cS=Ht(jr(),1),dS=Ht(Cd(),1),lS=Ht(Nd(),1),uS=Ht(Gd(),1),Bx=Ht(Yo(),1),fS=Ht(Mx(),1);var Fx=Bx.default;We();ee();var{FWS:TS}=Jx(),Ce=G("upstream.frontier"),Yx="application/json",Xx="none",RS=15e3;function PS(t){class e extends Fx{constructor(i){super(i,Vf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Ce.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(Dl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let l=Buffer.from(c.slice(0,128)).toString("hex");Ce.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){Ce.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var as=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Ce.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Jf,...vn(this.opts.ppeOverride)},r=PS(e),i=Yf(this.opts.urlOverride),o={url:i,ws:r,fpID:$f,aID:go,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Yx,force:!0},payloadEncoding:{encoding:Xx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new TS(o),l=!1,u=null,f,x,g=new Promise((y,v)=>{f=y,x=v}),w=y=>{l||(l=!0,u&&(clearTimeout(u),u=null),y?x(y):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Ce.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&w();for(let v of this.connectHandlers)Promise.resolve(v({initial:y})).catch(I=>Ce.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Ce.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Ce.warn("frontier error",{code:y.code,msg:y.message}),w(new T("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??RS;u=setTimeout(()=>{w(new T("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(v){Ce.warn("fws close during start failure threw (ignored)",{err:String(v)})}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){Ce.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Ce.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?(Ce.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),c=e;Qx(c)||Ce.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:Yx,payloadEncoding:Xx})}catch(u){throw Ce.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.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){Ce.debug("drop non-adapter frontier frame",{service:r});return}let i=OS(e);if(!i){Ce.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Ce.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(l){Ce.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;Qx(c)||Ce.info("frontier frame in",{logid:CS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:DS(i)}),Promise.resolve(this.handler(o)).catch(l=>Ce.warn("frontier frame handler threw",{err:String(l)}))}};function Qx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var ep=2e3;function DS(t){return t.length<=ep?t:`${t.slice(0,ep)}...<truncated, total ${t.length} chars>`}function CS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function OS(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();ee();var Wd=G("skill-publish"),LS="/api/marketplace/product/skill/publish_with_assets",NS=15e4;async function tp(t,e={}){let i=`${Dr(Cr(e.handshakeBase))}${LS}`,o=e.timeoutMs??NS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let l={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...vn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);Wd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...l,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:l,body:c,signal:u.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${g}: ${y.slice(0,200)}`)}let w=await x.json();if(Wd.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),Wd.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(f)}}ee();var Kd=G("upstream.switchable"),oa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Kd.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 Kd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Kd.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()}};ee();var $d=G("upstream"),Jr=class{handler=null;async start(){$d.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){$d.info("NoopUpstream stopped",{reason:e})}async send(e){$d.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();ee();jt();ee();Re();import{promises as MS}from"node:fs";var np=G("pat-token-store");async function aa(t=J()){try{let r=(await MS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(np.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"&&np.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function cs(t,e=J()){if(!t)throw new Error("writePatToken: empty patToken");await dt(e.patTokenFile,t,{mode:384})}Re();Re();import{promises as ca}from"node:fs";import{join as BS}from"node:path";function FS(t,e){return`#!/bin/sh
102
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function I0(t,e,r,i){let o=await g0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let d of o){if(!d.isDirectory())continue;let u=d.name,x=xe(r,u),h=xe(e,u,"SKILL.md"),g=await Eo(h,{encoding:"utf8"}).catch(()=>null);if(g===null)continue;let _=S0(g);c.push({relPath:x,skill:{skillId:v0(t,x),skillName:_.name||u,..._.description?{description:_.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function ky(t,e,r,i){let{base:o,subdir:c}=Br(r,t,e,i);return I0(t,xe(o,c),c,!1)}async function Ty(t,e){let r=[],i=new Set;for(let o of E0(e)){let c=await I0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var Ry=3e4,Py=50*1024*1024,p0=10*1024*1024,Mr=3e4;async function So(t){let{agentId:e,workspace:r,framework:i,skill:o,paths:c}=t;if(!o.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!u)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let x=b0(o.skillName),{base:h,subdir:g}=Br(i,e,r,c),_=xe(g,x),S=xe(h,_);if(await cd(S,{recursive:!0}),d){let v=Buffer.from(o.content,"utf8");ji(v.length),await ld(xe(S,"SKILL.md"),v,"utf8")}else{let v=await Oy(o.downloadUrl);Ny(v)?await Fy(v,S):My(v)?await By(v,S):await ld(xe(S,"SKILL.md"),v.toString("utf8"),"utf8")}let w={skillId:o.skillId,skillName:o.skillName,relPath:_,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return ne.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:_,source:d?"content":"downloadUrl"}),w}function Io(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 Cy(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 Dy(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 A0(t,e){let r=await Ie(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Bt,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((_,S)=>[_.skillId,S])),u=c.filter(_=>_.builtin===!0&&!!_.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Ue(r,e),{status:"noop",count:0};let x=0,h=0,{base:g}=Br(r.framework,t,r.workspace,e);ne.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:r.framework,prev:o,current:i,skillBase:g,builtinCount:u.length,builtinRelPaths:u.map(_=>_.relPath)});for(let _ of u)try{let S=xe(g,_.relPath);ne.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:_.skillId,relPath:_.relPath,rmTarget:S}),await dd(S,{recursive:!0,force:!0});let w=await So({agentId:t,workspace:r.workspace,framework:r.framework,skill:Dy(_),...e?{paths:e}:{}});Io(c,d,w),x+=1}catch(S){h+=1,ne.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:_.skillId,skillName:_.skillName,err:String(S)})}return r.skills=c,h===0&&(r.skillsRefreshedForVersion=i),await Ue(r,e),ne.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:x,failed:h}),{status:"refreshed",count:x}}async function Oy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);ji(e);let r=Ly(t);return ji(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await Eo(e);return ji(r.length),r}if(zi(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Ry);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 ji(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 ji(t){if(t>Py)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Ly(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 Ny(t){return t.length>=2&&t[0]===31&&t[1]===139}function My(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 fd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function By(t,e){let r,i;try{r=new hd.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||fd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(h=>h===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let x=d.header.attr>>>16&61440;if(x!==0&&x!==32768&&x!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${x.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=zy(i),c=ud(e);for(let d of i){if(fd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let x=ud(e,u),h=xd(c,x);if(h.startsWith("..")||h==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await cd(x,{recursive:!0});continue}await cd(gy(x),{recursive:!0});let g;try{g=d.getData()}catch(_){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${_.message}`,{cause:_})}await ld(x,g)}}function zy(t){let e;for(let r of t){let i=r.entryName;if(!i||fd(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 Fy(t,e){await Uy(t);let r=Uf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Mr}ms)`))},Mr);try{await y0(_0.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Mr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Uy(t){let e=[],r=Dr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(h=>h==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Mr}ms)`))},Mr);try{await y0(_0.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Mr}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Gy=5e3;async function Hy(t,e,r,i){return k0(t,e,r,i,{count:0})}async function k0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await g0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(yy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Gy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let x=xe(e,u.name),h=my(xe(r,u.name)),g=null;try{g=await ad(x)}catch{continue}if(g.isSymbolicLink())continue;o.count++;let _={name:u.name,path:T0(xd(t,x)),isDir:g.isDirectory(),size:g.size,modifiedAt:Math.floor(g.mtimeMs)};g.isDirectory()&&i>1&&(_.children=await k0(t,x,h,i-1,o)),d.push(_)}return d.sort((u,x)=>u.isDir!==x.isDir?u.isDir?-1:1:u.name.localeCompare(x.name)),d}function qy(t){return!t||t<=0?wy:Math.min(t,_y)}function jy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function T0(t){return t.split(w0).join("/")}te();var kn=q("agent-health-reporter"),Wy=1e4,Ky=3,Wi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Wy,this.livenessFailureThreshold=e.livenessFailureThreshold??Ky}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()}),kn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),kn.info("heartbeat stopped"))}async tick(){if(this.inFlight){kn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,kn.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=$y(d);if(!u)continue;let x={agentId:d.agentId,status:u};d.patToken&&(x.patToken=d.patToken),d.accountId&&(x.accountId=d.accountId),r.push(x)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Bt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,kn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(kn.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){kn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){kn.warn("onTickEnd hook failed",{err:String(r)})}}};function $y(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Kt();import{mkdir as wd,rm as zb,stat as Fb}from"node:fs/promises";import{homedir as Ub}from"node:os";import{join as ix}from"node:path";fn();import{existsSync as ib}from"node:fs";import{release as sb}from"node:os";import{basename as ob,isAbsolute as ab}from"node:path";function Ki(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function zr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Fr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Tn(t,e){return{jsonrpc:"2.0",id:t,error:e}}$e();var Ao=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function R0(t){return"method"in t&&"id"in t&&t.id!==void 0}function P0(t){return"method"in t&&!("id"in t)}function ko(t){return!("method"in t)&&"id"in t}var Vy={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function Jy(t){if(t!=null)return t instanceof Error?{name:t.name,message:$i(t.message)}:typeof t=="string"?$i(t):typeof t=="object"?Yy(t):t}var Zy=[[/\/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 $i(t){let e=t;for(let[r,i]of Zy)e=e.replace(r,i);return e}function Yy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=$i(i):e[r]=i;return e}function Vi(t){if(t instanceof T){let e=Jy(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:Vy[t.code]??Y.INTERNAL_ERROR,message:$i(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:$i(t instanceof Error?t.message:String(t))}}function C0(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 T(r,o,{retriable:e?.retriable??!1,cause:c})}function O0(t){return`${JSON.stringify(t)}
103
+ `}var D0=10*1024*1024,To=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>D0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${D0} bytes`)}),[]}let r=this.buffer.split(`
104
+ `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var N0={"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"},uT=Object.fromEntries(Object.entries(N0).map(([t,e])=>[e,t])),Xy={"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:[]},Ur=class{seq=0;next(e,r){this.seq+=1;let i=N0[e]??Qy(e),o=Xy[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(x=>L0(r?.[x]??"")),u=eb(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>L0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Qy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function L0(t){return t.replace(/[:_\s]+/g,"-")}function eb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Qt();lr();$e();te();Ce();import{execFileSync as tb,spawnSync as nb}from"node:child_process";function Ji(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Zi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),nb("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var pd=new Set;function M0(t){typeof t=="number"&&t>0&&pd.add(t)}function B0(t){typeof t=="number"&&pd.delete(t)}function z0(){for(let t of pd)Zi(t,"SIGKILL")}var Gr="coze-bridge-daemon";function F0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return tb("pgrep",["-U",String(o),"-f",Gr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
105
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function U0(t,e){if(t.length===0)return;let r=e?.killFn??Zi,i=e?.isAliveFn??Ji,o=e?.sleepFn??(u=>new Promise(x=>setTimeout(x,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(x=>i(x));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var rb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/]claude-agent-acp|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function G0(t,e){if(!e)return null;for(let r of rb)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function H0(t,e){return G0(t,e)}function q0(t,e){return G0(t,e)}function Hr(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 j0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let h=t.suspendedMs+o,g=r-t.startedAt-h;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Hr(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:Hr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Hr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Hr(c,!1,e)}}var W0=Ze("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),cb=200,db=40,lb=Ze("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),ub=Ze("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),fb=Ze("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),xb=Ze("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),hb=Ze("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),pb=Ze("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),K0=500;function gb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=K0?t:`${e.slice(0,K0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function mb(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 $0(t){try{return ib(t)}catch{return}}function wb(t,e){return{platform:process.platform,osRelease:sb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:ab(e.command)?$0(e.command):void 0,cwd:e.cwd,cwdExists:$0(e.cwd),envKeys:e.envKeys}}function _b(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${ob(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var wt=class{constructor(e){this.opts=e;this.log=q(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new To({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Ur;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=Vf(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=st(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,M0(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>cb&&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,B0(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=wb(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 T("AGENT_SPAWN_FAILED",_b(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()));Zi(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Zi(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:hb,phase2GateMs:lb,livenessWindowMs:ub,absoluteMaxMs:fb,approvalMaxMs:pb,suspendThresholdMs:xb,...r};return this.call("session/prompt",e,W0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(zr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Fr(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(Tn(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=W0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Ki(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let x=r.sessionId;return typeof x=="string"?x:void 0})();return new Promise((x,h)=>{let g={resolve:x,reject:h,timer:null,method:e,promptTimeout:null};if(o){let _=this.now(),S={cfg:o,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:Hr(0,!1,o),sessionId:u};g.promptTimeout=S;let w=()=>{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=j0(v,S.cfg,I),R=D=>{S.armedAt=I,S.expectedIntervalMs=D,g.timer=setTimeout(w,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}:{}}),R(A.rearmMs);return}if(A.action==="continue"){R(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),h(A.awaitingApproval?new 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:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),h(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};g.timer=setTimeout(w,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}),h(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,g);try{this.writeFrame(d)}catch(_){g.timer&&clearTimeout(g.timer),this.pending.delete(c),h(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(O0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(ko(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:gb(e.result)}),r.resolve(e.result));return}if(P0(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(R0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Tn(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(Tn(e.id,Vi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=C0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=q0(this.framework,mb(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(db).join(`
106
+ `),o=H0(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 yb(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 Ro=class extends wt{framework="claude-code";constructor(e){let{command:r,args:i}=ci("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return yb(e)}};fn();import{mkdtempSync as bb,rmSync as Eb}from"node:fs";import{tmpdir as vb}from"node:os";import{join as Sb}from"node:path";var Po=class extends wt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ci("codex",e.command,i),d=e.isolateCodexHome?bb(Sb(vb(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(x),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}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Eb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};te();var Ib=q("hermes-downstream"),Co=class extends wt{framework="hermes";modelId;constructor(e){let r={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(r),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(r){Ib.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(r)})}}};$e();var Ab=3e4,qr=class extends wt{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}`}]},Ab))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var V0=["default","acceptEdits","plan","auto","bypassPermissions"],J0=["read-only","auto","full-access"],Z0=["default","accept_edits","dont_ask"];function Rn(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return V0.includes(e);case"codex":return J0.includes(e);case"hermes":return Z0.includes(e);case"openclaw":return!1}}function gd(t){switch(t){case"claude-code":return V0.join("/");case"codex":return J0.join("/");case"hermes":return Z0.join("/");case"openclaw":return""}}Wt();$e();te();Ce();function md(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}fn();var Pn=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 Do=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 Pn,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)Yi(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 Yi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function en(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Qt();te();import{constants as Y0}from"node:fs";import{access as kb,readFile as Tb}from"node:fs/promises";import{delimiter as Rb,dirname as Pb,join as X0}from"node:path";var et=q("framework-detector"),Q0={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Cb=[".exe",".cmd",".bat",".ps1"],Qn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??kb,readFile:e.readFile??Tb}}async detect(e){let r=Q0[e],i=await this.which(r);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return et.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(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(Rb).filter(Boolean),i=this.env.platform==="win32"?["",...Cb]:[""];for(let o of r)for(let c of i){let d=X0(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?Y0.F_OK:Y0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let r;try{r=await this.env.readFile(e,"utf8")}catch(d){return et.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let o=r.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return et.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let c=X0(Pb(o),"hermes-acp");return await this.isExecutable(c)?(et.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:c}),c):(et.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:c}),null)}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return et.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return et.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return et.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return et.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(et.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(et.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return et.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return et.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||et.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){et.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(Ob(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,d,u=x=>{c||(c=!0,d&&clearTimeout(d),i(x))};try{let x=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{x.kill("SIGKILL"),u(null)},15e3),x.stdout?.on("data",h=>{o+=h.toString("utf8")}),x.on("error",()=>u(null)),x.on("close",h=>u({code:h,stdout:o}))}catch{u(null)}})}},Db=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Ob(t){return t.replace(Db,"")}import{homedir as Lb}from"node:os";import{join as Nb}from"node:path";Wt();Qt();lr();$e();te();async function nx(){let t=Nb(Lb(),".openclaw/openclaw.json");return hr(t)}async function rx(){return(await nx())?.gateway?.auth?.token??""}var ex=q("openclaw.config"),Mb=[0,5e3,5e3],Bb=Ze("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),tx="models.providers.",Oo="agents.defaults.models",Lo=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new Pn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Mb,this.cliTimeoutMs=e.cliTimeoutMs??Bb}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,ex.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=st(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=h=>{d||(d=!0,clearTimeout(x),h())};o.stderr?.on("data",h=>{c+=h.toString("utf8")});let x=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);x.unref(),o.on("error",h=>u(()=>i(h))),o.on("close",h=>u(()=>{h===0?r():i(new Error(`exit ${h}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(i){ex.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",`${tx}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${tx}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Oo}[${e}]`,()=>this.runCli(["config","set",Oo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Oo}[${e}]`,`${Oo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await nx())?.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=q("agent-manager"),yd="acceptEdits",ax="full-access",cx="read-only";function Gb(t){switch(t){case"read-only":return["-c",'sandbox_mode="read-only"',"-c",'approval_policy="on-request"'];case"auto":return["-c",'sandbox_mode="workspace-write"',"-c",'approval_policy="on-failure"'];case"full-access":return["-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"']}}var Hb=(t,e,r,i,o,c,d,u,x,h)=>{switch(t){case"claude-code":{let g={...o?{...r0(o),...o0(o,d,u)}:{},...x??{},IS_SANDBOX:"1"};return new Ro({cwd:r,env:g,agentId:i})}case"codex":{let g=o?[...i0(o),...c0(o,d,u)]:[],_=ax;h!==void 0&&(Rn("codex",h)?_=h:ue.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let S=[...g,...Gb(_)],w={...o?s0(o):{},...x??{}},v=!!o;return new Po({cwd:r,agentId:i,...S.length>0?{extraArgs:S}:{},...Object.keys(w).length>0?{env:w}:{},...v?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new qr({command:e,cwd:r,agentId:i,...c?{sessionName:md(c)}:{}});case"hermes":return new Co({command:e,cwd:r,agentId:i,...x&&Object.keys(x).length>0?{env:{...x}}:{},...o?.model?{modelId:o.model}:{}})}};function _d(t){return t==="claude-code"||t==="codex"}var qb={path:"",version:"cloud-deployed"},sx="openclaw_gateway_unavailable",jb="openclaw_default_agent_missing";function ox(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 Wb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Kb=6e4,No=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??Hb,this.createTimeoutMs=e.createTimeoutMs??Kb,this.detectorFactory=e.detectorFactory??(()=>new Qn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Lo({command:r})),this.openclawConfigDir=e.openclawConfigDir??ix(Ub(),".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=>{ue.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=ix(e,".env");if(await Fb(r).then(c=>c.isFile()).catch(()=>!1)){ue.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Ui({...process.env,...Fi(this.paths.agentEnvFile)});await ht(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 T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await Ie(e.agentId,this.paths).catch(()=>null),o=go(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new T("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(R=>ue.warn("dispose stale agent failed (ignored)",{err:String(R)})),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(R=>ue.warn("dispose drifted agent failed (ignored)",{err:String(R)})),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 R=await Ie(e.agentId,this.paths).catch(()=>null);R&&(R.patToken=e.patToken,await Ue(R,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ue.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let R=await Ie(e.agentId,this.paths).catch(()=>null);R&&(R.modelInfo=e.modelInfo,await Ue(R,this.paths))}return ue.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework]){let D=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${D}`)}let u=Fe(e.agentId,this.paths),x=o?"cloud":"local",h=e.framework==="openclaw"&&x==="local",g;h&&!r?.revive&&(g=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=g??(h?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),S=e.workspace??_??u.workspace,w=new AbortController,v=setTimeout(()=>w.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&_d(e.framework)&&await xr(e.framework,w.signal);let R=()=>{if(w.signal.aborted)throw w.signal.reason instanceof Error?w.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await wd(u.root,{recursive:!0}),await wd(S,{recursive:!0}),await wd(u.logs,{recursive:!0}),R(),h||await gr(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(x==="cloud"?await ja(S,"cloud"):await ja(S,"local",yd)),R();let D=i,b=t0({model:e.model??D?.model}),C=Hf(e._meta)??D?.accountId,L=e.patToken??D?.patToken,z=x==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new Do({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Tt,deployType:x,...C?{accountId:C}:{},...L?{patToken:L}:{},...z?{modelInfo:z}:{}}),I.status="ok",D?.sessions){let V=e.framework==="hermes"||x==="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};V?oe.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ue.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:ae.permissionMode})):Rn(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:x}),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 M={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:b.model};x==="cloud"&&(M.deployType="cloud"),C&&(M.accountId=C),L&&(M.patToken=L),z&&(M.modelInfo=z),D?.skills&&(M.skills=D.skills),D?.agentName&&(M.agentName=D.agentName),D?.description&&(M.description=D.description),M.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Bt,e.framework==="openclaw"&&x==="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 J=e.initialSkills??[];if(J.length>0){let V=[...M.skills??[]],re=new Map(V.map((ae,P)=>[ae.skillId,P])),X=await Promise.allSettled(J.map(ae=>So({agentId:e.agentId,workspace:S,framework:e.framework,skill:ae,paths:this.paths}))),oe=0;for(let[ae,P]of X.entries()){let G=J[ae];G&&(P.status==="fulfilled"?(Io(V,re,P.value),oe++):ue.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(P.reason)}))}oe>0&&(M.skills=V,ue.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:J.length}))}return await Ue(M,this.paths),ue.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:x}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(R){throw ue.error("agent create failed, rolling back",{agentId:e.agentId,err:String(R)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ue.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:r?.revive===!0,framework:e.framework,errStack:R instanceof Error?R.stack:String(R)}),await zb(u.root,{recursive:!0,force:!0}).catch(D=>ue.warn("rm agent dir failed (ignored)",{err:String(D)})),R instanceof T?R:new T("AGENT_SPAWN_FAILED",String(R),{cause:R})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&_d(e.framework))u=qb;else throw e.framework==="hermes"?new T("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);_d(e.framework)&&!Es(e.framework)&&(ue.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await xr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,h;if(e.framework==="openclaw")h=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else if(e.framework==="hermes"){let g={...this.buildBinShimPathEnv()};x&&(await x0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:c}),g.HERMES_HOME=Xn(e.agentId,this.paths)),h=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,c,g)}else{let g=e.sessions.get(i),_=en(e)?g?.permissionMode??ax:"full-access";h=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),_)}try{return await h.start(),await h.initialize(Wb),h}catch(g){let _=h instanceof wt?h.getStderrTail():[];throw _.length>0&&ue.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof T?g.code:"unknown",recentStderr:_}),await h.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,g)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new T("AGENT_ENV_NOT_READY",ox(o),{cause:{reason:sx}})}catch(o){ue.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};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 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:jb}})}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",ox(r),{cause:{reason:sx}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,x=md(o);if(r.deployType==="local"){let _=await this.ensureOpenclawDefaultAgent();return new qr({command:u,cwd:_.workspace,agentId:_.id,sessionName:x})}let h=await rx(),g;if(i?.modelToken){let _=nd(o),S=rd(i),w=`${_}/${S}`;if(!this.ensuredProviders.has(w)){let v=this.getOpenclawConfig(),I=await v.getAllowlistModelsForProvider(_),A=a0(i,c,d,I);A&&(await v.ensureProvider(_,A),await v.addModelToAllowlist(w),this.ensuredProviders.add(w))}g=w}return new qr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:x,...h?{gatewayToken:h}:{},...g?{slashModelOnStart:g}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e,r){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=r??e.model;for(let c of e.sessions.keys()){let d=nd(c),u=`${d}/${o}`,x=!0;try{await i.removeProvider(d)}catch(h){x=!1,ue.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(h)})}try{await i.removeModelFromAllowlist(u)}catch(h){x=!1,ue.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(h)})}x&&this.ensuredProviders.delete(u)}}};import{randomUUID as xx}from"node:crypto";import{promises as Qb}from"node:fs";import{basename as hx}from"node:path";$e();te();import{promises as $b}from"node:fs";import{basename as Vb}from"node:path";var dx=q("file-upload"),Jb="/api/coze_claw/file/agent_upload",Zb=6e4;async function lx(t,e={}){let i=`${Lr(Nr(e.handshakeBase))}${Jb}`,o=e.timeoutMs??Zb,c=await $b.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",...An(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},x=new AbortController,h=setTimeout(()=>x.abort(),o);dx.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:x.signal}),_=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=${_}: ${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=${_}`);let w=S.data?.file?.file_url;if(!w)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(S).slice(0,200)}`);return dx.info("file upload ok",{uri:w,logid:_}),{uri:w}}catch(g){throw g instanceof T?g:g.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Vb(t.path)}`):new T("UPLOAD_FAILED",String(g),{cause:g})}finally{clearTimeout(h)}}$e();te();import{extname as Yb}from"node:path";var Xb={".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 ux(t){let e=Yb(t).toLowerCase();return Xb[e]??"application/octet-stream"}Ce();var Mo=q("agent-send"),fx=50*1024*1024;function px(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 gx(t,e,r,i,o,c){let u;for(let x=0;x<=2;x++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(h){u=h,x<2&&(Mo.warn("sendAgentFileUpdate failed, retrying",{attempt:x+1,err:String(h)}),await new Promise(g=>setTimeout(g,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function mx(t,e){let{session:r,runtime:i}=px(e.core,t.agentId,t.sessionId);if(!await di(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await Qb.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>fx)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${fx}`);let c=await ux(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??hx(t.path),u;try{u=await lx({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(h){throw Mo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:h instanceof T?h.code:"UNKNOWN",message:h instanceof Error?h.message:String(h)}),h}let x={sessionUpdate:"agent_file",messageId:xx(),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 gx(e,r,i,t.sessionId,x,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Mo.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 _x(t,e){let{session:r,runtime:i}=px(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??hx(t.path),c={sessionUpdate:"group_file",messageId:xx(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await gx(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Mo.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 yx(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}Qt();te();fn();var zt=q("coze-cli-installer"),bx="@coze/cli@latest",eE="coze",Ex="0.1.8",tE=5e3,nE=5e3,rE=9e4,vx=1e4,Xi=null,Bo=!1;async function Ed(t,e={}){if(Bo)return;if(Xi)return Xi;let r=e.exec??$f;return Xi=(async()=>{try{let i=await iE(eE,r),o=!1;if(i){let d=await sE(r);if(d===void 0)zt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(yx(d,Ex))zt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Ex}),o=!0;else{zt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Bo=!0;return}}let c=o?"upgrade-only":"full";zt.info("coze-cli install start",{package:bx,mode:c});try{await r("npm",["i","-g","--prefer-online",bx],{timeout:rE,maxBuffer:10*1024*1024}),zt.info("coze-cli install ok")}catch(d){zt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Bo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:vx}),zt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){zt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:vx}),zt.info("coze auth login ok")}catch(d){zt.warn("coze auth login failed",{err:String(d)});return}Bo=!0}finally{Xi=null}})(),Xi}async function iE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:tE});return Ha(i)}catch{return}}async function sE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:nE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Kt();Wt();Ce();var oE=10*6e4;function Sx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?oE:e}function zo(t){return hr(t??Z().configFile)}function Qi(t,e){return pr(e??Z().configFile,t)}import{randomBytes as AE}from"node:crypto";lr();$e();te();import{createReadStream as aE}from"node:fs";import{mkdir as cE,readFile as dE,realpath as lE,stat as uE,writeFile as fE}from"node:fs/promises";import{basename as xE,dirname as vd,isAbsolute as hE,join as pE,relative as gE,resolve as Ix,sep as mE}from"node:path";import{createInterface as wE}from"node:readline";var kx=q("fs-rpc"),es=Ze("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Tx(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>es)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${es} bytes`);let i=await Px(t.path,e);return await cE(vd(i),{recursive:!0}),await fE(i,t.content,"utf8"),kx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Rx(t,e){let r=await Px(t.path,e),i=await uE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>es&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${es} bytes`);let c;if(o&&i.size>es)c=await _E(r,t.line??1,t.limit);else{let d=await dE(r,"utf8");if(o){let u=d.split(`
107
+ `),x=Math.max(0,(t.line??1)-1),h=typeof t.limit=="number"?x+t.limit:void 0;c=u.slice(x,h).join(`
108
+ `)}else c=d}return kx.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function _E(t,e,r){let i=wE({input:aE(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 x of i)if(u>=o&&u<c&&d.push(x),u++,u>=c)break}finally{i.close()}return d.join(`
109
+ `)}async function Px(t,e){if(typeof t!="string"||t.length===0)throw new T("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([Ax(Ix(e)),Ax(Ix(t))]),o=gE(r,i);if(yE(o,mE,hE(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function yE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Ax(t){let e=[],r=t;for(;r!==vd(r);)try{let i=await lE(r);return e.length?pE(i,...e.reverse()):i}catch{e.push(xE(r)),r=vd(r)}return t}te();var Cx=q("prompt-multimodal"),Dx=10*1024*1024,bE=15e3,EE=6;async function Ox(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 vE(d))}}let o=Array.from({length:Math.min(EE,t.length)},()=>i());return await Promise.all(o),e}function Lx(t){return t.some(e=>e.type==="image")}async function vE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!zi(e.uri))return t;try{let{buf:r,contentType:i}=await IE(e.uri),o=e.mimeType||SE(i)||"application/octet-stream";return Cx.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 Cx.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function SE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function IE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),bE);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>Dx)throw new Error(`image too large: ${o.byteLength} bytes (max ${Dx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}Kt();$e();te();var $=q("core"),kE=3e4,TE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,RE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",PE="\u5BA1\u6279\u5DF2\u8D85\u65F6",CE=3e4,Fo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Ur;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=Sx(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){$.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&$.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Yi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(Tn(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>$.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(ko(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&TE.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Fr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Fr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Fr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(o){$.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(Tn(r,Vi(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 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 x=o.sessions.get(c);if(x?.pendingPermission){let h=r._meta?.cozeTriggerMsgId,g=mo(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,x,c,RE,h,g)}}let d=Date.now(),u=!1;try{let x=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,x}finally{$.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=jf(i);switch(r){case"session/new":{let c=DE();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return $.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=en(e)?qf(i._meta):void 0;if(u!==void 0&&!Rn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${gd(e.framework)}`);let x=await this.ensureRuntime(e,d);if(u!==void 0&&x.permissionMode===void 0&&(x.permissionMode=u,await this.persistSessionMapping(e)),x.replySeq=0,await this.ensureDownstream(e,d,x),!x.downstream||!x.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&x.permissionMode!==void 0&&x.permissionMode!==u){let S=x.permissionMode;x.permissionMode=u,await this.persistSessionMapping(e);try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),w}}let h=i._meta?.cozeTriggerMsgId;h?e.activeTriggers.set(x.acpSessionId,h):e.activeTriggers.delete(x.acpSessionId);let g=mo(i._meta);if(g?e.activeGroupIds.set(x.acpSessionId,g):e.activeGroupIds.delete(x.acpSessionId),g&&x.cozeGroupId!==g&&(x.cozeGroupId=g,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Lx(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await Ox(c.prompt);try{let S=await x.downstream.sessionPrompt({...c,sessionId:x.acpSessionId,prompt:_});return x.lastActiveAt=Date.now(),S}catch(S){if(S instanceof T&&S.code==="AGENT_APPROVAL_TIMEOUT"){let w=x.pendingPermission;w&&(w.downstream.respondAgentRequest(w.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(w.upstreamId),x.pendingPermission=void 0);let v=x.acpSessionId,I=v?e.activeTriggers.get(v):void 0,A=v?e.activeGroupIds.get(v):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,x,d,PE,I,A)}throw S}finally{if(e.activeTriggers.delete(x.acpSessionId),e.activeGroupIds.delete(x.acpSessionId),x.pendingPermission=void 0,x.reloadAfterTurn){x.reloadAfterTurn=!1;let S=x.downstream;S&&(x.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:x.acpSessionId}),S.stop("reload-after-turn").catch(w=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(w)})))}else x.downstream?.isAlive()&&this.armIdleTimer(e,d,x)}}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 x=e.getSessionQueue(d);x.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:x.size}),x.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 c=o,d=c.sessionId,u=c.modeId,x=mo(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!en(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(!Rn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${gd(e.framework)}`);if(x)return await this.handleGroupSetMode(e,x,u);let h=e.sessions.get(d)??await this.ensureRuntime(e,d);if(h.permissionMode===u)return{};let g=h.permissionMode;if(h.permissionMode=u,await this.persistSessionMapping(e),h.downstream?.isAlive()&&h.acpSessionId)try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(_){throw h.permissionMode=g,await this.persistSessionMapping(e).catch(()=>{}),_}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new 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 $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,x=d.runtime.acpSessionId;u?.isAlive()&&x&&c.push({downstream:u,acpSessionId:x,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 x of o)x.runtime.permissionMode=x.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 en(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?l0:u0:c.permissionMode=e.framework==="claude-code"?yd:cx),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(mt.GEN_MODEL_TOKEN,i,CE);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(Yi(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,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)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((c-(Date.now()-u))/1e3)}s`);let x;try{x=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(h){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&($.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),h}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=x,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await x.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(h){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),i.acpSessionId=void 0;let g=await x.sessionNew({cwd:e.workspace});i.acpSessionId=g.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let h=await x.sessionNew({cwd:e.workspace});i.acpSessionId=h.sessionId,await this.persistSessionMapping(e)}}catch(h){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),await x.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,h}if(x.afterSessionEstablished&&i.acpSessionId&&await x.afterSessionEstablished(i.acpSessionId),en(e)&&i.acpSessionId&&i.permissionMode)try{await x.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(h){$.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(h)})}}armIdleTimer(e,r,i){if(Yi(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let d=e.activeTriggers.get(r.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(zr("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(zr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(x=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(x)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(NE(r)){$.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=r.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&en(e)){let g=d.currentModeId;Rn(e.framework,g)&&c.permissionMode!==g?(c.permissionMode=g,this.persistSessionMapping(e).catch(_=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof g=="string"&&!Rn(e.framework,g)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:g})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},x=e.activeTriggers.get(i);x&&(u.cozeTriggerMsgId=x);let h=e.activeGroupIds.get(i);h&&(u.cozeGroupId=h),this.upstream.send(zr("session/update",{...r,sessionId:o,_meta:u})).catch(g=>$.warn("forward update failed",{agentId:e.agentId,err:String(g)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}$.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Tx(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Rx(c,o);r.respondAgentRequest(i.id,d)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Vi(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,x=u?e.activeTriggers.get(u):void 0,h={cozeAgentId:e.agentId};x&&(h.cozeTriggerMsgId=x);let g=u?e.activeGroupIds.get(u):void 0;g&&(h.cozeGroupId=g);let _=u?this.reverseSessionId(e,u):void 0,S=_?e.sessions.get(_):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let w={...c,..._?{sessionId:_}:{},_meta:h};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:_}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Ki(o,"session/request_permission",w)).catch(v=>{this.pendingUpstream.delete(o),$.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?($.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"&&OE(e.result,o),$.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Ao(e.error)):i.value.resolve(e.result);return}$.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),d=e.get(c);if(d)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=kE){let o=this.upstreamIds.next(e);return new Promise((c,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:c,reject:d,timer:u}),this.upstream.send(Ki(o,e,r)).catch(x=>{let h=this.pendingBridge.get(o);h&&(clearTimeout(h.timer),this.pendingBridge.delete(o)),d(x)})})}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&&en(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await li(e.agentId,r,this.paths)}catch(r){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(Tn(e,{code:r,message:i,data:{bridgeVersion:Bt}}))}};function DE(){return AE(16).toString("hex")}function OE(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){$.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){$.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var LE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function NE(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{text:o}=i;return LE.some(c=>o.startsWith(c))}Wt();te();Ce();import{randomBytes as ME}from"node:crypto";import{createServer as BE}from"node:http";var zE=1e6,Nx=q("ipc"),Uo=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Z()}async start(){this.token=ME(32).toString("hex");let e=BE((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(),Nx.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 ht(this.paths.portFile,String(this.port)),await ht(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){ts(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){ts(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await FE(e)}catch(u){ts(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);ts(r,200,u??{ok:!0})}catch(u){Nx.error("IPC handler failed",{key:o,err:String(u)}),ts(r,500,{error:u instanceof Error?u.message:String(u)})}}};function ts(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function FE(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>zE)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 oS=jt(Ph(),1),aS=jt(Jo(),1),cS=jt(Kr(),1),dS=jt(Ld(),1),lS=jt(Bd(),1),uS=jt(qd(),1),Fh=jt(Qo(),1),fS=jt(zh(),1);var Uh=Fh.default;$e();te();var{FWS:TS}=Yh(),Le=q("upstream.frontier"),Qh="application/json",ep="none",RS=15e3;function PS(t){class e extends Uh{constructor(i){super(i,Zf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Le.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(Ol("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");Le.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Le.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ls=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Le.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Yf,...An(this.opts.ppeOverride)},r=PS(e),i=Qf(this.opts.urlOverride),o={url:i,ws:r,fpID:Jf,aID:wo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Qh,force:!0},payloadEncoding:{encoding:ep,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new TS(o),d=!1,u=null,x,h,g=new Promise((w,v)=>{x=w,h=v}),_=w=>{d||(d=!0,u&&(clearTimeout(u),u=null),w?h(w):x())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let w=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:w,openCount:this.openCount}),w&&_();for(let v of this.connectHandlers)Promise.resolve(v({initial:w})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=w=>{this.opened=!1,Le.info("frontier closed",{code:w.code,reason:w.reason,willReconnect:w.willReconnect})},c.onerror=w=>{Le.warn("frontier error",{code:w.code,msg:w.message}),_(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${w.code} msg=${w.message??""}`))},c.onmessage=w=>this.handleMessage(w),this.fws=c;let S=this.opts.openTimeoutMs??RS;u=setTimeout(()=>{_(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await g}catch(w){try{c.close(1e3,"open failed")}catch(v){Le.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,w}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Le.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?(Le.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),c=e;tp(c)||Le.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:Qh,payloadEncoding:ep})}catch(u){throw Le.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.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){Le.debug("drop non-adapter frontier frame",{service:r});return}let i=OS(e);if(!i){Le.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Le.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Le.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;tp(c)||Le.info("frontier frame in",{logid:DS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:CS(i)}),Promise.resolve(this.handler(o)).catch(d=>Le.warn("frontier frame handler threw",{err:String(d)}))}};function tp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var np=2e3;function CS(t){return t.length<=np?t:`${t.slice(0,np)}...<truncated, total ${t.length} chars>`}function DS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function OS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}$e();te();var $d=q("skill-publish"),LS="/api/marketplace/product/skill/publish_with_assets",NS=15e4;async function rp(t,e={}){let i=`${Lr(Nr(e.handshakeBase))}${LS}`,o=e.timeoutMs??NS,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",...An(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,x=setTimeout(()=>u.abort(),o);$d.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let h=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),g=h.headers.get("x-tt-logid")??"";if(!h.ok){let w=await h.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${h.status} logid=${g}: ${w.slice(0,200)}`)}let _=await h.json();if($d.info("skill publish response",{logid:g,httpStatus:h.status,code:_.code,msg:_.msg,dataSkillId:_.data?.skill_id??"",dataVersion:_.data?.version??""}),_.code!==void 0&&_.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${_.code} msg=${_.msg??"-"} logid=${g}`);let S={};return _.data?.skill_id!==void 0&&_.data.skill_id!==""&&(S.skillId=String(_.data.skill_id)),_.data?.version&&(S.version=_.data.version),$d.info("skill publish ok",{logid:g,skillId:S.skillId??"",version:S.version??""}),S}catch(h){throw h instanceof T?h:h.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(h),{cause:h})}finally{clearTimeout(x)}}te();var Vd=q("upstream.switchable"),ca=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Vd.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 Vd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Vd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};te();var Jd=q("upstream"),Xr=class{handler=null;async start(){Jd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Jd.info("NoopUpstream stopped",{reason:e})}async send(e){Jd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};$e();te();Wt();te();Ce();import{promises as MS}from"node:fs";var ip=q("pat-token-store");async function da(t=Z()){try{let r=(await MS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(ip.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"&&ip.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function us(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await ht(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as la}from"node:fs";import{join as BS}from"node:path";function zS(t,e){return`#!/bin/sh
110
110
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
111
- `}function zS(t,e){return`@echo off\r
111
+ `}function FS(t,e){return`@echo off\r
112
112
  "${e}" "${t}" %*\r
113
- `}async function rp(t,e=J()){let r=e.binDir;await ca.mkdir(r,{recursive:!0});let i=BS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?zS(t,o):FS(t,o);return await ca.readFile(i,"utf8").catch(()=>null)===c||(await ca.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ca.chmod(i,493)),r}ee();Re();import{execSync as ip}from"node:child_process";import{readFileSync as sp,unlinkSync as US}from"node:fs";import{mkdir as GS,open as HS,readFile as op,unlink as Vd,writeFile as jS}from"node:fs/promises";import{dirname as qS}from"node:path";var WS=G("single-instance"),KS=t=>new Promise(e=>setTimeout(e,t)),da=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??J().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ki(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&WS.warn("removing stale pid file",{stalePid:i}),await jS(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 op(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Vd(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 op(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 GS(qS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await HS(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(r);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await KS(this.claimLockIntervalMs);continue}await Vd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Vd(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=sp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Fr)||r.includes("lib/index.js"))}catch{}try{let r=ip(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Fr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=ip(`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{sp(this.pidFile,"utf8").trim()===String(this.selfPid)&&US(this.pidFile)}catch{}})}};la();ee();var nr=G("daemon.upstream-watchdog"),e1=12e4,t1=9e5,n1=3e4;function Zd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ua=class{constructor(e){this.opts=e;this.softMs=e.softMs??Zd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",e1),this.hardMs=e.hardMs??Zd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",t1),this.intervalMs=e.intervalMs??Zd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",n1),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),nr.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&nr.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&nr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,nr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){nr.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:r,hardMs:this.hardMs}),this.opts.onFatal(r);return}r>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,nr.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>nr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var j=G("daemon");async function dp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Rl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Be(P,t).logs,listAgentIds:()=>bs(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
113
+ `}async function sp(t,e=Z()){let r=e.binDir;await la.mkdir(r,{recursive:!0});let i=BS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?FS(t,o):zS(t,o);return await la.readFile(i,"utf8").catch(()=>null)===c||(await la.writeFile(i,c,"utf8"),process.platform!=="win32"&&await la.chmod(i,493)),r}te();Ce();import{execSync as op}from"node:child_process";import{readFileSync as ap,unlinkSync as US}from"node:fs";import{mkdir as GS,open as HS,readFile as cp,unlink as Zd,writeFile as qS}from"node:fs/promises";import{dirname as jS}from"node:path";var WS=q("single-instance"),KS=t=>new Promise(e=>setTimeout(e,t)),ua=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Z().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ji(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&&WS.warn("removing stale pid file",{stalePid:i}),await qS(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 cp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Zd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let r=await cp(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 GS(jS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await HS(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 KS(this.claimLockIntervalMs);continue}await Zd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Zd(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=ap(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Gr)||r.includes("lib/index.js"))}catch{}try{let r=op(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Gr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=op(`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{ap(this.pidFile,"utf8").trim()===String(this.selfPid)&&US(this.pidFile)}catch{}})}};fa();te();var sr=q("daemon.upstream-watchdog"),e2=12e4,t2=9e5,n2=3e4;function Xd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var xa=class{constructor(e){this.opts=e;this.softMs=e.softMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",e2),this.hardMs=e.hardMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",t2),this.intervalMs=e.intervalMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",n2),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?.(),sr.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&&sr.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&&sr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,sr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){sr.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,sr.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>sr.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=q("daemon");async function up(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Cl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Fe(P,t).logs,listAgentIds:()=>vs(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
114
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
115
115
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
116
- `)}catch{}}let e=new da({processTitle:Fr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Mo(),o=i??{};ws({pid:process.pid}),j.info(i?"loaded bridge config":"initialized bridge config");let c=new oa(new Jr),l=null,u=new Bo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,z,H,Q)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(P,z,H,Q)}}),f=new Oo({paths:t,config:o,registry:u});l=f;let x,g,w=null,S={},y,v=null,I=null,A=null,R=new kn;function C(P,z){return R.enqueue(()=>D(P,z))}function b(){I||(I=new ua({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?C(A,{force:!0}):void 0,onFatal:P=>{if(process.env[ds]==="1"){j.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}j.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function D(P,z){let H=P,Q=H?.privatecode;if(!Q)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let $e=zi(H.env),xe=H.handshake_url,pe=H.frontier_url,At=cp(H.env,xe,pe);if(A=H,!z?.force&&x===Q&&g===At){let _e=await r1(t);return u.agents.size===0&&_e?(j.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ha(t,f).catch(ke=>j.warn("connect-noop auto-revive error (ignored)",{err:String(ke)}))):j.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let gt=!!x&&x!==Q,sn=g!==void 0&&g!==At,zt=gt||sn,on=await Xc({privatecode:Q,...xe?{endpoint:xe}:{},ppeOverride:$e});if(zt){j.warn("connect config switched, resetting agents",{pcChanged:gt,envChanged:sn,previousPc:x?fa(x):"",nextPc:fa(Q)});for(let _e of[...u.agents.values()])await _e.dispose("connect config switch").catch(()=>{}),u.agents.delete(_e.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"connect switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),yd({patToken:Q,env:H.env}).catch(_e=>j.warn("coze-cli setup error (ignored)",{err:String(_e)}));let ei=new as({handshake:on,privatecode:Q,...pe?{urlOverride:pe}:{},ppeOverride:$e,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(ei,"connect"),x=Q,g=At,S=$e,y=xe,H.mock_scenario!==void 0&&(u.setMockScenario(H.mock_scenario),j.info("mock scenario set",{scenario:H.mock_scenario})),v||(v=new Hi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(_e=>j.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:V})),v.start(),b(),zt&&ha(t,f).catch(_e=>j.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),cs(Q,t).catch(_e=>j.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),j.info("/connect: WS established",{deviceId:w}),{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 bo({agents:u.agents,paths:t,publishSkillToMarketplace:async P=>{let z=u.agents.get(P.agentId)?.patToken??x;if(!z)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return tp({patToken:z,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,z)=>{let H=u.agents.get(P);if(H){await f.cleanupOpenclawSessionProviders(H).catch($e=>j.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String($e)})),H.framework==="hermes"&&H.deployType==="cloud"&&await id(P,t).catch($e=>j.warn("cleanup hermes-home failed (ignored)",{agentId:P,err:String($e)}));let Q=!0;try{await H.dispose(`disconnect: ${z}`)}catch($e){Q=!1,j.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String($e)}),H.status="error"}Q&&(H.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,z)=>{let H=u.agents.get(P);H&&(await f.cleanupOpenclawSessionProviders(H).catch(Q=>j.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(Q)})),H.framework==="hermes"&&H.deployType==="cloud"&&await id(P,t).catch(Q=>j.warn("cleanup hermes-home during delete failed (ignored)",{agentId:P,err:String(Q)})),await H.dispose(`delete: ${z}`).catch(Q=>j.warn("dispose during delete failed (ignored)",{agentId:P,err:String(Q)})),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,z)=>{await f.cleanupOpenclawSessionProviders(P,z)},openclawRepair:async(P,z)=>{await f.openclawRepair(P,z)},hermesReset:async(P,z)=>{let H=await ve(P).catch(()=>null);!H||H.framework!=="hermes"||H.deployType!=="cloud"||await l0({paths:t,agentId:P,model:H.model,modelInfo:H.modelInfo,cozeEnv:z,mockScenario:u.getMockScenario()})},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 Ss({paths:t,handlers:F,agentManager:f,sendDetail:P=>u.sendRequest("_agent/detail",P)});O.ref=B;let V=async P=>{await Promise.allSettled(P.map(async z=>{try{await F.disconnectAgent({agentId:z.agentId,reason:`auth_failure: code=${z.code} ${z.message}`}),j.info("agent disconnected due to auth failure from heartbeat response",{agentId:z.agentId,code:z.code,message:z.message})}catch(H){j.warn("disconnect during authFailure handling failed (ignored)",{agentId:z.agentId,err:String(H)})}}))};c.onConnect(({initial:P})=>{j.info("frontier upstream connected, triggering detail sync",{initial:P}),B.syncAll(P?"initial-connect":"reconnect").catch(z=>j.warn("detail sync top-level error (ignored)",{err:String(z)}))});let $=new Fo({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[ds]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let z=P,H=z?.privatecode,Q=z?.pairing_code;if(!H||!Q)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let $e=zi(z.env),xe=z.handshake_url,pe=z.frontier_url,At=cp(z.env,xe,pe),gt=!!x&&x!==H,sn=g!==void 0&&g!==At,zt=gt||sn,on=await Xc({privatecode:H,...xe?{endpoint:xe}:{},ppeOverride:$e});if(zt){j.warn("pair config switched, resetting agents",{pcChanged:gt,envChanged:sn,previousPc:x?fa(x):"",nextPc:fa(H),previousEnvKey:g??"",nextEnvKey:At});for(let ke of[...u.agents.values()])await ke.dispose("pair config switch").catch(()=>{}),u.agents.delete(ke.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Jr,"pair switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),yd({patToken:H,env:z.env}).catch(ke=>j.warn("coze-cli setup error (ignored)",{err:String(ke)}));let ei=new as({handshake:on,privatecode:H,...pe?{urlOverride:pe}:{},ppeOverride:$e,getPatTokenForAgent:ke=>u.agents.get(ke)?.patToken});await c.swap(ei,"pair");try{let ke=new Zn;o.frameworksCache=await ke.detectAll(),await Zi(o),j.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(ke){j.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ke)})}let _e=Object.keys(o.frameworksCache??{});try{let ke=await u.sendRequest("_agent/pair",{pairCode:Q,patToken:H,frameworks:_e,_meta:{cozeDeviceId:w}});j.info("_agent/pair ok",{pairResult:ke}),x=H,g=At,S=$e,y=xe,z.mock_scenario!==void 0&&(u.setMockScenario(z.mock_scenario),j.info("mock scenario set",{scenario:z.mock_scenario})),cs(H,t).catch(Oe=>j.warn("writePatToken after /pair failed (ignored)",{err:String(Oe)})),v||(v=new Hi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(Oe=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Oe)})),onAuthFailures:V})),v.start(),b(),zt&&ha(t,f).catch(Oe=>j.warn("post-pair-switch auto-revive error (ignored)",{err:String(Oe)}));let rr;return z.agent_id&&(rr=await s1(z.agent_id,t,f,Oe=>u.sendRequest("_agent/detail",Oe),H).catch(Oe=>(j.error("--agent-id ensureAgent failed",{agentId:z.agent_id,err:String(Oe)}),{ok:!1,agentId:z.agent_id??"",note:String(Oe)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(ke){return j.error("_agent/pair failed",{err:String(ke)}),{ok:!1,note:`pair failed: ${String(ke)}`}}}},{method:"POST",path:"/connect",handler:P=>C(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let z=P;return{ok:!0,result:await f.createAgent(z)}}},{method:"POST",path:"/agent/send",handler:async P=>{let z=P;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 H=z;return await(H.groupFile?gh:ph)(H,{core:u,patToken:x,handshakeBase:y,ppeOverride:S})}catch(H){if(H instanceof T)return{ok:!1,code:H.code,message:H.message};throw H}}},{method:"POST",path:"/reload",handler:async P=>{let z=P?.agent_id,H=await u.reloadAgents(z);return j.info("IPC /reload: recycled agent subprocesses",{agentId:z??"(all)",recycled:H}),{ok:!0,recycled:H}}},{method:"POST",path:"/shutdown",handler:async()=>(j.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:Y}=await $.start();try{await rp(t.libEntry,t)}catch(P){j.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),o1({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Zn().detectAll(),await Zi(o),o.frameworksCache)}).catch(P=>j.warn("startup warmup error (ignored)",{err:String(P)})),zl().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(dn(),Bl));for(let z of["claude-code","codex"]){let H=await P(z);H&&j.info("acp wrapper version",{framework:z,version:H})}}).catch(P=>j.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let se=null,oe={port:re,token:Y,core:u,ipc:$,shutdown(P){return se||(j.info("daemon shutdown",{reason:P}),se=(async()=>{v?.stop(),I?.stop(),await u.stop(P),await $.stop(),await e.release()})(),se)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{oe.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>M0()),process.on("unhandledRejection",P=>{j.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{j.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}
117
- `)}catch{}process.exit(1)}),j.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),c1({cliSpawned:process.env[ds]==="1",readPatToken:()=>aa(t),connect:C}).catch(P=>j.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),oe}async function r1(t){return bs(t).length>0}function fa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function cp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function i1(t,e){let r=bs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(qt(),vs));for(let c of r){await o(c,t).catch(l=>j.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),j.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),j.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){j.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function s1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(qt(),vs)),l=await c(t,e);if(l){if(l.deletedAt)throw new T("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);j.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let g=lp(l),w={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...o?{patToken:o}:{},...g?{_meta:g}:{}};return await r.createAgent(w),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}j.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 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 o1(t){let e=t.logger??j;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 i1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ha(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await a1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ha(t,e){let{readdir:r}=await import("node:fs/promises"),i;try{i=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(qt(),vs));j.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){j.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),l+=1;continue}if(!f){l+=1;continue}if(f.deletedAt){j.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),l+=1;continue}if(f.disconnectedAt){j.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),l+=1;continue}try{j.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=lp(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){j.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),l+=1}}return j.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function a1(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 S0(o,t)).status==="refreshed"&&(i+=1)}catch(c){j.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&j.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function c1(t){let e=t.logger??j;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 lp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}la();Re();import{readFile as up}from"node:fs/promises";var rn=class{paths;constructor(e){this.paths=e??J()}async probe(e=1e3){let r=await xa(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:l1(i)}}}async request(e){let r=await xa(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,l=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),f=await u.text();return{status:u.status,body:d1(f)}}finally{clearTimeout(l)}}};async function xa(t){try{let[e,r]=await Promise.all([up(t.portFile,"utf8"),up(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 d1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function l1(t){return t instanceof Error?t.message:String(t)}Yt();ee();ar();import{spawn as u1}from"node:child_process";import{userInfo as hp}from"node:os";var Yd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",f1=new Set(["bash","zsh","sh","dash","ksh"]),fp=Ve("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),h1=2e3;function x1(t,e=Yd){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 l of o.split(`
118
- `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function p1(){let t=(process.env.SHELL??"").trim()||(hp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return f1.has(e)?t:null}function g1(t){return new Promise(e=>{let r=`printf '%s' '${Yd}'; env; printf '%s' '${Yd}'`,i;try{i=u1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??hp().homedir}})}catch{e(null);return}let o="",c=!1,l=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(()=>l("SIGTERM"),fp),x=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},fp+h1)})}async function Xd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=p1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??g1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=x1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Re();function Pn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],l=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||r.push(c)}return{value:i,rest:r}}dn();import{chmod as m1,copyFile as xp,mkdir as gp,readFile as us,rename as pp,rm as tl,stat as nl,writeFile as w1}from"node:fs/promises";import{homedir as VD}from"node:os";import{dirname as _1,join as Ft,resolve as rl,sep as ls}from"node:path";import{fileURLToPath as y1}from"node:url";Yt();ee();Re();var Zr=G("dist-install");function mp(){return{darwin:{arm64:"@zed-industries/codex-acp-darwin-arm64",x64:"@zed-industries/codex-acp-darwin-x64"},linux:{arm64:"@zed-industries/codex-acp-linux-arm64",x64:"@zed-industries/codex-acp-linux-x64"},win32:{arm64:"@zed-industries/codex-acp-win32-arm64",x64:"@zed-industries/codex-acp-win32-x64"}}[process.platform]?.[process.arch]}function b1(){return process.platform==="win32"?"codex-acp.exe":"codex-acp"}function E1(t){let e=y1(t),r=_1(e),i=`${ls}src${ls}`;if(r.includes(i)||r.endsWith(`${ls}src${ls}cli`))return null;let o=rl(r,"index.js"),c=rl(r,"..","package.json");return{dist:o,pkgJson:c}}async function il(t={}){let e=t.paths??J(),r=E1(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,l;try{let v=JSON.parse(await us(o,"utf8"));c=v.version??"unknown",l=v.dependencies??{}}catch(v){return Zr.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=_s.map(v=>({name:v,spec:l[v]??"latest"})),f=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await Mo(e.configFile)??{},g=x.libVersion,w=await us(e.libEntry).then(()=>!0).catch(()=>!1),S=g===c,y=await wp(e,u);if(S&&w&&y)return{kind:"already-current",libVersion:c};if(!S||!w){await gp(e.libDir,{recursive:!0}),await xp(i,e.libEntry),await xp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=rl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
119
- `;await us(v,"utf8").catch(()=>null)!==I&&await w1(v,I)}return y||(t.installWrappers?await t.installWrappers(e,f):await S1(e,f,u)),x.libVersion=c,await Zi(x,e.configFile),Zr.info("dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:c}),S&&w?{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 wp(t,e){for(let r of e){let i=Ft(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await us(i,"utf8"))}catch(l){return Zr.warn("wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(l)}),!1}let c=o.version;if(!c)return Zr.warn("wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!v1(c,r.spec))return Zr.warn("wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await _p(Ft(t.libDir,"node_modules"))}function v1(t,e){let r=Qd(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=Qd(i.slice(1));if(!c)return!0;if(el(r,c)<0)return!1;let l=c[0]>0?[c[0]+1,0,0]:c[1]>0?[0,c[1]+1,0]:[0,0,c[2]+1];return el(r,l)<0}let o=Qd(i);return o?el(r,o)===0:!0}function Qd(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function el(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 S1(t,e,r){await k1(t.installLock,async()=>{if(await wp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ls}.staging-${process.pid}-${i}`,c=Ft(o,"node_modules"),l=Ft(t.libDir,"node_modules");try{await gp(o,{recursive:!0}),await I1(e,o),await A1(c);let u=`${l}.trash-${i}`;await pp(l,u).catch(()=>{}),await pp(c,l),await tl(u,{recursive:!0,force:!0}).catch(()=>{}),Zr.info("wrapper closure installed",{liveNm:l,specs:e})}finally{await tl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function I1(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=nt("npm",r,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",f=>{l.length<8192&&(l+=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}: ${l.trim().slice(0,2e3)}`))})})}async function A1(t){for(let e of _s){let r=Ft(t,...e.split("/")),i=JSON.parse(await us(Ft(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=Ft(t,".bin",o),l=await nl(c);process.platform!=="win32"&&!(l.mode&73)&&await m1(c,l.mode|73).catch(()=>{})}if(!await _p(t)){let e=mp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex-acp binary \u7F3A\u5931`)}}async function _p(t){let e=mp();if(!e)return!0;let r=Ft(t,...e.split("/")),i=Ft(r,"package.json"),o=Ft(r,"bin",b1()),[c,l]=await Promise.all([nl(i).then(u=>u.isFile()).catch(()=>!1),nl(o).then(u=>u.isFile()).catch(()=>!1)]);return c&&l}async function k1(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 tl(t,{force:!0}).catch(()=>{})}}Ma();ee();Re();import{closeSync as bp,fstatSync as Ep,openSync as vp,readFileSync as T1,readSync as R1,readdirSync as P1,statSync as D1}from"node:fs";import{join as pa}from"node:path";var C1=new Set(["debug","info","warn","error"]);function Sp(t){let e=t,r=Pn(e,"--agent-id");e=r.rest;let i=Pn(e,"--date");e=i.rest;let o=Pn(e,"-n","--lines");e=o.rest;let c=Pn(e,"--level");e=c.rest;let l=Pn(e,"--grep");e=l.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=c.value&&C1.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),l.value&&(g.grep=l.value),g}function O1(t,e){return t.agentId?pa(Be(t.agentId,e).logs,cr("agent",t.date)):pa(e.bridgeLogsDir,cr("bridge",t.date))}function L1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function N1(t,e){let r;try{r=P1(t)}catch{return[]}let i=[];for(let o of r){let c=Na(o,e);if(!c)continue;let l=0;try{l=D1(pa(t,o)).size}catch{}i.push({file:pa(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Ip(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"&&!Cl(r,e.level))return!1}return!0}var yp={debug:"90",info:"36",warn:"33",error:"31"},M1=new Set(["ts","level","module","msg"]);function B1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Ap(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=B1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&yp[o]&&(c=`\x1B[${yp[o]}m${c}\x1B[0m`);let l=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",f=Object.entries(r).filter(([x])=>!M1.has(x)).map(([x,g])=>` ${x}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${l} ${u}${f}`}function F1(t,e,r){let c=T1(t,"utf8").split(`
120
- `).filter(l=>l.length>0).filter(l=>Ip(l,{level:e.level,grep:e.grep}));for(let l of L1(c,e.lines))process.stdout.write(`${Ap(l,{raw:e.raw,color:r})}
121
- `)}async function kp(t,e){let r=e.paths??J(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Be(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=N1(l,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
122
- `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
123
- `);return 0}let o=t.date??Cn(new Date),c=O1({agentId:t.agentId,date:o},r);try{F1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
116
+ `)}catch{}}let e=new ua({processTitle:Gr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await zo(),o=i??{};ys({pid:process.pid}),K.info(i?"loaded bridge config":"initialized bridge config");let c=new ca(new Xr),d=null,u=new Fo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,G,j,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,G,j,ee)}}),x=new No({paths:t,config:o,registry:u});d=x;let h,g,_=null,S={},w,v=null,I=null,A=null,R=new Pn;function D(P,G){return R.enqueue(()=>C(P,G))}function b(){I||(I=new xa({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:P=>{if(process.env[fs]==="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 C(P,G){let j=P,ee=j?.privatecode;if(!ee)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Je=Hi(j.env),pe=j.handshake_url,ge=j.frontier_url,Pt=lp(j.env,pe,ge);if(A=j,!G?.force&&h===ee&&g===Pt){let _e=await r2(t);return u.agents.size===0&&_e?(K.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),pa(t,x).catch(Re=>K.warn("connect-noop auto-revive error (ignored)",{err:String(Re)}))):K.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let bt=!!h&&h!==ee,an=g!==void 0&&g!==Pt,qt=bt||an,cn=await ed({privatecode:ee,...pe?{endpoint:pe}:{},ppeOverride:Je});if(qt){K.warn("connect config switched, resetting agents",{pcChanged:bt,envChanged:an,previousPc:h?ha(h):"",nextPc:ha(ee)});for(let _e of[...u.agents.values()])await _e.dispose("connect config switch").catch(()=>{}),u.agents.delete(_e.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 Xr,"connect switch").catch(()=>{})}_=cn.deviceId,ys({deviceId:_,pid:process.pid}),Ed({patToken:ee,env:j.env}).catch(_e=>K.warn("coze-cli setup error (ignored)",{err:String(_e)}));let ri=new ls({handshake:cn,privatecode:ee,...ge?{urlOverride:ge}:{},ppeOverride:Je,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(ri,"connect"),h=ee,g=Pt,S=Je,w=pe,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),K.info("mock scenario set",{scenario:j.mock_scenario})),v||(v=new Wi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(_e=>K.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:J})),v.start(),b(),qt&&pa(t,x).catch(_e=>K.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),us(ee,t).catch(_e=>K.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),K.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>x.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let L={},z=new vo({agents:u.agents,paths:t,publishSkillToMarketplace:async P=>{let G=u.agents.get(P.agentId)?.patToken??h;if(!G)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return rp({patToken:G,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:w,ppeOverride:S})},disposeAndMarkDisconnected:async(P,G)=>{let j=u.agents.get(P);if(j){await x.cleanupOpenclawSessionProviders(j).catch(Je=>K.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Je)})),j.framework==="hermes"&&j.deployType==="cloud"&&await od(P,t).catch(Je=>K.warn("cleanup hermes-home failed (ignored)",{agentId:P,err:String(Je)}));let ee=!0;try{await j.dispose(`disconnect: ${G}`)}catch(Je){ee=!1,K.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Je)}),j.status="error"}ee&&(j.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,G)=>{let j=u.agents.get(P);j&&(await x.cleanupOpenclawSessionProviders(j).catch(ee=>K.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(ee)})),j.framework==="hermes"&&j.deployType==="cloud"&&await od(P,t).catch(ee=>K.warn("cleanup hermes-home during delete failed (ignored)",{agentId:P,err:String(ee)})),await j.dispose(`delete: ${G}`).catch(ee=>K.warn("dispose during delete failed (ignored)",{agentId:P,err:String(ee)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!L.ref)throw new Error("agent-detail-sync not initialized yet");await L.ref.syncOne(P)},cleanupOpenclawProviders:async(P,G)=>{await x.cleanupOpenclawSessionProviders(P,G)},openclawRepair:async(P,G)=>{await x.openclawRepair(P,G)},hermesReset:async(P,G)=>{let j=await Ie(P).catch(()=>null);!j||j.framework!=="hermes"||j.deployType!=="cloud"||await f0({paths:t,agentId:P,model:j.model,modelInfo:j.modelInfo,cozeEnv:G,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>z.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>z.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>z.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>z.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>z.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>z.getFileContent(P.params)),u.registerExtension("_agent/update",P=>z.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>z.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>z.switchModel(P.params)),u.registerExtension("_agent/reset",P=>z.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>z.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>z.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>z.upgradeBridge(P.params));let M=new As({paths:t,handlers:z,agentManager:x,sendDetail:P=>u.sendRequest("_agent/detail",P)});L.ref=M;let J=async P=>{await Promise.allSettled(P.map(async G=>{try{await z.disconnectAgent({agentId:G.agentId,reason:`auth_failure: code=${G.code} ${G.message}`}),K.info("agent disconnected due to auth failure from heartbeat response",{agentId:G.agentId,code:G.code,message:G.message})}catch(j){K.warn("disconnect during authFailure handling failed (ignored)",{agentId:G.agentId,err:String(j)})}}))};c.onConnect(({initial:P})=>{K.info("frontier upstream connected, triggering detail sync",{initial:P}),M.syncAll(P?"initial-connect":"reconnect").catch(G=>K.warn("detail sync top-level error (ignored)",{err:String(G)}))});let V=new Uo({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[fs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let G=P,j=G?.privatecode,ee=G?.pairing_code;if(!j||!ee)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Je=Hi(G.env),pe=G.handshake_url,ge=G.frontier_url,Pt=lp(G.env,pe,ge),bt=!!h&&h!==j,an=g!==void 0&&g!==Pt,qt=bt||an,cn=await ed({privatecode:j,...pe?{endpoint:pe}:{},ppeOverride:Je});if(qt){K.warn("pair config switched, resetting agents",{pcChanged:bt,envChanged:an,previousPc:h?ha(h):"",nextPc:ha(j),previousEnvKey:g??"",nextEnvKey:Pt});for(let Re of[...u.agents.values()])await Re.dispose("pair config switch").catch(()=>{}),u.agents.delete(Re.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 Xr,"pair switch").catch(()=>{})}_=cn.deviceId,ys({deviceId:_,pid:process.pid}),Ed({patToken:j,env:G.env}).catch(Re=>K.warn("coze-cli setup error (ignored)",{err:String(Re)}));let ri=new ls({handshake:cn,privatecode:j,...ge?{urlOverride:ge}:{},ppeOverride:Je,getPatTokenForAgent:Re=>u.agents.get(Re)?.patToken});await c.swap(ri,"pair");try{let Re=new Qn;o.frameworksCache=await Re.detectAll(),await Qi(o),K.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Re){K.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Re)})}let _e=Object.keys(o.frameworksCache??{});try{let Re=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:j,frameworks:_e,_meta:{cozeDeviceId:_}});K.info("_agent/pair ok",{pairResult:Re}),h=j,g=Pt,S=Je,w=pe,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),K.info("mock scenario set",{scenario:G.mock_scenario})),us(j,t).catch(Ne=>K.warn("writePatToken after /pair failed (ignored)",{err:String(Ne)})),v||(v=new Wi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(Ne=>K.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:J})),v.start(),b(),qt&&pa(t,x).catch(Ne=>K.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let or;return G.agent_id&&(or=await s2(G.agent_id,t,x,Ne=>u.sendRequest("_agent/detail",Ne),j).catch(Ne=>(K.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(Ne)}),{ok:!1,agentId:G.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...or?{agent:or}:{}}}catch(Re){return K.error("_agent/pair failed",{err:String(Re)}),{ok:!1,note:`pair failed: ${String(Re)}`}}}},{method:"POST",path:"/connect",handler:P=>D(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let G=P;return{ok:!0,result:await x.createAgent(G)}}},{method:"POST",path:"/agent/send",handler:async P=>{let G=P;if(!G?.agentId||!G?.sessionId||!G?.kind||!G?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!h)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=G;return await(j.groupFile?_x:mx)(j,{core:u,patToken:h,handshakeBase:w,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 P=>{let G=P?.agent_id,j=await u.reloadAgents(G);return K.info("IPC /reload: recycled agent subprocesses",{agentId:G??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(K.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:X}=await V.start();try{await sp(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(),o2({paths:t,core:u,agentManager:x,detectAll:async()=>(o.frameworksCache=await new Qn().detectAll(),await Qi(o),o.frameworksCache)}).catch(P=>K.warn("startup warmup error (ignored)",{err:String(P)})),Gl().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(fn(),Fl));for(let G of["claude-code","codex"]){let j=await P(G);j&&K.info("acp wrapper version",{framework:G,version:j})}}).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:V,shutdown(P){return oe||(K.info("daemon shutdown",{reason:P}),oe=(async()=>{v?.stop(),I?.stop(),await u.stop(P),await V.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",()=>z0()),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}
117
+ `)}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"}),c2({cliSpawned:process.env[fs]==="1",readPatToken:()=>da(t),connect:D}).catch(P=>K.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),ae}async function r2(t){return vs(t).length>0}function ha(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function lp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function i2(t,e){let r=vs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(Kt(),Is));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 s2(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Kt(),Is)),d=await c(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`);K.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let g=fp(d),_={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...g?{_meta:g}:{}};return await r.createAgent(_),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}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 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 x={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(x);let h=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:h?"cloud agent acknowledged":"created from cloud detail"}}async function o2(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 i2(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await pa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await a2(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function pa(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(()=>(Kt(),Is));K.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let x;try{x=await o(u,t)}catch(h){K.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(h)}),d+=1;continue}if(!x){d+=1;continue}if(x.deletedAt){K.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:x.deletedAt}),d+=1;continue}if(x.disconnectedAt){K.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:x.disconnectedAt}),d+=1;continue}try{K.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:x.framework});let h=fp(x);await e.createAgent({agentId:x.agentId,framework:x.framework,...x.cozeIdentity?{cozeIdentity:x.cozeIdentity}:{},...x.model?{model:x.model}:{},...h?{_meta:h}:{}},{revive:!0}),c+=1}catch(h){K.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:x.framework,err:String(h)}),d+=1}}return K.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function a2(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 A0(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 c2(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 fp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}fa();Ce();import{readFile as xp}from"node:fs/promises";var on=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let r=await ga(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:l2(i)}}}async request(e){let r=await ga(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}),x=await u.text();return{status:u.status,body:d2(x)}}finally{clearTimeout(d)}}};async function ga(t){try{let[e,r]=await Promise.all([xp(t.portFile,"utf8"),xp(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 d2(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function l2(t){return t instanceof Error?t.message:String(t)}Qt();te();lr();import{spawn as u2}from"node:child_process";import{userInfo as pp}from"node:os";var Qd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",f2=new Set(["bash","zsh","sh","dash","ksh"]),hp=Ze("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),x2=2e3;function h2(t,e=Qd){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let d of o.split(`
118
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function p2(){let t=(process.env.SHELL??"").trim()||(pp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return f2.has(e)?t:null}function g2(t){return new Promise(e=>{let r=`printf '%s' '${Qd}'; env; printf '%s' '${Qd}'`,i;try{i=u2(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??pp().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(x),clearTimeout(h),e(g))};i.stdout?.on("data",g=>{o+=g.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let x=setTimeout(()=>d("SIGTERM"),hp),h=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},hp+x2)})}async function el(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=p2();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??g2)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=h2(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Ce();function On(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||r.push(c)}return{value:i,rest:r}}fn();import{chmod as m2,copyFile as gp,mkdir as wp,readFile as hs,rename as mp,rm as rl,stat as il,writeFile as w2}from"node:fs/promises";import{homedir as VD}from"node:os";import{dirname as _2,join as Ht,resolve as sl,sep as xs}from"node:path";import{fileURLToPath as y2}from"node:url";Qt();te();Ce();var Qr=q("dist-install");function _p(){return{darwin:{arm64:"@zed-industries/codex-acp-darwin-arm64",x64:"@zed-industries/codex-acp-darwin-x64"},linux:{arm64:"@zed-industries/codex-acp-linux-arm64",x64:"@zed-industries/codex-acp-linux-x64"},win32:{arm64:"@zed-industries/codex-acp-win32-arm64",x64:"@zed-industries/codex-acp-win32-x64"}}[process.platform]?.[process.arch]}function b2(){return process.platform==="win32"?"codex-acp.exe":"codex-acp"}function E2(t){let e=y2(t),r=_2(e),i=`${xs}src${xs}`;if(r.includes(i)||r.endsWith(`${xs}src${xs}cli`))return null;let o=sl(r,"index.js"),c=sl(r,"..","package.json");return{dist:o,pkgJson:c}}async function ol(t={}){let e=t.paths??Z(),r=E2(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 v=JSON.parse(await hs(o,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){return Qr.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=bs.map(v=>({name:v,spec:d[v]??"latest"})),x=u.map(({name:v,spec:I})=>`${v}@${I}`),h=await zo(e.configFile)??{},g=h.libVersion,_=await hs(e.libEntry).then(()=>!0).catch(()=>!1),S=g===c,w=await yp(e,u);if(S&&_&&w)return{kind:"already-current",libVersion:c};if(!S||!_){await wp(e.libDir,{recursive:!0}),await gp(i,e.libEntry),await gp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=sl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
119
+ `;await hs(v,"utf8").catch(()=>null)!==I&&await w2(v,I)}return w||(t.installWrappers?await t.installWrappers(e,x):await S2(e,x,u)),h.libVersion=c,await Qi(h,e.configFile),Qr.info("dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:c}),S&&_?{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 yp(t,e){for(let r of e){let i=Ht(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await hs(i,"utf8"))}catch(d){return Qr.warn("wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(d)}),!1}let c=o.version;if(!c)return Qr.warn("wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!v2(c,r.spec))return Qr.warn("wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await bp(Ht(t.libDir,"node_modules"))}function v2(t,e){let r=tl(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=tl(i.slice(1));if(!c)return!0;if(nl(r,c)<0)return!1;let d=c[0]>0?[c[0]+1,0,0]:c[1]>0?[0,c[1]+1,0]:[0,0,c[2]+1];return nl(r,d)<0}let o=tl(i);return o?nl(r,o)===0:!0}function tl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function nl(t,e){for(let r=0;r<3;r++){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return 0}async function S2(t,e,r){await k2(t.installLock,async()=>{if(await yp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${xs}.staging-${process.pid}-${i}`,c=Ht(o,"node_modules"),d=Ht(t.libDir,"node_modules");try{await wp(o,{recursive:!0}),await I2(e,o),await A2(c);let u=`${d}.trash-${i}`;await mp(d,u).catch(()=>{}),await mp(c,d),await rl(u,{recursive:!0,force:!0}).catch(()=>{}),Qr.info("wrapper closure installed",{liveNm:d,specs:e})}finally{await rl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function I2(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",x=>{d.length<8192&&(d+=x.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",x=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(x)}`))}),c.once("close",x=>{clearTimeout(u),x===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${x}: ${d.trim().slice(0,2e3)}`))})})}async function A2(t){for(let e of bs){let r=Ht(t,...e.split("/")),i=JSON.parse(await hs(Ht(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=Ht(t,".bin",o),d=await il(c);process.platform!=="win32"&&!(d.mode&73)&&await m2(c,d.mode|73).catch(()=>{})}if(!await bp(t)){let e=_p()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex-acp binary \u7F3A\u5931`)}}async function bp(t){let e=_p();if(!e)return!0;let r=Ht(t,...e.split("/")),i=Ht(r,"package.json"),o=Ht(r,"bin",b2()),[c,d]=await Promise.all([il(i).then(u=>u.isFile()).catch(()=>!1),il(o).then(u=>u.isFile()).catch(()=>!1)]);return c&&d}async function k2(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 rl(t,{force:!0}).catch(()=>{})}}za();te();Ce();import{closeSync as vp,fstatSync as Sp,openSync as Ip,readFileSync as T2,readSync as R2,readdirSync as P2,statSync as C2}from"node:fs";import{join as ma}from"node:path";var D2=new Set(["debug","info","warn","error"]);function Ap(t){let e=t,r=On(e,"--agent-id");e=r.rest;let i=On(e,"--date");e=i.rest;let o=On(e,"-n","--lines");e=o.rest;let c=On(e,"--level");e=c.rest;let d=On(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),x=Number.isInteger(u)&&u>=0?u:200,h=c.value&&D2.has(c.value)?c.value:void 0,g={lines:x,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(g.agentId=r.value),i.value&&(g.date=i.value),h&&(g.level=h),d.value&&(g.grep=d.value),g}function O2(t,e){return t.agentId?ma(Fe(t.agentId,e).logs,ur("agent",t.date)):ma(e.bridgeLogsDir,ur("bridge",t.date))}function L2(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function N2(t,e){let r;try{r=P2(t)}catch{return[]}let i=[];for(let o of r){let c=Ba(o,e);if(!c)continue;let d=0;try{d=C2(ma(t,o)).size}catch{}i.push({file:ma(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function kp(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"&&!Ll(r,e.level))return!1}return!0}var Ep={debug:"90",info:"36",warn:"33",error:"31"},M2=new Set(["ts","level","module","msg"]);function B2(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Tp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=B2(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Ep[o]&&(c=`\x1B[${Ep[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",x=Object.entries(r).filter(([h])=>!M2.has(h)).map(([h,g])=>` ${h}=${typeof g=="string"?g:JSON.stringify(g)}`).join("");return`${i} ${c} ${d} ${u}${x}`}function z2(t,e,r){let c=T2(t,"utf8").split(`
120
+ `).filter(d=>d.length>0).filter(d=>kp(d,{level:e.level,grep:e.grep}));for(let d of L2(c,e.lines))process.stdout.write(`${Tp(d,{raw:e.raw,color:r})}
121
+ `)}async function Rp(t,e){let r=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Fe(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",x=N2(d,u);if(x.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
122
+ `),1;for(let h of x)process.stdout.write(`${h.date} ${(h.size/1024).toFixed(1)}KB ${h.file}
123
+ `);return 0}let o=t.date??Nn(new Date),c=O2({agentId:t.agentId,date:o},r);try{z2(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
124
124
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
125
125
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
126
- `),1}return t.follow&&await G1(c,t,i),0}var z1=500;function U1(t){try{let e=vp(t,"r");try{return Ep(e).size}finally{bp(e)}}catch{return 0}}async function G1(t,e,r){let i=U1(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let f=vp(t,"r");try{let x=Ep(f).size;if(x>i){let g=Buffer.allocUnsafe(x-i),w=R1(f,g,0,g.length,i);u=g.subarray(0,w).toString("utf8"),i+=w}}finally{bp(f)}}catch{}if(u){let f=(o+u).split(`
127
- `);o=f.pop()??"";for(let x of f)x.length>0&&Ip(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Ap(x,{raw:e.raw,color:r})}
128
- `)}await new Promise(f=>setTimeout(f,z1))}}finally{process.off("SIGINT",l)}}import{basename as H1,resolve as j1}from"node:path";Re();var q1=9e4,W1={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 K1(t){return W1[t]??1}async function Tp(t,e={}){let r=e.paths??J();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
126
+ `),1}return t.follow&&await G2(c,t,i),0}var F2=500;function U2(t){try{let e=Ip(t,"r");try{return Sp(e).size}finally{vp(e)}}catch{return 0}}async function G2(t,e,r){let i=U2(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let x=Ip(t,"r");try{let h=Sp(x).size;if(h>i){let g=Buffer.allocUnsafe(h-i),_=R2(x,g,0,g.length,i);u=g.subarray(0,_).toString("utf8"),i+=_}}finally{vp(x)}}catch{}if(u){let x=(o+u).split(`
127
+ `);o=x.pop()??"";for(let h of x)h.length>0&&kp(h,{level:e.level,grep:e.grep})&&process.stdout.write(`${Tp(h,{raw:e.raw,color:r})}
128
+ `)}await new Promise(x=>setTimeout(x,F2))}}finally{process.off("SIGINT",d)}}import{basename as H2,resolve as q2}from"node:path";Ce();var j2=9e4,W2={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 K2(t){return W2[t]??1}async function Pp(t,e={}){let r=e.paths??Z();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
129
129
  `),4;if(t.groupFile&&!t.mimeType)return process.stderr.write(`Error: --group-file requires --mime <mimeType> (e.g. application/pdf, image/png). No local file is read in group-file mode, mime cannot be auto-detected.
130
- `),3;let i=await xa(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
131
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:j1(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 $1(i,"/agent/send",o,q1)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
130
+ `),3;let i=await ga(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
131
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:q2(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 $2(i,"/agent/send",o,j2)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
132
132
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
133
- `),K1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
134
- `);else{let l=t.name??H1(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
135
- `)}else process.stdout.write(`Sent ${t.kind} ${l} (${V1(c.bytes)})
136
- `)}return 0}async function $1(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await l.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=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function V1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Fp=G("cli");function qe(t,e){let{value:r,rest:i}=Pn(t,e);return{value:r,rest:i}}function ba(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
137
- `)}function w2(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:C}=qe(e.slice(1),"--agent-id");return C?{mode:"reload",agentId:C}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return _2(e.slice(1));if(e[0]==="log")return{mode:"log",...Sp(e.slice(1))};if(e[0]==="connect")return y2(e.slice(1));if(e.includes("--status"))return ba("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ba("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ba("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ba("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=qe(r,"--pat-token");r=o;let{value:c,rest:l}=qe(r,"--pair-code");r=l;let{value:u,rest:f}=qe(r,"--env");r=f;let{value:x,rest:g}=qe(r,"--handshake-url");r=g;let{value:w,rest:S}=qe(r,"--frontier-url");r=S;let{value:y,rest:v}=qe(r,"--mock-scenario");r=v;let{value:I}=qe(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let R={mode:"pair",privatecode:i,pairingCode:c};return u&&(R.env=u),x&&(R.handshakeUrl=x),w&&(R.frontierUrl=w),y&&(R.mockScenario=y),I&&(R.agentId=I),A&&(R.skipRebuildEnv=!0),R}function _2(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}=qe(i,"--caption");i=c;let{value:l,rest:u}=qe(i,"--name");i=u;let{value:f,rest:x}=qe(i,"--agent-id");i=x;let{value:g,rest:w}=qe(i,"--session-id");i=w;let{value:S,rest:y}=qe(i,"--mime");i=y;let v=i.includes("--group-file");i=i.filter(R=>R!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),l&&(A.name=l),f&&(A.agentId=f),g&&(A.sessionId=g),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function y2(t){let e=t,{value:r,rest:i}=qe(e,"--pat-token");e=i;let{value:o,rest:c}=qe(e,"--env");e=c;let{value:l,rest:u}=qe(e,"--handshake-url");e=u;let{value:f,rest:x}=qe(e,"--frontier-url");e=x;let{value:g,rest:w}=qe(e,"--mock-scenario");e=w;let S=e.includes("--skip-rebuild-env"),y={mode:"connect"};return r&&(y.privatecode=r),o&&(y.env=o),l&&(y.handshakeUrl=l),f&&(y.frontierUrl=f),g&&(y.mockScenario=g),S&&(y.skipRebuildEnv=!0),y}var b2=`
133
+ `),K2(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
134
+ `);else{let d=t.name??H2(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
135
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${V2(c.bytes)})
136
+ `)}return 0}async function $2(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(),x=u?JSON.parse(u):null;return x&&typeof x=="object"&&"ok"in x?x:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function V2(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Up=q("cli");function Ke(t,e){let{value:r,rest:i}=On(t,e);return{value:r,rest:i}}function va(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
137
+ `)}function wI(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 _I(e.slice(1));if(e[0]==="log")return{mode:"log",...Ap(e.slice(1))};if(e[0]==="connect")return yI(e.slice(1));if(e.includes("--status"))return va("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return va("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return va("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return va("--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:x}=Ke(r,"--env");r=x;let{value:h,rest:g}=Ke(r,"--handshake-url");r=g;let{value:_,rest:S}=Ke(r,"--frontier-url");r=S;let{value:w,rest:v}=Ke(r,"--mock-scenario");r=v;let{value:I}=Ke(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let R={mode:"pair",privatecode:i,pairingCode:c};return u&&(R.env=u),h&&(R.handshakeUrl=h),_&&(R.frontierUrl=_),w&&(R.mockScenario=w),I&&(R.agentId=I),A&&(R.skipRebuildEnv=!0),R}function _I(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:x,rest:h}=Ke(i,"--agent-id");i=h;let{value:g,rest:_}=Ke(i,"--session-id");i=_;let{value:S,rest:w}=Ke(i,"--mime");i=w;let v=i.includes("--group-file");i=i.filter(R=>R!=="--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),x&&(A.agentId=x),g&&(A.sessionId=g),v&&(A.groupFile=!0),S&&(A.mimeType=S),A}function yI(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:x,rest:h}=Ke(e,"--frontier-url");e=h;let{value:g,rest:_}=Ke(e,"--mock-scenario");e=_;let S=e.includes("--skip-rebuild-env"),w={mode:"connect"};return r&&(w.privatecode=r),o&&(w.env=o),d&&(w.handshakeUrl=d),x&&(w.frontierUrl=x),g&&(w.mockScenario=g),S&&(w.skipRebuildEnv=!0),w}var bI=`
138
138
  coze-bridge - local bridge daemon for cloud Agent Service
139
139
 
140
140
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -215,57 +215,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
215
215
 
216
216
  Internal:
217
217
  <node> <entry> --daemon daemon mode (OS supervisor only)
218
- `.trimStart();async function zp(t=process.argv,e={}){let r=w2(t);switch(r.mode){case"help":return process.stdout.write(b2),0;case"version":return process.stdout.write(`${Ot}
219
- `),0;case"daemon":{try{await dp()}catch(i){return Fp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return E2(e);case"stop":return Gp(e);case"reload":return I2(r.agentId,e);case"log":return kp(r,e);case"update":return v2(e);case"purge":return k2(e);case"service-install":return T2(e);case"service-uninstall":return R2(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),P2(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),D2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Tp({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 Up(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 E2(t){let e=t.paths??J(),r=new rn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
220
- `),1;if(i.kind==="stale")return await Up(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
218
+ `.trimStart();async function Gp(t=process.argv,e={}){let r=wI(t);switch(r.mode){case"help":return process.stdout.write(bI),0;case"version":return process.stdout.write(`${Bt}
219
+ `),0;case"daemon":{try{await up()}catch(i){return Up.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return EI(e);case"stop":return qp(e);case"reload":return II(r.agentId,e);case"log":return Rp(r,e);case"update":return vI(e);case"purge":return kI(e);case"service-install":return TI(e);case"service-uninstall":return RI(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),PI(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),CI(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Pp({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 Hp(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 EI(t){let e=t.paths??Z(),r=new on(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
220
+ `),1;if(i.kind==="stale")return await Hp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
221
221
  `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
222
222
  ${JSON.stringify(o.body,null,2)}
223
- `),0}async function Gp(t){let e=t.paths??J(),r=new rn(e),i=t.daemonSweep??(async()=>{let f=B0();return await F0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await hs(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
224
- `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
223
+ `),0}async function qp(t){let e=t.paths??Z(),r=new on(e),i=t.daemonSweep??(async()=>{let x=F0();return await U0(x),x}),o=async()=>{t.skipProcessKill||await i(e)},c=await gs(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(x){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(x)}
224
+ `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
225
225
  `:`coze-bridge: not running
226
- `),0;if(u.kind==="stale")return await Up(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
226
+ `),0;if(u.kind==="stale")return await Hp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
227
227
  `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
228
- `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
229
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
230
- `),1)}}async function v2(t){return await Gp(t),(t.spawnNpx??S2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function S2(t){return new Promise(e=>{let r=nt("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
231
- `),e(1)})})}async function I2(t,e){let r=new rn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
228
+ `),0}catch(x){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
229
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(x)}
230
+ `),1)}}async function vI(t){return await qp(t),(t.spawnNpx??SI)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function SI(t){return new Promise(e=>{let r=st("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
231
+ `),e(1)})})}async function II(t,e){let r=new on(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
232
232
  `),1;try{let o=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
233
233
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
234
234
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
235
235
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
236
- `),1}}async function hs(t){if(t.supervisor){let c=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(l,u),uninstall:()=>c.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Np(),Lp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Hp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??C2,c=t.paths??J();if(r.kind==="connected"){if(!A2(r.body))return r;ct(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=>ct(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await Bp(c.pidFile,o)}let l=t.spawnDaemon??ap,u=await hs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Mp(e,i,o);if(f.kind==="connected")return f;ct(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(f){ct(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}ct(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await Bp(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)}
236
+ `),1}}async function gs(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(()=>(Bp(),Mp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function jp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??DI,c=t.paths??Z();if(r.kind==="connected"){if(!AI(r.body))return r;xt(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:r.body}),await e.request({method:"POST",path:"/shutdown"}).catch(x=>xt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(x)})),await Fp(c.pidFile,o)}let d=t.spawnDaemon??dp,u=await gs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let x=await zp(e,i,o);if(x.kind==="connected")return x;xt(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(x){xt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(x)})}xt(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await Fp(c.pidFile,o)}else u&&await u.install({activate:!1}).catch(x=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(x)}
237
237
  `));return process.stdout.write(`coze-bridge: starting daemon...
238
- `),await l({paths:t.paths}),Mp(e,i,o)}function A2(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 k2(t){let e=new rn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
239
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
240
- `)}await new Promise(l=>setTimeout(l,500))}let i=await hs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
241
- `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
242
- `)}let o=t.paths??J(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
243
- `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
238
+ `),await d({paths:t.paths}),zp(e,i,o)}function AI(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 kI(t){let e=new on(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
239
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
240
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await gs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
241
+ `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
242
+ `)}let o=t.paths??Z(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
243
+ `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
244
244
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
245
- `),0}async function T2(t){let e=await hs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
245
+ `),0}async function TI(t){let e=await gs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
246
246
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
247
247
  `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
248
- `),1}}async function R2(t){let e=await hs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
248
+ `),1}}async function RI(t){let e=await gs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
249
249
  `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
250
- `),1}}async function jp(t,e,r){if(e)return ct(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(ct(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ct(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
251
- `),ct(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function P2(t,e,r,i={},o,c){let l=new rn(r.paths),u=r.paths??J(),f=await jp(u,c,r.reconstructEnv??Xd);if(await Yc(u,f).catch(w=>ct(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!r.skipDistInstall){let w=await il({paths:r.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
252
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
253
- `)}let x=await Hp(r,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
254
- `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),o&&(g.agent_id=o);try{let w=await l.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
+ `),1}}async function Wp(t,e,r){if(e)return xt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(xt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(xt(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
251
+ `),xt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function PI(t,e,r,i={},o,c){let d=new on(r.paths),u=r.paths??Z(),x=await Wp(u,c,r.reconstructEnv??el);if(await Qc(u,x).catch(_=>xt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!r.skipDistInstall){let _=await ol({paths:r.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
252
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(w=>setTimeout(w,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
253
+ `)}let h=await jp(r,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
254
+ `),1;let g={privatecode:t,pairing_code:e};i.env&&(g.env=i.env),i.handshakeUrl&&(g.handshake_url=i.handshakeUrl),i.frontierUrl&&(g.frontier_url=i.frontierUrl),i.mockScenario&&(g.mock_scenario=i.mockScenario),o&&(g.agent_id=o);try{let _=await d.request({method:"POST",path:"/pair",body:g,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let S=_.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
255
255
  `),1):(process.stdout.write(`\u5DF2\u914D\u5BF9\u8FDE\u63A5\u5B8C\u6210\uFF0C\u8BF7\u8FD4\u56DE\u5230 coze \u5E73\u53F0\u4E0A\u70B9\u51FB "\u6211\u5DF2\u6267\u884C"
256
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
257
- `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
258
- `),1}}async function D2(t,e,r={},i){let o=e.paths??J(),c=t??await aa(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new rn(e.paths),u=await jp(o,i,e.reconstructEnv??Xd);if(await Yc(o,u).catch(g=>ct(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await il({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
259
- `),(await l.probe()).kind==="connected"&&(await l.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}
260
- `)}let f=await Hp(e,l);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
261
- `),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 l.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"})
262
- `),t!==void 0&&await cs(c,o).catch(w=>Fp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
256
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(_.body)}
257
+ `),1}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
258
+ `),1}}async function CI(t,e,r={},i){let o=e.paths??Z(),c=t??await da(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 on(e.paths),u=await Wp(o,i,e.reconstructEnv??el);if(await Qc(o,u).catch(g=>xt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!e.skipDistInstall){let g=await ol({paths:e.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
259
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
260
+ `)}let x=await jp(e,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
261
+ `),1;let h={privatecode:c};r.env&&(h.env=r.env),r.handshakeUrl&&(h.handshake_url=r.handshakeUrl),r.frontierUrl&&(h.frontier_url=r.frontierUrl),r.mockScenario&&(h.mock_scenario=r.mockScenario);try{let g=await d.request({method:"POST",path:"/connect",body:h,timeoutMs:35e3});return g.status===200&&g.body?.ok?(process.stdout.write(`coze-bridge: connected (${g.body.note??"ok"})
262
+ `),t!==void 0&&await us(c,o).catch(_=>Up.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(g.body)}
263
263
  `),1)}catch(g){return process.stderr.write(`coze-bridge: connect failed: ${String(g)}
264
- `),1}}async function Mp(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 Bp(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Ki(u))return;await e(i)}}function C2(t){return new Promise(e=>setTimeout(e,t))}ee();function O2(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 qp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=O2(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
264
+ `),1}}async function zp(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 Fp(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||!Ji(u))return;await e(i)}}function DI(t){return new Promise(e=>setTimeout(e,t))}te();function OI(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 Kp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=OI(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
265
  `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
266
266
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
267
267
  npx -y coze-bridge@latest stop
268
268
  npx -y coze-bridge@latest connect
269
269
 
270
- `)}qp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Pl("warn");zp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
270
+ `)}Kp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Dl("warn");Gp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
271
271
  `),process.exit(1)});