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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +86 -88
  2. package/package.json +7 -3
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var Wg=Object.create;var Da=Object.defineProperty;var Kg=Object.getOwnPropertyDescriptor;var $g=Object.getOwnPropertyNames;var Vg=Object.getPrototypeOf,Yg=Object.prototype.hasOwnProperty;var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var et=(t,e)=>()=>(t&&(e=t(t=0)),e);var de=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Oa=(t,e)=>{for(var r in e)Da(t,r,{get:e[r],enumerable:!0})},Jg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $g(e))!Yg.call(t,o)&&o!==r&&Da(t,o,{get:()=>e[o],enumerable:!(i=Kg(e,o))||i.enumerable});return t};var Ht=(t,e,r)=>(r=t!=null?Wg(Vg(t)):{},Jg(e||!t||!t.__esModule?Da(r,"default",{value:t,enumerable:!0}):r,t));function Ye(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ar=et(()=>{"use strict"});import{createWriteStream as Xg,mkdirSync as Zg,readdirSync as Qg,unlinkSync as em}from"node:fs";import{join as Cl}from"node:path";function Dn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function cr(t,e){return`${t}-${e}.log`}function La(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function tm(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 hs(t,e,r,i){let o;try{o=Qg(t)}catch{return}for(let c of o){let d=La(c,e);if(d&&tm(d,r,i))try{em(Cl(t,c))}catch{}}}var ri,Na=et(()=>{"use strict";ri=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Dn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{Zg(this.dir,{recursive:!0});let r=Xg(Cl(this.dir,cr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var Kg=Object.create;var La=Object.defineProperty;var $g=Object.getOwnPropertyDescriptor;var Vg=Object.getOwnPropertyNames;var Jg=Object.getPrototypeOf,Zg=Object.prototype.hasOwnProperty;var fe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var nt=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Na=(t,e)=>{for(var r in e)La(t,r,{get:e[r],enumerable:!0})},Xg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Vg(e))!Zg.call(t,o)&&o!==r&&La(t,o,{get:()=>e[o],enumerable:!(i=$g(e,o))||i.enumerable});return t};var qt=(t,e,r)=>(r=t!=null?Kg(Jg(t)):{},Xg(e||!t||!t.__esModule?La(r,"default",{value:t,enumerable:!0}):r,t));function Xe(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var dr=nt(()=>{"use strict"});import{createWriteStream as Yg,mkdirSync as Qg,readdirSync as em,unlinkSync as tm}from"node:fs";import{join as Ll}from"node:path";function Nn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function lr(t,e){return`${t}-${e}.log`}function Ma(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function nm(t,e,r){let i=c=>{let[d,u,h]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>r}function ps(t,e,r,i){let o;try{o=em(t)}catch{return}for(let c of o){let d=Ma(c,e);if(d&&nm(d,r,i))try{tm(Ll(t,c))}catch{}}}var ai,Ba=nt(()=>{"use strict";ai=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Nn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{Qg(this.dir,{recursive:!0});let r=Yg(Ll(this.dir,lr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
9
  `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&hs(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as nm,mkdirSync as rm}from"node:fs";import{join as im}from"node:path";function Rl(t){let e=t.retentionDays??am,r=t.clock??(()=>Dn(new Date));gs={bridgeSink:new ri(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ri(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();hs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])hs(t.agentLogsDir(o),"agent",i,e)}function cm(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Dl(t){Ma=t}function Ol(t){return dr[Ma]<=dr[t]}function Ll(t,e){let r=dr[t];return r===void 0?!0:r>=dr[e]}function ms(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`${Dn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function nt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Nl(new Date),level:e,module:r,msg:i,...o})}
11
- `;rm(t,{recursive:!0}),nm(im(t,cr("bridge",Dn(new Date))),c)}catch{}}function dm(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ps(t,e,r,i,o){if(dr[t]<dr[Ma])return;let c=`${JSON.stringify({ts:Nl(new Date),level:t,module:e,msg:r,...Pl,...i})}
12
- `;if(gs){let d=dm(o,i),u=d?cm(gs,d):gs.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?om.write(c):sm.write(c)}function j(t,e){return{debug:(r,i)=>ps("debug",t,r,i,e),info:(r,i)=>ps("info",t,r,i,e),warn:(r,i)=>ps("warn",t,r,i,e),error:(r,i)=>ps("error",t,r,i,e),child:r=>j(`${t}.${r}`,e),forAgent:r=>j(t,r)}}var dr,Ma,sm,om,Pl,am,gs,te=et(()=>{"use strict";ar();Na();dr={debug:10,info:20,warn:30,error:40},Ma=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),sm=process.stdout,om=process.stderr,Pl={},am=Ye("COZE_BRIDGE_LOG_RETENTION_DAYS",30),gs=null});var T,Ke=et(()=>{"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 zl={};Oa(zl,{ACP_WRAPPER_NPM_PACKAGES:()=>ws,_resetAcpInstallerForTests:()=>pm,_setBinaryPathCacheForTests:()=>gm,buildAcpSpawn:()=>si,ensureAcpInstalled:()=>lr,getAcpBinaryPath:()=>_s,pickWhichLine:()=>za,probeAcpVersion:()=>hm,resolveAcpCommand:()=>Fl});import{readFileSync as Ml}from"node:fs";import{createRequire as lm}from"node:module";import{dirname as um,resolve as fm}from"node:path";function za(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function xm(t){let e=Bl.resolve(`${t.npmPackage}/package.json`),r=um(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 fm(r,o)}async function lr(t,e){let r=Fa[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=xm(r);return ii.set(t,o),Ba.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ba.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 hm(t){let e=Fa[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){Ba.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function _s(t){return ii.get(t)}function Fl(t,e){if(e)return e;let r=_s(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=Fl(t);return{command:process.execPath,args:[i,...r]}}function pm(){ii.clear()}function gm(t,e){ii.set(t,e)}var Ba,Fa,ws,Bl,ii,ln=et(()=>{"use strict";Ke();te();Ba=j("agents.acp-installer"),Fa={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ws=Object.values(Fa).filter(t=>t!==void 0).map(t=>t.npmPackage),Bl=lm(import.meta.url),ii=new Map});import{chmod as wm,mkdir as _m,readFile as ym,rename as bm,rm as Em,writeFile as vm}from"node:fs/promises";import{dirname as Sm}from"node:path";async function ur(t){try{let e=await ym(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ut(t,e,r){await _m(Sm(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await vm(i,e,{encoding:"utf8",mode:r?.mode}),await bm(i,t),r?.mode!==void 0&&await wm(t,r.mode)}catch(o){throw await Em(i,{force:!0}).catch(()=>{}),o}}async function fr(t,e,r){await ut(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var Gt=et(()=>{"use strict"});import{promises as Gl,readdirSync as Im}from"node:fs";import{homedir as Am}from"node:os";import{sep as km,join as Te,resolve as ql}from"node:path";function J(t){let e=t??Am(),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 Fe(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 ys(t=J()){try{return Im(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function oi(t,e){let r=await Gl.realpath(ql(t)).catch(()=>null);if(!r)return!1;let i=await Gl.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+km)}var Ce=et(()=>{"use strict"});var Es={};Oa(Es,{AGENT_CONFIG_FILE_MODE:()=>bs,enforceAgentConfigMode:()=>Pm,loadAgentConfig:()=>ve,persistAgentSessions:()=>ai,persistAgentSkills:()=>ci,saveAgentConfig:()=>ze});import{chmod as Tm,stat as Cm}from"node:fs/promises";function ve(t,e){return ur(Fe(t,e).config)}function ze(t,e){return fr(Fe(t.agentId,e).config,t,{mode:bs})}async function Pm(t,e){if(process.platform==="win32")return;let r=Fe(t,e).config;try{let i=await Cm(r);if(!i.isFile())return;let o=i.mode&511;o!==bs&&(await Tm(r,bs),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 ai(t,e,r){let i=await ve(t,r);i&&(i.sessions=Object.fromEntries(e),await ze(i,r))}async function ci(t,e,r){let i=await ve(t,r);i&&(i.skills=e,await ze(i,r))}var jl,bs,qt=et(()=>{"use strict";Gt();te();Ce();jl=j("agent-config"),bs=384});var Ga=de((NI,$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 Ss=de(Yl=>{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 Mm(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))Yl[t]=Mm(Vl[t])});var eu=de((BI,Ql)=>{var Bm=xe("fs"),Ne=xe("path"),Jl=Ga(),Fm=Ss(),zm=typeof process=="object"&&process.platform==="win32",Xl=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=Ne.sep,this.fs=Bm,Xl(t)&&Xl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Ql.exports=Se;Se.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw Fm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Se.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Ne.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!r)return o(!1);c.fs.stat(t,function(u,x){if(d&&x.isDirectory())return o(!1);var h=Ne.dirname(t);c.fs.exists(h,function(m){m||c.makeDir(h),c.fs.open(t,"w",438,function(w,I){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(b,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)})})})})}):I?c.fs.write(I,e,0,e.length,0,function(){c.fs.close(I,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Se.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let x=Ne.join(i,u),h=e.fs.statSync(x);(!o||o.test(x))&&d.push(Ne.normalize(x)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&c&&(d=d.concat(r(x,o,c)))}),d}return r(t,void 0,!0)};Se.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Ne.join(t,u),r.fs.stat(u,function(x,h){if(x)return e(x);h&&(i.push(Ne.normalize(u)+(h.isDirectory()?r.sep:"")),h.isDirectory()?r.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--d||e(null,i)}):--d||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 Jl.STORED:return"STORED ("+t+")";case Jl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Ne.posix.normalize("/"+t.split("\\").join("/"));return Ne.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=Ne.resolve(Ne.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Ne.normalize(Ne.join(t,r.slice(i,o).join(Ne.sep)));if(c.indexOf(t)===0)return c}return Ne.normalize(Ne.join(t,Ne.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=zm;Se.crcTable=Zl});var nu=de((FI,tu)=>{var Um=xe("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=Um.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=de((zI,ru)=>{ru.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var pr=de((UI,hr)=>{hr.exports=eu();hr.exports.Constants=Ga();hr.exports.Errors=Ss();hr.exports.FileAttr=nu();hr.exports.decoder=iu()});var ou=de((HI,su)=>{var un=pr(),q=un.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,m=0,w=0,I=0,b=0,S=0;t|=un.isWin?2560:768,r|=q.FLG_EFS;let A={extraLen:0},k=E=>Math.max(0,E)>>>0,P=E=>Math.max(0,E)&65535,L=E=>Math.max(0,E)&255;return o=un.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return r},set flags(E){r=E},get flags_efs(){return(r&q.FLG_EFS)>0},set flags_efs(E){E?r|=q.FLG_EFS:r&=~q.FLG_EFS},get flags_desc(){return(r&q.FLG_DESC)>0},set flags_desc(E){E?r|=q.FLG_DESC:r&=~q.FLG_DESC},get method(){return i},set method(E){switch(E){case q.STORED:this.version=10;case q.DEFLATED:default:this.version=20}i=E},get time(){return un.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=un.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=k(E)},get timeHighByte(){return L(o>>>8)},get crc(){return c},set crc(E){c=k(E)},get compressedSize(){return d},set compressedSize(E){d=k(E)},get size(){return u},set size(E){u=k(E)},get fileNameLength(){return x},set fileNameLength(E){x=E},get extraLength(){return h},set extraLength(E){h=E},get extraLocalLength(){return A.extraLen},set extraLocalLength(E){A.extraLen=E},get commentLength(){return m},set commentLength(E){m=E},get diskNumStart(){return w},set diskNumStart(E){w=k(E)},get inAttr(){return I},set inAttr(E){I=k(E)},get attr(){return b},set attr(E){b=k(E)},get fileAttr(){return(b||0)>>16&4095},get offset(){return S},set offset(E){S=k(E)},get encrypted(){return(r&q.FLG_ENC)===q.FLG_ENC},get centralHeaderSize(){return q.CENHDR+x+h+m},get realDataOffset(){return S+q.LOCHDR+A.fnameLen+A.extraLen},get localHeader(){return A},loadLocalHeaderFromBinary:function(E){var D=E.slice(S,S+q.LOCHDR);if(D.readUInt32LE(0)!==q.LOCSIG)throw un.Errors.INVALID_LOC();A.version=D.readUInt16LE(q.LOCVER),A.flags=D.readUInt16LE(q.LOCFLG),A.flags_desc=(A.flags&q.FLG_DESC)>0,A.method=D.readUInt16LE(q.LOCHOW),A.time=D.readUInt32LE(q.LOCTIM),A.crc=D.readUInt32LE(q.LOCCRC),A.compressedSize=D.readUInt32LE(q.LOCSIZ),A.size=D.readUInt32LE(q.LOCLEN),A.fnameLen=D.readUInt16LE(q.LOCNAM),A.extraLen=D.readUInt16LE(q.LOCEXT);let N=S+q.LOCHDR+A.fnameLen,z=N+A.extraLen;return E.slice(N,z)},loadFromBinary:function(E){if(E.length!==q.CENHDR||E.readUInt32LE(0)!==q.CENSIG)throw un.Errors.INVALID_CEN();t=E.readUInt16LE(q.CENVEM),e=E.readUInt16LE(q.CENVER),r=E.readUInt16LE(q.CENFLG),i=E.readUInt16LE(q.CENHOW),o=E.readUInt32LE(q.CENTIM),c=E.readUInt32LE(q.CENCRC),d=E.readUInt32LE(q.CENSIZ),u=E.readUInt32LE(q.CENLEN),x=E.readUInt16LE(q.CENNAM),h=E.readUInt16LE(q.CENEXT),m=E.readUInt16LE(q.CENCOM),w=E.readUInt16LE(q.CENDSK),I=E.readUInt16LE(q.CENATT),b=E.readUInt32LE(q.CENATX),S=E.readUInt32LE(q.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(q.LOCHDR);return E.writeUInt32LE(q.LOCSIG,0),E.writeUInt16LE(e,q.LOCVER),E.writeUInt16LE(r,q.LOCFLG),E.writeUInt16LE(i,q.LOCHOW),E.writeUInt32LE(o,q.LOCTIM),E.writeUInt32LE(c,q.LOCCRC),E.writeUInt32LE(d,q.LOCSIZ),E.writeUInt32LE(u,q.LOCLEN),E.writeUInt16LE(x,q.LOCNAM),E.writeUInt16LE(A.extraLen,q.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(q.CENHDR+x+h+m);return E.writeUInt32LE(q.CENSIG,0),E.writeUInt16LE(t,q.CENVEM),E.writeUInt16LE(e,q.CENVER),E.writeUInt16LE(r,q.CENFLG),E.writeUInt16LE(i,q.CENHOW),E.writeUInt32LE(o,q.CENTIM),E.writeUInt32LE(c,q.CENCRC),E.writeUInt32LE(d,q.CENSIZ),E.writeUInt32LE(u,q.CENLEN),E.writeUInt16LE(x,q.CENNAM),E.writeUInt16LE(h,q.CENEXT),E.writeUInt16LE(m,q.CENCOM),E.writeUInt16LE(w,q.CENDSK),E.writeUInt16LE(I,q.CENATT),E.writeUInt32LE(b,q.CENATX),E.writeUInt32LE(S,q.CENOFF),E},toJSON:function(){let E=function(D){return D+" bytes"};return{made:t,version:e,flags:r,method:un.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(x),extraLength:E(h),commentLength:E(m),diskNumStart:w,inAttr:I,attr:b,offset:S,centralHeaderSize:E(q.CENHDR+x+h+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var cu=de((GI,au)=>{var gr=pr(),ye=gr.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 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(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 ja=de(qa=>{qa.EntryHeader=ou();qa.MainHeader=cu()});var lu=de((jI,du)=>{du.exports=function(t){var e=xe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var 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 m=c[h];m.copy(u,x),x+=m.length}i&&i(u)}),o.end(t)}}}});var fu=de((WI,uu)=>{var Hm=+(process.versions?process.versions.node:"").split(".")[0]||0;uu.exports=function(t,e){var r=xe("zlib");let i=Hm>=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 m=0;m<d.length;m++){var w=d[m];w.copy(x,h),h+=w.length}o&&o(x)}),c.end(t)}}}});var mu=de((KI,gu)=>{"use strict";var{randomFillSync:xu}=xe("crypto"),Gm=Ss(),qm=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)=>qm[(t^e)&255]^t>>>8,di=()=>typeof xu=="function"?xu(Buffer.alloc(12)):di.node();di.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var Is={genSalt:di};function As(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}As.prototype.updateKeys=function(t){let e=this.keys;return e[0]=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};As.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return pu(t,t^1)>>8&255};function jm(t){let e=new As(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function Wm(t){let e=new As(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let d=e.next();i[o++]=c^d,e.updateKeys(c)}return i}}function Km(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=jm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Gm.WRONG_PASSWORD();return i(t.slice(12))}function $m(t){Buffer.isBuffer(t)&&t.length>=12?Is.genSalt=function(){return t.slice(0,12)}:t==="node"?Is.genSalt=di.node:Is.genSalt=di}function Vm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Wm(r),c=Is.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(c,d),o(t,d,12)}gu.exports={decrypt:Km,encrypt:Vm,_salter:$m}});var wu=de(ks=>{ks.Deflater=lu();ks.Inflater=fu();ks.ZipCrypto=mu()});var Ka=de((VI,_u)=>{var le=pr(),Ym=ja(),Ie=le.Constants,Wa=wu();_u.exports=function(t,e){var r=new Ym.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),x=Buffer.alloc(0),h=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:le.decoder;h=w.hasOwnProperty("efs")?w.efs:!1;function I(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(x=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function b(E){if(!r.flags_desc&&!r.localHeader.flags_desc){if(le.crc32(E)!==r.localHeader.crc)return!1}else{let D={},N=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(N)==Ie.LOCSIG||e.readUInt32LE(N)==Ie.CENSIG)throw le.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(N)==Ie.EXTSIG)D.crc=e.readUInt32LE(N+Ie.EXTCRC),D.compressedSize=e.readUInt32LE(N+Ie.EXTSIZ),D.size=e.readUInt32LE(N+Ie.EXTLEN);else if(e.readUInt16LE(N+12)===19280)D.crc=e.readUInt32LE(N+Ie.EXTCRC-4),D.compressedSize=e.readUInt32LE(N+Ie.EXTSIZ-4),D.size=e.readUInt32LE(N+Ie.EXTLEN-4);else throw le.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==r.compressedSize||D.size!==r.size||D.crc!==r.crc)throw le.Errors.DESCRIPTOR_FAULTY();if(le.crc32(E)!==D.crc)return!1}return!0}function S(E,D,N){if(typeof D>"u"&&typeof E=="string"&&(N=E,E=void 0),c)return E&&D&&D(Buffer.alloc(0),le.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=I();if(z.length===0)return E&&D&&D(z),z;if(r.encrypted){if(typeof N!="string"&&!Buffer.isBuffer(N))throw le.Errors.INVALID_PASS_PARAM();z=Wa.ZipCrypto.decrypt(z,r,N)}var B=Buffer.alloc(r.size);switch(r.method){case le.Constants.STORED:if(z.copy(B),b(B))return E&&D&&D(B),B;throw E&&D&&D(B,le.Errors.BAD_CRC()),le.Errors.BAD_CRC();case le.Constants.DEFLATED:var Y=new Wa.Inflater(z,r.size);if(E)Y.inflateAsync(function(V){V.copy(V,0),D&&(b(V)?D(V):D(V,le.Errors.BAD_CRC()))});else{if(Y.inflate(B).copy(B,0),!b(B))throw le.Errors.BAD_CRC(`"${w.decode(i)}"`);return B}break;default:throw E&&D&&D(Buffer.alloc(0),le.Errors.UNKNOWN_METHOD()),le.Errors.UNKNOWN_METHOD()}}function A(E,D){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&D&&D(I()),I();if(d.length&&!c){var N;switch(r.method){case le.Constants.STORED:return r.compressedSize=r.size,N=Buffer.alloc(d.length),d.copy(N),E&&D&&D(N),N;default:case le.Constants.DEFLATED:var z=new Wa.Deflater(d);if(E)z.deflateAsync(function(Y){N=Buffer.alloc(Y.length),r.compressedSize=Y.length,Y.copy(N),D&&D(N)});else{var B=z.deflate();return r.compressedSize=B.length,B}z=null;break}}else if(E&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function k(E,D){return le.readBigUInt64LE(E,D)}function P(E){try{for(var D=0,N,z,B;D+4<E.length;)N=E.readUInt16LE(D),D+=2,z=E.readUInt16LE(D),D+=2,B=E.slice(D,D+z),D+=z,Ie.ID_ZIP64===N&&L(B)}catch{throw le.Errors.EXTRA_FIELD_PARSE_ERROR()}}function L(E){var D,N,z,B;E.length>=Ie.EF_ZIP64_SCOMP&&(D=k(E,Ie.EF_ZIP64_SUNCOMP),r.size===Ie.EF_ZIP64_OR_32&&(r.size=D)),E.length>=Ie.EF_ZIP64_RHO&&(N=k(E,Ie.EF_ZIP64_SCOMP),r.compressedSize===Ie.EF_ZIP64_OR_32&&(r.compressedSize=N)),E.length>=Ie.EF_ZIP64_DSN&&(z=k(E,Ie.EF_ZIP64_RHO),r.offset===Ie.EF_ZIP64_OR_32&&(r.offset=z)),E.length>=Ie.EF_ZIP64_DSN+4&&(B=E.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(E){i=le.toBuffer(E,w.encode);var D=i[i.length-1];c=D===47||D===92,r.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(E){u=E,r.extraLength=E.length,P(E)},get comment(){return w.decode(o)},set comment(E){if(o=le.toBuffer(E,w.encode),r.commentLength=o.length,o.length>65535)throw le.Errors.COMMENT_TOO_LONG()},get name(){var E=w.decode(i);return c?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return A(!1,null)},getCompressedDataAsync:function(E){A(!0,E)},setData:function(E){d=le.toBuffer(E,le.decoder.encode),!c&&d.length?(r.size=d.length,r.method=le.Constants.DEFLATED,r.crc=le.crc32(E),r.changed=!0):r.method=le.Constants.STORED},getData:function(E){return r.changed?d:S(!1,null,E)},getDataAsync:function(E,D){r.changed?E(d):S(!0,E,D)},set attr(E){r.attr=E},get attr(){return r.attr},set header(E){r.loadFromBinary(E)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var E=r.centralHeaderToBinary(),D=le.Constants.CENHDR;return i.copy(E,D),D+=i.length,u.copy(E,D),D+=r.extraLength,o.copy(E,D),E},packLocalHeader:function(){let E=0;r.flags_efs=this.efs,r.extraLocalLength=x.length;let D=r.localHeaderToBinary(),N=Buffer.alloc(D.length+i.length+r.extraLocalLength);return D.copy(N,E),E+=D.length,i.copy(N,E),E+=i.length,x.copy(N,E),E+=x.length,N},toJSON:function(){let E=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:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Eu=de((YI,bu)=>{var yu=Ka(),Jm=ja(),$e=pr();bu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Jm.MainHeader,d=!1,u=null;let x=new Set,h=e,{noSort:m,decoder:w}=h;t?S(h.readEntries):d=!0;function I(){let k=new Set;for(let P of Object.keys(i)){let L=P.split("/");if(L.pop(),!!L.length)for(let E=0;E<L.length;E++){let D=L.slice(0,E+1).join("/")+"/";k.add(D)}}for(let P of k)if(!(P in i)){let L=new yu(h);L.entryName=P,L.attr=16,L.temporary=!0,r.push(L),i[L.entryName]=L,x.add(L)}}function b(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/$e.Constants.CENHDR)throw $e.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var k=c.offset,P=0;P<r.length;P++){var L=k,E=new yu(h,t);E.header=t.slice(L,L+=$e.Constants.CENHDR),E.entryName=t.slice(L,L+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(L,L+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(L,L+E.header.commentLength)),k+=E.header.centralHeaderSize,r[P]=E,i[E.entryName]=E}x.clear(),I()}function S(k){var P=t.length-$e.Constants.ENDHDR,L=Math.max(0,P-65535),E=L,D=t.length,N=-1,z=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(L=0),P;P>=E;P--)if(t[P]===80){if(t.readUInt32LE(P)===$e.Constants.ENDSIG){N=P,z=P,D=P+$e.Constants.ENDHDR,E=P-$e.Constants.END64HDR;continue}if(t.readUInt32LE(P)===$e.Constants.END64SIG){E=L;continue}if(t.readUInt32LE(P)===$e.Constants.ZIP64SIG){N=P,D=P+$e.readBigUInt64LE(t,P+$e.Constants.ZIP64SIZE)+$e.Constants.ZIP64LEAD;break}}if(N==-1)throw $e.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(N,D)),c.commentLength&&(o=t.slice(z+$e.Constants.ENDHDR)),k&&b()}function A(){r.length>1&&!m&&r.sort((k,P)=>k.entryName.toLowerCase().localeCompare(P.entryName.toLowerCase()))}return{get entries(){return d||b(),r.filter(k=>!x.has(k))},get comment(){return w.decode(o)},set comment(k){o=$e.toBuffer(k,w.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(k){this.entries.forEach(k)},getEntry:function(k){return d||b(),i[k]||null},setEntry:function(k){d||b(),r.push(k),i[k.entryName]=k,c.totalEntries=r.length},deleteFile:function(k,P=!0){d||b();let L=i[k];this.getEntryChildren(L,P).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(k){d||b();let P=i[k],L=r.indexOf(P);L>=0&&(r.splice(L,1),delete i[k],c.totalEntries=r.length)},getEntryChildren:function(k,P=!0){if(d||b(),typeof k=="object")if(k.isDirectory&&P){let L=[],E=k.entryName;for(let D of r)D.entryName.startsWith(E)&&L.push(D);return L}else return[k];return[]},getChildCount:function(k){if(k&&k.isDirectory){let P=this.getEntryChildren(k);return P.includes(k)?P.length-1:P.length}return 0},compressToBuffer:function(){d||b(),A();let k=[],P=[],L=0,E=0;c.size=0,c.offset=0;let D=0;for(let B of this.entries){let Y=B.getCompressedData();B.header.offset=E;let V=B.packLocalHeader(),re=V.length+Y.length;E+=re,k.push(V),k.push(Y);let Z=B.packCentralHeader();P.push(Z),c.size+=Z.length,L+=re+Z.length,D++}L+=c.mainHeaderSize,c.offset=E,c.totalEntries=D,E=0;let N=Buffer.alloc(L);for(let B of k)B.copy(N,E),E+=B.length;for(let B of P)B.copy(N,E),E+=B.length;let z=c.toBinary();return o&&o.copy(z,$e.Constants.ENDHDR),z.copy(N,E),t=N,d=!1,N},toAsyncBuffer:function(k,P,L,E){try{d||b(),A();let D=[],N=[],z=0,B=0,Y=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let Z=re.shift(),oe=Z.entryName+Z.extra.toString();L&&L(oe),Z.getCompressedDataAsync(function(ce){E&&E(oe),Z.header.offset=B;let R=Z.packLocalHeader(),G=R.length+ce.length;B+=G,D.push(R),D.push(ce);let W=Z.packCentralHeader();N.push(W),c.size+=W.length,z+=G+W.length,Y++,V(re)})}else{z+=c.mainHeaderSize,c.offset=B,c.totalEntries=Y,B=0;let Z=Buffer.alloc(z);D.forEach(function(ce){ce.copy(Z,B),B+=ce.length}),N.forEach(function(ce){ce.copy(Z,B),B+=ce.length});let oe=c.toBinary();o&&o.copy(oe,$e.Constants.ENDHDR),oe.copy(Z,B),t=Z,d=!1,k(Z)}};V(Array.from(this.entries))}catch(D){P(D)}}}}});var Iu=de((JI,Su)=>{var Ee=pr(),be=xe("path"),Xm=Ka(),Zm=Eu(),On=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),vu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Qm=(...t)=>Ee.findLast(t,e=>typeof e=="function"),ew={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};Su.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),ew);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 Zm(r,i),{canonical:d,sanitize:u,zipnamefix:x}=Ee;function h(b){if(b&&c){var S;if(typeof b=="string"&&(S=c.getEntry(be.posix.normalize(b))),typeof b=="object"&&typeof b.entryName<"u"&&typeof b.header<"u"&&(S=c.getEntry(b.entryName)),S)return S}return null}function m(b){let{join:S,normalize:A,sep:k}=be.posix;return S(be.isAbsolute(b)?"/":".",A(k+b.split("\\").join(k)+k))}function w(b){return b instanceof RegExp?(function(S){return function(A){return S.test(A)}})(b):typeof b!="function"?()=>!0:b}let I=(b,S)=>{let A=S.slice(-1);return A=A===o.sep?o.sep:"",be.relative(b,S)+A};return{readFile:function(b,S){var A=h(b);return A&&A.getData(S)||null},childCount:function(b){let S=h(b);if(S)return c.getChildCount(S)},readFileAsync:function(b,S){var A=h(b);A?A.getDataAsync(S):S(null,"getEntry failed for:"+b)},readAsText:function(b,S){var A=h(b);if(A){var k=A.getData();if(k&&k.length)return k.toString(S||"utf8")}return""},readAsTextAsync:function(b,S,A){var k=h(b);k?k.getDataAsync(function(P,L){if(L){S(P,L);return}P&&P.length?S(P.toString(A||"utf8")):S("")}):S("")},deleteFile:function(b,S=!0){var A=h(b);A&&c.deleteFile(A.entryName,S)},deleteEntry:function(b){var S=h(b);S&&c.deleteEntry(S.entryName)},addZipComment:function(b){c.comment=b},getZipComment:function(){return c.comment||""},addZipEntryComment:function(b,S){var A=h(b);A&&(A.comment=S)},getZipEntryComment:function(b){var S=h(b);return S&&S.comment||""},updateFile:function(b,S){var A=h(b);A&&A.setData(S)},addLocalFile:function(b,S,A,k){if(o.fs.existsSync(b)){S=S?m(S):"";let P=be.win32.basename(be.win32.normalize(b));S+=A||P;let L=o.fs.statSync(b),E=L.isFile()?o.fs.readFileSync(b):Buffer.alloc(0);L.isDirectory()&&(S+=o.sep),this.addFile(S,E,k,L)}else throw Ee.Errors.FILE_NOT_FOUND(b)},addLocalFileAsync:function(b,S){b=typeof b=="object"?b:{localPath:b};let A=be.resolve(b.localPath),{comment:k}=b,{zipPath:P,zipName:L}=b,E=this;o.fs.stat(A,function(D,N){if(D)return S(D,!1);P=P?m(P):"";let z=be.win32.basename(be.win32.normalize(A));if(P+=L||z,N.isFile())o.fs.readFile(A,function(B,Y){return B?S(B,!1):(E.addFile(P,Y,k,N),setImmediate(S,void 0,!0))});else if(N.isDirectory())return P+=o.sep,E.addFile(P,Buffer.alloc(0),k,N),setImmediate(S,void 0,!0)})},addLocalFolder:function(b,S,A){if(A=w(A),S=S?m(S):"",b=be.normalize(b),o.fs.existsSync(b)){let k=o.findFiles(b),P=this;if(k.length)for(let L of k){let E=be.join(S,I(b,L));A(E)&&P.addLocalFile(L,be.dirname(E))}}else throw Ee.Errors.FILE_NOT_FOUND(b)},addLocalFolderAsync:function(b,S,A,k){k=w(k),A=A?m(A):"",b=be.normalize(b);var P=this;o.fs.open(b,"r",function(L){if(L&&L.code==="ENOENT")S(void 0,Ee.Errors.FILE_NOT_FOUND(b));else if(L)S(void 0,L);else{var E=o.findFiles(b),D=-1,N=function(){if(D+=1,D<E.length){var z=E[D],B=I(b,z).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),k(B)?o.fs.stat(z,function(Y,V){Y&&S(void 0,Y),V.isFile()?o.fs.readFile(z,function(re,Z){re?S(void 0,re):(P.addFile(A+B,Z,"",V),N())}):(P.addFile(A+B+"/",Buffer.alloc(0),"",V),N())}):process.nextTick(()=>{N()})}else S(!0,void 0)};N()}})},addLocalFolderAsync2:function(b,S){let A=this;b=typeof b=="object"?b:{localPath:b},localPath=be.resolve(m(b.localPath));let{zipPath:k,filter:P,namefix:L}=b;P instanceof RegExp?P=(function(N){return function(z){return N.test(z)}})(P):typeof P!="function"&&(P=function(){return!0}),k=k?m(k):"",L=="latin1"&&(L=N=>N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof L!="function"&&(L=N=>N);let E=N=>be.join(k,L(I(localPath,N))),D=N=>be.win32.basename(be.win32.normalize(L(N)));o.fs.open(localPath,"r",function(N){N&&N.code==="ENOENT"?S(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):N?S(void 0,N):o.findFilesAsync(localPath,function(z,B){if(z)return S(z);B=B.filter(Y=>P(E(Y))),B.length||S(void 0,!1),setImmediate(B.reverse().reduce(function(Y,V){return function(re,Z){if(re||Z===!1)return setImmediate(Y,re,!1);A.addLocalFileAsync({localPath:V,zipPath:be.dirname(E(V)),zipName:D(V)},Y)}},S))})})},addLocalFolderPromise:function(b,S){return new Promise((A,k)=>{this.addLocalFolderAsync2(Object.assign({localPath:b},S),(P,L)=>{P&&k(P),L&&A(this)})})},addFile:function(b,S,A,k){b=x(b);let P=h(b),L=P!=null;L||(P=new Xm(i),P.entryName=b),P.comment=A||"";let E=typeof k=="object"&&k instanceof o.fs.Stats;E&&(P.header.time=k.mtime);var D=P.isDirectory?16:0;let N=P.isDirectory?16384:32768;return E?N|=4095&k.mode:typeof k=="number"?N|=4095&k:N|=P.isDirectory?493:420,D=(D|N<<16)>>>0,P.attr=D,P.setData(S),L||c.setEntry(P),P},getEntries:function(b){return c.password=b,c?c.entries:[]},getEntry:function(b){return h(b)},getEntryCount:function(){return c.getEntryCount()},forEach:function(b){return c.forEach(b)},extractEntryTo:function(b,S,A,k,P,L){k=On(!1,k),P=On(!1,P),A=On(!0,A),L=vu(P,L);var E=h(b);if(!E)throw Ee.Errors.NO_ENTRY();var D=d(E.entryName),N=u(S,L&&!E.isDirectory?L:A?D:be.basename(D));if(E.isDirectory){var z=c.getEntryChildren(E);return z.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw Ee.Errors.CANT_EXTRACT_FILE();var Z=d(V.entryName),oe=u(S,A?Z:be.basename(Z));let ce=P?V.header.fileAttr:void 0;o.writeFileTo(oe,re,k,ce)}),!0}var B=E.getData(c.password);if(!B)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(N)&&!k)throw Ee.Errors.CANT_OVERRIDE();let Y=P?b.header.fileAttr:void 0;return o.writeFileTo(N,B,k,Y),!0},test:function(b){if(!c)return!1;for(var S in c.entries)try{if(S.isDirectory)continue;var A=c.entries[S].getData(b);if(!A)return!1}catch{return!1}return!0},extractAllTo:function(b,S,A,k){if(A=On(!1,A),k=vu(A,k),S=On(!1,S),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(P){var L=u(b,d(P.entryName));if(P.isDirectory){o.makeDir(L);return}var E=P.getData(k);if(!E)throw Ee.Errors.CANT_EXTRACT_FILE();let D=A?P.header.fileAttr:void 0;o.writeFileTo(L,E,S,D);try{o.fs.utimesSync(L,P.header.time,P.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(b,S,A,k){if(k=Qm(S,A,k),A=On(!1,A),S=On(!1,S),!k)return new Promise((N,z)=>{this.extractAllToAsync(b,S,A,function(B){B?z(B):N(this)})});if(!c){k(Ee.Errors.NO_ZIP());return}b=be.resolve(b);let P=N=>u(b,be.normalize(d(N.entryName))),L=(N,z)=>new Error(N+': "'+z+'"'),E=[],D=[];c.entries.forEach(N=>{N.isDirectory?E.push(N):D.push(N)});for(let N of E){let z=P(N),B=A?N.header.fileAttr:void 0;try{o.makeDir(z),B&&o.fs.chmodSync(z,B),o.fs.utimesSync(z,N.header.time,N.header.time)}catch{k(L("Unable to create folder",z))}}D.reverse().reduce(function(N,z){return function(B){if(B)N(B);else{let Y=be.normalize(d(z.entryName)),V=u(b,Y);z.getDataAsync(function(re,Z){if(Z)N(Z);else if(!re)N(Ee.Errors.CANT_EXTRACT_FILE());else{let oe=A?z.header.fileAttr:void 0;o.writeFileToAsync(V,re,S,oe,function(ce){ce||N(L("Unable to write file",V)),o.fs.utimes(V,z.header.time,z.header.time,function(R){R?N(L("Unable to set times",V)):N()})})}})}}},k)()},writeZip:function(b,S){if(arguments.length===1&&typeof b=="function"&&(S=b,b=""),!b&&i.filename&&(b=i.filename),!!b){var A=c.compressToBuffer();if(A){var k=o.writeFileTo(b,A,!0);typeof S=="function"&&S(k?null:new Error("failed"),"")}}},writeZipPromise:function(b,S){let{overwrite:A,perm:k}=Object.assign({overwrite:!0},S);return new Promise((P,L)=>{!b&&i.filename&&(b=i.filename),b||L("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let D=N=>N?P(N):L("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(b,E,A,k,D)},L)})},toBufferPromise:function(){return new Promise((b,S)=>{c.toAsyncBuffer(b,S)})},toBuffer:function(b,S,A,k){return typeof b=="function"?(c.toAsyncBuffer(b,S,A,k),null):c.compressToBuffer()}}}});import{execFile as oy,spawn as ay,spawnSync as hk}from"node:child_process";import{promisify as cy}from"node:util";function ly(t){if(process.platform!=="win32")return!1;if(Wf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Wf,"").toLowerCase();return dy.has(r)}function Kf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return ly(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function it(t,e=[],r={}){return ay(t,e,Kf(t,r))}function $f(t,e=[],r={}){return uy(t,e,Kf(t,r))}var dy,Wf,uy,Jt=et(()=>{"use strict";dy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Wf=/\.(cmd|bat|ps1)$/i;uy=cy(oy)});var Zt=de((ER,qx)=>{"use strict";var Hx=["nodebuffer","arraybuffer","fragments"],Gx=typeof Blob<"u";Gx&&Hx.push("blob");qx.exports={BINARY_TYPES:Hx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Gx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qi=de((vR,Fo)=>{"use strict";var{EMPTY_BUFFER:nv}=Zt(),vd=Buffer[Symbol.species];function rv(t,e){if(t.length===0)return nv;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];r.set(c,i),i+=c.length}return i<e?new vd(r.buffer,r.byteOffset,i):r}function jx(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Wx(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function iv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Sd(t){if(Sd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vd(t):ArrayBuffer.isView(t)?e=new vd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Sd.readOnly=!1),e}Fo.exports={concat:rv,mask:jx,toArrayBuffer:iv,toBuffer:Sd,unmask:Wx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");Fo.exports.mask=function(e,r,i,o,c){c<48?jx(e,r,i,o,c):t.mask(e,r,i,o,c)},Fo.exports.unmask=function(e,r){e.length<32?Wx(e,r):t.unmask(e,r)}}catch{}});var Vx=de((SR,$x)=>{"use strict";var Kx=Symbol("kDone"),Id=Symbol("kRun"),Ad=class{constructor(e){this[Kx]=()=>{this.pending--,this[Id]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Id]()}[Id](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Kx])}}};$x.exports=Ad});var qr=de((IR,Zx)=>{"use strict";var es=xe("zlib"),Yx=Qi(),sv=Vx(),{kStatusCode:Jx}=Zt(),ov=Buffer[Symbol.species],av=Buffer.from([0,0,255,255]),Uo=Symbol("permessage-deflate"),Qt=Symbol("total-length"),Hr=Symbol("callback"),Tn=Symbol("buffers"),Gr=Symbol("error"),zo,kd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zo=new sv(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[Hr];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){zo.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){zo.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=es.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Uo]=this,this._inflate[Qt]=0,this._inflate[Tn]=[],this._inflate.on("error",dv),this._inflate.on("data",Xx)}this._inflate[Hr]=i,this._inflate.write(e),r&&this._inflate.write(av),this._inflate.flush(()=>{let c=this._inflate[Gr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Yx.concat(this._inflate[Tn],this._inflate[Qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qt]=0,this._inflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?es.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=es.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Qt]=0,this._deflate[Tn]=[],this._deflate.on("data",cv)}this._deflate[Hr]=i,this._deflate.write(e),this._deflate.flush(es.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Yx.concat(this._deflate[Tn],this._deflate[Qt]);r&&(c=new ov(c.buffer,c.byteOffset,c.length-4)),this._deflate[Hr]=null,this._deflate[Qt]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Zx.exports=kd;function cv(t){this[Tn].push(t),this[Qt]+=t.length}function Xx(t){if(this[Qt]+=t.length,this[Uo]._maxPayload<1||this[Qt]<=this[Uo]._maxPayload){this[Tn].push(t);return}this[Gr]=new RangeError("Max payload size exceeded"),this[Gr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gr][Jx]=1009,this.removeListener("data",Xx),this.reset()}function dv(t){if(this[Uo]._inflate=null,this[Gr]){this[Hr](this[Gr]);return}t[Jx]=1007,this[Hr](t)}});var jr=de((AR,Ho)=>{"use strict";var{isUtf8:Qx}=xe("buffer"),{hasBlob:lv}=Zt(),uv=[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 fv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Td(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function xv(t){return lv&&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:xv,isValidStatusCode:fv,isValidUTF8:Td,tokenChars:uv};if(Qx)Ho.exports.isValidUTF8=function(t){return t.length<24?Td(t):Qx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");Ho.exports.isValidUTF8=function(e){return e.length<32?Td(e):t(e)}}catch{}});var Od=de((kR,oh)=>{"use strict";var{Writable:hv}=xe("stream"),eh=qr(),{BINARY_TYPES:pv,EMPTY_BUFFER:th,kStatusCode:gv,kWebSocket:mv}=Zt(),{concat:Cd,toArrayBuffer:wv,unmask:_v}=Qi(),{isValidStatusCode:yv,isValidUTF8:nh}=jr(),Go=Buffer[Symbol.species],gt=0,rh=1,ih=2,sh=3,Pd=4,Rd=5,qo=6,Dd=class extends hv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[mv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=gt}_write(e,r,i){if(this._opcode===8&&this._state==gt)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 Go(i.buffer,i.byteOffset+e,i.length-e),new Go(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 Go(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 gt:this.getInfo(e);break;case rh:this.getPayloadLength16(e);break;case ih:this.getPayloadLength64(e);break;case sh:this.getMask();break;case Pd:this.getData(e);break;case Rd: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[eh.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=rh:this._payloadLength===127?this._state=ih: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=sh:this._state=Pd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Pd}getData(e){let r=th;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&&_v(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Rd,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[eh.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===gt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=gt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Cd(i,r):this._binaryType==="arraybuffer"?o=wv(Cd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=gt):(this._state=qo,setImmediate(()=>{this.emit("message",o,!0),this._state=gt,this.startLoop(e)}))}else{let o=Cd(i,r);if(!this._skipUTF8Validation&&!nh(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Rd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=gt):(this._state=qo,setImmediate(()=>{this.emit("message",o,!1),this._state=gt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,th),this.end();else{let i=e.readUInt16BE(0);if(!yv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Go(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!nh(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=gt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=gt):(this._state=qo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=gt,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[gv]=o,d}};oh.exports=Dd});var Md=de((CR,dh)=>{"use strict";var{Duplex:TR}=xe("stream"),{randomFillSync:bv}=xe("crypto"),{types:{isUint8Array:Ev}}=xe("util"),ah=qr(),{EMPTY_BUFFER:vv,kWebSocket:Sv,NOOP:Iv}=Zt(),{isBlob:Wr,isValidStatusCode:Av}=jr(),{mask:ch,toBuffer:Xn}=Qi(),mt=Symbol("kByteLength"),kv=Buffer.alloc(4),jo=8*1024,Zn,Kr=jo,At=0,Tv=1,Cv=2,Ld=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=At,this.onerror=Iv,this[Sv]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||kv,r.generateMask?r.generateMask(i):(Kr===jo&&(Zn===void 0&&(Zn=Buffer.alloc(jo)),bv(Zn,0,jo),Kr=0),i[0]=Zn[Kr++],i[1]=Zn[Kr++],i[2]=Zn[Kr++],i[3]=Zn[Kr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[mt]!==void 0?u=r[mt]:(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?(ch(e,i,h,c,u),[h]):(ch(e,i,e,0,u),[h,e])):[h,e]}close(e,r,i,o){let c;if(e===void 0)c=vv;else{if(typeof e!="number"||!Av(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(Ev(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[mt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==At?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Wr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Wr(e)?this._state!==At?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==At?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Wr(e)?(o=e.size,c=!1):(e=Xn(e),o=e.length,c=Xn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[mt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Wr(e)?this._state!==At?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==At?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[ah.extensionName],c=r.binary?2:1,d=r.compress,u,x;typeof e=="string"?(u=Buffer.byteLength(e),x=!1):Wr(e)?(u=e.size,x=!1):(e=Xn(e),u=e.length,x=Xn.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={[mt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:x,rsv1:d};Wr(e)?this._state!==At?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==At?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[mt],this._state=Cv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Nd,this,u,o);return}this._bufferedBytes-=i[mt];let d=Xn(c);r?this.dispatch(d,r,i,o):(this._state=At,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(Pv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[ah.extensionName];this._bufferedBytes+=i[mt],this._state=Tv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let x=new Error("The socket was closed while data was being compressed");Nd(this,x,o);return}this._bufferedBytes-=i[mt],this._state=At,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===At&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][mt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][mt],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)}};dh.exports=Ld;function Nd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function Pv(t,e,r){Nd(t,e,r),t.onerror(e)}});var wh=de((PR,mh)=>{"use strict";var{kForOnEventAttribute:ts,kListener:Bd}=Zt(),lh=Symbol("kCode"),uh=Symbol("kData"),fh=Symbol("kError"),xh=Symbol("kMessage"),hh=Symbol("kReason"),$r=Symbol("kTarget"),ph=Symbol("kType"),gh=Symbol("kWasClean"),en=class{constructor(e){this[$r]=null,this[ph]=e}get target(){return this[$r]}get type(){return this[ph]}};Object.defineProperty(en.prototype,"target",{enumerable:!0});Object.defineProperty(en.prototype,"type",{enumerable:!0});var Qn=class extends en{constructor(e,r={}){super(e),this[lh]=r.code===void 0?0:r.code,this[hh]=r.reason===void 0?"":r.reason,this[gh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[lh]}get reason(){return this[hh]}get wasClean(){return this[gh]}};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 en{constructor(e,r={}){super(e),this[fh]=r.error===void 0?null:r.error,this[xh]=r.message===void 0?"":r.message}get error(){return this[fh]}get message(){return this[xh]}};Object.defineProperty(Vr.prototype,"error",{enumerable:!0});Object.defineProperty(Vr.prototype,"message",{enumerable:!0});var ns=class extends en{constructor(e,r={}){super(e),this[uh]=r.data===void 0?null:r.data}get data(){return this[uh]}};Object.defineProperty(ns.prototype,"data",{enumerable:!0});var Rv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[ts]&&o[Bd]===e&&!o[ts])return;let i;if(t==="message")i=function(c,d){let u=new ns("message",{data:d?c:c.toString()});u[$r]=this,Wo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Qn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[$r]=this,Wo(e,this,u)};else if(t==="error")i=function(c){let d=new Vr("error",{error:c,message:c.message});d[$r]=this,Wo(e,this,d)};else if(t==="open")i=function(){let c=new en("open");c[$r]=this,Wo(e,this,c)};else return;i[ts]=!!r[ts],i[Bd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Bd]===e&&!r[ts]){this.removeListener(t,r);break}}};mh.exports={CloseEvent:Qn,ErrorEvent:Vr,Event:en,EventTarget:Rv,MessageEvent:ns};function Wo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ko=de((RR,_h)=>{"use strict";var{tokenChars:rs}=jr();function Bt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Dv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,x=-1,h=-1,m=-1,w=0;for(;w<t.length;w++)if(h=t.charCodeAt(w),d===void 0)if(m===-1&&rs[h]===1)x===-1&&(x=w);else if(w!==0&&(h===32||h===9))m===-1&&x!==-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let b=t.slice(x,m);h===44?(Bt(e,b,r),r=Object.create(null)):d=b,x=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&rs[h]===1)x===-1&&(x=w);else if(h===32||h===9)m===-1&&x!==-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w),Bt(r,t.slice(x,m),!0),h===44&&(Bt(e,d,r),r=Object.create(null),d=void 0),x=m=-1}else if(h===61&&x!==-1&&m===-1)u=t.slice(x,w),x=m=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(rs[h]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);x===-1?x=w:i||(i=!0),o=!1}else if(c)if(rs[h]===1)x===-1&&(x=w);else if(h===34&&x!==-1)c=!1,m=w;else if(h===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(h===34&&t.charCodeAt(w-1)===61)c=!0;else if(m===-1&&rs[h]===1)x===-1&&(x=w);else if(x!==-1&&(h===32||h===9))m===-1&&(m=w);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let b=t.slice(x,m);i&&(b=b.replace(/\\/g,""),i=!1),Bt(r,u,b),h===44&&(Bt(e,d,r),r=Object.create(null),d=void 0),u=void 0,x=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(x===-1||c||h===32||h===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=w);let I=t.slice(x,m);return d===void 0?Bt(e,I,r):(u===void 0?Bt(r,I,!0):i?Bt(r,u,I.replace(/\\/g,"")):Bt(r,u,I),Bt(e,d,r)),e}function Ov(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(", ")}_h.exports={format:Ov,parse:Dv}});var Jo=de((LR,Rh)=>{"use strict";var Lv=xe("events"),Nv=xe("https"),Mv=xe("http"),Eh=xe("net"),Bv=xe("tls"),{randomBytes:Fv,createHash:zv}=xe("crypto"),{Duplex:DR,Readable:OR}=xe("stream"),{URL:Fd}=xe("url"),Cn=qr(),Uv=Od(),Hv=Md(),{isBlob:Gv}=jr(),{BINARY_TYPES:yh,CLOSE_TIMEOUT:qv,EMPTY_BUFFER:$o,GUID:jv,kForOnEventAttribute:zd,kListener:Wv,kStatusCode:Kv,kWebSocket:je,NOOP:vh}=Zt(),{EventTarget:{addEventListener:$v,removeEventListener:Vv}}=wh(),{format:Yv,parse:Jv}=Ko(),{toBuffer:Xv}=Qi(),Sh=Symbol("kAborted"),Ud=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],Zv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends Lv{constructor(e,r,i){super(),this._binaryType=yh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$o,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]),Ih(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){yh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,i){let o=new Uv({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new Hv(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",t1),o.on("drain",n1),o.on("error",r1),o.on("message",i1),o.on("ping",s1),o.on("pong",o1),c.onerror=a1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Th),e.on("data",Yo),e.on("end",Ch),e.on("error",Ph),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Cn.extensionName]&&this._extensions[Cn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),kh(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||$o,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||$o,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[Cn.extensionName]||(o.compress=!1),this._sender.send(e||$o,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:tn.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:tn.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[zd])return e[Wv];return null},set(e){for(let r of this.listeners(t))if(r[zd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[zd]:!0})}})});we.prototype.addEventListener=$v;we.prototype.removeEventListener=Vv;Rh.exports=we;function Ih(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qv,protocolVersion:Ud[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Ud.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ud.join(", ")})`);let c;if(e instanceof Fd)c=e;else try{c=new Fd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",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 A=new SyntaxError(x);if(t._redirects===0)throw A;Vo(t,A);return}let h=d?443:80,m=Fv(16).toString("base64"),w=d?Nv.request:Mv.request,I=new Set,b;if(o.createConnection=o.createConnection||(d?e1:Qv),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":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new Cn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Yv({[Cn.extensionName]:b.offer()})),r.length){for(let A of r){if(typeof A!="string"||!Zv.test(A)||I.has(A))throw new SyntaxError("An invalid or duplicated subprotocol was specified");I.add(A)}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 A=o.path.split(":");o.socketPath=A[0],o.path=A[1]}let S;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let A=i&&i.headers;if(i={...i,headers:{}},A)for(let[k,P]of Object.entries(A))i.headers[k.toLowerCase()]=P}else if(t.listenerCount("redirect")===0){let A=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!A||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,A||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),S=t._req=w(o),t._redirects&&t.emit("redirect",t.url,S)}else S=t._req=w(o);o.timeout&&S.on("timeout",()=>{dt(t,S,"Opening handshake has timed out")}),S.on("error",A=>{S===null||S[Sh]||(S=t._req=null,Vo(t,A))}),S.on("response",A=>{let k=A.headers.location,P=A.statusCode;if(k&&o.followRedirects&&P>=300&&P<400){if(++t._redirects>o.maxRedirects){dt(t,S,"Maximum redirects exceeded");return}S.abort();let L;try{L=new Fd(k,e)}catch{let D=new SyntaxError(`Invalid URL: ${k}`);Vo(t,D);return}Ih(t,L,r,i)}else t.emit("unexpected-response",S,A)||dt(t,S,`Unexpected server response: ${A.statusCode}`)}),S.on("upgrade",(A,k,P)=>{if(t.emit("upgrade",A),t.readyState!==we.CONNECTING)return;S=t._req=null;let L=A.headers.upgrade;if(L===void 0||L.toLowerCase()!=="websocket"){dt(t,k,"Invalid Upgrade header");return}let E=zv("sha1").update(m+jv).digest("base64");if(A.headers["sec-websocket-accept"]!==E){dt(t,k,"Invalid Sec-WebSocket-Accept header");return}let D=A.headers["sec-websocket-protocol"],N;if(D!==void 0?I.size?I.has(D)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":I.size&&(N="Server sent no subprotocol"),N){dt(t,k,N);return}D&&(t._protocol=D);let z=A.headers["sec-websocket-extensions"];if(z!==void 0){if(!b){dt(t,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=Jv(z)}catch{dt(t,k,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(B);if(Y.length!==1||Y[0]!==Cn.extensionName){dt(t,k,"Server indicated an extension that was not requested");return}try{b.accept(B[Cn.extensionName])}catch{dt(t,k,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cn.extensionName]=b}t.setSocket(k,P,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,t):S.end()}function Vo(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Qv(t){return t.path=t.socketPath,Eh.connect(t)}function e1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Eh.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[Sh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Vo,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=Gv(e)?e.size:Xv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${tn[t.readyState]})`);process.nextTick(r,i)}}function t1(t,e){let r=this[je];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[je]!==void 0&&(r._socket.removeListener("data",Yo),process.nextTick(Ah,r._socket),t===1005?r.close():r.close(t,e))}function n1(){let t=this[je];t.isPaused||t._socket.resume()}function r1(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",Yo),process.nextTick(Ah,e._socket),e.close(t[Kv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function bh(){this[je].emitClose()}function i1(t,e){this[je].emit("message",t,e)}function s1(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,vh),e.emit("ping",t)}function o1(t){this[je].emit("pong",t)}function Ah(t){t.resume()}function a1(t){let e=this[je];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,kh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function kh(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Th(){let t=this[je];if(this.removeListener("close",Th),this.removeListener("data",Yo),this.removeListener("end",Ch),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",bh),t._receiver.on("finish",bh))}function Yo(t){this[je]._receiver.write(t)||this.pause()}function Ch(){let t=this[je];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function Ph(){let t=this[je];this.removeListener("error",Ph),this.on("error",vh),t&&(t._readyState=we.CLOSING,this.destroy())}});var Nh=de((MR,Lh)=>{"use strict";var NR=Jo(),{Duplex:c1}=xe("stream");function Dh(t){t.emit("close")}function d1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Oh(t){this.removeListener("error",Oh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function l1(t,e){let r=!0,i=new c1({...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(Dh,i);return}let d=!1;t.once("error",function(x){d=!0,c(x)}),t.once("close",function(){d||c(o),process.nextTick(Dh,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",d1),i.on("error",Oh),i}Lh.exports=l1});var Gd=de((BR,Mh)=>{"use strict";var{tokenChars:u1}=jr();function f1(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&&u1[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}Mh.exports={parse:f1}});var qh=de((zR,Gh)=>{"use strict";var x1=xe("events"),Xo=xe("http"),{Duplex:FR}=xe("stream"),{createHash:h1}=xe("crypto"),Bh=Ko(),er=qr(),p1=Gd(),g1=Jo(),{CLOSE_TIMEOUT:m1,GUID:w1,kWebSocket:_1}=Zt(),y1=/^[+/0-9A-Za-z]{22}==$/,Fh=0,zh=1,Hh=2,qd=class extends x1{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:m1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:g1,...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=b1(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=Fh}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===Hh){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!==zh)if(this._state=zh,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",Uh);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){tr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!y1.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 x=e.headers["sec-websocket-protocol"],h=new Set;if(x!==void 0)try{h=p1.parse(x)}catch{tr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&m!==void 0){let I=new er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let b=Bh.parse(m);b[er.extensionName]&&(I.accept(b[er.extensionName]),w[er.extensionName]=I)}catch{tr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let I={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(I,(b,S,A,k)=>{if(!b)return ss(r,S||401,A,k);this.completeUpgrade(w,c,h,e,r,i,o)});return}if(!this.options.verifyClient(I))return ss(r,401)}this.completeUpgrade(w,c,h,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[_1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Fh)return ss(c,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${h1("sha1").update(r+w1).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(h.push(`Sec-WebSocket-Protocol: ${w}`),m._protocol=w)}if(e[er.extensionName]){let w=e[er.extensionName].params,I=Bh.format({[er.extensionName]:[w]});h.push(`Sec-WebSocket-Extensions: ${I}`),m._extensions=e}this.emit("headers",h,o),c.write(h.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&ps(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as rm,mkdirSync as im}from"node:fs";import{join as sm}from"node:path";function Ml(t){let e=t.retentionDays??cm,r=t.clock??(()=>Nn(new Date));ms={bridgeSink:new ai(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ai(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();ps(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ps(t.agentLogsDir(o),"agent",i,e)}function dm(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Bl(t){Fa=t}function Fl(t){return ur[Fa]<=ur[t]}function zl(t,e){let r=ur[t];return r===void 0?!0:r>=ur[e]}function ws(t){Nl={...t}}function Ul(t){let e=(u,h=2)=>String(u).padStart(h,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),d=e(o%60);return`${Nn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function rt(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Ul(new Date),level:e,module:r,msg:i,...o})}
11
+ `;im(t,{recursive:!0}),rm(sm(t,lr("bridge",Nn(new Date))),c)}catch{}}function lm(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function gs(t,e,r,i,o){if(ur[t]<ur[Fa])return;let c=`${JSON.stringify({ts:Ul(new Date),level:t,module:e,msg:r,...Nl,...i})}
12
+ `;if(ms){let d=lm(o,i),u=d?dm(ms,d):ms.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?am.write(c):om.write(c)}function G(t,e){return{debug:(r,i)=>gs("debug",t,r,i,e),info:(r,i)=>gs("info",t,r,i,e),warn:(r,i)=>gs("warn",t,r,i,e),error:(r,i)=>gs("error",t,r,i,e),child:r=>G(`${t}.${r}`,e),forAgent:r=>G(t,r)}}var ur,Fa,om,am,Nl,cm,ms,re=nt(()=>{"use strict";dr();Ba();ur={debug:10,info:20,warn:30,error:40},Fa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),om=process.stdout,am=process.stderr,Nl={},cm=Xe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ms=null});var A,Ke=nt(()=>{"use strict";A=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var jl={};Na(jl,{ACP_WRAPPER_NPM_PACKAGES:()=>ys,_resetAcpInstallerForTests:()=>gm,_setBinaryPathCacheForTests:()=>mm,buildAcpSpawn:()=>ci,ensureAcpInstalled:()=>hr,getAcpBinaryPath:()=>bs,pickWhichLine:()=>Ha,probeAcpVersion:()=>pm,resolveAcpCommand:()=>ql});import{readFileSync as Hl}from"node:fs";import{createRequire as um}from"node:module";import{dirname as fm,resolve as hm}from"node:path";function Ua(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Ha(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function xm(t){let e=Gl.resolve(`${t.npmPackage}/package.json`),r=fm(e),i=JSON.parse(Hl(e,"utf8")),o=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!o)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return hm(r,o)}async function hr(t,e){let r=za[t];if(!r)throw new A("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=fr.get(t);if(i)return i;let o=Ua(t);if(o)return fr.set(t,o),_s.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let c=xm(r);return fr.set(t,c),_s.info("acp wrapper resolved",{framework:t,binary:r.binary,path:c}),c}catch(c){throw _s.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(c)}),new A("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:c})}}async function pm(t){let e=za[t];if(e)try{let r=Gl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Hl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){_s.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function bs(t){return fr.get(t)}function ql(t,e){if(e)return e;let r=Ua(t);if(r)return r;let i=bs(t);if(!i)throw new A("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function ci(t,e,r){if(e)return{command:e,args:[...r]};let i=Ua(t);if(i)return{command:i,args:[...r]};let o=ql(t);return{command:process.execPath,args:[o,...r]}}function gm(){fr.clear()}function mm(t,e){fr.set(t,e)}var _s,za,ys,Gl,fr,dn=nt(()=>{"use strict";Ke();re();_s=G("agents.acp-installer"),za={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ys=Object.values(za).filter(t=>t!==void 0).map(t=>t.npmPackage),Gl=um(import.meta.url),fr=new Map});import{chmod as _m,mkdir as ym,readFile as bm,rename as Em,rm as vm,writeFile as Sm}from"node:fs/promises";import{dirname as Im}from"node:path";async function ln(t){try{let e=await bm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function un(t,e,r){await ym(Im(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Sm(i,e,{encoding:"utf8",mode:r?.mode}),await Em(i,t),r?.mode!==void 0&&await _m(t,r.mode)}catch(o){throw await vm(i,{force:!0}).catch(()=>{}),o}}async function fn(t,e,r){await un(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var hn=nt(()=>{"use strict"});import{promises as $l,readdirSync as Am}from"node:fs";import{homedir as km}from"node:os";import{sep as Tm,join as ke,resolve as Vl}from"node:path";function Z(t){let e=t??km(),r=ke(e,".coze"),i=ke(r,"bridge"),o=ke(i,"lib"),c=ke(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:ke(o,"index.js"),binDir:ke(i,"bin"),pidFile:ke(i,"bridge.pid"),portFile:ke(i,"bridge.port"),tokenFile:ke(i,"bridge.token"),patTokenFile:ke(i,"pat-token"),agentEnvFile:ke(i,"agent-env.json"),logFile:ke(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:ke(c,"daemon-stdio.log"),installLock:ke(i,"install.lock"),configFile:ke(i,"config.json"),agentsRoot:ke(r,"agents")}}function Fe(t,e=Z()){let r=ke(e.agentsRoot,t);return{root:r,config:ke(r,"config.json"),workspace:ke(r,"workspace"),logs:ke(r,"logs")}}function Es(t=Z()){try{return Am(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function di(t,e){let r=await $l.realpath(Vl(t)).catch(()=>null);if(!r)return!1;let i=await $l.realpath(Vl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?r.toLowerCase():r,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+Tm)}var Te=nt(()=>{"use strict"});var Ss={};Na(Ss,{AGENT_CONFIG_FILE_MODE:()=>vs,enforceAgentConfigMode:()=>Dm,loadAgentConfig:()=>Ce,persistAgentSessions:()=>li,persistAgentSkills:()=>ui,saveAgentConfig:()=>ze});import{chmod as Cm,stat as Rm}from"node:fs/promises";function Ce(t,e){return ln(Fe(t,e).config)}function ze(t,e){return fn(Fe(t.agentId,e).config,t,{mode:vs})}async function Dm(t,e){if(process.platform==="win32")return;let r=Fe(t,e).config;try{let i=await Rm(r);if(!i.isFile())return;let o=i.mode&511;o!==vs&&(await Cm(r,vs),Jl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Jl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function li(t,e,r){let i=await Ce(t,r);i&&(i.sessions=Object.fromEntries(e),await ze(i,r))}async function ui(t,e,r){let i=await Ce(t,r);i&&(i.skills=e,await ze(i,r))}var Jl,vs,xn=nt(()=>{"use strict";hn();re();Te();Jl=G("agent-config"),vs=384});var ja=ae((t2,Yl)=>{Yl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var As=ae(eu=>{var Ql={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Bm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Ql))eu[t]=Bm(Ql[t])});var su=ae((r2,iu)=>{var Fm=fe("fs"),Le=fe("path"),tu=ja(),zm=As(),Um=typeof process=="object"&&process.platform==="win32",nu=t=>typeof t=="object"&&t!==null,ru=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ee(t){this.sep=Le.sep,this.fs=Fm,nu(t)&&nu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}iu.exports=Ee;Ee.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw zm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ee.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Le.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ee.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!r)return o(!1);c.fs.stat(t,function(u,h){if(d&&h.isDirectory())return o(!1);var x=Le.dirname(t);c.fs.exists(x,function(m){m||c.makeDir(x),c.fs.open(t,"w",438,function(w,v){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ee.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Le.join(i,u),x=e.fs.statSync(h);(!o||o.test(h))&&d.push(Le.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(r(h,o,c)))}),d}return r(t,void 0,!0)};Ee.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Le.join(t,u),r.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Le.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};Ee.prototype.getAttributes=function(){};Ee.prototype.setAttributes=function(){};Ee.crc32update=function(t,e){return ru[(t^e)&255]^t>>>8};Ee.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ee.crc32update(r,t[i++]);return~r>>>0};Ee.methodToString=function(t){switch(t){case tu.STORED:return"STORED ("+t+")";case tu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ee.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};Ee.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.posix.join(".",e)};Ee.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ee.sanitize=function(t,e){t=Le.resolve(Le.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Le.normalize(Le.join(t,r.slice(i,o).join(Le.sep)));if(c.indexOf(t)===0)return c}return Le.normalize(Le.join(t,Le.basename(e)))};Ee.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ee.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ee.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ee.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Ee.isWin=Um;Ee.crcTable=ru});var au=ae((i2,ou)=>{var Hm=fe("path");ou.exports=function(t,{fs:e}){var r=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(o=e.statSync(r),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=Hm.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var du=ae((s2,cu)=>{cu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var gr=ae((o2,pr)=>{pr.exports=su();pr.exports.Constants=ja();pr.exports.Errors=As();pr.exports.FileAttr=au();pr.exports.decoder=du()});var uu=ae((a2,lu)=>{var pn=gr(),z=pn.Constants;lu.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,h=0,x=0,m=0,w=0,v=0,_=0,E=0;t|=pn.isWin?2560:768,r|=z.FLG_EFS;let S={extraLen:0},I=b=>Math.max(0,b)>>>0,k=b=>Math.max(0,b)&65535,R=b=>Math.max(0,b)&255;return o=pn.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return r},set flags(b){r=b},get flags_efs(){return(r&z.FLG_EFS)>0},set flags_efs(b){b?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(b){b?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(b){switch(b){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=b},get time(){return pn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=pn.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=I(b)},get timeHighByte(){return R(o>>>8)},get crc(){return c},set crc(b){c=I(b)},get compressedSize(){return d},set compressedSize(b){d=I(b)},get size(){return u},set size(b){u=I(b)},get fileNameLength(){return h},set fileNameLength(b){h=b},get extraLength(){return x},set extraLength(b){x=b},get extraLocalLength(){return S.extraLen},set extraLocalLength(b){S.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return w},set diskNumStart(b){w=I(b)},get inAttr(){return v},set inAttr(b){v=I(b)},get attr(){return _},set attr(b){_=I(b)},get fileAttr(){return(_||0)>>16&4095},get offset(){return E},set offset(b){E=I(b)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+m},get realDataOffset(){return E+z.LOCHDR+S.fnameLen+S.extraLen},get localHeader(){return S},loadLocalHeaderFromBinary:function(b){var D=b.slice(E,E+z.LOCHDR);if(D.readUInt32LE(0)!==z.LOCSIG)throw pn.Errors.INVALID_LOC();S.version=D.readUInt16LE(z.LOCVER),S.flags=D.readUInt16LE(z.LOCFLG),S.flags_desc=(S.flags&z.FLG_DESC)>0,S.method=D.readUInt16LE(z.LOCHOW),S.time=D.readUInt32LE(z.LOCTIM),S.crc=D.readUInt32LE(z.LOCCRC),S.compressedSize=D.readUInt32LE(z.LOCSIZ),S.size=D.readUInt32LE(z.LOCLEN),S.fnameLen=D.readUInt16LE(z.LOCNAM),S.extraLen=D.readUInt16LE(z.LOCEXT);let O=E+z.LOCHDR+S.fnameLen,F=O+S.extraLen;return b.slice(O,F)},loadFromBinary:function(b){if(b.length!==z.CENHDR||b.readUInt32LE(0)!==z.CENSIG)throw pn.Errors.INVALID_CEN();t=b.readUInt16LE(z.CENVEM),e=b.readUInt16LE(z.CENVER),r=b.readUInt16LE(z.CENFLG),i=b.readUInt16LE(z.CENHOW),o=b.readUInt32LE(z.CENTIM),c=b.readUInt32LE(z.CENCRC),d=b.readUInt32LE(z.CENSIZ),u=b.readUInt32LE(z.CENLEN),h=b.readUInt16LE(z.CENNAM),x=b.readUInt16LE(z.CENEXT),m=b.readUInt16LE(z.CENCOM),w=b.readUInt16LE(z.CENDSK),v=b.readUInt16LE(z.CENATT),_=b.readUInt32LE(z.CENATX),E=b.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(z.LOCHDR);return b.writeUInt32LE(z.LOCSIG,0),b.writeUInt16LE(e,z.LOCVER),b.writeUInt16LE(r,z.LOCFLG),b.writeUInt16LE(i,z.LOCHOW),b.writeUInt32LE(o,z.LOCTIM),b.writeUInt32LE(c,z.LOCCRC),b.writeUInt32LE(d,z.LOCSIZ),b.writeUInt32LE(u,z.LOCLEN),b.writeUInt16LE(h,z.LOCNAM),b.writeUInt16LE(S.extraLen,z.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(z.CENHDR+h+x+m);return b.writeUInt32LE(z.CENSIG,0),b.writeUInt16LE(t,z.CENVEM),b.writeUInt16LE(e,z.CENVER),b.writeUInt16LE(r,z.CENFLG),b.writeUInt16LE(i,z.CENHOW),b.writeUInt32LE(o,z.CENTIM),b.writeUInt32LE(c,z.CENCRC),b.writeUInt32LE(d,z.CENSIZ),b.writeUInt32LE(u,z.CENLEN),b.writeUInt16LE(h,z.CENNAM),b.writeUInt16LE(x,z.CENEXT),b.writeUInt16LE(m,z.CENCOM),b.writeUInt16LE(w,z.CENDSK),b.writeUInt16LE(v,z.CENATT),b.writeUInt32LE(_,z.CENATX),b.writeUInt32LE(E,z.CENOFF),b},toJSON:function(){let b=function(D){return D+" bytes"};return{made:t,version:e,flags:r,method:pn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(d),size:b(u),fileNameLength:b(h),extraLength:b(x),commentLength:b(m),diskNumStart:w,inAttr:v,attr:_,offset:E,centralHeaderSize:b(z.CENHDR+h+x+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var hu=ae((c2,fu)=>{var mr=gr(),_e=mr.Constants;fu.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return _e.ENDHDR+o},loadFromBinary:function(c){if((c.length!==_e.ENDHDR||c.readUInt32LE(0)!==_e.ENDSIG)&&(c.length<_e.ZIP64HDR||c.readUInt32LE(0)!==_e.ZIP64SIG))throw mr.Errors.INVALID_END();c.readUInt32LE(0)===_e.ENDSIG?(t=c.readUInt16LE(_e.ENDSUB),e=c.readUInt16LE(_e.ENDTOT),r=c.readUInt32LE(_e.ENDSIZ),i=c.readUInt32LE(_e.ENDOFF),o=c.readUInt16LE(_e.ENDCOM)):(t=mr.readBigUInt64LE(c,_e.ZIP64SUB),e=mr.readBigUInt64LE(c,_e.ZIP64TOT),r=mr.readBigUInt64LE(c,_e.ZIP64SIZE),i=mr.readBigUInt64LE(c,_e.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(_e.ENDHDR+o);return c.writeUInt32LE(_e.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,_e.ENDSUB),c.writeUInt16LE(e,_e.ENDTOT),c.writeUInt32LE(r,_e.ENDSIZ),c.writeUInt32LE(i,_e.ENDOFF),c.writeUInt16LE(o,_e.ENDCOM),c.fill(" ",_e.ENDHDR),c},toJSON:function(){let c=function(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ka=ae(Wa=>{Wa.EntryHeader=uu();Wa.MainHeader=hu()});var pu=ae((l2,xu)=>{xu.exports=function(t){var e=fe("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<c.length;x++){var m=c[x];m.copy(u,h),h+=m.length}i&&i(u)}),o.end(t)}}}});var mu=ae((u2,gu)=>{var Gm=+(process.versions?process.versions.node:"").split(".")[0]||0;gu.exports=function(t,e){var r=fe("zlib");let i=Gm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),d=[],u=0;c.on("data",function(h){d.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var m=0;m<d.length;m++){var w=d[m];w.copy(h,x),x+=w.length}o&&o(h)}),c.end(t)}}}});var Eu=ae((f2,bu)=>{"use strict";var{randomFillSync:wu}=fe("crypto"),qm=As(),jm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),yu=(t,e)=>Math.imul(t,e)>>>0,_u=(t,e)=>jm[(t^e)&255]^t>>>8,fi=()=>typeof wu=="function"?wu(Buffer.alloc(12)):fi.node();fi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ks={genSalt:fi};function Ts(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}Ts.prototype.updateKeys=function(t){let e=this.keys;return e[0]=_u(e[0],t),e[1]+=e[0]&255,e[1]=yu(e[1],134775813)+1,e[2]=_u(e[2],e[1]>>>24),t};Ts.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return yu(t,t^1)>>8&255};function Wm(t){let e=new Ts(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function Km(t){let e=new Ts(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let d=e.next();i[o++]=c^d,e.updateKeys(c)}return i}}function $m(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Wm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw qm.WRONG_PASSWORD();return i(t.slice(12))}function Vm(t){Buffer.isBuffer(t)&&t.length>=12?ks.genSalt=function(){return t.slice(0,12)}:t==="node"?ks.genSalt=fi.node:ks.genSalt=fi}function Jm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Km(r),c=ks.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(c,d),o(t,d,12)}bu.exports={decrypt:$m,encrypt:Jm,_salter:Vm}});var vu=ae(Cs=>{Cs.Deflater=pu();Cs.Inflater=mu();Cs.ZipCrypto=Eu()});var Va=ae((x2,Su)=>{var ce=gr(),Zm=Ka(),ve=ce.Constants,$a=vu();Su.exports=function(t,e){var r=new Zm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:ce.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let D={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==ve.LOCSIG||e.readUInt32LE(O)==ve.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==ve.EXTSIG)D.crc=e.readUInt32LE(O+ve.EXTCRC),D.compressedSize=e.readUInt32LE(O+ve.EXTSIZ),D.size=e.readUInt32LE(O+ve.EXTLEN);else if(e.readUInt16LE(O+12)===19280)D.crc=e.readUInt32LE(O+ve.EXTCRC-4),D.compressedSize=e.readUInt32LE(O+ve.EXTSIZ-4),D.size=e.readUInt32LE(O+ve.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==r.compressedSize||D.size!==r.size||D.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==D.crc)return!1}return!0}function E(b,D,O){if(typeof D>"u"&&typeof b=="string"&&(O=b,b=void 0),c)return b&&D&&D(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var F=v();if(F.length===0)return b&&D&&D(F),F;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ce.Errors.INVALID_PASS_PARAM();F=$a.ZipCrypto.decrypt(F,r,O)}var M=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(F.copy(M),_(M))return b&&D&&D(M),M;throw b&&D&&D(M,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var V=new $a.Inflater(F,r.size);if(b)V.inflateAsync(function(K){K.copy(K,0),D&&(_(K)?D(K):D(K,ce.Errors.BAD_CRC()))});else{if(V.inflate(M).copy(M,0),!_(M))throw ce.Errors.BAD_CRC(`"${w.decode(i)}"`);return M}break;default:throw b&&D&&D(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function S(b,D){if((!d||!d.length)&&Buffer.isBuffer(e))return b&&D&&D(v()),v();if(d.length&&!c){var O;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),b&&D&&D(O),O;default:case ce.Constants.DEFLATED:var F=new $a.Deflater(d);if(b)F.deflateAsync(function(V){O=Buffer.alloc(V.length),r.compressedSize=V.length,V.copy(O),D&&D(O)});else{var M=F.deflate();return r.compressedSize=M.length,M}F=null;break}}else if(b&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function I(b,D){return ce.readBigUInt64LE(b,D)}function k(b){try{for(var D=0,O,F,M;D+4<b.length;)O=b.readUInt16LE(D),D+=2,F=b.readUInt16LE(D),D+=2,M=b.slice(D,D+F),D+=F,ve.ID_ZIP64===O&&R(M)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function R(b){var D,O,F,M;b.length>=ve.EF_ZIP64_SCOMP&&(D=I(b,ve.EF_ZIP64_SUNCOMP),r.size===ve.EF_ZIP64_OR_32&&(r.size=D)),b.length>=ve.EF_ZIP64_RHO&&(O=I(b,ve.EF_ZIP64_SCOMP),r.compressedSize===ve.EF_ZIP64_OR_32&&(r.compressedSize=O)),b.length>=ve.EF_ZIP64_DSN&&(F=I(b,ve.EF_ZIP64_RHO),r.offset===ve.EF_ZIP64_OR_32&&(r.offset=F)),b.length>=ve.EF_ZIP64_DSN+4&&(M=b.readUInt32LE(ve.EF_ZIP64_DSN),r.diskNumStart===ve.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,w.encode);var D=i[i.length-1];c=D===47||D===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,k(b)},get comment(){return w.decode(o)},set comment(b){if(o=ce.toBuffer(b,w.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var b=w.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return S(!1,null)},getCompressedDataAsync:function(b){S(!0,b)},setData:function(b){d=ce.toBuffer(b,ce.decoder.encode),!c&&d.length?(r.size=d.length,r.method=ce.Constants.DEFLATED,r.crc=ce.crc32(b),r.changed=!0):r.method=ce.Constants.STORED},getData:function(b){return r.changed?d:E(!1,null,b)},getDataAsync:function(b,D){r.changed?b(d):E(!0,b,D)},set attr(b){r.attr=b},get attr(){return r.attr},set header(b){r.loadFromBinary(b)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var b=r.centralHeaderToBinary(),D=ce.Constants.CENHDR;return i.copy(b,D),D+=i.length,u.copy(b,D),D+=r.extraLength,o.copy(b,D),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=h.length;let D=r.localHeaderToBinary(),O=Buffer.alloc(D.length+i.length+r.extraLocalLength);return D.copy(O,b),b+=D.length,i.copy(O,b),b+=i.length,h.copy(O,b),b+=h.length,O},toJSON:function(){let b=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:b(e),data:b(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ku=ae((p2,Au)=>{var Iu=Va(),Xm=Ka(),$e=gr();Au.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Xm.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:m,decoder:w}=x;t?E(x.readEntries):d=!0;function v(){let I=new Set;for(let k of Object.keys(i)){let R=k.split("/");if(R.pop(),!!R.length)for(let b=0;b<R.length;b++){let D=R.slice(0,b+1).join("/")+"/";I.add(D)}}for(let k of I)if(!(k in i)){let R=new Iu(x);R.entryName=k,R.attr=16,R.temporary=!0,r.push(R),i[R.entryName]=R,h.add(R)}}function _(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/$e.Constants.CENHDR)throw $e.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var I=c.offset,k=0;k<r.length;k++){var R=I,b=new Iu(x,t);b.header=t.slice(R,R+=$e.Constants.CENHDR),b.entryName=t.slice(R,R+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(R,R+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(R,R+b.header.commentLength)),I+=b.header.centralHeaderSize,r[k]=b,i[b.entryName]=b}h.clear(),v()}function E(I){var k=t.length-$e.Constants.ENDHDR,R=Math.max(0,k-65535),b=R,D=t.length,O=-1,F=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(R=0),k;k>=b;k--)if(t[k]===80){if(t.readUInt32LE(k)===$e.Constants.ENDSIG){O=k,F=k,D=k+$e.Constants.ENDHDR,b=k-$e.Constants.END64HDR;continue}if(t.readUInt32LE(k)===$e.Constants.END64SIG){b=R;continue}if(t.readUInt32LE(k)===$e.Constants.ZIP64SIG){O=k,D=k+$e.readBigUInt64LE(t,k+$e.Constants.ZIP64SIZE)+$e.Constants.ZIP64LEAD;break}}if(O==-1)throw $e.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,D)),c.commentLength&&(o=t.slice(F+$e.Constants.ENDHDR)),I&&_()}function S(){r.length>1&&!m&&r.sort((I,k)=>I.entryName.toLowerCase().localeCompare(k.entryName.toLowerCase()))}return{get entries(){return d||_(),r.filter(I=>!h.has(I))},get comment(){return w.decode(o)},set comment(I){o=$e.toBuffer(I,w.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(I){this.entries.forEach(I)},getEntry:function(I){return d||_(),i[I]||null},setEntry:function(I){d||_(),r.push(I),i[I.entryName]=I,c.totalEntries=r.length},deleteFile:function(I,k=!0){d||_();let R=i[I];this.getEntryChildren(R,k).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(I){d||_();let k=i[I],R=r.indexOf(k);R>=0&&(r.splice(R,1),delete i[I],c.totalEntries=r.length)},getEntryChildren:function(I,k=!0){if(d||_(),typeof I=="object")if(I.isDirectory&&k){let R=[],b=I.entryName;for(let D of r)D.entryName.startsWith(b)&&R.push(D);return R}else return[I];return[]},getChildCount:function(I){if(I&&I.isDirectory){let k=this.getEntryChildren(I);return k.includes(I)?k.length-1:k.length}return 0},compressToBuffer:function(){d||_(),S();let I=[],k=[],R=0,b=0;c.size=0,c.offset=0;let D=0;for(let M of this.entries){let V=M.getCompressedData();M.header.offset=b;let K=M.packLocalHeader(),ie=K.length+V.length;b+=ie,I.push(K),I.push(V);let Y=M.packCentralHeader();k.push(Y),c.size+=Y.length,R+=ie+Y.length,D++}R+=c.mainHeaderSize,c.offset=b,c.totalEntries=D,b=0;let O=Buffer.alloc(R);for(let M of I)M.copy(O,b),b+=M.length;for(let M of k)M.copy(O,b),b+=M.length;let F=c.toBinary();return o&&o.copy(F,$e.Constants.ENDHDR),F.copy(O,b),t=O,d=!1,O},toAsyncBuffer:function(I,k,R,b){try{d||_(),S();let D=[],O=[],F=0,M=0,V=0;c.size=0,c.offset=0;let K=function(ie){if(ie.length>0){let Y=ie.shift(),te=Y.entryName+Y.extra.toString();R&&R(te),Y.getCompressedDataAsync(function(oe){b&&b(te),Y.header.offset=M;let P=Y.packLocalHeader(),U=P.length+oe.length;M+=U,D.push(P),D.push(oe);let j=Y.packCentralHeader();O.push(j),c.size+=j.length,F+=U+j.length,V++,K(ie)})}else{F+=c.mainHeaderSize,c.offset=M,c.totalEntries=V,M=0;let Y=Buffer.alloc(F);D.forEach(function(oe){oe.copy(Y,M),M+=oe.length}),O.forEach(function(oe){oe.copy(Y,M),M+=oe.length});let te=c.toBinary();o&&o.copy(te,$e.Constants.ENDHDR),te.copy(Y,M),t=Y,d=!1,I(Y)}};K(Array.from(this.entries))}catch(D){k(D)}}}}});var Ru=ae((g2,Cu)=>{var be=gr(),ye=fe("path"),Ym=Va(),Qm=ku(),Mn=(...t)=>be.findLast(t,e=>typeof e=="boolean"),Tu=(...t)=>be.findLast(t,e=>typeof e=="string"),ew=(...t)=>be.findLast(t,e=>typeof e=="function"),tw={noSort:!1,readEntries:!1,method:be.Constants.NONE,fs:null};Cu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),tw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=be.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new be(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=be.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=be.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw be.Errors.INVALID_FILENAME();let c=new Qm(r,i),{canonical:d,sanitize:u,zipnamefix:h}=be;function x(_){if(_&&c){var E;if(typeof _=="string"&&(E=c.getEntry(ye.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(E=c.getEntry(_.entryName)),E)return E}return null}function m(_){let{join:E,normalize:S,sep:I}=ye.posix;return E(ye.isAbsolute(_)?"/":".",S(I+_.split("\\").join(I)+I))}function w(_){return _ instanceof RegExp?(function(E){return function(S){return E.test(S)}})(_):typeof _!="function"?()=>!0:_}let v=(_,E)=>{let S=E.slice(-1);return S=S===o.sep?o.sep:"",ye.relative(_,E)+S};return{readFile:function(_,E){var S=x(_);return S&&S.getData(E)||null},childCount:function(_){let E=x(_);if(E)return c.getChildCount(E)},readFileAsync:function(_,E){var S=x(_);S?S.getDataAsync(E):E(null,"getEntry failed for:"+_)},readAsText:function(_,E){var S=x(_);if(S){var I=S.getData();if(I&&I.length)return I.toString(E||"utf8")}return""},readAsTextAsync:function(_,E,S){var I=x(_);I?I.getDataAsync(function(k,R){if(R){E(k,R);return}k&&k.length?E(k.toString(S||"utf8")):E("")}):E("")},deleteFile:function(_,E=!0){var S=x(_);S&&c.deleteFile(S.entryName,E)},deleteEntry:function(_){var E=x(_);E&&c.deleteEntry(E.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,E){var S=x(_);S&&(S.comment=E)},getZipEntryComment:function(_){var E=x(_);return E&&E.comment||""},updateFile:function(_,E){var S=x(_);S&&S.setData(E)},addLocalFile:function(_,E,S,I){if(o.fs.existsSync(_)){E=E?m(E):"";let k=ye.win32.basename(ye.win32.normalize(_));E+=S||k;let R=o.fs.statSync(_),b=R.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);R.isDirectory()&&(E+=o.sep),this.addFile(E,b,I,R)}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,E){_=typeof _=="object"?_:{localPath:_};let S=ye.resolve(_.localPath),{comment:I}=_,{zipPath:k,zipName:R}=_,b=this;o.fs.stat(S,function(D,O){if(D)return E(D,!1);k=k?m(k):"";let F=ye.win32.basename(ye.win32.normalize(S));if(k+=R||F,O.isFile())o.fs.readFile(S,function(M,V){return M?E(M,!1):(b.addFile(k,V,I,O),setImmediate(E,void 0,!0))});else if(O.isDirectory())return k+=o.sep,b.addFile(k,Buffer.alloc(0),I,O),setImmediate(E,void 0,!0)})},addLocalFolder:function(_,E,S){if(S=w(S),E=E?m(E):"",_=ye.normalize(_),o.fs.existsSync(_)){let I=o.findFiles(_),k=this;if(I.length)for(let R of I){let b=ye.join(E,v(_,R));S(b)&&k.addLocalFile(R,ye.dirname(b))}}else throw be.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,E,S,I){I=w(I),S=S?m(S):"",_=ye.normalize(_);var k=this;o.fs.open(_,"r",function(R){if(R&&R.code==="ENOENT")E(void 0,be.Errors.FILE_NOT_FOUND(_));else if(R)E(void 0,R);else{var b=o.findFiles(_),D=-1,O=function(){if(D+=1,D<b.length){var F=b[D],M=v(_,F).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),I(M)?o.fs.stat(F,function(V,K){V&&E(void 0,V),K.isFile()?o.fs.readFile(F,function(ie,Y){ie?E(void 0,ie):(k.addFile(S+M,Y,"",K),O())}):(k.addFile(S+M+"/",Buffer.alloc(0),"",K),O())}):process.nextTick(()=>{O()})}else E(!0,void 0)};O()}})},addLocalFolderAsync2:function(_,E){let S=this;_=typeof _=="object"?_:{localPath:_},localPath=ye.resolve(m(_.localPath));let{zipPath:I,filter:k,namefix:R}=_;k instanceof RegExp?k=(function(O){return function(F){return O.test(F)}})(k):typeof k!="function"&&(k=function(){return!0}),I=I?m(I):"",R=="latin1"&&(R=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof R!="function"&&(R=O=>O);let b=O=>ye.join(I,R(v(localPath,O))),D=O=>ye.win32.basename(ye.win32.normalize(R(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?E(void 0,be.Errors.FILE_NOT_FOUND(localPath)):O?E(void 0,O):o.findFilesAsync(localPath,function(F,M){if(F)return E(F);M=M.filter(V=>k(b(V))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(V,K){return function(ie,Y){if(ie||Y===!1)return setImmediate(V,ie,!1);S.addLocalFileAsync({localPath:K,zipPath:ye.dirname(b(K)),zipName:D(K)},V)}},E))})})},addLocalFolderPromise:function(_,E){return new Promise((S,I)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},E),(k,R)=>{k&&I(k),R&&S(this)})})},addFile:function(_,E,S,I){_=h(_);let k=x(_),R=k!=null;R||(k=new Ym(i),k.entryName=_),k.comment=S||"";let b=typeof I=="object"&&I instanceof o.fs.Stats;b&&(k.header.time=I.mtime);var D=k.isDirectory?16:0;let O=k.isDirectory?16384:32768;return b?O|=4095&I.mode:typeof I=="number"?O|=4095&I:O|=k.isDirectory?493:420,D=(D|O<<16)>>>0,k.attr=D,k.setData(E),R||c.setEntry(k),k},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,E,S,I,k,R){I=Mn(!1,I),k=Mn(!1,k),S=Mn(!0,S),R=Tu(k,R);var b=x(_);if(!b)throw be.Errors.NO_ENTRY();var D=d(b.entryName),O=u(E,R&&!b.isDirectory?R:S?D:ye.basename(D));if(b.isDirectory){var F=c.getEntryChildren(b);return F.forEach(function(K){if(K.isDirectory)return;var ie=K.getData();if(!ie)throw be.Errors.CANT_EXTRACT_FILE();var Y=d(K.entryName),te=u(E,S?Y:ye.basename(Y));let oe=k?K.header.fileAttr:void 0;o.writeFileTo(te,ie,I,oe)}),!0}var M=b.getData(c.password);if(!M)throw be.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!I)throw be.Errors.CANT_OVERRIDE();let V=k?_.header.fileAttr:void 0;return o.writeFileTo(O,M,I,V),!0},test:function(_){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var S=c.entries[E].getData(_);if(!S)return!1}catch{return!1}return!0},extractAllTo:function(_,E,S,I){if(S=Mn(!1,S),I=Tu(S,I),E=Mn(!1,E),!c)throw be.Errors.NO_ZIP();c.entries.forEach(function(k){var R=u(_,d(k.entryName));if(k.isDirectory){o.makeDir(R);return}var b=k.getData(I);if(!b)throw be.Errors.CANT_EXTRACT_FILE();let D=S?k.header.fileAttr:void 0;o.writeFileTo(R,b,E,D);try{o.fs.utimesSync(R,k.header.time,k.header.time)}catch{throw be.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,E,S,I){if(I=ew(E,S,I),S=Mn(!1,S),E=Mn(!1,E),!I)return new Promise((O,F)=>{this.extractAllToAsync(_,E,S,function(M){M?F(M):O(this)})});if(!c){I(be.Errors.NO_ZIP());return}_=ye.resolve(_);let k=O=>u(_,ye.normalize(d(O.entryName))),R=(O,F)=>new Error(O+': "'+F+'"'),b=[],D=[];c.entries.forEach(O=>{O.isDirectory?b.push(O):D.push(O)});for(let O of b){let F=k(O),M=S?O.header.fileAttr:void 0;try{o.makeDir(F),M&&o.fs.chmodSync(F,M),o.fs.utimesSync(F,O.header.time,O.header.time)}catch{I(R("Unable to create folder",F))}}D.reverse().reduce(function(O,F){return function(M){if(M)O(M);else{let V=ye.normalize(d(F.entryName)),K=u(_,V);F.getDataAsync(function(ie,Y){if(Y)O(Y);else if(!ie)O(be.Errors.CANT_EXTRACT_FILE());else{let te=S?F.header.fileAttr:void 0;o.writeFileToAsync(K,ie,E,te,function(oe){oe||O(R("Unable to write file",K)),o.fs.utimes(K,F.header.time,F.header.time,function(P){P?O(R("Unable to set times",K)):O()})})}})}}},I)()},writeZip:function(_,E){if(arguments.length===1&&typeof _=="function"&&(E=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var S=c.compressToBuffer();if(S){var I=o.writeFileTo(_,S,!0);typeof E=="function"&&E(I?null:new Error("failed"),"")}}},writeZipPromise:function(_,E){let{overwrite:S,perm:I}=Object.assign({overwrite:!0},E);return new Promise((k,R)=>{!_&&i.filename&&(_=i.filename),_||R("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let D=O=>O?k(O):R("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,S,I,D)},R)})},toBufferPromise:function(){return new Promise((_,E)=>{c.toAsyncBuffer(_,E)})},toBuffer:function(_,E,S,I){return typeof _=="function"?(c.toAsyncBuffer(_,E,S,I),null):c.compressToBuffer()}}}});import{execFile as dy,spawn as ly,spawnSync as Lk}from"node:child_process";import{promisify as uy}from"node:util";function hy(t){if(process.platform!=="win32")return!1;if(Yf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Yf,"").toLowerCase();return fy.has(r)}function Qf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return hy(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function st(t,e=[],r={}){return ly(t,e,Qf(t,r))}function e0(t,e=[],r={}){return xy(t,e,Qf(t,r))}var fy,Yf,xy,Zt=nt(()=>{"use strict";fy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Yf=/\.(cmd|bat|ps1)$/i;xy=uy(dy)});var Qt=ae((SD,jh)=>{"use strict";var Gh=["nodebuffer","arraybuffer","fragments"],qh=typeof Blob<"u";qh&&Gh.push("blob");jh.exports={BINARY_TYPES:Gh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var es=ae((ID,Uo)=>{"use strict";var{EMPTY_BUFFER:vv}=Qt(),Cd=Buffer[Symbol.species];function Sv(t,e){if(t.length===0)return vv;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];r.set(c,i),i+=c.length}return i<e?new Cd(r.buffer,r.byteOffset,i):r}function Wh(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Kh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Iv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Rd(t){if(Rd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Cd(t):ArrayBuffer.isView(t)?e=new Cd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Rd.readOnly=!1),e}Uo.exports={concat:Sv,mask:Wh,toArrayBuffer:Iv,toBuffer:Rd,unmask:Kh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=fe("bufferutil");Uo.exports.mask=function(e,r,i,o,c){c<48?Wh(e,r,i,o,c):t.mask(e,r,i,o,c)},Uo.exports.unmask=function(e,r){e.length<32?Kh(e,r):t.unmask(e,r)}}catch{}});var Jh=ae((AD,Vh)=>{"use strict";var $h=Symbol("kDone"),Dd=Symbol("kRun"),Pd=class{constructor(e){this[$h]=()=>{this.pending--,this[Dd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Dd]()}[Dd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$h])}}};Vh.exports=Pd});var Kr=ae((kD,Qh)=>{"use strict";var ts=fe("zlib"),Zh=es(),Av=Jh(),{kStatusCode:Xh}=Qt(),kv=Buffer[Symbol.species],Tv=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),en=Symbol("total-length"),jr=Symbol("callback"),Dn=Symbol("buffers"),Wr=Symbol("error"),Ho,Od=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ho){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new Av(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[jr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){Ho.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){Ho.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?ts.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=ts.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Go]=this,this._inflate[en]=0,this._inflate[Dn]=[],this._inflate.on("error",Rv),this._inflate.on("data",Yh)}this._inflate[jr]=i,this._inflate.write(e),r&&this._inflate.write(Tv),this._inflate.flush(()=>{let c=this._inflate[Wr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Zh.concat(this._inflate[Dn],this._inflate[en]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[en]=0,this._inflate[Dn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?ts.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=ts.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[en]=0,this._deflate[Dn]=[],this._deflate.on("data",Cv)}this._deflate[jr]=i,this._deflate.write(e),this._deflate.flush(ts.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Zh.concat(this._deflate[Dn],this._deflate[en]);r&&(c=new kv(c.buffer,c.byteOffset,c.length-4)),this._deflate[jr]=null,this._deflate[en]=0,this._deflate[Dn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Qh.exports=Od;function Cv(t){this[Dn].push(t),this[en]+=t.length}function Yh(t){if(this[en]+=t.length,this[Go]._maxPayload<1||this[en]<=this[Go]._maxPayload){this[Dn].push(t);return}this[Wr]=new RangeError("Max payload size exceeded"),this[Wr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Wr][Xh]=1009,this.removeListener("data",Yh),this.reset()}function Rv(t){if(this[Go]._inflate=null,this[Wr]){this[jr](this[Wr]);return}t[Xh]=1007,this[jr](t)}});var $r=ae((TD,qo)=>{"use strict";var{isUtf8:ex}=fe("buffer"),{hasBlob:Dv}=Qt(),Pv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Ov(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ld(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Lv(t){return Dv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}qo.exports={isBlob:Lv,isValidStatusCode:Ov,isValidUTF8:Ld,tokenChars:Pv};if(ex)qo.exports.isValidUTF8=function(t){return t.length<24?Ld(t):ex(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=fe("utf-8-validate");qo.exports.isValidUTF8=function(e){return e.length<32?Ld(e):t(e)}}catch{}});var zd=ae((CD,ax)=>{"use strict";var{Writable:Nv}=fe("stream"),tx=Kr(),{BINARY_TYPES:Mv,EMPTY_BUFFER:nx,kStatusCode:Bv,kWebSocket:Fv}=Qt(),{concat:Nd,toArrayBuffer:zv,unmask:Uv}=es(),{isValidStatusCode:Hv,isValidUTF8:rx}=$r(),jo=Buffer[Symbol.species],xt=0,ix=1,sx=2,ox=3,Md=4,Bd=5,Wo=6,Fd=class extends Nv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Mv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=xt}_write(e,r,i){if(this._opcode===8&&this._state==xt)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new jo(i.buffer,i.byteOffset+e,i.length-e),new jo(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=r.length-e;e>=i.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new jo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case xt:this.getInfo(e);break;case ix:this.getPayloadLength16(e);break;case sx:this.getPayloadLength64(e);break;case ox:this.getMask();break;case Md:this.getData(e);break;case Bd:case Wo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(r[0]&64)===64;if(i&&!this._extensions[tx.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=ix:this._payloadLength===127?this._state=sx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=ox:this._state=Md}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Md}getData(e){let r=nx;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Uv(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Bd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[tx.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(d);return}this._fragments.push(c)}this.dataMessage(r),this._state===xt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=xt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Nd(i,r):this._binaryType==="arraybuffer"?o=zv(Nd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=xt):(this._state=Wo,setImmediate(()=>{this.emit("message",o,!0),this._state=xt,this.startLoop(e)}))}else{let o=Nd(i,r);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===Bd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=xt):(this._state=Wo,setImmediate(()=>{this.emit("message",o,!1),this._state=xt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,nx),this.end();else{let i=e.readUInt16BE(0);if(!Hv(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!rx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=xt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xt):(this._state=Wo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xt,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(d,this.createError),d.code=c,d[Bv]=o,d}};ax.exports=Fd});var Gd=ae((DD,lx)=>{"use strict";var{Duplex:RD}=fe("stream"),{randomFillSync:Gv}=fe("crypto"),cx=Kr(),{EMPTY_BUFFER:qv,kWebSocket:jv,NOOP:Wv}=Qt(),{isBlob:Vr,isValidStatusCode:Kv}=$r(),{mask:dx,toBuffer:Qn}=es(),pt=Symbol("kByteLength"),$v=Buffer.alloc(4),Ko=8*1024,er,Jr=Ko,It=0,Vv=1,Jv=2,Ud=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=It,this.onerror=Wv,this[jv]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||$v,r.generateMask?r.generateMask(i):(Jr===Ko&&(er===void 0&&(er=Buffer.alloc(Ko)),Gv(er,0,Ko),Jr=0),i[0]=er[Jr++],i[1]=er[Jr++],i[2]=er[Jr++],i[3]=er[Jr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[pt]!==void 0?u=r[pt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let h=u;u>=65536?(c+=8,h=127):u>125&&(c+=2,h=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:o?(dx(e,i,x,c,u),[x]):(dx(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=qv;else{if(typeof e!="number"||!Kv(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(r);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string"?c.write(r,2):c.set(r,2)}}let d={[pt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Vr(e)?(o=e.size,c=!1):(e=Qn(e),o=e.length,c=Qn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Vr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Vr(e)?(o=e.size,c=!1):(e=Qn(e),o=e.length,c=Qn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Vr(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==It?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[cx.extensionName],c=r.binary?2:1,d=r.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Vr(e)?(u=e.size,h=!1):(e=Qn(e),u=e.length,h=Qn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),r.fin&&(this._firstFragment=!0);let x={[pt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};Vr(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==It?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[pt],this._state=Jv,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Hd,this,u,o);return}this._bufferedBytes-=i[pt];let d=Qn(c);r?this.dispatch(d,r,i,o):(this._state=It,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(Zv,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[cx.extensionName];this._bufferedBytes+=i[pt],this._state=Vv,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");Hd(this,h,o);return}this._bufferedBytes-=i[pt],this._state=It,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][pt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][pt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};lx.exports=Ud;function Hd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function Zv(t,e,r){Hd(t,e,r),t.onerror(e)}});var yx=ae((PD,_x)=>{"use strict";var{kForOnEventAttribute:ns,kListener:qd}=Qt(),ux=Symbol("kCode"),fx=Symbol("kData"),hx=Symbol("kError"),xx=Symbol("kMessage"),px=Symbol("kReason"),Zr=Symbol("kTarget"),gx=Symbol("kType"),mx=Symbol("kWasClean"),tn=class{constructor(e){this[Zr]=null,this[gx]=e}get target(){return this[Zr]}get type(){return this[gx]}};Object.defineProperty(tn.prototype,"target",{enumerable:!0});Object.defineProperty(tn.prototype,"type",{enumerable:!0});var tr=class extends tn{constructor(e,r={}){super(e),this[ux]=r.code===void 0?0:r.code,this[px]=r.reason===void 0?"":r.reason,this[mx]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[ux]}get reason(){return this[px]}get wasClean(){return this[mx]}};Object.defineProperty(tr.prototype,"code",{enumerable:!0});Object.defineProperty(tr.prototype,"reason",{enumerable:!0});Object.defineProperty(tr.prototype,"wasClean",{enumerable:!0});var Xr=class extends tn{constructor(e,r={}){super(e),this[hx]=r.error===void 0?null:r.error,this[xx]=r.message===void 0?"":r.message}get error(){return this[hx]}get message(){return this[xx]}};Object.defineProperty(Xr.prototype,"error",{enumerable:!0});Object.defineProperty(Xr.prototype,"message",{enumerable:!0});var rs=class extends tn{constructor(e,r={}){super(e),this[fx]=r.data===void 0?null:r.data}get data(){return this[fx]}};Object.defineProperty(rs.prototype,"data",{enumerable:!0});var Xv={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[ns]&&o[qd]===e&&!o[ns])return;let i;if(t==="message")i=function(c,d){let u=new rs("message",{data:d?c:c.toString()});u[Zr]=this,$o(e,this,u)};else if(t==="close")i=function(c,d){let u=new tr("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Zr]=this,$o(e,this,u)};else if(t==="error")i=function(c){let d=new Xr("error",{error:c,message:c.message});d[Zr]=this,$o(e,this,d)};else if(t==="open")i=function(){let c=new tn("open");c[Zr]=this,$o(e,this,c)};else return;i[ns]=!!r[ns],i[qd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[qd]===e&&!r[ns]){this.removeListener(t,r);break}}};_x.exports={CloseEvent:tr,ErrorEvent:Xr,Event:tn,EventTarget:Xv,MessageEvent:rs};function $o(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Vo=ae((OD,bx)=>{"use strict";var{tokenChars:is}=$r();function zt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Yv(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,h=-1,x=-1,m=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(m===-1&&is[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);x===44?(zt(e,_,r),r=Object.create(null)):d=_,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&is[x]===1)h===-1&&(h=w);else if(x===32||x===9)m===-1&&h!==-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w),zt(r,t.slice(h,m),!0),x===44&&(zt(e,d,r),r=Object.create(null),d=void 0),h=m=-1}else if(x===61&&h!==-1&&m===-1)u=t.slice(h,w),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(is[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),o=!1}else if(c)if(is[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)c=!1,m=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)c=!0;else if(m===-1&&is[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))m===-1&&(m=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1&&(m=w);let _=t.slice(h,m);i&&(_=_.replace(/\\/g,""),i=!1),zt(r,u,_),x===44&&(zt(e,d,r),r=Object.create(null),d=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=w);let v=t.slice(h,m);return d===void 0?zt(e,v,r):(u===void 0?zt(r,v,!0):i?zt(r,u,v.replace(/\\/g,"")):zt(r,u,v),zt(e,d,r)),e}function Qv(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bx.exports={format:Qv,parse:Yv}});var Yo=ae((MD,Ox)=>{"use strict";var eS=fe("events"),tS=fe("https"),nS=fe("http"),Sx=fe("net"),rS=fe("tls"),{randomBytes:iS,createHash:sS}=fe("crypto"),{Duplex:LD,Readable:ND}=fe("stream"),{URL:jd}=fe("url"),Pn=Kr(),oS=zd(),aS=Gd(),{isBlob:cS}=$r(),{BINARY_TYPES:Ex,CLOSE_TIMEOUT:dS,EMPTY_BUFFER:Jo,GUID:lS,kForOnEventAttribute:Wd,kListener:uS,kStatusCode:fS,kWebSocket:je,NOOP:Ix}=Qt(),{EventTarget:{addEventListener:hS,removeEventListener:xS}}=yx(),{format:pS,parse:gS}=Vo(),{toBuffer:mS}=es(),Ax=Symbol("kAborted"),Kd=[8,13],nn=["CONNECTING","OPEN","CLOSING","CLOSED"],wS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends eS{constructor(e,r,i){super(),this._binaryType=Ex[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Jo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),kx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ex.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,i){let o=new oS({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new aS(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[je]=this,c[je]=this,e[je]=this,o.on("conclude",bS),o.on("drain",ES),o.on("error",vS),o.on("message",SS),o.on("ping",IS),o.on("pong",AS),c.onerror=kS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Rx),e.on("data",Xo),e.on("end",Dx),e.on("error",Px),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pn.extensionName]&&this._extensions[Pn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Cx(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Jo,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Jo,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Pn.extensionName]||(o.compress=!1),this._sender.send(e||Jo,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){dt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Wd])return e[uS];return null},set(e){for(let r of this.listeners(t))if(r[Wd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Wd]:!0})}})});me.prototype.addEventListener=hS;me.prototype.removeEventListener=xS;Ox.exports=me;function kx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:dS,protocolVersion:Kd[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Kd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Kd.join(", ")})`);let c;if(e instanceof jd)c=e;else try{c=new jd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",h;if(c.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?h="The URL's pathname is empty":c.hash&&(h="The URL contains a fragment identifier"),h){let S=new SyntaxError(h);if(t._redirects===0)throw S;Zo(t,S);return}let x=d?443:80,m=iS(16).toString("base64"),w=d?tS.request:nS.request,v=new Set,_;if(o.createConnection=o.createConnection||(d?yS:_S),o.defaultPort=o.defaultPort||x,o.port=c.port||x,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Pn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=pS({[Pn.extensionName]:_.offer()})),r.length){for(let S of r){if(typeof S!="string"||!wS.test(S)||v.has(S))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(S)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let S=o.path.split(":");o.socketPath=S[0],o.path=S[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let S=i&&i.headers;if(i={...i,headers:{}},S)for(let[I,k]of Object.entries(S))i.headers[I.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let S=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!S||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,S||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=w(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=w(o);o.timeout&&E.on("timeout",()=>{dt(t,E,"Opening handshake has timed out")}),E.on("error",S=>{E===null||E[Ax]||(E=t._req=null,Zo(t,S))}),E.on("response",S=>{let I=S.headers.location,k=S.statusCode;if(I&&o.followRedirects&&k>=300&&k<400){if(++t._redirects>o.maxRedirects){dt(t,E,"Maximum redirects exceeded");return}E.abort();let R;try{R=new jd(I,e)}catch{let D=new SyntaxError(`Invalid URL: ${I}`);Zo(t,D);return}kx(t,R,r,i)}else t.emit("unexpected-response",E,S)||dt(t,E,`Unexpected server response: ${S.statusCode}`)}),E.on("upgrade",(S,I,k)=>{if(t.emit("upgrade",S),t.readyState!==me.CONNECTING)return;E=t._req=null;let R=S.headers.upgrade;if(R===void 0||R.toLowerCase()!=="websocket"){dt(t,I,"Invalid Upgrade header");return}let b=sS("sha1").update(m+lS).digest("base64");if(S.headers["sec-websocket-accept"]!==b){dt(t,I,"Invalid Sec-WebSocket-Accept header");return}let D=S.headers["sec-websocket-protocol"],O;if(D!==void 0?v.size?v.has(D)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":v.size&&(O="Server sent no subprotocol"),O){dt(t,I,O);return}D&&(t._protocol=D);let F=S.headers["sec-websocket-extensions"];if(F!==void 0){if(!_){dt(t,I,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=gS(F)}catch{dt(t,I,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(M);if(V.length!==1||V[0]!==Pn.extensionName){dt(t,I,"Server indicated an extension that was not requested");return}try{_.accept(M[Pn.extensionName])}catch{dt(t,I,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Pn.extensionName]=_}t.setSocket(I,k,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Zo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function _S(t){return t.path=t.socketPath,Sx.connect(t)}function yS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Sx.isIP(t.host)?"":t.host),rS.connect(t)}function dt(t,e,r){t._readyState=me.CLOSING;let i=new Error(r);Error.captureStackTrace(i,dt),e.setHeader?(e[Ax]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function $d(t,e,r){if(e){let i=cS(e)?e.size:mS(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${nn[t.readyState]})`);process.nextTick(r,i)}}function bS(t,e){let r=this[je];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[je]!==void 0&&(r._socket.removeListener("data",Xo),process.nextTick(Tx,r._socket),t===1005?r.close():r.close(t,e))}function ES(){let t=this[je];t.isPaused||t._socket.resume()}function vS(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",Xo),process.nextTick(Tx,e._socket),e.close(t[fS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vx(){this[je].emitClose()}function SS(t,e){this[je].emit("message",t,e)}function IS(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,Ix),e.emit("ping",t)}function AS(t){this[je].emit("pong",t)}function Tx(t){t.resume()}function kS(t){let e=this[je];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,Cx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Cx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Rx(){let t=this[je];if(this.removeListener("close",Rx),this.removeListener("data",Xo),this.removeListener("end",Dx),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vx),t._receiver.on("finish",vx))}function Xo(t){this[je]._receiver.write(t)||this.pause()}function Dx(){let t=this[je];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function Px(){let t=this[je];this.removeListener("error",Px),this.on("error",Ix),t&&(t._readyState=me.CLOSING,this.destroy())}});var Bx=ae((FD,Mx)=>{"use strict";var BD=Yo(),{Duplex:TS}=fe("stream");function Lx(t){t.emit("close")}function CS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Nx(t){this.removeListener("error",Nx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function RS(t,e){let r=!0,i=new TS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,d){let u=!d&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Lx,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(o),process.nextTick(Lx,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,d)});return}t.send(o,d)},i.on("end",CS),i.on("error",Nx),i}Mx.exports=RS});var Vd=ae((zD,Fx)=>{"use strict";var{tokenChars:DS}=$r();function PS(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&DS[d]===1)r===-1&&(r=o);else if(o!==0&&(d===32||d===9))i===-1&&r!==-1&&(i=o);else if(d===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Fx.exports={parse:PS}});var Wx=ae((HD,jx)=>{"use strict";var OS=fe("events"),Qo=fe("http"),{Duplex:UD}=fe("stream"),{createHash:LS}=fe("crypto"),zx=Vo(),nr=Kr(),NS=Vd(),MS=Yo(),{CLOSE_TIMEOUT:BS,GUID:FS,kWebSocket:zS}=Qt(),US=/^[+/0-9A-Za-z]{22}==$/,Ux=0,Hx=1,qx=2,Jd=class extends OS{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:BS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:MS,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Qo.createServer((i,o)=>{let c=Qo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=HS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,d)=>{this.handleUpgrade(o,c,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ux}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ss,this);return}if(e&&this.once("close",e),this._state!==Hx)if(this._state=Hx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ss,this):process.nextTick(ss,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ss(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,o){r.on("error",Gx);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){rr(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){rr(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!US.test(c)){rr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){rr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){os(r,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=NS.parse(h)}catch{rr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&m!==void 0){let v=new nr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=zx.parse(m);_[nr.extensionName]&&(v.accept(_[nr.extensionName]),w[nr.extensionName]=v)}catch{rr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(_,E,S,I)=>{if(!_)return os(r,E||401,S,I);this.completeUpgrade(w,c,x,e,r,i,o)});return}if(!this.options.verifyClient(v))return os(r,401)}this.completeUpgrade(w,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[zS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ux)return os(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${LS("sha1").update(r+FS).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),m._protocol=w)}if(e[nr.extensionName]){let w=e[nr.extensionName].params,v=zx.format({[nr.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",Uh),m.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(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(is,this)})),u(m,o)}};Gh.exports=qd;function b1(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=Hh,t.emit("close")}function Uh(){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",Gx),m.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ss,this)})),u(m,o)}};jx.exports=Jd;function HS(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function ss(t){t._state=qx,t.emit("close")}function Gx(){this.destroy()}function os(t,e,r,i){r=r||Qo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Qo.STATUS_CODES[e]}\r
17
17
  `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+r)}function tr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,tr),t.emit("wsClientError",d,r,e)}else ss(r,i,o,c)}});var np=de(Be=>{"use strict";var M=F;function ta(){let t=["BxnN","Dg9mB3DLCKm","txHRy2e","u3DnCLy","DKLluKS","C3vqyui","ExnLAem","EfvHtwK","zxjYtM8","C3bZteO","y3jLyxrLtwu","D24GCMvHC28","tK9lq0m","ChjVDg90Exa","zxmGCMvHy2G","BNrLCG","vw5PBxbSzw0","zgvMAw5Luhi","rgjzsum","AMTJDKC","x2nSzwfYvgK","ChbL","Bgj5Eue","DxrMofDYAxq","rNjyEfe","DMfSDwu","wxPIEM8","Afz5CuK","EufQvw4","C2vetNq","z0TLzM0","Ahnyu0S","sgP1u2q","x3DHAxq","zw13yKi","Cg9PBNrbBMq","x21PBMLoyxy","tvrWy2i","C2v0zgi","ENv5EKi","vK9xrwC","u3fmy1y","AefJA01LC3m","BeHdALG","rwHmDM8","qw1VDw50","BhrPCgXLihq","sM1YtKy","zNrTA3G","EfvZzuvUDG","rKjXwvq","zxj2AwnL","uNjHD20","DxH4s3K","AKf1Awq","yw9rtu8","tNncALK","DMvYC2LVBMm","BMnKD3i","wu5Zz0O","ywnOzwq","Dxfku1e","AxnbCNjHEq","uLjLvxC","ig1LC3nHz2u","DhjPzxmGCMu","AxnszwfKEq","ExP3C2q","zvvYBa","x2LZsw5PDa","q1P6Eva","q0vAz3y","uMzgtwu","EvngwvK","BxzXzfK","Bw9iyKy","C0jf","B2fJzKe","rKDUyMm","y29Uy2f0","BLfiuvK","DMXOCwq","B3jpBMXPBMu","Dg9cExrLC0i","qwj2tum","rNvQu1a","zeH6AeC","uhnfz1q","r2jjCwm","uxDbq1O","BvLqtKW","BfLZruy","sM9QAfC","uML6v1O","DLf0zM8","B25ozxr3B3i","tLfYuha","x2LZqNjVD3m","qKHLseq","yLf3wwq","Cg9PBNrdB24","whLtDvy","ufr1wwG","t2PrtMu","x2jPBMfYEvq","EwfvrwO","Bg9Nsurhzw4","DgHLBG","vg55D3G","CYbHBhjLywq","DfzhELO","x2LZtwLUAvC","Dw50","A0rnEwG","AvfStvi","Cgf5Bg9Hza","zgjUENK","se9LqMK","EwXRsxa","y29UBMvJDfm","B2zMBgLUzq","qNvYEfm","Eunsy3e","Cgf5Bg9Hzfq","yuLYBhy","DgHHBIbSB2m","BNruCMLLC0m","x2LZv29YA2u","z2vjBMzVu3K","BMv4DcGPigm","Cfr3qxm","x3DZ","rLHZvve","C3zzrg0","CgPyAgK","uu93EhK","r1jjwe8","EMrpAw8","DK5TrxC","C2vYDMLJzs0","ywXSB2nvBNm","Ahv3u0O","BM9Uzv9UB24","y3nTB2i","tMfTzq","BML0AwfSAxO","u2nrtK8","zM9YrwfJAa","wNPHsvy","CIb0DhDjra","v0H2BwG","AeLyt2i","C2rcDhm","sNbKDu8","zvD0AwG","z2zgsfO","BLHUtuq","vMLvy0m","s2vLu0O","DKzgrg0","r1DNq3m","CxPOswu","v01otKq","AvbwsuW","ww1WELq","zcbLCNjVCI4","qNjPzgDL","CgLUz09Uy2u","CfDyswS","zgjjsNG","A3DvDhq","tMjHAuy","r0n0tvG","q3vZDg9Trxi","CK1MugS","Bg9N","r2r4DxG","quXfs1C","zgvIDwC","u3PWCwm","AgLNAa","zeLgywG","rg9XueK","u2vYDMLJzvC","n3W0Fdb8nG","AevYCM9Yrxy","qMnOreK","C2v0y3vYC28","yw5kwu4","t2zxBhq","DvLrq3C","vu5cr1u","EuXIAgK","AxmGDw5Kzwy","vejNs2K","vNrcru8","yNbeu0W","B3jRig9MzMW","uKnfC3e","DMPosgi","tKjMrfO","DMLduhi","C0LouxC","yMLUyxj5vhK","q09oveLovuu","Ce5IAha","EKjgyNe","x3bYzwzPEa","zfbVrxi","ze5VzhO","s0XhC0m","CMvHzfvjBNq","EwvrExq","B25dBg9Zzq","q1bdvKK","zxf1ywXZ","EgXvyMS","tef5sgS","y2XVC2uSihC","EMDrC20","x3bHDgHlzxK","DMvYC2LVBG","yLzmzvC","r0HlwgS","zxjHDg9Y","CLreyxm","BwvKAwf0zwW","zw96uw8","CeD3zLG","Axnby2TdBgu","AvnMs0W","yw5kEei","y2zvzMe","CNnVCL9Uyw0","x2rLyNvN","Cw1gBNa","BfLvv2G","Dgz5ALO","t1bjyxq","q1Dut3y","uNnAsvC","r0jHs2i","DLnArK8","zgvJB2rLzey","vvfZyM4","DNzQwhy","B3P3uu8","ChjVy2vZCW","EMnzvgW","CgLUz1rPBwu","t2XOsNC","sKnlC1i","x2rItMfTzq","ruf0EKC","AM9PBG","sNfWzeu","x2HHBMrSzu8","wNL6u2S","AwX2B0q","yw1LoIa","yxnZAwDU","C1nzCuS","we1IBgq","t3bLBKv2zw4","uvrKzeG","nxWWFdn8mxW","ywjVCNq","whvIthC","y2HLy2Tszwe","tgr5rui","ywzL","y2rqB2m","Ew5JswO","CM92AwrLihy","DhPXuNO","AgvHzgvYCW","tgzKrvi","yMfvzKW","DcbVzIbYyw4","q0jgtwm","ALnYvKC","t0z2vvm","y29Kzq","BgLTAxq","y1fXzxO","x2n1CNnVCK0","tMj3zvq","BMv3vMvYC2K","Dxrjza","rK9yuKq","CMvQzwn0","tgX0CfK","C2DPza","EvjLy29UBMu","Aw1LCYbPBIa","teDIug8","ywDLu2HVDW","v2PbwLK","CNzJqLy","t2nlDeS","u0fRBxC","DhjQrMu","EfDVEe4","zLLpzwO","DLL4u0K","nhWXFdn8mNW","D2vI","sfzLrxG","yxGGCMv0CMK","x2LUAxrhBg8","x25HDMLNyxq","CNLrqMO","refNrwu","B2LUDfjLywm","y2HnyxHdB3u","weH4wfy","q29Kzq","zwnVBM5Ly3q","EwTPs3C","BfrUueO","zg5hzKS","m3WWFdf8nxW","rMfACMW","oda0mdqXDvj1u2Hw","ihzHBgLKihm","AwXLtMfTzq","AwX5B0y","AwDHDg9Yt24","CK5UreC","CMvZB2X2zq","CMvWBgfJzq","y2XVC2u","qvv5Eha","uejhBwK","u3rTtxm","C2v0","y3zsANm","y0H4Cvu","z0rtugm","BNv0tfK","r29hzxi","CgLKEMu","yufWz0y","wK9kreK","x2LZtwLUAvq","BwvZC2fNztO","zMXAD3m","C3rYAw5N","CMvZzxrfBMq","AM5qEgm","zMLArK0","x29UugfNzu4","x2DLDeLUDgu","BeXrDMu","EhrMAKK","EvPxwe8","x29UtwvZC2e","DxbKyxrLq3u","ugnzC0W","EM9Ls28","DhjrDgC","B25szwnLAxy","D0HLBwS","q0Xpu0ve","vNzKDeO","vu9uBee","vvDjq0q","wMHmAwi","nhWXFdv8mNW","AeHQr0e","DgrkChC","BLLWC1q","B3bLBIa","BNPvDMK","vKTQBhC","tLj3Dg4","r01KELe","B25Uzwn0Aw4","EeXzt1m","zgnQwNq","yMLUyxj5","BwvZC2fNzv8","icSG","BMvY","uu1Sugq","v3vjuwS","A2v0ignVBNm","x2nYzwf0zvm","Aw47y2HHCNm","sMj5txm","uLbmD0q","C2v0q3vYC28","ufvZv1C","zNjVBuHHC2G","y21KzvO","A1HTEvK","ihrVihjLDhi","zMLUza","zw5HyMXLvhi","tfbov0y","EuzsuK8","ChvZAa","wMjksgy","zhfnv24","B25JBg9Zzq","BMrWB2LUDfq","zKT2Aue","rK1Wq0m","x3jLywr5q2W","qLv6ELe","CgLUz0XVC3m","CLDrCve","CvfHBxu","AMnvtva","u3n2sxu","Bvzbvuy","C1rUzvy","r3vxBwm","qNvWvhe","s2DfBvO","Cu1lA3e","wejMsfy","yMLUza","ywX3yxLZ","B3beq0S","rKXRBKW","AvjQuLu","A1bMvhC","uuvkCNq","DgLLCKPtt04","teT3ue8","s010sMe","y3jLyxrLt3a","x2LUAxq","igzPzwXKoIa","qNfYAue","qwvSzNm","B0rUzMS","r2XgA2S","B0rzBeG","rNfmEwq","s2jezg4","AvrIALO","BxnNsuq","uMvJB25Uzwm","CgzMEuS","D0rgv2C","qvvXyKm","y2vZC0HHBMq","zw50","B2veuKi","yMfJA3vWigu","Fdz8m3WXmxW","wNjtA2K","A3PhCha","CMvWBgfJzui","x2LUAxrqCM8","y29UBMvJDeu","CLzHBhvLCW","B1DTy0u","AxnmB25N","u1zcz0G","DgLTzw91DcW","r0fpD0u","Ec1TC2CTy3u","Dg9VigXHCMC","C3vIyxjYyxK","ywnRpwzYB24","zKPxBKm","DePXDuK","C3vIC3rYAw4","BMnVzgLUzW","DMvUDa","C0XPC3rLBMu","v2vIu29JA2u","u0Lxzxi","u3Dttwu","uMLZB0u","yM9L","Auz3Ehi","vfveywS","t1bftG","DhnwENy","uMnLEMi","zunqteG","s1DKsui","yw94rhm","ihbYB3rVy28","ENfwA3O","DxLIDNO","ww1Kuwy","vgvrDxa","zu11CMq","AK9Nu0i","yw5ZzM9YBvq","A2v5","veLID0u","qvjKsue","B25pCgvU","y29TCgXLDgu","BwfW","qLbmwg8","vhjHz3m","Aw9Ul2PZB24","BKHUvfO","zNjVBuj5Dgu","zcWGDw5RBM8","DfLjtMq","vg1hy2O","vu9Tt2W","q1fOAKu","zw5NDgG","x3fVC0rc","BNrbBMrvCgq","CNnVCKzPBgu","AxnAzxjV","CeHlsgK","zKPVDKu","uLryt2W","BLbZvwy","z2jVuMu","CMvUDevUzha","mxWWFdr8m3W","CfbTr3y","z3LYEwW","ywr4Cgm","v3bVBhC","v0HcBg8","CuDkB1u","r25WvfG","DeLK","vu5eA1O","sNnJs2u","rMLADxq","ruTtrgu","CMvZDwX0","rxjYB3jdB2q","z2v0sxrLBq","AevbweO","BKfLufu","v2zOueu","zxjYtxnN","Bhr4Cvq","ywnRx2nVzgu","AfL0Avi","zxjFBxnNAwq","DeHRCuu","s3Lmzvu","wKDwC2m","y09NuKu","x3vYBa","BMrLEa","C2nYAxb0","vLDTC2O","BMnLq2XVC2u","vfnRzfm","Dw5RBM93BIa","x3nLCuLK","zwn0","z2DzCNG","EKHvEMy","CgLUz0LUDgu","vMPRANy","qKTeAKe","zuXQwhi","Dg9tDhjPBMC","sxrMA1a","wxnYrfy","DNDSCuS","z3rjueO","q1bnvMG","A0DvAMK","yw5Nzq","B2nMDKG","t0vLDNK","vgvmyKC","CeHcq28","y29UDgLUDwu","AgfZ","Bfz2DLq","DwPPD1i","DgfYz2v0","t1Hmv1u","CMvHC29U","yMfSrxzLBNq","vgfN","t0r4v20","r25lBgi","Aw50zwDLCIa","B25VCgvU","rxP3sgC","yw1L","A1PMv2m","A2LxvfG","CMvKDwnL","B3v0sLO","vxbKyxrLq28","AwrI","t3zIsgS","v2H1CKe","AgvKtwf4uMu","DhbizwfKzxi","z01cvNa","DMfqEvi","ExbL","vgfTuvG","u2TLzKW","yxrLq291BNq","x2HHBMrSzvi","x3bPBMDqB24","ALrKtw8","sNzzr0i","B3jLtMfTzxm","CKXrC0i","r0XLDvG","tuvtu0fhrv8","C2vYDMLJzq","z0TUEw8","tM9Zs0O","D0HbEe8","y2uGBM90igK","AM9nvue","AxnrB1nnzxm","DxjS","Chfozgu","B0nzAxK","y2j0quS","AKP2BwS","vhHgzeq","zgH4quK","Eg5QsK8","C2XPy2u","CffJExe","r0ryzee","BuTAELi","CxDKBfK","BMrWB2LUDca","ywXPzcb1CMW","DLnfreS","vgLTzw91Da","BMfTzq","y3vYC29Yx2y","zxH0zw5ZAw8","vMLnzwm","ANzoD0G","q2vRrNu","wgP5DMu","EhbyExy","tLvrsMC","CM51q3u","BfbrBxK","CK9is0G","yMfSu2nVCgu","B3Pzy2e","CNnVCL92ywW","y2Xdwhe","r1fZBKe","yxKSig5LDhC","vg5gzuS","EuTvquW","CMvTB3zLrxy","CgfNzwHPzgu","A3Pgs2y","B3nLrxzLBNq","BvPst0W","C2HPzNq","C0XJzuC","CMfTugfYyw0","A2nusLK","CuXRsuu","wfn0vM0","vLvXzKK","ywrK","B3PUzKG","thvzuKy","ywXty29Wzq","vwfYsxa","BwnmtNG","B2nRzxrgywK","zufJAW","v0P4AMK","zxHWB3j0CW","FdD8m3WX","tMvKs0G","zw50zwqGDhK","uLzQDva","zMLSzw5HBwu","u2TPCcbWyxm","C3fqse8","EfnvC3C","B0XKyuq","u2z2Bw8","y29UBMvJDa","B0zLzvy","vKDstee","B2vuCee","x2nSzwfYugK","yNLL","B3zbDhK","t0viuLy","surNtge","uMvHzcbWyxm","z3vvwM8","mJmYwK5rEe53","CK1Qswi","z2v0s2v5","B2XKvMvYC2K","EuvuuwO","zxrxB3jRq2G","Dw15v0C","Cg5ss0O","ruf1rNG","shbkENO","CNfNvKS","C3vJy2vZCW","EM1Sr1a","y3r4","z2v0u3rVCMe","Bwu6ia","DefJrKW","BM93","ywWGy3vYC28","qKnduvy","re1Ps0O","z2LPDgi","r21cs3m","v0L1AwO","EK9Jq0i","B25fCNjVCG","uxvLDwu","l3DZl3yY","rw1js1G","BMvLzf9Hy2S","ELPqvMu","ntyZmM5ntLrPta","BfLpDuK","B25TzxnZywC","x29Ut3bLBG","zNjVBNrPzxi","uKXMu1a","zhv1zhq","qKHJyNq","tNrjC0y","y2Ldy28","tgn2CKy","v3LKreG","Dg9hzw5LCMe","u3vPueS","zMLQrve","C3rHCNq","vLb4weu","ANbbB08","Bg9IywXty28","y2f0y2G","q0XfCxG","v0fowgu","zNzmweW","tu5Nt08","y3jLyxrLq2W","nhWWFdf8mNW","q2rNyu8","vwLJveO","A0TqA2i","EhHfDvq","AxnFywnR","A25Uz0u","Bw5eDuC","yxnL","tg9NsurozxC","Aw5KzxHpzG","ihrYEsbYzwm","wLzZwLu","ntKYzxfHCM9q","ANHvt1y","nZmZndyXD2Dttw1b","BNrfBMrWB2K","vMv2Aeu","EwTLtgO","B3bLCNr5tMe","zxjev2W","BfrPBwvVDxq","BgLZDgvUtMu","ihjLy29UBMu","ELz0Eue","B0nHCeq","y29UBMvJDca","aaaaaaaaaaa","AwjYvhy","C2fNzq","DhvOt3q","Cu93Dee","zLfKDg8","BwfUDwfSihi","vLrdrK0","yNHVrfm","s3nrzvC","vgzfEMi","tNnXEeu","zgjhqve","x19LC01Vzhu","wLHmCwW","D0Dlzfi","zw5fDMvUDa","q1rJvu8","yw5Hz2vY","zhzyuhe","wgXfvKy","qMDVwgi","DxDeyMq","yu9kAgy","twvZC2fNzuu","ChDcC2m","v05WzLK","wwTove0","qxLgue0","CMvJB25Uzwm","tg9Nsuq","y3vYDMfSDwu","BM5Ly3q","C0Xf","Ag1psxK","sLjVvLi","qM13BwG","CMv0CNLdB3u","Ef9MCM9UDgK","DMfuDLy","AxHVvMu","u0DAr0S","AwXK","rNjVBNrPzxi","refRDwe","De9jvwq","x2XPC3rLBMu","DMfS","Devms04","uNH2zhy","D3r3wfK","AgfUz2u","wMLAq3q","yMrFzgLK","qNvrq3m","t3LHwfq","AhLgCui","BgvY","Dev2zw50","rxLrCMW","q0jgzfa","C1H3wu0","CKHUsuu","C3bSAxq","tK5tzvy","ufv1tvO","EM1jDKS","q3vWELm","vgfNvwq","yvnXvKG","qNzRCKm","r2rdy24","Ae9Wzw5fDMu","ihn1y2nLC3m","BwLUAvbYB2C","B3bLCNr5","qujSDvK","z2vY","zMLSDgvY","B25nzxnZywC","v0Pfywi","tgLwq0u","Cgu6ia","y3ruAw1LB3u","v1LRvhi","CuLNwLy","sMHrC0e","BNvTyMvY","Dgv4Dc9Qyxy","sM9LBxe","A3HWA24","tg9KzwO","Auv4rwG","EhP3ExG","u053A0q","CM92AwrLigi","yLDJr2m","vgTZEMG","BwD3B1y","qw9wCw4","y3vYC29Yx24","Bwf4tg9ZC0m","v2LUzg93","CwXSDM8","nhWXFdL8nxW","y2HHCKnVzgu","sfjsCvy","x2DLBMvYyxq","sfnxrgK","yMf0A08","yMH1v08","DxPdEMq","ALrsA1e","Cg9W","DLPwqvy","yKPWAgS","AhHutgm","y3jLyxrLrwW","zMX1C2HfEha","DxLWBxK","EgfOBLy","rgL2C08","uLjpuG","vwHTuK0","x0rctMfTzq","D3jPDgu","z2Ppwuq","Fdj8nxW4Fda","y2HLy2TdDxi","Aw5KzxG","A1n0yxr1C0m","zMXQrg4","zvDhCK0","sNDYreG","y3vYCMvUDeu","zMroDem","ywDLsgLKzq","r3jxu2e","ywrKrxzLBNq","DhjHBNnHy3q","Bun6wfO","zv9ZDwnJzxm","q1PgtNq","x2n1CNnVCKy","t2jjzgK","q3vZDg9Tq2W","ChfisxC","qw1KCxi","zMXVB3i","zNjVBunOyxi","x3jLy29UBMu","y3vYCMvUDeK","BgnwsuO","twLZC2LUzYa","AMXNB0m","uuPhD1C","x29Uq2XVC2u","DfHPufe","AMTyDgi","ywDL","zNjHBwvuExa","EKfdsNC","tu9qt2e","yNn2u08","ywXSzwqGBxu","D01Yyu8","yKzSEfi","s0fNyvu","zenJue4","B1zXBeu","qxDSv2i","zKPtruO","DMLVANa","wvb2yxq","BMXKC3O","x29UrxjYB3i","B25LCNjVCG","qwrIzNq","B3vUDa","rwPpshm","BMzequm","uLfsAuO","uxPXuvC","rLjptLrjrvi","rLDt","A3fcCg8","EKrgBge","CM9YrxzLBNq","CYbWyxjHBxm","Dw5ZAwDUzwq","DKDouNy","D0LTAgy","D2fZq2XLyw4","ihrPBwvVDxq","DgvZDa","zKriD1m","CMfUzg9T","wxjMuxa","veHcsfO","zgv2AwnLx2K","nhWWFdn8mxW","CMvHzhLtDge","sfnwuM8","DMfSDwvZ","t2vfthG","zgnHy1K","AKfhAgm","yw1Lu3bHy2u","id4G","yxrHlcbKyxq","DMDQqvC","CgfNzxnOB3C","B3jgr0i","yNL0zu9MzNm","BvbZtK0","u0Hvrwq","y1Ljvfu","y291BNq","DhjPzxm","AMTtruW","zKz2z3e","z01ZENm","yxv0B21HDgK","zMHArey","wur3t08","C2zpsNC","CNrot1y","C3rLBMvYCW","sfnStu0","yMziqLi","B21jA0O","nxWX","Dgv4Dc9WBge","qNburMm","yxnJCMLWDa","BKTzDuK","zKXyEfG","vLPhBNK","zwDoD0O","tLroEg0","whzzsgC","z0r6rvm","BMCGzMfPBgu","EuDqugu","qvHbsvm","BwLZzq","veLjAem","ELjirKy","DgfIyxnL","wwjeuKO","DhL5A3u","sgfWBwq","r2feEgm","D2jfvM4","B2nRzxq","s01SwK4","zNDZxZeUmc4","t2zhvM4","x2vUzhbVAw4","t1bftL9fuLi","DNv0DuW","q09otKvdveK","Bg9cqxK","vfDHt0O","sxvnELy","qun4ugK","CgLUz19VBMm","DgTwzKi","BwLUzW","tgLZDgvUzxi","t0fwAhO","C3v6Chm","AwDHBuu","mNW0Fdn8mhW","rKjYzvy","sMHVqw8","EKHhyxC","CgfYC2u","zhz3vwW","ign1CNnVCIa","vhDzqxK","A1n0ugW","u0LrsfC","Dhntq04","y2XVC2veqG","zfDVCMTLCKC","r1j4wg0","EKDTAg8","ELjozve","BuzHveK","DeDsCgi","ndeWngTmr2HdEq","t2rnzMq","DwzQqwu","D3HeDxC","D0rHt3a","v1PJsxy","yxv0BW","ugDIz0q","zgf0yq","D0zUuhu","uMvzrxK","CM92AwrLihC","vxf4uLe","CMvHzhDYAxq","zMLN","AwHzqNq","zeXRuNO","BNvpuNm","tM5MtNu","qvDRtxK","C0nVDw50zxi","C2vUDa","BMDLza","Bwv0Ag9K","C1D0q2K","tLHhywy","vwXPthO","wKPoBwe","CMfTzq","BwvZ","tg9JAW","BMvJDa","DhLWzq","r1fSyLK","DvHesK0","B25tDgfYDfi","zw1LBNq","B2zM","C2vUzf9Hy2S","DK9IC1m","Au55z1y","ufLwChq","vw1LsLq","zNvUy3rPB24","DMrHAxK","DMTZsge","wMLKD0S","y3H5sNG","ugXdyK0","De5pv3O","ALDbufy","CgLHANu","rwvYywi","CMvXDwLYzwq","BKfoyuq","tfDmsem","x3bYB3rVy28","ywr2yw5Jzq","Bfzbz3y","tvPWzNO","zNjVBujPDhm","C2nrzva","AxvNv3m","mNW0","otu0nJuYt0T3A2Tf","z1rPBwvVDxq","BgLUzw5V","C3rVCMu","wNfiree","z2v0q3vYCMu","vgjXyK8","tLrUtwm","v1ffDva","zvHitMu","Ae1LC3nHz2u","zMfPuMq","tKfAy24","t1rxwNG","AKnOv0e","sxfWAvq","zxjFywnRx20","wxL3DK8","Aw9MEg0","BwvZC2fNzq","DMfbDKm","reT5z2O","AhDXyw8","uLnyEMm","wNPewKW","C3rVCcbPBw0","zw5JB2rLrNi","AuTizvG","sMPqEw0","wenmEMC","swrduu4","ALLqBwe","x2nVBM5Ly3q","sgjYALC","BefYtvO","AhL4Auq","D2LSBfjLy28","yvfiseK","Bw5lzNa","De1HBMfNzxi","oduYwxDvzuP4","DMLJzuLeig8","rxzLBNq","vwjtu3a","AwP5vK0","qMTWrMC","DLrlEwi","zgvS","zM9Yy2u","qMXNv2S","rxz2reW","q2zltg4","qvnAreu","z2vtEw5J","uLLqAvK","AuX6DfC","rKLmrv9ot1q","zwHKr0G","zu1rAuu","Bw16vKC","Cg93","q29UzMLN","v1Hpq3u","Dg9Y","t1nerNC","sLbNyvq","vePRvxK","zxf6ENu","Aw9UvgLTzw8","vgHgDxe","AwfTC3u","zM1VwMe","B2fK","x2zVCM1HDeu","BxvNs2W","v0ntt2G","BhLkCLe","BLHIrwK","B2fgBgC","ExfLvLy","yuXZD0y","vLzTEMC","x2fKzfDZtgK","zw5KCg9PBNq","tw9KDwXL","thn5Axm","DgLUzYbZzxi","Aw5JBhvKzxm","C3nHz2vfDMu","yNL0zxm","Dg9oDw1Izxi","sKfosMO","uhvYC08","x3jLBw92zvC","CgjICdi","zxjYB3i","A0XTEKW","y3vYC29YlNm","yxbWBhK","twP0uM0","ELb4shi","re1Ku0e","DMDkBKy","wKnhzeK","v1Djrgi","z1rwDwq","y3vYC29Y","r05vy3O","zwDXzgy","EeDwt0K","C29YDa","C0Pcz24","u0nQD20","r0rxuei","y0HvAgK","whLlsuC","sgz3rg8","s2PsCuG","Dg9cExrLC0W","y3jLyxrLuMu","x2rYB3bhBg8","oda4DMrHELjq","uwLwu3K","ywrKq291BNq","wfnLAui","uvPyAgO","wevlqxy","q2DYugC","C1jltLa","ufn4q0K","zNn3uLq","zxjFDhrS","z2v0qwXSs2u","CMnTBKm","CMXhzhm","vgTut2W","BgvUz3rO","x3nLBMrby2S","r29OCeO","CMvZzxrdB3u","CMvJzxzPzwq","y3nTv0K","q0Xpu0LorW","ugLTt0W","yKj2DNu","t0rNtKe","BeHHBMrSzxi","wNP1sve","Bhm6ia","D3blzgu","rvP3r1y","Ahr0Chm6","DcbSAw1PDa","vhvuqKe","AeLmteq","BMDuAw1LCG","zMzmAw5L","AxLSzLq","CMLLC0nVDw4","rK15EKe","ywnRtxnNswq","x2n1CNnVCK4","rvDpu2q","CMXouNq","yKnfA3a","CM92AwrLige","A1vHv2S","EMXzAgq","uK1Awey","A2v5CW","wKnvwgO","rxL3vfq","AuXJwfm","zxH0ugf5Bg8","AwPbBM4","Cgf5Bg9Hzeu","DufwBMq","AuDHy3C","B1nnDwi","ChrVCG","C2fyAeu","sMPrC0m","nhWY","BujoyKq","zw1PDa","zcWG","vNPhyxy","yw10A0y","t3ziBNO","A1jXzxO","DxbNCMfKzw4","zw5JB2rPBMC","AfjAs1u","AgnKy1m","EevbrNe","uw5AA1O","nxWWFdf8m3W","u1jyCLe","x2LUDgvYDMe","CNfuD0e","y2XLyxi","Awfhu2W","vgXprue","ndmZmffKuevbza","DxbkDKW","BNbmruq","s3j3zhi","x3bPBMDmB3m","AM5rBLO","vxzQsKC","AunWwwO","yKLHrKW","CKzND0W","t0fkD3u","AeTNDwq","ExbTDNa","r01IuKi","yLfnCvm","tKrvz0i","C2v0sxrLBq","yNvMuuS","igzHAwWSig0","x2HHBMrSzva","Cw1xzwS","svPwvKG","tfbSzhG","yMXVy2TLza","C3HPwge","tM1LDhG","q0Xbtfi","su5tvefova","BuvtDei","BvnUsfC","sg9MEhC","EuT4r3m","y2vuBKi","EuvMDMq","yxKSihrYEsa","zw5HyMXLuw8","yuLQv0K","zu1qAKm","BLzeANu","rKHTzhK","zwvKzwq","mdaWmdaWmda","qLDmBLm","vfPwvxi","u2XNwg8","lcbxzwjtB2m","t29drfy","B3jRzxjhBg8","v3rUug8","tKfusvzfx0u","zwfitvy","sLnptLa","mhWZ","y3jLyxrLrxi","vKLSsMK","y29SBM8","B3bLBG","DhjPBq","CxLtCKS","tvnUvvK","BLv6wfi","CeDXAva","tuLpEe8","wffvBMu","C2v0u3rVCMe","yxDUqvC","BgXhsgO","AenKEM8","Eg5hDfm","zwrPyxrLBhK","Dg9iyxnO","C2vYDMvYvgK","DeLUDgvYy2u","B2zMC2v0","Dhj1y3rVCIa","x2rLC3rYB3K","x29UvgLTzw8","EuXLz24","Aw5KzxGGB3u","CLfpCuW","y2fSBa","BwvY","BhjUvuC","ywjcyLq","wuXsq0S","zffxtgm","ywnRDxbfBMq","yM1NuvK","q291BNq","reiGzMfPBgu","mxWYFdv8m3W","zLHkA2K","C25nC2m","x2rPC2nVBM4","B3bLBKrc","AxjLza","zv90Aw1LB3u","qxz2wMS","DvvXwhu","Dg9cExrLCW","uxDvD3a","nhW2Fdi","x21LC3nHz2u","rvjst1i","Ae1uq1a","wuHysuW","yNvMzMvYzwq","uffts08","Cfvjue8","vg1ls3O","y29UC3rYDwm","x29WDgLVBNm","B2DTEfm","C3rYAw5NAwy","zgLZCgf0y2G","ELLwtKK","CKrYww4","qvDQChC","yM9KEq","uNjAzM8","uujOqLa","Aw5PDcbrB1m","DxnLCKLW","ANr1u3O","CMvTB3zLq2G","rezTB2m","z2v0","DM5Az1i","tgTLqKW","Bfbcz2e","uLDetg4","suvtx0vsuK8","CMTjDva","B3nLza","zsbHihn0CMK","ChjVDg9JB2W","AwXSihvZzsa","quXm","s2LKB0u","BIWGAg9ZDg4","sLnLuu0","uwTvr2e","Bvz0vxO","B2XcBKS","y09Wzw4","t0zXD2G","DMvY","B2nRzxrtDwm","tMPirvG","seDPqxK","tKnMv2q","AenSB3nLrxy","AunhA3u","z2v0qwXS","yNrAu2W","qwPrAeG","uMDcDNe","mdaWma","s2vzEwW","Bg93","Aw5L","tK92tvy","uKzQvxK","x3DZsw5ZDge","C29Tzq","z1z5se0","CgXLyxnLiha","Dgv4DfbHEwW","Au9nEhq","CKrey1e","yNL0zuXLBMC","mxW0Fdb8mNW","CMDsA2u","B25SAw5L","tufyx1jfvfi","rvHyEKS","Bwf4uMv0CMK","zgrjrcWGzgu","t1zxuu4","B2jQzwn0u3q","BKrtChi","v3rNyKu","Aw9U","u21jC3a","Efrurw52","q3zdDwy","zw50tgLZDgu","AxrNDvG","AxnrB1nby2S","B25tDg9Wsw0","y2HnyxHuCMK","zgjIBKK","CNzHBfzHBhu","vLrUsKS","x3bPBMC","qu9jBgS","sMnxyuy","m3W1","zNrOA00","ugHoyMq","vvDVBM8","wgXlzhy","rgrduwu","z29PBMCGyxC","q0PYEhO","t2PgvM8","Cw9Zx18","rwH4sNi","Ee1uCwG","zgXLuMu","y29UBMvJDgK","EKrutLa","sNbgEgC","vufKyu4","pxv0zI04","qLLeCwW","A1POBge","zxLRru4","y3vZDg9Tshq","BK5Mvwq","sKjnwvG","rxDUwxm","rhPvswi","AwXLx25HBwu","u2T1y3O","BgLUzq","vw5Oyw5KBgu","quHowM4","yxbWBgLJyxq","C0rpsuK","uejIthi","CKTTwgq","qLn3De8","ENjjveK","DgLTzw91Da","yNvMzMvY","BwvRqNK","B1jOwge","x2rPC3bHDgm","BwP5t28","uMDxr1O","s093Dhy","CfLdB28","CMvZzxruCMK","uKDJtgC","EKnlELG","ywDLrxzLBNq","AMvJDfn0B3i","z0jYEuO","zg9Uzq","u1LrBNm","x3nVy2TLDa","zLnJzwy","D3jPDgvvAw4","CerpyKu","nJuWnxDeCxbdva","vwDRCgK","thzIC1m","v2vPEgLUsLm","rvPQvu8","ELvKBui","C2vUza","t2jQzwn0","Dhr3Awq","tLHJswq","svPZtLK","zNjVBu51Bwi","DhDVCMTdAge","sLPTwvi","z2v0q3vYC28","EKHqu3C","venUAgW","ysbTDxn0igi","wg5MAMq","qNLywKy","CKvdEvm","s2rxA0i","CKvnrem","AvnRCfG","zxq9DxrMltG","DxrVuMvJB24","txPKwfi","BKXPBMu","x2TLEvbHDgG","B25mAw5L","lcbTyxGGCMu","CNjVCK1LC3m","B2DtDui","C3jJ","CMvHzg9UBhK","BhHpAuu","C09qwNy","qMf5AKO","tfLltxu","B0vjruu","Aw5Lza","zNvYs20","yM9KEK0","CMfNzvn5BMm","CKvpCu0","Dw5KzwzPBMu","rxvXzvu","z3bVy2u","B1vdEui","ufjrDgu","CezMAKG","z0jyDxi","Chv0","rfDIq3u","ywXSq3vYC28","AePYzfq","yMPtB3C","x1fVu01HBMe","q0H2Bvi"];return ta=function(){return t},ta()}(function(t,e){let r=F,i=t();for(;;)try{if(parseInt(r(1255))/1*(parseInt(r(765))/2)+parseInt(r(767))/3+-parseInt(r(1134))/4+-parseInt(r(1592))/5*(parseInt(r(1174))/6)+-parseInt(r(316))/7+-parseInt(r(696))/8*(-parseInt(r(1070))/9)+parseInt(r(1337))/10*(parseInt(r(727))/11)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ta,180307);var C1=Object[M(1668)+M(854)],P1=Object["getOwnPr"+M(771)+M(1099)],Xh=(t,e)=>function(){return t&&(e=(0,t[P1(t)[0]])(t=0)),e},R1=(t,e)=>{let r=M,i={hwqao:function(c,d,u,x){return c(d,u,x)}};for(var o in e)i[r(1156)](C1,t,o,{get:e[o],enumerable:!0})};function D1(){return Kh||(Kh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function O1(){let t=M;return $h||($h=[IDBCursor[t(1664)+"e"][t(1127)],IDBCursor[t(1664)+"e"][t(570)],IDBCursor[t(1664)+"e"][t(570)+"PrimaryKey"]])}function L1(t){let e=M,r={iylfT:e(707),KbDdn:e(1229),YbDRJ:function(o,c){return o!==c},LltpY:"LkSak",BlNyd:"Lzcgl",trQtg:function(o,c){return o(c)},JhKPu:function(o,c){return o===c},vaPyR:e(364)},i=new Promise((o,c)=>{let d=e,u={WZcIv:function(x,h){return r[F(1028)](x,h)},bJphk:r[d(284)],jJvmk:r.BlNyd,tdJpw:function(x,h){return r[d(353)](x,h)},iGacw:function(x,h){return x(h)}};if(r.JhKPu(d(1699),r[d(596)]))this.on(_0x573076,_0x493746);else{let x=()=>{let w=d;t[w(653)+w(1523)+w(376)](r[w(1291)],h),t[w(653)+w(1523)+w(376)](r[w(434)],m)},h=()=>{let w=d;if(u[w(1075)](u[w(894)],u[w(620)]))o(u[w(363)](zt,t.result)),x();else return _0x4b19e7?.[w(390)](I=>I[w(488)]===_0x541597)?.[w(1676)]},m=()=>{let w=d;u[w(1311)](c,t[w(1229)]),x()};t[d(917)+d(1048)](r.iylfT,h),t["addEvent"+d(1048)](d(1229),m)}});return i[e(1758)](o=>{let c=e;o instanceof IDBCursor&&Wd[c(328)](o,t)})[e(746)](()=>{}),ra[e(328)](i,t),i}function F(t,e){t=t-207;let r=ta(),i=r[t];if(F.sIiVUS===void 0){var o=function(x){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let I=0,b,S,A=0;S=x.charAt(A++);~S&&(b=I%4?b*64+S:S,I++%4)?m+=String.fromCharCode(255&b>>(-2*I&6)):0)S=h.indexOf(S);for(let I=0,b=m.length;I<b;I++)w+="%"+("00"+m.charCodeAt(I).toString(16)).slice(-2);return decodeURIComponent(w)};F.ePcqBW=o,F.nGhNCL={},F.sIiVUS=!0}let c=r[0],d=t+c,u=F.nGhNCL[d];return u?i=u:(i=F.ePcqBW(i),F.nGhNCL[d]=i),i}function N1(t){let e=M,r={dbnzy:function(o){return o()},jChWA:e(1444),UNDkZ:"AbortError",HobBL:function(o,c){return o===c},pGqiP:"mtkuX",PxtuM:e(492),OFvUS:e(1229)};if(na[e(571)](t))return;let i=new Promise((o,c)=>{let d=e,u={fAXrI:d(1229),FMpCC:"abort",jlgoC:function(x,h){return x!==h},UmeJT:r[d(1148)],yKUAL:d(1569),DxZhA:function(x,h){return x(h)},adxpc:r[d(524)],itguX:function(x){return x()}};if(r.HobBL(d(1205),r[d(1398)]))return!0;{let x=()=>{let w=d;t[w(653)+"entListe"+w(376)]("complete",h),t[w(653)+w(1523)+w(376)](u.fAXrI,m),t[w(653)+w(1523)+"ner"](u[w(400)],m)},h=()=>{r[d(1767)](o),r.dbnzy(x)},m=()=>{let w=d;u[w(933)](u[w(1112)],u[w(652)])?(u.DxZhA(c,t[w(1229)]||new DOMException(u.adxpc,u[w(518)])),u[w(1524)](x)):_0x4e585b.exports=_0x41581e[w(322)]()[w(1758)](()=>(_0x4f8e04(),_0x4560c7))[w(1758)](function(I){return I})};t[d(917)+d(1048)](r.PxtuM,h),t["addEvent"+d(1048)](r[d(274)],m),t[d(917)+"Listener"](d(259),m)}});na[e(328)](t,i)}function M1(t){ia={RWDLn:function(i,o){return i(o)}}[M(1467)](t,ia)}function B1(t){let e=M,r={OEHRV:function(i,o){return i(o)},QnyPS:function(i,o){return i===o},flZws:e(1516)+"oreNames",WMNND:function(i){return i()}};return r.QnyPS(t,IDBDatabase[e(1664)+"e"][e(918)+e(1519)])&&!(r[e(339)]in IDBTransaction[e(1664)+"e"])?function(i,...o){let c=e,d=t[c(1417)](r[c(692)](os,this),i,...o);return jd.set(d,i[c(1244)]?i.sort():[i]),r[c(692)](zt,d)}:r[e(1813)](O1)[e(1221)](t)?function(...i){let o=e;return t.apply(os(this),i),r[o(692)](zt,Wd.get(this))}:function(...i){let o=e;return zt(t.apply(r[o(692)](os,this),i))}}function F1(t){let e=M,r={qIgZV:function(i,o){return i(o)},VVmzg:function(i){return i()}};return typeof t===e(1113)?B1(t):(t instanceof IDBTransaction&&r[e(864)](N1,t),Zh(t,r[e(1215)](D1))?new Proxy(t,ia):t)}function zt(t){let e=M,r={uUkid:function(o,c){return o instanceof c},zUdmB:function(o,c){return o(c)},WJxji:function(o,c){return o(c)},bBvvu:function(o,c){return o!==c}};if(r.uUkid(t,IDBRequest))return r[e(1597)](L1,t);if(Qo[e(571)](t))return Qo[e(1463)](t);let i=r[e(673)](F1,t);return r[e(1278)](i,t)&&(Qo[e(328)](t,i),ra[e(328)](i,t)),i}var Zh,Kh,$h,Wd,na,jd,Qo,ra,ia,os,Vh=Xh({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={CHvmR:function(r,i){return r&i},yLegn:function(r,i){return r>>>i},xahnV:function(r,i){return r&i},SCpZu:function(r,i){return r>>>i},uXDJM:function(r,i){return r&i},ViMec:function(r,i){return r>>>i},OywOT:function(r,i){return r>>>i},zHGaw:function(r,i){return r(i)},Wpolw:function(r,i){return r===i},oMkfN:"xGHfy",eaHMV:function(r,i){return r instanceof i},DMiKJ:t(1e3),wHAxO:t(500),YmpzT:function(r,i){return r===i},AXAIS:t(1586),lPQmy:function(r,i){return r===i},sINQw:t(1137),hCdzo:function(r,i){return r(i)},ZzaIV:function(r,i){return r<i},gfFHZ:function(r,i){return r<<i},kkMDd:function(r,i){return r instanceof i},TkTOl:function(r,i){return r!==i},mnDuG:t(1850),BUzzQ:function(r,i){return r in i}};Zh=(r,i)=>i[t(1501)](o=>r instanceof o),Wd=new WeakMap,na=new WeakMap,jd=new WeakMap,Qo=new WeakMap,ra=new WeakMap,ia={get(r,i,o){let c=t,d={uZMRq:function(u,x){return e[F(1055)](u,x)}};if(e[c(519)](e.oMkfN,e.oMkfN)){if(e[c(1387)](r,IDBTransaction)){if(e[c(519)](e[c(716)],e[c(612)]))return d.uZMRq(_0x5c284d,_0x589689);if(e[c(1815)](i,e.AXAIS))return na.get(r);if(e[c(1815)](i,c(1516)+c(605)))return r[c(1516)+"oreNames"]||jd[c(1463)](r);if(e[c(643)](i,e[c(1853)]))return o[c(1516)+"oreNames"][1]?void 0:o.objectStore(o[c(1516)+c(605)][0])}return e[c(1404)](zt,r[i])}else{let u=this[c(1831)],x=this[c(1496)];return[255&x,e[c(1650)](e[c(1414)](x,8),255),e[c(899)](e.SCpZu(x,16),255),e.yLegn(x,24),e[c(1104)](255,u),e[c(899)](e[c(636)](u,8),255),e[c(899)](u>>>16,255),e.OywOT(u,24)]}},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;if(e.kkMDd(r,IDBTransaction)&&(i===e[o(1023)]||i===o(1137)))if(e[o(1269)](e[o(759)],e[o(759)]))_0x13086b=_0x480f5d(_0x5e4f25),e[o(1799)](_0x282dac,32)&&(_0x9b1a47|=e[o(1806)](e[o(899)](127,_0x499283),_0x4c1be2)),_0x41b953+=7;else return!0;return e[o(402)](i,r)}},os=r=>ra[t(1463)](r)}}),Qh={};R1(Qh,{deleteDB:()=>U1,openDB:()=>z1,unwrap:()=>os,wrap:()=>zt});function z1(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=M,u={Rxvdv:function(m,w,I,b,S){return m(w,I,b,S)},sdBts:function(m,w){return m(w)},IAeWI:"close",GLeuX:d(1708)+"hange",FMyzA:function(m,w){return m(w)},hYtiR:function(m,w){return m===w},wHemk:d(1324)+"eeded",gBryJ:d(1360)},x=indexedDB[d(1393)](t,e),h=u[d(1293)](zt,x);return i&&(u[d(537)]("iaGSl",d(1335))?x["addEvent"+d(1048)](u[d(355)],m=>{let w=d;u.Rxvdv(i,u[w(1803)](zt,x.result),m[w(699)+"on"],m[w(280)+"on"],zt(x[w(918)+w(1519)]))}):u[d(828)](_0x4dfe68,u[d(1803)](_0x3aed1a,_0x18c410[d(528)]),_0x1f0bea[d(699)+"on"],_0x78e07a[d(280)+"on"],u[d(1803)](_0x31614d,_0x4c353b[d(918)+d(1519)]))),r&&x[d(917)+d(1048)](u[d(1585)],()=>r()),h[d(1758)](m=>{let w=d;c&&m["addEvent"+w(1048)](u.IAeWI,()=>c()),o&&m[w(917)+w(1048)](u[w(607)],()=>o())})[d(746)](()=>{}),h}function U1(t,{blocked:e}={}){let r=M,i={zayZN:r(1360),IZsNY:function(c,d){return c(d)}},o=indexedDB["deleteDa"+r(1027)](t);return e&&o[r(917)+r(1048)](i.zayZN,()=>e()),i[r(1602)](zt,o).then(()=>{})}function Yh(t,e){let r=M,i={TfEzb:function(x,h){return x===h},zPxHr:function(x,h){return x===h},zHUzf:function(x,h){return x+h},hXpXN:r(1083)+"e",hVqAE:function(x,h){return x instanceof h},BHcbt:r(340),llGHj:function(x,h){return x!==h},EvvDL:function(x,h){return x in h},ZCUXj:function(x,h){return x!==h},vwlqK:r(250)};if(!(i.hVqAE(t,IDBDatabase)&&!(e in t)&&typeof e===i[r(734)]))return;if(ea[r(1463)](e))return ea[r(1463)](e);let o=e[r(323)](/FromIndex$/,""),c=i[r(1403)](e,o),d=tp[r(1221)](o);if(!i[r(1184)](o,(c?IDBIndex:IDBObjectStore)[r(1664)+"e"])||!(d||ep.includes(o)))return i[r(1304)](i[r(561)],i[r(561)])?i[r(789)](-1,this[r(1496)])&&i[r(1234)](-1,this[r(1831)])?_0x124c12[r(1130)](0,0,this[r(968)]):i.zPxHr(-1,this[r(1496)])?_0x533346[r(1130)](0,i[r(553)](this[r(1831)],1),this[r(968)]):_0x2dbf30[r(1130)](this[r(1496)]+1,this.high,this[r(968)]):void 0;let u=async function(x,...h){let m=r,w=this[m(918)+"ion"](x,d?i.hXpXN:m(1626)),I=w.store;return c&&(I=I[m(908)](h[m(658)]())),(await Promise.all([I[o](...h),d&&w[m(1586)]]))[0]};return ea[r(328)](e,u),u}var ep,tp,ea,H1=Xh({"node_modules/idb/build/index.js"(){let t=M,e={ylkIp:t(1644),buWIR:"delete",CBFMc:t(1334),bxoDS:function(o,c){return o(c)},bWcGc:function(o){return o()},Vjkjv:t(1463),OjFVo:t(698),qyttd:t(1490),yZWXO:t(1266)+"ys",fKviA:t(996)},r=(t(361)+t(1389))[t(842)]("|"),i=0;for(;;){switch(r[i++]){case"0":ea=new Map;continue;case"1":Vh();continue;case"2":tp=[e[t(1769)],t(665),e.buWIR,e[t(272)]];continue;case"3":e[t(787)](M1,o=>({...o,get:(c,d,u)=>Yh(c,d)||o[t(1463)](c,d,u),has:(c,d)=>!!Yh(c,d)||o[t(571)](c,d)}));continue;case"4":e[t(875)](Vh);continue;case"5":ep=[e[t(555)],e[t(1542)],e.qyttd,e[t(348)],e[t(399)]];continue}break}}}),G1={idb:function(t){let e=M;t[e(674)]=Promise[e(322)]().then(()=>(H1(),Qh))[e(1758)](function(r){return r})}},Jh={};function Ft(t){let e=M,r={rECyS:"2|0|3|1|4",nutLY:function(u,x){return u!==x}},i=r[e(1612)].split("|"),o=0;for(;;){switch(i[o++]){case"0":if(r[e(332)](void 0,c))return c.exports;continue;case"1":G1[t](d,d.exports,Ft);continue;case"2":var c=Jh[t];continue;case"3":var d=Jh[t]={exports:{}};continue;case"4":return d.exports}break}}Ft.d=(t,e)=>{let r=F;for(var i in e)Ft.o(e,i)&&!Ft.o(t,i)&&Object[r(1668)+r(854)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Ft.o=(e,r)=>Object[t(1664)+"e"].hasOwnProperty[t(1417)](e,r)})(),(()=>{let t=M,e={vWUbw:function(r,i){return r!=i},WuIQk:t(1637)+"d",gboRe:t(1218),iQlMR:t(792)+"le"};Ft.r=r=>{let i=t;e.vWUbw(e[i(378)],typeof Symbol)&&Symbol[i(558)+i(578)]&&Object[i(1668)+i(854)](r,Symbol.toStringTag,{value:e[i(513)]}),Object[i(1668)+i(854)](r,e[i(1765)],{value:!0})}})();var Re={};(()=>{let t=M,e={OXLWU:function(a,n){return a(n)},qySrK:function(a,n){return a+n},ZzDZL:function(a,n){return a+n},ZidwK:function(a,n){return a+n},sDOII:function(a,n){return a*n},GaDxc:function(a,n){return a+n},yGPPe:function(a,n){return a(n)},mekBy:function(a,n,s){return a(n,s)},nQHQY:function(a,n){return a===n},CuTaE:"aBoKb",KunFh:t(410),OVWQN:function(a,n){return a+n},FROXY:function(a,n){return a(n)},rTDas:function(a,n){return a+n},kGUji:function(a,n){return a(n)},MNgOO:t(1494),cfUfa:"ffff",trjFe:function(a,n){return a(n)},CPCVI:"0000000000000000"+t(1378)+t(1378),dCcPN:function(a,n){return a!==n},vaAvC:t(567),amtkF:function(a,n){return a>n},XStVm:function(a,n){return a<n},uwDbd:function(a,n){return a<n},ViUcC:function(a,n){return a-n},DWbCu:function(a,n){return a-n},KMIFM:function(a,n){return a<n},IdCQN:function(a,n){return a<n},OdMfd:"ruGJw",jnQnZ:t(1379),NQrPp:function(a,n){return a!==n},EuqeU:function(a,n,s){return a(n,s)},bsvSO:function(a,n,s){return a(n,s)},WNpfY:function(a,n){return a(n)},OSDFw:function(a,n){return a>>>n},FawFp:function(a,n,s){return a(n,s)},UbSSp:function(a,n){return a(n)},qMKkq:function(a,n){return a(n)},nzUvi:function(a,n,s){return a(n,s)},pqNde:function(a,n){return a&n},aApgF:t(932)+t(1123)+t(427)+t(1676),zACJw:function(a){return a()},suPaB:function(a,n,s){return a(n,s)},zCKzX:function(a,n){return a>n},GohpJ:t(680)+t(1286),TagUd:t(556),NBfDZ:function(a,n){return a!==n},wtwXY:function(a,n,s){return a(n,s)},JhoAo:function(a,n,s){return a(n,s)},CtIsf:function(a,n,s){return a(n,s)},pTwAs:function(a,n){return a!==n},EWOSd:function(a,n){return a(n)},ujiwR:function(a,n,s){return a(n,s)},zYVNI:function(a,n,s){return a(n,s)},VPxXE:function(a,n,s){return a(n,s)},nKYuI:function(a,n,s){return a(n,s)},furKm:function(a,n){return a!==n},Sbokt:function(a,n,s){return a(n,s)},OyaXT:function(a,n,s){return a(n,s)},TuTBA:function(a,n){return a!==n},LGbPo:function(a,n,s){return a(n,s)},GHKXk:function(a,n,s){return a(n,s)},ilvoD:function(a,n){return a===n},ryQBj:function(a,n){return a(n)},dbGAQ:function(a,n){return a(n)},nNfUd:function(a,n){return a>>>n},kzGpp:function(a,n,s){return a(n,s)},PqWkM:function(a,n,s){return a(n,s)},opDCK:function(a,n){return a(n)},GrWSa:function(a,n,s){return a(n,s)},OKHva:t(932)+t(1123)+t(427)+t(809),FLknL:function(a,n){return a===n},ogSuB:t(932)+t(1123)+t(427)+t(1093),gpoce:function(a,n){return a(n)},rtNOV:function(a,n){return a+n},NnfNu:function(a,n){return a&n},mgwoV:function(a,n){return a(n)},ACxPi:function(a,n,s){return a(n,s)},stDln:t(1667)+t(677)+t(861),vYxSI:function(a,n){return a>>n},FrXxQ:"close",hIXOb:function(a,n){return a+n},rMfPk:function(a,n){return a>n},ncdwr:t(1510),RLfSP:t(1771),Xnfjd:"pagehide",VWmsj:t(990),AyFPM:t(777),QwUwp:function(a,n){return a+n},BGFIl:t(694)+t(1286),dvwUl:function(a,n){return a>=n},wFnPu:function(a,n){return a+n},zmlGP:function(a,n){return a-n},nAePU:function(a,n){return a<<n},qzhIe:function(a,n){return a<n},bjSow:function(a,n){return a<n},QpFKf:function(a,n,s){return a(n,s)},ibrTv:function(a,n){return a<n},xMTqh:function(a,n){return a===n},TCnhl:function(a,n){return a&n},GCtMX:function(a,n){return a(n)},PBbLr:function(a,n){return a+n},ogmxS:function(a,n){return a+n},ABluY:function(a,n){return a<<n},KyLeU:function(a,n){return a&n},zHPSw:function(a,n){return a==n},LkeBL:function(a,n){return a+n},rDJEd:function(a,n){return a+n},FOXRD:function(a,n){return a!==n},jYPma:function(a,n){return a&n},WtgbE:function(a,n){return a|n},vSZFO:function(a,n){return a===n},kRqez:t(585),mvqdY:t(1326),VUqfI:function(a,n){return a|n},kKPkb:function(a,n){return a&n},iamsu:function(a,n){return a&n},lbyyA:function(a,n){return a&n},oacfA:function(a,n){return a+n},LpvtK:function(a,n){return a+n},zuyzB:function(a,n){return a+n},mZROL:function(a,n){return a!==n},oeTpA:function(a,n){return a&n},RReUw:function(a,n){return a|n},NOKCC:function(a,n){return a<<n},oUCyB:function(a,n){return a|n},ZVsZU:function(a,n){return a&n},MOPOa:function(a,n){return a<<n},SmIsp:function(a,n){return a&n},TlOEA:function(a,n){return a<<n},EhLvo:function(a,n){return a<n},SIWer:function(a,n){return a>n},bfHBR:function(a,n,s){return a(n,s)},mCzXZ:function(a,n){return a>>n},gDSPc:function(a,n){return a+n},JANJj:function(a,n){return a>>>n},pPmGv:function(a,n){return a*n},LKwPO:function(a,n,s){return a(n,s)},UhmRM:"lMYey",Lodej:function(a,n){return a<n},rvcBV:function(a,n){return a>=n},SwMrV:function(a,n){return a-n},RQRiJ:function(a,n){return a+n},BkpFg:function(a,n){return a<<n},StmMs:function(a,n){return a<n},MIOxO:function(a,n){return a<=n},vGNRv:function(a,n){return a<<n},XubLw:function(a,n){return a!==n},WANXe:t(248),spsLJ:"irYAa",fJWnC:function(a,n){return a|n},FujSP:function(a,n){return a&n},QJGwW:function(a,n){return a<n},abBbT:function(a,n){return a&n},bodzM:function(a,n){return a|n},iCpYj:function(a,n){return a&n},vgjAW:function(a,n){return a>>n},PsEgT:function(a,n){return a<n},sqPHO:function(a,n,s){return a(n,s)},PcYsL:function(a,n){return a(n)},dqMWn:function(a,n){return a&n},orFGB:t(1857),VvdtJ:function(a,n){return a(n)},NUQJg:function(a,n){return a(n)},nDSpr:function(a,n){return a(n)},ySFYY:function(a,n){return a(n)},JpduO:function(a,n){return a===n},ozwQO:t(814),dHzhG:function(a,n){return a(n)},pQsuK:function(a,n){return a&n},tAcFL:function(a,n){return a&n},TTGeC:function(a,n){return a&n},kZhla:function(a,n){return a!==n},bVLeW:"ZWDbY",CupzS:function(a,n){return a&n},RMZXF:function(a,n){return a&n},GoGer:function(a,n){return a&n},CnJQN:function(a,n){return a<<n},VevhE:function(a,n){return a&n},lHCjX:function(a,n){return a!==n},NNSeV:t(1380),TIbwE:function(a,n){return a(n)},NosKJ:function(a,n){return a<<n},hGQNI:function(a,n){return a&n},yCRcq:function(a,n){return a|n},OjQNe:function(a,n){return a>>>n},vUCCH:function(a,n){return a>>>n},EzwHg:function(a,n){return a===n},FHmdy:function(a,n){return a<n},sSYqK:function(a,n){return a<n},Szpqc:function(a,n){return a<n},pFfjH:function(a,n){return a|n},fJSEJ:function(a,n){return a+n},kxpkn:function(a,n){return a!==n},WYkTr:function(a,n){return a|n},SkefL:function(a,n){return a>>>n},BHeHD:function(a,n){return a>>>n},QzqQW:function(a,n){return a&n},XlEVF:function(a,n){return a>>>n},BgoXb:function(a,n){return a&n},dNodz:function(a,n){return a+n},OAVhz:function(a,n){return a+n},EXXzK:function(a,n){return a>>>n},zDTNP:function(a,n){return a>>>n},nfDAC:function(a,n){return a|n},mjyOo:function(a,n){return a>>>n},ZqXuI:function(a,n){return a&n},mKZzR:function(a,n){return a(n)},GnpTX:function(a,n){return a|n},YPvat:function(a,n){return a===n},RPLwD:function(a,n){return a===n},ocfvH:"jIFtE",iExEh:t(435),oSMub:function(a,n){return a<<n},GQlbY:function(a,n){return a|n},batkO:function(a,n){return a|n},yKxGs:function(a,n){return a<<n},GBaKb:t(1849),CEZgv:function(a,n){return a|n},Trags:function(a,n){return a|n},fQdto:function(a,n){return a<<n},ykeLj:function(a,n){return a<<n},LPNWF:function(a,n){return a|n},YrhAW:function(a,n){return a|n},iKHeX:function(a,n){return a<<n},KOwtv:function(a,n){return a|n},oEIEE:function(a,n){return a>>>n},uYQCw:function(a,n){return a>>>n},tOIUd:function(a,n){return a>>>n},zZPVe:function(a,n){return a>>>n},CQhjE:function(a,n){return a|n},ItfkP:function(a,n){return a/n},oPwuA:function(a,n){return a!==n},ggYrx:t(1856),jvNwH:t(1564),sRKNP:function(a,n){return a+n},UarIp:function(a,n){return a*n},ijAnn:function(a,n){return a>>>n},iDXVN:function(a,n){return a>>>n},PUuMZ:function(a,n){return a===n},HOeBi:function(a,n){return a&n},bCEkp:function(a,n){return a>>>n},oFeeV:function(a,n){return a&n},aQHHI:function(a,n){return a>>>n},EmIKX:function(a,n){return a>>>n},dVfxC:function(a,n){return a+n},eWtih:function(a,n){return a<<n},mYPNL:function(a,n){return a>>>n},oLdaD:function(a,n){return a===n},LvbsS:function(a,n){return a===n},tkVfB:function(a,n,s,l){return a(n,s,l)},HfwDo:t(431),omIkJ:function(a,n){return a+n},sWtCi:function(a,n){return a+n},nVDju:function(a,n){return a===n},yzwsd:t(736),AOIlk:t(752)+t(1534),EKSDe:"CONNECTING_ERROR",yEfvd:t(1511)+t(1468)+"R",Aelfs:t(608)+t(1440),anJYN:t(1038)+"OR",eCPLH:"NATIVE_E"+t(901),xGVOI:function(a,n){return a!==n},KgEww:"oGder",cHUhi:function(a,n){return a&n},DMdSA:function(a,n){return a>>>n},dwYRd:function(a,n){return a>>>n},zqVkz:function(a,n){return a&n},oDnfk:function(a,n){return a>>>n},bFlxR:function(a,n){return a>>>n},AbvMC:t(649),wGKdR:function(a,n){return a>>>n},aSqVH:function(a,n){return a>>>n},EyQrl:function(a,n){return a&n},Rrawm:function(a,n){return a>>>n},hsXSK:function(a,n){return a&n},PAsne:function(a,n){return a>>>n},PTuYh:function(a,n){return a+n},XOwsn:function(a,n){return a*n},NXGaf:t(687),ODxWm:t(314)+t(1438),wldEb:t(298)+"0",zVtyA:function(a,n){return a!==n},OoGJH:t(1820),GWgCs:t(923),WWIDb:function(a,n){return a===n},xWoxN:function(a,n){return a>n},iofxm:t(416),eykEN:t(1076),BchDI:function(a,n){return a===n},oVqlE:t(315),Krwdr:t(319),rlNRt:t(1229),HSWDi:function(a,n){return a instanceof n},XBfHV:function(a,n){return a+n},VZGny:t(1563)+t(1816),FBqYT:function(a,n){return a+n},awnAW:function(a,n){return a!==n},YGesZ:function(a,n){return a>>>n},dcjZt:function(a,n){return a===n},KeeSJ:t(1489),sJBgn:t(1454),BurxS:t(1393),WQEuP:function(a,n,s){return a(n,s)},dleRe:function(a,n){return a instanceof n},eWGrM:function(a,n){return a||n},WXOCu:function(a,n){return a||n},NsBjY:function(a,n){return a!=n},NtmLC:"1|3|0|4|2",viCPr:"undefined",KGYhy:function(a,n){return a!==n},FXsUQ:"Qkksn",RFjUy:function(a,n){return a<n},XHxXV:function(a,n){return a!==n},tDDQb:t(1363),HSlMM:"ofOKN",xEAFq:function(a,n){return a===n},dQWLc:function(a,n){return a&n},CvCuf:function(a,n){return a===n},fFvgq:t(1003),OPIat:function(a,n){return a<n},XSeiB:function(a,n,s){return a(n,s)},QEJrt:function(a,n){return a!==n},hyFqB:t(956),EAuFx:function(a,n){return a>=n},oeDRB:function(a,n){return a<n},Nmetx:function(a,n){return a<<n},HkJSx:function(a,n){return a&n},opTfO:function(a,n){return a>=n},xbSEA:function(a,n){return a<n},gjNAb:function(a,n){return a&n},iLztW:function(a,n){return a&n},uARTM:function(a,n){return a-n},sTneV:function(a,n){return a|n},xnjJO:function(a,n){return a|n},dhxAI:function(a,n){return a&n},SVBgH:function(a,n){return a<<n},NXcId:function(a,n){return a&n},EwnYs:function(a,n,s,l,f){return a(n,s,l,f)},UWICD:"upgraden"+t(1377),zRHFF:function(a,n){return a<n},rKmXd:function(a,n){return a|n},knngE:function(a,n){return a&n},iLcXS:function(a,n){return a===n},uxxKy:"OtwzV",fJovE:t(921),SJKuD:t(1330)+t(1316),KMlZN:function(a,n){return a&n},BuQCs:function(a,n){return a+n},kXmyY:function(a,n){return a+n},AUqbC:function(a,n){return a<<n},WHvmh:function(a,n){return a|n},MQNzI:function(a,n){return a&n},kPfTw:function(a,n){return a>>n},QiVSy:function(a,n){return a|n},vZVAV:function(a,n){return a&n},WHBlo:t(340),FBreV:t(1121),lVAgv:t(1565)+t(496),KidoE:function(a,n){return a(n)},JwrDH:t(471),zdOio:function(a,n,s){return a(n,s)},VTnJK:function(a,n,s,l){return a(n,s,l)},PUsWW:function(a,n){return a+n},rlGds:t(1163),IDgLa:function(a,n){return a>=n},loBAy:t(549)+t(576),QTddH:function(a,n){return a<<n},eBxXC:function(a,n){return a&n},NjHEX:function(a,n){return a===n},WydDH:t(1424),sxiXa:t(867)+t(1013),UvjJG:"http",PlCbM:"&jscallb"+t(460)+t(422)+"P",XyKIG:t(1859),YrfQp:function(a,n){return a!==n},ehdGH:t(1482),NedKH:t(590),pGwfX:function(a,n){return a!==n},QGZtS:"Adfgh",BPLXo:function(a,n){return a===n},XKcFx:t(798),eMPjC:function(a,n){return a!==n},kStPl:function(a,n){return a|n},KsQeW:function(a,n,s){return a(n,s)},SwSMe:function(a,n){return a!==n},UliLz:t(563),anJxB:t(873),uAVnd:function(a,n){return a===n},hJrdT:function(a,n){return a(n)},GDXdA:function(a,n){return a+n},gtpnl:function(a,n){return a+n},TJkUy:t(937),OvbHk:t(890),NsqxE:function(a,n){return a||n},lyJrQ:t(953),AWkMy:function(a,n){return a||n},GAOwE:"tLvmQ",xzwyx:function(a,n){return a||n},iNygV:function(a,n){return a<=n},ZrSki:function(a,n){return a>=n},AOdiR:function(a,n){return a===n},oDYlH:t(512),cbtAK:function(a,n){return a||n},lcVIJ:function(a,n){return a===n},pUIPO:"LnyJC",hEAXJ:function(a,n){return a(n)},KAgaU:function(a,n){return a(n)},yLbhi:t(1233),NtIsF:function(a,n){return a||n},uUqXu:function(a,n){return a||n},PgbgD:function(a,n){return a!=n},CZzyP:t(1458)+t(1426)+"d",zJLuq:"qos",csmWI:t(374)+"id",jLbUW:function(a,n){return a!==n},uypmy:t(1193),rWQqQ:function(a,n,s){return a(n,s)},KLGsC:function(a,n){return a(n)},EywTT:t(1111),oWmcE:function(a,n){return a+n},TUDak:t(1832),qOwtA:t(1132),rFgwL:function(a,n,s){return a(n,s)},vTFnY:function(a,n){return a!==n},nUzXR:t(951),lVvvT:t(1004),AMWBy:t(817)+"er_qos",LPldx:function(a,n,s,l){return a(n,s,l)},RizWZ:t(817)+"er_qos_ack",pWXIk:function(a,n,s,l){return a(n,s,l)},aOJhf:t(817)+t(1150)+t(285),OcKtK:function(a,n){return a!==n},SCjwm:t(490),pVaGF:t(1833),eeJJI:t(725),bIaFL:t(757),Tkszh:function(a,n){return a&&n},rkIuP:"ack_id",pQcyq:function(a,n){return a||n},suzps:t(536),yncIj:"received",EAtzG:function(a,n,s){return a(n,s)},mVtUz:function(a,n){return a|n},LdyEB:function(a,n){return a|n},CTcUO:function(a,n){return a<<n},kwUtt:function(a,n){return a&n},ceTnB:function(a,n){return a<<n},nANaD:t(1678),GRIXO:function(a,n){return a(n)},zgQsm:t(994),cxyJx:t(1011)+t(381)+"et=utf-8",WPGYM:t(1565)+t(496)+";charset"+t(1551),ZzuIQ:t(373),ixoVe:function(a){return a()},bFnXc:function(a,n){return a<n},SGZGK:function(a,n){return a+n},NvubG:function(a,n){return a&n},QOXNY:function(a,n){return a||n},hyxiD:function(a,n){return a+n},DAkua:function(a,n){return a|n},nnHSB:function(a,n){return a<<n},kzFKf:function(a,n){return a+n},vFFDm:function(a,n){return a+n},gtIPJ:function(a,n){return a+n},pHKHi:function(a,n){return a(n)},BayjJ:function(a,n){return a+n},lYsEF:t(375),ThFuq:t(987),QnZkZ:t(1068),jOtbp:t(581)+t(458)+"e",XEKAv:function(a,n){return a>=n},zcYTl:function(a,n){return a&n},KWdIB:function(a,n){return a+n},NAZcn:function(a,n){return a+n},vlhqd:function(a,n){return a-n},LcvrF:function(a,n){return a<n},xakps:function(a,n){return a&n},sOPZv:function(a,n){return a&n},cHxqU:function(a,n){return a|n},WjAZY:function(a,n){return a&n},tsVzv:function(a,n){return a|n},ZCGdI:function(a,n){return a!==n},uqJSQ:t(368),BqriA:function(a,n){return a+n},bQMqS:function(a,n){return a<n},ScQNO:function(a,n){return a<<n},ePtLU:function(a,n){return a===n},guUZo:"MgFnj",WCSOh:t(1508)+"3",ZNiFD:function(a,n){return a+n},TgqEJ:function(a,n){return a+n},KvWSg:function(a,n){return a|n},PimOL:function(a,n){return a|n},yZzFy:function(a,n){return a|n},rNnDG:function(a,n){return a<<n},RSXzc:function(a,n){return a|n},pIfjz:function(a,n){return a|n},scQeP:function(a,n){return a+n},jkcvG:function(a,n){return a+n},HRRqV:t(369),zOcCB:function(a,n){return a>>>n},egNwJ:function(a,n){return a+n},MzdXR:function(a,n){return a&n},ZbJHf:function(a,n){return a+n},Cygkv:function(a,n){return a&n},RYPiY:function(a,n){return a>>>n},qmWek:function(a,n){return a+n},uHlLi:function(a,n){return a>>>n},rQOqL:function(a,n){return a<n},qwdlY:function(a,n){return a>>>n},xxEuT:function(a,n){return a&n},BUHQS:function(a,n){return a>>>n},UAdaN:function(a,n){return a<<n},KeYyl:function(a,n){return a<n},WFCoH:function(a,n){return a(n)},Pshzm:function(a,n,s,l){return a(n,s,l)},cYITU:t(810),zRNeQ:t(609),SRIxF:function(a,n,s,l){return a(n,s,l)},tfyjZ:t(1790)+t(633),vutuL:"header",tsSCN:t(634)+t(1560),npLED:function(a,n,s){return a(n,s)},OAJwu:function(a,n,s){return a(n,s)},kCWHB:function(a,n,s){return a(n,s)},qmFnp:t(1646)+t(451),ReYEy:t(1474),jkSEL:t(1364),vIKRK:t(1855),jAGhc:function(a){return a()},WWTNZ:t(1838)+"r",HGiAy:t(511),tVGzZ:function(a,n){return a!==n},JfQyc:function(a,n){return a||n},iFwxr:function(a,n){return a(n)},pYCoo:function(a,n){return a(n)},YmdQf:"code",baUfL:function(a,n,s){return a(n,s)},EhxJr:"x_fronti"+t(538),pjXhi:function(a,n){return a(n)},zlYhd:function(a,n,s){return a(n,s)},QRXnO:t(817)+t(1265),tyyku:function(a,n,s,l){return a(n,s,l)},lxOiE:"x-msg-qos",IACoX:function(a,n,s){return a(n,s)},zoWbb:function(a,n){return a(n)},aIrlv:function(a){return a()},niNnJ:function(a,n){return a===n},gVyHM:function(a,n){return a+n},TamQX:function(a){return a()},VzGav:function(a,n){return a>>>n},YsrDV:function(a,n){return a<<n},rOHKH:function(a,n){return a<n},YHXIL:function(a,n){return a<n},OvHnz:function(a,n){return a!==n},sdXTv:function(a,n){return a|n},rLcuH:function(a,n){return a+n},yFRRO:function(a,n){return a&n},umyWG:function(a,n){return a>>>n},lNfyP:function(a,n){return a>>>n},zbUfG:function(a,n){return a>>>n},emwbB:function(a,n){return a>>>n},Mxkca:function(a,n){return a&n},DdCQe:function(a,n){return a&n},RgWGZ:function(a,n){return a>>>n},CaXGx:function(a,n){return a!==n},fXJki:function(a){return a()},Eerab:function(a,n){return a|n},SlgXo:function(a,n){return a&n},bhuWO:function(a,n,s){return a(n,s)},Rcezb:function(a,n){return a(n)},gFQqp:t(1072),kDMyh:function(a,n){return a!==n},pidze:function(a){return a()},DDJZQ:function(a,n){return a===n},mSnHW:function(a,n,s){return a(n,s)},sXwYM:function(a,n){return a===n},tNOWz:function(a,n,s,l){return a(n,s,l)},vObsS:"ping_onc"+t(920)+"s",hHjGA:t(707),Skucz:function(a,n){return a!==n},AjQhH:function(a,n,s){return a(n,s)},HSVRo:t(690),MVcQG:function(a,n){return a!==n},Sfvmo:function(a,n){return a(n)},UWsuV:"TRjlP",SqLcV:function(a,n){return a instanceof n},dBLlb:function(a,n){return a instanceof n},rqTwA:t(1793)+"e",OoCDV:"arraybuffer",ZGVsc:function(a,n){return a(n)},UOTlA:t(1503)+t(1081)+t(967)+t(1382)+t(379)+t(1411)+t(1844)+t(1632),qLkIE:t(682),xtfjI:function(a,n,s){return a(n,s)},FGnbc:t(1159)+t(1406)+t(775)+"ct",WJEab:function(a,n){return a>>>n},mcLNx:function(a,n){return a&n},PSxCI:function(a,n){return a&n},qoLxE:function(a,n){return a>>>n},saXhE:function(a,n){return a+n},RgBvq:function(a,n){return a>>>n},FiZut:t(1069),THBHZ:"function",LfdER:function(a,n){return a(n)},aLswF:function(a,n){return a instanceof n},oRhXa:function(a){return a()},ciprZ:t(485),BCCQV:t(326),HbrjW:t(1540)+t(1371)+t(808)+t(1220)+t(1483),yENlR:t(1261),IqpiT:t(639),TNfXv:function(a,n){return a!==n},wMraO:function(a,n){return a!==n},ltxqT:t(1043),mnKfp:t(1285),GmBKs:"wss://",vQtfo:"ws://",TmKKz:"vMStC",yAjUn:t(832),bQwYd:t(978)+"d",JvYGB:function(a,n){return a||n},gDzES:t(1503)+t(874)+t(1514)+t(1175)+t(1800),YywvO:function(a,n){return a==n},ASZDE:function(a,n,s){return a(n,s)},GNUcz:t(742),RrZfo:function(a,n,s){return a(n,s)},rHnIE:function(a,n,s){return a(n,s)},TBgKi:"0|3|1|4|2",OlhJw:function(a,n){return a+n},iSfKL:function(a,n){return a<n},iPVIL:t(300),npmFC:t(1141),ihYBt:function(a,n){return a(n)},DVPzl:function(a,n){return a-n},kUaWk:function(a,n){return a!==n},yqeVV:t(1045)+t(1433)+"t",MSnUY:t(1571),kzMJv:function(a,n,s){return a(n,s)},LAyHk:"iyePq",kqBpo:"nyOKe",FqLyd:t(455)+t(763)+t(370)+"g",lPBga:function(a,n){return a(n)},NbweT:function(a,n){return a===n},RVjuP:t(1108),gyryl:"ack",kcTJY:function(a,n){return a===n},YLRCK:"VrXlM",GbIqc:t(515)+"2",SIQHW:t(1153),pcLoI:"0|3|2|4|1",ODgNA:function(a,n){return a!==n},oCYiy:t(741),aIjWI:function(a,n,s){return a(n,s)},jWAPV:t(1540)+t(650)+t(1848)+t(1497),gBXur:function(a,n){return a===n},RsZIW:t(470),uzjbU:function(a,n){return a!==n},DzUIb:t(1354),CPupp:function(a,n){return a&n},hCvod:function(a,n){return a|n},QMlPd:function(a,n){return a&n},BCquO:function(a,n){return a|n},EjOHs:function(a,n){return a&n},ykiKw:function(a,n){return a&n},vaTvV:function(a,n){return a>>n},yXDkE:function(a,n){return a|n},LWLHC:function(a,n){return a&n},gKefm:t(408),hxTLc:t(1427)+t(1835),bpDSL:function(a,n){return a===n},dLkRz:"close, ws instan"+t(613)+t(1796)+"ed",mBNbD:function(a,n){return a||n},vdaiy:function(a,n){return a===n},tDMHM:function(a,n){return a==n},LYKMu:function(a,n){return a instanceof n},VsNbb:function(a,n){return a(n)},kiWTX:function(a,n){return a(n)},uzFkW:function(a,n){return a||n},VffVW:t(1503)+t(1299)+t(317)+t(1702),QkUGa:function(a,n){return a instanceof n},Ugkpi:t(1015),hzhaz:t(1091),gMBVp:"enqueue",XvYHg:t(1143),lrnUG:function(a,n){return a==n},Bcrbk:t(785)+t(310)+"ing",zrITI:function(a,n){return a!==n},MZpfz:t(367),NCfWd:t(979)+"2",rEOqM:function(a,n){return a(n)},fvLXL:t(1012),olBnK:function(a,n){return a!=n},dYmNr:"Window",TeQup:function(a,n){return a!=n},rgRke:t(1599),rcmnC:function(a,n){return a===n},IZVVH:"Dedicate"+t(1064)+t(745)+"pe",JCKsR:function(a,n){return a!=n},wpKde:function(a,n){return a===n},ZiZCt:function(a,n){return a==n},kExrs:function(a,n){return a!=n},Amdqr:function(a,n){return a!=n},CLMGL:"SharedWorkerGlob"+t(668),wDFWg:function(a,n){return a===n},DbYIC:t(1834)+t(1384)+t(645),Eljau:function(a,n){return a!=n},SsvIu:function(a,n){return a!=n},JSeQM:function(a,n){return a!=n},TUXDV:"__x_msg_"+t(1543)};Ft.r(Re),Ft.d(Re,{FWS:()=>Hg,CustomErrorEvent:()=>ul,createCloseEvent:()=>_t,ReconnectEvent:()=>ll,createErrorEvent:()=>lt,decodedFrame:()=>rn,createOpenEvent:()=>ml,CustomCloseEvent:()=>fl,createReconnectEvent:()=>ba,FrontierMessageEvent:()=>hl,encodeFrame:()=>Ut,createMessageEvent:()=>gl,OpenEvent:()=>pl,ErrorCode:()=>on,Event:()=>ir,MessageEvent:()=>xl});let r="";function i(a=""){let n=t,s="02",l=""+Date[n(713)](),f=r||(r=e[n(575)](x,a)),g=Math[n(975)]().toString(16)[n(624)](-6);return e[n(1395)](e[n(1158)](e[n(1116)](s,l),f),g)}function o(){let a=t;return e.ZzDZL(e.sDOII(1e4,Date[a(713)]()),Math[a(927)](e[a(1566)](1e4,Math[a(975)]())))}function c(a){let n=t;return e[n(1031)](e.yGPPe(Array,8)[n(247)]("0"),e[n(1573)](parseInt,a,10)[n(558)](2))[n(624)](-8)}function d(a){let n=t;return e[n(1731)](e.CuTaE,e.KunFh)?this._socket[n(635)+"ns"]:e[n(1515)](e.FROXY(Array,4).join("0"),e[n(1573)](parseInt,a,2)[n(558)](16))[n(624)](-4)}function u(a){let n=t,s=a.split(/\./)[n(493)](g=>c(g)),l=[];return l[0]=d(e[n(218)](s[0],s[1])),l[1]=e[n(564)](d,s[2]+s[3]),[e[n(750)],"0000",e[n(750)],e[n(750)],e.MNgOO,e[n(225)],l[0],l[1]][n(247)]("")}function x(a){let n=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(a),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(973)](a);return s?u(a):l?e.trjFe(h,a):e[n(207)]}function h(a){let n=t;if(e.dCcPN(n(1759),e[n(1154)])){let s="",l=[],f=0,g=0,v=!0,_=e[n(750)];if(e[n(1321)](a[n(762)]("::"),-1)){let p=a.split("::");for(let C=0;e[n(663)](C,p[n(1270)]);C++){let O=p[C];if(e[n(1321)](O[n(762)](":"),0)){let U=O[n(842)](":");v&&(f=U[n(1270)]),g+=U.length;for(let H=0;e.uwDbd(H,U[n(1270)]);H++)if(e[n(947)](4,U[H][n(1270)])){let ae=_[n(463)+"g"](0,e[n(1808)](4,U[H][n(1270)])),st=ae[n(1730)](U[H]);l[n(394)](st)}else l[n(394)](U[H]);v=!1}else{if(O[n(1270)]!==4){let U=_[n(463)+"g"](0,e[n(1645)](4,O[n(1270)])),H=U[n(1730)](O);l.push(H)}else l.push(O);v&&(f+=1),g+=1,v=!1}}let y="";for(let C=0;e.XStVm(C,8-g);C++)y=y[n(1730)](_);for(let C=0;e.KMIFM(C,l[n(1270)]);C++)e[n(1731)](C,f)?(s=s[n(1730)](y),s=s.concat(l[C])):s=s[n(1730)](l[C]);return s}{let p=a[n(842)](":");for(let y=0;e[n(1164)](y,p[n(1270)]);y++){let C=p[y];if(e.dCcPN(4,p[y][n(1270)]))if(e[n(947)](e[n(1071)],e[n(1342)])){let O=_[n(463)+"g"](0,e[n(1808)](4,p[y][n(1270)])),U=O[n(1730)](C);s=s[n(1730)](U)}else this[n(1782)]&&this[n(1782)][n(1598)](_0x5b431b),this[n(1439)+n(722)][_0xa07f00]=null;else s=s[n(1730)](C)}return s}}else return new _0x442577(_0x10c9d9,{code:_0x3067ee,reason:_0x24e8e3,wasClean:_0x55f20c,willReconnect:_0x1f6831})}function m(a,n){let s=t,l=a[s(488)];e[s(1747)](void 0,l)&&(e.EuqeU(ge,n,10),e[s(942)](G,n,l));let f=a[s(1676)];e[s(947)](void 0,f)&&(e[s(1638)](ge,n,18),e[s(1638)](G,n,f))}function w(a){let n=t,s={};e:for(;!e[n(1022)](V,a);){let l=e[n(805)](pe,a);switch(e[n(1198)](l,3)){case 0:break e;case 1:s[n(488)]=e.FawFp(R,a,e[n(1177)](pe,a));break;case 2:s[n(1676)]=R(a,e[n(413)](pe,a));break;default:e[n(366)](P,a,e.pqNde(7,l))}}if(e[n(1731)](void 0,s[n(488)]))throw new Error("Missing "+n(1123)+n(427)+"key");if(e[n(1731)](void 0,s[n(1676)]))throw new Error(e[n(335)]);return s}function I(a){let n=t,s=e.zACJw(D);return e[n(1656)](b,a,s),e[n(294)](B,s)}function b(a,n){let s=t,l={ozYca:function(f,g){return e[F(1582)](f,g)},snMsc:function(f,g){return f+g},JjQsC:e[s(1272)]};if(e[s(1731)](s(1145),e[s(847)])){if(l[s(646)](l[s(1429)](_0x1ef624[s(1410)],_0x54862f),_0x4b7db2.limit))throw new _0x1d7075(l[s(1315)]);_0x10e951[s(1410)]+=_0x1a68af}else{let f=a.SeqID;e[s(1851)](void 0,f)&&(e[s(829)](ge,n,8),e[s(1054)](wt,n,f));let g=a[s(809)];e[s(947)](void 0,g)&&(e.wtwXY(ge,n,16),e.CtIsf(wt,n,g));let v=a[s(609)];e[s(1781)](void 0,v)&&(e[s(1573)](ge,n,24),wt(n,e.EWOSd(L,v)));let _=a[s(1093)];e.pTwAs(void 0,_)&&(e[s(573)](ge,n,32),e[s(1638)](wt,n,L(_)));let p=a[s(268)];if(e[s(1851)](void 0,p))for(let cn of p){ge(n,42);let dn=e[s(940)](D);m(cn,dn),e[s(1452)](ge,n,dn[s(276)]),e[s(743)](W,n,dn),e[s(1296)](N,dn)}let y=a[s(1309)+"ncoding"];y!==void 0&&(e.FawFp(ge,n,50),e[s(1638)](G,n,y));let C=a["payloadT"+s(597)];e.NBfDZ(void 0,C)&&(ge(n,58),e[s(366)](G,n,C));let O=a[s(1766)];O!==void 0&&(e[s(1638)](ge,n,66),e.nKYuI(ge,n,O[s(1270)]),e[s(1054)](ce,n,O));let U=a[s(761)];e[s(1633)](void 0,U)&&(e[s(1638)](ge,n,74),e.Sbokt(G,n,U));let H=a[s(1408)+s(1047)];e.NBfDZ(void 0,H)&&(e[s(834)](ge,n,82),G(n,H));let ae=a[s(436)];e.TuTBA(void 0,ae)&&(e[s(288)](ge,n,90),e[s(216)](G,n,ae));let st=a[s(939)+"e"];if(st!==void 0)if(e[s(251)](s(606),s(606)))e.bsvSO(ge,n,96),wt(n,e[s(805)](L,st));else return 0}}function S(a){return e.ryQBj(A,z(a))}function A(a){let n=t,s={};e:for(;!e.yGPPe(V,a);){let l=e[n(791)](pe,a);switch(e[n(1556)](l,3)){case 0:break e;case 1:s.SeqID=e[n(447)](kt,a,!0);break;case 2:s[n(809)]=e.mekBy(kt,a,!0);break;case 3:s.service=pe(a);break;case 4:s.method=pe(a);break;case 5:{let f=e[n(575)](k,a);(s[n(268)]||(s[n(268)]=[]))[n(394)](e.yGPPe(w,a)),a[n(276)]=f;break}case 6:s[n(1309)+n(464)]=R(a,pe(a));break;case 7:s["payloadT"+n(597)]=R(a,pe(a));break;case 8:s[n(1766)]=e.PqWkM(oe,a,pe(a));break;case 9:s[n(761)]=e.kzGpp(R,a,e[n(417)](pe,a));break;case 10:s[n(1408)+n(1047)]=e.PqWkM(R,a,e[n(805)](pe,a));break;case 11:s.msgID=e[n(916)](R,a,pe(a));break;case 12:s.frameType=pe(a);break;default:P(a,e[n(617)](7,l))}}if(s.SeqID===void 0)throw new Error("Missing required field: SeqID");if(s[n(809)]===void 0)throw new Error(e.OKHva);if(e[n(251)](void 0,s[n(609)]))throw new Error("Missing required field: service");if(e[n(418)](void 0,s[n(1093)]))throw new Error(e[n(1624)]);return s}function k(a){let n=t,s=e[n(1639)](pe,a),l=a.limit;return a.limit=e[n(1005)](a[n(1410)],s),l}function P(a,n){let s=t;switch(n){case 0:for(;e.NnfNu(128,e.trjFe(ee,a)););break;case 2:e[s(1452)](Y,a,e[s(877)](pe,a));break;case 5:e[s(942)](Y,a,4);break;case 1:e[s(1044)](Y,a,8);break;default:throw new Error(e.stDln+n)}}function L(a){return a|=0,{low:a,high:e.vYxSI(a,31),unsigned:a>=0}}let E=[];function D(){let a=t,n={yhEVo:function(s,l,f){return e[F(829)](s,l,f)},sviLW:e[a(1675)]};if(a(717)!=="giitb"){let s=this[a(1448)][a(808)+a(1409)+a(1313)](_0x5b7d88,_0x24c410);this[a(1575)+a(1488)+a(442)](n.yhEVo(_0x1d4bfc,n.sviLW,{code:_0x2d4546,reason:_0x48d70a,wasClean:!0,willReconnect:s})),s&&this[a(1166)]()}else{let s=E[a(892)]();return s?(s[a(1410)]=s[a(276)]=0,s):{bytes:new Uint8Array(64),offset:0,limit:0}}}function N(a){E.push(a)}function z(a){return{bytes:a,offset:0,limit:a.length}}function B(a){let n=t,s=a[n(1223)],l=a.limit;return e[n(1731)](s[n(1270)],l)?s:s[n(459)](0,l)}function Y(a,n){let s=t;if(e[s(1802)](a.offset,n)>a[s(276)])throw new Error(e.GohpJ);a[s(1410)]+=n}function V(a){let n=t;return a[n(1410)]>=a[n(276)]}function re(a,n){let s=t,l=a[s(1223)],f=a[s(1410)],g=a[s(276)],v=e.GaDxc(f,n);if(v>l[s(1270)]){let _=new Uint8Array(e[s(1566)](2,v));_[s(328)](l),a[s(1223)]=_}return a.offset=v,e[s(1825)](v,g)&&(a.limit=v),f}function Z(a,n){let s=t;if(e[s(807)]===s(777)){let l=a[s(1410)];if(e[s(1321)](e[s(1437)](l,n),a[s(276)]))throw new Error(e.BGFIl);return a[s(1410)]+=n,l}else this[s(1748)+"er"]&&_0x3634af[s(917)+s(1048)](e[s(1709)],this["_handleO"+s(1619)]),this._isBrowser&&_0x11ec52[s(917)+s(1048)](e.RLfSP,this._handleOffLine),this._isBrowser&&_0x571dea["addEvent"+s(1048)](e[s(1610)],this[s(1356)+"ageHide"]),this._isBrowser&&_0x530916[s(917)+s(1048)](e[s(546)],this[s(1356)+s(289)])}function oe(a,n){let s=t,l=e[s(1044)](Z,a,n);return a[s(1223)].subarray(l,e.OVWQN(l,n))}function ce(a,n){let s=t,l=e.GHKXk(re,a,n[s(1270)]);a[s(1223)][s(328)](n,l)}function R(a,n){let s=t,l=e.QpFKf(Z,a,n),f=String[s(928)+s(309)],g=a.bytes,v="\uFFFD",_="";for(let p=0;e[s(780)](p,n);p++){let y=g[e.rTDas(p,l)],C,O,U,H;if(e.xMTqh(e[s(1608)](128,y),0))_+=e[s(1823)](f,y);else if(e[s(1545)](224&y,192))e[s(1057)](e[s(1567)](p,1),n)?_+=v:(C=g[e[s(1449)](e.PBbLr(p,l),1)],e[s(947)](192&C,128)?_+=v:(H=e[s(855)](e[s(540)](31,y),6)|e[s(617)](63,C),H<128?_+=v:(_+=f(H),p++)));else if(e.zHPSw(e.TCnhl(240,y),224))if(p+2>=n)_+=v;else if(C=g[e[s(1465)](e.rDJEd(p,l),1)],O=g[p+l+2],e.FOXRD(e.jYPma(e[s(1518)](C,e[s(532)](O,8)),49344),32896))_+=v;else if(e[s(235)](e[s(1323)],e[s(1725)])){let ae=_0xd961e.charCodeAt(_0x5168b5);e[s(1057)](ae,55296)&&ae<=56319&&e[s(663)](e[s(1079)](_0x23db12,1),_0x46c9a5)&&(ae=e.zmlGP(e[s(532)](ae,10)+_0x4a9e4f[s(884)+"At"](++_0x1e1ea6),56613888)),_0x30b0f4+=e.IdCQN(ae,128)?1:e[s(1812)](ae,2048)?2:e.bjSow(ae,65536)?3:4}else H=e[s(664)](e.VUqfI(e.kKPkb(15,y)<<12,e[s(532)](e.iamsu(63,C),6)),63&O),H<2048||e[s(1057)](H,55296)&&H<=57343?_+=v:(_+=e.qMKkq(f,H),p+=2);else e[s(1673)](248,y)==240?e[s(1057)](p+3,n)?_+=v:(C=g[e.oacfA(e.LpvtK(p,l),1)],O=g[e[s(1690)](e[s(1437)](p,l),2)],U=g[e[s(1449)](p+l,3)],e[s(657)](e[s(688)](e[s(1714)](C,e.nAePU(O,8))|e.NOKCC(U,16),12632256),8421504)?_+=v:(H=e[s(664)](e[s(1714)](e[s(1640)](e[s(764)](7,y)<<18,e[s(941)](e[s(1520)](63,C),12)),e.TlOEA(e[s(764)](63,O),6)),63&U),e[s(1695)](H,65536)||e[s(468)](H,1114111)?_+=v:s(1536)!=="PhNbd"?(this[s(1439)+s(722)][s(658)](),this[s(1439)+"Queue"][s(394)](_0x346371)):(H-=65536,_+=e[s(1008)](f,e[s(1728)](e[s(919)](H,10),55296),e[s(331)](e[s(764)](1023,H),56320)),p+=3))):_+=v}return _}function G(a,n){let s=t,l={cQqez:function(f,g,v){return e[F(423)](f,g,v)},wImhf:e[s(1675)],CLEqx:function(f,g,v){return f(g,v)}};if(s(648)===e[s(902)])return this[s(968)]?e[s(1437)](e.sDOII(this[s(1831)]>>>0,_0x17d182),e.JANJj(this.low,0)):e[s(1437)](e[s(516)](this[s(1831)],_0x172a42),this[s(1496)]>>>0);{let f=n.length,g=0;for(let p=0;e[s(870)](p,f);p++){let y=n[s(884)+"At"](p);e[s(291)](y,55296)&&y<=56319&&e[s(1812)](p+1,f)&&(y=e[s(1654)](e.RQRiJ(e[s(1179)](y,10),n[s(884)+"At"](++p)),56613888)),g+=e[s(663)](y,128)?1:e[s(801)](y,2048)?2:y<65536?3:4}ge(a,g);let v=re(a,g),_=a[s(1223)];for(let p=0;e[s(327)](p,f);p++){let y=n.charCodeAt(p);if(y>=55296&&e[s(1399)](y,56319)&&e[s(1648)](e[s(1079)](p,1),f)&&(y=e.ViUcC(e[s(960)](e[s(969)](y,10),n[s(884)+"At"](++p)),56613888)),y<128)_[v++]=y;else if(e[s(260)](e[s(748)],e[s(1660)]))e[s(870)](y,2048)?_[v++]=e[s(461)](e[s(1736)](e[s(297)](y,6),31),192):(e[s(934)](y,65536)?_[v++]=e[s(1640)](e[s(1608)](e[s(297)](y,12),15),224):(_[v++]=e[s(461)](e[s(1420)](y>>18,7),240),_[v++]=e.bodzM(y>>12&63,128)),_[v++]=e[s(1640)](e[s(1344)](e[s(989)](y,6),63),128)),_[v++]=e.VUqfI(63&y,128);else{if(this["_endpoin"+s(1173)]?.["checkRea"+s(1527)+"es"]()){let O=this[s(1037)+s(1173)]?.[s(1139)+s(768)+"nt"]();this[s(1575)+"hCloseEv"+s(442)](l[s(277)](_0x58b7f9,l[s(970)],{code:1006,reason:"connect "+O+(" timeout"+s(1622)+"tries re"+s(1711)),wasClean:!0}))}else{let O=this[s(1448)][s(808)+s(1409)+s(1313)](_0x39cc89,_0x187364);this[s(1575)+s(1488)+"ent"](l[s(747)](_0x179550,l.wImhf,{code:_0x58c9fc,reason:_0x45f7d6,wasClean:!0,willReconnect:O})),O&&this._connect()}return}}}}function W(a,n){let s=t,l=re(a,n.limit),f=a[s(1223)],g=n[s(1223)];for(let v=0,_=n.limit;e[s(1738)](v,_);v++)f[e.wFnPu(v,l)]=g[v]}function ee(a){let n=t;return a[n(1223)][e[n(681)](Z,a,1)]}function Ve(a,n){let s=t,l=re(a,1);a[s(1223)][l]=n}function pe(a){let n=t,s=0,l=0,f;do f=e[n(351)](ee,a),s<32&&(l|=e[n(1663)](e[n(396)](127,f),s)),s+=7;while(128&f);return l}function ge(a,n){let s=t;for(n>>>=0;e.dvwUl(n,128);)e[s(991)]!==s(1857)?(this[s(1782)]&&this[s(1782)].send(_0x1b01c3),this._debug(s(1091),_0x145a93)):(Ve(a,127&n|128),n>>>=7);e[s(1008)](Ve,a,n)}function kt(a,n){let s=t,l={gKnyo:function(p,y){return e[F(641)](p,y)}},f=0,g=0,v=0,_;if(_=e[s(1517)](ee,a),f=e[s(617)](127,_),128&_&&(_=e.mgwoV(ee,a),f|=e.MOPOa(127&_,7),128&_&&(_=e[s(1724)](ee,a),f|=e[s(941)](e[s(396)](127,_),14),e[s(1088)](128,_))))if(e[s(1804)](e.ozwQO,e[s(239)])){if(_=e[s(1737)](ee,a),f|=e[s(941)](e.pQsuK(127,_),21),128&_&&(_=e[s(791)](ee,a),g=e[s(712)](127,_),e.TTGeC(128,_))){if(e.kZhla(e[s(215)],e[s(215)]))eFeJkP[s(610)](_0x59b80e,_0x5e5624[s(1229)]),_0x1969e1();else if(_=e.WNpfY(ee,a),g|=e[s(1336)](e[s(846)](127,_),7),e[s(1302)](128,_)&&(_=e.kGUji(ee,a),g|=e[s(941)](e.GoGer(127,_),14),128&_&&(_=e.VvdtJ(ee,a),g|=e.CnJQN(e[s(769)](127,_),21),e[s(764)](128,_))))if(e[s(1694)](e[s(843)],e[s(843)])){let p={JBMYX:s(1229),upJvL:function(y,C,O){return y(C,O)},XySuV:s(324)};_0xecb416[s(322)]()[s(1758)](()=>{let y=s,C=_0x2ceaaa(p.JBMYX,{message:this[y(1207)+y(1623)+y(938)](_0x3bfa88)});this.emit(p[y(1557)],C);let O=p[y(1338)](_0x4ff029,p.XySuV,{reason:this[y(1207)+y(1623)+"age"](_0x154f98)});this[y(1318)](p[y(1752)],O)})}else _=e.TIbwE(ee,a),v=e[s(1736)](127,_),128&_&&(_=e[s(575)](ee,a),v|=e[s(611)](e.hGQNI(127,_),7))}}else _0x160921+=e[s(357)](_0x5a1e56,_0x207b6d),_0x1c5caf++;return{low:f|g<<28,high:e[s(1773)](e.OjQNe(g,4),v<<24),unsigned:n}}function wt(a,n){let s=t,l=e[s(1556)](n[s(1496)],0),f=e.nNfUd(e[s(1714)](e[s(1198)](n.low,28),e[s(1663)](n[s(1831)],4)),0),g=e.vUCCH(n[s(1831)],24),v=e[s(583)](0,g)?e[s(1731)](0,f)?e[s(1738)](l,16384)?l<128?1:2:l<2097152?3:4:e[s(663)](f,16384)?e[s(1376)](f,128)?5:6:e[s(254)](f,2097152)?7:8:e.Szpqc(g,128)?9:10,_=e.CtIsf(re,a,v),p=a.bytes;switch(v){case 10:p[_+9]=e[s(688)](g>>>7,1);case 9:p[_+8]=e[s(1694)](9,v)?e.pFfjH(128,g):127&g;case 8:p[e[s(950)](_,7)]=e[s(869)](8,v)?e.WYkTr(e[s(599)](f,21),128):e[s(1556)](f,21)&127;case 7:p[_+6]=e[s(1633)](7,v)?e[s(863)](e[s(1749)](f,14),128):e[s(961)](f>>>14,127);case 6:p[e[s(218)](_,5)]=e[s(260)](6,v)?e[s(799)](f,7)|128:e[s(800)](f>>>7,127);case 5:p[e[s(1802)](_,4)]=e[s(282)](5,v)?128|f:e.pqNde(127,f);case 4:p[e[s(1860)](_,3)]=v!==4?l>>>21|128:e[s(1556)](l,21)&127;case 3:p[e[s(1049)](_,2)]=e[s(657)](3,v)?e.yCRcq(e[s(1512)](l,14),128):e.VevhE(e[s(1548)](l,14),127);case 2:p[e.qySrK(_,1)]=e[s(1781)](2,v)?e[s(959)](e[s(1576)](l,7),128):e.ZqXuI(l>>>7,127);case 1:p[_]=e[s(947)](1,v)?e[s(1642)](128,l):127&l}}function rn(a){return e[t(627)](S,a)}function Ut(a){return e[t(1737)](I,a)}let sn=65536,ei=t(779),_e=sn*sn,ke=_e*_e,rr=ke/2,Le=String.prototype[t(884)+"At"];class he{constructor(n,s,l){let f=t;this[f(453)]=!0,this.low=e[f(522)](0,n),this[f(1831)]=e[f(1773)](0,s),this[f(968)]=!!l}static isLong(n){let s=t;return n&&e.YPvat(!0,n[s(453)])}static[t(1130)](n,s,l){let f=t;return e[f(383)](e[f(566)],e[f(871)])?{bytes:_0x14d193,offset:0,limit:_0x20ba5a[f(1270)]}:new he(n,s,l)}static[t(498)+"s"](n,s,l){let f=t;return l?he[f(498)+f(812)](n,s):he[f(498)+f(1727)](n,s)}static[t(498)+t(812)](n,s){let l=t;return new he(e[l(1714)](n[0]|e[l(1312)](n[1],8),e[l(1663)](n[2],16))|n[3]<<24,e[l(1714)](e[l(1103)](e[l(888)](n[4],e[l(855)](n[5],8)),e[l(1368)](n[6],16)),n[7]<<24),s)}static[t(498)+t(1727)](n,s){let l=t;if(e.YPvat(e[l(234)],l(642)))_0x41debd(this,_0x391953,[_0x1529be,_0x163959,_0x3a0fdc,_0x545bb7,_0x3dc621,_0xbaec28]);else return new he(e.fJWnC(e.CEZgv(e[l(1640)](n[4]<<24,e[l(855)](n[5],16)),n[6]<<8),n[7]),e[l(522)](e[l(495)](e.batkO(e[l(784)](n[0],24),e[l(770)](n[1],16)),e.MOPOa(n[2],8)),n[3]),s)}static[t(386)](n){let s=t;return e[s(1731)](n,ei)?dl:new he(e.BHeHD(e[s(461)](e[s(392)](e.YrhAW(Le[s(1417)](n,0),e[s(1161)](Le[s(1417)](n,1),8)),e[s(532)](Le[s(1417)](n,2),16)),Le[s(1417)](n,3)<<24),0),e.WYkTr(e[s(1578)](e.oUCyB(Le[s(1417)](n,4),Le.call(n,5)<<8),Le.call(n,6)<<16),Le[s(1417)](n,7)<<24)>>>0,!0)}[t(1407)](){let n=t;return String[n(928)+n(309)](255&this.low,e[n(1420)](this.low>>>8,255),e[n(1631)](this.low,16)&255,e.mjyOo(this[n(1496)],24),255&this.high,e[n(1088)](e[n(1841)](this[n(1831)],8),255),e[n(1204)](e[n(824)](this[n(1831)],16),255),e.zZPVe(this.high,24))}static[t(1603)+"er"](n,s=!0){let l=t;if(isNaN(n))return s?Qp:dl;if(s){if(e.rvcBV(n,ke))return tg}else{if(e[l(1399)](n,-rr))return ng;if(n+1>=rr)return eg}return he.fromBits(e[l(503)](n%_e,0),e.ItfkP(n,_e)|0,s)}[t(1224)](){let n=t;return e.oPwuA(e[n(552)],e[n(637)])?this.unsigned?e[n(1262)](e[n(669)](e[n(824)](this.high,0),_e),e[n(1308)](this.low,0)):e[n(1437)](e[n(669)](this[n(1831)],_e),e.iDXVN(this[n(1496)],0)):_0xb21fab["objectSt"+n(605)]||_0x186590[n(1463)](_0x20e5a1)}[t(508)](){let n=t;return e[n(1731)](0,this[n(1831)])&&e[n(844)](0,this[n(1496)])}[t(665)](n){let s=t;he[s(453)](n)||(n=he[s(1603)+"er"](n));let l=e[s(1198)](this[s(1831)],16),f=e[s(1344)](65535,this[s(1831)]),g=this.low>>>16,v=e[s(1768)](65535,this.low),_=e[s(599)](n.high,16),p=e[s(333)](65535,n.high),y=e[s(1298)](n[s(1496)],16),C=e[s(686)](65535,n[s(1496)]),O=0,U=0,H=0,ae=0;return ae+=v+C,H+=e.aQHHI(ae,16),ae&=65535,H+=g+y,U+=e[s(724)](H,16),H&=65535,U+=e.dVfxC(f,p),O+=e[s(1548)](U,16),U&=65535,O+=l+_,O&=65535,he[s(1130)](H<<16|ae,e[s(461)](e[s(1805)](O,16),U),this[s(968)])}[t(208)](n){let s=t;return he.isLong(n)||(n=he.fromNumber(n)),e[s(1553)](this[s(968)],n[s(968)])&&e[s(235)](e[s(1741)](this[s(1831)],31),1)&&e[s(683)](e[s(1298)](n[s(1831)],31),1)?!1:e.LvbsS(this.high,n[s(1831)])&&this[s(1496)]===n[s(1496)]}addOne(){let n=t;if(e[n(383)](e.HfwDo,e[n(1250)]))return e[n(844)](-1,this.low)&&e[n(844)](-1,this.high)?he[n(1130)](0,0,this[n(968)]):e[n(952)](-1,this[n(1496)])?he[n(1130)](0,e[n(1009)](this[n(1831)],1),this[n(968)]):he[n(1130)](e[n(1094)](this[n(1496)],1),this[n(1831)],this[n(968)]);{let s=new _0x4eec46(e[n(1737)](_0x43110e,_0x53d57d));return e.tkVfB(_0x3d663b,_0x5ec717,s,0),s}}[t(1436)](n){let s=t;return e.nVDju(e[s(1718)],e.yzwsd)?n?this[s(1252)+"E"]():this[s(1734)+"E"]():"frontier_"+this._DBName}[t(1252)+"E"](){let n=t;if(e[n(1243)](e.KgEww,"UhoXn")){let s=this[n(1831)],l=this[n(1496)];return[e[n(1204)](255,l),e.cHUhi(e[n(1235)](l,8),255),e.dwYRd(l,16)&255,e[n(1171)](l,24),e[n(481)](255,s),e[n(617)](e[n(430)](s,8),255),e[n(945)](s,16)&255,s>>>24]}else{let s=e[n(1532)][n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":_0x2fd2d3[_0x23c5d1[e[n(527)]]=5002]=n(1040)+"NG_ERROR";continue;case"1":_0x467d7a[_0x2c8533[e[n(1370)]]=5003]=e[n(1370)];continue;case"2":_0x4c90eb[_0xa8fdbf[e.Aelfs]=5004]=n(608)+n(1440);continue;case"3":_0x37af90[_0x83fe06.OPEN_ERROR=5005]=e[n(1839)];continue;case"4":_0x57534f[_0x5e104b[n(1386)+n(901)]=5001]=e.eCPLH;continue;case"5":return _0x2f2b88}break}}}[t(1734)+"E"](){let n=t,s={ezdba:function(l,f,g){return e[F(288)](l,f,g)}};if(e[n(1735)]!==n(882)){let l=this[n(1831)],f=this[n(1496)];return[e[n(794)](l,24),e[n(1576)](l,16)&255,e[n(848)](l,8)&255,e[n(838)](255,l),e[n(1703)](f,24),e[n(1682)](e.PAsne(f,16),255),f>>>8&255,e.jYPma(255,f)]}else _0xc5cbae(_0x1397f6,82),HWoOMj.ezdba(_0x2dcdc4,_0x3238b1,_0x1575b4)}}let dl=new he(0,0,!1),Qp=new he(0,0,!0),eg=he[t(1130)](-1,2147483647,!1),tg=he[t(1130)](-1,-1,!0),ng=he[t(1130)](0,-2147483648,!1);var on=(function(a){let n=t,s=(n(1052)+n(1010))[n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":a[a[n(608)+"ERROR"]=5004]=e[n(429)];continue;case"1":return a;case"2":a[a["NATIVE_E"+n(901)]=5001]=e[n(477)];continue;case"3":a[a[e[n(1370)]]=5003]=e.yEfvd;continue;case"4":a[a[e[n(527)]]=5002]=e[n(527)];continue;case"5":a[a[n(1038)+"OR"]=5005]=e[n(1839)];continue}break}})({});class ir{constructor(n){let s=t,l={bHvxJ:function(f,g){return e[F(1753)](f,g)},NrJaY:function(f,g){return e.XOwsn(f,g)}};if(e[s(282)](e[s(1095)],e.NXGaf))return VzjxkV.bHvxJ(VzjxkV.NrJaY(1e4,_0x2aaea4[s(713)]()),_0x216350[s(927)](1e4*_0x2357eb[s(975)]()));this[s(1102)]=n,this[s(574)]=null}}class ll extends ir{constructor(n,s){let l=t;super(n),this[l(1153)]=s&&s[l(1153)]||null}}class ul extends ir{constructor(n,s){let l=t,f=e[l(579)][l(842)]("|"),g=0;for(;;){switch(f[g++]){case"0":this.error=s&&s.error||null;continue;case"1":this[l(1392)]=s&&s[l(1392)]||0;continue;case"2":this[l(275)]=s&&s[l(275)]||5001;continue;case"3":super(n);continue;case"4":this[l(1136)]=s&&s[l(1136)]||0;continue;case"5":this[l(679)]=s&&s[l(679)]||"";continue;case"6":this.message=s&&s[l(1153)]||"";continue}break}}}class fl extends ir{constructor(n,s){let l=t,f=e.wldEb.split("|"),g=0;for(;;){switch(f[g++]){case"0":this[l(1170)+"nnect"]=s&&s[l(1170)+l(811)]||!1;continue;case"1":this[l(275)]=s&&s.code||0;continue;case"2":this[l(971)]=s&&s.wasClean||!1;continue;case"3":this[l(576)]=s&&s[l(576)]||"";continue;case"4":super(n);continue}break}}}class xl extends ir{constructor(n,s){let l=t;super(n),this[l(1078)]=s&&s.data||null}}class hl extends xl{constructor(n,s){let l=t;super(n),this[l(1078)]=s&&s[l(1078)]||null,this[l(1153)]=s&&s[l(1153)]||null}}class pl extends ir{constructor(n,s){let l=t;super(n),this[l(1078)]=s&&s.data||null}}function lt(a,{message:n,code:s,error:l}){return new ul(a,{message:n,code:s,error:l})}function _t(a,{code:n,reason:s,wasClean:l,willReconnect:f}){return new fl(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function gl(a,{data:n,message:s}){return new hl(a,{data:n,message:s})}function ml(a,{data:n}){return new pl(a,{data:n})}function ba(a,{message:n}){return new ll(a,{message:n})}class wl{constructor(n,s){let l=t;this[l(1217)+"s"]=n,this[l(1513)+"es"]=s,this["currentI"+l(544)]=0,this[l(913)+l(398)+"riesCount"]=0}["resetEndpointCon"+t(1084)](){let n=t;if(e[n(776)](e.OoGJH,e[n(1811)]))this[n(930)+"ndex"]=0,this[n(913)+"ndpointTriesCount"]=0;else return!!this[n(505)]}[t(1580)+"es"](){let n=t;this[n(913)+n(398)+n(1292)+"t"]=0}[t(1139)+"ntEndpoint"](){let n=t;return this[n(1217)+"s"][this[n(930)+"ndex"]]}["getCurrentEndpoi"+t(1777)+"ount"](){let n=t;return this[n(913)+"ndpointT"+n(1292)+"t"]}[t(261)+t(1527)+"es"](){let n=t;return!!(this[n(930)+n(544)]>=this[n(1217)+"s"][n(1270)]||e[n(1238)](this[n(930)+"ndex"],e[n(708)](this[n(1217)+"s"].length,1))&&e[n(1545)](this[n(913)+n(398)+n(1292)+"t"],this[n(1513)+"es"]))}["checkCur"+t(514)+t(306)+t(593)+t(997)](){let n=t;return e[n(1607)](this[n(930)+n(544)],this.endpoints[n(1270)])?!0:e[n(295)](this[n(913)+"ndpointTriesCount"],this[n(1513)+"es"])}[t(448)+t(1423)+t(1686)+t(589)+"unt"](){let n=t;return this[n(913)+n(398)+n(1292)+"t"]=1,this[n(930)+n(544)]++,this[n(1217)+"s"][this[n(930)+n(544)]]}[t(1139)+t(768)+t(506)+t(600)](){let n=t;return this[n(913)+n(398)+n(1292)+"t"]++,this[n(1139)+n(768)+"nt"]()}}let sr=(e.olBnK(e.viCPr,typeof globalThis)&&t(881)===globalThis["construc"+t(1197)][t(633)]||e.NsBjY(t(1637)+"d",typeof window)&&e.dYmNr===window[t(1447)+t(1197)][t(633)])&&e[t(1077)](e[t(1852)],typeof document),Rn=e.TeQup(e.viCPr,typeof globalThis)&&(e[t(1375)](e.rgRke,globalThis[t(1447)+t(1197)][t(633)])||e[t(1267)](e[t(1358)],globalThis[t(1447)+"tor"][t(633)]))&&e[t(244)](e[t(1852)],typeof tt),ti=(e[t(1480)](t(1637)+"d",typeof globalThis)&&e[t(1283)](e[t(1509)],globalThis[t(1447)+"tor"][t(633)])||e[t(831)](e[t(1852)],typeof globalThis)||e[t(484)](e[t(1852)],typeof globalThis)&&!!globalThis[t(1595)+t(1817)])&&e.kExrs(t(1637)+"d",typeof wx),ni=e[t(926)](t(1637)+"d",typeof globalThis)&&(e[t(1238)](e[t(1358)],globalThis["construc"+t(1197)].name)||e.CLMGL===globalThis[t(1447)+t(1197)][t(633)]||e[t(439)](e[t(1669)],globalThis[t(1447)+t(1197)][t(633)]))&&e.Eljau(e[t(1852)],typeof self),rg=e.Amdqr(e[t(1852)],typeof globalThis)&&e[t(1267)](t(1599),globalThis[t(1447)+t(1197)][t(633)])&&e[t(407)](e.viCPr,typeof global)&&e.rgRke===global[t(1447)+"tor"].name&&e[t(1477)](e.viCPr,typeof process)&&!!process[t(214)];class Ea{constructor(){let n=t,s={cOgRE:function(l,f){return e.LvbsS(l,f)},eMQiE:e[n(1152)],mugKl:e[n(1554)],GnKlb:function(l,f,g){return e[n(743)](l,f,g)},AGoHQ:function(l,f){return l===f},TmGcj:function(l,f,g,v){return e[n(1046)](l,f,g,v)}};if(e[n(1837)](e[n(948)],n(1596))){let{pingInterval:l,pingFrequency:f}=this[n(1448)];if((_0xe0276d.data==="hi"&&s[n(542)](s[n(1192)],f)||s[n(1208)]===f)&&(this[n(689)+n(1289)](),this.emit(n(1045)+n(920)+"s",n(707)),this[n(602)+n(1135)+"Id"]=s.GnKlb(_0x7e2897,this[n(1531)][n(415)](this),l)),s.AGoHQ("hi",_0x2f3446[n(1078)]))return;try{s[n(501)](_0x3785a9,this,_0x4d1861,[_0x14e45c,_0x10c779,_0x17b070,_0x5c39b3,_0x2eca91,_0x2fe06c])}catch(g){let v=s[n(580)](_0x4e17f7,"error",{message:g[n(1153)],code:_0x2900a4[n(608)+n(1440)],error:g});this["_dispatc"+n(1836)+n(442)](v)}}else this[n(825)+"rs"]={}}[t(1318)](n,...s){let l=t;if(e[l(1340)]==="ilyoF"){let f=this[l(825)+"rs"][n];if(f)f.slice().forEach(g=>g.fn.apply(g[l(709)],s));else if(e[l(583)](e[l(1297)],n)&&!this[l(955)]){let g=s[l(1270)]&&s[0];if(e.HSWDi(g,Error))throw g;let v=new Error(e[l(414)](e[l(1016)],g?e[l(1860)](e[l(1701)](" (",g[l(1153)]),")"):""));throw v.context=g,g}return this}else return this[l(1782)]?this[l(1782)].url:this[l(543)]}[t(1107)](n,s){let l=t,f={rEMDC:function(g,v){return e[F(1402)](g,v)},BYDql:function(g,v){return e.YGesZ(g,v)},CWTOv:function(g,v){return g===v}};if(e[l(372)](e[l(1809)],e[l(1809)])){if(n===void 0)this[l(825)+"rs"]={};else if(e[l(251)](void 0,s))this._listeners[n]=null;else{let g=this[l(825)+"rs"][n];if(g)for(let v=0;v<g[l(1270)];)g[v].fn===s?g.splice(v,1):++v}return this}else return _0x3b53bc.isLong(_0x2c8ce)||(_0x1cedd5=_0x1e127f.fromNumber(_0x4a1241)),cyijWT[l(1614)](this[l(968)],_0x4b78b6[l(968)])&&cyijWT[l(1552)](this[l(1831)],31)===1&&cyijWT.CWTOv(cyijWT[l(1552)](_0x1007cb[l(1831)],31),1)?!1:cyijWT[l(232)](this[l(1831)],_0x3559ea[l(1831)])&&cyijWT[l(232)](this[l(1496)],_0x4b4492[l(1496)])}on(n,s,l){let f=t;return(this._listeners[n]||(this._listeners[n]=[]))[f(394)]({fn:s,ctx:l||this}),this}}class ig extends Ea{[t(1207)+t(1623)+t(938)](n){let s=t;return n[s(534)]||n[s(1659)]?(s(338)+" "+(n[s(534)]||"")+" code: "+(n[s(1659)]||""))[s(1394)]():JSON[s(1450)+"y"](n)}constructor(n,s,l){let f=t;super(),this[f(1588)]=null,ti&&wx[f(1770)+f(1033)]&&(this[f(1588)]=wx[f(1770)+"ocket"]({url:n,protocols:s,header:l,fail:this["_createS"+f(671)+f(1280)][f(415)](this),success:this[f(380)+f(1484)+f(441)+f(836)][f(415)](this)})),Rn&&tt[f(1770)+f(1033)]&&(this[f(1588)]=tt[f(1770)+f(1033)]({url:n,protocols:s,header:l,fail:this["_createS"+f(671)+f(1280)].bind(this),success:this["_createS"+f(1484)+"cessHand"+f(836)][f(415)](this)}))}[t(380)+t(1484)+"cessHand"+t(836)](){let n=t;Promise[n(322)]()[n(1758)](()=>{let s=n;this[s(1216)+s(1006)]()})}["_createS"+t(671)+t(1280)](n){let s=t,l={mPsNM:function(f,g,v){return e.OyaXT(f,g,v)},CfKLn:e.rlNRt,xLYOS:e[s(1675)]};Promise[s(322)]()[s(1758)](()=>{let f=s,g=l[f(993)](lt,l[f(1185)],{message:this[f(1207)+f(1623)+"age"](n)});this[f(1318)](l[f(1185)],g);let v=l[f(993)](_t,l[f(371)],{reason:this["_formatE"+f(1623)+f(938)](n)});this[f(1318)](l[f(371)],v)})}["_addWsLi"+t(1006)](){let n=t,s={XQUne:n(1153),RfFMe:function(l,f,g){return l(f,g)},oznfH:function(l,f,g){return e[n(1638)](l,f,g)}};this._socket[n(491)](l=>{let f=n;if(e[f(1402)](e[f(1245)],e[f(1245)]))return this._qosDB?.[f(1463)](_0x47aab9);this[f(1318)](e[f(1772)],ml(e[f(1772)],{...l,data:l.errMsg||""}))}),this[n(1588)][n(1864)](l=>{let f=n;this[f(1318)](e[f(1675)],e[f(1014)](_t,e.FrXxQ,{...l}))}),this[n(1588)][n(858)+"e"](l=>{let f=n;this[f(1318)](s[f(1400)],s[f(1723)](gl,s.XQUne,{...l}))}),this[n(1588)][n(721)](l=>{let f=n;this[f(1318)](f(1229),s[f(666)](lt,f(1229),{...l,message:l[f(534)]||""}))})}[t(1598)](n){let s=t,l={DFmoc:e[s(1297)],lYUWh:function(f,g,v){return e[s(1142)](f,g,v)},oqmSD:function(f,g,v){return e[s(942)](f,g,v)}};if(e.dleRe(n,Uint8Array)){let f=n.buffer[s(624)](n.byteOffset,e[s(960)](n[s(1507)+"th"],n[s(992)+"et"]));this[s(1588)]&&this[s(1588)][s(1598)]({data:f,fail:g=>{let v=s;this[v(1318)](l[v(1462)],l[v(229)](lt,v(1229),{message:this[v(1207)+"rrorMess"+v(938)](g)}))}})}else this[s(1588)]&&this[s(1588)][s(1598)]({data:n,fail:f=>{let g=s;this.emit(g(1229),l.oqmSD(lt,l[g(1462)],{message:this._formatErrorMessage(f)}))}})}[t(324)](n,s){let l=t;this[l(1588)]&&this[l(1588)][l(324)]({code:n,reason:s})}[t(917)+t(1048)](n,s){this.on(n,s)}["removeEventListe"+t(376)](n,s){this[t(1107)](n,s)}get[t(980)+"te"](){let n=t;return this._socket[n(980)+"te"]}get[t(1854)+"pe"](){let n=t;return this._socket[n(1854)+"pe"]}set[t(1854)+"pe"](n){}get[t(616)](){let n=t;return this[n(1588)][n(616)]}get[t(1472)](){let n=t;return this[n(1588)][n(1472)]}get[t(635)+"ns"](){let n=t;return this[n(1588)][n(635)+"ns"]}get[t(1443)+t(1696)](){return 0}}function sg(a,n){let s=t;if(n)return new n(a.url,a[s(1472)]);if(e.eWGrM(ti,Rn))return new ig(a.url,a[s(1472)],a[s(268)]);if(e[s(1196)](sr,ni)&&e[s(1707)](s(1637)+"d",typeof WebSocket)&&WebSocket)return new WebSocket(a.url,a[s(1472)+"s"])}function og(a){let n=t,s=e.NtmLC.split("|"),l=0;for(;;){switch(s[l++]){case"0":if(Rn&&tt[n(1770)+"ocket"])return!0;continue;case"1":if(a)return!0;continue;case"2":return!1;case"3":if(ti&&wx[n(1770)+n(1033)])return!0;continue;case"4":if(e[n(911)](sr,ni)&&e[n(1707)](e[n(1852)],typeof WebSocket)&&WebSocket)return!0;continue}break}}function _l(a,n,s){let l=t,f={FkRMZ:l(1780)+l(943)+l(1697)+l(287)+l(240),nHnTZ:function(g,v){return g===v},pvrjn:function(g,v){return g+v}};if(e.KGYhy(e[l(1783)],e[l(1783)]))return this[l(505)][l(1717)];{let g=-1;async function v(_){let p=l;return _<=g?Promise[p(283)](new Error(f.FkRMZ)):(g=_,f[p(497)](_,s[p(1270)])?Promise[p(322)]():s[_].bind(a)(n,v[p(415)](null,f.pvrjn(_,1))))}v(0)}}function yl(a){let n=t,s={SYQns:e[n(1675)]},l=0,f=0;for(let g=0;e[n(1499)](g,a.length);++g)e[n(308)](e.tDDQb,e[n(1007)])?(f=a.charCodeAt(g),e[n(254)](f,128)?l+=1:e[n(1648)](f,2048)?l+=2:e.xEAFq(e[n(1422)](64512,f),55296)&&e.CvCuf(e.iCpYj(64512,a[n(884)+"At"](e[n(1515)](g,1))),56320)?e.XubLw(e[n(999)],n(766))?(++g,l+=4):(this[n(453)]=!0,this[n(1496)]=0|_0xfb0959,this[n(1831)]=0|_0xef6a74,this[n(968)]=!!_0x29279a):l+=3):(_0x4e95ec&&_0x3e2f20[n(917)+"Listener"](RlCvfU[n(1587)],()=>_0x460fcc()),_0x416b24&&_0x1f4fee[n(917)+n(1048)](n(1708)+n(830),()=>_0x56dfa1()));return l}function bl(a,n,s){let l=t,f={QZXhj:function(v,_){return e[F(1158)](v,_)},gTVud:function(v,_){return e[F(231)](v,_)},svYDm:function(v,_,p){return e[F(1258)](v,_,p)},KjRqH:function(v,_){return e[F(1225)](v,_)},yeQyt:function(v,_){return e[F(611)](v,_)}};if(e.ViUcC(s,n)<1)return"";let g="";for(let v=n;e[l(1830)](v,s);)if(e[l(421)](e[l(835)],"YHnIR")){let _=a[v++];if(e[l(1399)](_,127))g+=String[l(928)+l(309)](_);else if(e[l(704)](_,192)&&e[l(443)](_,224))g+=String["fromChar"+l(309)](e[l(1773)](e[l(1362)](e.HkJSx(31,_),6),e[l(1248)](63,a[v++])));else if(e.opTfO(_,224)&&e.xbSEA(_,240))g+=String["fromChar"+l(309)](e[l(1518)](e[l(1103)](e[l(770)](15&_,12),e[l(1362)](e.gjNAb(63,a[v++]),6)),e.iLztW(63,a[v++])));else if(_>=240){let p=e.uARTM(e[l(1634)](e[l(409)](e[l(623)](e[l(1312)](7&_,18),e[l(1368)](e[l(622)](63,a[v++]),12)),e[l(454)](e[l(1520)](63,a[v++]),6)),e[l(688)](63,a[v++])),65536);g+=String[l(928)+l(309)](55296+e[l(297)](p,10)),g+=String[l(928)+l(309)](e.sWtCi(56320,e[l(1601)](1023,p)))}}else{let _=0,p=_0x184e02,y=f[l(1259)](_0x3f8fcd,4);for(;f[l(1239)](p,y);){let{value:C,offset:O}=f[l(1784)](_0x59b31c,_0x210f24,p);p=O,_=f[l(1251)](f[l(1863)](_,8),0),_+=C}return{value:_,offset:y}}return g}function va(a,n,s){let l=t,f={gzOVn:function(p,y,C,O,U){return e[F(1558)](p,y,C,O,U)},jTdMo:function(p,y){return e.mKZzR(p,y)},OfWlt:function(p,y){return e[F(1823)](p,y)},QOwxy:e[l(359)]},g=s,v,_;for(let p=0;e[l(801)](p,a[l(1270)]);++p)if(v=a[l(884)+"At"](p),v<128)n[s++]=v;else if(e[l(1026)](v,2048))n[s++]=e[l(919)](v,6)|192,n[s++]=e[l(1568)](e[l(758)](63,v),128);else if(e.iLcXS(e.hsXSK(64512,v),55296)&&e[l(1306)](e[l(333)](64512,_=a.charCodeAt(p+1)),56320))if(e.LvbsS(e[l(1704)],e[l(510)]))_0x4de9bc[l(917)+l(1048)](uGmNmF[l(1786)],y=>{let C=l;uGmNmF.gzOVn(_0x19517e,uGmNmF[C(603)](_0x50b186,_0x44ed0c[C(528)]),y.oldVersion,y[C(280)+"on"],uGmNmF[C(1840)](_0x3da8e6,_0x389592[C(918)+C(1519)]))});else{let y=e.SJKuD[l(842)]("|"),C=0;for(;;){switch(y[C++]){case"0":++p;continue;case"1":n[s++]=v>>18|240;continue;case"2":n[s++]=e[l(522)](e[l(755)](63,v),128);continue;case"3":n[s++]=e[l(1642)](e[l(1034)](v>>12,63),128);continue;case"4":n[s++]=e[l(919)](v,6)&63|128;continue;case"5":v=e[l(833)](e[l(388)](65536,e[l(440)](1023&v,10)),e.KMlZN(1023,_));continue}break}}else n[s++]=e[l(522)](v>>12,224),n[s++]=e[l(1801)](e.MQNzI(e[l(420)](v,6),63),128),n[s++]=e[l(1256)](e[l(893)](63,v),128);return e[l(1654)](s,g)}async function El(a){let n=t,s={PRQte:function(l,f){return e[F(708)](l,f)}};if(e.WHBlo==typeof a)if(e.XubLw(e[n(1053)],n(1121))){let l=_0xf412c[n(463)+"g"](0,fyUBai[n(1641)](4,_0x19debb[_0x239230][n(1270)])),f=l.concat(_0x2a080b);_0x3d9df2=_0x40a5e4[n(1730)](f)}else{let l=new Uint8Array(e.mKZzR(yl,a));return va(a,l,0),l}return e[n(887)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(1572)],a[n(992)+"et"],a.byteLength)}function ag(a){let n=t;try{return e.NsBjY(e[n(520)],typeof a)&&(a instanceof ArrayBuffer||a[n(1572)]&&e[n(1546)](a[n(1572)],ArrayBuffer))||e.NsBjY(e[n(520)],typeof a)?"":(JSON[n(1056)](a),e[n(1128)])}catch{return e.WHBlo==typeof a?n(1011)+n(381)+n(1616):""}}let cg=(a,n)=>{let s=t,l={tXiPQ:function(f,g){return e[F(1475)](f,g)},XqXGP:function(f,g,v){return e.zYVNI(f,g,v)}};switch(a){case e[s(912)]:case s(1672):return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class dg{constructor(n){let s=t;this[s(880)+"ount"]=n,this.count=0}addCount(){let n=t;if(e[n(583)](e[n(1268)],e[n(1268)]))this.count++;else{let s=0,l=[];for(;e[n(1164)](s,_0x211fdb.byteLength);){let{offset:f}=e[n(1008)](_0x8a717a,_0x18d70f,s);s=f;let g={cursor_name:"",cursor:0,service:0},{value:v,offset:_}=_0x350687(_0x5b57a1,s);g[n(609)]=v,s=_;let{value:p,offset:y}=e.zdOio(_0x56e80c,_0x480e98,s);s=y,g[n(879)+"ame"]=e[n(1530)](_0x4d3935,_0x42d0e4,s,e[n(385)](s,p)),s+=p;let{value:C,offset:O}=_0x1811e0(_0xcdc765,s);g.cursor=C[n(1224)](),s=O,l[n(394)](g)}return l}}[t(261)+"chMaxCount"](){let n=t;return e[n(693)](this[n(996)],this[n(880)+n(957)])}[t(1273)+"nter"](n=0){let s=t;this[s(880)+s(957)]=n,this[s(996)]=0}}async function lg(a){let n=t,s={LuYRF:function(l,f){return e.mgwoV(l,f)},igamE:e[n(1041)],AUyxp:function(l,f,g,v){return e[n(1046)](l,f,g,v)},Hofxw:function(l,f){return e[n(257)](l,f)},huwSJ:function(l,f){return e.eBxXC(l,f)},btZSl:function(l,f){return e[n(1520)](l,f)},Yihsr:function(l,f){return e[n(1485)](l,f)},CBFdP:e[n(738)],UQsbn:e[n(1361)],PursO:e[n(1343)],pwBsc:e[n(1118)],DAgEe:function(l,f){return e[n(1545)](l,f)},wbEVn:e[n(1249)],NTNxm:function(l,f){return l(f)}};return new Promise(l=>{let f=n,g={rqgVK:function(_,p){return s[F(1367)](_,p)},SAkmw:function(_,p){return s[F(1792)](_,p)},fhZDF:function(_,p){return s[F(1491)](_,p)},zoeKo:function(_,p){return s.LuYRF(_,p)},fiZFM:function(_,p){return _<<p}};if(s.Yihsr(s[f(839)],s.CBFdP)){if(!sr)return s[f(667)](l,s[f(1051)]);try{let _=document[f(896)+f(1106)](f(545));window.frontierJSONP=p=>{let y=f;document[y(1455)][y(1461)+"ild"](_),window[y(731)+y(1388)]=void 0,s[y(667)](l,p&&p[y(1651)]||s[y(1051)])},_.type=s[f(237)],_[f(1625)]=a.replace(/^ws/,s[f(1226)])+s[f(804)];try{s[f(305)](s[f(1032)],s[f(1032)])?document[f(1455)]["appendCh"+f(821)](_):(_0x3ef61a=_0x338d45(_0x30a5ee),_0x38d801|=xmcoTK[f(706)](127&_0x263e62,21),xmcoTK[f(293)](128,_0x5484a4)&&(_0x47d14c=_0x455bf6(_0x51226f),_0x11a397=xmcoTK[f(1002)](127,_0x428546),128&_0x1139c4&&(_0x2e93f9=xmcoTK[f(352)](_0x566484,_0xf59a85),_0x335be5|=xmcoTK[f(343)](xmcoTK[f(293)](127,_0x370294),7))))}catch{document[f(1455)][f(1461)+"ild"](_)}}catch{window["frontier"+f(1388)]=void 0,s[f(1018)](l,f(549)+f(576))}}else for(var v in _0xe459c0)SaPLxt[f(325)](_0x391791,_0x7bbd4d,v,{get:_0x19d6cb[v],enumerable:!0})})}function an(a,n,s){return!!a?.[t(390)](f=>f.key===n&&f.value===s)}function or(a,n){let s=t;if(e[s(976)](e.ehdGH,e[s(1191)])){let l=this[s(1037)+s(1173)]?.["getCurre"+s(768)+"nt"](),f=this[s(1448)]["reconnec"+s(1409)+s(1313)](_0x5c9eca[s(275)],_0x4f411c[s(576)]);this[s(1575)+"hCloseEv"+s(442)](e[s(1638)](_0xa1d0cf,s(324),{code:1006,reason:_0x320d12.reason||s(1547)+s(1021)+"d, unkno"+s(1662)+s(1476)+"ame: "+l,willReconnect:f})),f&&this[s(1166)]();return}else return a?.[s(390)](l=>l[s(488)]===n)?.[s(1676)]}let Sa=null;async function ug(){let a=t;return Sa||(Sa=Promise[a(322)]().then(Ft[a(415)](Ft,e[a(676)]))),Sa}class fg extends Ea{constructor(n,s){let l=t;e[l(221)](e.QGZtS,l(1036))?(super(),this[l(245)]=n,this._keyPath=s,this[l(505)]=void 0,this[l(449)+l(1024)]=null):_0x13d955.set(_0x59aca1,_0x4a3f25)}async[t(1431)](){let n=t;if(e.BPLXo(n(1030),e.XKcFx)){let{type:s}=_0x22277c;this[n(1318)](s,_0x551720)}else await this[n(426)]()}async _init(){let n=t,s={MTpcb:function(l,f){return e[F(1374)](l,f)},kLmzL:n(220),EZwGV:function(l,f){return e[n(919)](l,f)},OTWZx:function(l,f){return l&f},DKygj:function(l,f){return e[n(683)](l,f)},Gdxux:function(l,f){return e[n(1801)](l,f)},fswRT:function(l,f){return l|f},VtBEO:function(l,f){return l+f},qXFOY:function(l,f){return e.AUqbC(l,f)},NFCZK:function(l,f){return l|f},JjPym:function(l,f){return e[n(1060)](l,f)},JbyMs:function(l,f,g){return e[n(788)](l,f,g)},TxFdD:e[n(1297)],HpJzz:"eqzzu",uybvz:function(l){return e[n(940)](l)}};if(e.SwSMe(e[n(1096)],e[n(224)])){if(this[n(505)])return;if(this[n(449)+n(1024)])return this[n(449)+n(1024)];try{let l=this[n(245)],f=this[n(1620)];this[n(449)+"mise"]=(async()=>{let g=n,v={ZhLib:function(_,p){return _<p},jAuid:function(_,p){return s[F(1284)](_,p)},hmOIy:function(_,p){return s[F(1147)](_,p)},JscKe:function(_,p){return s[F(1155)](_,p)},zmIvK:g(258)+g(1133),Joemq:function(_,p){return s[g(1827)](_,p)},pHBCo:function(_,p){return s[g(1264)](_,p)},rMjIb:function(_,p){return s[g(1846)](_,p)},fYOej:function(_,p){return s.qXFOY(_,p)},dbbnI:function(_,p){return s.OTWZx(_,p)},GdCcn:function(_,p){return s.NFCZK(_,p)},ovAty:function(_,p){return s[g(1162)](_,p)},gjOYD:function(_,p,y){return s[g(382)](_,p,y)},Yzbzo:s[g(621)]};if(s[g(1155)](s[g(705)],g(1201))){let{openDB:_}=await s[g(482)](ug);this[g(505)]=await _(g(731)+"_"+l,1,{upgrade(p){let y=g;if(s[y(1688)](s[y(1230)],y(220)))if(_0x407715=_0x14bdff[y(884)+"At"](_0x45d856),tbIuMP[y(360)](_0x250a9f,128))_0x8355b1[_0x5a1bba++]=_0x29ec62;else if(tbIuMP[y(360)](_0x56844f,2048))_0x501dc4[_0x48d7a9++]=tbIuMP.jAuid(_0x45fae9,6)|192,_0x3bee91[_0x2db730++]=tbIuMP[y(813)](63,_0x12bfc3)|128;else if((64512&_0x286540)===55296&&tbIuMP[y(525)](64512&(_0x2f4b14=_0x46470a[y(884)+"At"](_0x5f2440+1)),56320)){let C=tbIuMP[y(845)][y(842)]("|"),O=0;for(;;){switch(C[O++]){case"0":++_0x1b1d05;continue;case"1":_0x5f08a5[_0x3e3570++]=tbIuMP[y(868)](tbIuMP[y(813)](tbIuMP[y(1705)](_0x38f8f3,12),63),128);continue;case"2":_0x5d81c0[_0x551c95++]=tbIuMP[y(813)](tbIuMP[y(1705)](_0x415f40,6),63)|128;continue;case"3":_0x26feb6[_0x2e2578++]=tbIuMP[y(868)](tbIuMP[y(1705)](_0x55c3bb,18),240);continue;case"4":_0x17d525[_0x517bde++]=tbIuMP[y(569)](63&_0x1c0d21,128);continue;case"5":_0x383297=tbIuMP[y(697)](65536,tbIuMP[y(296)](1023&_0x50d28d,10))+tbIuMP[y(1528)](1023,_0x214e26);continue}break}}else _0x34fc0a[_0x20522c++]=tbIuMP[y(850)](tbIuMP.jAuid(_0x2bc807,12),224),_0x257776[_0x570a1e++]=tbIuMP[y(569)](tbIuMP[y(1705)](_0x235792,6)&63,128),_0xe3ecaa[_0x459799++]=tbIuMP[y(691)](63&_0x37cf7d,128);else p["createOb"+y(1584)+"e"](l,{keyPath:f})}})}else{let _="connect "+_0x30d07b+(g(1355)+g(301)+g(1665)+"ed");this[g(1575)+g(1836)+g(442)](v[g(905)](_0x53c158,v[g(1677)],{message:_,code:_0x33b494[g(1511)+g(1468)+"R"],error:_0x1d4f9f}));return}})(),await this[n(449)+n(1024)]}catch(l){console[n(1826)](l)}finally{this["_initPro"+n(1024)]=null}}else _0x3ea9d3.body["appendCh"+n(821)](_0x51b320)}async[t(1463)](n){let s=t;try{return await this[s(426)](),this[s(505)]?.[s(1463)](this._dbName,n)}catch(l){console.log(l)}}async set(n,s){let l=t;return await this._init(),this[l(505)]?.[l(1644)](this[l(245)],n)}async del(n){let s=t,l={YkNTM:function(f,g){return f+g}};if(e[s(1310)](s(631),"HUexd")){let f=this[s(1439)+s(722)][s(587)]((g,v)=>(g+=v&&v[s(1507)+"th"]||0,g),0);return l[s(806)](f,this[s(1782)]?this[s(1782)][s(1443)+s(1696)]:0)}else try{return await this[s(426)](),this._qosDB?.delete(this[s(245)],n)}catch(f){console.log(f)}}async[t(1334)](){let n=t;try{return await this[n(426)](),this[n(505)]?.clear(this[n(245)])}catch(s){console.log(s)}}async keys(){let n=t;return await this[n(426)](),this._qosDB?.[n(1266)+"ys"](this[n(245)])}async[t(1490)](){let n=t;return await this._init(),this[n(505)]?.[n(1490)](this[n(245)])}async[t(1063)](){let n=t;try{this._qosDB?.[n(324)](),this[n(505)]=void 0}catch(s){console[n(1826)](s)}}get[t(1717)](){let n=t;try{return!!this[n(505)]}catch(s){return console[n(1826)](s),!1}}}class xg{constructor(n,s){let l=t;this[l(903)]=n,this._pathKey=s,this[l(505)]=localStorage}async[t(1431)](){}get _prefix(){let n=t;if(e[n(1200)]===e[n(591)]){let l=""+_0x50fa3e.now(),f=_0xf3f7e||(_0x9d6ad3=e[n(1647)](_0x2af195,_0x5aa98f)),g=_0x227644[n(975)]()[n(558)](16).slice(-6);return e[n(626)](e.gtpnl("02"+l,f),g)}else return n(731)+"_"+this[n(903)]}async[t(1463)](n){let s=t,l=this[s(505)].getItem(this[s(1858)]);return JSON[s(1056)](e.WXOCu(l,"{}"))[n]}async set(n,s){let l=t,f=this[l(505)][l(530)](this[l(1858)]),g=JSON[l(1056)](e.NsqxE(f,"{}"));return g[s||n[this[l(213)]]]=n,this[l(505)][l(1353)](this[l(1858)],JSON[l(1450)+"y"](g)),s||n[this[l(213)]]}async del(n){let s=t,l=this[s(505)].getItem(this[s(1858)]),f=JSON[s(1056)](e[s(1196)](l,"{}"));return f[n]=void 0,this[s(505)].setItem(this[s(1858)],JSON[s(1450)+"y"](f))}async[t(1334)](){return this._qosDB.clear()}async[t(1303)](){let n=t,s={TIIhC:function(l,f){return e[F(1724)](l,f)}};if(e.xEAFq("nldsz",e[n(1210)])){let l=this._qosDB.getItem(this._prefix),f=JSON[n(1056)](l||"{}");return Object[n(1303)](f)}else return function(l,...f){let g=n,v=_0xbd2ccf[g(1417)](_0x10dc0e(this),l,...f);return _0x54c545[g(328)](v,l.sort?l[g(1244)]():[l]),gEkwyH[g(1025)](_0x48539c,v)}}async getAll(){let n=t,s=this[n(505)].getItem(this[n(1858)]),l=JSON[n(1056)](e[n(1089)](s,"{}"));return Object[n(982)](l)}[t(1063)](){return Promise[t(322)]()}get isReady(){return!!this[t(505)]}}class hg{constructor(n,s){let l=t;this[l(903)]=n,this[l(213)]=s,this._qosDB=Rn?tt:ti?wx:null}async[t(1431)](){}get _prefix(){return t(731)+"_"+this._DBName}async get(n){let s=t,l={vnZgR:function(f,g){return e.EAuFx(f,g)}};if(e[s(1781)](s(1242),e[s(456)])){let f=this._qosDB[s(710)+"geSync"](this._prefix);return JSON[s(1056)](e[s(872)](f,"{}"))[n]}else if(FJKKBX[s(1464)](_0x3c2a7a,_0x155c8c))return _0x5c32e8}async[t(328)](n,s){let l=t,f=this._qosDB["getStora"+l(1187)](this[l(1858)]),g=JSON[l(1056)](e[l(790)](f,"{}"));return g[s||n[this._pathKey]]=n,this[l(505)][l(1401)+l(1187)](this[l(1858)],JSON[l(1450)+"y"](g)),s||n[this[l(213)]]}async[t(1181)](n){let s=t,l=this._qosDB[s(710)+s(1187)](this[s(1858)]),f=JSON.parse(e[s(790)](l,"{}"));return f[n]=void 0,this[s(505)][s(1401)+s(1187)](this[s(1858)],JSON[s(1450)+"y"](f))}async[t(1334)](){let n=t;return this[n(505)]["clearSto"+n(1635)]()}async[t(1303)](){let n=t,s={qQamu:function(l,f){return e[F(1110)](l,f)},jpAoO:function(l,f){return e[F(446)](l,f)}};if(e.AOdiR(e[n(432)],e[n(432)])){let l=this[n(505)]["getStora"+n(1779)+"nc"](this[n(1858)]),f=JSON[n(1056)](e[n(790)](l,"{}"));return Object.keys(f)}else{if(xsMtSE[n(405)](_0x1f5c82,-_0x26fb14))return _0xf8bab9;if(xsMtSE[n(744)](_0xc73cbf+1,_0x167428))return _0x537c03}}async[t(1490)](){let n=t,s=this[n(505)][n(710)+n(1779)+"nc"](this._prefix),l=JSON[n(1056)](e[n(619)](s,"{}"));return Object[n(982)](l)}[t(1063)](){let n=t,s={pqHIw:function(l,f){return e[F(1639)](l,f)}};if(e[n(931)](e[n(1445)],e.pUIPO))return Promise.resolve();s[n(925)](_0x5ab672,this._pingPongTimeoutId),s[n(925)](_0x48f101,this[n(929)+n(862)+n(523)]),this[n(602)+n(1135)+"Id"]=null,this[n(929)+n(862)+n(523)]=null}get isReady(){return!!this[t(505)]}}function vl(a,n){let s=t;if(e[s(1843)]===e[s(1843)]){if(e[s(735)](Rn,Rn))return new hg(a,n);if(e[s(1435)](sr,ni)&&e[s(1707)](e.viCPr,typeof indexedDB))return new fg(a,n);if((sr||ni)&&e[s(1077)](e[s(1852)],typeof localStorage))return new xg(a,n);throw new Error(e[s(1721)])}else return _0x39af29.apply(ylhYic[s(531)](_0x2da1f6,this),_0x5a76ca),ylhYic[s(946)](_0x40241f,_0x41f71d[s(1463)](this))}class pg{constructor(){let n=t;this["_interva"+n(773)+"Id"]=null,this[n(1332)+"l"]=36e5,this[n(505)]=e[n(1258)](vl,e.zJLuq,e[n(1275)])}async[t(1332)+"lFlush"](){let n=t;e.TIbwE(clearInterval,this[n(1332)+"lTimeoutId"]),this[n(1332)+n(773)+"Id"]=e[n(404)](setInterval,()=>{let s=n;e.jLbUW(e[s(898)],e[s(898)])?_0x5211ec[s(322)]().then(()=>{let l=s;this[l(1216)+l(1006)]()}):this[s(897)+"ired"]()},this[n(1332)+"l"])}async openDB(){let n=t;await this[n(505)][n(1431)]().then(()=>{this._intervalFlush()})}async[t(897)+t(1432)](){let n=t;(await this[n(505)]?.[n(1490)]()||[]).filter(({timestamp:f})=>f<Date.now())[n(1798)](f=>{let g=n;this._qosDB?.[g(1181)](f[g(374)+"id"])})}async del(n){let s=t;return this[s(505)]?.[s(1181)](n)}async set(n,s){let l=t;return this[l(505)]?.[l(328)]({message_id:n,timestamp:s})}async get(n){return this[t(505)]?.get(n)}async[t(1063)](){let n=t,s={lArMZ:function(l,f){return e[F(1861)](l,f)}};if(e[n(469)](e.EywTT,e[n(1305)])){let l=_0x4ccf5d[n(1417)](avLdrO[n(1168)](_0x1b581e,this),_0x42832a,..._0x4a470b);return _0x4dff3c.set(l,_0x462515[n(1244)]?_0x48cc61[n(1244)]():[_0x575309]),avLdrO[n(1168)](_0x57463c,l)}else e[n(489)](clearInterval,this["_interva"+n(773)+"Id"]),await this[n(505)]?.[n(1063)]()}get isReady(){let n=t;return e[n(251)](e[n(473)],e[n(783)])?(_0x4f761d[n(1590)+"t8"]?_0x421bf7[n(1590)+"t8"](_0x1a5b23,_0x4cc61b):_0x5e44b4[_0x2343c9]=e[n(1189)](255,_0x2e1263),e[n(452)](_0x536f47,1)):this[n(505)]?.[n(1717)]}}function Ia(a){let n=t;if(e.vTFnY(e[n(1397)],e[n(572)])){let s=!!this[n(1448)][n(1372)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=an(a[n(1153)][n(268)],e.AMWBy,"2"),f=l&&e[n(1359)](an,a[n(1153)][n(268)],e[n(1744)],"1"),g=l&&e[n(1819)](an,a[n(1153)][n(268)],n(817)+"er_is_ack","1"),v=g?e[n(1788)](or,a[n(1153)].headers,e[n(802)])?.[n(842)](",").filter(Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:g,ackMsgIds:v}}else{let s={QBhBP:function(l,f,g){return e[n(1346)](l,f,g)}};return new _0xbaa79e(l=>{let f=n;s[f(1457)](_0xe8115d,l,this[f(345)+"rvalValue"](_0x359820))})}}async function Sl(){let a=t,n={yETQj:function(s,l,f,g){return e[F(1046)](s,l,f,g)},zDFla:function(s,l,f){return s(l,f)},wxDuw:e[a(1297)]};if(e[a(292)](e[a(1246)],e.pVaGF))return this[a(1649)+a(856)]||(this[a(1649)+a(856)]=new pg),this[a(1649)+a(856)].isReady||await this["_QoSMana"+a(856)][a(1431)](),this._QoSManager;try{n[a(700)](_0x5bf63d,this,_0x20a73e,[_0x470ade,_0x24222c,_0x4e8d55])}catch(s){let l=n[a(965)](_0x52ec3c,n[a(1073)],{message:s[a(1153)],code:_0x542389.OPEN_ERROR,error:s});this[a(1575)+a(1836)+a(442)](l)}}async function gg(a,n){let s=t,{enableAutoAck:l}=this._options,f=e[s(1359)](an,a[s(1153)][s(268)],e.eeJJI,"1"),g=e[s(1359)](an,a[s(1153)][s(268)],e[s(1345)],"1"),v=Ia.call(this,a);if(e[s(876)](l,f)){let{SeqID:_,LogID:p,service:y,LogIDNew:C,method:O}=a[s(1153)];this[s(1271)]({SeqID:_,LogID:p,LogIDNew:C,service:y,method:O,headers:[{key:e.bIaFL,value:"1"},{key:e[s(1469)],value:e[s(625)](C,"")},{key:e[s(1050)],value:"0"}]})}g&&!v.isQoSAck&&this[s(1575)+s(1693)+s(1583)](a),n()}async function mg(a,n){let s=t;this[s(227)](e[s(265)],a[s(1153)]),e[s(940)](n)}async function wg(a,n){let s=t,l={pnRKJ:function(f,g,v){return e[F(246)](f,g,v)},rDDcQ:function(f,g){return e[F(1479)](f,g)},myDtf:function(f,g){return e[F(262)](f,g)},CekFu:function(f,g){return e.CTcUO(f,g)},iQHWE:function(f,g){return e[F(1821)](f,g)},RGcLg:function(f,g){return e[F(1369)](f,g)},hKgud:function(f,g){return f&g},JcWaF:function(f,g){return e[F(626)](f,g)},DgzsO:function(f,g){return f>>g}};if(e[s(418)](s(1678),e[s(1124)])){let f=e[s(1647)](rn,await e[s(1787)](El,a.data));try{if(e[s(683)](e[s(212)],e[s(212)]))if(f[s(1766)]instanceof Uint8Array){let g=e[s(1546)](this._options[s(1309)+s(464)],Object)?{force:!!this[s(1448)][s(1309)+s(464)][s(1182)],encoding:this._options[s(1309)+"ncoding"][s(1325)]?this._options[s(1309)+"ncoding"][s(1325)].replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this[s(1448)][s(1309)+s(464)]?this[s(1448)][s(1309)+s(464)][s(323)](/\s/g,"").toLowerCase():""},v=f["payloadE"+s(464)]?f[s(1309)+s(464)].replace(/\s/g,"")[s(1652)+"ase"]():"",_=e[s(1546)](this[s(1448)][s(1774)+s(597)],Object)?{force:!!this[s(1448)][s(1774)+"ype"].force,type:this._options[s(1774)+s(597)][s(1102)]?this[s(1448)][s(1774)+"ype"][s(1102)][s(323)](/\s/g,"")[s(1652)+s(760)]():""}:{force:!1,type:this[s(1448)]["payloadT"+s(597)]?this[s(1448)][s(1774)+s(597)].replace(/\s/g,"")[s(1652)+"ase"]():""},p=f[s(1774)+s(597)]?f[s(1774)+s(597)][s(323)](/\s/g,"")[s(1652)+s(760)]():"",y=_[s(1182)]?_[s(1102)]:p||_[s(1102)],C=g[s(1182)]?g.encoding:v||g[s(1325)],O=[e[s(1117)],e[s(1128)],e.WPGYM,s(340)],U=[s(1793)+"e",e[s(1281)]];this[s(1448)][s(391)+s(487)+"extPayload"]&&O[s(1221)](y)&&(!C||U[s(1221)](C))?f[s(1504)+s(1206)]=e.VTnJK(bl,f[s(1766)],0,f[s(1766)][s(1507)+"th"]):f[s(1504)+"oad"]=""}else f[s(1504)+s(1206)]="";else jdXpyZ[s(703)](_0x45f316,_0x1bde6c,50),jdXpyZ.pnRKJ(_0x995e0e,_0x301338,_0x4b46ef)}catch(g){f["textPayl"+s(1206)]="",console[s(1826)](g)}a.message=f,e[s(819)](n)}else{let f=jdXpyZ[s(1506)](jdXpyZ.myDtf(jdXpyZ[s(638)](jdXpyZ.iQHWE(7,_0x3964f3),18)|jdXpyZ[s(1581)](63&_0x425e21[_0x3e3c2b++],12),jdXpyZ.CekFu(jdXpyZ[s(1348)](63,_0x255cd6[_0x151590++]),6)),63&_0x2135d3[_0x38533f++])-65536;_0x1b70b3+=_0x50f959[s(928)+s(309)](jdXpyZ[s(1533)](55296,jdXpyZ.DgzsO(f,10))),_0x359af6+=_0x40d8eb["fromChar"+s(309)](jdXpyZ.JcWaF(56320,1023&f))}}function _g(a,n,s){let l={TWaOJ:function(p,y){return e.bFnXc(p,y)},Lsyis:function(p,y){return e[F(357)](p,y)},hMTCP:function(p,y){return e[F(820)](p,y)},hYkob:function(p,y){return p(y)},HjuSd:function(p,y){return e.NvubG(p,y)},tuhOt:function(p,y){return e.oacfA(p,y)},QwACZ:function(p,y){return e[F(461)](p,y)}},f=e.QOXNY(s,8192),g=f>>>1,v=null,_=f;return function(p){let y=F;if(l[y(1042)](p,1)||p>g)return l[y(1219)](a,p);l[y(1441)](_,p)>f&&(v=l.hYkob(a,f),_=0);let C=n[y(1417)](v,_,_+=p);return l[y(1683)](7,_)&&(_=l[y(782)](l[y(1740)](7,_),1)),C}}let yg=4294967295;function bg(a,n,s){let l=t;if(e[l(1594)](l(329),l(753))){let f=new _0x2a4063(e.QiVSy(e[l(784)](_0x3231c3[e[l(1169)](_0x17590a,4)],24)|_0x1d6682[_0x412d89+5]<<16|_0x128e03[_0x5d1b40+6]<<8,_0xb4e7ce[_0x650922+7]),e[l(461)](e[l(823)](e[l(1642)](e.nnHSB(_0x304141[e[l(1437)](_0x362fec,0)],24),_0x36db43[e[l(655)](_0x491754,1)]<<16),_0x15d02a[e[l(1009)](_0x3c27ad,2)]<<8),_0x1a5ef5[e[l(1810)](_0x51217c,3)]),!0);return _0x32870d+=8,{value:f,offset:e[l(562)](_0x109822,8)}}else return e[l(509)](RangeError,e[l(1116)](e[l(1629)](l(1415)+l(271)+"ge: "+a+e[l(1742)],e.eWGrM(n,1)),e[l(1203)])+s)}function Eg(a,n,s){let l=t;if(e[l(1328)](e[l(1329)],e[l(1329)])){if(s>yg)throw new Error(e.jOtbp);let f=3;for(;e[l(1260)](f,0);){let g=e[l(241)](255,s);ka(g,a,e[l(478)](n,f)),s>>>=8,f--}return e[l(478)](n,4)}else return this._socket.binaryType}function vg(a,n){let s=t;if(e[s(1237)](s(1691),e[s(1712)])){let l=0,f=n,g=e[s(428)](n,4);for(;e[s(1351)](f,g);){let{value:v,offset:_}=Aa(a,f);f=_,l=e[s(1741)](e[s(1797)](l,8),0),l+=v}return{value:l,offset:g}}else{let l=_0x47ce0e[s(884)+"At"](_0x5493e5);e[s(693)](l,55296)&&l<=56319&&e.FHmdy(e.NAZcn(_0xccc08b,1),_0x26e8df)&&(l=e[s(1732)](e.PBbLr(l<<10,_0xd09583[s(884)+"At"](++_0x5263a3)),56613888)),e[s(737)](l,128)?_0x4f24a4[_0x36c650++]=l:(e[s(327)](l,2048)?_0xd39cae[_0x1fe67c++]=e.xakps(l>>6,31)|192:(e[s(663)](l,65536)?_0x57bacf[_0x4c519c++]=e[s(1628)](e[s(420)](l,12),15)|224:(_0x2c4187[_0x357a3a++]=l>>18&7|240,_0x631a26[_0x18864b++]=e[s(919)](l,12)&63|128),_0x4057ae[_0x75783f++]=e[s(330)](e[s(290)](l>>6,63),128)),_0x3624eb[_0x439928++]=e[s(475)](e[s(1248)](63,l),128))}}function Sg(a,n,s){let l=t;if(e.ePtLU("PYsvG",e[l(695)]))this[l(337)+"T"]||this[l(1762)+"X"]?this[l(344)+l(701)+l(565)]():this[l(1748)+"er"]&&this[l(302)+l(577)+"Listener"]();else{let f=e[l(1209)][l(842)]("|"),g=0;for(;;){switch(f[g++]){case"0":if(n[l(1674)+"e"])return e.ZNiFD(n[l(1674)+"e"](a,s),s);continue;case"1":if(!a)return s;continue;case"2":if(n.write)return e[l(1395)](n[l(904)](a,s),s);continue;case"3":return e.TgqEJ(e[l(1530)](va,a,n,s),s);case"4":if(e[l(801)](a[l(1270)],40))return e[l(1046)](va,a,n,s)+s;continue}break}}}function Ig(a,n){let s=t,l=new he(e.KvWSg(e[s(1277)](e.yZzFy(e.QTddH(a[e.oWmcE(n,4)],24),e.Nmetx(a[e.ZidwK(n,5)],16)),e[s(321)](a[e[s(960)](n,6)],8)),a[e[s(1146)](n,7)]),e[s(1157)](e.KOwtv(e.pIfjz(e[s(454)](a[e[s(1131)](n,0)],24),a[e[s(626)](n,1)]<<16),a[n+2]<<8),a[e[s(1670)](n,3)]),!0);return n+=8,{value:l,offset:n+8}}function Ag(a,n,s){let l=t;if(e[l(1522)](l(1066),e[l(885)]))this[l(880)+l(957)]=_0x47167c,this[l(996)]=0;else{let f=a.low,g=a[l(1831)];return n[s]=e.DMdSA(g,24),n[s+1]=e.sOPZv(e[l(720)](g,16),255),n[e[l(1017)](s,2)]=e[l(1618)](e.zZPVe(g,8),255),n[e[l(1116)](s,3)]=e.abBbT(255,g),n[e[l(395)](s,4)]=f>>>24,n[s+5]=e.Cygkv(e[l(1188)](f,16),255),n[e[l(388)](s,6)]=e.iLztW(e[l(1308)](f,8),255),n[s+7]=255&f,s+=8,s}}function Aa(a,n){let s=t;return a[s(1862)+"8"]?{value:a[s(1862)+"8"](n),offset:n+1}:{value:e.WjAZY(255,a[n]),offset:e[s(1357)](n,1)}}function ka(a,n,s){let l=t;return n[l(1590)+"t8"]?n[l(1590)+"t8"](a,s):n[s]=e[l(1165)](255,a),s+1}let kg=function(a){return new Uint8Array(a)},Tg=e[t(407)](e.viCPr,typeof Buffer)?Buffer[t(1791)+t(263)]:_g(kg,Uint8Array.prototype[t(459)]),Cg=16,Ta=32;function Pg(a){let n=t,s=0,l={};for(let f=0;e[n(1495)](f,a[n(1270)]);f++)l[a[f][n(879)+"ame"]]=e.WFCoH(yl,a[f][n(879)+n(584)]),s+=14+l[a[f][n(879)+"ame"]];return[s,l]}function Il(a,n,s){let l=t,[f,g]=e[l(1475)](Pg,a),v=e[l(1737)](Tg,f),_=0;return a.forEach(p=>{let y=l,C=("9|4|10|6"+y(906)+y(675)).split("|"),O=0;for(;;){switch(C[O++]){case"0":_=e.Pshzm(Sg,p[y(879)+y(584)],v,_);continue;case"1":console[y(1826)](e[y(995)],_);continue;case"2":console[y(1826)](e[y(1067)],_);continue;case"3":_=e[y(1530)](Ag,he[y(1603)+"er"](p[y(1240)]||n),v,_);continue;case"4":_=e.SRIxF(ka,0,v,_);continue;case"5":_=e[y(1530)](ka,g[p["cursor_n"+y(584)]],v,_);continue;case"6":_=e.LPldx(Eg,v,_,p[y(609)]||0);continue;case"7":console[y(1826)](y(633),_);continue;case"8":console[y(1826)](e[y(230)],_);continue;case"9":console.log(y(1231)+y(1702),p,p[y(609)]);continue;case"10":console[y(1826)](e[y(1039)],_);continue}break}}),{frameType:Ta,headers:[{key:e[l(1062)],value:s}],payload:v}}function Rg(a){let n=t,s=0,l=[];for(;e[n(254)](s,a[n(1507)+"th"]);){let{offset:f}=e[n(1339)](Aa,a,s);s=f;let g={cursor_name:"",cursor:0,service:0},{value:v,offset:_}=e[n(1347)](vg,a,s);g[n(609)]=v,s=_;let{value:p,offset:y}=e.kCWHB(Aa,a,s);s=y,g[n(879)+"ame"]=e.pWXIk(bl,a,s,e[n(1262)](s,p)),s+=p;let{value:C,offset:O}=e[n(788)](Ig,a,s);g.cursor=C[n(1224)](),s=O,l[n(394)](g)}return l}function Dg(){let a=t;return{frameType:Ta,headers:[{key:"cursor_f"+a(1560),value:a(1190)+"_EXIST"}],payload:void 0}}class Og{constructor(n,s,l){let f=t;this[f(1295)+f(986)]=n,this[f(922)+f(318)]=s,this[f(1439)+"Strategy"]=l,this[f(505)]=e[f(788)](vl,this[f(1295)+f(986)],f(879)+f(584))}async[t(1431)](){await this._qosDB.openDB()}async[t(1606)+"rs"](){let n=t;if(!this[n(505)][n(1717)])return;let s=this[n(1439)+"Strategy"],l=await this[n(505)].getAll();switch(console.log(e[n(228)],l),s){case e[n(1080)]:return l&&l[n(1270)]?Il(l,0,this[n(922)+n(318)]):void 0;case e[n(998)]:return;case e[n(1655)]:return l&&l.length?Il(l,0,this["_cursorF"+n(318)]):e[n(985)](Dg)}}async[t(328)](n,s,l){let f=t;return console[f(1826)](f(1689),n,s,l),this[f(505)][f(328)]({cursor_name:n,cursor:s,service:l})}async[t(384)+"rs"](n){let s=t,l=e[s(877)](Rg,n);for(let f of l)console[s(1826)](e.WWTNZ,l),await this[s(505)][s(328)](f)}async[t(1463)](n){let s=t;return e[s(221)](e[s(1486)],s(424))?(await this[s(505)][s(1463)](n))?.[s(1240)]:this[s(337)+"T"]||this._isMiniWX?this[s(1687)+s(320)+s(1562)]:(this[s(1748)+"er"]||this._isWorker)&&this._options[s(774)+s(1604)+s(1092)]?_0x2dca8c[s(1621)]:!0}async[t(1063)](){let n=t;if(e[n(1761)](n(1178),n(1178)))return _0x4853aa[n(322)]();await this._qosDB[n(1063)]()}[t(350)+t(507)+t(1795)](n){let s=t;this[s(922)+s(318)]=n}get[t(1717)](){let n=t;return this[n(505)][n(1717)]}}let Lg=e.TUXDV;async function Al(a){let n=t;if(!this[n(1448)].enableQoS)return null;let{aID:s,fpID:l,messageStrategy:f}=this[n(1448)],g=e.JfQyc(a,Lg);try{return this["_cursorM"+n(797)]?a&&this[n(278)+"anager"][n(350)+n(507)+n(1795)](a):this[n(278)+n(797)]=new Og(l+"_"+s+"_"+g,g,f),this[n(278)+n(797)].isReady||await this[n(278)+"anager"][n(1431)](),this["_cursorM"+n(797)]}catch{return null}}async function Ng(a,n){let s=t,l=an(a[s(1153)][s(268)],e[s(483)],"-1"),f=e[s(1046)](an,a[s(1153)].headers,s(757),"1"),g=e[s(270)](or,a[s(1153)].headers,e[s(1544)]),v=e[s(1785)](Number,e[s(1301)](or,a[s(1153)].headers,e.QRXnO))||0,_=Ia[s(1417)](this,a),p=e[s(1029)](an,a[s(1153)][s(268)],e[s(1627)],"2"),y=e.IACoX(or,a[s(1153)][s(268)],s(457)+s(226)+"e"),C=e.zoWbb(Number,e.sqPHO(or,a[s(1153)][s(268)],"x-msg-cu"+s(647)+"ue"));if(_[s(1525)])return e[s(1775)](n);let O=_[s(615)+s(781)]?await Sl[s(1417)](this):null;if(e[s(468)](a.message[s(609)],0)&&f&&!l||a.message.service>0)if(e.niNnJ(s(1453),s(1453))){if(g&&_[s(615)+"sage"]&&O)return!!!await O[s(1463)](g)&&(this[s(1575)+s(1144)+s(1176)](a),await O[s(328)](g,e[s(1502)](Date[s(713)](),v))),e.jAGhc(n);if(p){let U=await Al[s(1417)](this);if(!U){if(e[s(1485)](s(865),s(865)))return this[s(1575)+s(1144)+s(1176)](a),e.zACJw(n);{let ae=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(_0x4f5bbe),st=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[s(973)](_0x514d54);return ae?e.iFwxr(_0x119315,_0x6a0e09):st?e[s(1579)](_0x47bc17,_0x563053):e.CPCVI}}let H=await U[s(1463)](y)??-1;if(e.xbSEA(H,C))this[s(1575)+s(1144)+s(1176)](a),U[s(328)](y,C,a[s(1153)][s(609)]);else throw new Error(s(1274)+s(1715)+s(1058)+C+(" larger "+s(1776)+s(714)+"r ")+H);return e[s(598)](n)}return this[s(1575)+s(1144)+s(1176)](a),e[s(940)](n)}else return this[s(1588)][s(616)]}async function Mg(a,n){let s=t,l={fljDn:function(f,g){return e[F(1320)](f,g)},fthkM:function(f,g){return f|g},PHhkz:function(f,g){return e[F(560)](f,g)},PBKIw:function(f,g){return f===g},OKsua:function(f,g){return e[F(844)](f,g)},OeELx:function(f,g){return e[F(644)](f,g)},lTnPJ:function(f,g){return e[F(1442)](f,g)},OqyHu:function(f,g){return e[F(801)](f,g)},hILLD:function(f,g,v){return f(g,v)},tHkqE:function(f,g){return f+g},cmdeZ:function(f,g){return f&g},NOvMV:function(f,g){return e[F(1322)](f,g)},ByXZF:function(f,g){return e.sdXTv(f,g)},cdPoc:function(f,g){return f&g},BlgWk:function(f,g){return e.rLcuH(f,g)},UicTJ:function(f,g){return e.DMdSA(f,g)},jTRkQ:function(f,g){return e[F(393)](f,g)},zcIsi:function(f,g){return e[F(702)](f,g)},ZqHDA:function(f,g){return f!==g},JpFxg:function(f,g){return e[F(461)](f,g)},xUaMi:function(f,g){return e.lNfyP(f,g)},TbqbO:function(f,g){return e.zbUfG(f,g)},vNmEw:function(f,g){return e[F(1685)](f,g)},UOmOl:function(f,g){return f+g},GEygs:function(f,g){return f|g},LSHft:function(f,g){return e[F(1653)](f,g)},WIuij:function(f,g){return e.OvHnz(f,g)},zgoaG:function(f,g){return f!==g},tJquI:function(f,g){return e.nNfUd(f,g)},Bmwmh:function(f,g){return e[F(1768)](f,g)},vgJnF:function(f,g){return e.DMdSA(f,g)},VTCFM:function(f,g){return f>>>g},BvkrC:function(f,g){return e[F(1539)](f,g)},VIlJi:function(f,g){return e[F(1577)](f,g)},XMbld:function(f,g){return e.CaXGx(f,g)}};if(s(1505)===s(479)){let f=YhTktM[s(910)](_0x5f0bcd[s(1496)],0),g=YhTktM.fljDn(YhTktM[s(1535)](_0x196c90[s(1496)]>>>28,YhTktM.PHhkz(_0x39540f[s(1831)],4)),0),v=YhTktM[s(910)](_0x510222.high,24),_=YhTktM.PBKIw(0,v)?YhTktM.OKsua(0,g)?YhTktM[s(983)](f,16384)?YhTktM.lTnPJ(f,128)?1:2:YhTktM[s(983)](f,2097152)?3:4:YhTktM[s(312)](g,16384)?YhTktM.OeELx(g,128)?5:6:YhTktM[s(312)](g,2097152)?7:8:YhTktM.OqyHu(v,128)?9:10,p=YhTktM[s(1288)](_0x497f75,_0x2eaf7b,_),y=_0x1818af[s(1223)];switch(_){case 10:y[YhTktM[s(539)](p,9)]=YhTktM[s(387)](YhTktM.fljDn(v,7),1);case 9:y[p+8]=YhTktM.NOvMV(9,_)?YhTktM[s(1611)](128,v):YhTktM[s(264)](127,v);case 8:y[YhTktM[s(1183)](p,7)]=_!==8?YhTktM[s(754)](g,21)|128:YhTktM[s(891)](YhTktM.zcIsi(g,21),127);case 7:y[YhTktM[s(1183)](p,6)]=YhTktM[s(1138)](7,_)?YhTktM[s(1549)](YhTktM[s(1658)](g,14),128):YhTktM[s(1140)](g,14)&127;case 6:y[p+5]=_!==6?YhTktM[s(1535)](YhTktM.UicTJ(g,7),128):YhTktM.cmdeZ(YhTktM.vNmEw(g,7),127);case 5:y[YhTktM[s(502)](p,4)]=YhTktM[s(1498)](5,_)?YhTktM.GEygs(128,g):YhTktM.LSHft(127,g);case 4:y[p+3]=YhTktM[s(719)](4,_)?f>>>21|128:YhTktM[s(1789)](f,21)&127;case 3:y[YhTktM[s(1183)](p,2)]=YhTktM.zgoaG(3,_)?YhTktM[s(462)](f,14)|128:YhTktM[s(815)](YhTktM[s(1236)](f,14),127);case 2:y[YhTktM[s(539)](p,1)]=_!==2?YhTktM[s(1535)](YhTktM[s(786)](f,7),128):YhTktM[s(849)](YhTktM[s(1391)](f,7),127);case 1:y[p]=YhTktM[s(255)](1,_)?YhTktM[s(1611)](128,f):YhTktM.BvkrC(127,f)}}else{let f=Ia[s(1417)](this,a);if(!f["isQoSMes"+s(781)])return e[s(1428)](n);let g=await Sl[s(1417)](this);if(f[s(222)+"anupMess"+s(938)]&&f[s(1294)+"s"][s(1270)])for(let v of f[s(1294)+"s"])await g[s(1181)](v);e[s(940)](n)}}async function Bg(a,n){let s=t,l={jSrVG:function(p,y){return e[F(1578)](p,y)},moHbF:function(p,y){return p>>>y},AvvZk:function(p,y){return p<y},zbonS:function(p,y,C,O){return p(y,C,O)},UNBGU:function(p,y){return e[F(1122)](p,y)},NbaiF:function(p,y){return e[F(1381)](p,y)},YNsgJ:function(p,y){return p&y},WtnPo:function(p,y){return p>>>y}},f=a.message[s(939)+"e"]===Cg,g=e[s(931)](a[s(1153)][s(939)+"e"],Ta);if(!f&&!g)return n();let v=e[s(889)](or,a[s(1153)].headers,"cursor_f"+s(1560));if(!v)return n();let _=await Al[s(1417)](this,v);if(!_)return e[s(819)](n);if(f){let p=await _.getCursors(),y={frameType:p?.[s(939)+"e"],SeqID:he[s(1603)+"er"](this[s(550)]++),LogID:he[s(1603)+"er"](this._options[s(1757)+s(217)]()),service:9e3,method:5,headers:p?.[s(268)],payload:p?.payload},C=e[s(476)](I,y);this[s(1782)]&&this._ws[s(980)+"te"]&&this[s(1782)][s(1598)](C)}if(g)if(e.gFQqp===s(1072)){let p=a[s(1153)][s(1766)];p&&_[s(384)+"rs"](p)}else{let p={LiVCE:function(C,O){let U=s;return LRHdeL[U(273)](C,O)},JPgaT:function(C,O){let U=s;return LRHdeL[U(1726)](C,O)},vvjXv:function(C,O){return C<<O},jOgSB:function(C,O){return C&O},vksHa:function(C,O){return C>>>O},nXnMD:function(C,O){let U=s;return LRHdeL[U(1434)](C,O)},iRjRU:function(C,O){return C>O},AoVqn:function(C,O,U,H){return LRHdeL.zbonS(C,O,U,H)},WfhPE:function(C,O){let U=s;return LRHdeL[U(1842)](C,O)},UqxRQ:function(C,O){let U=s;return LRHdeL[U(1822)](C,O)},aoQMO:function(C,O){let U=s;return LRHdeL[U(1434)](C,O)},erDWl:function(C,O){return C|O},NDUgB:function(C,O){let U=s;return LRHdeL[U(1710)](C,O)},jtuSz:function(C,O){let U=s;return LRHdeL[U(273)](C,O)},JkSUG:function(C,O){let U=s;return LRHdeL[U(1385)](C,O)},joMUA:function(C,O){let U=s;return LRHdeL[U(273)](C,O)}},y=4294967295;return function(C,O,U=!0){let H=s,ae=("2|7|8|10"+H(445)+H(883)+"0")[H(842)]("|"),st=0;for(;;){switch(ae[st++]){case"0":return{value:U?y:p[H(860)](0,y),offset:O};case"1":y=p[H(1199)](y|p[H(238)](p[H(486)](15,C[O]),28),0);continue;case"2":y=p[H(1115)](p[H(486)](127,C[O]),0);continue;case"3":if(p[H(1807)](C[O++],128))return{value:U?y:0|y,offset:O};continue;case"4":if(p[H(1807)](C[O++],128))return{value:U?y:p[H(860)](0,y),offset:O};continue;case"5":if(p[H(419)](O+=5,C.length))throw O=C.length,p[H(878)](_0x2b5dff,O,10,C.length);continue;case"6":y=p[H(533)](y,p.vvjXv(p[H(1082)](127,C[O]),14))>>>0;continue;case"7":if(p[H(1706)](C[O++],128))return{value:U?y:p[H(772)](0,y),offset:O};continue;case"8":y=p.WfhPE(y,p[H(238)](p[H(1352)](127,C[O]),7))>>>0;continue;case"9":if(p[H(1706)](C[O++],128))return{value:U?y:p[H(860)](0,y),offset:O};continue;case"10":if(C[O++]<128)return{value:U?y:p[H(1460)](0,y),offset:O};continue;case"11":y=p.JkSUG(p[H(614)](y,(127&C[O])<<21),0);continue}break}}}}let Fg=async function(a,n){let s=t;this[s(1720)]=!1,e[s(413)](clearTimeout,this["_connect"+s(1202)+s(281)]),e[s(819)](n)},zg=async function(a,n){let s=t;if(!this._ws||e[s(1764)](this._ws[s(980)+"te"],this.OPEN))return e[s(334)](n);let{pingInterval:l}=this[s(1448)];this[s(1037)+s(1173)]?.[s(341)+s(1751)+"fig"]();for(let g=0;e[s(1738)](g,this["_message"+s(722)].length);g++){let v=this[s(1439)+s(722)][g];if(e.DDJZQ(this[s(1782)].readyState,this.OPEN)&&e[s(1374)](null,v))this[s(1782)]&&this[s(1782)][s(1598)](v),this["_message"+s(722)][g]=null;else break}this[s(1439)+s(722)]=this["_message"+s(722)][s(857)](g=>!!g),this[s(602)+s(1135)+"Id"]=e[s(1366)](setTimeout,()=>this[s(1531)](),l),this[s(1575)+"hOpenEvent"](a),this._isBrowser&&this[s(1782)]&&(this[s(1782)][s(1854)+"pe"]=this["_binaryT"+s(597)]);let f=this[s(1037)+s(1173)]?.[s(1139)+"ntEndpoint"]();this[s(227)](s(365)+f+s(852)),e[s(1775)](n)},Ug=async function(a,n){let s=t,l=this[s(1037)+s(1173)]?.getCurrentEndpoint();this[s(227)](s(365)+l),e.TamQX(n)};class Hg extends Ea{constructor(n){let s=t,l={sLceG:function(_,p,y,C){return e.tNOWz(_,p,y,C)},rrUPW:function(_,p,y){return e.kCWHB(_,p,y)},dnGfK:function(_,p){return _===p},csmob:s(416),xpXyv:e[s(1109)],TeLbG:e[s(362)],qNWvk:function(_,p,y,C){return _(p,y,C)},JZmYR:function(_,p){return e[s(1561)](_,p)},GMbRB:function(_,p,y){return e[s(1492)](_,p,y)},WhurA:e[s(1675)],xlUbk:e[s(981)],NQTZw:function(_,p){return e.MVcQG(_,p)},XlKdv:function(_,p){return e[s(684)](_,p)},seDNt:function(_,p){return e[s(869)](_,p)},jnPxc:e.UWsuV,pDObE:function(_,p){return e[s(1692)](_,p)},yaUEj:function(_,p){return e.dBLlb(_,p)},wDaOp:e[s(1128)],XxofP:"applicat"+s(496)+";charset"+s(1551),UWono:e[s(1333)]};super(),this[s(1687)+s(320)+"line"]=!0,this[s(1748)+"er"]=sr,this._isNode=rg,this[s(337)+"T"]=Rn,this[s(1762)+"X"]=ti,this._isWorker=ni,this["_message"+s(722)]=[],this[s(1037)+"tManager"]=null,this[s(401)+s(1470)]=!1,this[s(1755)+"ype"]=e[s(1383)],this[s(1166)+s(1100)]=!1,this[s(1166)+s(1202)+s(281)]=null,this[s(929)+s(862)+s(523)]=null,this[s(602)+s(1135)+"Id"]=null,this[s(550)]=0,this[s(1720)]=!1,this._url="",this[s(1649)+s(856)]=null,this[s(278)+s(797)]=null,this[s(1341)+s(1090)]=null,this[s(1126)+"ls"]=s(1228),this[s(356)]=3,this.CONNECTING=0,this.OPEN=1,this[s(1276)]=2,this._onOpen=_=>{let p=s;try{l[p(659)](_l,this,_,[Fg,zg,Ug])}catch(y){let C=l.rrUPW(lt,p(1229),{message:y[p(1153)],code:on[p(1038)+"OR"],error:y});this[p(1575)+"hErrorEv"+p(442)](C)}},this[s(349)+"ge"]=async _=>{let p=s,{pingInterval:y,pingFrequency:C}=this[p(1448)];if((_[p(1078)]==="hi"&&l[p(313)](l[p(1794)],C)||l[p(313)](p(1076),C))&&(this[p(689)+p(1289)](),this[p(1318)](l[p(640)],l[p(568)]),this[p(602)+p(1135)+"Id"]=setTimeout(this[p(1531)][p(415)](this),y)),!l.dnGfK("hi",_.data))try{l.qNWvk(_l,this,_,[wg,gg,Mg,Bg,Ng,mg])}catch(O){let U=l.rrUPW(lt,p(1229),{message:O[p(1153)],code:on[p(608)+p(1440)],error:O});this[p(1575)+p(1836)+p(442)](U)}},this[s(954)]=_=>{let p=s,y=this[p(1037)+p(1173)]?.[p(261)+p(1527)+"es"](),C=this[p(1037)+p(1173)]?.[p(1139)+p(768)+"nt"]();if(y&&!_[p(1153)]){let O=p(778)+C+(" fail, m"+p(301)+p(1665)+"ed");this["_dispatc"+p(1836)+p(442)](lt(p(1229),{message:O,code:on[p(1511)+"IES_ERROR"],error:_}));return}this[p(1782)]&&e[p(840)](this[p(1782)][p(980)+"te"],this[p(474)])&&this["_disconn"+p(551)](),this[p(1575)+"hErrorEvent"](e[p(1142)](lt,e[p(1297)],{message:_[p(1153)],code:on[p(1386)+p(901)],error:_}))},this._onClose=async _=>{let p=s;this[p(1671)+p(1418)](),this[p(689)+"ngTimer"](),this[p(1227)+p(466)+"rs"](),this[p(1782)]=null,this[p(1166)+p(1100)]=!1;let y=this[p(1037)+p(1173)]?.[p(261)+"chMaxTries"]();if(!y&&this[p(303)+p(1733)]()&&!this[p(401)+"osed"]){let C=this["_endpoin"+p(1173)]?.[p(1139)+p(768)+"nt"](),O=this[p(1448)]["reconnec"+p(1409)+p(1313)](_[p(275)],_[p(576)]);this[p(1575)+p(1488)+p(442)](_t(p(324),{code:1006,reason:_[p(576)]||p(1547)+"ng failed, unkno"+p(1662)+"n, hostn"+p(252)+C,willReconnect:O})),O&&this[p(1166)]();return}if(l[p(1605)](1e3,_[p(275)])&&this["_readyCl"+p(1470)]){this[p(1575)+p(1488)+p(442)](l[p(1350)](_t,l[p(592)],{code:1e3,reason:l[p(209)]})),this[p(1037)+p(1173)]?.["resetEnd"+p(1751)+p(1084)](),this["_pingLos"+p(1090)]?.[p(1273)+p(1666)]();return}if(l.NQTZw(1e3,_[p(275)])&&y){let C=this[p(1037)+"tManager"]?.[p(1139)+p(768)+"nt"](),O=_[p(576)];O||(O=await l[p(1538)](lg,this[p(543)])),O="connecti"+p(1021)+p(1319)+O+(", hostna"+p(711))+C+(p(1622)+p(1716)+"ached"),this[p(1575)+"hCloseEv"+p(442)](_t(p(324),{code:_.code,reason:O}));let U=p(778)+C+(p(1355)+p(301)+p(1665)+"ed");this[p(1575)+p(1836)+p(442)](l.GMbRB(lt,"error",{message:U,code:on[p(1511)+p(1468)+"R"]})),this[p(1037)+p(1173)]?.[p(341)+p(1751)+p(1084)](),this[p(1341)+p(1090)]?.[p(1273)+p(1666)]();return}if(l[p(1680)](1e3,_[p(275)])&&!_.reason)if(l[p(313)]("TRjlP",l[p(342)])){let C=this[p(1037)+p(1173)]?.[p(1139)+p(768)+"nt"]();this[p(1575)+"hCloseEv"+p(442)](l[p(1350)](_t,p(324),{code:_[p(275)],reason:p(1547)+"ng faile"+p(499)+p(1662)+p(1476)+"ame: "+C})),this["_endpoin"+p(1173)]?.[p(341)+p(1751)+p(1084)](),this["_pingLos"+p(1090)]?.[p(1273)+"nter"]();return}else this.endpoints=_0x57b29a,this[p(1513)+"es"]=_0x24a412,this[p(930)+p(544)]=0,this.currentEndpointTriesCount=0;this[p(1575)+"hCloseEv"+p(442)](_),this[p(1037)+p(1173)]?.[p(341)+p(1751)+p(1084)](),this[p(1341)+"sCounter"]?.["resetCou"+p(1666)]()},this[s(397)]=null,this.onerror=null,this[s(729)+"e"]=null,this[s(582)]=null,this[s(1105)+"econnect"]=null,this[s(354)+s(672)]=null,this[s(1526)+s(219)+s(286)+"ct"]=null,this["_handleO"+s(1619)]=this[s(249)+"nLine"][s(415)](this),this[s(249)+s(1290)]=this._handleOffLine[s(415)](this),this["_handleP"+s(915)]=this["_handleP"+s(915)][s(415)](this),this[s(1356)+s(289)]=this[s(1356)+"ageShow"][s(415)](this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(559)](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(1554)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.vIKRK,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:g}=n,v=Array.isArray(f)?f:e.zHPSw(e.WHBlo,typeof f)?[f]:[];if(!v||v[s(1270)]===0)throw new Error(s(1503)+s(266)+s(630));if(!e[s(541)](og,g))throw new Error(e[s(358)]);if(Object.assign(this[s(1448)],n),this["_endpoin"+s(1173)]=new wl(v,this._options.maxRetries),this[s(1341)+"sCounter"]=new dg(this[s(1448)][s(403)+s(1425)]),this[s(1448)][s(1001)+s(1481)])if(e[s(418)](e[s(662)],e[s(662)]))this[s(1720)]=!0,this[s(1166)]();else if(MysuFu[s(1591)](_0x1907cd.payload,_0x6f7b59)){let _=this[s(1448)][s(1309)+s(464)]instanceof _0x1df69e?{force:!!this[s(1448)][s(1309)+"ncoding"][s(1182)],encoding:this._options[s(1309)+s(464)].encoding?this[s(1448)][s(1309)+"ncoding"][s(1325)][s(323)](/\s/g,"")[s(1652)+"ase"]():""}:{force:!1,encoding:this[s(1448)]["payloadE"+s(464)]?this[s(1448)]["payloadE"+s(464)][s(323)](/\s/g,"")[s(1652)+s(760)]():""},p=_0x295a49[s(1309)+"ncoding"]?_0xfa9521[s(1309)+s(464)].replace(/\s/g,"")[s(1652)+s(760)]():"",y=MysuFu[s(1756)](this[s(1448)].payloadType,_0x21dd86)?{force:!!this[s(1448)][s(1774)+"ype"][s(1182)],type:this[s(1448)][s(1774)+s(597)][s(1102)]?this[s(1448)][s(1774)+s(597)][s(1102)][s(323)](/\s/g,"")["toLowerC"+s(760)]():""}:{force:!1,type:this[s(1448)][s(1774)+s(597)]?this[s(1448)][s(1774)+"ype"][s(323)](/\s/g,"")[s(1652)+s(760)]():""},C=_0x1d2205[s(1774)+s(597)]?_0x52cba9[s(1774)+s(597)][s(323)](/\s/g,"")[s(1652)+"ase"]():"",O=y[s(1182)]?y[s(1102)]:C||y[s(1102)],U=_[s(1182)]?_[s(1325)]:p||_[s(1325)],H=["text/pla"+s(381)+s(1616),MysuFu[s(1074)],MysuFu.XxofP,s(340)],ae=[MysuFu[s(1537)],s(373)];this[s(1448)][s(391)+s(487)+s(1307)+"ad"]&&H[s(1221)](O)&&(!U||ae[s(1221)](U))?_0x179386[s(1504)+s(1206)]=MysuFu[s(659)](_0x4b2649,_0x37e563.payload,0,_0x2999df[s(1766)][s(1507)+"th"]):_0x443b14[s(1504)+s(1206)]=""}else _0xc8d1d2[s(1504)+s(1206)]="";this[s(1448)]["listenNe"+s(1604)+s(1092)]&&(this[s(337)+"T"]||this[s(1762)+"X"]?this[s(344)+s(701)+"ange"]():this[s(1748)+"er"]&&this[s(302)+"balEvent"+s(1048)]())}[t(249)+t(1619)](){let n=t;this[n(1448)]["disableA"+n(1617)+n(1101)]||this[n(401)+"osed"]||this[n(601)+n(310)]()}[t(249)+t(1290)](){let n=t;this._destroyWebSocket();let s=e[n(347)](ba,"reconnect",{message:e[n(1729)]});this[n(1526)+n(219)+"yReconnect"]&&this[n(1526)+"mediatel"+n(286)+"ct"](s)}["_initGlobalEvent"+t(1048)](){let n=t;this[n(1748)+"er"]&&window[n(917)+n(1048)](e[n(1709)],this[n(249)+n(1619)]),this._isBrowser&&window[n(917)+n(1048)](e[n(732)],this[n(249)+n(1290)]),this._isBrowser&&window[n(917)+n(1048)](e.Xnfjd,this[n(1356)+n(915)]),this[n(1748)+"er"]&&window[n(917)+n(1048)](e[n(546)],this["_handleP"+n(289)])}[t(1254)+t(577)+t(1048)](){let n=t;if(e[n(526)]===e[n(526)])this[n(1748)+"er"]&&window[n(653)+n(1523)+n(376)](e[n(1709)],this[n(249)+n(1619)]),this[n(1748)+"er"]&&window[n(653)+n(1523)+n(376)](n(1771),this[n(249)+n(1290)]),this[n(1748)+"er"]&&window[n(653)+n(1523)+n(376)](n(654),this[n(1356)+n(915)]),this[n(1748)+"er"]&&window[n(653)+n(1523)+"ner"](e.VWmsj,this["_handleP"+n(289)]);else{_0x3ac07f[n(453)](_0x4145a7)||(_0x31e90b=_0x1fcd15[n(1603)+"er"](_0x25ac2e));let s=e[n(859)](this.high,16),l=e[n(670)](65535,this[n(1831)]),f=this[n(1496)]>>>16,g=e[n(756)](65535,this.low),v=e[n(1754)](_0x317896.high,16),_=e[n(1263)](65535,_0x35bc6a.high),p=e[n(1512)](_0x2aceb4[n(1496)],16),y=e[n(1302)](65535,_0x1cb749.low),C=0,O=0,U=0,H=0;return H+=e[n(1009)](g,y),U+=e.qoLxE(H,16),H&=65535,U+=e[n(1314)](f,p),O+=e[n(726)](U,16),U&=65535,O+=l+_,C+=e[n(1493)](O,16),O&=65535,C+=e[n(1701)](s,v),C&=65535,_0xb1fa01[n(1130)](e[n(1369)](U,16)|H,e[n(1722)](C<<16,O),this[n(968)])}}[t(1356)+t(915)](n){let s=t,l={JmrNF:function(f,g){return e[F(494)](f,g)},BupTq:e.THBHZ,wGtXk:function(f,g){return e[F(269)](f,g)},CJrxz:function(f,g){return e[F(1214)](f,g)},ZOJDI:function(f,g,v){return f(g,v)},ysehC:function(f){return e[F(1574)](f)}};if(!n.persisted)if(e[s(282)](e.ciprZ,e[s(715)]))this[s(1748)+"er"]&&window[s(653)+"entListe"+s(376)](e[s(1610)],this["_handleP"+s(915)]),this[s(1748)+"er"]&&window[s(653)+s(1523)+"ner"](e[s(546)],this["_handleP"+s(289)]),this.close();else return FktREh[s(1698)](typeof _0x439cf9,FktREh[s(411)])?FktREh.wGtXk(_0x24d0ca,_0x1574d4):(FktREh[s(1541)](_0x5e5faf,_0x46136d)&&_0x1cf367(_0x54c8c6),FktREh[s(336)](_0x27a581,_0x283ae1,FktREh[s(1657)](_0x4ed18e))?new _0x5eac9b(_0x27ca6d,_0x2ab670):_0x1f2f79);this._isBrowser&&window[s(653)+"entListe"+s(376)](s(1510),this[s(249)+s(1619)]),this._isBrowser&&window[s(653)+s(1523)+s(376)](e[s(732)],this[s(249)+s(1290)])}["_handleP"+t(289)](n){let s=t;if(e.yENlR!==e[s(1149)])n.persisted&&(this[s(303)+s(1733)]()&&(!this[s(1782)]||e.TNfXv(this[s(1782)][s(980)+"te"],this[s(474)])||e[s(944)](this[s(1782)].readyState,this[s(1040)+"NG"]))&&this[s(249)+"nLine"](),this[s(1748)+"er"]&&window[s(917)+s(1048)](e[s(1709)],this._handleOnLine),this[s(1748)+"er"]&&window[s(917)+s(1048)](s(1771),this[s(249)+s(1290)]));else{if(!this._navigatorOnline()||this[s(401)+"osed"])return;this[s(1037)+"tManager"]?.[s(341)+s(1751)+"fig"](),this[s(1341)+"sCounter"]?.[s(1273)+s(1666)](),this._ws?this[s(1430)+"ect"](1001,e[s(1167)],!0):this._connect()}}async[t(886)+"eUrl"](n){let s=t,l={TwYAy:"success",TSkdS:s(1045)+"e_success",AwlWb:"ping_onc"+s(1433)+"t"};if(e[s(235)](e[s(535)],s(1065)))_0x2ef30b(l[s(1059)]),this.off(l[s(548)],_0x1de966),this[s(1107)](l[s(949)],_0x2f8754);else{let{fpID:f,deviceID:g,bddID:v,ttwID:_,accessKey:p,aID:y,customParams:C={},enableAutoAck:O,enableQoS:U,QoSLevel:H,env:ae}=this[s(1448)],st,cn,dn;this[s(1748)+"er"]||this[s(1762)+"X"]||this._isMiniTT?(st=location&&e[s(1172)]==location[s(1472)]?e[s(718)]:e[s(1745)],cn=n[s(323)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),dn=/^wss(.*:\/\/)/[s(973)](n)?n:""+st+cn):e[s(1287)](s(1365),e[s(1446)])?(st=e[s(718)],cn=n[s(323)](/(^http)((?:[s]*:\/\/))/,""),dn=/(^ws)((?:[s]*:\/\/))/.test(cn)?cn:""+st+cn):(this[s(1318)](e[s(1675)],_0x19e07c),this[s(397)]&&this[s(397)](_0x1ae0d8));let kl=v?e[s(1679)]:_?s(1600):e[s(1750)],Tl=v||_||g;if(e[s(604)](!Tl,!kl))throw new Error(e[s(1020)]);let Gg=e[s(1151)](e[s(977)],typeof C)?await e.zACJw(C):C,qg=ae?e[s(1186)](cg,ae[s(1700)],ae[s(1521)]):{},Ca=Object[s(253)]({device_platform:s(299),version_code:s(1035)+"0",access_key:p,fpid:f,aid:y,[kl]:Tl,xsack:O?1:0,xaack:O?1:0,xsqos:U?1:0,qos_level:U?H:void 0,qos_sdk_version:2,...qg},Gg),jg=Object[s(1303)](Ca).reduce((Pa,Ra)=>Ca[Ra]!==void 0?""+Pa+(Pa?"&":"?")+Ra+"="+Ca[Ra]:Pa,"");return dn+s(723)+jg}}async _connect(){let n=t;if(!(this[n(1166)+n(1100)]||this["_readyCl"+n(1470)])){this[n(1166)+n(1100)]=!0;try{let s=this._endpointManager?.[n(907)+"rentEndp"+n(306)+n(593)+n(997)](),{timeoutInterval:l}=this[n(1448)];if(s){let g=this[n(1037)+n(1173)]?.["getCurre"+n(768)+"nt"](),v=this[n(1037)+n(1173)]?.[n(448)+"ackupEnd"+n(1686)+"UpdateCo"+n(1763)](),_=this["_endpoin"+n(1173)]?.[n(1139)+n(768)+n(1777)+n(957)]();if(v){let p=n(778)+g+(n(972)+", max re"+n(1716)+"ached, w"+n(1473)+n(444)+n(629))+v+(n(389)+"y"),y=e.mekBy(lt,e[n(1297)],{message:p,code:on[n(1511)+n(1468)+"R"]});this[n(227)](p),this[n(1575)+n(1836)+n(442)](y),this._url=await this[n(886)+n(1719)](v),this[n(227)]("connect "+v+" "+_+" times"),this["_removeW"+n(466)+"rs"]()}else{let p="connect "+g+(n(972)+n(1622)+n(1716)+n(1711));this[n(227)](p),this["_dispatc"+n(1836)+"ent"](e[n(1788)](lt,n(1229),{message:p,code:on[n(1511)+n(1468)+"R"]}));return}}else{let g=this[n(1037)+n(1173)]?.[n(1139)+n(768)+n(506)+n(600)](),v=this[n(1037)+"tManager"]?.["getCurre"+n(768)+"ntTriesC"+n(957)]();this[n(543)]=await this[n(886)+"eUrl"](e[n(911)](g,"")),this._debug(n(778)+g+" "+v+" times"),this["_removeW"+n(466)+"rs"]()}if(this[n(1720)])this[n(1720)]=!1;else{let g=e[n(1142)](ba,n(808)+"t",{message:e[n(1241)]});this[n(1105)+n(310)]&&this["onStartR"+n(310)](g)}let f=this[n(1037)+n(1173)]?.["getCurre"+n(768)+n(1777)+n(957)]()||0;e[n(468)](f,1)&&await this[n(1684)](e[n(708)](f,1)),this[n(227)]("connecting url: "+this[n(543)]+(n(480)+n(1282))+this[n(1126)+"ls"]),this[n(1782)]=e[n(1456)](sg,{url:this[n(543)],protocols:[this[n(1126)+"ls"]],headers:this[n(1448)][n(853)+n(660)+"s"][n(1555)+n(594)]},this._options.ws),(this[n(1748)+"er"]||this._isWorker)&&this[n(1782)]&&(this[n(1782)][n(1854)+"pe"]=this["_binaryT"+n(597)]),this[n(1216)+"steners"](),this[n(1166)+"ionTimeo"+n(281)]=e[n(841)](setTimeout,this[n(1413)+"ut"][n(415)](this),l)}catch(s){throw this[n(1166)+n(1100)]=!1,s}}}[t(1671)+"mer"](){let n=t;clearTimeout(this[n(1166)+n(1202)+n(281)]),this[n(1166)+n(1202)+n(281)]=null}[t(689)+t(1289)](){let n=t;if(e[n(976)](e[n(1814)],e.npmFC))e[n(1085)](clearTimeout,this[n(602)+"gTimeoutId"]),e[n(472)](clearTimeout,this[n(929)+n(862)+"tId"]),this["_pingPon"+n(1135)+"Id"]=null,this[n(929)+n(862)+n(523)]=null;else{let s=e[n(1845)][n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!_0x1676de)return _0x3df685;continue;case"1":if(_0x50696b.utf8Write)return e[n(243)](_0x60842c[n(1674)+"e"](_0xedda31,_0xd057ea),_0x529d36);continue;case"2":return e[n(1728)](e[n(1119)](_0x2d88d5,_0x3aedf1,_0x2b501e,_0xcb4ff2),_0x22776d);case"3":if(e[n(223)](_0x4b8405[n(1270)],40))return _0x1f1fca(_0x1bced2,_0x3b5972,_0x226a00)+_0x3d312e;continue;case"4":if(_0x374569[n(904)])return _0x439989[n(904)](_0x3f0c39,_0x1cfd12)+_0x283093;continue}break}}}[t(227)](...n){let s=t;this[s(1448)][s(1829)]&&console.log[s(1232)](console,[s(962)+">",...n])}[t(345)+t(1529)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:g}=this[s(1448)],v=l*Math[s(1194)](g,e.DVPzl(n,1));return v>f?f:v}[t(1531)](){let n=t;if(this[n(1782)]&&e[n(1804)](this[n(1782)].readyState,this[n(1040)+"NG"])){this[n(689)+n(1289)](),this[n(602)+n(1135)+"Id"]=e[n(423)](setTimeout,this[n(1531)][n(415)](this),this[n(1448)][n(554)+"rval"]);return}if(!this[n(1782)]||e[n(1300)](this[n(1782)].readyState,this[n(474)]))return void this[n(601)+n(310)]();this._ws&&this[n(1782)].send("hi"),this["_reconne"+n(862)+n(523)]=setTimeout(this["_handleR"+n(310)+n(632)][n(415)](this),this[n(1448)][n(242)+"outInter"+n(826)])}["_handleR"+t(310)+"Timeout"](){let n=t;this[n(1341)+n(1090)]?.[n(1257)](),this.emit(e.yqeVV,e[n(1396)]),this[n(1341)+n(1090)]?.checkReachMaxCount()?this[n(601)+n(310)]():this._ping()}[t(303)+t(1733)](){let n=t;return this._isMiniTT||this[n(1762)+"X"]?this[n(1687)+n(320)+n(1562)]:(this._isBrowser||this[n(1778)+"r"])&&this[n(1448)]["listenNe"+n(1604)+n(1092)]?navigator[n(1621)]:!0}[t(601)+t(310)](){let n=t;!this[n(303)+"orOnline"]()||this[n(401)+n(1470)]||(this[n(1037)+n(1173)]?.["resetEnd"+n(1751)+n(1084)](),this[n(1341)+"sCounter"]?.[n(1273)+n(1666)](),this[n(1782)]?this[n(1430)+n(551)](1001,n(1540)+n(1371)+n(808)+n(1220)+n(1483),!0):this[n(1166)]())}["_onPageNetWorkCh"+t(565)](){let n=t,s={outJZ:function(l,f){return l===f}};this[n(337)+"T"]?tt[n(1746)+"kStatusC"+n(830)](({isConnected:l})=>{let f=n;this[f(1687)+f(320)+f(1562)]=l,l?this[f(249)+f(1619)]():this[f(249)+f(1290)]()}):this._isMiniWX&&wx["onNetwor"+n(909)+n(830)](({isConnected:l})=>{let f=n;if(s[f(588)](f(900),f(1828))){let g=_0x209954[f(1153)][f(1766)];g&&_0x3e1af8[f(384)+"rs"](g)}else this["_miniNav"+f(320)+"line"]=l,l?this[f(249)+f(1619)]():this[f(249)+f(1290)]()})}[t(1684)](n){return new Promise(s=>{let l=F;e.kzMJv(setTimeout,s,this[l(345)+l(1529)+"e"](n))})}[t(1430)+t(551)](n=1e3,s="",l=!1){let f=t;if(e[f(210)]===e[f(964)])this["currentE"+f(398)+f(1292)+"t"]=0;else{if(!this._ws)return;this[f(1412)+f(467)+"t"](n,s,l)}}[t(1413)+"ut"](){let n=t,s=this[n(1037)+n(1173)]?.[n(1139)+n(768)+"nt"]();this[n(227)](n(778)+s+n(972)),this[n(1430)+n(551)](1001,e[n(433)],!0)}[t(1271)](n){let s=t,l=e[s(1466)](Ut,n);this[s(1782)]&&e[s(279)](this[s(1782)][s(980)+"te"],this[s(474)])&&(this[s(1782)]&&this[s(1782)][s(1598)](l),this._debug(e[s(678)],n))}[t(1227)+t(466)+"rs"](){let n=t,s={dcacY:e[n(517)]};if(e[n(661)](e.YLRCK,e[n(1421)])){let l=e[n(1739)][n(842)]("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(1782)][n(653)+n(1523)+n(376)](e[n(1772)],this[n(730)]);continue;case"1":if(!this[n(1782)])return;continue;case"2":this._ws["removeEv"+n(1523)+n(376)](e[n(1297)],this[n(954)]);continue;case"3":this[n(1782)][n(653)+"entListe"+n(376)](e[n(1061)],this[n(349)+"ge"]);continue;case"4":this._ws["removeEv"+n(1523)+n(376)](e.FrXxQ,this._onClose);continue}break}}else this[n(1318)](s[n(984)],_0x438ae4),this[n(354)+"eAck"]&&this[n(354)+n(672)](_0x44430b)}[t(1216)+t(1006)](){let n=t,s=e.pcLoI[n(842)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[n(1782)])return;continue;case"1":this[n(1782)][n(917)+n(1048)]("error",this[n(954)]);continue;case"2":this[n(1782)][n(917)+n(1048)](e[n(1675)],this[n(935)]);continue;case"3":this[n(1782)][n(917)+n(1048)]("open",this._onOpen);continue;case"4":this[n(1782)]["addEvent"+n(1048)](e.SIQHW,this[n(349)+"ge"]);continue}break}}[t(1500)+"nceClose"](n=1e3,s=""){let l=t;try{this._ws&&this[l(1782)].close(n,s)}catch{}}[t(1412)+t(467)+"t"](n=1e3,s="",l=!1){let f=t;if(this[f(689)+f(1289)](),this[f(1671)+f(1418)](),this[f(1227)+"sListeners"](),this["_wsInsta"+f(547)](1e3,s),this[f(1166)+f(1100)]=!1,l&&this[f(303)+f(1733)]()&&!this[f(401)+"osed"]){if(this[f(1037)+"tManager"]?.[f(261)+f(1527)+"es"]()){let v=this[f(1037)+f(1173)]?.[f(1139)+"ntEndpoint"]();this[f(1575)+f(1488)+f(442)](e[f(1456)](_t,f(324),{code:1006,reason:f(778)+v+(f(972)+f(1622)+"tries reached"),wasClean:!0}))}else if(e[f(1279)](e[f(618)],e.oCYiy)){let v=_0x341875[f(463)+"g"](0,e.vlhqd(4,_0x118422.length)),_=v[f(1730)](_0x475460);_0x59bb3c.push(_)}else{let v=this._options[f(808)+f(1409)+f(1313)](n,s);this[f(1575)+f(1488)+"ent"](_t(e.FrXxQ,{code:n,reason:s,wasClean:!0,willReconnect:v})),v&&this._connect()}return}this._navigatorOnline()||this["_readyCl"+f(1470)]?this[f(1575)+f(1488)+"ent"](e.kCWHB(_t,e[f(1675)],{code:n,reason:e[f(981)]})):this["_dispatc"+f(1488)+f(442)](e[f(1373)](_t,e[f(1675)],{code:1006,reason:e[f(1120)]})),this._ws=null,this[f(1037)+f(1173)]?.["resetEnd"+f(1751)+f(1084)](),this[f(1341)+f(1090)]?.[f(1273)+f(1666)]()}["_dispatc"+t(851)+"nt"](n){let s=t,l={ZJNma:e[s(1213)]};e[s(1643)](e[s(233)],s(974))?(this["_pingLos"+s(1090)]?.[s(1257)](),this[s(1318)](JpuwWE[s(1097)],s(1571)),this[s(1341)+"sCounter"]?.[s(261)+s(307)+"nt"]()?this["_handleR"+s(310)]():this[s(1531)]()):(this[s(1318)](e[s(1772)],n),this[s(582)]&&this.onopen(n))}[t(1575)+t(1144)+t(1176)](n){let s=t;if(e.uzjbU(e[s(1559)],s(438)))this[s(1318)](e[s(1061)],n),this[s(729)+"e"]&&this[s(729)+"e"](n);else return(this[s(825)+"rs"][_0x668acd]||(this[s(825)+"rs"][_0x26a7b5]=[]))[s(394)]({fn:_0x4a4fc8,ctx:_0x3d6a25||this}),this}[t(1575)+t(1693)+t(1583)](n){let s=t;e[s(657)](s(1613),e[s(1681)])?(this[s(1318)](e[s(517)],n),this[s(354)+s(672)]&&this["onReceiv"+s(672)](n)):(e[s(934)](_0x5985ca,2048)?_0x39be4c[_0x976471++]=e.CPupp(e[s(919)](_0x4c63fc,6),31)|192:(e[s(1830)](_0x3283fd,65536)?_0x2dd4ff[_0xc613b0++]=_0x248750>>12&15|224:(_0x485a08[_0x274ca7++]=e.hCvod(e[s(377)](e[s(919)](_0x32deb5,18),7),240),_0x1a46fc[_0xe7b171++]=e.BCquO(e[s(958)](e[s(919)](_0x40adb1,12),63),128)),_0x48f6fc[_0x1d3a74++]=e[s(311)](e[s(818)](_0xe942f2,6),63)|128),_0x4ba554[_0x53ae52++]=e.yXDkE(e[s(1125)](63,_0x13c5d5),128))}[t(1575)+t(1836)+t(442)](n){let s=t;this[s(1318)](e[s(1297)],n),this.onerror&&this[s(955)](n)}[t(1575)+"hCloseEvent"](n){let s=t;this[s(1318)](e[s(1675)],n),this[s(397)]&&this[s(397)](n)}get[t(1854)+"pe"](){let n=t;return this[n(1782)]?this[n(1782)][n(1854)+"pe"]:this[n(1755)+n(597)]}set[t(1854)+"pe"](n){let s=t;this["_binaryT"+s(597)]=n,this._ws&&(this[s(1782)].binaryType=n)}get[t(816)+"nt"](){let n=t;return this[n(1037)+n(1173)]?.[n(1139)+n(768)+n(1777)+n(957)]()||0}get bufferedAmount(){let n=t,s=this["_message"+n(722)][n(587)]((l,f)=>(l+=f&&f[n(1507)+"th"]||0,l),0);return e[n(1860)](s,this[n(1782)]?this[n(1782)][n(1443)+"Amount"]:0)}get extensions(){let n=t;return this[n(1782)]?this[n(1782)][n(635)+"ns"]:""}get protocol(){let n=t;return this[n(1782)]?this[n(1782)][n(1472)]:""}get readyState(){let n=t;return this._ws?this._ws[n(980)+"te"]:this[n(1448)][n(1001)+n(1481)]?this[n(1040)+"NG"]:this[n(356)]}get[t(616)](){let n=t;return this[n(1782)]?this._ws[n(616)]:this[n(543)]}[t(324)](n=1e3,s){let l=t,f=e[l(895)][l(842)]("|"),g=0;for(;;){switch(f[g++]){case"0":if(this[l(1782)][l(980)+"te"]===this[l(356)]||e[l(1847)](this._ws[l(980)+"te"],this[l(1276)]))return void this[l(227)](l(211)+l(1760)+"y closed");continue;case"1":this[l(401)+l(1470)]=!0;continue;case"2":this[l(1671)+"mer"]();continue;case"3":this[l(1254)+l(577)+l(1048)]();continue;case"4":if(!this._ws)return void this[l(227)](e[l(1086)]);continue;case"5":this[l(689)+"ngTimer"]();continue;case"6":this[l(1412)+l(467)+"t"](n,s);continue;case"7":this[l(1649)+l(856)]?.closeDB();continue}break}}async[t(1598)](n,s){let l=t;if(e.tDMHM(null,n))throw new Error(l(1503)+l(1299)+" valid d"+l(988)+l(1609)+l(1471)+"ng or an arraybuffer");l(866)==typeof n&&(n=JSON[l(1450)+"y"](n)),e[l(1707)](e[l(520)],typeof n)&&!e[l(887)](n,ArrayBuffer)&&!(n[l(1572)]&&e[l(1630)](n[l(1572)],ArrayBuffer))&&(n=JSON[l(1450)+"y"](n));let f=await e.VsNbb(El,n),g=e[l(586)](ag,n),{method:v=0,service:_=this[l(1448)][l(609)],logID:p=this[l(1448)][l(1757)+l(217)](),headers:y=this[l(1448)].headers,payloadEncoding:C=this[l(1448)][l(1309)+l(464)],payloadType:O=this[l(1448)][l(1774)+l(597)],logIDNew:U=this[l(1448)]["logIDNew"+l(1195)]["enableAu"+l(739)+"teLogIDNew"]?i(this[l(1448)]["logIDNew"+l(1195)][l(1459)]):""}=e.uzFkW(s,{});if(!_)throw new Error(e.VffVW);let H={SeqID:he.fromNumber(this[l(550)]++),LogID:he[l(1603)+"er"](p),service:_,method:v,headers:y,payloadEncoding:e[l(1546)](C,Object)?C[l(1325)]?C[l(1325)]:"":C,payloadType:e[l(1478)](O,Object)?O[l(1102)]?O.type:g:O||g,payload:f,LogIDNew:U},ae=e[l(304)](Ut,H);if(this[l(1782)]&&e.vSZFO(this[l(1782)][l(980)+"te"],this[l(474)]))if(e[l(1593)]!==e.Ugkpi){if(_0x511bbb)return new _0x118bef(_0x10790a[l(616)],_0x28acbe.protocol);if(e[l(1317)](_0x28b00b,_0x29b99d))return new _0x20f1ee(_0x33323b[l(616)],_0x558efa.protocol,_0x345c88[l(268)]);if(e.JfQyc(_0x4c65df,_0x142120)&&e[l(1077)](e[l(1852)],typeof _0x576371)&&_0x12f644)return new _0x26c5c7(_0xf71303[l(616)],_0x20ffc2.protocols)}else this[l(1782)]&&this[l(1782)][l(1598)](ae),this[l(227)](e.hzhaz,H);else if(this[l(1439)+"Queue"][l(1270)]<this._options["maxMessageQueueL"+l(504)])if(e[l(1310)](l(1331),"SRXrQ"))this[l(1439)+l(722)][l(394)](ae),this[l(227)](e[l(595)],H);else return _0x18e0a5&&e[l(1114)](!0,_0x1c4eae.isLong);else this._messageQueue[l(658)](),this[l(1439)+l(722)][l(394)](ae);return{seqID:this[l(550)],logID:p,logIDNew:U}}async[t(808)+"t"](n){let s=t;if(e[s(844)]("CsbkO",e[s(1019)]))throw this[s(1166)+"Lock"]=!1,_0x176838;{let{url:l}=e.AWkMy(n,{}),f=Array[s(1713)](l)?l:e[s(1419)](e[s(520)],typeof l)?[l]:[];n&&Object[s(253)](this[s(1448)],n),f&&f[s(1270)]?this[s(1037)+s(1173)]=new wl(f,this[s(1448)][s(1513)+"es"]):this[s(1037)+s(1173)]?.[s(341)+s(1751)+s(1084)](),this[s(1341)+"sCounter"]?.[s(1273)+s(1666)](this[s(1448)][s(403)+s(1425)]),this[s(401)+"osed"]=!1,this[s(1782)]&&e[s(292)](this[s(1782)][s(980)+"te"],this[s(356)])?this[s(1430)+s(551)](1e3,e.Bcrbk,!0):(this[s(1720)]=!0,this._connect())}}async[t(685)](){let n=t,s={oaFlg:function(l,f){return e[F(1317)](l,f)}};if(e[n(1570)](e[n(1129)],e[n(1129)])){let l=this._qosDB[n(710)+n(1187)](this[n(1858)]),f=_0x2975f0[n(1056)](XoiiLQ[n(1212)](l,"{}"));return f[_0x310e24||_0x1f3ef7[this._pathKey]]=_0x547e21,this[n(505)][n(1401)+n(1187)](this._prefix,_0x499e2f[n(1450)+"y"](f)),_0x52a319||_0x473f1d[this[n(213)]]}else if(!this[n(1166)+n(1100)]){let l=e[n(1487)].split("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(1341)+n(1090)]?.[n(1273)+n(1666)]();continue;case"1":this[n(1720)]=!0;continue;case"2":this._connect();continue;case"3":this[n(401)+"osed"]=!1;continue;case"4":this["_endpoin"+n(1173)]?.[n(341)+n(1751)+"fig"]();continue}break}}}[t(917)+t(1048)](n,s){this.on(n,s)}[t(1451)+t(1176)](n){let s=t,{type:l}=n;this[s(1318)](l,n)}[t(653)+t(1523)+t(376)](n,s){this[t(1107)](n,s)}[t(1818)](){let n=t,s={iIWru:function(l,f){return e[F(1636)](l,f)},TnFeK:e[n(1109)],iSkpX:n(1045)+"e_timeout",tzqRz:function(l,f,g){return e[n(1142)](l,f,g)},SuiPK:function(l,f){return e[n(1647)](l,f)},tIznB:e[n(749)],pGZih:e[n(362)],hcdcS:function(l,f,g){return e[n(1186)](l,f,g)}};return new Promise((l,f)=>{let g=n,v={nXbEi:function(y,C,O){return s[F(267)](y,C,O)},eLjXr:function(y,C){return s[F(740)](y,C)},nuORs:function(y,C){return y===C},KgEmZ:s.tIznB,qGJoU:s.pGZih};this[g(689)+g(1289)](),this[g(602)+g(1135)+"Id"]=s[g(1327)](setTimeout,this[g(1531)][g(415)](this),this._options.pingInterval);let _=()=>{let y=g;if(v[y(1087)]("FoCxD",v[y(412)])){let C=_0x269241();return vGrUTi[y(1211)](_0x82433b,_0x1fedc7,C),vGrUTi[y(557)](_0x97f5ea,C)}else l(v[y(521)]),this[y(1107)](y(1045)+y(920)+"s",_),this[y(1107)]("ping_onc"+y(1433)+"t",p)},p=()=>{let y=g;s.iIWru(f,y(1571)),this[y(1107)](s.TnFeK,_),this[y(1107)](s[y(1615)],p)};this.on(s[g(651)],_),this.on(s[g(1615)],p),this[g(1531)]()})}}})(),Be["CustomCl"+M(656)]=Re[M(924)+"oseEvent"],Be[M(1824)+M(966)]=Re[M(1824)+M(966)],Be[M(529)+"e"]=Re[M(529)+"e"],Be.Event=Re[M(1176)],Be[M(963)]=Re[M(963)],Be[M(822)+"MessageE"+M(465)]=Re[M(822)+M(803)+M(465)],Be[M(803)+M(465)]=Re[M(803)+M(465)],Be.OpenEvent=Re[M(256)+"t"],Be[M(437)+M(837)]=Re[M(437)+"tEvent"],Be[M(751)+"oseEvent"]=Re[M(751)+"oseEvent"],Be[M(1390)+M(966)]=Re.createErrorEvent,Be[M(1661)+M(1222)+"nt"]=Re["createMe"+M(1222)+"nt"],Be["createOp"+M(795)]=Re.createOpenEvent,Be[M(1253)+"connectEvent"]=Re[M(1253)+M(450)+M(465)],Be[M(236)+M(1098)]=Re[M(236)+"rame"],Be[M(1160)+M(584)]=Re["encodeFr"+M(584)];for(Zo in Re)[M(924)+M(656),"CustomEr"+M(966),M(529)+"e",M(1176),M(963),M(822)+M(803)+M(465),M(803)+"vent",M(256)+"t",M(437)+"tEvent",M(751)+M(656),M(1390)+M(966),M(1661)+"ssageEvent",M(425)+"enEvent",M(1253)+M(450)+M(465),M(236)+M(1098),M(1160)+M(584)][M(762)](Zo)===-1&&(Be[Zo]=Re[Zo]);var Zo;Object[M(1668)+M(854)](Be,M(792)+"le",{value:!0})});import{existsSync as dS,openSync as lS}from"node:fs";import{mkdir as uS}from"node:fs/promises";import{dirname as fS}from"node:path";import{fileURLToPath as xS}from"node:url";function pS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Jd(t=J()){return dS(t.libEntry)?t.libEntry:xS(new URL("../index.ts",import.meta.url))}async function hp(t={}){let e=t.paths??J(),r=t.entryOverride??Jd(e),i=pS(e,process.env.COZE_BRIDGE_LOG_MODE);await uS(fS(i),{recursive:!0});let o=lS(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=it(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[ds]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return hS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var hS,ds,da=et(()=>{"use strict";Jt();te();Ce();hS=j("spawn-daemon"),ds="COZE_BRIDGE_DAEMON"});import{spawn as f2}from"node:child_process";import{mkdir as x2,unlink as h2,writeFile as p2}from"node:fs/promises";import{dirname as g2,join as m2}from"node:path";function Zr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function w2(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Zr(r)}</key>
21
- <string>${Zr(i)}</string>`).join(`
20
+ `+r)}function rr(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,rr),t.emit("wsClientError",d,r,e)}else os(r,i,o,c)}});var ip=ae(Me=>{"use strict";var N=H;(function(t,e){let r=H,i=t();for(;;)try{if(parseInt(r(1703))/1+-parseInt(r(538))/2*(parseInt(r(1791))/3)+parseInt(r(1048))/4+parseInt(r(1428))/5*(-parseInt(r(337))/6)+-parseInt(r(1063))/7+parseInt(r(1850))/8+parseInt(r(1743))/9*(parseInt(r(500))/10)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(oa,929423);var JS=Object[N(1566)+"operty"],ZS=Object["getOwnPr"+N(1621)+N(1433)],Qx=(t,e)=>function(){return t&&(e=(0,t[{vOyfk:function(o,c){return o(c)}}.vOyfk(ZS,t)[0]])(t=0)),e},XS=(t,e)=>{let r=N,i={GTIsh:function(c,d,u,h){return c(d,u,h)}};for(var o in e)i[r(1401)](JS,t,o,{get:e[o],enumerable:!0})};function YS(){return Vx||(Vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function QS(){let t=N;return Jx||(Jx=[IDBCursor[t(1157)+"e"][t(1826)],IDBCursor[t(1157)+"e"][t(1272)],IDBCursor[t(1157)+"e"]["continue"+t(1655)+"ey"]])}function e1(t){let e=N,r={SXQEv:function(o,c){return o&c},BtDFr:function(o,c){return o===c},hwgqu:"OTmkP",OZKKu:"IUBLf",BFsfu:e(787),jcDcS:e(1298),DCrrM:function(o,c){return o(c)},DKjdB:function(o){return o()},TsaBn:e(1854),UBRPp:function(o,c){return o===c},CJuEG:e(1135),JEyRw:e(1132)},i=new Promise((o,c)=>{let d=e,u={DLzQv:function(w){return r[H(1405)](w)}},h=()=>{let w=H,v={eToma:function(_,E){return _|E},JDAYQ:function(_,E){return r[H(1558)](_,E)},NJqno:function(_,E){return _>>E},ihpYM:function(_,E){return _|E}};r.BtDFr(r[w(1755)],r.OZKKu)?(_0x5e8065[_0x1d02c2++]=v.eToma(_0x5c2395>>12,224),_0xc02e9f[_0xc1e6ef++]=v[w(1344)](v[w(889)](v[w(1584)](_0x26fa0e,6),63),128),_0x1ab4f9[_0x112caf++]=v[w(679)](v[w(889)](63,_0x3ffc4c),128)):(t[w(1449)+"entListe"+w(434)](r[w(948)],x),t[w(1449)+"entListener"](r[w(495)],m))},x=()=>{let w=H;o(Ht(t[w(891)])),u[w(721)](h)},m=()=>{let w=H;r[w(1251)](c,t[w(1298)]),h()};t[d(1803)+"Listener"](r.BFsfu,x),t["addEvent"+d(1262)](r[d(495)],m)});return i[e(1323)](o=>{let c=e,d={NyMzS:r[c(1154)],hDyfm:r[c(495)],YmAPh:c(1771),cSbYc:c(623)};if(r[c(1752)](r[c(683)],r.JEyRw)){let u=(c(420)+"2")[c(1317)]("|"),h=0;for(;;){switch(u[h++]){case"0":if(!this[c(975)])return;continue;case"1":this[c(975)].addEventListener(d[c(960)],this[c(1839)]);continue;case"2":this[c(975)][c(1803)+"Listener"](d.hDyfm,this[c(1544)]);continue;case"3":this[c(975)].addEventListener(d[c(438)],this._onOpen);continue;case"4":this._ws["addEvent"+c(1262)](d[c(1557)],this[c(577)+"ge"]);continue}break}}else o instanceof IDBCursor&&Xd[c(1487)](o,t)})[e(1696)](()=>{}),ia[e(1487)](i,t),i}function t1(t){let e=N,r={EsbQI:e(1552),CQJoG:e(1598),NLaeu:function(o){return o()},IioGe:function(o,c){return o!==c},iDDnj:function(o,c){return o(c)},JzJyp:e(705)+"or",pvTVA:"error"};if(ra[e(1506)](t))return;let i=new Promise((o,c)=>{let d=e,u={bHeVy:r.EsbQI,lJili:r[d(854)],LvPtw:function(w){return w()},dfsBc:function(w){return r.NLaeu(w)},fLsbB:function(w,v){return r.IioGe(w,v)},phvaZ:"QxmPs",QTXbU:function(w,v){return r[d(794)](w,v)},XZasq:r[d(1143)],JYiyj:function(w){return w()}},h=()=>{let w=d;t[w(1449)+w(442)+w(434)](u[w(1184)],x),t.removeEventListener(w(1298),m),t["removeEv"+w(442)+w(434)](u[w(950)],m)},x=()=>{let w=d;u[w(1617)](o),u[w(1509)](h)},m=()=>{let w=d;if(u[w(1218)](u[w(526)],u.phvaZ))return this[w(975)]?this[w(975)].extensions:"";u.QTXbU(c,t[w(1298)]||new DOMException(w(705)+"or",u.XZasq)),u[w(691)](h)};t[d(1803)+d(1262)](r[d(1130)],x),t[d(1803)+d(1262)](r.pvTVA,m),t[d(1803)+d(1262)](r[d(854)],m)});ra[e(1487)](t,i)}function n1(t){sa={eHGlv:function(i,o){return i(o)}}[N(1171)](t,sa)}function r1(t){let e=N,r={MrXRr:function(i,o){return i(o)},IwqDB:function(i,o){return i(o)},ltKXg:function(i,o){return i(o)},rCIcS:function(i,o){return i===o},QzHrb:function(i,o){return i in o},yJIKq:e(1305)+e(1727),dfTFr:e(440),NWGvh:function(i){return i()}};if(r.rCIcS(t,IDBDatabase[e(1157)+"e"].transaction)&&!r[e(1760)](r[e(607)],IDBTransaction.prototype))if(r.dfTFr!==e(440))this[e(1512)]=!0,this[e(1205)]();else return function(i,...o){let c=e,d=t[c(1398)](r.MrXRr(as,this),i,...o);return Zd[c(1487)](d,i[c(652)]?i[c(652)]():[i]),r[c(700)](Ht,d)};return r[e(767)](QS)[e(1459)](t)?function(...i){let o=e;return t[o(728)](r[o(1762)](as,this),i),r.ltKXg(Ht,Xd[o(1519)](this))}:function(...i){let o=e;return r[o(1582)](Ht,t[o(728)](as(this),i))}}function i1(t){let e=N,r={ZDCJs:e(1360),tpuOT:function(i,o){return i instanceof o},hMAsH:function(i,o){return i(o)},RXTkf:function(i,o,c){return i(o,c)},FwREG:function(i){return i()}};return typeof t===r[e(1520)]?r1(t):(r.tpuOT(t,IDBTransaction)&&r.hMAsH(t1,t),r[e(1314)](ep,t,r[e(481)](YS))?new Proxy(t,sa):t)}function Ht(t){let e=N,r={LbQmd:function(o,c,d){return o(c,d)},GuidK:function(o,c){return o instanceof c},pQASR:function(o,c){return o(c)},ZrsTZ:function(o,c){return o(c)},TWIPu:function(o,c){return o!==c},AkEkN:function(o,c){return o!==c},sAfLp:e(1037),hKoAk:e(369)};if(r[e(925)](t,IDBRequest))return r.pQASR(e1,t);if(ta[e(1506)](t))return ta[e(1519)](t);let i=r[e(1118)](i1,t);if(r[e(1378)](i,t))if(r[e(907)](r[e(1068)],r[e(996)]))ta.set(t,i),ia[e(1487)](i,t);else return _0x4dff80.bytes[r[e(1533)](_0x41333d,_0x449cb7,1)];return i}var ep,Vx,Jx,Xd,ra,Zd,ta,ia,sa,as,Zx=Qx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={VSyUA:function(r,i){return r(i)},EtzHH:function(r,i){return r instanceof i},KQWTk:function(r,i){return r===i},AtkEf:t(1837),OjevV:"done",UmSQd:function(r,i){return r===i},QNawT:"objectStoreNames",KaTRP:t(436),PqbRG:function(r,i){return r===i},mkZgd:function(r,i){return r instanceof i},ZKDXZ:function(r,i){return r===i},klagK:function(r,i){return r===i},bBiKS:t(847),IJAOJ:function(r,i){return r in i}};ep=(r,i)=>i[t(764)](o=>r instanceof o),Xd=new WeakMap,ra=new WeakMap,Zd=new WeakMap,ta=new WeakMap,ia=new WeakMap,sa={get(r,i,o){let c=t,d={YPjDE:function(u,h){return e[H(690)](u,h)}};if(e.EtzHH(r,IDBTransaction))if(e[c(1001)](e[c(786)],e[c(786)])){if(e[c(1001)](i,e[c(1180)]))return ra[c(1519)](r);if(e.UmSQd(i,e[c(1451)])){if(c(1511)!==e[c(587)])return r[c(1305)+c(1727)]||Zd[c(1519)](r);d[c(901)](_0x47dfcd,this[c(1588)+c(1099)+"Id"]),_0x31d14b(this[c(1188)+c(1820)+"tId"]),this[c(1588)+c(1099)+"Id"]=null,this[c(1188)+c(1820)+c(678)]=null}if(e[c(1603)](i,"store"))return o[c(1305)+c(1727)][1]?void 0:o[c(1305)+"ore"](o[c(1305)+c(1727)][0])}else return this[c(928)]?.set({message_id:_0x7a30f,timestamp:_0x35bf14});return e.VSyUA(Ht,r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e.mkZgd(r,IDBTransaction)&&(e[o(1394)](i,e[o(1180)])||e[o(639)](i,e[o(544)]))?!0:e[o(750)](i,r)}},as=r=>ia[t(1519)](r)}}),tp={};XS(tp,{deleteDB:()=>o1,openDB:()=>s1,unwrap:()=>as,wrap:()=>Ht});function s1(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=N,u={ZfCQg:function(m,w){return m!==w},SaXio:d(1565),Queul:function(m,w,v,_,E){return m(w,v,_,E)},JYKlU:function(m,w){return m(w)},BoxkL:"versionc"+d(1126),BXIZx:d(947)+"eeded",uhfxX:d(393)},h=indexedDB[d(1771)](t,e),x=u[d(1829)](Ht,h);return i&&h[d(1803)+d(1262)](u[d(1792)],m=>{let w=d;if(u[w(555)](u[w(1467)],u[w(1467)])){let v=_0x144ed2[w(623)].payload;v&&_0x1be9d4[w(1176)+"rs"](v)}else u.Queul(i,u[w(1829)](Ht,h[w(891)]),m.oldVersion,m[w(1150)+"on"],u[w(1829)](Ht,h[w(973)+w(594)]))}),r&&h[d(1803)+"Listener"](u.uhfxX,()=>r()),x.then(m=>{let w=d;c&&m[w(1803)+w(1262)](w(1854),()=>c()),o&&m[w(1803)+w(1262)](u[w(372)],()=>o())})[d(1696)](()=>{}),x}function o1(t,{blocked:e}={}){let r=N,i={iTHXW:r(393),NZvWn:function(c,d){return c(d)}},o=indexedDB[r(768)+r(944)](t);return e&&o[r(1803)+r(1262)](i.iTHXW,()=>e()),i[r(823)](Ht,o)[r(1323)](()=>{})}function Xx(t,e){let r=N,i={LTzXY:"readwrite",QRZEK:function(h,x){return h instanceof x},FLeDK:r(884),yADTT:function(h,x){return h!==x},snGvV:function(h,x){return h in x}};if(!(i[r(1518)](t,IDBDatabase)&&!(e in t)&&typeof e===i.FLeDK))return;if(na[r(1519)](e))return na.get(e);let o=e[r(795)](/FromIndex$/,""),c=i[r(1475)](e,o),d=rp.includes(o);if(!i[r(1465)](o,(c?IDBIndex:IDBObjectStore).prototype)||!(d||np.includes(o)))return;let u=async function(h,...x){let m=r,w=this[m(973)+"ion"](h,d?i[m(1628)]:m(933)),v=w.store;return c&&(v=v[m(1231)](x[m(924)]())),(await Promise[m(449)]([v[o](...x),d&&w.done]))[0]};return na[r(1487)](e,u),u}var np,rp,na,a1=Qx({"node_modules/idb/build/index.js"(){let t=N,e={aorcg:"get",ujVpp:"getKey",DgYID:t(498),jOnWI:t(472),pQAHW:t(844),uOSpK:function(r,i){return r(i)}};Zx(),Zx(),np=[e[t(491)],e[t(401)],e[t(737)],t(1252)+"ys",e[t(1537)]],rp=["put",e[t(942)],"delete",t(650)],na=new Map,e[t(582)](n1,r=>({...r,get:(i,o,c)=>Xx(i,o)||r[t(1519)](i,o,c),has:(i,o)=>!!Xx(i,o)||r.has(i,o)}))}}),c1={idb:function(t){let e=N;t.exports=Promise[e(1488)]()[e(1323)](()=>(a1(),tp)).then(function(r){return r})}},Yx={};function Ut(t){let e=N,r={uOSDF:e(1541)+"0",oAWwN:function(u,h){return u!==h}},i=r.uOSDF[e(1317)]("|"),o=0;for(;;){switch(i[o++]){case"0":return d[e(1329)];case"1":var c=Yx[t];continue;case"2":var d=Yx[t]={exports:{}};continue;case"3":c1[t](d,d[e(1329)],Ut);continue;case"4":if(r[e(702)](void 0,c))return c.exports;continue}break}}Ut.d=(t,e)=>{let r=H;for(var i in e)Ut.o(e,i)&&!Ut.o(t,i)&&Object["definePr"+r(970)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Ut.o=(e,r)=>Object.prototype[t(881)+t(970)][t(1398)](e,r)})(),(()=>{let t=N,e={CZvab:function(r,i){return r===i},GcHTD:t(1360),MRlPT:function(r,i){return r(i)},XeiLX:function(r,i){return r instanceof i},uOxiz:function(r,i,o){return r(i,o)},kuZfE:function(r){return r()},ZywBJ:t(581),MsvGd:t(1490),goROE:t(1302)+"d",CpJJK:t(1834),MzrUC:t(1326)+"le"};Ut.r=r=>{let i=t;if(e[i(399)](e[i(375)],e[i(642)]))return IpVOuz[i(399)](typeof _0x49152c,IpVOuz.GcHTD)?IpVOuz[i(1632)](_0x2160d5,_0x268ec5):(IpVOuz[i(482)](_0x324048,_0x21ec60)&&IpVOuz[i(1632)](_0x539bd1,_0x31fc4f),IpVOuz.uOxiz(_0x5e96a9,_0x1caba7,IpVOuz[i(1529)](_0x1532c7))?new _0x3bf3b4(_0x458731,_0x3a29e7):_0x5350c9);e.goROE!=typeof Symbol&&Symbol[i(560)+i(713)]&&Object[i(1566)+i(970)](r,Symbol["toString"+i(713)],{value:e[i(1294)]}),Object[i(1566)+i(970)](r,e.MzrUC,{value:!0})}})();function H(t,e){t=t-321;let r=oa(),i=r[t];if(H.lPoAjV===void 0){var o=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let v=0,_,E,S=0;E=h.charAt(S++);~E&&(_=v%4?_*64+E:E,v++%4)?m+=String.fromCharCode(255&_>>(-2*v&6)):0)E=x.indexOf(E);for(let v=0,_=m.length;v<_;v++)w+="%"+("00"+m.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(w)};H.GXmyss=o,H.RGiowA={},H.lPoAjV=!0}let c=r[0],d=t+c,u=H.RGiowA[d];return u?i=u:(i=H.GXmyss(i),H.RGiowA[d]=i),i}var Re={};(()=>{let t=N,e={YElaR:function(a,n){return a+n},aKrbt:function(a,n){return a+n},xehFD:function(a,n){return a+n},HenWQ:function(a,n){return a(n)},fjVHL:function(a,n,s){return a(n,s)},djjMv:function(a,n){return a>>n},GNERA:function(a,n){return a>=n},qUfPJ:function(a,n){return a===n},pryiI:t(1622),QXvVF:t(403),dPZpZ:function(a,n){return a+n},lYrTy:t(1246),kdROD:t(1605),dkCwL:t(338),rUFip:function(a,n){return a!==n},DPBkh:t(1196),snScx:t(1478)+"00000000"+t(1478)+t(1478),kUzyV:t(1415)+t(1723)+t(518)+t(1042)+t(1794),bFiTg:function(a,n){return a>n},hAqvf:function(a,n){return a<n},LyYHU:function(a,n){return a<n},myfIR:function(a,n){return a!==n},VyVmE:function(a,n){return a-n},GLIFp:function(a,n){return a!==n},JpeHB:function(a,n){return a<n},EoUzO:t(1645),OdUSw:"gdDbz",vBbox:function(a,n){return a!==n},rpleJ:t(665),iwdJE:function(a,n,s){return a(n,s)},edPHg:function(a,n,s){return a(n,s)},wTjRW:function(a,n,s){return a(n,s)},QkrcJ:function(a,n){return a&n},bZQan:t(852)+t(340)+" field: "+t(412),IpbPX:function(a,n){return a<n},nYeaC:function(a,n){return a>n},IMfjB:function(a,n){return a|n},jwfqL:function(a,n){return a===n},dRFJL:t(1010),aWYZa:"GfVcj",DwJCK:function(a){return a()},UowLN:function(a,n){return a(n)},ieiPz:function(a,n){return a==n},bvvas:"text/plain;chars"+t(1782),auGAP:t(1686)+t(754),wUzzB:function(a,n){return a*n},hFvGj:t(917),oQVYc:t(1217),UDBMw:function(a,n,s){return a(n,s)},cBvUk:function(a,n){return a!==n},LSblA:function(a,n,s){return a(n,s)},RSGZT:function(a,n,s){return a(n,s)},xQtvM:function(a,n){return a(n)},PFigN:function(a,n){return a!==n},LAaTP:function(a,n){return a===n},bxcmc:t(810),rpjqD:t(1456),iNMMN:function(a,n){return a(n)},boInv:function(a,n){return a!==n},tpMZH:t(1618),fjoHg:t(1731),kEdcz:function(a){return a()},cBwuL:function(a,n,s){return a(n,s)},iaBaf:function(a,n){return a!==n},RMteQ:function(a,n){return a!==n},EMTxN:function(a,n,s){return a(n,s)},ruuVA:function(a,n,s){return a(n,s)},sKqnV:function(a,n){return a!==n},kDjEW:function(a,n){return a!==n},uGPSU:t(632),SNDmO:function(a,n,s){return a(n,s)},GYsRb:function(a,n,s){return a(n,s)},BmAYh:function(a,n){return a<n},GGBSV:function(a,n){return a|n},TFUaU:function(a,n){return a!==n},ONEGZ:t(1108),eiKUm:t(1074),BXZJk:function(a,n){return a(n)},MSNky:function(a,n,s){return a(n,s)},YLpdC:function(a,n){return a(n)},OFfii:function(a,n){return a(n)},NYvmV:function(a,n,s){return a(n,s)},wPqZx:function(a,n){return a(n)},fcwHq:function(a,n,s){return a(n,s)},yWYFW:function(a,n){return a(n)},uAvBM:function(a,n,s){return a(n,s)},KnYCW:t(852)+"required"+t(1473)+"SeqID",aJnQs:function(a,n){return a===n},AjBSe:t(852)+t(340)+t(1473)+t(421),FZSHl:function(a,n){return a===n},rmZke:t(852)+t(340)+t(1473)+t(1264),vwTTg:function(a,n){return a&n},ZdHUF:function(a,n,s){return a(n,s)},CRgof:function(a,n){return a+n},lvvrs:t(1606)+t(1256),GkKDt:function(a,n){return a>=n},qvcWc:function(a,n){return a>n},EQPQJ:function(a,n){return a+n},RRBRn:t(1232)+t(1256),tbaSR:function(a,n,s){return a(n,s)},AqBFX:t(1854),dkLxi:function(a,n){return a===n},YDVFS:function(a,n){return a&n},WKjRM:function(a,n){return a===n},JmmXS:function(a,n){return a&n},etedy:function(a,n){return a+n},ywXib:function(a,n){return a&n},lHVve:function(a,n){return a<<n},DzXSz:function(a,n){return a&n},ZcMgh:function(a,n){return a&n},oypxS:function(a,n){return a+n},vqmFG:function(a,n){return a+n},hXiPS:function(a,n){return a+n},eHykB:function(a,n){return a+n},RqdrI:function(a,n){return a!==n},tEdcG:function(a,n){return a&n},kowAZ:function(a,n){return a|n},VfTin:function(a,n){return a<<n},NJiEG:function(a,n){return a&n},UEzqK:function(a,n){return a>=n},dOarj:function(a,n){return a<=n},rierQ:function(a,n){return a(n)},MBBHL:function(a,n){return a==n},WMBye:function(a,n){return a>=n},TXZzG:function(a,n){return a+n},dHtwQ:function(a,n){return a+n},cLAFt:function(a,n){return a+n},hhwkP:function(a,n){return a|n},rWNLl:function(a,n){return a<<n},qgdja:"kXLpJ",zdbxW:function(a,n){return a|n},nlCrf:function(a,n){return a<<n},Zquuh:function(a,n){return a&n},SinHa:function(a,n){return a&n},hsZET:function(a,n){return a<<n},wRAQZ:function(a,n){return a&n},aGKEW:function(a,n){return a<n},qKAzW:function(a,n){return a&n},tPzIO:function(a,n){return a<n},lBfDM:function(a,n){return a<=n},SyfoG:function(a,n){return a<n},TXomv:function(a,n){return a+n},hHlXY:function(a,n){return a<n},chaBY:function(a,n,s){return a(n,s)},Qrvqu:function(a,n,s){return a(n,s)},JbrBa:function(a,n){return a<n},YPEtw:function(a,n){return a+n},BERXX:function(a,n){return a<<n},waWIV:function(a,n){return a&n},zGDHQ:function(a,n){return a>>n},razEy:function(a,n){return a>>n},wyxbW:function(a,n){return a>>n},upVRa:function(a,n){return a<n},vOAjI:t(1437),KCecC:t(1849),wZbnP:function(a,n){return a===n},ncQVF:"oynrz",ukFkw:function(a,n){return a<n},boTJX:function(a,n){return a&n},IErPE:function(a,n){return a&n},fMaQo:function(a,n){return a>=n},foLvg:function(a,n){return a(n)},zAhOK:function(a,n){return a===n},Ipfzw:t(837),bPmPe:function(a,n){return a(n)},uAPEt:function(a,n){return a&n},EMkff:function(a,n){return a&n},jMmOp:function(a,n){return a&n},mBCHD:function(a,n){return a(n)},GQNqH:function(a,n){return a&n},TDrDV:function(a,n){return a<<n},UyjCT:function(a,n){return a&n},UzWsl:function(a,n){return a&n},joqIl:function(a,n){return a(n)},NiSRo:function(a,n){return a&n},fSJJt:function(a,n){return a&n},zzOQf:function(a,n){return a(n)},LdVvL:function(a,n){return a<<n},YmmTq:function(a,n){return a|n},bBthj:function(a,n){return a<<n},ycJHk:function(a,n){return a>>>n},QymjU:function(a,n){return a<<n},oArcE:function(a,n){return a===n},pCgUQ:t(1608),ZiXTI:function(a,n){return a>>>n},hcUcv:function(a,n){return a===n},XCqpB:function(a,n){return a<n},drZIX:function(a,n){return a<n},gvSta:function(a,n){return a&n},XdvGg:function(a,n){return a!==n},XcWPq:function(a,n){return a+n},LoSiP:function(a,n){return a!==n},oddId:function(a,n){return a|n},oSzEF:function(a,n){return a>>>n},hOqqE:function(a,n){return a+n},vrLAG:function(a,n){return a>>>n},CYHpA:function(a,n){return a+n},GGTyc:function(a,n){return a>>>n},kxEru:function(a,n){return a|n},NvJhp:function(a,n){return a!==n},eXWwJ:function(a,n){return a|n},fsEQW:function(a,n){return a>>>n},mUqUQ:function(a,n){return a+n},eBpZy:function(a,n){return a&n},sLBky:function(a,n){return a>>>n},nVmEg:function(a,n){return a+n},DQrYn:function(a,n){return a|n},YpVco:function(a,n){return a!==n},CgtoV:function(a,n){return a&n},loOgO:t(1614),DJyWH:"TNmNr",fVYHq:function(a,n){return a(n)},ffNQA:"qMjKq",BqZRA:t(687),QuRjG:function(a,n){return a|n},wIIgw:function(a,n){return a<<n},qKTPd:function(a,n){return a|n},AcgVY:function(a,n){return a|n},nCyIM:function(a,n){return a|n},aSAhk:function(a,n){return a<<n},RWFpZ:function(a,n){return a>>>n},hwSSO:function(a,n){return a|n},qLVRV:function(a,n){return a|n},kZypW:function(a,n){return a<<n},epNHw:function(a,n){return a<<n},QxIIH:function(a,n){return a<<n},agzZo:function(a,n){return a&n},pZTpa:function(a,n){return a&n},JRNMS:function(a,n){return a>>>n},szvId:function(a,n){return a&n},ddQRa:function(a,n){return a>>>n},RNIDJ:function(a,n){return a>>>n},dNXZT:function(a,n){return a>=n},ydMIg:function(a,n){return a<=n},SZEJX:function(a,n){return a>=n},KkcLO:function(a,n){return a+n},ChcBU:function(a,n){return a|n},DUTRD:function(a,n){return a|n},grool:function(a,n){return a/n},EEtoV:function(a,n){return a+n},yUXqM:function(a,n){return a>>>n},QSerl:function(a,n){return a+n},vjCkX:function(a,n){return a*n},WEXqy:function(a,n){return a>>>n},mHhGc:function(a,n){return a===n},FLtBk:function(a,n){return a&n},eyRin:function(a,n){return a+n},UUYtx:function(a,n){return a+n},jGjVq:function(a,n){return a===n},cJnYj:function(a,n){return a>>>n},lhaQQ:function(a,n){return a===n},laMiX:function(a,n){return a instanceof n},DiEtb:t(1197),aBiOX:t(817),fWbDZ:function(a,n){return a===n},MVmMs:function(a,n){return a+n},oTrJK:function(a,n){return a+n},BTEIx:function(a,n){return a&n},FwRXD:function(a,n){return a>>>n},HNoyU:function(a,n){return a&n},eWtdy:function(a,n){return a>>>n},xXnRm:function(a,n){return a>>>n},poEAI:function(a,n){return a>>>n},vaHvM:function(a,n){return a>>>n},KoPbC:function(a,n){return a&n},WvbEd:function(a,n){return a>>>n},PAwCc:t(1170)+t(465),ZSRoF:t(1583)+t(1066)+"R",GbwJq:t(1283)+"OR",zkfzT:t(1447)+t(329),cXGEG:"NATIVE_E"+t(893),UARYO:function(a,n){return a===n},xsHRk:"jOINZ",REqEV:function(a,n){return a!==n},kyvjV:t(1057),zFsOn:function(a,n){return a!==n},VSbjh:t(743),SrLmX:t(761),pivrx:function(a,n){return a|n},xncKt:function(a,n){return a+n},PdcaB:function(a,n){return a<<n},kvnVl:function(a,n){return a|n},zFPXJ:function(a,n){return a<<n},VEnDu:t(1469),Tollk:t(1162),YLMdn:t(1070),RwFvZ:function(a,n){return a>n},jhAiV:t(850)+t(836),IMctB:function(a,n){return a===n},iDKaY:function(a,n){return a===n},tlRay:function(a,n){return a&n},QrvWi:function(a,n){return a+n},Dfktr:function(a,n){return a+n},fAoBJ:t(478),qXdNQ:function(a,n,s){return a(n,s)},vdQCx:function(a,n,s){return a(n,s)},AxcSI:t(1298),yHQYN:t(1771),mLmrK:t(623),QNxQr:"JGtxu",qlNlS:"vBKcQ",zwBkk:function(a,n,s){return a(n,s)},BuNEQ:t(584),poBNj:function(a,n){return a instanceof n},KtqQc:function(a,n){return a+n},rmaTM:function(a,n){return a<n},QwqNg:t(1089),vEUkk:function(a,n){return a(n)},GrQab:function(a,n){return a!==n},SkRKN:"BWZzl",zIlin:function(a,n){return a||n},KJfUh:function(a,n){return a||n},CGNYe:t(953)+t(1126),hrBLV:"JGeEZ",zbbmc:t(1464)+"3",Kjuvf:function(a,n){return a||n},iWzmW:function(a,n){return a!=n},PwRLE:t(1302)+"d",klHOh:function(a,n){return a<=n},WLiTs:function(a,n){return a(n)},gsZIj:function(a,n){return a<n},QFIIL:function(a,n){return a<n},OVZkt:function(a,n){return a<n},ioUpG:function(a,n){return a&n},HomRV:function(a,n){return a===n},TZHRn:function(a,n){return a&n},tyGcB:function(a,n){return a+n},HdOLr:t(1399),GPxpd:function(a,n){return a<n},pDLMY:function(a,n){return a&n},DqqrS:function(a,n){return a>=n},qsWTU:function(a,n){return a|n},nZgrg:function(a,n){return a&n},WXmpq:function(a,n){return a&n},yPXEC:function(a,n){return a>=n},twrJP:function(a,n){return a|n},Aseae:function(a,n){return a<<n},nnzVl:function(a,n){return a&n},wCIlf:function(a,n){return a&n},BSbQj:function(a,n){return a+n},MRNvc:function(a,n){return a&n},iJgkv:function(a,n){return a<n},KlTDx:function(a,n){return a<n},nhNJJ:function(a,n){return a>>n},WlFNo:"2|5|3|1|"+t(646),aZsTX:function(a,n){return a&n},iIEJe:function(a,n){return a>>n},ZtAJG:function(a,n){return a|n},WDxpT:function(a,n){return a&n},XnHrN:function(a,n){return a>>n},PrToE:function(a,n){return a|n},xgjuw:function(a,n){return a-n},JBbqT:t(1777)+t(1297)+t(1610)+t(1445)+"ed",ceopx:"close, w"+t(962)+t(1581),QTRJZ:function(a,n){return a!==n},Radyn:"rQzuI",GIvEb:"NjIWp",ziIdd:function(a,n){return a(n)},FIvbc:t(884),AQYeR:function(a,n){return a!=n},AmkUw:function(a,n){return a===n},Ocbqo:t(958),TBKUR:function(a,n){return a==n},NaZQj:t(1562),gjaLC:function(a,n){return a>=n},NmIYz:t(1090),ottRD:function(a,n){return a(n)},Ighxy:function(a,n){return a(n)},Trmrh:t(425)+t(629),FAORE:function(a,n){return a+n},CfmpQ:t(1491),LQTgG:"&jscallb"+t(902)+t(1285)+"P",GasiE:t(1597),WXOpB:t(1061),CFrYo:function(a,n,s){return a(n,s)},MYBTa:function(a,n){return a!==n},UwcpE:t(1559),KCrnt:t(1257),BtuEm:function(a){return a()},XYvxA:function(a,n,s,l){return a(n,s,l)},WYnob:function(a,n){return a|n},tyWwt:t(804),oYgeE:t(1458),HcfhD:function(a,n){return a||n},AWWYw:function(a,n){return a||n},esuqr:"aIJnp",SvUch:"NAVXc",YUujv:function(a){return a()},vBTMq:function(a,n){return a===n},HtBqo:t(873),DxTCz:t(1571),NoMLa:function(a,n){return a||n},kMrXp:t(408),IzNyu:t(848),QqhPA:function(a,n){return a!==n},sEwel:t(807),gTgxx:"DIBIn",qYKXi:function(a,n){return a||n},YOMgD:function(a,n){return a||n},VJZYd:"init QoS"+t(826)+"d",thAWi:t(1357),KdoYr:t(1052)+"id",DRefP:function(a,n){return a===n},turQI:t(1560),MfwIF:t(929),VnVVF:t(681),sxBVp:function(a,n,s,l){return a(n,s,l)},qbdFy:t(396)+t(1594),hrWHu:function(a,n,s,l){return a(n,s,l)},dMYtc:"x_fronti"+t(1693)+"ck",cWEpP:t(396)+"er_is_ack",rDdmY:t(396)+"er_ack_m"+t(597),WKZAY:t(1301),uCvTu:t(592),wNyiB:function(a,n){return a&&n},qtmND:"ack_id",Wyypr:t(1697),IxfmV:function(a){return a()},vWsbb:t(1714),LkMuu:function(a,n){return a(n)},mjsMR:function(a,n,s,l){return a(n,s,l)},KomWo:function(a,n){return a instanceof n},HLKuB:function(a,n){return a(n)},ZLnbR:function(a,n){return a<<n},QrAht:function(a,n){return a(n)},qdAmo:function(a,n){return a&n},yaWmF:function(a,n){return a&n},dyikf:function(a,n){return a&n},KUMBC:function(a,n){return a(n)},xhhCL:function(a,n){return a&n},tbmJw:function(a,n){return a===n},sLdOD:t(1022),zRgaV:t(1046),hQMOE:function(a,n){return a(n)},dzfsB:function(a,n){return a instanceof n},zQDFQ:function(a,n){return a instanceof n},ZUXxQ:"applicat"+t(859),dftXR:"application/json;charset"+t(1324),Ffwib:t(734)+"e",QnzxC:t(982),HXxfR:function(a,n,s,l){return a(n,s,l)},jYyIe:function(a,n){return a!==n},lNyKh:function(a){return a()},IeLiC:function(a,n){return a<n},sOlyj:function(a,n){return a(n)},frCls:function(a,n){return a|n},aFxUr:function(a,n){return a>>>n},RTxCZ:function(a,n){return a+n},CDYJf:function(a,n){return a+n},WhcOl:function(a,n){return a+n},GAJhG:"index out of ran"+t(1104),jjuHv:t(1335),OPOnU:t(1719),RAAAK:function(a,n){return a>n},MDKZU:t(1072)+t(1750)+"e",uTsTm:function(a,n){return a>=n},XmUSf:function(a,n){return a&n},EhoTj:function(a,n){return a+n},sYXnM:function(a,n){return a+n},treLL:function(a,n,s){return a(n,s)},ItlGE:function(a,n){return a>>>n},cjrrJ:function(a,n){return a(n)},wkWIG:function(a,n){return a&n},cXykS:function(a,n){return a&n},fOMiY:function(a,n){return a<<n},SdnbO:function(a,n){return a&n},hOkCZ:"CtPtY",RcxdQ:t(1287)+"4",Bnxxe:function(a,n){return a+n},VHSWc:function(a,n){return a<n},AYShd:function(a,n,s,l){return a(n,s,l)},RSpuK:function(a,n){return a+n},XZSOY:function(a,n){return a+n},FHdkn:function(a,n){return a<<n},szNsM:function(a,n){return a+n},ZhITr:function(a,n){return a<<n},FpwWw:function(a,n){return a+n},RosDR:function(a,n){return a+n},Uxuen:function(a,n){return a+n},OBskJ:function(a,n){return a&n},fgVdi:function(a,n){return a+n},NTWfi:function(a,n){return a>>>n},YKpxM:function(a,n){return a&n},GnlEy:function(a,n){return a+n},vbPji:function(a,n){return a+n},kCqbG:function(a,n){return a+n},yADWF:function(a,n){return a&n},bKITu:function(a,n){return a&n},ChPyu:function(a,n){return a!==n},mQQDQ:"fMzHb",IUBdR:function(a,n){return a+n},Wxvww:function(a,n){return a+n},TZvOj:t(972),lbNDx:function(a,n){return a&n},KWmwH:function(a,n){return a<=n},eKMuw:function(a,n){return a>=n},GozTz:function(a,n){return a|n},VEEmI:function(a,n){return a<n},ALhUa:function(a,n){return a>>>n},KoqIo:function(a,n){return a|n},LOrfe:function(a,n,s,l){return a(n,s,l)},BPRVA:function(a,n){return a===n},hflEt:t(1281),KsTzN:function(a,n){return a<n},gpvIm:function(a,n){return a(n)},RwZVv:"cursor.s"+t(800),VdjvC:function(a,n,s,l){return a(n,s,l)},RczYe:t(493),lQWHz:t(733),xlPex:function(a,n){return a(n)},INPFo:"cursor_f"+t(563),SJGZm:function(a,n){return a<n},nHWBI:function(a,n,s){return a(n,s)},ihNRs:function(a,n,s,l){return a(n,s,l)},ZJdQv:t(1797)+t(565),pKNkh:t(410)+t(1268),pArKs:t(714),VuurF:"INSTANT",Gavrk:"CONTINUE",XhLEC:function(a,n,s,l){return a(n,s,l)},nYiAg:t(389),jlfxN:function(a,n){return a(n)},geUWm:function(a,n){return a!=n},pnyRj:function(a,n){return a instanceof n},YVFXq:function(a,n){return a==n},vFiPj:function(a,n){return a===n},BSdpZ:t(789),hOFha:function(a,n){return a!==n},JtUxO:t(824),JaBka:"jrjGK",edXyH:function(a,n){return a||n},dyCEq:t(1482),eQQBy:function(a,n){return a||n},RtmiX:t(1209),LalBU:function(a,n,s){return a(n,s)},DqfcV:function(a,n,s){return a(n,s)},JTLhL:t(396)+"er_ttl",PdXAg:function(a,n,s,l){return a(n,s,l)},jtWEL:t(385)+"s",dcgHT:function(a,n,s){return a(n,s)},fsJFg:t(1331)+"rsor_name",ltmPu:function(a,n,s){return a(n,s)},QZyhp:function(a,n){return a>n},LqoHC:function(a,n){return a>n},uJCEq:function(a){return a()},xMcvV:function(a,n){return a<n},OLFoF:function(a){return a()},BkeoK:function(a){return a()},HSjCp:function(a){return a()},MDevT:function(a,n){return a&&n},uAnSR:function(a,n){return a(n)},GsAne:t(1477),aAWZQ:t(1038),jiXwi:t(359),oCnHI:function(a){return a()},CKMGA:function(a,n){return a!==n},yOVwQ:function(a,n){return a<n},TRFeM:function(a,n,s){return a(n,s)},xKKpE:function(a){return a()},vTahP:function(a,n){return a===n},Eucsd:function(a,n){return a===n},zCGOa:"auto",sDUFg:t(1015)+t(626)+"s",JoYBf:t(787),LzILe:t(523),euJKf:function(a,n,s){return a(n,s)},mYULk:function(a,n,s){return a(n,s)},KnRAj:function(a,n){return a===n},vLXDf:function(a,n,s){return a(n,s)},OQjXZ:function(a,n){return a!==n},Frtkw:t(429),RQCUC:"kAZjL",tOrbH:function(a,n,s){return a(n,s)},msEYS:t(593),xLQjt:t(914),TSeiK:t(1859),CvYsG:t(1185)+"fer",USLfB:t(323),BBKyH:function(a,n){return a/n},uLCSt:function(a,n){return a===n},NQcVl:t(1077)+t(825)+t(723),YXSAI:function(a,n){return a(n)},HkIHG:t(1077)+t(484)+"s params"+t(1173)+t(1225)+t(1404)+t(1161)+t(1091),qHCIl:function(a,n){return a===n},XKIpJ:t(861),Jmuzo:t(518)+"t",dnskl:t(1436)+t(831)+" reconnect",tNHsd:"offline",APImi:"pagehide",Rmcvb:t(1832),WRZsy:"online",zYLyC:t(1667),WIOUf:t(1018),SHGIG:"bd_did",ITxmp:function(a,n){return a||n},iRKTQ:t(1077)+t(653)+"ddID, de"+t(1564)+t(1515),arDlb:t(1360),JtZyl:function(a){return a()},JHLve:t(601),aJsYh:"fws_1.0.0",RjCuK:function(a,n){return a(n)},pgRXc:function(a,n){return a!==n},EeRfA:function(a,n,s){return a(n,s)},hPtfm:function(a,n){return a!==n},Gaoxd:t(1615),hbpxm:t(1856),RaBDh:function(a,n){return a||n},hlwOc:function(a,n,s){return a(n,s)},uUUVT:function(a,n){return a>n},Mflpk:function(a,n){return a-n},vEJbi:function(a,n,s){return a(n,s)},xVuYA:function(a,n){return a(n)},burqG:t(1388),nsOKP:t(1757)+">",InKYm:function(a,n,s){return a(n,s)},jDxlw:t(1015)+t(667)+"t",RAxvd:t(1127),uuEVT:t(1830),rSlqx:t(1476),SMgZa:function(a,n,s){return a(n,s)},AYePB:function(a,n,s){return a(n,s)},uaEmc:function(a,n,s){return a(n,s)},NjmRT:function(a,n){return a===n},jgfGF:t(1561),dszcQ:function(a,n,s){return a(n,s)},eBIZl:function(a,n){return a!==n},ubkzW:"upXRc",Cjpwc:function(a,n){return a===n},bYtzV:t(350)+"1",PoiyI:function(a,n,s,l){return a(n,s,l)},RkBsk:function(a,n){return a===n},OZyRb:t(890),CxWRv:t(1671),jKyEG:function(a,n){return a===n},lsrUO:t(1275),kxeyq:t(984),wLKLT:function(a,n,s){return a(n,s)},dgdqM:function(a,n,s){return a(n,s)},CNClJ:t(1415)+t(649)+t(451)+t(528),lzkBY:function(a,n){return a instanceof n},HuxLt:"BYOCU",QTXzF:t(610),rVOXH:function(a,n,s){return a(n,s)},hdeUG:t(1248),tVbdN:function(a,n){return a+n},eEsjd:t(1426),tONUu:"bSEoS",VgSfv:function(a,n){return a+n},fVVal:function(a,n,s){return a(n,s)},GpRTV:t(1843),RpUEM:t(719),uWqQk:t(503)+t(1676),RsSwj:function(a,n){return a>>>n},QyeSa:function(a,n){return a>>>n},jJrRA:function(a,n){return a<n},tXKKj:function(a,n){return a<n},bKfyL:function(a,n){return a+n},WDGxA:function(a,n){return a>>>n},AlZhW:function(a,n){return a+n},bfRka:function(a,n){return a!==n},gLawA:function(a,n){return a&n},wQZfo:function(a,n){return a&n},WXCOx:function(a,n){return a>>>n},JIcuR:function(a,n){return a&n},SLvBJ:function(a,n){return a+n},GszAQ:function(a,n){return a|n},DCiGm:function(a,n){return a>>>n},ALtVQ:function(a,n){return a&n},YznpS:function(a,n){return a&n},HVECm:function(a,n){return a|n},ugTMn:function(a,n){return a&n},xWllN:function(a,n){return a>>>n},iGOMx:function(a,n){return a!==n},CGuqa:function(a,n){return a!==n},xZLlx:t(386),jsWNh:function(a,n){return a==n},xFUDR:t(1640),PESwM:function(a,n){return a!=n},kUVjI:function(a,n){return a instanceof n},YGXKm:function(a,n){return a instanceof n},HSPte:function(a,n){return a(n)},XXWsW:function(a,n){return a||n},MlxUl:function(a,n){return a instanceof n},hjwjc:function(a,n){return a(n)},NexPD:function(a,n){return a===n},NzRDN:t(1778),ShnOq:function(a,n){return a==n},bFEnb:t(755)+t(1243)+t(1435),XXXKb:function(a,n){return a!==n},zTSex:t(456),DkxhG:function(a,n){return a!==n},yWyXN:"ThpGs",umyqs:t(1551),wqNrb:function(a,n,s){return a(n,s)},MHSWV:t(1424),VmWjT:function(a,n){return a!=n},oissD:t(1315),zeJMa:function(a,n){return a===n},apuiK:t(654)+t(1587)+t(516)+"pe",cNGFV:function(a,n){return a===n},LwPNh:"Object",YWlhI:function(a,n){return a!=n},QJiPq:function(a,n){return a===n},sLukw:t(612)+"rkerGlobalScope",UrhEB:"ServiceWorkerGlobalScope",fGZvj:function(a,n){return a!=n},Rzmia:function(a,n){return a===n},NDahK:function(a,n){return a!=n},QVIfI:function(a,n){return a!=n},FfxsF:t(908)+t(1503)};Ut.r(Re),Ut.d(Re,{FWS:()=>qg,CustomErrorEvent:()=>ml,createCloseEvent:()=>mt,ReconnectEvent:()=>gl,createErrorEvent:()=>lt,decodedFrame:()=>sn,createOpenEvent:()=>vl,CustomCloseEvent:()=>wl,createReconnectEvent:()=>va,FrontierMessageEvent:()=>yl,encodeFrame:()=>Gt,createMessageEvent:()=>El,OpenEvent:()=>bl,ErrorCode:()=>an,Event:()=>or,MessageEvent:()=>_l});let r="";function i(a=""){let n=t,s="02",l=""+Date[n(370)](),f=r||(r=h(a)),p=Math.random()[n(560)](16)[n(956)](-6);return e[n(1102)](e[n(1102)](e[n(1082)](s,l),f),p)}function o(){let a=t;return e[a(573)](1e4*Date[a(370)](),Math[a(519)](1e4*Math[a(1241)]()))}function c(a){let n=t;return e[n(1102)](e[n(912)](Array,8).join("0"),e[n(1307)](parseInt,a,10).toString(2))[n(956)](-8)}function d(a){let n=t;return e[n(1319)](e.pryiI,e[n(812)])?(_0x73d141|=0,{low:_0xddb4aa,high:e[n(1098)](_0x2e960c,31),unsigned:e.GNERA(_0x12b3c0,0)}):e[n(1102)](e[n(912)](Array,4).join("0"),e[n(1307)](parseInt,a,2)[n(560)](16))[n(956)](-4)}function u(a){let n=t,s=a[n(1317)](/\./)[n(400)](p=>c(p)),l=[];return l[0]=e[n(912)](d,e[n(535)](s[0],s[1])),l[1]=d(e[n(535)](s[2],s[3])),[e[n(1670)],n(1246),n(1246),n(1246),e[n(1670)],e[n(1500)],l[0],l[1]][n(994)]("")}function h(a){let n=t;if(e[n(1183)](e.DPBkh,"xcKXZ"))switch(_0x3096de){case n(1562):case e.dkCwL:return{[n(1369)+_0x3c20e9]:1,"x-tt-env":_0x102816};default:return{}}else{let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(416)](a),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(a);return s?e[n(912)](u,a):l?x(a):e[n(1316)]}}function x(a){let n=t,s="",l=[],f=0,p=0,y=!0,g=e[n(1670)];if(e[n(922)](a[n(509)]("::"),-1)){let T=a[n(1317)]("::");for(let L=0;e.hAqvf(L,T[n(1273)]);L++){let B=T[L];if(e.bFiTg(B.indexOf(":"),0)){let $=B[n(1317)](":");y&&(f=$.length),p+=$[n(1273)];for(let J=0;e[n(1024)](J,$[n(1273)]);J++)if(e.myfIR(4,$[J].length)){let Be=g[n(1556)+"g"](0,e[n(473)](4,$[J].length)),wt=Be[n(1710)]($[J]);l[n(1097)](wt)}else l[n(1097)]($[J]);y=!1}else{if(e.GLIFp(4,B[n(1273)])){let $=g[n(1556)+"g"](0,4-B[n(1273)]),J=$[n(1710)](B);l[n(1097)](J)}else l.push(B);y&&(f+=1),p+=1,y=!1}}let C="";for(let L=0;e[n(1024)](L,e[n(473)](8,p));L++)C=C[n(1710)](g);for(let L=0;e[n(622)](L,l[n(1273)]);L++)e[n(1319)](L,f)&&(s=s[n(1710)](C)),s=s[n(1710)](l[L]);return s}{let T=a[n(1317)](":");for(let C=0;e[n(1211)](C,T.length);C++)if(e[n(1808)]!==e[n(1497)]){let L=T[C];if(e[n(1345)](4,T[C][n(1273)])){if(e.vBbox(n(665),e[n(467)]))return this[n(570)+n(324)+n(1159)](_0x18960e),_0x482067();{let B=g[n(1556)+"g"](0,e.VyVmE(4,T[C][n(1273)])),$=B.concat(L);s=s[n(1710)]($)}}else s=s[n(1710)](L)}else{if(!this[n(1718)+n(874)]()||this["_readyCl"+n(979)])return;this[n(1340)+"tManager"]?.[n(1121)+"pointCon"+n(915)](),this["_pingLos"+n(1325)]?.[n(468)+n(798)](),this[n(975)]?this[n(1106)+n(710)](1001,e.kUzyV,!0):this[n(1205)]()}return s}}function m(a,n){let s=t,l=a[s(412)];e[s(886)](void 0,l)&&(e[s(635)](pe,n,10),e[s(1306)](U,n,l));let f=a[s(897)];e[s(886)](void 0,f)&&(e.fjVHL(pe,n,18),U(n,f))}function w(a){let n=t,s={};e:for(;!K(a);){let l=e[n(912)](le,a);switch(l>>>3){case 0:break e;case 1:s[n(412)]=e[n(1306)](P,a,le(a));break;case 2:s[n(897)]=e[n(788)](P,a,le(a));break;default:e[n(788)](k,a,e[n(640)](7,l))}}if(e[n(1319)](void 0,s[n(412)]))throw new Error(e[n(1239)]);if(e.qUfPJ(void 0,s.value))throw new Error(n(852)+n(340)+n(1473)+n(897));return s}function v(a){let n=t;if(e[n(1421)](e[n(1818)],e[n(880)])){if(e[n(1021)](_0x54f810,1)||_0x3155bc>_0x419dc3)return e[n(912)](_0x224f6c,_0x1cf694);e.nYeaC(e[n(1102)](_0x3e59b2,_0x46c3f6),_0x41aa6a)&&(_0x357a8d=e[n(912)](_0x11f189,_0xc4512d),_0x21b356=0);let s=_0x5830b0[n(1398)](_0x389bb0,_0xe7756b,_0x305212+=_0x198355);return e[n(640)](7,_0x35ae6b)&&(_0x7dcc94=e[n(573)](e[n(1858)](7,_0x1b7273),1)),s}else{let s=e[n(1026)](D);return _(a,s),e[n(1263)](M,s)}}function _(a,n){let s=t,l={BTZbo:function(Je,Ze,oi){return e[H(1307)](Je,Ze,oi)},XSxrQ:function(Je,Ze){return Je(Ze)},RFPNE:e[s(1419)],RJqBB:function(Je,Ze){return e[s(345)](Je,Ze)}},f=a.SeqID;if(e[s(886)](void 0,f)){if(e[s(1319)](e[s(515)],e[s(1058)]))return e[s(1013)](s(884),typeof _0x133eba)?e[s(674)]:"";e[s(542)](pe,n,8),e[s(1307)](gt,n,f)}let p=a.LogID;e.cBvUk(void 0,p)&&(e[s(635)](pe,n,16),gt(n,p));let y=a[s(421)];e.GLIFp(void 0,y)&&(e[s(1299)](pe,n,24),e.RSGZT(gt,n,e[s(1147)](R,y)));let g=a[s(1264)];if(e.PFigN(void 0,g)){if(e[s(602)](e[s(864)],e[s(1444)]))return new _0x1104af(Je=>{let Ze=s;l[Ze(715)](_0x173164,Je,this[Ze(328)+"rvalValue"](_0x574246))});pe(n,32),e[s(1299)](gt,n,e[s(796)](R,g))}let T=a.headers;if(e[s(1345)](void 0,T))for(let Je of T)if(e.boInv(e[s(1861)],e.fjoHg)){pe(n,42);let Ze=e.kEdcz(D);e[s(1796)](m,Je,Ze),e[s(1848)](pe,n,Ze.limit),e.iwdJE(j,n,Ze),e[s(912)](O,Ze)}else _0x3f7c2f[s(1694)]["removeCh"+s(508)](_0x5af763),_0x151aea[s(1148)+s(1742)]=void 0,l[s(1220)](_0x33d936,_0xeac700&&_0x2b4002.msg||l[s(381)]);let C=a[s(1403)+s(1781)];e.iaBaf(void 0,C)&&(pe(n,50),e[s(635)](U,n,C));let L=a[s(896)+s(1230)];e[s(1427)](void 0,L)&&(e[s(991)](pe,n,58),e[s(1721)](U,n,L));let B=a[s(448)];B!==void 0&&(pe(n,66),pe(n,B.length),e[s(1848)](oe,n,B));let $=a.LogIDNew;e[s(1555)](void 0,$)&&(e.LSblA(pe,n,74),e[s(1848)](U,n,$));let J=a["serverTi"+s(1312)];if(e[s(886)](void 0,J))if(e[s(829)](e[s(1789)],"YecKp"))e[s(1214)](pe,n,82),e.UDBMw(U,n,J);else{let Je=new _0x25abf6(l.RJqBB(2,_0x1361ff));Je[s(1487)](_0x425d41),_0x2c66a1[s(1738)]=Je}let Be=a[s(951)];Be!==void 0&&(e[s(1299)](pe,n,90),U(n,Be));let wt=a[s(1027)+"e"];wt!==void 0&&(e[s(1371)](pe,n,96),e.UDBMw(gt,n,R(wt)))}function E(a){let n=t,s={GIyYj:function(l,f){return e[H(1211)](l,f)},QZASw:function(l,f){return e[H(1858)](l,f)},vkhbT:function(l,f){return e.QkrcJ(l,f)},KsmgW:function(l,f){return e[H(1707)](l,f)},QCSnt:function(l,f){return e.GGBSV(l,f)},LhXoV:function(l,f){return l&f},mmDuv:function(l,f){return e[H(1098)](l,f)},Hepid:function(l,f){return l>>f},qZEkr:function(l,f){return e.GGBSV(l,f)}};if(e[n(878)](e.ONEGZ,e[n(530)]))return e.xQtvM(S,e[n(384)](F,a));s[n(903)](_0x2d6c23,2048)?_0x1c7d74[_0x2b56b1++]=s[n(1690)](s.vkhbT(_0x42e44e>>6,31),192):(s[n(1593)](_0x1a8f29,65536)?_0xff208c[_0x346640++]=s.QCSnt(s.LhXoV(s[n(1191)](_0x178cc8,12),15),224):(_0x423d58[_0x1d1c13++]=s[n(1690)](s[n(1191)](_0x5737b8,18)&7,240),_0x2b127f[_0x4c8e43++]=s[n(698)](_0x4657b5,12)&63|128),_0x337234[_0x557add++]=s[n(857)](s[n(698)](_0x47a88d,6)&63,128)),_0x50ebeb[_0x3846ab++]=s[n(932)](63,_0x2f1d11)|128}function S(a){let n=t,s={};e:for(;!e[n(384)](K,a);){let l=le(a);switch(l>>>3){case 0:break e;case 1:s.SeqID=e[n(504)](At,a,!0);break;case 2:s[n(1756)]=At(a,!0);break;case 3:s.service=le(a);break;case 4:s[n(1264)]=e[n(586)](le,a);break;case 5:{let f=I(a);(s.headers||(s.headers=[])).push(e[n(1334)](w,a)),a[n(418)]=f;break}case 6:s[n(1403)+n(1781)]=e[n(788)](P,a,e[n(796)](le,a));break;case 7:s[n(896)+n(1230)]=e[n(474)](P,a,e.wPqZx(le,a));break;case 8:s[n(448)]=e[n(923)](te,a,e[n(919)](le,a));break;case 9:s[n(377)]=e.uAvBM(P,a,e.xQtvM(le,a));break;case 10:s[n(1547)+n(1312)]=e[n(923)](P,a,e[n(1263)](le,a));break;case 11:s[n(951)]=e.fjVHL(P,a,e[n(1334)](le,a));break;case 12:s.frameType=e[n(1334)](le,a);break;default:e[n(1214)](k,a,7&l)}}if(s.SeqID===void 0)throw new Error(e[n(762)]);if(e[n(672)](void 0,s[n(1756)]))throw new Error(n(852)+"required"+n(1473)+n(1756));if(e[n(1421)](void 0,s[n(421)]))throw new Error(e[n(507)]);if(e[n(1149)](void 0,s.method))throw new Error(e[n(1240)]);return s}function I(a){let n=t,s=e[n(1147)](le,a),l=a[n(418)];return a.limit=e[n(535)](a[n(546)],s),l}function k(a,n){let s=t;switch(n){case 0:for(;e[s(534)](128,ne(a)););break;case 2:V(a,e[s(586)](le,a));break;case 5:e[s(1848)](V,a,4);break;case 1:e[s(1432)](V,a,8);break;default:throw new Error(e[s(535)]("Unimplem"+s(1785)+"pe: ",n))}}function R(a){let n=t;return a|=0,{low:a,high:e[n(1098)](a,31),unsigned:e[n(1709)](a,0)}}let b=[];function D(){let a=t,n=b[a(676)]();return n?(n[a(546)]=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){b[t(1097)](a)}function F(a){return{bytes:a,offset:0,limit:a[t(1273)]}}function M(a){let n=t,s=a.bytes,l=a[n(418)];return e[n(1421)](s.length,l)?s:s[n(790)](0,l)}function V(a,n){let s=t;if(e[s(1123)](e[s(875)](a[s(546)],n),a[s(418)]))throw new Error(e[s(1009)]);a[s(546)]+=n}function K(a){let n=t;return e[n(634)](a[n(546)],a[n(418)])}function ie(a,n){let s=t,l=a.bytes,f=a.offset,p=a[s(418)],y=f+n;if(y>l[s(1273)]){let g=new Uint8Array(e[s(345)](2,y));g[s(1487)](l),a[s(1738)]=g}return a[s(546)]=y,e[s(922)](y,p)&&(a.limit=y),f}function Y(a,n){let s=t,l=a[s(546)];if(e.qvcWc(e[s(1201)](l,n),a[s(418)]))throw new Error(e.RRBRn);return a[s(546)]+=n,l}function te(a,n){let s=t,l=e[s(1114)](Y,a,n);return a.bytes.subarray(l,e[s(875)](l,n))}function oe(a,n){let s=t,l=e[s(1796)](ie,a,n[s(1273)]);a[s(1738)][s(1487)](n,l)}function P(a,n){let s=t,l=Y(a,n),f=String[s(1155)+"Code"],p=a[s(1738)],y="\uFFFD",g="";for(let T=0;e[s(1024)](T,n);T++){let C=p[T+l],L,B,$,J;e[s(1480)](e[s(1078)](128,C),0)?g+=f(C):e[s(1543)](e[s(1643)](224,C),192)?e[s(634)](T+1,n)?g+=y:(L=p[e[s(1599)](e[s(1102)](T,l),1)],e[s(1183)](e.ywXib(192,L),128)?g+=y:(J=e.lHVve(e[s(708)](31,C),6)|e[s(640)](63,L),e[s(622)](J,128)?g+=y:(g+=f(J),T++))):e.ZcMgh(240,C)==224?e[s(1607)](T,2)>=n?g+=y:(L=p[e[s(954)](e[s(1110)](T,l),1)],B=p[e[s(573)](e[s(1753)](T,l),2)],e.RqdrI(e[s(397)](e[s(1036)](L,e[s(785)](B,8)),49344),32896)?g+=y:(J=e[s(871)](e.VfTin(e[s(534)](15,C),12)|e[s(785)](e[s(1238)](63,L),6),63&B),J<2048||e[s(1682)](J,55296)&&e[s(443)](J,57343)?g+=y:(g+=e.rierQ(f,J),T+=2))):e.MBBHL(e[s(708)](248,C),240)?e.WMBye(e[s(1409)](T,3),n)?g+=y:(L=p[e.xehFD(T,l)+1],B=p[e.dHtwQ(e.EQPQJ(T,l),2)],$=p[e[s(1387)](e.oypxS(T,l),3)],e.kDjEW(e[s(1406)](e[s(1036)](L,e[s(1647)](B,8)),e[s(945)]($,16))&12632256,8421504)?g+=y:s(999)===e[s(747)]?(J=e.zdbxW(e[s(1406)](e.nlCrf(e.Zquuh(7,C),18),e.rWNLl(e[s(1289)](63,L),12)),e[s(1216)](63&B,6))|e.wRAQZ(63,$),e[s(703)](J,65536)||e[s(922)](J,1114111)?g+=y:(J-=65536,g+=f(e[s(1387)](e[s(1098)](J,10),55296),e[s(1054)](1023,J)+56320),T+=3)):(this[s(778)](e.AqBFX,_0x328c39),this[s(1634)]&&this.onclose(_0x393711))):g+=y}return g}function U(a,n){let s=t,l=n[s(1273)],f=0;for(let g=0;e[s(1442)](g,l);g++){let T=n[s(711)+"At"](g);T>=55296&&e[s(1112)](T,56319)&&e[s(532)](g+1,l)&&(T=e[s(1802)](T<<10,n[s(711)+"At"](++g))-56613888),f+=T<128?1:e[s(780)](T,2048)?2:e[s(780)](T,65536)?3:4}e[s(1578)](pe,a,f);let p=e.Qrvqu(ie,a,f),y=a[s(1738)];for(let g=0;e[s(1828)](g,l);g++){let T=n[s(711)+"At"](g);e[s(1682)](T,55296)&&e.lBfDM(T,56319)&&e[s(703)](e.YPEtw(g,1),l)&&(T=e[s(1607)](e[s(1134)](T,10),n[s(711)+"At"](++g))-56613888),e[s(1211)](T,128)?y[p++]=T:(T<2048?y[p++]=e.djjMv(T,6)&31|192:(T<65536?y[p++]=e[s(871)](T>>12&15,224):(y[p++]=e[s(435)](e[s(1402)](T,18),7)|240,y[p++]=e[s(1631)](T,12)&63|128),y[p++]=e[s(1406)](e[s(1044)](T,6)&63,128)),y[p++]=e[s(871)](e[s(397)](63,T),128))}}function j(a,n){let s=t,l=e[s(1307)](ie,a,n[s(418)]),f=a[s(1738)],p=n.bytes;for(let y=0,g=n[s(418)];e[s(1330)](y,g);y++)f[y+l]=p[y]}function ne(a){let n=t;if(n(887)!=="xfdYP"){let s=_0x199eef[n(1738)],l=_0x3ec906[n(418)];return s.length===l?s:s[n(790)](0,l)}else return a.bytes[e[n(1534)](Y,a,1)]}function Ve(a,n){let s=t,l={MXQOU:function(f,p){return f+p}};if(e[s(602)](e.vOAjI,e[s(583)])){let f=this[s(964)+"Queue"][s(363)]((p,y)=>(p+=y&&y.byteLength||0,p),0);return l.MXQOU(f,this[s(975)]?this[s(975)][s(751)+"Amount"]:0)}else{let f=ie(a,1);a[s(1738)][f]=n}}function le(a){let n=t,s=0,l=0,f;do e.wZbnP(n(1505),e[n(1215)])?(f=ne(a),e.ukFkw(s,32)&&(l|=e[n(945)](e.boTJX(127,f),s)),s+=7):_0x46845b.d=(p,y)=>{let g=n;for(var T in y)_0x1ccc0a.o(y,T)&&!_0x5d86a0.o(p,T)&&_0x5996ad[g(1566)+"operty"](p,T,{enumerable:!0,get:y[T]})};while(e[n(809)](128,f));return l}function pe(a,n){let s=t;for(n>>>=0;e.fMaQo(n,128);)Ve(a,e[s(1036)](e[s(1460)](127,n),128)),n>>>=7;Ve(a,n)}function At(a,n){let s=t,l={hllCw:function(T,C){return e[H(1769)](T,C)}},f=0,p=0,y=0,g;if(g=e[s(1334)](ne,a),f=e[s(976)](127,g),e.tEdcG(128,g)&&(g=e[s(486)](ne,a),f|=e[s(1134)](e[s(1779)](127,g),7),e[s(1289)](128,g)&&(g=ne(a),f|=e[s(1107)](e[s(1054)](127,g),14),e[s(435)](128,g)))){if(e[s(452)](s(1485),e.Ipfzw))return l[s(520)](this.count,this[s(322)+"ount"]);g=e.bPmPe(ne,a),f|=(127&g)<<21,e.uAPEt(128,g)&&(g=e.iNMMN(ne,a),p=e[s(1352)](127,g),e[s(534)](128,g)&&(g=e.bPmPe(ne,a),p|=e[s(1452)](127,g)<<7,e[s(708)](128,g)&&(g=e[s(356)](ne,a),p|=e[s(1011)](127,g)<<14,128&g&&(g=ne(a),p|=e[s(906)](e[s(1431)](127,g),21),e[s(616)](128,g)&&(g=e[s(693)](ne,a),y=e.NiSRo(127,g),e[s(511)](128,g)&&(g=e[s(834)](ne,a),y|=e[s(1355)](127&g,7)))))))}return{low:e[s(1092)](f,e.bBthj(p,28)),high:e[s(342)](p,4)|e.QymjU(y,24),unsigned:n}}function gt(a,n){let s=t;if(e[s(735)](e[s(636)],s(514)))try{return!!this._qosDB}catch(l){return _0x48e3f2[s(446)](l),!1}else{let l=e.ycJHk(n[s(1396)],0),f=e[s(342)](e[s(1092)](e[s(1086)](n[s(1396)],28),e[s(906)](n[s(1228)],4)),0),p=e[s(1086)](n[s(1228)],24),y=e[s(927)](0,p)?f===0?e[s(1707)](l,16384)?e[s(413)](l,128)?1:2:e[s(1021)](l,2097152)?3:4:e[s(780)](f,16384)?e[s(1442)](f,128)?5:6:e[s(1207)](f,2097152)?7:8:e[s(1828)](p,128)?9:10,g=ie(a,y),T=a[s(1738)];switch(y){case 10:T[e[s(1102)](g,9)]=e[s(1267)](e[s(342)](p,7),1);case 9:T[e[s(875)](g,8)]=e[s(502)](9,y)?128|p:127&p;case 8:T[e[s(513)](g,7)]=e.LoSiP(8,y)?e[s(1025)](e[s(1100)](f,21),128):e[s(867)](e[s(342)](f,21),127);case 7:T[e[s(1846)](g,6)]=y!==7?e[s(644)](f,14)|128:e[s(1086)](f,14)&127;case 6:T[e[s(599)](g,5)]=e[s(1555)](6,y)?e[s(644)](f,7)|128:e[s(1290)](f,7)&127;case 5:T[g+4]=y!==5?e[s(1784)](128,f):127&f;case 4:T[e[s(573)](g,3)]=e[s(971)](4,y)?e[s(802)](l>>>21,128):e[s(867)](e.fsEQW(l,21),127);case 3:T[e[s(1195)](g,2)]=e.PFigN(3,y)?e[s(862)](e[s(1100)](l,14),128):e.eBpZy(e[s(1045)](l,14),127);case 2:T[e[s(1591)](g,1)]=y!==2?e[s(549)](e[s(342)](l,7),128):e.YDVFS(l>>>7,127);case 1:T[g]=e.YpVco(1,y)?e[s(1092)](128,l):e[s(1342)](127,l)}}}function sn(a){return e[t(834)](E,a)}function Gt(a){let n=t;return e.DJyWH===e[n(815)]?e[n(512)](v,a):(_0x26fe2c||(_0x22024c=_0x2aa9ee[n(1488)]()[n(1323)](_0x11fe4b.bind(_0x538871,e[n(1514)]))),_0x2ed8d8)}let on=65536,ri=e[t(742)],we=on*on,Ae=e.vjCkX(we,we),sr=e[t(840)](Ae,2),Oe=String[t(1157)+"e"][t(711)+"At"];class ue{constructor(n,s,l){let f=t,p={tmPQQ:function(y,g,T){return e.cBwuL(y,g,T)},htaBd:f(1298)};e[f(1495)]===e.BqZRA?this[f(778)](f(1298),p[f(992)](_0x19e2df,p[f(494)],{message:this[f(457)+f(1350)+f(1702)](_0x24e2b5)})):(this.isLong=!0,this[f(1396)]=e[f(549)](0,n),this[f(1228)]=e[f(997)](0,s),this[f(692)]=!!l)}static isLong(n){return n&&n[t(1660)]===!0}static[t(1616)](n,s,l){return new ue(n,s,l)}static fromBytes(n,s,l){let f=t;return l?ue[f(1179)+f(1144)](n,s):ue[f(1179)+f(1646)](n,s)}static["fromByte"+t(1144)](n,s){let l=t;return new ue(e[l(1025)](e[l(1784)](n[0]|e[l(1107)](n[1],8),e[l(1601)](n[2],16)),e[l(455)](n[3],24)),e[l(1092)](e[l(862)](e[l(1784)](n[4],n[5]<<8),e.TDrDV(n[6],16)),n[7]<<24),s)}static["fromByte"+t(1646)](n,s){let l=t;return new ue(e[l(1347)](e[l(1730)](e.wIIgw(n[4],24)|n[5]<<16,e.bBthj(n[6],8)),n[7]),e[l(1744)](e[l(871)](e[l(1343)](n[0],24),e[l(1647)](n[1],16))|e[l(1343)](n[2],8),n[3]),s)}static[t(1786)](n){let s=t;return n===ri?pl:new ue(e[s(930)](e[s(1700)](e[s(1804)](e[s(1347)](Oe.call(n,0),e[s(1051)](Oe.call(n,1),8)),e.epNHw(Oe[s(1398)](n,2),16)),e[s(941)](Oe[s(1398)](n,3),24)),0),e[s(342)](e[s(1025)](e[s(802)](Oe[s(1398)](n,4),Oe[s(1398)](n,5)<<8)|e.kZypW(Oe[s(1398)](n,6),16),Oe[s(1398)](n,7)<<24),0),!0)}toHash(){let n=t;return String.fromCharCode(e[n(1219)](255,this[n(1396)]),e[n(976)](this.low>>>8,255),e[n(918)](e.ZiXTI(this[n(1396)],16),255),e[n(1100)](this[n(1396)],24),e[n(1431)](255,this[n(1228)]),e[n(943)](e.JRNMS(this.high,8),255),e[n(1384)](e[n(1235)](this[n(1228)],16),255),e[n(524)](this[n(1228)],24))}static fromNumber(n,s=!0){let l=t;if(e.OFfii(isNaN,n))return s?tg:pl;if(s){if(e[l(682)](n,Ae))return rg}else{if(e[l(1341)](n,-sr))return ig;if(e[l(1745)](e[l(1510)](n,1),sr))return ng}return ue[l(1616)](e[l(872)](n%we,0),e[l(1580)](e.grool(n,we),0),s)}[t(1274)](){let n=t;return this.unsigned?e[n(355)](e[n(345)](e[n(1733)](this.high,0),we),e[n(644)](this[n(1396)],0)):e[n(424)](e[n(537)](this[n(1228)],we),e[n(1585)](this[n(1396)],0))}[t(1374)](){let n=t;return e[n(1421)](0,this[n(1228)])&&e[n(732)](0,this[n(1396)])}[t(844)](n){let s=t;ue[s(1660)](n)||(n=ue[s(845)+"er"](n));let l=e[s(1733)](this.high,16),f=e[s(325)](65535,this[s(1228)]),p=this.low>>>16,y=65535&this[s(1396)],g=e[s(1733)](n[s(1228)],16),T=e[s(1643)](65535,n[s(1228)]),C=e[s(1290)](n.low,16),L=e.DzXSz(65535,n[s(1396)]),B=0,$=0,J=0,Be=0;return Be+=e[s(422)](y,L),J+=e.RWFpZ(Be,16),Be&=65535,J+=p+C,$+=e[s(1086)](J,16),J&=65535,$+=e[s(1816)](f,T),B+=e[s(1585)]($,16),$&=65535,B+=e[s(573)](l,g),B&=65535,ue[s(1616)](e[s(1744)](e[s(1601)](J,16),Be),e[s(997)](B<<16,$),this[s(692)])}[t(1668)](n){let s=t;return ue[s(1660)](n)||(n=ue[s(845)+"er"](n)),e[s(1284)](this[s(692)],n[s(692)])&&e[s(1733)](this[s(1228)],31)===1&&e[s(781)](e[s(1429)](n[s(1228)],31),1)?!1:e.qUfPJ(this[s(1228)],n[s(1228)])&&e[s(1448)](this[s(1396)],n[s(1396)])}[t(447)](){let n=t,s={AgPsy:function(l,f){return e[H(1800)](l,f)},wSrrS:function(l,f){return l+f},qsCNn:function(l,f){return e[H(599)](l,f)}};if(e[n(1149)](e[n(1698)],e[n(571)])){let l=_0x35705b[n(1273)]&&_0x2d6b7c[0];if(s[n(1291)](l,_0x46faf1))throw l;let f=new _0x241bec(s[n(1417)](n(850)+n(836),l?s[n(1417)](s[n(637)](" (",l[n(623)]),")"):""));throw f[n(1177)]=l,l}else return this[n(1396)]===-1&&e[n(1149)](-1,this[n(1228)])?ue.fromBits(0,0,this[n(692)]):e.fWbDZ(-1,this[n(1396)])?ue[n(1616)](0,e[n(1528)](this.high,1),this[n(692)]):ue[n(1616)](e.oTrJK(this.low,1),this.high,this.unsigned)}[t(663)](n){let s=t;return n?this[s(1016)+"E"]():this[s(900)+"E"]()}[t(1016)+"E"](){let n=t,s=this[n(1228)],l=this[n(1396)];return[e[n(1194)](255,l),e[n(1733)](l,8)&255,e.FwRXD(l,16)&255,e[n(644)](l,24),255&s,e[n(655)](s>>>8,255),e[n(525)](s,16)&255,e[n(1328)](s,24)]}toBytesBE(){let n=t,s=this.high,l=this[n(1396)];return[s>>>24,e[n(1290)](s,16)&255,e[n(1779)](e[n(648)](s,8),255),255&s,e[n(738)](l,24),e.KoPbC(e[n(1093)](l,16),255),e[n(1290)](l,8)&255,255&l]}}let pl=new ue(0,0,!1),tg=new ue(0,0,!0),ng=ue.fromBits(-1,2147483647,!1),rg=ue[t(1616)](-1,-1,!0),ig=ue[t(1616)](0,-2147483648,!1);var an=(function(a){let n=t,s=(n(957)+n(379))[n(1317)]("|"),l=0;for(;;){switch(s[l++]){case"0":a[a[e[n(633)]]=5002]=e[n(633)];continue;case"1":return a;case"2":a[a[e[n(756)]]=5003]=e[n(756)];continue;case"3":a[a[e[n(1174)]]=5005]=e[n(1174)];continue;case"4":a[a[e[n(1665)]]=5004]=e[n(1665)];continue;case"5":a[a[n(1151)+n(893)]=5001]=e[n(458)];continue}break}})({});class or{constructor(n){let s=t;this[s(321)]=n,this.target=null}}class gl extends or{constructor(n,s){let l=t;super(n),this.message=s&&s[l(623)]||null}}class ml extends or{constructor(n,s){let l=t,f=(l(327)+l(858))[l(1317)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[l(623)]=s&&s[l(623)]||"";continue;case"1":this[l(1688)]=s&&s.filename||"";continue;case"2":super(n);continue;case"3":this[l(1298)]=s&&s[l(1298)]||null;continue;case"4":this[l(1209)]=s&&s[l(1209)]||5001;continue;case"5":this[l(1295)]=s&&s[l(1295)]||0;continue;case"6":this[l(1067)]=s&&s[l(1067)]||0;continue}break}}}class wl extends or{constructor(n,s){let l=t,f="1|0|4|3|2"[l(1317)]("|"),p=0;for(;;){switch(f[p++]){case"0":this[l(1209)]=s&&s[l(1209)]||0;continue;case"1":super(n);continue;case"2":this[l(437)+l(1535)]=s&&s[l(437)+l(1535)]||!1;continue;case"3":this[l(1813)]=s&&s[l(1813)]||!1;continue;case"4":this[l(754)]=s&&s.reason||"";continue}break}}}class _l extends or{constructor(n,s){let l=t,f={LPcuW:function(p,y){return p<y},eytmk:function(p,y){return p!==y},mvQiR:function(p,y){return e[H(473)](p,y)}};if(e[l(1680)](l(1260),e[l(647)]))super(n),this[l(466)]=s&&s[l(466)]||null;else{let p=_0x9d1f90[l(1317)](":");for(let y=0;eIMDZb[l(1663)](y,p[l(1273)]);y++){let g=p[y];if(eIMDZb[l(1308)](4,p[y][l(1273)])){let T=_0x123283[l(1556)+"g"](0,eIMDZb[l(1111)](4,p[y][l(1273)])),C=T.concat(g);_0xce5169=_0xe0f237[l(1710)](C)}else _0x9fed03=_0x4b8d85[l(1710)](g)}return _0x490a9e}}}class yl extends _l{constructor(n,s){let l=t;super(n),this.data=s&&s[l(466)]||null,this.message=s&&s[l(623)]||null}}class bl extends or{constructor(n,s){let l=t,f={xzfyw:e[l(633)],QORCh:e.zkfzT,NMQkc:e[l(458)],vEVBD:e[l(1174)]};if(e[l(1773)](l(946),e[l(651)]))super(n),this.data=s&&s[l(466)]||null;else{let p=(l(1814)+l(394))[l(1317)]("|"),y=0;for(;;){switch(p[y++]){case"0":return _0x257a57;case"1":_0x3e7f26[_0x404eaf[yCNTZU.xzfyw]=5002]=yCNTZU.xzfyw;continue;case"2":_0x56160f[_0x2072ef[yCNTZU.QORCh]=5004]=yCNTZU[l(541)];continue;case"3":_0xdc5d5f[_0x37da62["MAX_RETR"+l(1066)+"R"]=5003]="MAX_RETR"+l(1066)+"R";continue;case"4":_0x44f6a7[_0x29cded[yCNTZU[l(1286)]]=5001]=yCNTZU[l(1286)];continue;case"5":_0x25ecc6[_0x65cc8d[yCNTZU[l(803)]]=5005]=yCNTZU[l(803)];continue}break}}}}function lt(a,{message:n,code:s,error:l}){return new ml(a,{message:n,code:s,error:l})}function mt(a,{code:n,reason:s,wasClean:l,willReconnect:f}){return new wl(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function El(a,{data:n,message:s}){return new yl(a,{data:n,message:s})}function vl(a,{data:n}){return new bl(a,{data:n})}function va(a,{message:n}){return new gl(a,{message:n})}class Sl{constructor(n,s){let l=t;this.endpoints=n,this[l(380)+"es"]=s,this[l(483)+"ndex"]=0,this["currentE"+l(1684)+l(1790)+"t"]=0}[t(1121)+t(614)+t(915)](){let n=t;this[n(483)+n(974)]=0,this[n(1592)+n(1684)+n(1790)+"t"]=0}[t(1087)+"es"](){let n=t;this["currentE"+n(1684)+"riesCount"]=0}[t(1712)+t(398)+"nt"](){let n=t;if(e[n(1313)](e[n(547)],e[n(931)]))return this[n(548)+"s"][this.currentIndex];if(this._options["disableAutoRecon"+n(671)]||this[n(1636)+n(979)])return;this[n(497)+"econnect"]()}[t(1712)+t(398)+t(1253)+t(1438)](){let n=t;return this[n(1592)+"ndpointT"+n(1790)+"t"]}[t(744)+t(1071)+"es"](){let n=t,s={MnAxb:function(l,f){return e[H(1650)](l,f)},SHXdB:function(l,f){return e[H(771)](l,f)},GdMkY:function(l,f){return e[H(983)](l,f)},GRTuR:function(l,f){return l+f},RkYLK:function(l,f){return e.kvnVl(l,f)},EVAsJ:function(l,f){return e[H(573)](l,f)},bwvJR:function(l,f){return e.zFPXJ(l,f)},iuUVQ:function(l,f){return l+f}};if(e[n(1773)](n(1840),e[n(471)]))return!!(e.dNXZT(this[n(483)+"ndex"],this.endpoints[n(1273)])||e[n(822)](this[n(483)+n(974)],e[n(473)](this[n(548)+"s"][n(1273)],1))&&this[n(1592)+n(1684)+n(1790)+"t"]===this[n(380)+"es"]);{let l=new _0xf732b0(s[n(462)](s.MnAxb(s[n(462)](_0x84e686[s[n(1481)](_0x4b904f,4)]<<24,s[n(1638)](_0x3cc195[s[n(1146)](_0x330cac,5)],16)),s[n(1638)](_0x3a0713[_0xc73691+6],8)),_0x3c7d97[_0x4ad8a1+7]),s[n(805)](s[n(1638)](_0x3cb4be[_0x98576e+0],24)|s[n(1638)](_0x537a9a[s[n(842)](_0x325ddf,1)],16),s[n(1029)](_0x171495[s[n(842)](_0x1dc267,2)],8))|_0x5e33be[_0x3ff6a6+3],!0);return _0x513d93+=8,{value:l,offset:s[n(730)](_0x5285ac,8)}}}[t(1400)+t(590)+"ointReachedMaxRetries"](){let n=t;if(e[n(502)](e[n(1540)],e[n(895)]))return this["currentI"+n(974)]==this[n(548)+"s"].length?!0:e[n(1708)](this[n(1592)+n(1684)+n(1790)+"t"],this[n(380)+"es"]);_0x5d1486(_0x501861,58),_0x727976(_0x2b063f,_0x3aed61)}[t(480)+t(727)+t(1664)+t(688)+t(1590)](){let n=t;return this[n(1592)+n(1684)+n(1790)+"t"]=1,this["currentI"+n(974)]++,this[n(548)+"s"][this["currentI"+n(974)]]}[t(1712)+"ntEndpointAndUpd"+t(1741)](){let n=t;return this.currentEndpointTriesCount++,this["getCurre"+n(398)+"nt"]()}}let ar=(e.VmWjT(e.PwRLE,typeof globalThis)&&e.oissD===globalThis[t(1397)+t(556)][t(493)]||e[t(1064)](e[t(414)],typeof window)&&e[t(1596)](t(1315),window[t(1397)+t(556)].name))&&e.geUWm(e[t(414)],typeof document),Ln=e[t(1489)](e[t(414)],typeof globalThis)&&(e[t(339)](t(631),globalThis[t(1397)+t(556)][t(493)])||e[t(349)](e[t(432)],globalThis[t(1397)+"tor"].name))&&e[t(414)]!=typeof tt,ii=(e[t(414)]!=typeof globalThis&&e[t(656)](e[t(1860)],globalThis["construc"+t(556)][t(493)])||t(1302)+"d"==typeof globalThis||e[t(1062)]("undefined",typeof globalThis)&&!!globalThis[t(745)+"Bridge"])&&e[t(1489)](e[t(414)],typeof wx),si=e[t(986)](e[t(414)],typeof globalThis)&&(e.LAaTP(e[t(432)],globalThis[t(1397)+t(556)][t(493)])||e[t(828)](e[t(1339)],globalThis[t(1397)+"tor"][t(493)])||e[t(1199)](e.UrhEB,globalThis[t(1397)+t(556)][t(493)]))&&e[t(1059)](e[t(414)],typeof self),sg=e.VmWjT(t(1302)+"d",typeof globalThis)&&e.Rzmia(e[t(1860)],globalThis.constructor[t(493)])&&e.NDahK(e[t(414)],typeof global)&&e[t(662)](e.LwPNh,global[t(1397)+"tor"][t(493)])&&e.PwRLE!=typeof process&&!!process[t(1788)];class Sa{constructor(){this._listeners={}}[t(778)](n,...s){let l=t,f=this._listeners[n];if(f)f[l(956)]()[l(540)](p=>p.fn.apply(p[l(1365)],s));else if(l(1298)===n&&!this.onerror){let p=s[l(1273)]&&s[0];if(p instanceof Error)throw p;let y=new Error(e[l(1679)]+(p?e[l(1387)](" (",p[l(623)])+")":""));throw y[l(1177)]=p,p}return this}[t(838)](n,s){let l=t;if(n===void 0)this[l(1532)+"rs"]={};else if(e[l(349)](void 0,s))this[l(1532)+"rs"][n]=null;else{let f=this[l(1532)+"rs"][n];if(f)for(let p=0;e[l(1021)](p,f.length);)e[l(1250)](f[p].fn,s)?f[l(1122)](p,1):++p}return this}on(n,s,l){let f=t;return(this[f(1532)+"rs"][n]||(this._listeners[n]=[]))[f(1097)]({fn:s,ctx:l||this}),this}}class og extends Sa{[t(457)+t(1350)+"age"](n){let s=t;return n[s(1259)]||n[s(1440)]?(s(454)+" "+(n[s(1259)]||"")+s(1793)+(n[s(1440)]||""))[s(677)]():JSON[s(870)+"y"](n)}constructor(n,s,l){let f=t;super(),this[f(911)]=null,ii&&wx[f(936)+f(1739)]&&(this[f(911)]=wx[f(936)+"ocket"]({url:n,protocols:s,header:l,fail:this["_createS"+f(921)+"lHandler"][f(977)](this),success:this[f(1178)+"ocketSuc"+f(660)+f(1446)][f(977)](this)})),Ln&&tt[f(936)+f(1739)]&&(this[f(911)]=tt[f(936)+"ocket"]({url:n,protocols:s,header:l,fail:this[f(1178)+f(921)+"lHandler"][f(977)](this),success:this[f(1178)+f(1713)+"cessHand"+f(1446)].bind(this)}))}[t(1178)+t(1713)+t(660)+t(1446)](){let n=t;Promise[n(1488)]()[n(1323)](()=>{let s=n,l={wWeva:function(f,p){return e[H(443)](f,p)},GIZcV:function(f,p){return f>=p},PUwDA:function(f,p){return e[H(1025)](f,p)},FEXHI:function(f,p){return e[H(1372)](f,p)},rIhFc:function(f,p){return f<<p},UVUiw:function(f,p){return f&p},LruYR:function(f,p){return f&p},bCois:function(f,p){return e[H(1682)](f,p)},nVAaL:function(f,p){return e.VyVmE(f,p)},EBcuP:function(f,p){return e[H(1700)](f,p)},fYxqS:function(f,p){return f<<p},VDYug:function(f,p){return e[H(534)](f,p)},MjrDl:function(f,p){return f&p},HczDS:function(f,p){return e[H(1079)](f,p)},SRaoE:function(f,p){return e.Dfktr(f,p)},kYhMb:function(f,p){return e[H(1779)](f,p)}};if(e[s(1149)](s(478),e.fAoBJ))this[s(1521)+s(1507)]();else{let f=_0x1db455[_0x2c3873++];if(l[s(1020)](f,127))_0x5f5222+=_0x56afa5[s(1155)+s(1366)](f);else if(l[s(531)](f,192)&&f<224)_0x275c63+=_0x32cdb6["fromChar"+s(1366)](l[s(961)](l[s(783)](31,f)<<6,l[s(783)](63,_0xf2718[_0x12ac67++])));else if(l[s(531)](f,224)&&f<240)_0x210f50+=_0x70283[s(1155)+"Code"](l.PUwDA(l[s(1656)](l[s(1844)](15,f),12),l[s(1656)](63&_0x266257[_0x5cc1ba++],6))|l[s(1055)](63,_0x5bfdb1[_0x4f3227++]));else if(l[s(860)](f,240)){let p=l[s(940)](l[s(1073)](l[s(1656)](l[s(1844)](7,f),18),l[s(331)](63&_0x1cf7b0[_0x5e14bd++],12))|l.rIhFc(l[s(1206)](63,_0xfe28dd[_0x4ca537++]),6)|l[s(485)](63,_0x58bd0a[_0x97049a++]),65536);_0x4b1370+=_0x2e4e42["fromChar"+s(1366)](l[s(591)](55296,p>>10)),_0x5ce667+=_0x41cf94.fromCharCode(l.SRaoE(56320,l.kYhMb(1023,p)))}}})}[t(1178)+t(921)+"lHandler"](n){let s=t,l={nsgyd:"error",lqSpD:function(f,p,y){return e[H(883)](f,p,y)},JcoRF:e[s(638)]};Promise[s(1488)]()[s(1323)](()=>{let f=s,p=lt(f(1298),{message:this[f(457)+f(1350)+"age"](n)});this[f(778)](l[f(1163)],p);let y=l[f(1857)](mt,l[f(1573)],{reason:this[f(457)+f(1350)+"age"](n)});this[f(778)](l[f(1573)],y)})}[t(1521)+t(1507)](){let n=t,s={lRMeH:function(l,f,p){return e[H(504)](l,f,p)},TvNLL:e[n(1483)],zVDSm:e.mLmrK};if(e.hcUcv(e[n(1526)],e[n(777)])){let l=s.lRMeH(_0x2a5ec2,n(1298),{message:_0x262ed5.message,code:_0x59a777.OPEN_ERROR,error:_0xf0081});this[n(570)+n(717)+n(1172)](l)}else this[n(911)][n(444)](l=>{let f=n;this[f(778)](s[f(716)],vl(s[f(716)],{...l,data:l[f(1259)]||""}))}),this[n(911)][n(464)](l=>{let f=n;this[f(778)](e[f(638)],e[f(1729)](mt,e[f(638)],{...l}))}),this[n(911)].onMessage(l=>{let f=n;this[f(778)](s[f(427)],s[f(1811)](El,f(623),{...l}))}),this[n(911)][n(1699)](l=>{let f=n;this[f(778)](f(1298),e.UDBMw(lt,e[f(1318)],{...l,message:l[f(1259)]||""}))})}[t(1642)](n){let s=t;if(e[s(770)](e[s(792)],e[s(792)]))return!!_0x3808f3?.[s(558)](l=>l[s(412)]===_0x4a9f62&&l[s(897)]===_0x4d9217);if(e[s(1392)](n,Uint8Array)){let l=n[s(1683)][s(956)](n[s(489)+"et"],e.KtqQc(n[s(1474)+"th"],n.byteOffset));this[s(911)]&&this[s(911)].send({data:l,fail:f=>{let p=s;this[p(778)]("error",e[p(1525)](lt,e[p(1318)],{message:this[p(457)+p(1350)+p(1702)](f)}))}})}else this[s(911)]&&this[s(911)][s(1642)]({data:n,fail:l=>{let f=s;this[f(778)](f(1298),lt("error",{message:this[f(457)+f(1350)+f(1702)](l)}))}})}[t(1854)](n,s){let l=t;this[l(911)]&&this[l(911)][l(1854)]({code:n,reason:s})}[t(1803)+t(1262)](n,s){this.on(n,s)}["removeEv"+t(442)+t(434)](n,s){this[t(838)](n,s)}get readyState(){let n=t;return this[n(911)][n(1841)+"te"]}get[t(1393)+"pe"](){let n=t;return this[n(911)][n(1393)+"pe"]}set[t(1393)+"pe"](n){}get[t(1661)](){let n=t;if(e[n(822)](n(1089),e[n(505)]))return this[n(911)][n(1661)];_0x420f9a=_0x58bd8c.charCodeAt(_0x326ab5),e[n(703)](_0x186c13,128)?_0x679ed8+=1:e[n(841)](_0x1f494f,2048)?_0x5d561d+=2:e[n(1149)](64512&_0x382268,55296)&&e[n(325)](64512,_0x1dd054[n(711)+"At"](_0x134b8a+1))===56320?(++_0x29ad6a,_0x4faa4b+=4):_0x454e3c+=3}get[t(773)](){let n=t;return this[n(911)][n(773)]}get[t(731)+"ns"](){let n=t;return this._socket[n(731)+"ns"]}get[t(751)+t(441)](){return 0}}function ag(a,n){let s=t;if(e[s(1527)](e[s(1288)],s(1827))){let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[s(416)](_0x58fe8e),f=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[s(416)](_0x1e0ac2);return l?e.vEUkk(_0x43b10b,_0x1ed3e6):f?e[s(919)](_0x1bfd5f,_0x773cb0):s(1478)+s(1478)+s(1478)+s(1478)}else{if(n)return new n(a[s(1661)],a[s(773)]);if(e.zIlin(ii,Ln))return new og(a[s(1661)],a[s(773)],a.headers);if(e[s(1691)](ar,si)&&s(1302)+"d"!=typeof WebSocket&&WebSocket)return new WebSocket(a[s(1661)],a[s(773)+"s"])}}function cg(a){let n=t,s={wFoRW:e[n(638)],dhyca:e[n(814)]};if(e.hrBLV===e[n(1649)]){let l=e[n(352)][n(1317)]("|"),f=0;for(;;){switch(l[f++]){case"0":if(a)return!0;continue;case"1":if(e[n(376)](ar,si)&&e[n(718)](e[n(414)],typeof WebSocket)&&WebSocket)return!0;continue;case"2":if(Ln&&tt["connectS"+n(1739)])return!0;continue;case"3":return!1;case"4":if(ii&&wx.connectSocket)return!0;continue}break}}else _0x2ce8d6&&_0x5b3bbf["addEvent"+n(1262)](BRpnnq.wFoRW,()=>_0x7674f7()),_0x1a15d1&&_0xdc403a[n(1803)+n(1262)](BRpnnq.dhyca,()=>_0x254753())}function Il(a,n,s){let l=t,f=-1;async function p(y){let g=H;return e.klHOh(y,f)?Promise.reject(new Error(g(1413)+g(775)+g(624)+g(463)+"process")):(f=y,y===s[g(1273)]?Promise[g(1488)]():s[y][g(977)](a)(n,p[g(977)](null,y+1)))}e[l(1222)](p,0)}function Al(a){let n=t,s=0,l=0;for(let f=0;e[n(1208)](f,a[n(1273)]);++f)l=a[n(711)+"At"](f),e.QFIIL(l,128)?s+=1:e[n(459)](l,2048)?s+=2:e[n(1543)](e[n(1677)](64512,l),55296)&&e[n(938)](e[n(1158)](64512,a[n(711)+"At"](e[n(1654)](f,1))),56320)?(++f,s+=4):s+=3;return s}function kl(a,n,s){let l=t;if(e[l(532)](s-n,1))return"";let f="";for(let p=n;p<s;){if(e.HdOLr!==l(1399))return this[l(928)].clear();{let y=a[p++];if(y<=127)f+=String[l(1155)+l(1366)](y);else if(y>=192&&e.GPxpd(y,224))f+=String[l(1155)+l(1366)](e.qLVRV(e[l(1134)](e.pDLMY(31,y),6),e[l(1460)](63,a[p++])));else if(e[l(1212)](y,224)&&e[l(703)](y,240))f+=String[l(1155)+l(1366)](e.qsWTU(e[l(1134)](e.nZgrg(15,y),12)|e.zFPXJ(e.YDVFS(63,a[p++]),6),e[l(926)](63,a[p++])));else if(e[l(1711)](y,240)){let g=e[l(473)](e[l(1092)](e[l(832)](e.aSAhk(e[l(1194)](7,y),18),e.UyjCT(63,a[p++])<<12),e[l(1376)](e[l(739)](63,a[p++]),6))|e[l(1502)](63,a[p++]),65536);f+=String["fromChar"+l(1366)](e[l(1094)](55296,g>>10)),f+=String[l(1155)+l(1366)](56320+e.MRNvc(1023,g))}}}return f}function Ia(a,n,s){let l=t,f=s,p,y;for(let g=0;e.iJgkv(g,a.length);++g)if(p=a[l(711)+"At"](g),e.OVZkt(p,128))n[s++]=p;else if(e[l(1625)](p,2048))n[s++]=e[l(1761)](e.nhNJJ(p,6),192),n[s++]=63&p|128;else if(e[l(781)](64512&p,55296)&&e[l(809)](64512,y=a.charCodeAt(g+1))===56320){let T=e[l(1637)][l(1317)]("|"),C=0;for(;;){switch(T[C++]){case"0":n[s++]=e[l(1280)](e.iIEJe(p,6),63)|128;continue;case"1":n[s++]=e[l(1041)](e[l(1342)](e[l(1631)](p,12),63),128);continue;case"2":p=e[l(875)](e[l(1802)](65536,(1023&p)<<10),e[l(341)](1023,y));continue;case"3":n[s++]=e[l(1701)](p,18)|240;continue;case"4":n[s++]=e[l(1267)](63,p)|128;continue;case"5":++g;continue}break}}else n[s++]=e.twrJP(e.djjMv(p,12),224),n[s++]=e[l(392)](e[l(1631)](p,6)&63,128),n[s++]=e[l(1761)](e[l(976)](63,p),128);return e[l(758)](s,f)}async function Tl(a){let n=t,s={QNItx:e[n(1050)],NUnJp:e.ceopx};if(n(884)==typeof a)if(e.QTRJZ(e[n(963)],e.GIvEb)){let l=new Uint8Array(e[n(1764)](Al,a));return Ia(a,l,0),l}else{if(this[n(1636)+n(979)]=!0,this[n(1499)+n(830)](),this[n(388)+n(415)](),this[n(1600)+n(819)+n(1262)](),this["_QoSMana"+n(332)]?.[n(1375)](),!this[n(975)])return void this[n(617)](s[n(333)]);if(this[n(975)][n(1841)+"te"]===this[n(1611)]||this[n(975)][n(1841)+"te"]===this[n(1354)])return void this[n(617)](s[n(343)]);this[n(1783)+n(1395)+"t"](_0x4084eb,_0x24ee1c)}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a[n(1683)],a[n(489)+"et"],a[n(1474)+"th"])}function dg(a){let n=t,s={EMTDl:function(l,f){return l||f}};try{return e.FIvbc!=typeof a&&(e.laMiX(a,ArrayBuffer)||a[n(1683)]&&e[n(1800)](a.buffer,ArrayBuffer))||e[n(1064)](n(884),typeof a)?"":(JSON[n(1740)](a),n(1798)+n(859))}catch{if(e[n(934)](e[n(387)],n(958)))return e[n(1137)](n(884),typeof a)?e.bvvas:"";{let l=this._qosDB.getItem(this[n(1244)]),f=_0xfb386c[n(1740)](s.EMTDl(l,"{}"));return _0x569774[n(373)](f)}}}let lg=(a,n)=>{let s=t;switch(a){case e[s(1030)]:case e.dkCwL:return{[s(1369)+a]:1,"x-tt-env":n};default:return{}}};class ug{constructor(n){let s=t;this[s(322)+s(1438)]=n,this[s(472)]=0}[t(1140)](){let n=t;this[n(472)]++}[t(744)+t(1221)+"nt"](){let n=t;return e.gjaLC(this.count,this["maxLossC"+n(1438)])}[t(468)+"nter"](n=0){let s=t;if(e[s(499)](s(1687),e.NmIYz))this[s(322)+s(1438)]=n,this[s(472)]=0;else return _0x5c5afb[_0x131bb4]=_0x45dac9,!0}}async function fg(a){let n=t,s={DUShc:function(l,f){return e.ottRD(l,f)},WczKe:e.auGAP,qENFe:function(l,f){return e[H(1524)](l,f)},rEcSY:e[n(1136)],VcDFg:function(l,f){return e.FAORE(l,f)},lIFJo:e[n(428)],bqsXl:e[n(1754)],fzfmB:e[n(569)]};return e[n(1543)](n(1061),e[n(1546)])?new Promise(l=>{let f=n;if(!ar)return s.qENFe(l,s[f(995)]);try{let p=document[f(618)+f(1575)](f(620));window.frontierJSONP=y=>{let g=f;document.body["removeCh"+g(508)](p),window[g(1148)+g(1742)]=void 0,s.DUShc(l,y&&y[g(335)]||s[g(995)])},p.type=s[f(1019)],p[f(1245)]=s.VcDFg(a[f(795)](/^ws/,s[f(752)]),s[f(1787)]);try{document[f(1694)][f(1356)+"ild"](p)}catch{document.body.removeChild(p)}}catch{if(s[f(404)]===s.fzfmB)window[f(1148)+f(1742)]=void 0,s[f(686)](l,s[f(995)]);else return new _0x540230(_0x5ac3d5,{message:_0x5e0ff9,code:_0x3da178,error:_0xa93031})}}):(_0x1c169f[n(772)+"t8"]?_0x480a45.writeUint8(_0xd3fb3d,_0x5333e0):_0x3ac259[_0x10ff28]=255&_0x4dd2cb,_0x5226b2+1)}function cn(a,n,s){let l=t;return!!a?.find(f=>f[l(412)]===n&&f[l(897)]===s)}function cr(a,n){let s=t;return a?.[s(558)](l=>l[s(412)]===n)?.value}let Aa=null;async function hg(){let a=t;return Aa||(Aa=Promise[a(1488)]()[a(1323)](Ut[a(977)](Ut,a(1614)))),Aa}class xg extends Sa{constructor(n,s){let l=t;e[l(1666)](e[l(1493)],e.KCrnt)?(super(),this[l(1441)]=n,this[l(661)]=s,this[l(928)]=void 0,this[l(816)+"mise"]=null):(e.CFrYo(_0x32b6c9,_0x34d9f6,24),_0x268e06(_0x1440b2,_0x14ef3a(_0x47426f)))}async[t(1083)](){await this[t(1443)]()}async[t(1443)](){let n=t;if(!this[n(928)]){if(this[n(816)+n(1076)])return this[n(816)+n(1076)];try{let s=this._dbName,l=this[n(661)];this[n(816)+"mise"]=(async()=>{let f=n,{openDB:p}=await e[f(346)](hg);this[f(928)]=await e[f(855)](p,f(1148)+"_"+s,1,{upgrade(y){let g=f;y[g(1261)+g(793)+"e"](s,{keyPath:l})}})})(),await this[n(816)+n(1076)]}catch(s){console[n(446)](s)}finally{this._initPromise=null}}}async get(n){let s=t;try{return await this[s(1443)](),this[s(928)]?.[s(1519)](this[s(1441)],n)}catch(l){e[s(927)](e.tyWwt,e[s(1759)])?(this[s(1660)]=!0,this[s(1396)]=0|_0x36884f,this[s(1228)]=e[s(1770)](0,_0x117b3e),this[s(692)]=!!_0xa180b9):console[s(446)](l)}}async[t(1487)](n,s){let l=t;return await this[l(1443)](),this[l(928)]?.[l(1131)](this[l(1441)],n)}async[t(1192)](n){let s=t;try{return await this._init(),this[s(928)]?.[s(371)](this[s(1441)],n)}catch(l){console[s(446)](l)}}async[t(650)](){let n=t;try{return await this[n(1443)](),this[n(928)]?.[n(650)](this[n(1441)])}catch(s){console[n(446)](s)}}async[t(1270)](){let n=t;return await this[n(1443)](),this[n(928)]?.[n(1252)+"ys"](this[n(1441)])}async getAll(){let n=t;return await this[n(1443)](),this[n(928)]?.[n(498)](this[n(1441)])}async[t(1375)](){let n=t;try{this[n(928)]?.[n(1854)](),this[n(928)]=void 0}catch(s){console[n(446)](s)}}get[t(806)](){let n=t;try{return!!this[n(928)]}catch(s){return console[n(446)](s),!1}}}class pg{constructor(n,s){let l=t;this._DBName=n,this._pathKey=s,this[l(928)]=localStorage}async openDB(){}get[t(1244)](){let n=t;return n(1148)+"_"+this[n(1471)]}async get(n){let s=t,l=this[s(928)][s(469)](this[s(1244)]);return JSON[s(1740)](e[s(1363)](l,"{}"))[n]}async set(n,s){let l=t,f=this[l(928)][l(469)](this[l(1244)]),p=JSON.parse(e[l(856)](f,"{}"));return p[s||n[this[l(554)]]]=n,this[l(928)].setItem(this._prefix,JSON[l(870)+"y"](p)),s||n[this._pathKey]}async[t(1192)](n){let s=t;if(e[s(502)](e[s(1113)],e[s(553)])){let l=this._qosDB[s(469)](this[s(1244)]),f=JSON[s(1740)](e[s(856)](l,"{}"));return f[n]=void 0,this[s(928)][s(1043)](this[s(1244)],JSON[s(870)+"y"](f))}else _0xa39c0a&&this["_cursorM"+s(1200)][s(351)+"rsorFile"+s(1806)](_0x207d34)}async[t(650)](){let n=t,s={BztUP:"AbortError",oUcUL:function(l){return e[H(1349)](l)}};if(e[n(1040)](e.HtBqo,e[n(1202)]))return this[n(928)][n(650)]();_0x2cd639(_0x4aac65[n(1298)]||new _0x46f5df(cqLERv[n(695)],cqLERv[n(695)])),cqLERv[n(1776)](_0x164a7d)}async[t(1270)](){let n=t,s=this[n(928)].getItem(this._prefix),l=JSON[n(1740)](e[n(1363)](s,"{}"));return Object[n(1270)](l)}async[t(498)](){let n=t;if(e[n(1115)]!==e[n(1115)])this[n(816)+"mise"]=null;else{let s=this[n(928)].getItem(this[n(1244)]),l=JSON[n(1740)](e[n(856)](s,"{}"));return Object[n(373)](l)}}closeDB(){return Promise.resolve()}get[t(806)](){return!!this[t(928)]}}class gg{constructor(n,s){let l=t;this._DBName=n,this._pathKey=s,this[l(928)]=Ln?tt:ii?wx:null}async[t(1083)](){}get[t(1244)](){return"frontier_"+this[t(1471)]}async[t(1519)](n){let s=t,l=this._qosDB[s(1203)+s(391)](this[s(1244)]);return JSON[s(1740)](e[s(1258)](l,"{}"))[n]}async[t(1487)](n,s){let l=t,f=this._qosDB[l(1203)+l(391)](this[l(1244)]),p=JSON[l(1740)](e[l(1258)](f,"{}"));return p[s||n[this._pathKey]]=n,this[l(928)][l(364)+l(391)](this[l(1244)],JSON[l(870)+"y"](p)),s||n[this[l(554)]]}async[t(1192)](n){let s=t;if(e.wZbnP(s(1373),e[s(533)]))return"frontier_"+this._DBName;{let l=this._qosDB["getStora"+s(391)](this._prefix),f=JSON[s(1740)](e.Kjuvf(l,"{}"));return f[n]=void 0,this[s(928)][s(364)+s(391)](this[s(1244)],JSON[s(870)+"y"](f))}}async[t(650)](){let n=t;return this._qosDB[n(572)+n(1236)]()}async keys(){let n=t,s=this[n(928)][n(1203)+n(1462)+"nc"](this._prefix),l=JSON[n(1740)](e[n(1333)](s,"{}"));return Object[n(1270)](l)}async[t(498)](){let n=t,s=this._qosDB["getStora"+n(1462)+"nc"](this[n(1244)]),l=JSON[n(1740)](e.NoMLa(s,"{}"));return Object[n(373)](l)}closeDB(){return Promise[t(1488)]()}get[t(806)](){let n=t;if(e[n(913)](e[n(1463)],e[n(347)]))return!!this[n(928)];this[n(975)]&&this._ws[n(1642)](_0x4b8966),this[n(617)](e[n(1310)],_0x41a9fd)}}function Cl(a,n){let s=t;if(e[s(934)]("pftNH","EErim"))return _0x339018&&(_0x4d894e=(0,_0x309214[_0x2b834e(_0x276ec9)[0]])(_0x33bd28=0)),_0x28ecac;if(e[s(1539)](Ln,Ln))return new gg(a,n);if((ar||si)&&e[s(414)]!=typeof indexedDB)return new xg(a,n);if(e[s(1579)](ar,si)&&e[s(1064)](s(1302)+"d",typeof localStorage))return new pg(a,n);throw new Error(e[s(1604)])}class mg{constructor(){let n=t;this["_interva"+n(1619)+"Id"]=null,this[n(669)+"l"]=36e5,this._qosDB=e[n(991)](Cl,e[n(1129)],e[n(521)])}async[t(669)+t(1852)](){let n=t;e[n(796)](clearInterval,this[n(669)+"lTimeoutId"]),this._intervalTimeoutId=e[n(696)](setInterval,()=>{this.flushExpired()},this[n(669)+"l"])}async[t(1083)](){let n=t;await this[n(928)].openDB()[n(1323)](()=>{let s=n;this[s(669)+s(1852)]()})}async[t(419)+t(1337)](){let n=t;(await this[n(928)]?.[n(498)]()||[])[n(1548)](({timestamp:f})=>f<Date[n(370)]())[n(540)](f=>{let p=n;this[p(928)]?.[p(1192)](f[p(1052)+"id"])})}async[t(1192)](n){return this[t(928)]?.del(n)}async[t(1487)](n,s){let l=t;if(e[l(589)](e[l(1612)],l(1560)))return this._qosDB?.[l(1487)]({message_id:n,timestamp:s});this[l(1166)+"T"]||this._isMiniWX?this._onPageNetWorkChange():this[l(330)+"er"]&&this["_initGlo"+l(819)+"Listener"]()}async[t(1519)](n){return this[t(928)]?.get(n)}async[t(1375)](){let n=t;e[n(512)](clearInterval,this[n(669)+"lTimeoutId"]),await this[n(928)]?.[n(1375)]()}get[t(806)](){let n=t,s={DYHNe:function(l,f,p,y){return e[H(855)](l,f,p,y)}};if(e[n(813)]===e[n(1576)])s.DYHNe(_0x4ca339,this,_0x1aaa95,[_0x3a3606,_0x537aff,_0x249e70]);else return this[n(928)]?.[n(806)]}}function ka(a){let n=t,s=!!this._options[n(1824)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(1210)](cn,a[n(623)].headers,e[n(578)],"2"),f=l&&e[n(1484)](cn,a.message[n(1498)],e[n(1006)],"1"),p=l&&e.XYvxA(cn,a.message[n(1498)],e.cWEpP,"1"),y=p?cr(a[n(623)][n(1498)],e[n(899)])?.[n(1317)](",")[n(1548)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:p,ackMsgIds:y}}async function Rl(){let a=t;return this["_QoSMana"+a(332)]||(this[a(1300)+a(332)]=new mg),this[a(1300)+a(332)][a(806)]||await this["_QoSMana"+a(332)].openDB(),this[a(1300)+a(332)]}async function wg(a,n){let s=t,{enableAutoAck:l}=this[s(374)],f=e[s(855)](cn,a.message[s(1498)],e[s(1145)],"1"),p=e[s(855)](cn,a.message[s(1498)],e[s(585)],"1"),y=ka[s(1398)](this,a);if(e.wNyiB(l,f)){let{SeqID:g,LogID:T,service:C,LogIDNew:L,method:B}=a[s(623)];this[s(724)]({SeqID:g,LogID:T,LogIDNew:L,service:C,method:B,headers:[{key:e[s(585)],value:"1"},{key:e[s(1609)],value:e.zIlin(L,"")},{key:e[s(1075)],value:"0"}]})}p&&!y[s(1383)]&&this[s(570)+s(1035)+s(496)](a),e[s(1120)](n)}async function _g(a,n){let s=t;this._debug(e[s(405)],a.message),n()}async function yg(a,n){let s=t;if(e.tbmJw(e[s(1085)],e[s(1095)])){if(e.MBBHL(e[s(539)],typeof _0x182b19)){let l=new _0x2b3bea(e[s(811)](_0x1378d6,_0x37dad7));return e.mjsMR(_0x4dbd6a,_0x31b47d,l,0),l}return e[s(1227)](_0x57211f,_0x2d233c)?new _0x133037(_0x36c7f2):new _0x5002cd(_0x56f7a3[s(1683)],_0x3d62e7[s(489)+"et"],_0x2d211c[s(1474)+"th"])}else{let l=e.OFfii(sn,await e[s(666)](Tl,a[s(466)]));try{if(e[s(987)](l[s(448)],Uint8Array)){let f=this._options.payloadEncoding instanceof Object?{force:!!this[s(374)][s(1403)+"ncoding"][s(1553)],encoding:this[s(374)]["payloadE"+s(1781)][s(1278)]?this[s(374)].payloadEncoding[s(1278)][s(795)](/\s/g,"")[s(1513)+s(1190)]():""}:{force:!1,encoding:this._options[s(1403)+"ncoding"]?this[s(374)][s(1403)+s(1781)][s(795)](/\s/g,"")[s(1513)+s(1190)]():""},p=l[s(1403)+s(1781)]?l[s(1403)+s(1781)][s(795)](/\s/g,"")["toLowerC"+s(1190)]():"",y=e[s(1748)](this._options[s(896)+s(1230)],Object)?{force:!!this._options[s(896)+"ype"][s(1553)],type:this._options[s(896)+s(1230)][s(321)]?this._options[s(896)+s(1230)][s(321)].replace(/\s/g,"")["toLowerC"+s(1190)]():""}:{force:!1,type:this[s(374)]["payloadT"+s(1230)]?this[s(374)]["payloadT"+s(1230)][s(795)](/\s/g,"")[s(1513)+s(1190)]():""},g=l[s(896)+s(1230)]?l[s(896)+s(1230)][s(795)](/\s/g,"")[s(1513)+"ase"]():"",T=y[s(1553)]?y[s(321)]:g||y.type,C=f[s(1553)]?f[s(1278)]:p||f[s(1278)],L=["text/plain;charset=utf-8",e[s(1766)],e.dftXR,e.FIvbc],B=[e[s(1496)],e[s(613)]];this[s(374)][s(1681)+"ansformT"+s(689)+"ad"]&&L[s(1459)](T)&&(!C||B[s(1459)](C))?l[s(1181)+s(1765)]=e.HXxfR(kl,l[s(448)],0,l[s(448)][s(1474)+"th"]):l["textPayl"+s(1765)]=""}else l[s(1181)+s(1765)]=""}catch(f){e.jYyIe(s(1836),s(1836))?(_0x3c14c9=e[s(527)](_0x213062,_0x3c0815),_0x5dd2b6|=e.ZLnbR(127&_0x4cdd2f,14),e[s(1384)](128,_0x3b636c)&&(_0x4159f4=e[s(877)](_0x4758f0,_0x2512d4),_0xd65037|=e[s(1343)](e[s(988)](127,_0x119885),21),e[s(1767)](128,_0x570001)&&(_0x300b51=_0x3d4e29(_0x3585f7),_0x14415f=e.dyikf(127,_0x17c8aa),e.aZsTX(128,_0x2a4156)&&(_0x1c605a=e[s(1039)](_0x4e408c,_0x15cf57),_0x4f6303|=e[s(1673)](127,_0x16be1a)<<7)))):(l[s(1181)+s(1765)]="",console.log(f))}a[s(623)]=l,e.lNyKh(n)}}function bg(a,n,s){let l=t,f={BofQt:function(C,L){return e[H(1746)](C,L)},sIYwQ:function(C,L){return e[H(922)](C,L)},DjYHr:function(C,L){return e[H(965)](C,L)},GiDKM:function(C,L){return C+L},YgUWU:function(C,L){return e[H(1263)](C,L)},YlOVO:function(C,L){return e.QkrcJ(C,L)},Jqpbj:function(C,L){return e[H(937)](C,L)}},p=e[l(1691)](s,8192),y=e[l(559)](p,1),g=null,T=p;return function(C){let L=l;if(f[L(1322)](C,1)||f.sIYwQ(C,y))return f[L(1720)](a,C);f[L(1780)](f[L(1653)](T,C),p)&&(g=f[L(1282)](a,p),T=0);let B=n[L(1398)](g,T,T+=C);return f.YlOVO(7,T)&&(T=f[L(1653)](f[L(990)](7,T),1)),B}}let Eg=4294967295;function vg(a,n,s){let l=t;return RangeError(e[l(411)](e[l(1311)](e.CRgof(e[l(1387)](e[l(1031)](e[l(808)],a),e.jjuHv),n||1),e[l(1706)]),s))}function Sg(a,n,s){let l=t;if(e.RAAAK(s,Eg))throw new Error(e[l(1296)]);let f=3;for(;e.uTsTm(f,0);){let p=e[l(1182)](255,s);e[l(1210)](Ca,p,a,e[l(355)](n,f)),s>>>=8,f--}return e[l(1346)](n,4)}function Ig(a,n){let s=t,l=0,f=n,p=e[s(608)](n,4);for(;f<p;){let{value:y,offset:g}=e[s(1271)](Ta,a,f);f=g,l=e.ItlGE(e[s(378)](l,8),0),l+=y}return{value:l,offset:p}}function Ag(a,n,s){let l=t,f={HotqG:function(p,y){return e[H(1674)](p,y)},sgMwk:function(p,y){return p<<y},KIdes:function(p,y){return e[H(1128)](p,y)},ZyAxH:function(p,y){return e.aZsTX(p,y)},ELhXs:function(p,y){return e[H(965)](p,y)},aoqAh:function(p,y){return e[H(1795)](p,y)},CdJHC:function(p,y){return e[H(1263)](p,y)},qRNlK:function(p,y){return e[H(326)](p,y)},veEJV:function(p,y){return e.SdnbO(p,y)}};if(e[l(1345)]("CtPtY",e[l(1028)]))_0x39b427=HPxzzd[l(1380)](_0x2d7a10,_0x546458),_0x3ac6df|=HPxzzd[l(776)](HPxzzd[l(1774)](127,_0x3f2524),21),HPxzzd[l(628)](128,_0x4eaf79)&&(_0xe4fb97=HPxzzd[l(833)](_0x478c37,_0xebf7be),_0x5de058=HPxzzd[l(909)](127,_0x18ae68),128&_0xb58847&&(_0x34eb9a=HPxzzd[l(600)](_0x375f21,_0x5ee3c5),_0x56df71|=HPxzzd[l(694)](HPxzzd.veEJV(127,_0x3de40e),7)));else{let p=e[l(453)][l(1317)]("|"),y=0;for(;;){switch(p[y++]){case"0":if(n.utf8Write)return e[l(1105)](n[l(1453)+"e"](a,s),s);continue;case"1":if(n.write)return n[l(431)](a,s)+s;continue;case"2":if(!a)return s;continue;case"3":if(e[l(367)](a[l(1273)],40))return e.AYShd(Ia,a,n,s)+s;continue;case"4":return e[l(968)](Ia,a,n,s)+s}break}}}function kg(a,n){let s=t;if(e[s(1345)]("RkXOw",s(1626))){let l=new ue(e.eXWwJ(e[s(1041)](e[s(1784)](a[e[s(1065)](n,4)]<<24,e.wIIgw(a[e[s(1105)](n,5)],16)),e[s(945)](a[e[s(1657)](n,6)],8)),a[n+7]),e[s(1804)](e[s(746)](a[e[s(821)](n,0)],24),e.ZhITr(a[e[s(513)](n,1)],16))|e[s(983)](a[e[s(1409)](n,2)],8)|a[e[s(1689)](n,3)],!0);return n+=8,{value:l,offset:e[s(1669)](n,8)}}else{let l=255&_0x2fdae4;_0x21c974(l,_0x3dff95,e[s(1846)](_0x42df02,_0x2185e0)),_0x40047a>>>=8,_0x1ea36d--}}function Tg(a,n,s){let l=t,f=a[l(1396)],p=a[l(1228)];return n[s]=e[l(1045)](p,24),n[e[l(1685)](s,1)]=e[l(1819)](e.vrLAG(p,16),255),n[e[l(564)](s,2)]=e[l(809)](e[l(529)](p,8),255),n[e.RSpuK(s,3)]=e[l(1732)](255,p),n[e.GnlEy(s,4)]=f>>>24,n[e[l(1651)](s,5)]=e[l(1128)](f>>>16,255),n[e[l(725)](s,6)]=e.yADWF(f>>>8,255),n[e[l(1079)](s,7)]=e[l(1508)](255,f),s+=8,s}function Ta(a,n){let s=t;return e.ChPyu(e[s(1168)],e[s(1168)])?_0x18bb9d["objectSt"+s(1727)]||_0x3fad91[s(1519)](_0x3b31c3):a[s(985)+"8"]?{value:a.readUInt8(n),offset:e[s(1351)](n,1)}:{value:255&a[n],offset:e[s(1775)](n,1)}}function Ca(a,n,s){let l=t;return e[l(971)](e[l(1418)],"eGWMO")?(n[l(772)+"t8"]?n[l(772)+"t8"](a,s):n[s]=e[l(1008)](255,a),e[l(1094)](s,1)):_0x28d441[l(1488)]()}let Cg=function(a){return new Uint8Array(a)},Rg=e[t(1457)](e[t(414)],typeof Buffer)?Buffer["allocUns"+t(1815)]:bg(Cg,Uint8Array.prototype[t(790)]);(()=>{let a=t,n={XGNeB:function(l,f){return l(f)},IlHAm:function(l,f){return e[H(1801)](l,f)},fwiyk:function(l,f){return e[H(445)](l,f)},vWfZj:function(l,f){return l+f},MVCst:function(l,f){return e[H(740)](l,f)},jYBbs:function(l,f){return l%f},QtgVc:function(l,f){return e[H(1347)](l,f)},xBccy:function(l,f){return l/f},iktnB:function(l,f){return l>>>f},cTEvU:function(l,f){return e.VEEmI(l,f)},QqgMl:function(l,f){return e.boTJX(l,f)},IuNGY:function(l,f){return e[H(1139)](l,f)},Osfyo:function(l,f){return l|f},TAMbj:function(l,f){return l|f},FyvDb:function(l,f){return e.kvnVl(l,f)},VMRoW:function(l,f){return l<<f},szBgm:function(l,f){return e[H(943)](l,f)},CnzqW:function(l,f){return e[H(657)](l,f)},xdZut:a(1353),snoTo:function(l,f,p,y){return e[a(1338)](l,f,p,y)}},s=4294967295;return function(l,f,p=!0){let y=a;if(s=n.iktnB(127&l[f],0),n[y(1407)](l[f++],128))return{value:p?s:n[y(1060)](0,s),offset:f};if(s=n.iktnB(n[y(1060)](s,n[y(1734)](127,l[f])<<7),0),n[y(1407)](l[f++],128))return{value:p?s:0|s,offset:f};if(s=n.IuNGY(n[y(980)](s,(127&l[f])<<14),0),l[f++]<128)return{value:p?s:n[y(354)](0,s),offset:f};if(s=n.iktnB(n.TAMbj(s,(127&l[f])<<21),0),n.cTEvU(l[f++],128))return{value:p?s:0|s,offset:f};if(s=n[y(1751)](n[y(741)](s,n[y(658)](n[y(876)](15,l[f]),28)),0),n.cTEvU(l[f++],128))return{value:p?s:n[y(1550)](0,s),offset:f};if((f+=5)>l[y(1273)]){if(n.xdZut===n.xdZut)throw f=l.length,n[y(707)](vg,f,10,l[y(1273)]);if(TLOqIT[y(753)](_0x2ff709,_0x5385a5))return _0x3dc7b8?_0x5b421c:_0x2ce4b0;if(_0x5bf74d){if(_0x2379e4>=_0x5578e0)return _0x31679a}else{if(TLOqIT[y(1293)](_0x27c8fa,-_0x1652a8))return _0x2ff7cc;if(TLOqIT[y(1845)](TLOqIT[y(1117)](_0x123171,1),_0x2b9f03))return _0x3354a9}return _0x104534[y(1616)](TLOqIT[y(1060)](TLOqIT[y(1007)](_0x170271,_0x120503),0),TLOqIT.QtgVc(TLOqIT[y(1662)](_0x8c044a,_0x55ff8a),0),_0x5cbd41)}return{value:p?s:n.MVCst(0,s),offset:f}}})();let Dg=16,Ra=32;function Pg(a){let n=t;if(e.BPRVA(e[n(383)],e.hflEt)){let s=0,l={};for(let f=0;e.KsTzN(f,a[n(1273)]);f++)l[a[f][n(1542)+"ame"]]=e[n(774)](Al,a[f][n(1542)+n(1470)]),s+=14+l[a[f][n(1542)+n(1470)]];return[s,l]}else return n(1148)+"_"+this[n(1471)]}function Dl(a,n,s){let l=t,[f,p]=e.xlPex(Pg,a),y=e.hQMOE(Rg,f),g=0;return a[l(540)](T=>{let C=l;console[C(446)](e[C(1833)],T,T[C(421)]),g=Ca(0,y,g),console[C(446)](C(579),g),g=e.VdjvC(Sg,y,g,T[C(421)]||0),console.log(C(421),g),g=Ca(p[T[C(1542)+"ame"]],y,g),console[C(446)](C(879)+"name",g),g=e[C(1338)](Ag,T[C(1542)+C(1470)],y,g),console[C(446)](e[C(1423)],g),g=e[C(1381)](Tg,ue[C(845)+"er"](T[C(959)]||n),y,g),console[C(446)](e[C(1193)],g)}),{frameType:Ra,headers:[{key:e.INPFo,value:s}],payload:y}}function Og(a){let n=t,s=0,l=[];for(;e[n(1570)](s,a[n(1474)+"th"]);){let{offset:f}=e[n(1729)](Ta,a,s);s=f;let p={cursor_name:"",cursor:0,service:0},{value:y,offset:g}=e.nHWBI(Ig,a,s);p[n(421)]=y,s=g;let{value:T,offset:C}=Ta(a,s);s=C,p[n(1542)+n(1470)]=e[n(1109)](kl,a,s,e.KkcLO(s,T)),s+=T;let{value:L,offset:B}=e.nHWBI(kg,a,s);p[n(959)]=L.toNumber(),s=B,l[n(1097)](p)}return l}function Lg(){let a=t;return{frameType:Ra,headers:[{key:e[a(916)],value:e[a(1320)]}],payload:void 0}}class Ng{constructor(n,s,l){let f=t;this._cursorNameSpace=n,this._cursorFileName=s,this[f(964)+f(1348)]=l,this[f(928)]=e[f(1525)](Cl,this[f(1229)+"ameSpace"],f(1542)+f(1470))}async[t(1083)](){let n=t;await this._qosDB[n(1083)]()}async[t(818)+"rs"](){let n=t;if(!this[n(928)][n(806)])return;let s=this[n(964)+"Strategy"],l=await this[n(928)][n(498)]();switch(console.log(e.pKNkh,l),s){case e.pArKs:return l&&l.length?Dl(l,0,this[n(477)+n(1167)]):void 0;case e[n(1226)]:return;case e.Gavrk:return l&&l.length?e.XhLEC(Dl,l,0,this[n(477)+n(1167)]):e[n(346)](Lg)}}async[t(1487)](n,s,l){let f=t;return console[f(446)](e.nYiAg,n,s,l),this[f(928)][f(1487)]({cursor_name:n,cursor:s,service:l})}async[t(1176)+"rs"](n){let s=t,l=e[s(475)](Og,n);for(let f of l)console[s(446)](s(791)+"r",l),await this._qosDB[s(1487)](f)}async get(n){let s=t;if(e[s(757)](e[s(510)],s(1012)))try{return e[s(1062)](e.FIvbc,typeof _0x363e5f)&&(e[s(882)](_0x35666f,_0x523e5a)||_0x4f2003[s(1683)]&&e.poBNj(_0x317a62[s(1683)],_0x15b5eb))||e[s(539)]!=typeof _0x3da639?"":(_0x5bd9f9.parse(_0xc9a80e),e[s(1766)])}catch{return e.YVFXq(e[s(539)],typeof _0x12cfff)?e[s(674)]:""}else return(await this[s(928)][s(1519)](n))?.[s(959)]}async[t(1375)](){let n=t;if(e[n(1414)](e[n(1014)],e[n(433)]))await this[n(928)].closeDB();else return new _0x528e45(_0x5d97e6,{message:_0x484b15})}[t(351)+t(748)+t(1806)](n){let s=t,l={FeXyh:function(f,p){return e[H(846)](f,p)}};if(s(1482)===e[s(1726)])this[s(477)+"ileName"]=n;else{let f=this[s(928)]["getStora"+s(391)](this[s(1244)]),p=_0x5835d3[s(1740)](DwmzEd.FeXyh(f,"{}"));return p[_0x2803dd]=void 0,this[s(928)]["setStora"+s(391)](this._prefix,_0x4e466f.stringify(p))}}get[t(806)](){let n=t;return this[n(928)][n(806)]}}let Mg=e[t(576)];async function Pl(a){let n=t;if(!this[n(374)][n(1824)+"S"])return null;let{aID:s,fpID:l,messageStrategy:f}=this[n(374)],p=e.eQQBy(a,Mg);try{return this[n(869)+n(1200)]?a&&this[n(869)+n(1200)][n(351)+n(748)+n(1806)](a):this[n(869)+n(1200)]=new Ng(l+"_"+s+"_"+p,p,f),this[n(869)+n(1200)][n(806)]||await this["_cursorM"+n(1200)][n(1083)](),this[n(869)+"anager"]}catch{return null}}async function Bg(a,n){let s=t,l=e[s(1338)](cn,a[s(623)].headers,e[s(1572)],"-1"),f=cn(a[s(623)][s(1498)],e[s(585)],"1"),p=e[s(904)](cr,a[s(623)][s(1498)],s(396)+s(801)),y=Number(e[s(1554)](cr,a[s(623)][s(1498)],e.JTLhL))||0,g=ka[s(1398)](this,a),T=e[s(1266)](cn,a[s(623)].headers,e[s(706)],"2"),C=e[s(439)](cr,a[s(623)].headers,e[s(1822)]),L=Number(e[s(1847)](cr,a[s(623)][s(1498)],s(1331)+s(1047)+"ue"));if(g[s(1383)])return n();let B=g[s(827)+"sage"]?await Rl[s(1398)](this):null;if(e[s(1096)](a.message[s(421)],0)&&f&&!l||e[s(1629)](a.message[s(421)],0)){if(p&&g[s(827)+"sage"]&&B)return!!!await B.get(p)&&(this[s(570)+s(324)+s(1159)](a),await B.set(p,Date[s(370)]()+y)),n();if(T){let $=await Pl[s(1398)](this);if(!$)return this[s(570)+s(324)+s(1159)](a),e[s(1269)](n);let J=await $[s(1519)](C)??-1;if(e[s(699)](J,L))this[s(570)+s(324)+s(1159)](a),$[s(1487)](C,L,a[s(623)][s(421)]);else throw new Error("recevied"+s(1749)+" cursor "+L+(s(1648)+s(1586)+s(568)+"r ")+J);return e.OLFoF(n)}return this[s(570)+s(324)+s(1159)](a),e[s(346)](n)}}async function Fg(a,n){let s=t,l=ka.call(this,a);if(!l[s(827)+s(763)])return e[s(1466)](n);let f=await Rl[s(1398)](this);if(l[s(736)+s(1361)+s(1702)]&&l.ackMsgIds[s(1273)])for(let p of l.ackMsgIds)await f[s(1192)](p);e[s(1494)](n)}async function zg(a,n){let s=t,l=e[s(1250)](a[s(623)].frameType,Dg),f=e[s(732)](a.message[s(1027)+"e"],Ra);if(e[s(407)](!l,!f))return e[s(1531)](n);let p=e[s(1214)](cr,a[s(623)].headers,e[s(916)]);if(!p)return e[s(1349)](n);let y=await Pl[s(1398)](this,p);if(!y)return e[s(1494)](n);if(l){let g=await y[s(818)+"rs"](),T={frameType:g?.[s(1027)+"e"],SeqID:ue.fromNumber(this[s(1747)]++),LogID:ue[s(845)+"er"](this[s(374)][s(898)+s(1084)]()),service:9e3,method:5,headers:g?.headers,payload:g?.[s(448)]},C=e.uAnSR(v,T);this._ws&&this._ws[s(1841)+"te"]&&this._ws[s(1642)](C)}if(f){if(e[s(1408)]!==e.GsAne)return _0x22033d.offset>=_0x2f48ed[s(418)];{let g=a[s(623)][s(448)];g&&y.setCursors(g)}}}let Ug=async function(a,n){let s=t;e.AmkUw(e.aAWZQ,e[s(1595)])?_0x250216[s(446)](_0x24806c):(this[s(1512)]=!1,clearTimeout(this[s(1205)+s(701)+"utId"]),e.oCnHI(n))},Hg=async function(a,n){let s=t;if(!this[s(975)]||e[s(390)](this._ws[s(1841)+"te"],this[s(517)]))return n();let{pingInterval:l}=this[s(374)];this[s(1340)+"tManager"]?.[s(1121)+s(614)+s(915)]();for(let p=0;e[s(1659)](p,this[s(964)+s(1309)].length);p++){let y=this[s(964)+s(1309)][p];if(e[s(757)](this[s(975)][s(1841)+"te"],this[s(517)])&&y!==null)this[s(975)]&&this._ws[s(1642)](y),this[s(964)+s(1309)][p]=null;else break}this[s(964)+s(1309)]=this[s(964)+"Queue"][s(1548)](p=>!!p),this[s(1588)+"gTimeoutId"]=e.TRFeM(setTimeout,()=>this[s(1169)](),l),this[s(570)+s(1672)+"nt"](a),this[s(330)+"er"]&&this[s(975)]&&(this._ws[s(1393)+"pe"]=this[s(729)+s(1230)]);let f=this["_endpoin"+s(1336)]?.[s(1712)+s(398)+"nt"]();this._debug(s(1367)+f+" success"),e.BkeoK(n)},Gg=async function(a,n){let s=t,l=this["_endpoin"+s(1336)]?.["getCurre"+s(398)+"nt"]();this[s(617)](s(1367)+l),e.xKKpE(n)};class qg extends Sa{constructor(n){let s=t;super(),this[s(1545)+s(625)+"line"]=!0,this[s(330)+"er"]=ar,this[s(1853)]=sg,this[s(1166)+"T"]=Ln,this[s(1725)+"X"]=ii,this[s(574)+"r"]=si,this[s(964)+s(1309)]=[],this[s(1340)+s(1336)]=null,this["_readyCl"+s(979)]=!1,this[s(729)+s(1230)]=e.CvYsG,this[s(1205)+s(1116)]=!1,this[s(1205)+s(701)+s(641)]=null,this[s(1188)+"ctTimeou"+s(678)]=null,this[s(1588)+s(1099)+"Id"]=null,this[s(1747)]=0,this[s(1512)]=!1,this[s(604)]="",this[s(1300)+s(332)]=null,this[s(869)+s(1200)]=null,this["_pingLos"+s(1325)]=null,this[s(1391)+"ls"]=e[s(843)],this[s(1611)]=3,this[s(1170)+"NG"]=0,this[s(517)]=1,this[s(1354)]=2,this[s(1455)]=y=>{let g=s;try{Il(this,y,[Ug,Hg,Gg])}catch(T){let C=lt("error",{message:T[g(623)],code:an[g(1283)+"OR"],error:T});this[g(570)+g(717)+"ent"](C)}},this[s(577)+"ge"]=async y=>{let g=s,{pingInterval:T,pingFrequency:C}=this[g(374)];if((e[g(1234)]("hi",y.data)&&e[g(1005)](g(1658),C)||e[g(822)](e[g(366)],C))&&(this[g(388)+"ngTimer"](),this[g(778)](e[g(704)],e[g(1715)]),this["_pingPon"+g(1099)+"Id"]=e.tbaSR(setTimeout,this._ping[g(977)](this),T)),!e[g(781)]("hi",y[g(466)]))try{Il(this,y,[yg,wg,Fg,zg,Bg,_g])}catch(L){if(e[g(672)](g(598),e[g(1165)]))return _0x12495a[g(1259)]||_0x274bb3[g(1440)]?(g(454)+" "+(_0xd4ae0d[g(1259)]||"")+g(1793)+(_0x4913a6[g(1440)]||""))[g(677)]():_0x2ce620.stringify(_0x5d69ef);{let B=e[g(365)](lt,e[g(1318)],{message:L[g(623)],code:an[g(1447)+g(329)],error:L});this[g(570)+g(717)+"ent"](B)}}},this[s(1544)]=y=>{let g=s,T=this[g(1340)+g(1336)]?.[g(744)+g(1071)+"es"](),C=this[g(1340)+g(1336)]?.["getCurre"+g(398)+"nt"]();if(T&&!y[g(623)]){let L=g(588)+C+(g(952)+g(1223)+g(1175)+"ed");this[g(570)+"hErrorEvent"](e[g(1768)](lt,e[g(1318)],{message:L,code:an[g(1583)+g(1066)+"R"],error:y}));return}this[g(975)]&&e[g(1763)](this[g(975)].readyState,this[g(517)])&&this[g(1106)+g(710)](),this[g(570)+g(717)+g(1172)](e[g(1641)](lt,g(1298),{message:y[g(623)],code:an[g(1151)+g(893)],error:y}))},this[s(1839)]=async y=>{let g=s;if(e.OQjXZ(e[g(492)],e.RQCUC)){this[g(1499)+g(830)](),this[g(388)+g(415)](),this[g(1362)+g(1835)+"rs"](),this._ws=null,this[g(1205)+"Lock"]=!1;let C=this["_endpoin"+g(1336)]?.[g(744)+g(1071)+"es"]();if(!C&&this[g(1718)+"orOnline"]()&&!this["_readyCl"+g(979)]){let L=this[g(1340)+g(1336)]?.[g(1712)+g(398)+"nt"](),B=this._options["reconnec"+g(782)+g(993)](y[g(1209)],y[g(754)]);this["_dispatc"+g(1810)+g(1172)](e[g(685)](mt,e[g(638)],{code:1006,reason:y[g(754)]||"connecti"+g(981)+g(885)+g(487)+"n, hostn"+g(1479)+L,willReconnect:B})),B&&this[g(1205)]();return}if(e[g(673)](1e3,y[g(1209)])&&this["_readyCl"+g(979)]){this[g(570)+g(1810)+g(1172)](mt(e[g(638)],{code:1e3,reason:e[g(1817)]})),this[g(1340)+g(1336)]?.[g(1121)+g(614)+g(915)](),this[g(910)+g(1325)]?.[g(468)+"nter"]();return}if(e[g(1183)](1e3,y[g(1209)])&&C){let L=this["_endpoin"+g(1336)]?.[g(1712)+g(398)+"nt"](),B=y[g(754)];B||(B=await e[g(1764)](fg,this[g(604)])),B=g(1536)+"ng faile"+g(423)+B+(g(1692)+"me: ")+L+(g(1379)+g(1390)+"ached"),this[g(570)+g(1810)+g(1172)](e[g(1114)](mt,g(1854),{code:y[g(1209)],reason:B}));let $=g(588)+L+(g(952)+g(1223)+"es reached");this[g(570)+g(717)+g(1172)](e.UDBMw(lt,e[g(1318)],{message:$,code:an[g(1583)+g(1066)+"R"]})),this[g(1340)+g(1336)]?.[g(1121)+g(614)+g(915)](),this[g(910)+g(1325)]?.[g(468)+g(798)]();return}if(e[g(1427)](1e3,y[g(1209)])&&!y[g(754)])if(e.xLQjt!==e[g(1416)]){let L=this["_endpoin"+g(1336)]?.getCurrentEndpoint();this[g(570)+g(1810)+g(1172)](e[g(904)](mt,e[g(638)],{code:y[g(1209)],reason:g(1536)+"ng failed, unkno"+g(487)+g(488)+g(1479)+L})),this["_endpoin"+g(1336)]?.[g(1121)+g(614)+g(915)](),this[g(910)+g(1325)]?.["resetCou"+g(798)]();return}else for(var T in _0x9b045f)_0x3180d7.o(_0x398d47,T)&&!_0x36dc8d.o(_0x3cbd82,T)&&_0x4cb32d[g(1566)+g(970)](_0x3dca60,T,{enumerable:!0,get:_0x18b303[T]});this[g(570)+"hCloseEvent"](y),this[g(1340)+g(1336)]?.[g(1121)+"pointCon"+g(915)](),this["_pingLos"+g(1325)]?.[g(468)+"nter"]()}else{let{type:C}=_0x1e79ef;this[g(778)](C,_0x1c1843)}},this[s(1634)]=null,this.onerror=null,this[s(1838)+"e"]=null,this[s(615)]=null,this[s(1153)+"econnect"]=null,this[s(1569)+"eAck"]=null,this["onStopIm"+s(905)+s(621)+"ct"]=null,this[s(1004)+s(668)]=this[s(1004)+"nLine"][s(977)](this),this[s(1004)+s(749)]=this[s(1004)+s(749)][s(977)](this),this[s(1237)+s(1613)]=this["_handleP"+s(1613)][s(977)](this),this._handlePageShow=this[s(1237)+s(1563)][s(977)](this),this[s(374)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(840)](1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(366)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(894)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:l,ws:f}=n,p=Array[s(799)](l)?l:e[s(1420)](e[s(539)],typeof l)?[l]:[];if(!p||e.uLCSt(0,p[s(1273)]))throw new Error(e[s(334)]);if(!e[s(1204)](cg,f))throw new Error(e[s(1842)]);Object[s(759)](this[s(374)],n),this["_endpoin"+s(1336)]=new Sl(p,this[s(374)].maxRetries),this["_pingLos"+s(1325)]=new ug(this[s(374)][s(1504)+s(1809)]),this[s(374)][s(766)+s(1410)]&&(this[s(1512)]=!0,this[s(1205)]()),this._options[s(769)+s(1265)+s(839)]&&(this[s(1166)+"T"]||this[s(1725)+"X"]?this["_onPageNetWorkCh"+s(1823)]():this._isBrowser&&this[s(1851)+s(819)+s(1262)]())}["_handleO"+t(668)](){let n=t;this[n(374)][n(645)+"utoRecon"+n(671)]||this[n(1636)+n(979)]||this[n(497)+"econnect"]()}[t(1004)+t(749)](){let n=t;if(e.qHCIl(e.XKIpJ,"CdkXB")){this[n(1783)+n(1395)+"t"]();let s=e[n(1114)](va,e[n(1623)],{message:e[n(1434)]});this["onStopIm"+n(905)+n(621)+"ct"]&&this["onStopIm"+n(905)+n(621)+"ct"](s)}else _0x29d29b[n(1488)]()[n(1323)](()=>{this[n(1521)+"steners"]()})}[t(1851)+"balEventListener"](){let n=t;this[n(330)+"er"]&&window[n(1803)+n(1262)](n(580),this["_handleO"+n(668)]),this[n(330)+"er"]&&window[n(1803)+"Listener"](e[n(966)],this["_handleO"+n(749)]),this._isBrowser&&window.addEventListener(e[n(1003)],this._handlePageHide),this[n(330)+"er"]&&window[n(1803)+n(1262)](e[n(1032)],this[n(1237)+n(1563)])}[t(1600)+t(819)+t(1262)](){let n=t;this._isBrowser&&window["removeEv"+n(442)+n(434)](e[n(1717)],this["_handleO"+n(668)]),this[n(330)+"er"]&&window[n(1449)+n(442)+"ner"]("offline",this[n(1004)+"ffLine"]),this[n(330)+"er"]&&window[n(1449)+n(442)+n(434)](n(939),this._handlePageHide),this[n(330)+"er"]&&window[n(1449)+n(442)+n(434)](e[n(1032)],this[n(1237)+n(1563)])}[t(1237)+t(1613)](n){let s=t;!n.persisted&&(this[s(330)+"er"]&&window[s(1449)+s(442)+s(434)](s(939),this[s(1237)+"ageHide"]),this[s(330)+"er"]&&window[s(1449)+s(442)+"ner"](e.Rmcvb,this[s(1237)+s(1563)]),this[s(1854)]()),this[s(330)+"er"]&&window[s(1449)+s(442)+s(434)](e[s(1717)],this["_handleO"+s(668)]),this._isBrowser&&window[s(1449)+s(442)+s(434)](e[s(966)],this[s(1004)+"ffLine"])}[t(1237)+t(1563)](n){let s=t;n[s(619)+"d"]&&(this[s(1718)+"orOnline"]()&&(!this._ws||e[s(1414)](this[s(975)].readyState,this[s(517)])||e[s(829)](this._ws.readyState,this.CONNECTING))&&this._handleOnLine(),this[s(330)+"er"]&&window[s(1803)+s(1262)](e[s(1717)],this[s(1004)+s(668)]),this[s(330)+"er"]&&window[s(1803)+s(1262)](e[s(966)],this[s(1004)+s(749)]))}async[t(461)+"eUrl"](n){let s=t,{fpID:l,deviceID:f,bddID:p,ttwID:y,accessKey:g,aID:T,customParams:C={},enableAutoAck:L,enableQoS:B,QoSLevel:$,env:J}=this[s(374)],Be,wt,Je;this[s(330)+"er"]||this[s(1725)+"X"]||this[s(1166)+"T"]?(Be=location&&e[s(1013)](e[s(1292)],location[s(773)])?e[s(1138)]:s(1812),wt=n[s(795)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),Je=/^wss(.*:\/\/)/[s(416)](n)?n:""+Be+wt):(Be=s(1018),wt=n[s(795)](/(^http)((?:[s]*:\/\/))/,""),Je=/(^ws)((?:[s]*:\/\/))/[s(416)](wt)?wt:""+Be+wt);let Ze=p?e.SHGIG:y?"ttwid":s(1002)+"d",oi=p||y||f;if(e.ITxmp(!oi,!Ze))throw new Error(e[s(1141)]);let Ol=e[s(1321)]==typeof C?await e[s(501)](C):C,jg=J?e[s(1214)](lg,J.xUseEnv,J[s(561)]):{},Da=Object[s(759)]({device_platform:e.JHLve,version_code:e[s(1799)],access_key:g,fpid:l,aid:T,[Ze]:oi,xsack:L?1:0,xaack:L?1:0,xsqos:B?1:0,qos_level:B?$:void 0,qos_sdk_version:2,...jg},Ol),Wg=Object[s(1270)](Da).reduce((Pa,Oa)=>Da[Oa]!==void 0?""+Pa+(Pa?"&":"?")+Oa+"="+Da[Oa]:Pa,"");return Je+"/ws/v2"+Wg}async _connect(){let n=t,s={mNnyB:function(p,y){return e.pgRXc(p,y)}};if(!(this["_connect"+n(1116)]||this[n(1636)+n(979)])){this["_connect"+n(1116)]=!0;try{let p=this[n(1340)+"tManager"]?.[n(1400)+"rentEndpointReac"+n(1602)+n(1855)](),{timeoutInterval:y}=this[n(374)];if(p){let T=this["_endpoin"+n(1336)]?.["getCurre"+n(398)+"nt"](),C=this[n(1340)+n(1336)]?.[n(480)+n(727)+n(1664)+n(688)+n(1590)](),L=this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]();if(C){let B="connect "+T+(n(1450)+", max re"+n(1390)+n(358)+n(1359)+n(562)+"ndpoint ")+C+(n(536)+"y"),$=e[n(1368)](lt,e.AxcSI,{message:B,code:an[n(1583)+"IES_ERROR"]});this._debug(B),this["_dispatc"+n(717)+n(1172)]($),this[n(604)]=await this["_generat"+n(1678)](C),this[n(617)](n(588)+C+" "+L+n(784)),this[n(1362)+"sListeners"]()}else if(e[n(709)](e.Gaoxd,e[n(357)])){let B=(n(1088)+"1")[n(1317)]("|"),$=0;for(;;){switch(B[$++]){case"0":var l=_0x3a461e[_0x1f36ac]={exports:{}};continue;case"1":return l.exports;case"2":var f=_0x2aabbc[_0x27530f];continue;case"3":_0x15a9de[_0x210ef8](l,l[n(1329)],_0x40482a);continue;case"4":if(KzsAts[n(1568)](void 0,f))return f[n(1329)];continue}break}}else{let B=n(588)+T+(n(1450)+", max re"+n(1390)+n(863));this[n(617)](B),this[n(570)+n(717)+"ent"](e[n(685)](lt,e.AxcSI,{message:B,code:an[n(1583)+n(1066)+"R"]}));return}}else if(e[n(339)](n(1461),e[n(1644)]))_0x119bd8=e[n(1277)](_0x3f5da1,_0x5ccebf),_0x2f0305=127&_0xe82d4c,e[n(1767)](128,_0x1d2804)&&(_0x4e28f9=e[n(486)](_0x404f40,_0x199dc2),_0x366fa0|=e[n(1355)](e[n(1238)](127,_0x171112),7));else{let T=this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1425)+"ateCount"](),C=this["_endpoin"+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]();this._url=await this[n(461)+n(1678)](e[n(1198)](T,"")),this[n(617)]("connect "+T+" "+C+n(784)),this[n(1362)+n(1835)+"rs"]()}if(this._isInit)this[n(1512)]=!1;else{let T=e[n(1549)](va,e[n(1623)],{message:n(1830)});this[n(1153)+"econnect"]&&this[n(1153)+"econnect"](T)}let g=this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]()||0;e.uUUVT(g,1)&&await this[n(1538)](e[n(680)](g,1)),this[n(617)](n(1536)+n(1370)+this[n(604)]+(n(611)+"ls: ")+this._protocols),this[n(975)]=e[n(406)](ag,{url:this[n(604)],protocols:[this[n(1391)+"ls"]],headers:this[n(374)][n(1133)+n(1630)+"s"][n(551)+n(1635)]},this[n(374)].ws),(this[n(330)+"er"]||this[n(574)+"r"])&&this[n(975)]&&(this[n(975)][n(1393)+"pe"]=this._binaryType),this[n(1521)+"steners"](),this[n(1205)+"ionTimeo"+n(641)]=setTimeout(this[n(1486)+"ut"][n(977)](this),y)}catch(p){throw this[n(1205)+n(1116)]=!1,p}}}["_clearTi"+t(830)](){let n=t;e[n(384)](clearTimeout,this["_connect"+n(701)+n(641)]),this["_connect"+n(701)+"utId"]=null}["_clearPi"+t(415)](){let n=t;e[n(1255)](clearTimeout,this[n(1588)+"gTimeoutId"]),e.WLiTs(clearTimeout,this[n(1188)+"ctTimeou"+n(678)]),this[n(1588)+n(1099)+"Id"]=null,this[n(1188)+n(1820)+n(678)]=null}[t(617)](...n){let s=t;s(1388)===e[s(361)]?this[s(374)].debug&&console.log[s(728)](console,[e[s(1382)],...n]):(this[s(778)](s(1298),_0x195be6),this[s(1276)]&&this.onerror(_0x2f3cbf))}[t(328)+t(1125)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:p}=this[s(374)],y=l*Math.pow(p,e[s(680)](n,1));return y>f?f:y}[t(1169)](){let n=t;if(this[n(975)]&&e[n(452)](this[n(975)][n(1841)+"te"],this.CONNECTING)){this[n(388)+n(415)](),this[n(1588)+n(1099)+"Id"]=e.InKYm(setTimeout,this._ping[n(977)](this),this._options[n(1081)+"rval"]);return}if(!this[n(975)]||e.zFsOn(this[n(975)][n(1841)+"te"],this[n(517)]))return void this[n(497)+n(1243)]();this[n(975)]&&this[n(975)][n(1642)]("hi"),this[n(1188)+"ctTimeou"+n(678)]=setTimeout(this[n(497)+n(1243)+n(522)][n(977)](this),this[n(374)][n(630)+"outInter"+n(1053)])}[t(497)+t(1243)+t(522)](){let n=t;this[n(910)+n(1325)]?.[n(1140)](),this[n(778)](e[n(1758)],e[n(1386)]),this[n(910)+"sCounter"]?.[n(744)+"chMaxCount"]()?this[n(497)+n(1243)]():this[n(1169)]()}["_navigat"+t(874)](){let n=t,s={pWdMb:function(l,f,p){return e[H(1306)](l,f,p)},LVaSQ:e.Jmuzo,hvykm:e[n(557)]};if(e.HomRV(e[n(1249)],e[n(1249)]))return this[n(1166)+"T"]||this[n(1725)+"X"]?this[n(1545)+n(625)+"line"]:(this._isBrowser||this._isWorker)&&this[n(374)][n(769)+n(1265)+n(839)]?navigator[n(1e3)]:!0;{let l=CiLhuX[n(989)](_0x25b465,CiLhuX.LVaSQ,{message:CiLhuX[n(1705)]});this[n(1153)+n(1243)]&&this[n(1153)+"econnect"](l)}}[t(497)+t(1243)](){let n=t;!this[n(1718)+n(874)]()||this[n(1636)+n(979)]||(this[n(1340)+n(1336)]?.["resetEnd"+n(614)+n(915)](),this[n(910)+"sCounter"]?.["resetCou"+n(798)](),this._ws?this[n(1106)+n(710)](1001,e[n(1056)],!0):this._connect())}_onPageNetWorkChange(){let n=t;this[n(1166)+"T"]?tt[n(1825)+"kStatusC"+n(1126)](({isConnected:s})=>{let l=n;this[l(1545)+l(625)+l(1411)]=s,s?this[l(1004)+l(668)]():this._handleOffLine()}):this[n(1725)+"X"]&&wx[n(1825)+n(820)+n(1126)](({isConnected:s})=>{let l=n;this[l(1545)+l(625)+l(1411)]=s,s?this[l(1004)+"nLine"]():this._handleOffLine()})}[t(1538)](n){let s=t,l={ZIVOx:function(f,p,y){return e[H(1577)](f,p,y)},RpmxH:e.AqBFX,xdJwu:function(f,p,y){return e[H(426)](f,p,y)},SUtvC:e[s(1817)]};if(e.NjmRT(e[s(1522)],s(1561)))return new Promise(f=>{let p=s;e[p(1304)](setTimeout,f,this["_getInte"+p(1125)+"e"](n))});if(this["_clearPi"+s(415)](),this["_clearTi"+s(830)](),this[s(1362)+s(1835)+"rs"](),this["_wsInsta"+s(853)](1e3,_0x337bac),this[s(1205)+s(1116)]=!1,_0x44b738&&this[s(1718)+s(874)]()&&!this[s(1636)+s(979)]){if(this[s(1340)+s(1336)]?.[s(744)+s(1071)+"es"]()){let p=this[s(1340)+"tManager"]?.["getCurre"+s(398)+"nt"]();this[s(570)+s(1810)+s(1172)](l[s(1530)](_0x3c4ce0,l[s(955)],{code:1006,reason:s(588)+p+(s(1450)+s(1379)+s(1390)+"ached"),wasClean:!0}))}else{let p=this._options[s(518)+s(782)+"ptor"](_0x11f126,_0x8a26f1);this[s(570)+s(1810)+"ent"](l[s(1530)](_0x16c583,l[s(955)],{code:_0x51e127,reason:_0x5b9ff5,wasClean:!0,willReconnect:p})),p&&this._connect()}return}this._navigatorOnline()||this[s(1636)+s(979)]?this["_dispatchCloseEv"+s(1172)](l[s(1589)](_0x1d74d2,l[s(955)],{code:_0x362c4,reason:l[s(1523)]})):this[s(570)+s(1810)+s(1172)](_0x2d7310(l[s(955)],{code:1006,reason:"going aw"+s(649)+s(451)+"ine"})),this[s(975)]=null,this["_endpoin"+s(1336)]?.[s(1121)+s(614)+"fig"](),this[s(910)+s(1325)]?.[s(468)+s(798)]()}["_disconn"+t(710)](n=1e3,s="",l=!1){let f=t;this[f(975)]&&this["_destroy"+f(1395)+"t"](n,s,l)}[t(1486)+"ut"](){let n=t,s={hoGsU:e[n(1318)],Xpkzz:function(l,f,p){return e.dszcQ(l,f,p)}};if(e[n(1303)](n(476),e[n(1119)]))this[n(778)](HtpPwV[n(779)],HtpPwV[n(892)](_0x3def81,HtpPwV.hoGsU,{message:this["_formatE"+n(1350)+n(1702)](_0x208d24)}));else{let l=this[n(1340)+n(1336)]?.[n(1712)+"ntEndpoint"]();this[n(617)](n(588)+l+" timeout"),this[n(1106)+n(710)](1001,n(1160)+n(605)+"onnecting",!0)}}[t(724)](n){let s=t,l=e[s(796)](Gt,n);this[s(975)]&&e[s(662)](this[s(975)].readyState,this[s(517)])&&(this[s(975)]&&this[s(975)][s(1642)](l),this._debug("send_ack",n))}[t(1362)+"sListeners"](){let n=t,s=(n(1033)+"1").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(975)][n(1449)+n(442)+n(434)](e[n(1483)],this[n(1455)]);continue;case"1":this[n(975)][n(1449)+n(442)+"ner"](n(1298),this._onError);continue;case"2":this[n(975)][n(1449)+n(442)+n(434)](e.AqBFX,this[n(1839)]);continue;case"3":if(!this[n(975)])return;continue;case"4":this[n(975)]["removeEv"+n(442)+n(434)](e[n(336)],this[n(577)+"ge"]);continue}break}}["_addWsLi"+t(1507)](){let n=t,s=e[n(1627)][n(1317)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(975)][n(1803)+n(1262)](e.mLmrK,this[n(577)+"ge"]);continue;case"1":this[n(975)]["addEvent"+n(1262)](n(1298),this[n(1544)]);continue;case"2":this[n(975)][n(1803)+n(1262)](n(1771),this[n(1455)]);continue;case"3":this[n(975)]["addEvent"+n(1262)](e[n(638)],this[n(1839)]);continue;case"4":if(!this._ws)return;continue}break}}[t(1735)+"nceClose"](n=1e3,s=""){let l=t;try{if(e[l(1454)](e.OZyRb,e[l(595)]))try{e.PoiyI(_0x4dc453,this,_0x1b12e1,[_0x3c2206,_0x5a9661,_0x40cc14])}catch(f){let p=e[l(635)](_0x832633,e[l(1318)],{message:f[l(623)],code:_0x429f99[l(1283)+"OR"],error:f});this[l(570)+l(717)+l(1172)](p)}else this._ws&&this[l(975)][l(1854)](n,s)}catch{}}[t(1783)+t(1395)+"t"](n=1e3,s="",l=!1){let f=t;if(this[f(388)+"ngTimer"](),this[f(1499)+f(830)](),this[f(1362)+f(1835)+"rs"](),this[f(1735)+f(853)](1e3,s),this[f(1205)+f(1116)]=!1,l&&this[f(1718)+f(874)]()&&!this[f(1636)+f(979)]){if(this[f(1340)+"tManager"]?.[f(744)+f(1071)+"es"]())if(e[f(797)](e[f(470)],e[f(543)]))_0x406b0c.exports=_0x4c6ef5[f(1488)]()[f(1323)](()=>(_0x26ba17(),_0x3e7144))[f(1323)](function(y){return y});else{let y=this[f(1340)+"tManager"]?.[f(1712)+f(398)+"nt"]();this[f(570)+f(1810)+f(1172)](mt(e.AqBFX,{code:1006,reason:f(588)+y+(f(1450)+f(1379)+f(1390)+f(863)),wasClean:!0}))}else{let y=this[f(374)][f(518)+f(782)+f(993)](n,s);this[f(570)+f(1810)+f(1172)](e[f(720)](mt,e.AqBFX,{code:n,reason:s,wasClean:!0,willReconnect:y})),y&&this[f(1205)]()}return}this[f(1718)+f(874)]()||this["_readyCl"+f(979)]?this["_dispatc"+f(1810)+f(1172)](e.dgdqM(mt,e[f(638)],{code:n,reason:f(593)})):this[f(570)+f(1810)+f(1172)](e[f(1721)](mt,e[f(638)],{code:1006,reason:e[f(1156)]})),this[f(975)]=null,this[f(1340)+f(1336)]?.[f(1121)+f(614)+f(915)](),this[f(910)+f(1325)]?.resetCounter()}[t(570)+t(1672)+"nt"](n){let s=t;this[s(778)](e[s(1483)],n),this.onopen&&this[s(615)](n)}["_dispatc"+t(324)+t(1159)](n){let s=t;this.emit(e.mLmrK,n),this[s(1838)+"e"]&&this[s(1838)+"e"](n)}["_dispatc"+t(1035)+"ageEvent"](n){let s=t,l={Qmurl:function(f,p){return e[H(1064)](f,p)},GytWb:e[s(539)],EzicJ:function(f,p){return e[s(1736)](f,p)},RxzMT:e[s(1766)]};if(e[s(1421)](s(1358),e.HuxLt))this[s(778)](e[s(348)],n),this[s(1569)+s(920)]&&this[s(1569)+s(920)](n);else return vdTqyH[s(450)](vdTqyH[s(1332)],typeof _0x56c498)&&(_0x3286e8 instanceof _0x2d6eef||_0x12f7ef[s(1683)]&&vdTqyH[s(506)](_0x576cf0[s(1683)],_0x579b90))||s(884)!=typeof _0x313d4e?"":(_0x49411d[s(1740)](_0x54516d),vdTqyH[s(395)])}[t(570)+"hErrorEv"+t(1172)](n){let s=t;if(e.NjmRT(e[s(866)],s(643))){let l={TzYFe:function(f,p,y){return e[s(1675)](f,p,y)},IsVER:e[s(638)]};_0x12c68e[s(1488)]()[s(1323)](()=>{let f=s,p=l[f(567)](_0xab7f8a,f(1298),{message:this["_formatE"+f(1350)+"age"](_0x51c6d)});this[f(778)](f(1298),p);let y=_0x4bd5ab("close",{reason:this[f(457)+f(1350)+f(1702)](_0x2b8542)});this[f(778)](l[f(1247)],y)})}else this[s(778)](s(1298),n),this.onerror&&this[s(1276)](n)}[t(570)+t(1810)+t(1172)](n){let s=t;if(e[s(1427)](e[s(575)],e[s(575)])){let l=_0x48ca4f[s(1317)](/\./)[s(400)](y=>_0x4cfddd(y)),f=[];return f[0]=e[s(368)](_0x3406d4,e[s(935)](l[0],l[1])),f[1]=e[s(1147)](_0x56a802,l[2]+l[3]),[e[s(1670)],e[s(1670)],e[s(1670)],"0000",s(1246),e.kdROD,f[0],f[1]][s(994)]("")}else this[s(778)](s(1854),n),this[s(1634)]&&this.onclose(n)}get[t(1393)+"pe"](){let n=t;return this._ws?this._ws[n(1393)+"pe"]:this[n(729)+n(1230)]}set[t(1393)+"pe"](n){let s=t;if(s(1704)===e[s(888)])return null;this[s(729)+s(1230)]=n,this._ws&&(this[s(975)][s(1393)+"pe"]=n)}get retryCount(){let n=t;return this[n(1340)+n(1336)]?.[n(1712)+n(398)+n(1253)+n(1438)]()||0}get[t(751)+t(441)](){let n=t,s=this["_message"+n(1309)].reduce((l,f)=>(l+=f&&f.byteLength||0,l),0);return e[n(722)](s,this[n(975)]?this[n(975)][n(751)+"Amount"]:0)}get extensions(){let n=t;if(e[n(1345)](e[n(362)],e[n(1831)]))return this[n(975)]?this[n(975)][n(731)+"ns"]:"";{this[n(1783)+n(1395)+"t"]();let s=e[n(726)](_0x52e249,e.Jmuzo,{message:e.dnskl});this[n(1023)+"mediatel"+n(621)+"ct"]&&this["onStopIm"+n(905)+n(621)+"ct"](s)}}get[t(773)](){let n=t;return this[n(975)]?this[n(975)][n(773)]:""}get[t(1841)+"te"](){let n=t;return this[n(975)]?this[n(975)][n(1841)+"te"]:this[n(374)][n(766)+n(1410)]?this.CONNECTING:this.CLOSED}get[t(1661)](){let n=t;return this[n(975)]?this[n(975)][n(1661)]:this[n(604)]}[t(1854)](n=1e3,s){let l=t,f=e[l(344)][l(1317)]("|"),p=0;for(;;){switch(f[p++]){case"0":if(!this._ws)return void this[l(617)](e[l(1050)]);continue;case"1":this._destroyWebSocket(n,s);continue;case"2":this[l(1499)+l(830)]();continue;case"3":this[l(388)+l(415)]();continue;case"4":this[l(1600)+l(819)+l(1262)]();continue;case"5":this["_QoSMana"+l(332)]?.[l(1375)]();continue;case"6":this[l(1636)+l(979)]=!0;continue;case"7":if(e[l(757)](this[l(975)][l(1841)+"te"],this[l(1611)])||e[l(602)](this[l(975)][l(1841)+"te"],this[l(1354)]))return void this._debug(e[l(360)]);continue}break}}async send(n,s){let l=t;if(e[l(1345)](l(386),e[l(1439)])){let f=e[l(525)](_0x4cfccf[l(1396)],0),p=e[l(1429)](e[l(997)](e.RsSwj(_0x1d93a5[l(1396)],28),_0x578ece[l(1228)]<<4),0),y=e[l(868)](_0x5d4dbe[l(1228)],24),g=e[l(735)](0,y)?p===0?e[l(1017)](f,16384)?e[l(550)](f,128)?1:2:f<2097152?3:4:e[l(479)](p,16384)?e[l(1069)](p,128)?5:6:p<2097152?7:8:e[l(1746)](y,128)?9:10,T=e[l(923)](_0x58e440,_0x26dda1,g),C=_0xda81d3.bytes;switch(g){case 10:C[e.bKfyL(T,9)]=e[l(325)](e[l(1412)](y,7),1);case 9:C[e.AlZhW(T,8)]=e[l(1624)](9,g)?e.KoqIo(128,y):e.gLawA(127,y);case 8:C[T+7]=e[l(499)](8,g)?e[l(524)](p,21)|128:e.wQZfo(p>>>21,127);case 7:C[T+6]=e.XdvGg(7,g)?e[l(392)](e[l(417)](p,14),128):e[l(1639)](e[l(648)](p,14),127);case 6:C[e[l(1728)](T,5)]=e[l(390)](6,g)?e[l(552)](e[l(409)](p,7),128):e[l(1186)](p>>>7,127);case 5:C[e[l(659)](T,4)]=e[l(673)](5,g)?128|p:e[l(1049)](127,p);case 4:C[T+3]=g!==4?e[l(1242)](e.RNIDJ(f,21),128):e[l(1652)](f>>>21,127);case 3:C[T+2]=g!==3?e[l(1025)](e[l(868)](f,14),128):e[l(664)](f,14)&127;case 2:C[T+1]=e[l(1722)](2,g)?e.RNIDJ(f,7)|128:e[l(511)](f>>>7,127);case 1:C[T]=e[l(490)](1,g)?128|f:e[l(969)](127,f)}}else{if(e[l(670)](null,n))throw new Error("please provide a"+l(1724)+l(765)+l(998)+l(1567)+l(1472)+l(1633)+"ffer");e.MBBHL(e.xFUDR,typeof n)&&(n=JSON[l(870)+"y"](n)),e[l(1489)](l(884),typeof n)&&!e[l(1737)](n,ArrayBuffer)&&!(n.buffer&&e.YGXKm(n[l(1683)],ArrayBuffer))&&(n=JSON[l(870)+"y"](n));let f=await e.HSPte(Tl,n),p=e[l(1255)](dg,n),{method:y=0,service:g=this[l(374)].service,logID:T=this[l(374)][l(898)+l(1084)](),headers:C=this[l(374)][l(1498)],payloadEncoding:L=this[l(374)][l(1403)+l(1781)],payloadType:B=this[l(374)][l(896)+l(1230)],logIDNew:$=this[l(374)][l(675)+l(851)][l(865)+l(627)+l(1152)+"ew"]?e[l(1124)](i,this[l(374)].logIDNewConfig[l(1574)]):""}=e.XXWsW(s,{});if(!g)throw new Error(l(1077)+l(1805)+l(1224)+l(800));let J={SeqID:ue[l(845)+"er"](this._seqId++),LogID:ue.fromNumber(T),service:g,method:y,headers:C,payloadEncoding:e[l(987)](L,Object)?L.encoding?L[l(1278)]:"":L,payloadType:e.MlxUl(B,Object)?B[l(321)]?B[l(321)]:p:B||p,payload:f,LogIDNew:$},Be=e[l(978)](Gt,J);return this[l(975)]&&e[l(1199)](this[l(975)].readyState,this[l(517)])?(this[l(975)]&&this[l(975)][l(1642)](Be),this[l(617)](e[l(1310)],J)):this._messageQueue[l(1273)]<this._options["maxMessa"+l(1080)+l(1187)]?(this[l(964)+l(1309)].push(Be),this[l(617)](e.NzRDN,J)):(this._messageQueue[l(924)](),this[l(964)+l(1309)][l(1097)](Be)),{seqID:this._seqId,logID:T,logIDNew:$}}}async reconnect(n){let s=t,{url:l}=e[s(1539)](n,{}),f=Array[s(799)](l)?l:e.ShnOq(e[s(539)],typeof l)?[l]:[];n&&Object[s(759)](this[s(374)],n),f&&f[s(1273)]?this["_endpoin"+s(1336)]=new Sl(f,this[s(374)][s(380)+"es"]):this[s(1340)+"tManager"]?.["resetEnd"+s(614)+s(915)](),this[s(910)+"sCounter"]?.[s(468)+s(798)](this[s(374)]["pingLoss"+s(1809)]),this[s(1636)+s(979)]=!1,this[s(975)]&&this[s(975)][s(1841)+"te"]!==this[s(1611)]?this[s(1106)+"ect"](1e3,e[s(1142)],!0):(this[s(1512)]=!0,this[s(1205)]())}async[t(609)](){let n=t,s={nzVMH:e[n(1715)]};if(e.XXXKb(e[n(1377)],n(456)))this[n(388)+n(415)](),this[n(778)]("ping_onc"+n(626)+"s",CBdsYh[n(1695)]),this[n(1588)+n(1099)+"Id"]=_0x2dd74f(this._ping[n(977)](this),_0x59cfdd);else if(!this[n(1205)+n(1116)]){let l="0|2|4|3|1"[n(1317)]("|"),f=0;for(;;){switch(l[f++]){case"0":this[n(1340)+"tManager"]?.[n(1121)+"pointCon"+n(915)]();continue;case"1":this._connect();continue;case"2":this._pingLossCounter?.[n(468)+n(798)]();continue;case"3":this[n(1512)]=!0;continue;case"4":this[n(1636)+n(979)]=!1;continue}break}}}[t(1803)+t(1262)](n,s){this.on(n,s)}["dispatch"+t(1159)](n){let s=t,{type:l}=n;this[s(778)](l,n)}[t(1449)+t(442)+t(434)](n,s){let l=t,f={BEQHW:function(p,y){return p(y)},NqzmP:function(p,y){return p+y},GDhVH:function(p,y){return e[H(708)](p,y)},RPiRR:function(p,y){return p||y}};if(e[l(1492)](e.yWyXN,e.yWyXN)){let p={eAMAV:function(L,B){return L>B},pftFz:function(L,B){let $=l;return aFfjQg[$(684)](L,B)},SFucI:function(L,B){let $=l;return aFfjQg[$(849)](L,B)},KSqDq:function(L,B){return aFfjQg.GDhVH(L,B)},bBARp:function(L,B){return aFfjQg.NqzmP(L,B)},jIVKS:function(L,B){return L|B}},y=aFfjQg.RPiRR(_0x173d3f,8192),g=y>>>1,T=null,C=y;return function(L){let B=l;if(L<1||p[B(760)](L,g))return p.pftFz(_0xec9762,L);p.eAMAV(p[B(1034)](C,L),y)&&(T=p.pftFz(_0x54280f,y),C=0);let $=_0x34ec67[B(1398)](T,C,C+=L);return p[B(1422)](7,C)&&(C=p[B(1364)](p[B(949)](7,C),1)),$}}else this[l(838)](n,s)}[t(1101)](){let n=t,s={WJpUH:function(l,f){return l!==f},CxfnI:e[n(1517)],axNyu:function(l,f){return l(f)},SYfpD:e[n(704)],hhvBl:e[n(1483)],JMvak:function(l,f,p){return e[n(1807)](l,f,p)}};return new Promise((l,f)=>{let p=n,y={oiqBb:s[p(1189)]};this[p(388)+p(415)](),this[p(1588)+p(1099)+"Id"]=s[p(1468)](setTimeout,this[p(1169)].bind(this),this[p(374)][p(1081)+p(603)]);let g=()=>{let C=p;s[C(1279)](C(1620),s[C(1430)])?(s[C(430)](l,"success"),this[C(838)](s[C(1716)],g),this[C(838)](C(1015)+C(667)+"t",T)):this.emit(GdToer[C(545)],_0x2eceed(GdToer[C(545)],{..._0x29f45e,data:_0x31c523[C(1259)]||""}))},T=()=>{let C=p;f(C(1127)),this.off(s[C(1716)],g),this[C(838)](C(1015)+"e_timeout",T)};this.on(p(1015)+p(626)+"s",g),this.on("ping_onc"+p(667)+"t",T),this[p(1169)]()})}}})(),Me[N(1327)+"oseEvent"]=Re[N(1327)+N(460)],Me[N(1516)+N(1164)]=Re.CustomErrorEvent,Me[N(1821)+"e"]=Re[N(1821)+"e"],Me[N(1159)]=Re[N(1159)],Me[N(382)]=Re[N(382)],Me[N(353)+"MessageE"+N(1213)]=Re[N(353)+N(1501)+N(1213)],Me[N(1501)+N(1213)]=Re[N(1501)+N(1213)],Me[N(835)+"t"]=Re[N(835)+"t"],Me.ReconnectEvent=Re[N(1233)+"tEvent"],Me["createCl"+N(460)]=Re[N(1103)+"oseEvent"],Me.createErrorEvent=Re[N(1389)+N(1164)],Me[N(596)+"ssageEvent"]=Re[N(596)+N(712)+"nt"],Me[N(967)+N(1254)]=Re["createOp"+N(1254)],Me[N(1385)+N(566)+"vent"]=Re[N(1385)+N(566)+"vent"],Me["decodedF"+N(697)]=Re["decodedF"+N(697)],Me[N(1772)+N(1470)]=Re[N(1772)+N(1470)];function oa(){let t=["u2LREuW","y2HLy2TdDxi","r1rjC2G","EKDesfe","Cgf5Bg9Hzeu","Dhj1y3rVCIa","reTQzei","AgH3A1a","y1rfDLu","r3nbBMu","vfHAEKC","y09Wzw4","BgLUzq","v0rhEee","BMv4DcGPigm","Ae9gAge","z29PBMCGyxC","vfnLAuS","D1nYCLm","vfP2t2O","yxvhqva","wvzgwhe","ANDMCuW","s1nXrhe","uMn6wwu","aaaaaaaaaaa","BNrbBMrvCgq","EwrbzgS","uK10zve","ntbODfzLqMu","y0PUwwO","q3HMBKK","vxLQq1q","wMrivuy","BwvZ","zg5ZA2W","Aw5N","C3rVCcbPBw0","tMLUBw8","B3vUDa","EfPmBhG","zxjYtM8","x2rItMfTzq","Dfb6su8","x2LUAxq","CNbQCuq","BML0AwfSAxO","BgvY","tuvtu0fhrv8","BgHHuve","CMvTB3zLrxy","ihrPBwvVDxq","uu5HD1q","AK1Tt3a","DxrMofDYAxq","uMTcC2S","x29Ut3bLBG","u2Lnvey","uvzjzKK","zefsve0","Aw5JBhvKzxm","wMnnz2G","sgH1zwe","z2vjBMzVu3K","C0v3zwW","mhW0Fdj8mxW","C25hDLy","qMTLB0S","u2fyAw8","sK12ywS","BxPysgq","yw1L","x0rctMfTzq","BMCGB3iGyw4","igzPzwXKoIa","yNL0zuXLBMC","Eufevfq","r1fxuKG","Bg1iAMe","mdaWmdaWmda","yw1LoIa","zgTmEgK","u0Hyzei","DeDiy1O","EuHrwu4","Ahjxshu","we9vtgS","x29UvgLTzw8","C2v0","CMvZB2X2zq","uevtD00","rw1hCMS","Ahr0Ca","rgT4AeC","vxDJCeu","sfnQq3a","zMzouue","rMz3Awi","t2rvu3C","AgvHzgvYCW","x2nSzwfYvgK","A2rst0q","twvZC2fNzuu","D0njBgy","Cw9Zx18","CgLUz0XVC3m","B3LUCNO","AgfZ","C3rLBMvYCW","yKTjvhu","zgzZqMm","s2TJte8","qxHZv3C","x2LZsw5PDa","Dg9mB3DLCKm","Bg9pz08","CIb0DhDjra","q3vZDg9Trxi","Dw15Cxm","uvjAruS","z2v0","wKrdsNm","x2fKzfDZtgK","AMDMr0y","u1v0DKm","swDOEhK","ENDcA2S","uu54uxi","r3jrywi","tvzTtxm","A3vAzKu","wKLwt3G","t0XgB0y","x2XPC3rLBMu","tgjrBwq","uxj2Cxu","BM5Ly3q","y29UBMvJDgK","AK9Uv0K","x3DHAxq","CvLlwgK","vg9SBgS","mxW0Fdj8m3W","y3vYC29Yx24","v0TQuK0","x29UrxjYB3i","x21PBMLoyxy","v1HpCei","C2vYDMvYvgK","zMLSDgvY","AgX3t2m","q256CvC","rxzAExG","y29TCgXLDgu","zM9Yy2u","rhfMy1y","C0TXBLy","C3vIC3rYAw4","y1nIwwm","u1Hrrxy","zuvQq1u","ruLnA2C","BgzuywS","yM9L","ywDLu2HVDW","DMLJzuLeig8","vhPVr24","zgvMAw5Luhi","zsbHihn0CMK","Bu5UEui","B25szwnLAxy","u0PhwM0","qLHTDKC","uNrTAvG","sMnVuKy","DxnLCKLW","zw1LBNq","vM5wvKy","qvLLuei","y2HHqLK","wu9nz0q","rfvuuKq","EsbJBg9Zzwq","BhrlwgC","tufyx1jfvfi","tKPXBM8","v0vyCxK","DgHHBIbSB2m","zfDVCMTLCKC","x3bPBMDqB24","EgrkD3u","Dw50","BLzTrwC","y3vYCMvUDeu","s3nTz1C","zxjFCw9Z","AMLyD2K","EMvktwe","tgnPBeS","ywjVCNq","zxrLzhK","x2rYB3bhBg8","yKj0AgO","AgvKtwf4uMu","uhfIuKC","vKPAwwq","zMzMzG","u2TPCcbWyxm","B3LWEfm","zfz6wKK","CxrTtKq","y2uGBM90igK","q0Xpu0ve","DhvYuuK","ywDLsgLKzq","AwrI","AwDOvLe","zNjVBujPDhm","thzqDhC","z0XoC2O","BfrPBwvVDxq","vhHptg0","B3bLCNr5tMe","Eej4twy","sM11EM8","yMzsA2e","s2XurhG","s0rRr0C","yLL0ELy","tfr6wfK","thfVsem","CMfTugfYyw0","CMf6rxK","tvjSufq","igfYCMf5yNu","B25JBg9Zzq","DhbizwfKzxi","x3jLywr5q2W","v2XgtM8","r2rnA1K","sKLJDvi","BNvTyMvY","DKXyrgy","C2vUza","sM1Twfm","AgjWEg0","ExfOC0y","C0jf","BeHwDMu","igXHCMDLCIa","Ahjctfy","CgL2CNG","DMjqAMK","DwDutw4","r2Les00","DhLhy0i","uhjPBwfYEuS","CKLOrMm","wfPtt1K","ywX3yxLZ","Eu9wD1e","AxnmB25N","DxjS","EejJy3K","tfbJDvC","Cg9PBNrbBMq","EMTMELq","tvLcvge","Ahr0Chm6","zxf1ywXZ","uM9Zrfi","BfLYvhK","sKTxBwm","Ae9Wzw5fDMu","EgHOq0W","y2PYCKO","CLzpweG","nxWWFdD8mq","Aw9vCeC","zvvYBa","AMHbAvy","vufswu8","zw5HyMXLvhi","vuv6CuS","yNvMzMvY","BMrWB2LUDfq","vxH1zw4","Dw5RBM93BIa","vKfLtvy","zMLSzw5HBwu","rNb3v3C","uvPbu3C","s0PMvwG","lcbOB3n0BMe","zxjFCw9Zx2e","yM9KEq","BNPwtuG","y2f0y2G","ywnRx2nVzgu","rgLfDgi","B25fCNjVCG","AhDtu08","wg5iCK4","ywDL","mti1nduWmxbnvvPYuG","EgjKwNG","Ahz5A20","t1bpBLu","qM1bwwG","uNDgDLO","r05fuKe","y29Uy2f0","Evbyrum","z2v0q3vYCMu","B2nRzxrtDwm","CMvJzwL2zwq","sM9zqMy","u1LMCeq","v1jAC3K","x25HDMLNyxq","id4G","rgPzshi","CNv1vKe","AuDptxG","yxKSihrYEsa","ihzHBgLKigq","x2LZtwLUAvC","zhLdrxe","B3jLtMfTzxm","u0X2qKO","DMrrq3G","qwnNvLK","thPkBvy","wuTWEe0","EvvyCu0","uxfNtwW","x3DZsw5ZDge","BhPRqLK","A1vwAKK","yNL0zxm","B2nRzxq","CgfYC2u","yxrLq291BNq","sLnptLa","mJG4ndy4oxH2ywfbsG","BKn5su0","u1PfsLG","swvmAum","x3nLCuLK","ELferLe","ig1LC3nHz2u","Dg9VigXHCMC","sxvor1K","vujsuha","zuH5A0i","tffuz0C","AhDNCxu","tg9Nsuq","rLjptLrjrvi","AKr4BhC","B1LNzuu","uxPiCMi","Cxnxvfu","sxDXrei","s25sqwO","EMLjzgq","B2fK","wLvyEfe","EwfxBuy","BvLvtgS","zK1Huw8","v1LUB2i","B3bLBG","zw5JB2rLrNi","uKvXrvy","s0LKzxm","v3H2D3C","B1vJvuW","y2XVC2uSihC","zw5XDwv1zq","wNf1DwG","C0LzD1e","BMnVzgLUzW","zxq9DxrMltG","x2rLC3rYB3K","A3HfCNu","zw50zwqGDhK","zNjVBuHHC2G","yNfZwgW","DMvYC2LVBG","DuDqu1u","CMLLC0nVDw4","mty4odfuELbXEwC","qLHjwNG","ignVzgu6ia","DMvY","y1H5A1m","uLnhwLq","rKLmrv9ot1q","yxbWBgLJyxq","yuPZwwG","BgfnAvG","s1DTD0G","vfHVBxy","ywrKrxzLBNq","CuXwuLy","CM92AwrLige","tMfTzq","D3foCMi","rw9vEK8","q291BNq","AenSB3nLrxy","BfjnzuG","D3m6lY8","D2fZq2XLyw4","nhWXFdn8mNW","ywzL","vvvzDhG","Bxnfwvm","zfjgsKW","t0jZA0O","y3ruAw1LB3u","rxjYB3jdB2q","zNnkrMC","yw5Nzq","zw5HyMXLuw8","B25ozxr3B3i","ywr2yw5Jzq","qLDAEMW","sMjYqMe","sLLlBfu","C3rHCNq","uNbvru0","CgfNzxnOB3C","uNDAvNy","tw9KDwXL","C0XPC3rLBMu","zgjMDgC","DMjyqw8","B25TzxnZywC","x29Uq2XVC2u","Bu1hs1m","CMvHzhLtDge","sgTjseC","zwHRCNK","vvzvAxC","zNDPEwS","Ae9XCuu","BhrTuhu","y0j3DuW","y3zrtwG","nZi4nZyXnMDyC2zwyG","x2LUAxrhBg8","BezSDxnO","x2LZtM9Kzq","y2XVC2u","DhjPzxm","D3Hhtwy","BhftCeq","su1MAKi","wMj3vgS","thDqtMG","DhbnwKG","DhLWzq","Bwf4tg9ZC0m","CgjICdi","Ae1LC3nHz2u","rKX0qMS","zK9nAvK","mNWZFdv8mxW","x2DLDeLUDgu","rvjst1i","x2LZqNjVD3m","zLL4Cvm","z2vY","uu5jDhG","tLfJvMW","BxnN","BuXTCKS","mZy2otqYrhzQqKnn","ChbL","DuXdu3q","CMvXDwLYzwq","v0r4Cfq","EwnksgS","tLvUsNa","DvDXuwS","D1v6EKi","qNr1rw0","z1rNEhG","uvryEKy","su1JDei","nhWYFdn8mhW","DxbKyxrLq3u","EMjIBwm","rNjVBNrPzxi","vefnyMO","ruv0B1y","Bujdseq","r2fVEgq","ywnOzwqSihC","B2nkEe8","y2vVChG","yNvYCuC","r3bsvfy","CMvKDwnL","C2v0u3rVCMe","zxvks2y","EKnht2e","vKHtv2m","EgXqzxG","uhffyxq","BM93","zgvSzxrL","qM94A0W","DMfSDwvZ","x29WDgLVBNm","wNL3qKO","s2P1DMy","tg9NsurozxC","EKzqweO","m3WX","Bwf4uMv0CMK","uKzqtKu","rLDt","AgzSrxq","qLHAsMS","Ec1TC2CTCw8","sLDqt3i","t2nICw8","x2nSzwfYugK","C2v0zgi","q0Tnr0e","z2vtEw5J","uhjuB0u","yMXVy2TLza","nxWW","uNH6tvq","Ef9MCM9UDgK","DevKy0C","BNrfBMrWB2K","q1P2ywi","BwfW","DwPwCha","Dev2zw50","BffqDwe","zNPMBui","DLDZyMi","DKvkyMK","turLDLq","CgvYquu","renPr20","ywXSq3vYC28","uLr4q1O","A2v5","wenXCei","uhDsteu","BMDuAw1LCG","DgvZDa","v1Hdt3G","BgLTAxq","zMX1C2HfEha","mhWZFdf8nhW","C2vYDMLJzq","zxLsAw4","zcWG","uvnLCMW","Dgv4Dc9Qyxy","DwffBwm","ELzeu20","q2zTCfe","zgv4wNi","yxHoExu","D3jPDgu","yxb1AuS","sMfcA2e","BMvY","D2fxsvy","EKvcz3a","D2LSBfjLy28","ww1bugG","zgnNsfq","CuLoBMu","qw1VDw50","zw50tgLZDgu","ze9HCMO","B25pCgvU","zuTnDxC","Bg9N","ywrKt25L","Cgf5Bg9Hza","ywXS","uw11CMW","B3jRig9MzMW","EKfOt0S","uMn4zfe","BwvZC2fNztO","D0Ljz3C","z2rWzNa","x2zVCM1HDeu","y1HhruC","t1zAA3q","B3nLrxzLBNq","x2DLBMvYyxq","tw5bEgi","Aw1LCYbPBIa","B25dBg9Zzq","tKDFrvjst1i","zgf0yq","CNbSzuO","CMvZzxrdB3u","z2v0sxrLBq","BhnYvu8","vKvUrhu","y291BNq","vNLwBuu","tLL2Bvy","AMXMEe4","DxbyuMm","x2n1CNnVCKy","u0DZuwG","AuPNA3y","CMvWBgfJzui","rNDsruC","wgvPtfG","y3vYCMvUDeK","CM92AwrLihC","twPYrgW","zM9mDMC","D24GCMvHC28","BIWGAg9ZDg4","yNL0zu9MzNm","q0D1Cwe","yw9Yy2C","rNj0A3C","BMfTzq","AhrHqMq","AMney1m","ywDLrxzLBNq","x2HHBMrSzvi","z2v0qwXS","DKjIB3G","nJbOD0rjq2C","sNrAEwW","wgr2r2C","nNWYFdn8nhW","tvnoA3K","uxDXtMC","rxPPy0O","qwPcu2u","AwXK","Aw5KzxHpzG","qLnKCfO","zLnksNq","zLzzshe","wgnxuhe","ywrxrhu","Aez2r2O","Bg9IywXty28","t1bftG","CMvJB25Uzwm","zMXVB3i","AgXSq3C","s2rVwxi","vgLTzw91Da","CfHXwLi","uK5jreO","zvD0zhK","CgH2yvO","seXlDui","Aw5L","tLrxzMK","zwLlvw0","r0LAy1y","u3LMB0C","A01Ywha","DNDuvgC","zfbACfO","ihrVihjLDhi","DMPdA1G","mZyWEu5RAeHe","rKL2yMm","zM9YrwfJAa","uu9sq2G","vurctxC","A3HLExe","yKjPs1m","B2LXqMi","B2zMC2v0","vLnIAMG","zw5KCg9PBNq","rffYww4","DfHls2O","y3vZDg9Tshq","r3n6qve","u3zvy2G","x3bHDgHlzxK","wMzduwC","Dg9Y","DxvfvLq","zMLUza","yuz4vxi","Dg9tDhjPBMC","Efrurw52","yMfJA3vWigu","AwXLx25HBwu","zMDwzgK","x0vysvnu","y29UBMvJDeu","vhPzrMu","ywWGy3vYC28","r2fZAuu","x2rPC3bHDgm","yujPt1G","y2XLyxjtDg8","EgvOrKq","x2LZv29YA2u","zuvZAMq","rMz4C0y","x29UtwvZC2e","CwjKrNK","AgvHzgvY","B25SAw5L","uMzkCNO","Du9tCeS","s0nLy0m","EMv3thG","Dun2vhu","wuXWzem","s2fuuLa","y29UBMvJDca","rfjLzLa","CMvUDevUzha","sgn6rfm","AxnFywnR","yNLL","Aw9U","q3HxuNy","y3jLyxrLtwu","C2DPza","C0HKqNm","q1LiCee","q2rksem","D2vI","tefHvfa","CNzHBa","x3vYBa","ihrYEsbYzwm","zgvJB2rLzey","EuPjs3e","C1LyBK0","y29UBMvJDa","ywnR","ihbYB3rVy28","u2HHCMvKv28","uw56Eem","Cg9PBNrdB24","B25VCgvU","vxPxC2W","x2rLyNvN","y3jLyxrLrwW","CgvYC2LZDgu","C2nYAxb0","EvjLy29UBMu","AefXDMy","BwvZC2fNzq","BhrPCgXLihq","AwDHDg9Yt24","zv9ZDwnJzxm","Dg9hzw5LCMe","wNLbEeG","yxnJCMLWDa","CgLUz1rPBwu","t2jQzwn0","Bwj0EM4","uef3q2m","r2Tlrhq","AxDKsKu","CenNvve","CxndtM4","qxfcrLG","A2XHz0S","uwTYy0O","Dxrjza","txn2r2q","Euj1B0O","DNjmquC","zgLZywjSzue","mhW0","EhniuMS","Cg9fquK","yxKSig5LDhC","y2XLyxi","A3L2ALy","C29YDa","CM92AwrLigi","rgvKAwnHDgu","se5VEvu","y05hrLy","s29Xsw8","vK1sB1C","wvbfDhC","y2vZC0HHBMq","x2TLEvbHDgG","q2PWD2m","Dg9cExrLCW","EfDSBe4","qxjbvxi","Affnt0u","zv90Aw1LB3u","BKXPBMu","x2LUDgvYDMe","ANnxtMG","BMvJDa","yuPUuxm","t1fQwfO","yNz2yxm","Bg9NsurozxC","Cg9W","DhjPBq","DeLK","AwHWwu0","twzSCgS","B3zqweu","ze5ywLq","q0P1ruC","qKvrsfC","De9YyKG","CuvorMu","wLbArui","vxbKyxrLq28","zxH0ugf5Bg8","vLn5vue","sLLPEwO","Dw5ZAwDUzwq","AM9XswW","CvjoBeS","qNP0vva","q0zYww8","CMfTzq","sgvWAwq","Ee1JDLy","txjyuNi","Aw9UvgLTzw8","B0fxD04","yuDlrvC","C0rvrMC","qwjVCNrfCNi","ANrxruW","C25Vvg8","rhPyu3O","Afb0zM0","zwn0","y2HHCKnVzgu","C3nHz2vfDMu","vgfN","quXm","qLrAyM8","vhzoteW","AevYCM9Yrxy","AvD6BvC","wgHfzw8","D0Xltfq","reX6uxy","vMDtzNy","ywXPzcb1CMW","x3nLBMrby2S","A0nXyKC","zLzwywW","ywnRDxbfBMq","yxbWBhK","x2jPBMfYEvq","AxvvvLe","zxH0zw5ZAw8","BuHOr2m","y3vYDMfSDwu","BM9Uzv9UB24","B0fYy0u","Axnby2TdBgu","rgDzsuq","DMfiDK0","BM56vMW","r296vhO","rNL2rgi","tuHtv1y","qK5Zvxu","y2HLy2Tszwe","v2vPEgLUsLm","rKHKA24","CwDKAMe","CNnVCKzPBgu","zMzmAw5L","suPbt0O","yNvMzMvYzwq","BeLgsM8","weDozui","CMvHC29U","BwfUDwfSihi","wLnsB0y","DKzPugO","EgDQDxC","yxnZAwDU","zufnqvy","v25jtwi","s25zq1C","C2fNzq","C29Tzq","yxrHlcbKyxq","yxv0B21HDgK","tLDhDMG","zgvSzxrLrge","BgLZDgvUtMu","yM9jBNy","Eg5Js3q","D3jPDgvvAw4","ChjVDg9JB2W","z3b2sw0","ywXSzwqGBxu","C2DnD2S","CwXoBfm","zw1PDa","Ag9hC1u","AeHSwfK","AKDQvNe","DeLUDgvYy2u","rKvyseK","ihrPBwvZ","vMzuAw4","qxrRrwy","C3vJy2vZCW","D1rQuLC","s2L0wuW","C3vIyxjYyxK","C2v0y3vYC28","qNvorve","AMvJDfn0B3i","AureBMO","CMvWBgfJzq","Au5ntu4","AKT5ruC","BNrLCG","AxnbCNjHEq","zxj2AwnL","zxjFBxnNAwq","zvHxD0O","DKvwqKq","wvzty1i","uMTzteS","AxnszwfKEq","A2TPyNa","r0fkAeC","suvYueu","uvP5ENi","tgTnDxu","uvH2vKy","twz3suy","q0Dowwu","reP5v0G","x2LUAxrqCM8","BgHwufq","z2v0q3vYC28","yMfSrxzLBNq","A1n0yxr1C0m","C3PoC00","D1PIBLa","tLP2v24","EuLwwNa","CM92AwrLihy","reiGzMfPBgu","AxnrB1nnzxm","uuPPuhe","A0rQrvC","BwvY","zwrPyxrLBhK","DhDYsLa","ruXOwhm","ENPpuwy","t3bLBKv2zw4","zcbLCNjVCI4","BvPSBKW","B2zM","BMDLza","qKjlEuG","CM1Hve0","rvzbC0O","vvnmzKi","ywrK","zNjVBu51Bwi","zwryEuG","C3rVCMu","C2vUDa","tNf6Bva","vw5Oyw5KBgu","q29UzMLN","twLZC2LUzYa","BMnLq2XVC2u","q1fkB0C","wfL2Eee","qvDxwxC","CvPfA3i","nNWWFdq","Aw9Ul2PZB24","yKnVAxm","q2rRwei","EMrIEfC","ywnOzwq","yNHJBwm","zw5HyMXLqxu","AgrLvuC","yM9usLG","uxLLu2e","x2n1CNnVCK0","C3rYAw5NAwy","r0Dcu1y","q2HJqLu","yxjmCwu","B3jpBMXPBMu","q1jNB2y","C3Pcz20","uxjbAhq","vezvyvu","C2vYDMLJzs0","yvDzwMe","AgfZt3DUuhi","Cg55uMO","CvHKtLe","C3rYAw5N","zcWGDw5RBM8","BxLMsvi","EgzKwva","De9ovxu","sKrbwve","DeL0Bxe","CMvZDwX0","whbRENO","uLjpuG","r2f2CMS","wuXnzg4","Cgf5Bg9Hzfq","DMfSDwu","Bg9Nsurhzw4","CKrKBvK","Dg9cExrLC0i","wvbQreu","ywnRpwzYB24","r0L5wwO","tgfSqLu","BwvKAwf0zwW","verYrfy","qwTfA04","x194x21Zz18","yw9XqwG","x3bPBMDmB3m","x3nVy2TLDa","sgvUv1e","uxfOuee","r1zXww0","zMLN","su5qrM8","AKvoCfi","ywD6wM8","EvDzrLC","zufJAW","B2nRzxrgywK","yKzPvgC","zMn3she","C2HPzNq","r3vPzeS","v1HTChe","Agnvy3y","x3fVC0rc","ww14t2y","uLDgCfO","u3jmBvG","tgHyB1y","CMvHzg9UBhK","qw1RvxC","DfzIze4","y29UBMvJDfm","zNjdBhm","sg9TuLy","CgfNzwHPzgu","BLzbyuW","uxHjsuG","CffbsfC","CfPuCge","DgfIyxnL","CLDotgW","y1PTwhy","DxbNCMfKzw4","qKzZzNu","AKLws1m","BePPBgK","BxnNsuq","igzHAwWSig0","DMvYC2LVBMm","DNfTrKC","uNbTEeG","C2XPy2u","nxWWFdj8nhW","rxrJAfO","y3vYC29Y","tNLnELm","ufv3ree","CYbHBhjLywq","uMfKEw4","x21LC3nHz2u","C09SEwO","De5iC2q","y3jLyxrLt3a","sfH4zLi","zhLPA2y","B3bLCNr5","tNzkAha","yvLbv3u","DhjHBNnHy3q","BMrLEa","x3DZ","ExDyAwi","yMLUza","AgP3AMm","B3nLza","t3nMEw8","BMCGzMfPBgu","yMLUyxj5","ugrJyui","vgLUt0m","CMvHzfvjBNq","wvDSAeK","zhPMC0i","CwrbBw8","CfDKtwi","sNfWyMO","ru1uEe4","Dg1quve","ChrVCG","AM9PBG","v2n6s2u","AeTVqwS","uxvsAKC","ysbTDxn0igi","A1HmCeO","B25mAw5L","s1fxvgS","zgv2AwnLx2K","qvbjBwK","x2HHBMrSzu8","rxvJC2q","ze1zDgm","ALLcyNm","BgjorhG","Bhz2CNm","BfLlB2q","r1foCuG","txLtBe8","AwvPuhO","sNrvEe8","CgLUz19VBMm","Dg9cExrLC0W","AKPYuKe","D3nZoI8V","CKvJu1K","D1DLDMe","sxbIufG","ANzvsvq","B25tDg9Wsw0","thLzsfu","B2rKswq","rhDkq0S","zNjHBwvuExa","Ae9Rq1O","yND2sLi","tMfAuwO","v2HJt2W","uM1JDMi","m3WWFdj8nhW","u0z1y0K","AefJA01LC3m","A293qvO","Egn3y0S","D1PAywe","s1vnqKm","DKjutxe","wNrbsKC","DgLUzYbZzxi","C2v0sxrLBq","D3L4yLC","C0XcA3K","Eefvt1e","CNnVCL92ywW","mtaYnZeZnNfyy0jPzq","wxPUCfm","sKjICvq","A1P5CfC","BwvZC2fNzv8","DMfS","CuTbELC","thj1wvi","A1v6Evy","ufjtu0e","B1fwwwm","zKDADMO","tvzdC3q","sK5HBhi","z2vvv20","mti1nda1nZb3CxnWuNm","qvfzzvi","uLnWDuS","suvtx0vsuK8","BgLUzw5V","C0fMtha","r1b4Cgq","BMT1zxG","y2HnyxHuCMK","Aw50zwDLCIa","rujJDva","vvrIAxi","v3L5Chi","BwLZzq","CgXLyxnLiha","wurwrLm","uxj2v2K","z2vrDwv1zuW","CgLUz0LUDgu","yuTYyNq","B3bLBKrc","zxjHDg9Y","C0XKt0q","wMLyveK","CMvZzxruCMK","mNW0Fdb8m3W","t2zNA0q","EvPNr3G","Aw5Lza","ww1Tvhe","v3zIrwq","qLnIuwO","ELjNyvy","uvP5Aha","ChvZAa","zgPQtxy","z1rPBwvVDxq","B1n6ruy","CgLUz09Uy2u","wuvSyvi","y3jLyxrLq2W","z2u6ia","qM54Egu","x2rPC2nVBM4","BMXdCMy","rNPswLG","AwHouNm","AfHPufm","BxzrAvi","BejMre0","zxn1Cxi","DgjHu1i","rhHuq3O","tg9JAW","DLDMwMO","wNjZvfO","DwjRELC","sxHMBvy","CMvZzxrfBMq","C3bSAwnL","BLLLyum","sfnqDgu","CNzHBfzHBhu","AgfUz2u","DgLTzw91Da","D2TxsuC","DgHbv2K","rxnIuuK","Chv0","ENLNvNO","BwLUAvbYB2C","qKvswfG","yMT6zhe","vhjTCMG","vejlvvi","v0Lpvwy","quXOvwe","ywrKq291BNq","Avjlvfe","yKzfBMi","sNPkExa","C0Xf","v0TAqvK","r1juDvi","Eff0DK0","zNjVBNrPzxi","rLPtsgW","BMv3vMvYC2K","tKfusvzfx0u","DgvmB2Djre4","B25tDgfYDfi","vhnHqM4","zNjVBunOyxi","q05dBeO","ChjVDg90Exa","vfPiuM4","rxzLBNq","DgLTzw91DcW","AxmGDw5Kzwy","AMDUtKO","BNnNEwq","CM9YrxzLBNq","thPjtgu","x2LZtwLUAvq","AwXLtMfTzq","Bvfrrfe","x3bPBMC","q09otKvdveK","zuHhBhy","zw50","lcbxzwjtB2m","r2j3sNe","zxmGCMvHy2G","C2v0q3vYC28","y29UDgv4Da","x2nYzwf0zvm","zNjVBuj5Dgu","t2PLDLy","Dgv4DfbHEwW","wg1vu2y","CLvgAxa","yKHLvNK","yxjYyxLIDwy","quX0vLe","zw5NDgG","x3jLy29UBMu","AgH2qMW","yxnL","Bw1eDxy","zgvS","BffxshO","qLrfsxG","BvvXvve","EgnlwfO","zKfpwvC","uMfcrgG","tMv4ueq","yw5Hz2vY","rvfquuO","shrcCw8","z2v0u3rVCMe","wvHtquK","x2nVBM5Ly3q","vKrzDwC","zhjAsvG","z3nAswO","y29Kzq","C3HcvNa","sNbLsei","rhfXCLm","DMvUDa","u05eBu8","BMnrvKy","AhnArvq","tLPXDNq","zKXZyKi","zujWwNK","wfn4CLe","y2HnyxHdB3u","v0XPvhm","yxGGCMv0CMK","ihzHBgLKihm","A2v0ignVBNm","vNv1CKy","s29Tv28","AgLNAa","x2n1CNnVCK4","ExbL","Aw5KzxG","uMvHzcbWyxm","uMvJB25Uzwm","DLrHAfa","zgrruMe","CMfNzvn5BMm","x2HHBMrSzva","tKPPruC","yLPryw4","CM1AA2u","CMfUzg9T","sfzfq20","zwnVBM5Ly3q","x3bYzwzPEa","C3jJ","mdaWma","sxnwrvi","z01RBKK","CLnSCxG","AurlyvK","renYCK0","z2v0qwXSs2u","BNruCMLLC0m","zw5fDMvUDa","Efz1wue","DcbSAw1PDa","wePnzui","tM9ntge","zxjYtxnN","AK9jtLO","y3jLyxrLt2i","tgLZDgvUzxi","vw93te4","Bwv0Ag9K","DhDVCMTdAge","ugryqwC","z3ztDge","CLzHBhvLCW","DuPdrxe","A2v5CW","DhjLteW","y29UDgLUDwu","BgvUz3rO","Dg9oDw1Izxi","Ce91vNu","B25LCNjVCG","uMPdDuS","zw5JB2rPBMC","v0PWvuG","yvPZvfG","uMXHChK","wwDvv1u","t1bftL9fuLi","uezPz04","DgLLCKPtt04","tK1rA2m","mNWZFdb8mxW","u2Tss04","u2LUsge","r0DuEwm","qwDqC3K","ELLmEum","swXiqw0","q3bksKS","y29SBM8","turlwLu","CYbPBNn0yw4","zxjYB3i","tfnIBee","x1fVu01HBMe","BMvLzf9Hy2S","Dw5KzwzPBMu","zujjwMW","u01NwMe","B2jQzwn0u3q","zwrqsgC","zMPwseW","zxL0BwS","uxvLDwu","sxPoExu","q0rzsMy","BwLUzW","EKzZt24","uLHuA2y","v2LUzg93","C25ty3G","C3bSAxq","qxHJu0K","CvvMueO","wKPKuxy","yxjeBgi","qM9Muxq","DgHLBG","pxv0zI04","C0nVDw50zxi","x19LC01Vzhu","q3vZDg9Tq2W","EfHUuM0","zxHWB3j0CW","DxbwuMe","Ec1TC2CTy3u","r3L0v2i","EKLSAw4","t0zMAwK","icSG","De1HBMfNzxi","AxjLza","te9YzMu","C0X1A3C","x2vUzhbVAw4","EwrnswC","q2D0B1y","yvnbAgS","zvrVBwe","r0XjrNa","rwHVvgO","CuTuugq","u3rYyxrLz3K","wvv1ANy","CNjVCK1LC3m","svvczfi","ru1RzMy","CgjAsuq","q0Xpu0LorW","tgrwDKW","yxbWzw5Kq2G","Cw9Z","qLLpq1u","AwXSihvZzsa","zNvUy3rPB24","yw51Ce1LC3m","x3jLBw92zvC","sgnMAeq","yKjbuNa","y3r4","q29Kzq","B3bLBIa","rwvszKe","Ec11C2uT","BMCGDxjSoIa","r1LZuMi","DgXsyxK","BeLvugK","AxnAzxjV","y2XVC2veqG","qxnLywu","ELrtzxG","vfDjuhu","lcbTyxGGCMu","sg90CuC","BwPZtvi","BNnps1a","AxnrB1nby2S","C3P2swq","y3jLyxrLuMu","uKf4DMq","y0XbrNq","AxDSAha","y3jLyxrLrxi","DhjPzxmGCMu","x3bYB3rVy28","Cg9ctMO","yMLUyxj5vhK","wKTewfO","v2vIu29JA2u","Bg93","y29UC3rYDwm","y2fSBa"];return oa=function(){return t},oa()}for(ea in Re)[N(1327)+N(460),"CustomEr"+N(1164),N(1821)+"e","Event",N(382),"Frontier"+N(1501)+N(1213),N(1501)+N(1213),"OpenEvent",N(1233)+N(402),N(1103)+"oseEvent","createEr"+N(1164),"createMessageEvent",N(967)+N(1254),N(1385)+N(566)+N(1213),N(606)+N(697),N(1772)+N(1470)][N(509)](ea)===-1&&(Me[ea]=Re[ea]);var ea;Object[N(1566)+N(970)](Me,N(1326)+"le",{value:!0})});import{existsSync as C1,openSync as R1}from"node:fs";import{mkdir as D1}from"node:fs/promises";import{dirname as P1}from"node:path";import{fileURLToPath as O1}from"node:url";function N1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function nl(t=Z()){return C1(t.libEntry)?t.libEntry:O1(new URL("../index.ts",import.meta.url))}async function gp(t={}){let e=t.paths??Z(),r=t.entryOverride??nl(e),i=N1(e,process.env.COZE_BRIDGE_LOG_MODE);await D1(P1(i),{recursive:!0});let o=R1(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=st(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[ls]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return L1.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var L1,ls,ua=nt(()=>{"use strict";Zt();re();Te();L1=G("spawn-daemon"),ls="COZE_BRIDGE_DAEMON"});import{spawn as PI}from"node:child_process";import{mkdir as OI,unlink as LI,writeFile as NI}from"node:fs/promises";import{dirname as MI,join as BI}from"node:path";function ti(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function FI(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${ti(r)}</key>
21
+ <string>${ti(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function _2(t,e){return new Promise((r,i)=>{let o=f2(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 Xr,fs,pa,sl,Bp=et(()=>{"use strict";te();Xr=j("supervisor.launchd"),fs="ai.coze.bridge",pa=_2,sl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function zI(t,e){return new Promise((r,i)=>{let o=PI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ei,hs,ma,ul,zp=nt(()=>{"use strict";re();ei=G("supervisor.launchd"),hs="ai.coze.bridge",ma=zI,ul={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
29
29
  <dict>
30
30
  <key>Label</key>
31
- <string>${fs}</string>
31
+ <string>${hs}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Zr(t.nodeBin)}</string>
35
- <string>${Zr(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>${Zr(t.logFile)}</string>
45
+ <string>${ti(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Zr(t.logFile)}</string>${w2(t.env)}
47
+ <string>${ti(t.logFile)}</string>${FI(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return m2(t.homeDir,"Library","LaunchAgents",`${fs}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await x2(g2(i),{recursive:!0}),await p2(i,this.renderConfig(t),"utf8"),Xr.info("plist written",{plistPath:i,activate:r}),!r)return;await pa("launchctl",["unload","-w",i]).catch(c=>Xr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await pa("launchctl",["load","-w",i]),Xr.info("launchd job loaded",{label:fs});let o=process.getuid?.()??0;await pa("launchctl",["kickstart","-k",`gui/${o}/${fs}`]),Xr.info("launchd job kickstarted",{label:fs,uid:o})},async uninstall(t){let e=this.configPath(t);await pa("launchctl",["unload","-w",e]).catch(r=>Xr.warn("launchctl unload failed (ignored)",{err:String(r)})),await h2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Xr.info("launchd job removed",{plistPath:e})}}});import{spawn as y2}from"node:child_process";import{mkdir as b2,unlink as E2,writeFile as v2}from"node:fs/promises";import{dirname as S2,join as Fp}from"node:path";function ma(t,e){return t.isRoot?e:["--user",...e]}function A2(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function wa(t,e){return new Promise((r,i)=>{let o=y2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var ga,Qr,I2,ol,zp=et(()=>{"use strict";te();ga=j("supervisor.systemd"),Qr="coze-bridge.service",I2="/etc/systemd/system";ol={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return BI(t.homeDir,"Library","LaunchAgents",`${hs}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await OI(MI(i),{recursive:!0}),await NI(i,this.renderConfig(t),"utf8"),ei.info("plist written",{plistPath:i,activate:r}),!r)return;await ma("launchctl",["unload","-w",i]).catch(c=>ei.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ma("launchctl",["load","-w",i]),ei.info("launchd job loaded",{label:hs});let o=process.getuid?.()??0;await ma("launchctl",["kickstart","-k",`gui/${o}/${hs}`]),ei.info("launchd job kickstarted",{label:hs,uid:o})},async uninstall(t){let e=this.configPath(t);await ma("launchctl",["unload","-w",e]).catch(r=>ei.warn("launchctl unload failed (ignored)",{err:String(r)})),await LI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),ei.info("launchd job removed",{plistPath:e})}}});import{spawn as UI}from"node:child_process";import{mkdir as HI,unlink as GI,writeFile as qI}from"node:fs/promises";import{dirname as jI,join as Up}from"node:path";function _a(t,e){return t.isRoot?e:["--user",...e]}function KI(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function ya(t,e){return new Promise((r,i)=>{let o=UI(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var wa,ni,WI,fl,Hp=nt(()=>{"use strict";re();wa=G("supervisor.systemd"),ni="coze-bridge.service",WI="/etc/systemd/system";fl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
52
52
  Description=Coze Bridge daemon
53
53
  After=network.target
54
54
 
@@ -59,10 +59,10 @@ Restart=always
59
59
  RestartSec=3
60
60
  StandardOutput=append:${t.logFile}
61
61
  StandardError=append:${t.logFile}
62
- ${A2(t.env)}
62
+ ${KI(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Fp(I2,Qr):Fp(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 b2(S2(i),{recursive:!0}),await v2(i,this.renderConfig(t),"utf8"),ga.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await wa("systemctl",ma(t,["daemon-reload"])),await wa("systemctl",ma(t,r?["enable","--now",Qr]:["enable",Qr])),ga.info("systemd unit enabled",{unitName:Qr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await wa("systemctl",ma(t,["disable","--now",Qr])).catch(r=>ga.warn("systemctl disable failed (ignored)",{err:String(r)})),await E2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await wa("systemctl",ma(t,["daemon-reload"])).catch(()=>{}),ga.info("systemd unit removed",{unitPath:e})}}});import{spawn as k2}from"node:child_process";import{join as T2}from"node:path";function Up(t,e){return new Promise((r,i)=>{let o=k2(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var al,_a,cl,Hp=et(()=>{"use strict";te();al=j("supervisor.taskscheduler"),_a="CozeBridge",cl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Up(WI,ni):Up(t.homeDir,".config","systemd","user",ni)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await HI(jI(i),{recursive:!0}),await qI(i,this.renderConfig(t),"utf8"),wa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await ya("systemctl",_a(t,["daemon-reload"])),await ya("systemctl",_a(t,r?["enable","--now",ni]:["enable",ni])),wa.info("systemd unit enabled",{unitName:ni,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await ya("systemctl",_a(t,["disable","--now",ni])).catch(r=>wa.warn("systemctl disable failed (ignored)",{err:String(r)})),await GI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ya("systemctl",_a(t,["daemon-reload"])).catch(()=>{}),wa.info("systemd unit removed",{unitPath:e})}}});import{spawn as $I}from"node:child_process";import{join as VI}from"node:path";function Gp(t,e){return new Promise((r,i)=>{let o=$I(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var hl,ba,xl,qp=nt(()=>{"use strict";re();hl=G("supervisor.taskscheduler"),ba="CozeBridge",xl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
66
66
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
67
67
  <RegistrationInfo>
68
68
  <Description>Coze Bridge daemon</Description>
@@ -86,61 +86,59 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return T2(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 Up("schtasks",["/Create","/SC","ONLOGON","/TN",_a,"/TR",r,"/RU",t.userName,"/F"]),al.info("task scheduler entry created",{task:_a,logFile:t.logFile})},async uninstall(t){await Up("schtasks",["/Delete","/TN",_a,"/F"]).catch(e=>al.warn("schtasks /Delete failed (ignored)",{err:String(e)})),al.info("task scheduler entry removed",{task:_a})}}});var Gp={};Oa(Gp,{buildContext:()=>L2,getSupervisor:()=>R2,launchdSupervisor:()=>sl,systemdSupervisor:()=>ol,taskSchedulerSupervisor:()=>cl});import{homedir as C2,userInfo as P2}from"node:os";function R2(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 O2(){let t={};for(let e of D2){let r=process.env[e];r&&(t[e]=r)}return t}function L2(){let t=J();return{nodeBin:process.execPath,entry:Jd(t),logFile:t.logFile,homeDir:C2(),userName:P2().username,isRoot:process.getuid?.()===0,env:O2()}}var D2,qp=et(()=>{"use strict";Ce();da();Bp();zp();Hp();D2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();ln();var Ul=j("acp-installer-warmup"),mm=["claude-code","codex"];async function Hl(t={}){let e=t.ensure??lr,i=(await Promise.allSettled(mm.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))})}qt();te();import{readdir as Om}from"node:fs/promises";import{mkdir as Wl,readFile as Rm,writeFile as Kl}from"node:fs/promises";import{join as Ua}from"node:path";var Dm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function xr(t,e,r){await Wl(t,{recursive:!0});let i=Dm[e],o=Ua(t,i);return await Kl(o,r??"","utf8"),o}async function Ha(t,e,r){let i=Ua(t,".claude");await Wl(i,{recursive:!0});let o=Ua(i,"settings.local.json"),c={};try{let u=await Rm(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=j("agent-detail-sync"),Lm=6e4,Nm=5*6e4,vs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Om(r)}catch(o){Xe.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Xe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await ve(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Xe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Xe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Xe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Xe.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Xe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await ve(e,this.opts.paths);if(!i){Xe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(x){Xe.warn("detail RPC failed, using local data",{agentId:e,err:String(x)});let h=this.retryQueue.get(e),m=h?Math.min(h.currentDelay*2,Nm):Lm;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});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 ze(i,this.opts.paths),Xe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Xe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await xr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var xd=Ht(Iu(),1);import{createHash as vy}from"node:crypto";import{lstat as sd,mkdir as od,readFile as wo,readdir as m0,rm as ad,stat as ud,writeFile as cd}from"node:fs/promises";import{homedir as Sy}from"node:os";import{basename as h0,dirname as Iy,join as fe,normalize as Ay,relative as fd,resolve as dd,sep as w0}from"node:path";import{Readable as _0}from"node:stream";import{pipeline as y0}from"node:stream/promises";import rw from"events";import rt from"fs";import{EventEmitter as Uc}from"node:events";import af from"node:stream";import{StringDecoder as iw}from"node:string_decoder";import lf from"node:path";import Ir from"node:fs";import{dirname as mw,parse as ww}from"path";import{EventEmitter as Aw}from"events";import bc from"assert";import{Buffer as qn}from"buffer";import*as Pu from"zlib";import kw from"zlib";import{posix as wr}from"node:path";import{basename as e_}from"node:path";import to from"fs";import Rt from"fs";import Bu from"path";import{win32 as f_}from"node:path";import ju from"path";import If from"node:fs";import C_ from"node:assert";import{randomBytes as Af}from"node:crypto";import ie from"node:fs";import Me from"node:path";import kf from"fs";import uo from"node:fs";import ki from"node:path";import ct from"node:fs";import M_ from"node:fs/promises";import io from"node:path";import{join as Ff}from"node:path";import at from"node:fs";import Hf from"node:path";var tw=Object.defineProperty,nw=(t,e)=>{for(var r in e)tw(t,r,{get:e[r],enumerable:!0})},Au=typeof process=="object"&&process?process:{stdout:null,stderr:null},sw=t=>!!t&&typeof t=="object"&&(t instanceof Kn||t instanceof af||ow(t)||aw(t)),ow=t=>!!t&&typeof t=="object"&&t instanceof Uc&&typeof t.pipe=="function"&&t.pipe!==af.Writable.prototype.pipe,aw=t=>!!t&&typeof t=="object"&&t instanceof Uc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),fn=Symbol("emittedEnd"),Ts=Symbol("emittingEnd"),li=Symbol("emittedError"),Cs=Symbol("closed"),ku=Symbol("read"),Ps=Symbol("flush"),Tu=Symbol("flushChunk"),yt=Symbol("encoding"),mr=Symbol("decoder"),Ue=Symbol("flowing"),ui=Symbol("paused"),Er=Symbol("resume"),He=Symbol("buffer"),Ze=Symbol("pipes"),Ge=Symbol("bufferLength"),$a=Symbol("bufferPush"),Rs=Symbol("bufferShift"),Je=Symbol("objectMode"),Ae=Symbol("destroyed"),Va=Symbol("error"),Ya=Symbol("emitData"),Cu=Symbol("emitEnd"),Ja=Symbol("emitEnd2"),Tt=Symbol("async"),Xa=Symbol("abort"),Ds=Symbol("aborted"),fi=Symbol("signal"),Ln=Symbol("dataListeners"),ot=Symbol("discarded"),xi=t=>Promise.resolve().then(t),cw=t=>t(),dw=t=>t==="end"||t==="finish"||t==="prefinish",lw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,uw=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[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()}},fw=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)}},xw=t=>!!t.objectMode,hw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Kn=class extends Uc{[Ue]=!1;[ui]=!1;[Ze]=[];[He]=[];[Je];[yt];[Tt];[mr];[jt]=!1;[fn]=!1;[Ts]=!1;[Cs]=!1;[li]=null;[Ge]=0;[Ae]=!1;[fi];[Ds]=!1;[Ln]=0;[ot]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");xw(e)?(this[Je]=!0,this[yt]=null):hw(e)?(this[yt]=e.encoding,this[Je]=!1):(this[Je]=!1,this[yt]=null),this[Tt]=!!e.async,this[mr]=this[yt]?new iw(this[yt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ze]});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[yt]}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[Tt]}set async(t){this[Tt]=this[Tt]||!!t}[Xa](){this[Ds]=!0,this.emit("abort",this[fi]?.reason),this.destroy(this[fi]?.reason)}get aborted(){return this[Ds]}set aborted(t){}write(t,e,r){if(this[Ds])return!1;if(this[jt])throw new Error("write after end");if(this[Ae])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[Tt]?xi:cw;if(!this[Je]&&!Buffer.isBuffer(t)){if(uw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(lw(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[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[$a](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):t.length?(typeof t=="string"&&!(e===this[yt]&&!this[mr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[yt]&&(t=this[mr].write(t)),this[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[$a](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue])}read(t){if(this[Ae])return null;if(this[ot]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[Wt](),null;this[Je]&&(t=null),this[He].length>1&&!this[Je]&&(this[He]=[this[yt]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[ku](t||null,this[He][0]);return this[Wt](),e}[ku](t,e){if(this[Je])this[Rs]();else{let r=e;t===r.length||t===null?this[Rs]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].length&&!this[jt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[jt]=!0,this.writable=!1,(this[Ue]||!this[ui])&&this[Wt](),this}[Er](){this[Ae]||(!this[Ln]&&!this[Ze].length&&(this[ot]=!0),this[ui]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[Ps]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[Er]()}pause(){this[Ue]=!1,this[ui]=!0,this[ot]=!1}get destroyed(){return this[Ae]}get flowing(){return this[Ue]}get paused(){return this[ui]}[$a](t){this[Je]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[Rs](){return this[Je]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[Ps](t=!1){do;while(this[Tu](this[Rs]())&&this[He].length);!t&&!this[He].length&&!this[jt]&&this.emit("drain")}[Tu](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[Ae])return t;this[ot]=!1;let r=this[fn];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[Ze].push(e.proxyErrors?new fw(this,t,e):new cf(this,t,e)),this[Tt]?xi(()=>this[Er]()):this[Er]()),t}unpipe(t){let e=this[Ze].find(r=>r.dest===t);e&&(this[Ze].length===1?(this[Ue]&&this[Ln]===0&&(this[Ue]=!1),this[Ze]=[]):this[Ze].splice(this[Ze].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[ot]=!1,this[Ln]++,!this[Ze].length&&!this[Ue]&&this[Er]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(dw(t)&&this[fn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[li]){let i=e;this[Tt]?xi(()=>i.call(this,this[li])):i.call(this,this[li])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[ot]&&!this[Ze].length&&(this[Ue]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[ot]&&!this[Ze].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[fn]}[Wt](){!this[Ts]&&!this[fn]&&!this[Ae]&&this[He].length===0&&this[jt]&&(this[Ts]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Cs]&&this.emit("close"),this[Ts]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ae&&this[Ae])return!1;if(t==="data")return!this[Je]&&!r?!1:this[Tt]?(xi(()=>this[Ya](r)),!0):this[Ya](r);if(t==="end")return this[Cu]();if(t==="close"){if(this[Cs]=!0,!this[fn]&&!this[Ae])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[li]=r,super.emit(Va,r);let o=!this[fi]||this.listeners("error").length?super.emit("error",r):!1;return this[Wt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Wt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[Wt](),i}[Ya](t){for(let r of this[Ze])r.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Wt](),e}[Cu](){return this[fn]?!1:(this[fn]=!0,this.readable=!1,this[Tt]?(xi(()=>this[Ja]()),!0):this[Ja]())}[Ja](){if(this[mr]){let e=this[mr].end();if(e){for(let r of this[Ze])r.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[Ze])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Je]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Je]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Je])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[yt]?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[ot]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[jt])return e();let i,o,c=h=>{this.off("data",d),this.off("end",u),this.off(Ae,x),e(),o(h)},d=h=>{this.off("error",c),this.off("end",u),this.off(Ae,x),this.pause(),i({value:h,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Ae,x),e(),i({done:!0,value:void 0})},x=()=>c(new Error("stream destroyed"));return new Promise((h,m)=>{o=m,i=h,this.once(Ae,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(Va,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(Va,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[ot]=!0,this[He].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Cs]&&e.close(),t?this.emit("error",t):this.emit(Ae),this}static get isStream(){return sw}},pw=rt.writev,En=Symbol("_autoClose"),St=Symbol("_close"),hi=Symbol("_ended"),ue=Symbol("_fd"),Za=Symbol("_finished"),Yt=Symbol("_flags"),Qa=Symbol("_flush"),_c=Symbol("_handleChunk"),yc=Symbol("_makeBuf"),Ii=Symbol("_mode"),Os=Symbol("_needDrain"),kr=Symbol("_onerror"),Tr=Symbol("_onopen"),ec=Symbol("_onread"),vr=Symbol("_onwrite"),vn=Symbol("_open"),vt=Symbol("_path"),mn=Symbol("_pos"),Ct=Symbol("_queue"),Sr=Symbol("_read"),tc=Symbol("_readSize"),Vt=Symbol("_reading"),pi=Symbol("_remain"),nc=Symbol("_size"),qs=Symbol("_write"),Nn=Symbol("_writing"),js=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Hc=class extends Kn{[Gn]=!1;[ue];[vt];[tc];[Vt]=!1;[nc];[pi];[En];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Gn]=!1,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[vt]=t,this[tc]=e.readSize||16*1024*1024,this[Vt]=!1,this[nc]=typeof e.size=="number"?e.size:1/0,this[pi]=this[nc],this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ue]=="number"?this[Sr]():this[vn]()}get fd(){return this[ue]}get path(){return this[vt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[vn](){rt.open(this[vt],"r",(t,e)=>this[Tr](t,e))}[Tr](t,e){t?this[kr](t):(this[ue]=e,this.emit("open",e),this[Sr]())}[yc](){return Buffer.allocUnsafe(Math.min(this[tc],this[pi]))}[Sr](){if(!this[Vt]){this[Vt]=!0;let t=this[yc]();if(t.length===0)return process.nextTick(()=>this[ec](null,0,t));rt.read(this[ue],t,0,t.length,null,(e,r,i)=>this[ec](e,r,i))}}[ec](t,e,r){this[Vt]=!1,t?this[kr](t):this[_c](e,r)&&this[Sr]()}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[kr](t){this[Vt]=!0,this[St](),this.emit("error",t)}[_c](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[St](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ue]=="number"&&this[Sr](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},gw=class extends Hc{[vn](){let t=!0;try{this[Tr](null,rt.openSync(this[vt],"r")),t=!1}finally{t&&this[St]()}}[Sr](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[yc](),r=e.length===0?0:rt.readSync(this[ue],e,0,e.length,null);if(!this[_c](r,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[St]()}}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.closeSync(t),this.emit("close")}}},so=class extends rw{readable=!1;writable=!0;[Gn]=!1;[Nn]=!1;[hi]=!1;[Ct]=[];[Os]=!1;[vt];[Ii];[En];[ue];[js];[Yt];[Za]=!1;[mn];constructor(t,e){e=e||{},super(e),this[vt]=t,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Ii]=e.mode===void 0?438:e.mode,this[mn]=typeof e.start=="number"?e.start:void 0,this[En]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[mn]!==void 0?"r+":"w";this[js]=e.flags===void 0,this[Yt]=e.flags===void 0?r:e.flags,this[ue]===void 0&&this[vn]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[ue]}get path(){return this[vt]}[kr](t){this[St](),this[Nn]=!0,this.emit("error",t)}[vn](){rt.open(this[vt],this[Yt],this[Ii],(t,e)=>this[Tr](t,e))}[Tr](t,e){this[js]&&this[Yt]==="r+"&&t&&t.code==="ENOENT"?(this[Yt]="w",this[vn]()):t?this[kr](t):(this[ue]=e,this.emit("open",e),this[Nn]||this[Qa]())}end(t,e){return t&&this.write(t,e),this[hi]=!0,!this[Nn]&&!this[Ct].length&&typeof this[ue]=="number"&&this[vr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[hi]?(this.emit("error",new Error("write() after end()")),!1):this[ue]===void 0||this[Nn]||this[Ct].length?(this[Ct].push(t),this[Os]=!0,!1):(this[Nn]=!0,this[qs](t),!0)}[qs](t){rt.write(this[ue],t,0,t.length,this[mn],(e,r)=>this[vr](e,r))}[vr](t,e){t?this[kr](t):(this[mn]!==void 0&&typeof e=="number"&&(this[mn]+=e),this[Ct].length?this[Qa]():(this[Nn]=!1,this[hi]&&!this[Za]?(this[Za]=!0,this[St](),this.emit("finish")):this[Os]&&(this[Os]=!1,this.emit("drain"))))}[Qa](){if(this[Ct].length===0)this[hi]&&this[vr](null,0);else if(this[Ct].length===1)this[qs](this[Ct].pop());else{let t=this[Ct];this[Ct]=[],pw(this[ue],t,this[mn],(e,r)=>this[vr](e,r))}}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},df=class extends so{[vn](){let t;if(this[js]&&this[Yt]==="r+")try{t=rt.openSync(this[vt],this[Yt],this[Ii])}catch(e){if(e?.code==="ENOENT")return this[Yt]="w",this[vn]();throw e}else t=rt.openSync(this[vt],this[Yt],this[Ii]);this[Tr](null,t)}[St](){if(this[En]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,rt.closeSync(t),this.emit("close")}}[qs](t){let e=!0;try{this[vr](null,rt.writeSync(this[ue],t,0,t.length,this[mn])),e=!1}finally{if(e)try{this[St]()}catch{}}}},_w=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"]]),yw=t=>!!t.sync&&!!t.file,bw=t=>!t.sync&&!!t.file,Ew=t=>!!t.sync&&!t.file,vw=t=>!t.sync&&!t.file,Sw=t=>!!t.file,Iw=t=>_w.get(t)||t,Gc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Iw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Li=(t,e,r,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let x=Gc(c);if(o?.(x,d),yw(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(x,d)}else if(bw(x)){let h=e(x,d);return u?h.then(()=>u(),u):h}else if(Ew(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(x,d)}else if(vw(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}),Tw=kw.constants||{ZLIB_VERNUM:4736},Ot=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Tw)),Cw=qn.concat,Ru=Object.getOwnPropertyDescriptor(qn,"concat"),Pw=t=>t,rc=Ru?.writable===!0||Ru?.set!==void 0?t=>{qn.concat=t?Pw:Cw}:t=>{},jn=Symbol("_superWrite"),Ls=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},ic=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 Pu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Pu[e](t)}catch(r){throw new Ls(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ls(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return bc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(qn.alloc(0),{[ic]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[jn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=qn.from(t,e)),this.#e)return;bc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},rc(!0);let d;try{let x=typeof t[ic]=="number"?t[ic]:this.#r;d=this.#t._processChunk(t,x),rc(!1)}catch(x){rc(!1),this.#o(new Ls(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 Ls(x,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let x=d[0];u=this[jn](qn.from(x));for(let h=1;h<d.length;h++)u=this[jn](d[h])}else u=this[jn](qn.from(d));return r&&r(),u}},uf=class extends qc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ot.Z_FINISH,t.fullFlushFlag=Ot.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Ot.Z_SYNC_FLUSH),bc(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)}}}},Rw=class extends uf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[jn](t){return this.#e?(this.#e=!1,t[9]=255,super[jn](t)):super[jn](t)}},Dw=class extends uf{constructor(t){super(t,"Unzip")}},ff=class extends qc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ot.BROTLI_OPERATION_FLUSH,super(t,e)}},Ow=class extends ff{constructor(t){super(t,"BrotliCompress")}},Lw=class extends ff{constructor(t){super(t,"BrotliDecompress")}},xf=class extends qc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ot.ZSTD_e_end,t.fullFlushFlag=Ot.ZSTD_e_flush,super(t,e)}},Nw=class extends xf{constructor(t){super(t,"ZstdCompress")}},Mw=class extends xf{constructor(t){super(t,"ZstdDecompress")}},Bw=(t,e)=>{if(Number.isSafeInteger(t))t<0?zw(t,e):Fw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Fw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},zw=(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))}},Uw=t=>{let e=t[0],r=e===128?Gw(t.subarray(1,t.length)):e===255?Hw(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},Hw=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},Gw=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,qw={};nw(qw,{code:()=>jc,isCode:()=>Ws,isName:()=>jw,name:()=>oo,normalFsTypes:()=>gf});var Ws=t=>oo.has(t),jw=t=>jc.has(t),gf=new Set(["0","","1","2","3","4","5","6","7","D"]),oo=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),jc=new Map(Array.from(oo).map(t=>[t[1],t[0]])),Wn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,i){Buffer.isBuffer(t)?this.decode(t,e||0,r,i):t&&this.#n(t)}decode(t,e,r,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Mn(t,e+156,1),c=gf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Mn(t,e,100),this.mode=d?.mode??u?.mode??wn(t,e+100,8),this.uid=d?.uid??u?.uid??wn(t,e+108,8),this.gid=d?.gid??u?.gid??wn(t,e+116,8),this.size=d?.size??u?.size??wn(t,e+124,12),this.mtime=d?.mtime??u?.mtime??sc(t,e+136,12),this.cksum=wn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Ws(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Mn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Mn(t,e+265,32),this.gname=d?.gname??u?.gname??Mn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??wn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??wn(t,e+337,8)??0,t[e+475]!==0){let h=Mn(t,e+345,155);this.path=h+"/"+this.path}else{let h=Mn(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=r?.atime??i?.atime??sc(t,e+476,12),this.ctime=r?.ctime??i?.ctime??sc(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=Ww(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Bn(t,e,100,o)||this.needPax,this.needPax=_n(t,e+100,8,this.mode)||this.needPax,this.needPax=_n(t,e+108,8,this.uid)||this.needPax,this.needPax=_n(t,e+116,8,this.gid)||this.needPax,this.needPax=_n(t,e+124,12,this.size)||this.needPax,this.needPax=oc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Bn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Bn(t,e+265,32,this.uname)||this.needPax,this.needPax=Bn(t,e+297,32,this.gname)||this.needPax,this.needPax=_n(t,e+329,8,this.devmaj)||this.needPax,this.needPax=_n(t,e+337,8,this.devmin)||this.needPax,this.needPax=Bn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Bn(t,e+345,155,c)||this.needPax:(this.needPax=Bn(t,e+345,130,c)||this.needPax,this.needPax=oc(t,e+476,12,this.atime)||this.needPax,this.needPax=oc(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,_n(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:oo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(jc.get(t));if(Ws(e)||e==="Unsupported")this.#e=e;else if(Ws(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Ww=(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.*/,""),sc=(t,e,r)=>Kw(wn(t,e,r)),Kw=t=>t===void 0?void 0:new Date(t*1e3),wn=(t,e,r)=>Number(t[e])&128?Uw(t.subarray(e,e+r)):Vw(t,e,r),$w=t=>isNaN(t)?void 0:t,Vw=(t,e,r)=>$w(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Yw={12:8589934591,8:2097151},_n=(t,e,r,i)=>i===void 0?!1:i>Yw[r]||i<0?(Bw(i,t.subarray(e,e+r)),!0):(Jw(t,e,r,i),!1),Jw=(t,e,r,i)=>t.write(Xw(i,r),e,r,"ascii"),Xw=(t,e)=>Zw(Math.floor(t).toString(8),e),Zw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",oc=(t,e,r,i)=>i===void 0?!1:_n(t,e,r,i.getTime()/1e3),Qw=new Array(156).join("\0"),Bn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Qw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),eo=class mf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),i=512*Math.ceil(1+r/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new Wn({path:("PaxHeader/"+e_(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(t_(n_(e),r),i)}},t_=(t,e)=>e?Object.assign({},e,t):t,n_=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(r_,Object.create(null)),r_=(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},i_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=i_!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),s_=class extends Kn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},ao=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},o_=1024*1024,Ec=Buffer.from([31,139]),vc=Buffer.from([40,181,47,253]),a_=Math.max(Ec.length,vc.length),ft=Symbol("state"),Fn=Symbol("writeEntry"),Kt=Symbol("readEntry"),ac=Symbol("nextEntry"),Du=Symbol("processEntry"),Pt=Symbol("extendedHeader"),gi=Symbol("globalExtendedHeader"),xn=Symbol("meta"),Ou=Symbol("emitMeta"),me=Symbol("buffer"),$t=Symbol("queue"),hn=Symbol("ended"),cc=Symbol("emittedEnd"),zn=Symbol("emit"),Pe=Symbol("unzip"),Ns=Symbol("consumeChunk"),Ms=Symbol("consumeChunkSub"),dc=Symbol("consumeBody"),Lu=Symbol("consumeMeta"),Nu=Symbol("consumeHeader"),mi=Symbol("consuming"),lc=Symbol("bufferConcat"),Bs=Symbol("maybeEnd"),_r=Symbol("writing"),pn=Symbol("aborted"),Fs=Symbol("onDone"),Un=Symbol("sawValidEntry"),zs=Symbol("sawNullBlock"),Us=Symbol("sawEOF"),Mu=Symbol("closeStream"),c_=()=>!0,Oi=class extends Aw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[$t]=[];[me];[Kt];[Fn];[ft]="begin";[xn]="";[Pt];[gi];[hn]=!1;[Pe];[pn]=!1;[Un];[zs]=!1;[Us]=!1;[_r]=!1;[mi]=!1;[cc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Fs,()=>{(this[ft]==="begin"||this[Un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Fs,t.ondone):this.on(Fs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||o_,this.filter=typeof t.filter=="function"?t.filter:c_;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={}){ao(this,t,e,r)}[Nu](t,e){this[Un]===void 0&&(this[Un]=!1);let r;try{r=new Wn(t,e,this[Pt],this[gi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[zs]?(this[Us]=!0,this[ft]==="begin"&&(this[ft]="header"),this[zn]("eof")):(this[zs]=!0,this[zn]("nullBlock"));else if(this[zs]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[Fn]=new s_(r,this[Pt],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[ft]="ignore",o.resume()):o.size>0&&(this[xn]="",o.on("data",c=>this[xn]+=c),this[ft]="meta"):(this[Pt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[ft]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ft]="body":(this[ft]="header",o.end()),this[Kt]?this[$t].push(o):(this[$t].push(o),this[ac]())))}}}[Mu](){queueMicrotask(()=>this.emit("close"))}[Du](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ac]()),e=!1);return e}[ac](){do;while(this[Du](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[_r]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[dc](t,e){let r=this[Fn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[ft]="header",this[Fn]=void 0,r.end()),o.length}[Lu](t,e){let r=this[Fn],i=this[dc](t,e);return!this[Fn]&&r&&this[Ou](r),i}[zn](t,e,r){this[$t].length===0&&!this[Kt]?this.emit(t,e,r):this[$t].push([t,e,r])}[Ou](t){switch(this[zn]("meta",this[xn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Pt]=eo.parse(this[xn],this[Pt],!1);break;case"GlobalExtendedHeader":this[gi]=eo.parse(this[xn],this[gi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Pt]??Object.create(null);this[Pt]=e,e.path=this[xn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Pt]||Object.create(null);this[Pt]=e,e.linkpath=this[xn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[pn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[pn])return r?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[me]&&(t=Buffer.concat([this[me],t]),this[me]=void 0),t.length<a_)return this[me]=t,r?.(),!0;for(let d=0;this[Pe]===void 0&&d<Ec.length;d++)t[d]!==Ec[d]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<vc.length;d++)if(t[d]!==vc[d]){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[me]=t,r?.(),!0;else try{new Wn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||o)){let d=this[hn];this[hn]=!1,this[Pe]=this[Pe]===void 0?new Dw({}):o?new Mw({}):new Lw({}),this[Pe].on("data",x=>this[Ns](x)),this[Pe].on("error",x=>this.abort(x)),this[Pe].on("end",()=>{this[hn]=!0,this[Ns]()}),this[_r]=!0;let u=!!this[Pe][d?"end":"write"](t);return this[_r]=!1,r?.(),u}}this[_r]=!0,this[Pe]?this[Pe].write(t):this[Ns](t),this[_r]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),r?.(),i}[lc](t){t&&!this[pn]&&(this[me]=this[me]?Buffer.concat([this[me],t]):t)}[Bs](){if(this[hn]&&!this[cc]&&!this[pn]&&!this[mi]){this[cc]=!0;let t=this[Fn];if(t&&t.blockRemain){let e=this[me]?this[me].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[me]&&t.write(this[me]),t.end()}this[zn](Fs)}}[Ns](t){if(this[mi]&&t)this[lc](t);else if(!t&&!this[me])this[Bs]();else if(t){if(this[mi]=!0,this[me]){this[lc](t);let e=this[me];this[me]=void 0,this[Ms](e)}else this[Ms](t);for(;this[me]&&this[me]?.length>=512&&!this[pn]&&!this[Us];){let e=this[me];this[me]=void 0,this[Ms](e)}this[mi]=!1}(!this[me]||this[hn])&&this[Bs]()}[Ms](t){let e=0,r=t.length;for(;e+512<=r&&!this[pn]&&!this[Us];)switch(this[ft]){case"begin":case"header":this[Nu](t,e),e+=512;break;case"ignore":case"body":e+=this[dc](t,e);break;case"meta":e+=this[Lu](t,e);break;default:throw new Error("invalid state: "+this[ft])}e<r&&(this[me]=this[me]?Buffer.concat([t.subarray(e),this[me]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[pn]||(this[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[Bs]())),this}},Ai=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},d_=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=>[Ai(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||ww(c).root||".",x;if(c===u)x=!1;else{let h=r.get(c);x=h!==void 0?h:o(mw(c),u)}return r.set(c,x),x};t.filter=i?(c,d)=>i(c,d)&&o(Ai(c)):c=>o(Ai(c))},l_=t=>{let e=new Oi(t),r=t.file,i;try{i=Ir.openSync(r,"r");let o=Ir.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Ir.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<o.size;){let x=Ir.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{Ir.closeSync(i)}catch{}}},u_=(t,e)=>{let r=new Oi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Ir.stat(o,(u,x)=>{if(u)d(u);else{let h=new Hc(o,{readSize:i,size:x.size});h.on("error",d),h.pipe(r)}})})},Cr=Li(l_,u_,t=>new Oi(t),t=>new Oi(t),(t,e)=>{e?.length&&wf(t,e),t.noResume||d_(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:x_,parse:Fu}=f_,Wc=t=>{let e="",r=Fu(t);for(;x_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Fu(t)}return[e,t]},co=["|","<",">","?",":"],Kc=co.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),h_=new Map(co.map((t,e)=>[t,Kc[e]])),p_=new Map(Kc.map((t,e)=>[t,co[e]])),zu=t=>co.reduce((e,r)=>e.split(r).join(h_.get(r)),t),g_=t=>Kc.reduce((e,r)=>e.split(r).join(p_.get(r)),t),yf=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ai(e)+"/"+t):Q(t),m_=16*1024*1024,Uu=Symbol("process"),Hu=Symbol("file"),Gu=Symbol("directory"),Sc=Symbol("symlink"),qu=Symbol("hardlink"),wi=Symbol("header"),Ks=Symbol("read"),Ic=Symbol("lstat"),$s=Symbol("onlstat"),Ac=Symbol("onread"),kc=Symbol("onreadlink"),Tc=Symbol("openfile"),Cc=Symbol("onopenfile"),yn=Symbol("close"),no=Symbol("mode"),Pc=Symbol("awaitDrain"),uc=Symbol("ondrain"),Dt=Symbol("prefix"),bf=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=Gc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||m_,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]=Wc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=g_(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[$s](o):this[Ic]()}warn(t,e,r={}){return ao(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Ic](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[$s](e)})}[$s](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=y_(t),this.emit("stat",t),this[Uu]()}[Uu](){switch(this.type){case"File":return this[Hu]();case"Directory":return this[Gu]();case"SymbolicLink":return this[Sc]();default:return this.end()}}[no](t){return _f(t,this.type==="Directory",this.portable)}[Dt](t){return yf(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[no](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new eo({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[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)}[Gu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[wi](),this.end()}[Sc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[kc](e)})}[kc](t){this.linkpath=Q(t),this[wi](),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[wi](),this.end()}[Hu](){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[wi](),this.stat.size===0)return this.end();this[Tc]()}[Tc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Cc](e)})}[Cc](t){if(this.fd=t,this.#e)return this[yn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Ks]()}[Ks](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Rt.read(t,e,r,i,o,(c,d)=>{if(c)return this[yn](()=>this.emit("error",c));this[Ac](d)})}[yn](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[Ac](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[yn](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[yn](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[uc]():this[Pc](()=>this[uc]())}[Pc](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)}[uc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[yn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Ks]()}},w_=class extends bf{sync=!0;[Ic](){this[$s](Rt.lstatSync(this.absolute))}[Sc](){this[kc](Rt.readlinkSync(this.absolute))}[Tc](){this[Cc](Rt.openSync(this.absolute,"r"))}[Ks](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let d=Rt.readSync(e,r,i,o,c);this[Ac](d),t=!1}finally{if(t)try{this[yn](()=>{})}catch{}}}[Pc](t){t()}[yn](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},__=class extends Kn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return ao(this,t,e,r)}constructor(t,e={}){let r=Gc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[no](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Wc(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new 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 eo({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[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 yf(t,this.prefix)}[no](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}},y_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",b_=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++)v_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)S_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new Ar;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new Ar;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Ar;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<r;d++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=E_(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 E_(t,e,r){let i=e,o=e?e.next:t.head,c=new $c(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function v_(t,e){t.tail=new $c(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function S_(t,e){t.head=new $c(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var $c=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),Vs=Symbol("onStat"),_i=Symbol("ended"),bt=Symbol("queue"),yi=Symbol("pendingLinks"),gn=Symbol("current"),Hn=Symbol("process"),bi=Symbol("processing"),Hs=Symbol("processJob"),Et=Symbol("jobs"),fc=Symbol("jobDone"),Ys=Symbol("addFSEntry"),$u=Symbol("addTarEntry"),Rc=Symbol("stat"),Dc=Symbol("readdir"),Js=Symbol("onreaddir"),Xs=Symbol("pipe"),Vu=Symbol("entry"),xc=Symbol("entryOpt"),Zs=Symbol("writeEntryClass"),Ef=Symbol("write"),hc=Symbol("ondrain"),lo=class extends Kn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Zs];onWriteEntry;[bt];[yi]=new Map;[Et]=0;[bi]=!1;[_i]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Zs]=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 Rw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Ow(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Nw(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[hc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[hc]);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[bt]=new b_,this[Et]=0,this.jobs=Number(t.jobs)||4,this[bi]=!1,this[_i]=!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[_i]=!0,this[Hn](),r&&r(),this}write(t){if(this[_i])throw new Error("write after end");return typeof t=="string"?this[Ys](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 __(t,this[xc](r)),r.entry.on("end",()=>this[fc](r)),this[Et]+=1,this[bt].push(r)}this[Hn]()}[Ys](t){let e=Q(ju.resolve(this.cwd,t));this[bt].push(new Wu(t,e)),this[Hn]()}[Rc](t){t.pending=!0,this[Et]+=1;let e=this.follow?"stat":"lstat";to[e](t.absolute,(r,i)=>{t.pending=!1,this[Et]-=1,r?this.emit("error",r):this[Vs](t,i)})}[Vs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[gn])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[Hn]()}[Dc](t){t.pending=!0,this[Et]+=1,to.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[Et]-=1,e)return this.emit("error",e);this[Js](t,r)})}[Js](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Hn]()}[Hn](){if(!this[bi]){this[bi]=!0;for(let t=this[bt].head;t&&this[Et]<this.jobs;t=t.next)if(this[Hs](t.value),t.value.ignore){let e=t.next;this[bt].removeNode(t),t.next=e}this[bi]=!1,this[_i]&&this[bt].length===0&&this[Et]===0&&(this.zip?this.zip.end(Ku):(super.write(Ku),super.end()))}}get[gn](){return this[bt]&&this[bt].head&&this[bt].head.value}[fc](t){this[bt].shift(),this[Et]-=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[Hn]()}[Hs](t){if(t.pending&&t.pendingLink&&t===this[gn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[gn]&&!t.piped&&this[Xs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Vs](t,e):this[Rc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Js](t,e):this[Dc](t),!t.readdir)return}if(t.entry=this[Vu](t),!t.entry){t.ignore=!0;return}t===this[gn]&&!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}}[Vu](t){this[Et]+=1;try{return new this[Zs](t.path,this[xc](t)).on("end",()=>this[fc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[hc](){this[gn]&&this[gn].entry&&this[gn].entry.resume()}[Xs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Ys](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){ao(this,t,e,r)}},Vc=class extends lo{sync=!0;constructor(t){super(t),this[Zs]=w_}pause(){}resume(){}[Rc](t){let e=this.follow?"statSync":"lstatSync";this[Vs](t,to[e](t.absolute))}[Dc](t){this[Js](t,to.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[Ys](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)})}},I_=(t,e)=>{let r=new Vc(t),i=new df(t.file,{mode:t.mode||438});r.pipe(i),vf(r,e)},A_=(t,e)=>{let r=new lo(t),i=new so(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,d)=>{i.on("error",d),i.on("close",c),r.on("error",d)});return Sf(r,e).catch(c=>r.emit("error",c)),o},vf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({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 Cr({file:lf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},k_=(t,e)=>{let r=new Vc(t);return vf(r,e),r},T_=(t,e)=>{let r=new lo(t);return Sf(r,e).catch(i=>r.emit("error",i)),r},gA=Li(I_,A_,k_,T_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),P_=process.env.__FAKE_PLATFORM__||process.platform,Tf=P_==="win32",{O_CREAT:Cf,O_NOFOLLOW:Yu,O_TRUNC:Pf,O_WRONLY:Rf}=kf.constants,Df=Number(process.env.__FAKE_FS_O_FILENAME__)||kf.constants.UV_FS_O_FILEMAP||0,R_=Tf&&!!Df,D_=512*1024,O_=Df|Pf|Cf|Rf,Ju=!Tf&&typeof Yu=="number"?Yu|Pf|Cf|Rf:null,Of=Ju!==null?()=>Ju:R_?t=>t<D_?O_:"w":()=>"w",Oc=(t,e,r)=>{try{return uo.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},ro=(t,e,r,i)=>{uo.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},L_=(t,e,r,i,o)=>{if(e.isDirectory())Lf(ki.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=ki.resolve(t,e.name);ro(d,r,i,o)});else{let c=ki.resolve(t,e.name);ro(c,r,i,o)}},Lf=(t,e,r,i)=>{uo.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return ro(t,e,r,i);let d=c.length,u=null,x=h=>{if(!u){if(h)return i(u=h);if(--d===0)return ro(t,e,r,i)}};for(let h of c)L_(t,h,e,r,x)})},N_=(t,e,r,i)=>{e.isDirectory()&&Nf(ki.resolve(t,e.name),r,i),Oc(ki.resolve(t,e.name),r,i)},Nf=(t,e,r)=>{let i;try{i=uo.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Oc(t,e,r);throw c}for(let o of i)N_(t,o,e,r);return Oc(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"}},fo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},B_=(t,e)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Mf(t,r?.code||"ENOTDIR")),e(r)})},F_=(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,m=e.unlink,w=Q(e.cwd),I=(S,A)=>{S?r(S):A&&x?Lf(A,d,u,k=>I(k)):c?ct.chmod(t,o,r):r()};if(t===w)return B_(t,I);if(h)return M_.mkdir(t,{mode:o,recursive:!0}).then(S=>I(null,S??void 0),I);let b=Q(io.relative(w,t)).split("/");Lc(w,b,o,m,w,void 0,I)},Lc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),x=Q(io.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())Lc(t,e,r,i,o,c,d);else if(i)ct.unlink(t,m=>{if(m)return d(m);ct.mkdir(t,r,Bf(t,e,r,i,o,c,d))});else{if(h.isSymbolicLink())return d(new fo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Lc(t,e,r,i,o,c,d))},z_=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")}},U_=(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,m=Q(e.cwd),w=S=>{S&&u&&Nf(S,c,d),o&&ct.chmodSync(t,i)};if(t===m)return z_(m),w();if(x)return w(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let I=Q(io.relative(m,t)).split("/"),b;for(let S=I.shift(),A=m;S&&(A+="/"+S);S=I.shift()){A=Q(io.resolve(A));try{ct.mkdirSync(A,i),b=b||A}catch{let k=ct.lstatSync(A);if(k.isDirectory())continue;if(h){ct.unlinkSync(A),ct.mkdirSync(A,i),b=b||A;continue}else if(k.isSymbolicLink())return new fo(A,A+"/"+I.join("/"))}}return w(b)},pc=Object.create(null),Xu=1e4,yr=new Set,H_=t=>{yr.has(t)?yr.delete(t):pc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),yr.add(t);let e=pc[t],r=yr.size-Xu;if(r>Xu/10){for(let i of yr)if(yr.delete(i),delete pc[i],--r<=0)break}return e},G_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,q_=G_==="win32",j_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=Ff(i,r)),e.push(r||"/"),e},[]),W_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=q_?["win32 parallelization disabled"]:t.map(i=>Ai(Ff(H_(i))));let r=new Set(t.map(i=>j_(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}},K_=()=>process.umask(),Zu=Symbol("onEntry"),Nc=Symbol("checkFs"),Qu=Symbol("checkFs2"),Mc=Symbol("isReusable"),xt=Symbol("makeFs"),Bc=Symbol("file"),Fc=Symbol("directory"),Qs=Symbol("link"),ef=Symbol("symlink"),tf=Symbol("hardlink"),Si=Symbol("ensureNoSymlink"),nf=Symbol("unsupported"),rf=Symbol("checkPath"),gc=Symbol("stripAbsolutePath"),bn=Symbol("mkdir"),qe=Symbol("onError"),Gs=Symbol("pending"),sf=Symbol("pend"),br=Symbol("unpend"),mc=Symbol("ended"),wc=Symbol("maybeClose"),zc=Symbol("skip"),Ti=Symbol("doChown"),Ci=Symbol("uid"),Pi=Symbol("gid"),Ri=Symbol("checkedCwd"),$_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Di=$_==="win32",V_=1024,Y_=(t,e)=>{if(!Di)return ie.unlink(t,e);let r=t+".DELETE."+Af(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},J_=t=>{if(!Di)return ie.unlinkSync(t);let e=t+".DELETE."+Af(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},of=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Yc=class extends Oi{[mc]=!1;[Ri]=!1;[Gs]=0;reservations=new W_;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[mc]=!0,this[wc]()},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:V_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Di,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Me.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:K_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Zu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[wc](){this[mc]&&this[Gs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[gc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Wc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Di&&/^[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=Me.posix.dirname(t.path),x=Me.posix.normalize(Me.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[gc](t,"path")||!this[gc](t,"linkpath"))return!1;if(t.absolute=Me.isAbsolute(t.path)?Q(Me.resolve(t.path)):Q(Me.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Me.win32.parse(String(t.absolute));t.absolute=i+zu(String(t.absolute).slice(i.length));let{root:o}=Me.win32.parse(t.path);t.path=o+zu(t.path.slice(o.length))}return!0}[Zu](t){if(!this[rf](t))return t.resume();switch(C_.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[Nc](t);default:return this[nf](t)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[br](),e.resume())}[bn](t,e,r){F_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ti](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ci](t){return of(this.uid,t.uid,this.processUid)}[Pi](t){return of(this.gid,t.gid,this.processGid)}[Bc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new so(String(t.absolute),{flags:Of(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[qe](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,x=>{x?this[qe](x,t):this[br](),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,m=t.mtime;ie.futimes(x,h,m,w=>w?ie.utimes(u,h,m,I=>c(I&&w)):c())}if(typeof x=="number"&&this[Ti](t)){o++;let h=this[Ci](t),m=this[Pi](t);typeof h=="number"&&typeof m=="number"&&ie.fchown(x,h,m,w=>w?ie.chown(u,h,m,I=>c(I&&w)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[qe](u,t),e()}),t.pipe(d)),d.pipe(i)}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[bn](String(t.absolute),r,i=>{if(i){this[qe](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[br](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ti](t)&&(o++,ie.chown(String(t.absolute),Number(this[Ci](t)),Number(this[Pi](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(Me.relative(this.cwd,Me.resolve(Me.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Si](t,this.cwd,r,()=>this[Qs](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[tf](t,e){let r=Q(Me.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Si](t,this.cwd,i,()=>this[Qs](t,r,"link",e),o=>{this[qe](o,t),e()})}[Si](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Me.resolve(e,c);ie.lstat(d,(u,x)=>{if(u)return i();if(x?.isSymbolicLink())return o(new fo(d,Me.resolve(d,r.join("/"))));this[Si](t,d,r,i,o)})}[sf](){this[Gs]++}[br](){this[Gs]--,this[wc]()}[zc](t){this[br](),t.resume()}[Mc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Di}[Nc](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[bn](this.cwd,this.dmode,d=>{if(d){this[qe](d,t),r();return}this[Ri]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Me.dirname(String(t.absolute)));if(d!==this.cwd)return this[bn](d,this.dmode,u=>{if(u){this[qe](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[zc](t),r();return}if(d||this[Mc](t,u))return this[xt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let x=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=m=>this[xt](m??null,t,r);return x?ie.chmod(String(t.absolute),Number(t.mode),h):h()}if(t.absolute!==this.cwd)return ie.rmdir(String(t.absolute),x=>this[xt](x??null,t,r))}if(t.absolute===this.cwd)return this[xt](null,t,r);Y_(String(t.absolute),x=>this[xt](x??null,t,r))})};this[Ri]?o():i()}[xt](t,e,r){if(t){this[qe](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Bc](e,r);case"Link":return this[tf](e,r);case"SymbolicLink":return this[ef](e,r);case"Directory":case"GNUDumpDir":return this[Fc](e,r)}}[Qs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[qe](o,t):(this[br](),t.resume()),i()})}},Ei=t=>{try{return[null,t()]}catch(e){return[e,null]}},zf=class extends Yc{sync=!0;[xt](t,e){return super[xt](t,e,()=>{})}[Nc](t){if(!this[Ri]){let o=this[bn](this.cwd,this.dmode);if(o)return this[qe](o,t);this[Ri]=!0}if(t.absolute!==this.cwd){let o=Q(Me.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[bn](o,this.dmode);if(c)return this[qe](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[zc](t);if(e||this[Mc](t,r))return this[xt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?Ei(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[xt](d,t)}let[o]=Ei(()=>ie.rmdirSync(String(t.absolute)));this[xt](o,t)}let[i]=t.absolute===this.cwd?[]:Ei(()=>J_(String(t.absolute)));this[xt](i,t)}[Bc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{ie.closeSync(o)}catch(x){u=x}(d||u)&&this[qe](d||u,t),e()},o;try{o=ie.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[qe](d,t)),t.pipe(c)),c.on("data",d=>{try{ie.writeSync(o,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,x=t.mtime;try{ie.futimesSync(o,u,x)}catch(h){try{ie.utimesSync(String(t.absolute),u,x)}catch{d=h}}}if(this[Ti](t)){let u=this[Ci](t),x=this[Pi](t);try{ie.fchownSync(o,Number(u),Number(x))}catch(h){try{ie.chownSync(String(t.absolute),Number(u),Number(x))}catch{d=d||h}}}i(d)})}[Fc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[bn](String(t.absolute),r);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ti](t))try{ie.chownSync(String(t.absolute),Number(this[Ci](t)),Number(this[Pi](t)))}catch{}e(),t.resume()}[bn](t,e){try{return U_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Si](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Me.resolve(c,d);let[u,x]=Ei(()=>ie.lstatSync(c));if(u)return i();if(x.isSymbolicLink())return o(new fo(c,Me.resolve(e,r.join("/"))))}i()}[Qs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[qe](c,t)}}},X_=t=>{let e=new zf(t),r=t.file,i=If.statSync(r),o=t.maxReadSize||16*1024*1024;new gw(r,{readSize:o,size:i.size}).pipe(e)},Z_=(t,e)=>{let r=new Yc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),If.stat(o,(u,x)=>{if(u)d(u);else{let h=new Hc(o,{readSize:i,size:x.size});h.on("error",d),h.pipe(r)}})})},Uf=Li(X_,Z_,t=>new zf(t),t=>new Yc(t),(t,e)=>{e?.length&&wf(t,e)}),Q_=(t,e)=>{let r=new Vc(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 m=0,w=0;m<512;m+=w){if(w=at.readSync(o,u,m,u.length-m,c+m),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let x=new Wn(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,ey(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},ey=(t,e,r,i,o)=>{let c=new df(t.file,{fd:i,start:r});e.pipe(c),ny(e,o)},ty=(t,e)=>{e=Array.from(e);let r=new lo(t),i=(o,c,d)=>{let u=(I,b)=>{I?at.close(o,S=>d(I)):d(null,b)},x=0;if(c===0)return u(null,0);let h=0,m=Buffer.alloc(512),w=(I,b)=>{if(I||b===void 0)return u(I);if(h+=b,h<512&&b)return at.read(o,m,h,m.length-h,x+h,w);if(x===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(h<512)return u(null,x);let S=new Wn(m);if(!S.cksumValid)return u(null,x);let A=512*Math.ceil((S.size??0)/512);if(x+A+512>c||(x+=A+512,x>=c))return u(null,x);t.mtimeCache&&S.mtime&&t.mtimeCache.set(String(S.path),S.mtime),h=0,at.read(o,m,0,512,x,w)};at.read(o,m,0,512,x,w)};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,(m,w)=>{if(m)return at.close(h,()=>c(m));i(h,w.size,(I,b)=>{if(I)return c(I);let S=new so(t.file,{fd:h,start:b});r.pipe(S),S.on("error",c),S.on("close",o),ry(r,e)})})};at.open(t.file,d,u)})},ny=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Cr({file:Hf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},ry=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Cr({file:Hf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},vi=Li(Q_,ty,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Sw(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")}),RA=Li(vi.syncFile,vi.asyncFile,vi.syncNoFile,vi.asyncNoFile,(t,e=[])=>{vi.validate?.(t,e),iy(t)}),iy=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 ht={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function xo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Gf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ho(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function 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 $n(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Jt();Ke();te();Ce();Ke();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 Rr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as Ek}from"node:fs";import{dirname as Sk,join as Ik}from"node:path";import{fileURLToPath as kk}from"node:url";var Lt="0.2.7-beta.1";import{mkdir as by,rm as d0}from"node:fs/promises";import{join as Ui}from"node:path";Gt();import{readFileSync as fy}from"node:fs";var xy=384;async function Jc(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:xy})}function Mi(t){try{let e=JSON.parse(fy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Vf(t,e,r={},i=o=>o){return{...i({...t,...Mi(e)}),...r}}Gt();function Bi(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(hy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
92
- `)}
93
- `}function hy(t){if(t.includes(`
94
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();Ce();import{homedir as my}from"node:os";import{join as wy}from"node:path";Ke();te();var po="1008033",Yf="1289";var Jf="pbbp2",Xf="https://www.coze.cn",Zf="/api/coze_claw/resource/get_frontier_key",py="https://www.coze.cn",gy="wss://frontier.coze.cn";function Dr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??py}function Qf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??gy}function Sn(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function zi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Fi=j("handshake");async function Xc(t){let e=Dr(t.endpoint),r=t.timeoutMs??1e4,i=`${Rr(e)}${Zf}?aid=${encodeURIComponent(po)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Sn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Fi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),x=u.headers.get("x-tt-logid")??"",h=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let S=await u.text().catch(()=>"");throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${x}: ${S.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${x}`);let w=m.data??{},I=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,b=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!I||!b){let S=JSON.stringify(m).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${x}: ${S}`)}return Fi.info("handshake ok",{remoteDeviceId:b,logid:x,traceId:h}),{accessKey:I,deviceId:b}}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 x=u.cause;throw Fi.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 go=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",It="auto",Zc=19e4,e0=8192;function n0(t){return{model:Qc(t.model)??It,...t.modelToken?{modelToken:t.modelToken}:{}}}function r0(t){return!t||t===It}var _y=new Set(["auto","\u81EA\u52A8"]);function Qc(t){let e=t?.trim();if(e)return _y.has(e.toLowerCase())?It:e}function i0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=go,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||It;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else r0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function s0(t,e,r){let i={};if(t.modelToken?i.model=t.model||It:r0(t.model)||(i.model=t.model),t.modelToken){let o={name:"coze",base_url:`${go}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},c=mo(e,r);Object.keys(c).length>0&&(o.http_headers=c),i.model_providers={coze:o},i.model_context_window=t.modelInfo?.contextWindow??Zc}return Object.keys(i).length===0?{}:{CODEX_CONFIG:JSON.stringify(i),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function o0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function mo(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 a0(t,e,r){if(!t.modelToken)return{};let i=mo(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
95
- `)}}function ed(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function td(t){return t.model||It}function t0(t,e,r,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:r,maxTokens:i,api:"openai-completions"}}function c0(t,e,r,i){if(!t.modelToken)return null;let o=td(t),c=mo(e,r),d=["text"];t.modelInfo?.capabilities?.image===!0&&d.push("image");let u=[t0(o,d,t.modelInfo?.contextWindow??Zc,t.modelInfo?.maxOutput??e0)],x=new Set([o]);for(let m of i??[])!m||x.has(m)||(x.add(m),u.push(t0(m,["text"],Zc,e0)));let h={baseUrl:`${go}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(c).length>0&&(h.headers=c),h}function yy(t){if(t!==void 0)return t?"auto":"text"}function nd(t,e,r){let i=mo(e,r),o=t.model||It,c=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${go}/v1`];if(t.modelInfo?.contextWindow&&c.push(` context_length: ${t.modelInfo.contextWindow}`),t.modelInfo?.maxOutput&&c.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&c.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){c.push(" default_headers:");for(let[u,x]of Object.entries(i))c.push(` ${u}: ${JSON.stringify(x)}`)}c.push("compression:"),c.push(" threshold: 0.8"),c.push("approvals:"),c.push(` mode: ${JSON.stringify("off")}`),c.push(` cron_mode: ${JSON.stringify("approve")}`);let d=yy(t.modelInfo?.capabilities?.image);return d&&(c.push("agent:"),c.push(` image_input_mode: ${JSON.stringify(d)}`)),c.push("skills:"),c.push(" external_dirs:"),c.push(` - ${wy(my(),".hermes","skills")}`),`${c.join(`
96
- `)}
97
- `}var Vn=j("hermes-config"),l0="dont_ask",u0="default";function Yn(t,e){return Ui(Fe(t,e).root,"hermes-home")}async function Ey(t){let e=Yn(t.agentId,t.paths);await by(e,{recursive:!0,mode:448});let r=Bi({...process.env,...Mi(t.paths.agentEnvFile)});await ut(Ui(e,".env"),r,{mode:384});let i=nd(t.modelConfig,t.cozeEnv,t.mockScenario);await ut(Ui(e,"config.yaml"),i,{mode:384}),Vn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:r.length,yamlBytes:i.length})}async function f0(t){let e=Yn(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 d0(r,{force:!0}).catch(c=>Vn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(c)}));let o=nd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ut(i,o,{mode:384}).catch(c=>Vn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(c)})),Vn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function id(t,e){let r=Yn(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 d0(r,{recursive:!0,force:!0}).catch(i=>Vn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var rd=new Map;function x0(t){let e=rd.get(t.agentId);if(e)return e;let r=Ey(t).finally(()=>rd.delete(t.agentId));return rd.set(t.agentId,r),r}var ne=j("agent-handlers"),p0=5*1024*1024,ky=1,Ty=6,Cy=new Set(["node_modules",".git",".coze","dist","build",".next"]),Py=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ry=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Dy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Oy(t){let e=t?.trim();return e?Dy.test(e)||Ry.test(e)?e:(ne.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Ly(t){return new Promise((e,r)=>{let i=it("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))})}function Ny(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var _o=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??Fe(r,this.paths).workspace,c=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Lr(c,r,o,this.paths),x=[],h=new Set;for(let m of d){let w=fe(u,m.relPath,"SKILL.md");await ud(w).then(b=>b.isFile()).catch(()=>!1)&&(x.push(Uy(m)),h.add(m.relPath))}if(e.scanLocal){let m=await A0(r,o,c,this.paths),w=await k0(r,c);for(let I of[...m,...w])h.has(I.relPath)||(h.add(I.relPath),x.push(I.skill))}return{skills:x}}async addSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((x,h)=>[x.skillId,h])),u=[];for(let x of o){let h=await yo({agentId:r,workspace:i.workspace,framework:i.framework,skill:x,paths:this.paths});bo(c,d,h),u.push(x)}return await ci(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],d=[],{base:u}=Lr(i.framework,r,i.workspace,this.paths);for(let x of c){if(!o.has(x.skillId)){d.push(x);continue}let h=fe(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 ad(h,{recursive:!0,force:!0}),ne.info("skill removed",{agentId:r,skillId:x.skillId,relPath:x.relPath})}return await ci(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=$n(e._meta);if(!e.skillName)throw new 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=await By(r,o,c,e.skillName,d,this.paths);if(!u){let L=d?"global":"workspace";throw new T("SKILL_NOT_FOUND",`skill not found in ${L}: ${e.skillName}`)}let{absDir:x,relPath:h,dirName:m}=u,w=fe(x,"SKILL.md"),I=new xd.default;I.addLocalFolder(x,m);let b=I.toBuffer();if(b.length>g0)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${b.length} bytes exceeds limit ${g0}`);let S=await wo(w,{encoding:"utf8"}).then(L=>S0(L).description).catch(()=>{}),A={};this.opts.publishSkillToMarketplace?A=await this.opts.publishSkillToMarketplace({zip:b,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...S?{description:S}:{},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 k=A.version??"v1.0",P=A.skillId??e.skillId??v0(r,h);if(i&&!d){let L=i.skills??[],E=L.find(D=>D.relPath===h);E?(E.version=k,E.skillId=P):L.push({skillId:P,skillName:e.skillName,relPath:h,version:k,installedAt:Date.now(),...S?{description:S}:{}}),await ci(r,L)}return ne.info("skill published",{agentId:r,skillName:e.skillName,relPath:h,zipBytes:b.length,skillId:P,version:k}),{ok:!0,skillId:P,version:k}}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 ve(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 xr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw ne.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await ze(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 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=Oy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Py.test(d)&&o.push("--env",d);let u=await Ly(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 ve(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await ze(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",`${ht.DELETE}: missing agentId`);ne.warn("[AUDIT] deleteAgent handler entry",{agentId:r,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
- `).slice(1,6).join(" | ")});let i=await ve(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let d=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 ad(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await ze(i)),ne.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)??It,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 ze(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,d=o.modelInfo;o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(h=>ne.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(h)}));let u=o.framework==="hermes"&&Ny(d,o.modelInfo);if(o.framework==="hermes"&&!u){let h=[];for(let[m,w]of o.allSessionQueues())h.push(w.enqueue(async()=>{let I=o.sessions.get(m);if(!(!I?.downstream||!I.acpSessionId))try{await I.downstream.setSessionModel?.({sessionId:I.acpSessionId,modelId:r})}catch(b){ne.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:m,acpId:I.acpSessionId,err:String(b)})}}));return await Promise.all(h),ne.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:r,cloudSessions:h.length}),{ok:!0}}let x=[];for(let[h,m]of o.allSessionQueues())x.push(m.enqueue(async()=>{let w=o.sessions.get(h);w?.downstream&&(await w.downstream.stop(`switchModel: ${r}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(x),ne.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:x.length}),{ok:!0}}async resetAgent(e){if(Pr(e._meta,ht.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ht.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ht.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(r=>ne.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(r)})),await this.runDetailSync(e.agentId,ht.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),ne.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await ai(e,o)}async clearPersistedAcpSessionIds(e){let r=await ve(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await ze(r)}async repairAgent(e){if(Pr(e._meta,ht.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ht.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${ht.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){ne.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ht.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){ne.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){ne.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Pr(e._meta,"_agent/getFileTree");let r=e._meta,i=$n(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await sd(d).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await oi(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let x=Zy(e.depth);return u.isDirectory()?{tree:await Xy(o,d,c,x)}:{tree:[{name:Qy(c),path:P0(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>p0)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${p0})`);let d=await wo(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:c.size}:{content:d.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await ve(e).catch(()=>null))?.workspace??Fe(e).workspace}safeJoin(e,r){let i=dd(e,r||"."),o=fd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${w0}`))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 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 Lr(t,e,r,i){switch(t){case"claude-code":return{base:r,subdir:fe(".claude","skills")};case"codex":case"openclaw":return{base:r,subdir:fe(".agents","skills")};case"hermes":return{base:Yn(e,i??J()),subdir:"skills"}}}function E0(t){let e=Sy();if(t==="claude-code")return[fe(e,".claude","skills")];if(t==="codex")return[fe(e,".agents","skills"),fe(e,".codex","skills")];if(t==="openclaw")return[fe(e,".agents","skills"),fe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA||fe(e,"AppData","Local");return[fe(r,"hermes","skills"),fe(e,".hermes","skills")]}return[fe(e,".hermes","skills")]}return[]}async function My(t,e,r,i,o,c){let d=async u=>ud(fe(u,"SKILL.md")).then(x=>x.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:x}=Lr(r,t,e,c),h=fe(x,i),m=fe(u,h);return await d(m)?{absDir:m,relPath:h}:null}for(let u of E0(r)){let x=fe(u,i);if(await d(x))return{absDir:x,relPath:x}}return null}async function By(t,e,r,i,o,c){let d=b0(i),u=await My(t,e,r,d,o,c);if(u)return{...u,dirName:d};let h=(o?await k0(t,r):await A0(t,e,r,c)).filter(I=>I.skill.skillName===i);if(h.length>1)throw new T("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(I=>h0(I.relPath)).join(", ")} \u2014 rename or remove duplicates`);let m=h[0];return m?{absDir:o?m.relPath:fe(e,m.relPath),relPath:m.relPath,dirName:h0(m.relPath)}:null}function v0(t,e){return(vy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function S0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
89
+ `},configPath(t){return VI(t.homeDir,".coze","bridge","task.xml")},async install(t){let r=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await Gp("schtasks",["/Create","/SC","ONLOGON","/TN",ba,"/TR",r,"/RU",t.userName,"/F"]),hl.info("task scheduler entry created",{task:ba,logFile:t.logFile})},async uninstall(t){await Gp("schtasks",["/Delete","/TN",ba,"/F"]).catch(e=>hl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),hl.info("task scheduler entry removed",{task:ba})}}});var jp={};Na(jp,{buildContext:()=>eA,getSupervisor:()=>XI,launchdSupervisor:()=>ul,systemdSupervisor:()=>fl,taskSchedulerSupervisor:()=>xl});import{homedir as JI,userInfo as ZI}from"node:os";function XI(t=process.platform){switch(t){case"darwin":return ul;case"linux":return fl;case"win32":return xl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function QI(){let t={};for(let e of YI){let r=process.env[e];r&&(t[e]=r)}return t}function eA(){let t=Z();return{nodeBin:process.execPath,entry:nl(t),logFile:t.logFile,homeDir:JI(),userName:ZI().username,isRoot:process.getuid?.()===0,env:QI()}}var YI,Wp=nt(()=>{"use strict";Te();ua();zp();Hp();qp();YI=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});re();dn();var Wl=G("acp-installer-warmup"),wm=["claude-code","codex"];async function Kl(t={}){let e=t.ensure??hr,i=(await Promise.allSettled(wm.map(async o=>{let c=await e(o);Wl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Wl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}xn();re();import{readdir as Lm}from"node:fs/promises";import{mkdir as Zl,readFile as Pm,writeFile as Xl}from"node:fs/promises";import{join as Ga}from"node:path";var Om={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function xr(t,e,r){await Zl(t,{recursive:!0});let i=Om[e],o=Ga(t,i);return await Xl(o,r??"","utf8"),o}async function qa(t,e,r){let i=Ga(t,".claude");await Zl(i,{recursive:!0});let o=Ga(i,"settings.local.json"),c={};try{let u=await Pm(o,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(c=h)}catch{}let d=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=r)}return c.permissions=d,await Xl(o,JSON.stringify(c,null,2),"utf8"),o}var Qe=G("agent-detail-sync"),Nm=6e4,Mm=5*6e4,Is=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Lm(r)}catch(o){Qe.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Ce(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Qe.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await Ce(e,this.opts.paths);if(!i){Qe.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),m=x?Math.min(x.currentDelay*2,Mm):Nm;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(o.agentId&&o.agentId!==e){Qe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Qe.debug("detail sync: no diff",{agentId:e});return}await ze(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await xr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var xd=qt(Ru(),1);import{createHash as wy}from"node:crypto";import{lstat as od,mkdir as ad,readFile as wo,readdir as w0,rm as cd,stat as fd,writeFile as dd}from"node:fs/promises";import{homedir as _y}from"node:os";import{basename as p0,dirname as yy,join as xe,normalize as by,relative as hd,resolve as ld,sep as _0}from"node:path";import{Readable as y0}from"node:stream";import{pipeline as b0}from"node:stream/promises";import iw from"events";import it from"fs";import{EventEmitter as qc}from"node:events";import hf from"node:stream";import{StringDecoder as sw}from"node:string_decoder";import gf from"node:path";import Ar from"node:fs";import{dirname as ww,parse as _w}from"path";import{EventEmitter as kw}from"events";import Sc from"assert";import{Buffer as Kn}from"buffer";import*as Nu from"zlib";import Tw from"zlib";import{posix as _r}from"node:path";import{basename as n_}from"node:path";import ro from"fs";import Dt from"fs";import qu from"path";import{win32 as p_}from"node:path";import Zu from"path";import Df from"node:fs";import P_ from"node:assert";import{randomBytes as Pf}from"node:crypto";import se from"node:fs";import Ne from"node:path";import Of from"fs";import ho from"node:fs";import Di from"node:path";import ct from"node:fs";import z_ from"node:fs/promises";import oo from"node:path";import{join as jf}from"node:path";import at from"node:fs";import $f from"node:path";var nw=Object.defineProperty,rw=(t,e)=>{for(var r in e)nw(t,r,{get:e[r],enumerable:!0})},Du=typeof process=="object"&&process?process:{stdout:null,stderr:null},ow=t=>!!t&&typeof t=="object"&&(t instanceof Jn||t instanceof hf||aw(t)||cw(t)),aw=t=>!!t&&typeof t=="object"&&t instanceof qc&&typeof t.pipe=="function"&&t.pipe!==hf.Writable.prototype.pipe,cw=t=>!!t&&typeof t=="object"&&t instanceof qc&&typeof t.write=="function"&&typeof t.end=="function",jt=Symbol("EOF"),Wt=Symbol("maybeEmitEnd"),gn=Symbol("emittedEnd"),Rs=Symbol("emittingEnd"),hi=Symbol("emittedError"),Ds=Symbol("closed"),Pu=Symbol("read"),Ps=Symbol("flush"),Ou=Symbol("flushChunk"),_t=Symbol("encoding"),wr=Symbol("decoder"),Ue=Symbol("flowing"),xi=Symbol("paused"),vr=Symbol("resume"),He=Symbol("buffer"),et=Symbol("pipes"),Ge=Symbol("bufferLength"),Ja=Symbol("bufferPush"),Os=Symbol("bufferShift"),Ye=Symbol("objectMode"),Ie=Symbol("destroyed"),Za=Symbol("error"),Xa=Symbol("emitData"),Lu=Symbol("emitEnd"),Ya=Symbol("emitEnd2"),kt=Symbol("async"),Qa=Symbol("abort"),Ls=Symbol("aborted"),pi=Symbol("signal"),Bn=Symbol("dataListeners"),ot=Symbol("discarded"),gi=t=>Promise.resolve().then(t),dw=t=>t(),lw=t=>t==="end"||t==="finish"||t==="prefinish",uw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,fw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),xf=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[vr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},hw=class extends xf{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},xw=t=>!!t.objectMode,pw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Jn=class extends qc{[Ue]=!1;[xi]=!1;[et]=[];[He]=[];[Ye];[_t];[kt];[wr];[jt]=!1;[gn]=!1;[Rs]=!1;[Ds]=!1;[hi]=null;[Ge]=0;[Ie]=!1;[pi];[Ls]=!1;[Bn]=0;[ot]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");xw(e)?(this[Ye]=!0,this[_t]=null):pw(e)?(this[_t]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[_t]=null),this[kt]=!!e.async,this[wr]=this[_t]?new sw(this[_t]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:r}=e;r&&(this[pi]=r,r.aborted?this[Qa]():r.addEventListener("abort",()=>this[Qa]()))}get bufferLength(){return this[Ge]}get encoding(){return this[_t]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[kt]}set async(t){this[kt]=this[kt]||!!t}[Qa](){this[Ls]=!0,this.emit("abort",this[pi]?.reason),this.destroy(this[pi]?.reason)}get aborted(){return this[Ls]}set aborted(t){}write(t,e,r){if(this[Ls])return!1;if(this[jt])throw new Error("write after end");if(this[Ie])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[kt]?gi:dw;if(!this[Ye]&&!Buffer.isBuffer(t)){if(fw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(uw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[Ja](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):t.length?(typeof t=="string"&&!(e===this[_t]&&!this[wr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[_t]&&(t=this[wr].write(t)),this[Ue]&&this[Ge]!==0&&this[Ps](!0),this[Ue]?this.emit("data",t):this[Ja](t),this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue]):(this[Ge]!==0&&this.emit("readable"),r&&i(r),this[Ue])}read(t){if(this[Ie])return null;if(this[ot]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[Wt](),null;this[Ye]&&(t=null),this[He].length>1&&!this[Ye]&&(this[He]=[this[_t]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[Pu](t||null,this[He][0]);return this[Wt](),e}[Pu](t,e){if(this[Ye])this[Os]();else{let r=e;t===r.length||t===null?this[Os]():typeof r=="string"?(this[He][0]=r.slice(t),e=r.slice(0,t),this[Ge]-=t):(this[He][0]=r.subarray(t),e=r.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].length&&!this[jt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[jt]=!0,this.writable=!1,(this[Ue]||!this[xi])&&this[Wt](),this}[vr](){this[Ie]||(!this[Bn]&&!this[et].length&&(this[ot]=!0),this[xi]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[Ps]():this[jt]?this[Wt]():this.emit("drain"))}resume(){return this[vr]()}pause(){this[Ue]=!1,this[xi]=!0,this[ot]=!1}get destroyed(){return this[Ie]}get flowing(){return this[Ue]}get paused(){return this[xi]}[Ja](t){this[Ye]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[Os](){return this[Ye]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[Ps](t=!1){do;while(this[Ou](this[Os]())&&this[He].length);!t&&!this[He].length&&!this[jt]&&this.emit("drain")}[Ou](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[Ie])return t;this[ot]=!1;let r=this[gn];return e=e||{},t===Du.stdout||t===Du.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[et].push(e.proxyErrors?new hw(this,t,e):new xf(this,t,e)),this[kt]?gi(()=>this[vr]()):this[vr]()),t}unpipe(t){let e=this[et].find(r=>r.dest===t);e&&(this[et].length===1?(this[Ue]&&this[Bn]===0&&(this[Ue]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[ot]=!1,this[Bn]++,!this[et].length&&!this[Ue]&&this[vr]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(lw(t)&&this[gn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[hi]){let i=e;this[kt]?gi(()=>i.call(this,this[hi])):i.call(this,this[hi])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Bn]=this.listeners("data").length,this[Bn]===0&&!this[ot]&&!this[et].length&&(this[Ue]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Bn]=0,!this[ot]&&!this[et].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[gn]}[Wt](){!this[Rs]&&!this[gn]&&!this[Ie]&&this[He].length===0&&this[jt]&&(this[Rs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ds]&&this.emit("close"),this[Rs]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ie&&this[Ie])return!1;if(t==="data")return!this[Ye]&&!r?!1:this[kt]?(gi(()=>this[Xa](r)),!0):this[Xa](r);if(t==="end")return this[Lu]();if(t==="close"){if(this[Ds]=!0,!this[gn]&&!this[Ie])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[hi]=r,super.emit(Za,r);let o=!this[pi]||this.listeners("error").length?super.emit("error",r):!1;return this[Wt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Wt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[Wt](),i}[Xa](t){for(let r of this[et])r.dest.write(t)===!1&&this.pause();let e=this[ot]?!1:super.emit("data",t);return this[Wt](),e}[Lu](){return this[gn]?!1:(this[gn]=!0,this.readable=!1,this[kt]?(gi(()=>this[Ya]()),!0):this[Ya]())}[Ya](){if(this[wr]){let e=this[wr].end();if(e){for(let r of this[et])r.dest.write(e);this[ot]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Ye]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[_t]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Ie,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ot]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[jt])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(Ie,h),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(Ie,h),this.pause(),i({value:x,done:!!this[jt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Ie,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((x,m)=>{o=m,i=x,this.once(Ie,h),this.once("error",c),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ot]=!1;let t=!1,e=()=>(this.pause(),this.off(Za,e),this.off(Ie,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Za,e),this.once(Ie,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Ie])return t?this.emit("error",t):this.emit(Ie),this;this[Ie]=!0,this[ot]=!0,this[He].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Ds]&&e.close(),t?this.emit("error",t):this.emit(Ie),this}static get isStream(){return ow}},gw=it.writev,In=Symbol("_autoClose"),vt=Symbol("_close"),mi=Symbol("_ended"),de=Symbol("_fd"),ec=Symbol("_finished"),Jt=Symbol("_flags"),tc=Symbol("_flush"),Ec=Symbol("_handleChunk"),vc=Symbol("_makeBuf"),Ci=Symbol("_mode"),Ns=Symbol("_needDrain"),Tr=Symbol("_onerror"),Cr=Symbol("_onopen"),nc=Symbol("_onread"),Sr=Symbol("_onwrite"),An=Symbol("_open"),Et=Symbol("_path"),yn=Symbol("_pos"),Tt=Symbol("_queue"),Ir=Symbol("_read"),rc=Symbol("_readSize"),Vt=Symbol("_reading"),wi=Symbol("_remain"),ic=Symbol("_size"),Ws=Symbol("_write"),Fn=Symbol("_writing"),Ks=Symbol("_defaultFlag"),Wn=Symbol("_errored"),jc=class extends Jn{[Wn]=!1;[de];[Et];[rc];[Vt]=!1;[ic];[wi];[In];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Wn]=!1,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Et]=t,this[rc]=e.readSize||16*1024*1024,this[Vt]=!1,this[ic]=typeof e.size=="number"?e.size:1/0,this[wi]=this[ic],this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[Ir]():this[An]()}get fd(){return this[de]}get path(){return this[Et]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[An](){it.open(this[Et],"r",(t,e)=>this[Cr](t,e))}[Cr](t,e){t?this[Tr](t):(this[de]=e,this.emit("open",e),this[Ir]())}[vc](){return Buffer.allocUnsafe(Math.min(this[rc],this[wi]))}[Ir](){if(!this[Vt]){this[Vt]=!0;let t=this[vc]();if(t.length===0)return process.nextTick(()=>this[nc](null,0,t));it.read(this[de],t,0,t.length,null,(e,r,i)=>this[nc](e,r,i))}}[nc](t,e,r){this[Vt]=!1,t?this[Tr](t):this[Ec](e,r)&&this[Ir]()}[vt](){if(this[In]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Tr](t){this[Vt]=!0,this[vt](),this.emit("error",t)}[Ec](t,e){let r=!1;return this[wi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[wi]<=0)&&(r=!1,this[vt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[Ir](),!1;case"error":return this[Wn]?!1:(this[Wn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},mw=class extends jc{[An](){let t=!0;try{this[Cr](null,it.openSync(this[Et],"r")),t=!1}finally{t&&this[vt]()}}[Ir](){let t=!0;try{if(!this[Vt]){this[Vt]=!0;do{let e=this[vc](),r=e.length===0?0:it.readSync(this[de],e,0,e.length,null);if(!this[Ec](r,e))break}while(!0);this[Vt]=!1}t=!1}finally{t&&this[vt]()}}[vt](){if(this[In]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.closeSync(t),this.emit("close")}}},ao=class extends iw{readable=!1;writable=!0;[Wn]=!1;[Fn]=!1;[mi]=!1;[Tt]=[];[Ns]=!1;[Et];[Ci];[In];[de];[Ks];[Jt];[ec]=!1;[yn];constructor(t,e){e=e||{},super(e),this[Et]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[Ci]=e.mode===void 0?438:e.mode,this[yn]=typeof e.start=="number"?e.start:void 0,this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[yn]!==void 0?"r+":"w";this[Ks]=e.flags===void 0,this[Jt]=e.flags===void 0?r:e.flags,this[de]===void 0&&this[An]()}emit(t,...e){if(t==="error"){if(this[Wn])return!1;this[Wn]=!0}return super.emit(t,...e)}get fd(){return this[de]}get path(){return this[Et]}[Tr](t){this[vt](),this[Fn]=!0,this.emit("error",t)}[An](){it.open(this[Et],this[Jt],this[Ci],(t,e)=>this[Cr](t,e))}[Cr](t,e){this[Ks]&&this[Jt]==="r+"&&t&&t.code==="ENOENT"?(this[Jt]="w",this[An]()):t?this[Tr](t):(this[de]=e,this.emit("open",e),this[Fn]||this[tc]())}end(t,e){return t&&this.write(t,e),this[mi]=!0,!this[Fn]&&!this[Tt].length&&typeof this[de]=="number"&&this[Sr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[mi]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[Fn]||this[Tt].length?(this[Tt].push(t),this[Ns]=!0,!1):(this[Fn]=!0,this[Ws](t),!0)}[Ws](t){it.write(this[de],t,0,t.length,this[yn],(e,r)=>this[Sr](e,r))}[Sr](t,e){t?this[Tr](t):(this[yn]!==void 0&&typeof e=="number"&&(this[yn]+=e),this[Tt].length?this[tc]():(this[Fn]=!1,this[mi]&&!this[ec]?(this[ec]=!0,this[vt](),this.emit("finish")):this[Ns]&&(this[Ns]=!1,this.emit("drain"))))}[tc](){if(this[Tt].length===0)this[mi]&&this[Sr](null,0);else if(this[Tt].length===1)this[Ws](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],gw(this[de],t,this[yn],(e,r)=>this[Sr](e,r))}}[vt](){if(this[In]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},pf=class extends ao{[An](){let t;if(this[Ks]&&this[Jt]==="r+")try{t=it.openSync(this[Et],this[Jt],this[Ci])}catch(e){if(e?.code==="ENOENT")return this[Jt]="w",this[An]();throw e}else t=it.openSync(this[Et],this[Jt],this[Ci]);this[Cr](null,t)}[vt](){if(this[In]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,it.closeSync(t),this.emit("close")}}[Ws](t){let e=!0;try{this[Sr](null,it.writeSync(this[de],t,0,t.length,this[yn])),e=!1}finally{if(e)try{this[vt]()}catch{}}}},yw=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),bw=t=>!!t.sync&&!!t.file,Ew=t=>!t.sync&&!!t.file,vw=t=>!!t.sync&&!t.file,Sw=t=>!t.sync&&!t.file,Iw=t=>!!t.file,Aw=t=>yw.get(t)||t,Wc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Aw(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Fi=(t,e,r,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=Wc(c);if(o?.(h,d),bw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(Ew(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(vw(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(h,d)}else if(Sw(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),Cw=Tw.constants||{ZLIB_VERNUM:4736},Ot=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Cw)),Rw=Kn.concat,Mu=Object.getOwnPropertyDescriptor(Kn,"concat"),Dw=t=>t,sc=Mu?.writable===!0||Mu?.set!==void 0?t=>{Kn.concat=t?Dw:Rw}:t=>{},$n=Symbol("_superWrite"),Ms=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},oc=Symbol("flushFlag"),Kc=class extends Jn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Nu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Nu[e](t)}catch(r){throw new Ms(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ms(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Sc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Kn.alloc(0),{[oc]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[$n](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Kn.from(t,e)),this.#e)return;Sc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},sc(!0);let d;try{let h=typeof t[oc]=="number"?t[oc]:this.#r;d=this.#t._processChunk(t,h),sc(!1)}catch(h){sc(!1),this.#o(new Ms(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new Ms(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[$n](Kn.from(h));for(let x=1;x<d.length;x++)u=this[$n](d[x])}else u=this[$n](Kn.from(d));return r&&r(),u}},mf=class extends Kc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ot.Z_FINISH,t.fullFlushFlag=Ot.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Ot.Z_SYNC_FLUSH),Sc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},Pw=class extends mf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[$n](t){return this.#e?(this.#e=!1,t[9]=255,super[$n](t)):super[$n](t)}},Ow=class extends mf{constructor(t){super(t,"Unzip")}},wf=class extends Kc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ot.BROTLI_OPERATION_FLUSH,super(t,e)}},Lw=class extends wf{constructor(t){super(t,"BrotliCompress")}},Nw=class extends wf{constructor(t){super(t,"BrotliDecompress")}},_f=class extends Kc{constructor(t,e){t=t||{},t.flush=t.flush||Ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ot.ZSTD_e_end,t.fullFlushFlag=Ot.ZSTD_e_flush,super(t,e)}},Mw=class extends _f{constructor(t){super(t,"ZstdCompress")}},Bw=class extends _f{constructor(t){super(t,"ZstdDecompress")}},Fw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Uw(t,e):zw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},zw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Uw=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),r?e[i-1]=yf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=bf(o))}},Hw=t=>{let e=t[0],r=e===128?qw(t.subarray(1,t.length)):e===255?Gw(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},Gw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=yf(c):c===0?d=c:(i=!0,d=bf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},qw=t=>{for(var e=t.length,r=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(r+=o*Math.pow(256,e-i-1))}return r},yf=t=>(255^t)&255,bf=t=>(255^t)+1&255,jw={};rw(jw,{code:()=>$c,isCode:()=>$s,isName:()=>Ww,name:()=>co,normalFsTypes:()=>Ef});var $s=t=>co.has(t),Ww=t=>$c.has(t),Ef=new Set(["0","","1","2","3","4","5","6","7","D"]),co=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),$c=new Map(Array.from(co).map(t=>[t[1],t[0]])),Kw=t=>t===void 0||t<0?void 0:t,Vn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,i){Buffer.isBuffer(t)?this.decode(t,e||0,r,i):t&&this.#n(t)}decode(t,e,r,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=zn(t,e+156,1),c=Ef.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??zn(t,e,100),this.mode=d?.mode??u?.mode??bn(t,e+100,8),this.uid=d?.uid??u?.uid??bn(t,e+108,8),this.gid=d?.gid??u?.gid??bn(t,e+116,8),this.size=Kw(d?.size??u?.size??bn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??ac(t,e+136,12),this.cksum=bn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),$s(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=zn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??zn(t,e+265,32),this.gname=d?.gname??u?.gname??zn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??bn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??bn(t,e+337,8)??0,t[e+475]!==0){let x=zn(t,e+345,155);this.path=x+"/"+this.path}else{let x=zn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??ac(t,e+476,12),this.ctime=r?.ctime??i?.ctime??ac(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="size"&&Number(i)<0||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=$w(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Un(t,e,100,o)||this.needPax,this.needPax=En(t,e+100,8,this.mode)||this.needPax,this.needPax=En(t,e+108,8,this.uid)||this.needPax,this.needPax=En(t,e+116,8,this.gid)||this.needPax,this.needPax=En(t,e+124,12,this.size)||this.needPax,this.needPax=cc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Un(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Un(t,e+265,32,this.uname)||this.needPax,this.needPax=Un(t,e+297,32,this.gname)||this.needPax,this.needPax=En(t,e+329,8,this.devmaj)||this.needPax,this.needPax=En(t,e+337,8,this.devmin)||this.needPax,this.needPax=Un(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Un(t,e+345,155,c)||this.needPax:(this.needPax=Un(t,e+345,130,c)||this.needPax,this.needPax=cc(t,e+476,12,this.atime)||this.needPax,this.needPax=cc(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,En(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:co.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String($c.get(t));if($s(e)||e==="Unsupported")this.#e=e;else if($s(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},$w=(t,e)=>{let r=t,i="",o,c=_r.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=_r.dirname(r),r=_r.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=_r.join(_r.basename(i),r),i=_r.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},zn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),ac=(t,e,r)=>Vw(bn(t,e,r)),Vw=t=>t===void 0?void 0:new Date(t*1e3),bn=(t,e,r)=>Number(t[e])&128?Hw(t.subarray(e,e+r)):Zw(t,e,r),Jw=t=>isNaN(t)?void 0:t,Zw=(t,e,r)=>Jw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Xw={12:8589934591,8:2097151},En=(t,e,r,i)=>i===void 0?!1:i>Xw[r]||i<0?(Fw(i,t.subarray(e,e+r)),!0):(Yw(t,e,r,i),!1),Yw=(t,e,r,i)=>t.write(Qw(i,r),e,r,"ascii"),Qw=(t,e)=>e_(Math.floor(t).toString(8),e),e_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",cc=(t,e,r,i)=>i===void 0?!1:En(t,e,r,i.getTime()/1e3),t_=new Array(156).join("\0"),Un=(t,e,r,i)=>i===void 0?!1:(t.write(i+t_,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),no=class vf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),i=512*Math.ceil(1+r/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new Vn({path:("PaxHeader/"+n_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+o}static parse(e,r,i=!1){return new vf(r_(i_(e),r),i)}},r_=(t,e)=>e?Object.assign({},e,t):t,i_=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(s_,Object.create(null)),s_=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(c){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[c]=d;break;case"ctime":case"atime":case"mtime":t[c]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[c]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[c]=+d;break}return t},o_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=o_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),a_=class extends Jn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},lo=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},c_=1024*1024,Ic=Buffer.from([31,139]),Ac=Buffer.from([40,181,47,253]),d_=Math.max(Ic.length,Ac.length),ut=Symbol("state"),Hn=Symbol("writeEntry"),Kt=Symbol("readEntry"),dc=Symbol("nextEntry"),Bu=Symbol("processEntry"),Ct=Symbol("extendedHeader"),_i=Symbol("globalExtendedHeader"),mn=Symbol("meta"),Fu=Symbol("emitMeta"),ge=Symbol("buffer"),$t=Symbol("queue"),wn=Symbol("ended"),lc=Symbol("emittedEnd"),Gn=Symbol("emit"),Se=Symbol("unzip"),Bs=Symbol("consumeChunk"),Fs=Symbol("consumeChunkSub"),uc=Symbol("consumeBody"),zu=Symbol("consumeMeta"),Uu=Symbol("consumeHeader"),yi=Symbol("consuming"),fc=Symbol("bufferConcat"),zs=Symbol("maybeEnd"),yr=Symbol("writing"),Rt=Symbol("aborted"),Us=Symbol("onDone"),qn=Symbol("sawValidEntry"),Hs=Symbol("sawNullBlock"),Gs=Symbol("sawEOF"),Hu=Symbol("closeStream"),l_=1e3,bi=Symbol("compressedBytesRead"),hc=Symbol("decompressedBytesRead"),Gu=Symbol("checkDecompressionRatio"),u_=()=>!0,Bi=class extends kw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[$t]=[];[ge];[Kt];[Hn];[ut]="begin";[mn]="";[Ct];[_i];[wn]=!1;[Se];[Rt]=!1;[qn];[Hs]=!1;[Gs]=!1;[yr]=!1;[yi]=!1;[lc]=!1;[bi]=0;[hc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Us,()=>{(this[ut]==="begin"||this[qn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Us,t.ondone):this.on(Us,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:l_,this.maxMetaEntrySize=t.maxMetaEntrySize||c_,this.filter=typeof t.filter=="function"?t.filter:u_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[Hu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){lo(this,t,e,r)}[Uu](t,e){this[qn]===void 0&&(this[qn]=!1);let r;try{r=new Vn(t,e,this[Ct],this[_i])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Hs]?(this[Gs]=!0,this[ut]==="begin"&&(this[ut]="header"),this[Gn]("eof")):(this[Hs]=!0,this[Gn]("nullBlock"));else if(this[Hs]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[Hn]=new a_(r,this[Ct],this[_i]);if(!this[qn])if(o.remain){let c=()=>{o.invalid||(this[qn]=!0)};o.on("end",c)}else this[qn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Gn]("ignoredEntry",o),this[ut]="ignore",o.resume()):o.size>0&&(this[mn]="",o.on("data",c=>this[mn]+=c),this[ut]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Gn]("ignoredEntry",o),this[ut]=o.remain?"ignore":"header",o.resume()):(o.remain?this[ut]="body":(this[ut]="header",o.end()),this[Kt]?this[$t].push(o):(this[$t].push(o),this[dc]())))}}}[Hu](){queueMicrotask(()=>this.emit("close"))}[Bu](t){let e=!0;if(!t)this[Kt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Kt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[dc]()),e=!1);return e}[dc](){do;while(this[Bu](this[$t].shift()));if(this[$t].length===0){let t=this[Kt];!t||t.flowing||t.size===t.remain?this[yr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[uc](t,e){let r=this[Hn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[ut]="header",this[Hn]=void 0,r.end()),o.length}[zu](t,e){let r=this[Hn],i=this[uc](t,e);return!this[Hn]&&r&&this[Fu](r),i}[Gn](t,e,r){this[$t].length===0&&!this[Kt]?this.emit(t,e,r):this[$t].push([t,e,r])}[Fu](t){switch(this[Gn]("meta",this[mn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=no.parse(this[mn],this[Ct],!1);break;case"GlobalExtendedHeader":this[_i]=no.parse(this[mn],this[_i],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[mn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[mn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Rt]){if(this[Se]){let e=this[Se];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Rt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Gu](t){this[hc]+=t.length;let e=this[hc]/this[bi];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Rt])return r?.(),!1;if((this[Se]===void 0||this.brotli===void 0&&this[Se]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<d_)return this[ge]=t,r?.(),!0;for(let d=0;this[Se]===void 0&&d<Ic.length;d++)t[d]!==Ic[d]&&(this[Se]=!1);let o=!1;if(this[Se]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Ac.length;d++)if(t[d]!==Ac[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Se]===!1&&c)if(t.length<512)if(this[wn])this.brotli=!0;else return this[ge]=t,r?.(),!0;else try{new Vn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Se]===void 0||this[Se]===!1&&(this.brotli||o)){let d=this[wn];this[wn]=!1,this[Se]=this[Se]===void 0?new Ow({}):o?new Bw({}):new Nw({}),this[Se].on("data",h=>{this[Gu](h)&&this[Bs](h)}),this[Se].on("error",h=>{this[Rt]||this.abort(h)}),this[Se].on("end",()=>{this[wn]=!0,this[Bs]()}),this[yr]=!0,this[bi]+=t.length;let u=!!this[Se][d?"end":"write"](t);return this[yr]=!1,r?.(),u}}this[yr]=!0,this[Se]?(this[bi]+=t.length,this[Se].write(t)):this[Bs](t),this[yr]=!1;let i=this[$t].length>0?!1:this[Kt]?this[Kt].flowing:!0;return!i&&this[$t].length===0&&this[Kt]?.once("drain",()=>this.emit("drain")),r?.(),i}[fc](t){t&&!this[Rt]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[zs](){if(this[wn]&&!this[lc]&&!this[Rt]&&!this[yi]){this[lc]=!0;let t=this[Hn];if(t?.blockRemain){let e=this[ge]?this[ge].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ge]&&t.write(this[ge]),t.end()}this[Gn](Us)}}[Bs](t){if(this[yi]&&t)this[fc](t);else if(!t&&!this[ge])this[zs]();else if(t){if(this[yi]=!0,this[ge]){this[fc](t);let e=this[ge];this[ge]=void 0,this[Fs](e)}else this[Fs](t);for(;this[ge]&&this[ge]?.length>=512&&!this[Rt]&&!this[Gs];){let e=this[ge];this[ge]=void 0,this[Fs](e)}this[yi]=!1}(!this[ge]||this[wn])&&this[zs]()}[Fs](t){let e=0,r=t.length;for(;e+512<=r&&!this[Rt]&&!this[Gs];)switch(this[ut]){case"begin":case"header":this[Uu](t,e),e+=512;break;case"ignore":case"body":e+=this[uc](t,e);break;case"meta":e+=this[zu](t,e);break;default:throw new Error("invalid state: "+this[ut])}e<r&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[Rt]||(this[Se]?(t&&(this[bi]+=t.length,this[Se].write(t)),this[Se].end()):(this[wn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[zs]())),this}},Ri=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},f_=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},Sf=(t,e)=>{let r=new Map(e.map(c=>[Ri(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||_w(c).root||".",h;if(c===u)h=!1;else{let x=r.get(c);h=x!==void 0?x:o(ww(c),u)}return r.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&o(Ri(c)):c=>o(Ri(c))},h_=t=>{let e=new Bi(t),r=t.file,i;try{i=Ar.openSync(r,"r");let o=Ar.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Ar.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<o.size;){let h=Ar.readSync(i,u,0,c,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Ar.closeSync(i)}catch{}}},x_=(t,e)=>{let r=new Bi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Ar.stat(o,(u,h)=>{if(u)d(u);else{let x=new jc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Rr=Fi(h_,x_,t=>new Bi(t),t=>new Bi(t),(t,e)=>{e?.length&&Sf(t,e),t.noResume||f_(t)}),If=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:g_,parse:ju}=p_,Vc=t=>{let e="",r=ju(t);for(;g_(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=ju(t)}return[e,t]},uo=["|","<",">","?",":"],Jc=uo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),m_=new Map(uo.map((t,e)=>[t,Jc[e]])),w_=new Map(Jc.map((t,e)=>[t,uo[e]])),Wu=t=>uo.reduce((e,r)=>e.split(r).join(m_.get(r)),t),__=t=>Jc.reduce((e,r)=>e.split(r).join(w_.get(r)),t),Af=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Ri(e)+"/"+t):Q(t),y_=16*1024*1024,Ku=Symbol("process"),$u=Symbol("file"),Vu=Symbol("directory"),kc=Symbol("symlink"),Ju=Symbol("hardlink"),Ei=Symbol("header"),Vs=Symbol("read"),Tc=Symbol("lstat"),Js=Symbol("onlstat"),Cc=Symbol("onread"),Rc=Symbol("onreadlink"),Dc=Symbol("openfile"),Pc=Symbol("onopenfile"),vn=Symbol("close"),io=Symbol("mode"),Oc=Symbol("awaitDrain"),xc=Symbol("ondrain"),Pt=Symbol("prefix"),kf=class extends Jn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Wc(e);super(),this.path=Q(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||y_,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Q(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Q(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Vc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=__(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(r.absolute||qu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[Js](o):this[Tc]()}warn(t,e,r={}){return lo(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Tc](){Dt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Js](e)})}[Js](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=v_(t),this.emit("stat",t),this[Ku]()}[Ku](){switch(this.type){case"File":return this[$u]();case"Directory":return this[Vu]();case"SymbolicLink":return this[kc]();default:return this.end()}}[io](t){return If(t,this.type==="Directory",this.portable)}[Pt](t){return Af(t,this.prefix)}[Ei](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Vn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[io](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new no({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Vu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ei](),this.end()}[kc](){Dt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Rc](e)})}[Rc](t){this.linkpath=Q(t),this[Ei](),this.end()}[Ju](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(qu.relative(this.cwd,t)),this.stat.size=0,this[Ei](),this.end()}[$u](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[Ju](e);this.linkCache.set(t,this.absolute)}if(this[Ei](),this.stat.size===0)return this.end();this[Dc]()}[Dc](){Dt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Pc](e)})}[Pc](t){if(this.fd=t,this.#e)return this[vn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Vs]()}[Vs](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Dt.read(t,e,r,i,o,(c,d)=>{if(c)return this[vn](()=>this.emit("error",c));this[Cc](d)})}[vn](t=()=>{}){this.fd!==void 0&&Dt.close(this.fd,t)}[Cc](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[vn](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[vn](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[xc]():this[Oc](()=>this[xc]())}[Oc](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[xc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[vn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Vs]()}},b_=class extends kf{sync=!0;[Tc](){this[Js](Dt.lstatSync(this.absolute))}[kc](){this[Rc](Dt.readlinkSync(this.absolute))}[Dc](){this[Pc](Dt.openSync(this.absolute,"r"))}[Vs](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let d=Dt.readSync(e,r,i,o,c);this[Cc](d),t=!1}finally{if(t)try{this[vn](()=>{})}catch{}}}[Oc](t){t()}[vn](t=()=>{}){this.fd!==void 0&&Dt.closeSync(this.fd),t()}},E_=class extends Jn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return lo(this,t,e,r)}constructor(t,e={}){let r=Wc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[io](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Vc(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Vn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new no({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Pt](t){return Af(t,this.prefix)}[io](t){return If(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},v_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",S_=class kr{tail;head;length=0;static create(e=[]){return new kr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)A_(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)k_(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new kr;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new kr;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new kr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new kr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<r;d++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=I_(this,o,d);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function I_(t,e,r){let i=e,o=e?e.next:t.head,c=new Zc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function A_(t,e){t.tail=new Zc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function k_(t,e){t.head=new Zc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Zc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Xu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Yu=Buffer.alloc(1024),Zs=Symbol("onStat"),vi=Symbol("ended"),yt=Symbol("queue"),Si=Symbol("pendingLinks"),_n=Symbol("current"),jn=Symbol("process"),Ii=Symbol("processing"),qs=Symbol("processJob"),bt=Symbol("jobs"),pc=Symbol("jobDone"),Xs=Symbol("addFSEntry"),Qu=Symbol("addTarEntry"),Lc=Symbol("stat"),Nc=Symbol("readdir"),Ys=Symbol("onreaddir"),Qs=Symbol("pipe"),ef=Symbol("entry"),gc=Symbol("entryOpt"),eo=Symbol("writeEntryClass"),Tf=Symbol("write"),mc=Symbol("ondrain"),fo=class extends Jn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[eo];onWriteEntry;[yt];[Si]=new Map;[bt]=0;[Ii]=!1;[vi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[eo]=kf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new Pw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Lw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Mw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[mc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[mc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[yt]=new S_,this[bt]=0,this.jobs=Number(t.jobs)||4,this[Ii]=!1,this[vi]=!1}[Tf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[vi]=!0,this[jn](),r&&r(),this}write(t){if(this[vi])throw new Error("write after end");return typeof t=="string"?this[Xs](t):this[Qu](t),this.flowing}[Qu](t){let e=Q(Zu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Xu(t.path,e);r.entry=new E_(t,this[gc](r)),r.entry.on("end",()=>this[pc](r)),this[bt]+=1,this[yt].push(r)}this[jn]()}[Xs](t){let e=Q(Zu.resolve(this.cwd,t));this[yt].push(new Xu(t,e)),this[jn]()}[Lc](t){t.pending=!0,this[bt]+=1;let e=this.follow?"stat":"lstat";ro[e](t.absolute,(r,i)=>{t.pending=!1,this[bt]-=1,r?this.emit("error",r):this[Zs](t,i)})}[Zs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[_n])this[qs](t);else{let r=`${e.dev}:${e.ino}`,i=this[Si].get(r);i?i.push(t):this[Si].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[jn]()}[Nc](t){t.pending=!0,this[bt]+=1,ro.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[bt]-=1,e)return this.emit("error",e);this[Ys](t,r)})}[Ys](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[jn]()}[jn](){if(!this[Ii]){this[Ii]=!0;for(let t=this[yt].head;t&&this[bt]<this.jobs;t=t.next)if(this[qs](t.value),t.value.ignore){let e=t.next;this[yt].removeNode(t),t.next=e}this[Ii]=!1,this[vi]&&this[yt].length===0&&this[bt]===0&&(this.zip?this.zip.end(Yu):(super.write(Yu),super.end()))}}get[_n](){return this[yt]&&this[yt].head&&this[yt].head.value}[pc](t){this[yt].shift(),this[bt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[Si].get(r);if(i){this[Si].delete(r);for(let o of i)o.pending=!1,this[qs](o)}}this[jn]()}[qs](t){if(t.pending&&t.pendingLink&&t===this[_n]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[_n]&&!t.piped&&this[Qs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Zs](t,e):this[Lc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Ys](t,e):this[Nc](t),!t.readdir)return}if(t.entry=this[ef](t),!t.entry){t.ignore=!0;return}t===this[_n]&&!t.piped&&this[Qs](t)}}}[gc](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[ef](t){this[bt]+=1;try{return new this[eo](t.path,this[gc](t)).on("end",()=>this[pc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[mc](){this[_n]&&this[_n].entry&&this[_n].entry.resume()}[Qs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Xs](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){lo(this,t,e,r)}},Xc=class extends fo{sync=!0;constructor(t){super(t),this[eo]=b_}pause(){}resume(){}[Lc](t){let e=this.follow?"statSync":"lstatSync";this[Zs](t,ro[e](t.absolute))}[Nc](t){this[Ys](t,ro.readdirSync(t.absolute))}[Qs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Xs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[Tf](i)})}},T_=(t,e)=>{let r=new Xc(t),i=new pf(t.file,{mode:t.mode||438});r.pipe(i),Cf(r,e)},C_=(t,e)=>{let r=new fo(t),i=new ao(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,d)=>{i.on("error",d),i.on("close",c),r.on("error",d)});return Rf(r,e).catch(c=>r.emit("error",c)),o},Cf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Rr({file:gf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},Rf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Rr({file:gf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},R_=(t,e)=>{let r=new Xc(t);return Cf(r,e),r},D_=(t,e)=>{let r=new fo(t);return Rf(r,e).catch(i=>r.emit("error",i)),r},M2=Fi(T_,C_,R_,D_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),O_=process.env.__FAKE_PLATFORM__||process.platform,Lf=O_==="win32",{O_CREAT:Nf,O_NOFOLLOW:tf,O_TRUNC:Mf,O_WRONLY:Bf}=Of.constants,Ff=Number(process.env.__FAKE_FS_O_FILENAME__)||Of.constants.UV_FS_O_FILEMAP||0,L_=Lf&&!!Ff,N_=512*1024,M_=Ff|Mf|Nf|Bf,nf=!Lf&&typeof tf=="number"?tf|Mf|Nf|Bf:null,zf=nf!==null?()=>nf:L_?t=>t<N_?M_:"w":()=>"w",Mc=(t,e,r)=>{try{return ho.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},so=(t,e,r,i)=>{ho.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},B_=(t,e,r,i,o)=>{if(e.isDirectory())Uf(Di.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Di.resolve(t,e.name);so(d,r,i,o)});else{let c=Di.resolve(t,e.name);so(c,r,i,o)}},Uf=(t,e,r,i)=>{ho.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return so(t,e,r,i);let d=c.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return so(t,e,r,i)}};for(let x of c)B_(t,x,e,r,h)})},F_=(t,e,r,i)=>{e.isDirectory()&&Hf(Di.resolve(t,e.name),r,i),Mc(Di.resolve(t,e.name),r,i)},Hf=(t,e,r)=>{let i;try{i=ho.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Mc(t,e,r);throw c}for(let o of i)F_(t,o,e,r);return Mc(t,e,r)},Gf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},xo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},U_=(t,e)=>{ct.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Gf(t,r?.code||"ENOTDIR")),e(r)})},H_=(t,e,r)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,m=e.unlink,w=Q(e.cwd),v=(E,S)=>{E?r(E):S&&h?Uf(S,d,u,I=>v(I)):c?ct.chmod(t,o,r):r()};if(t===w)return U_(t,v);if(x)return z_.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let _=Q(oo.relative(w,t)).split("/");Bc(w,_,o,m,w,void 0,v)},Bc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=Q(oo.resolve(t+"/"+u));ct.mkdir(h,r,qf(h,e,r,i,o,c,d))},qf=(t,e,r,i,o,c,d)=>u=>{u?ct.lstat(t,(h,x)=>{if(h)h.path=h.path&&Q(h.path),d(h);else if(x.isDirectory())Bc(t,e,r,i,o,c,d);else if(i)ct.unlink(t,m=>{if(m)return d(m);ct.mkdir(t,r,qf(t,e,r,i,o,c,d))});else{if(x.isSymbolicLink())return d(new xo(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,Bc(t,e,r,i,o,c,d))},G_=t=>{let e=!1,r;try{e=ct.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Gf(t,r??"ENOTDIR")}},q_=(t,e)=>{t=Q(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,m=Q(e.cwd),w=E=>{E&&u&&Hf(E,c,d),o&&ct.chmodSync(t,i)};if(t===m)return G_(m),w();if(h)return w(ct.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=Q(oo.relative(m,t)).split("/"),_;for(let E=v.shift(),S=m;E&&(S+="/"+E);E=v.shift()){S=Q(oo.resolve(S));try{ct.mkdirSync(S,i),_=_||S}catch{let I=ct.lstatSync(S);if(I.isDirectory())continue;if(x){ct.unlinkSync(S),ct.mkdirSync(S,i),_=_||S;continue}else if(I.isSymbolicLink())return new xo(S,S+"/"+v.join("/"))}}return w(_)},wc=Object.create(null),rf=1e4,br=new Set,j_=t=>{br.has(t)?br.delete(t):wc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),br.add(t);let e=wc[t],r=br.size-rf;if(r>rf/10){for(let i of br)if(br.delete(i),delete wc[i],--r<=0)break}return e},W_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,K_=W_==="win32",$_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=jf(i,r)),e.push(r||"/"),e},[]),V_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=K_?["win32 parallelization disabled"]:t.map(i=>Ri(jf(j_(i))));let r=new Set(t.map(i=>$_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let h of u)o.add(h)}for(let c of i){let d=this.#e.get(c),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(c);continue}else if(u.size===1){d.shift();let h=d[0];typeof h=="function"&&o.add(h)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},J_=()=>process.umask(),sf=Symbol("onEntry"),Fc=Symbol("checkFs"),of=Symbol("checkFs2"),zc=Symbol("isReusable"),ft=Symbol("makeFs"),Uc=Symbol("file"),Hc=Symbol("directory"),to=Symbol("link"),af=Symbol("symlink"),cf=Symbol("hardlink"),Ti=Symbol("ensureNoSymlink"),df=Symbol("unsupported"),lf=Symbol("checkPath"),_c=Symbol("stripAbsolutePath"),Sn=Symbol("mkdir"),qe=Symbol("onError"),js=Symbol("pending"),uf=Symbol("pend"),Er=Symbol("unpend"),yc=Symbol("ended"),bc=Symbol("maybeClose"),Gc=Symbol("skip"),Pi=Symbol("doChown"),Oi=Symbol("uid"),Li=Symbol("gid"),Ni=Symbol("checkedCwd"),Z_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Mi=Z_==="win32",X_=1024,Y_=(t,e)=>{if(!Mi)return se.unlink(t,e);let r=t+".DELETE."+Pf(16).toString("hex");se.rename(t,r,i=>{if(i)return e(i);se.unlink(r,e)})},Q_=t=>{if(!Mi)return se.unlinkSync(t);let e=t+".DELETE."+Pf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},ff=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Yc=class extends Bi{[yc]=!1;[Ni]=!1;[js]=0;reservations=new V_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[yc]=!0,this[bc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:X_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Mi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Ne.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:J_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[sf](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[bc](){this[yc]&&this[js]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[_c](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Vc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Mi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Ne.posix.dirname(t.path),h=Ne.posix.normalize(Ne.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[lf](t){let e=Q(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[_c](t,"path")||!this[_c](t,"linkpath"))return!1;if(t.absolute=Ne.isAbsolute(t.path)?Q(Ne.resolve(t.path)):Q(Ne.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Ne.win32.parse(String(t.absolute));t.absolute=i+Wu(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Wu(t.path.slice(o.length))}return!0}[sf](t){if(!this[lf](t))return t.resume();switch(P_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Fc](t);default:return this[df](t)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Er](),e.resume())}[Sn](t,e,r){H_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Pi](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Oi](t){return ff(this.uid,t.uid,this.processUid)}[Li](t){return ff(this.gid,t.gid,this.processGid)}[Uc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new ao(String(t.absolute),{flags:zf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let o=1,c=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[qe](u,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,h=>{h?this[qe](h,t):this[Er](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,m=t.mtime;se.futimes(h,x,m,w=>w?se.utimes(u,x,m,v=>c(v&&w)):c())}if(typeof h=="number"&&this[Pi](t)){o++;let x=this[Oi](t),m=this[Li](t);typeof x=="number"&&typeof m=="number"&&se.fchown(h,x,m,w=>w?se.chown(u,x,m,v=>c(v&&w)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[qe](u,t),e()}),t.pipe(d)),d.pipe(i)}[Hc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Sn](String(t.absolute),r,i=>{if(i){this[qe](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[Er](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Pi](t)&&(o++,se.chown(String(t.absolute),Number(this[Oi](t)),Number(this[Li](t)),c)),c()})}[df](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[af](t,e){let r=Q(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ti](t,this.cwd,r,()=>this[to](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[cf](t,e){let r=Q(Ne.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Ti](t,this.cwd,i,()=>this[to](t,r,"link",e),o=>{this[qe](o,t),e()})}[Ti](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Ne.resolve(e,c);se.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new xo(d,Ne.resolve(d,r.join("/"))));this[Ti](t,d,r,i,o)})}[uf](){this[js]++}[Er](){this[js]--,this[bc]()}[Gc](t){this[Er](),t.resume()}[zc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Mi}[Fc](t){this[uf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[of](t,r))}[of](t,e){let r=d=>{e(d)},i=()=>{this[Sn](this.cwd,this.dmode,d=>{if(d){this[qe](d,t),r();return}this[Ni]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Ne.dirname(String(t.absolute)));if(d!==this.cwd)return this[Sn](d,this.dmode,u=>{if(u){this[qe](u,t),r();return}c()})}c()},c=()=>{se.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Gc](t),r();return}if(d||this[zc](t,u))return this[ft](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=m=>this[ft](m??null,t,r);return h?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),h=>this[ft](h??null,t,r))}if(t.absolute===this.cwd)return this[ft](null,t,r);Y_(String(t.absolute),h=>this[ft](h??null,t,r))})};this[Ni]?o():i()}[ft](t,e,r){if(t){this[qe](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Uc](e,r);case"Link":return this[cf](e,r);case"SymbolicLink":return this[af](e,r);case"Directory":case"GNUDumpDir":return this[Hc](e,r)}}[to](t,e,r,i){se[r](e,String(t.absolute),o=>{o?this[qe](o,t):(this[Er](),t.resume()),i()})}},Ai=t=>{try{return[null,t()]}catch(e){return[e,null]}},Wf=class extends Yc{sync=!0;[ft](t,e){return super[ft](t,e,()=>{})}[Fc](t){if(!this[Ni]){let o=this[Sn](this.cwd,this.dmode);if(o)return this[qe](o,t);this[Ni]=!0}if(t.absolute!==this.cwd){let o=Q(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[Sn](o,this.dmode);if(c)return this[qe](c,t)}}let[e,r]=Ai(()=>se.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Gc](t);if(e||this[zc](t,r))return this[ft](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?Ai(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ft](d,t)}let[o]=Ai(()=>se.rmdirSync(String(t.absolute)));this[ft](o,t)}let[i]=t.absolute===this.cwd?[]:Ai(()=>Q_(String(t.absolute)));this[ft](i,t)}[Uc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(o)}catch(h){u=h}(d||u)&&this[qe](d||u,t),e()},o;try{o=se.openSync(String(t.absolute),zf(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[qe](d,t)),t.pipe(c)),c.on("data",d=>{try{se.writeSync(o,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{se.futimesSync(o,u,h)}catch(x){try{se.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Pi](t)){let u=this[Oi](t),h=this[Li](t);try{se.fchownSync(o,Number(u),Number(h))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[Hc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Sn](String(t.absolute),r);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Pi](t))try{se.chownSync(String(t.absolute),Number(this[Oi](t)),Number(this[Li](t)))}catch{}e(),t.resume()}[Sn](t,e){try{return q_(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Ti](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Ne.resolve(c,d);let[u,h]=Ai(()=>se.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new xo(c,Ne.resolve(e,r.join("/"))))}i()}[to](t,e,r,i){let o=`${r}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[qe](c,t)}}},ey=t=>{let e=new Wf(t),r=t.file,i=Df.statSync(r),o=t.maxReadSize||16*1024*1024;new mw(r,{readSize:o,size:i.size}).pipe(e)},ty=(t,e)=>{let r=new Yc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),Df.stat(o,(u,h)=>{if(u)d(u);else{let x=new jc(o,{readSize:i,size:h.size});x.on("error",d),x.pipe(r)}})})},Kf=Fi(ey,ty,t=>new Wf(t),t=>new Yc(t),(t,e)=>{e?.length&&Sf(t,e)}),ny=(t,e)=>{let r=new Xc(t),i=!0,o,c;try{try{o=at.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=at.openSync(t.file,"w+");else throw h}let d=at.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,w=0;m<512;m+=w){if(w=at.readSync(o,u,m,u.length-m,c+m),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let h=new Vn(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,ry(t,r,c,o,e)}finally{if(i)try{at.closeSync(o)}catch{}}},ry=(t,e,r,i,o)=>{let c=new pf(t.file,{fd:i,start:r});e.pipe(c),sy(e,o)},iy=(t,e)=>{e=Array.from(e);let r=new fo(t),i=(o,c,d)=>{let u=(v,_)=>{v?at.close(o,E=>d(v)):d(null,_)},h=0;if(c===0)return u(null,0);let x=0,m=Buffer.alloc(512),w=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return at.read(o,m,x,m.length-x,h+x,w);if(h===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let E=new Vn(m);if(!E.cksumValid)return u(null,h);let S=512*Math.ceil((E.size??0)/512);if(h+S+512>c||(h+=S+512,h>=c))return u(null,h);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,at.read(o,m,0,512,h,w)};at.read(o,m,0,512,h,w)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",at.open(t.file,d,u);if(h||!x)return c(h);at.fstat(x,(m,w)=>{if(m)return at.close(x,()=>c(m));i(x,w.size,(v,_)=>{if(v)return c(v);let E=new ao(t.file,{fd:x,start:_});r.pipe(E),E.on("error",c),E.on("close",o),oy(r,e)})})};at.open(t.file,d,u)})},sy=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Rr({file:$f.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},oy=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Rr({file:$f.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},ki=Fi(ny,iy,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Iw(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.zstd||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")}),X2=Fi(ki.syncFile,ki.asyncFile,ki.syncNoFile,ki.asyncNoFile,(t,e=[])=>{ki.validate?.(t,e),ay(t)}),ay=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,i)=>e(r,i)&&!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};xn();var ht={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function po(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Vf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function go(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Jf(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function Zf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Xf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Zn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Zt();Ke();re();Te();Ke();function Dr(t,e){if(po(t)!=="cloud")throw new A("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function zi(t){return t.startsWith("http://")||t.startsWith("https://")}function Pr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as Gk}from"node:fs";import{dirname as jk,join as Wk}from"node:path";import{fileURLToPath as $k}from"node:url";var Lt="0.2.7-beta.3";Ke();re();var mo="1008033",t0="1289";var n0="pbbp2",r0="https://www.coze.cn",i0="/api/coze_claw/resource/get_frontier_key",py="https://www.coze.cn",gy="wss://frontier.coze.cn";function Or(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??py}function s0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??gy}function kn(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Hi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Ui=G("handshake");async function Qc(t){let e=Or(t.endpoint),r=t.timeoutMs??1e4,i=`${Pr(e)}${i0}?aid=${encodeURIComponent(mo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...kn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Ui.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),h=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${E.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${h}`);let w=m.data??{},v=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!v||!_){let E=JSON.stringify(m).slice(0,500);throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${E}`)}return Ui.info("handshake ok",{remoteDeviceId:_,logid:h,traceId:x}),{accessKey:v,deviceId:_}}catch(u){if(u instanceof A)throw Ui.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Ui.warn("handshake timeout",{base:e,timeoutMs:r}),new A("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let h=u.cause;throw Ui.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new A("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var td=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Nt="auto",ed=15e4,o0=32e3;function c0(t){return{model:nd(t.model)??Nt,...t.modelToken?{modelToken:t.modelToken}:{}}}function d0(t){return!t||t===Nt}var my=new Set(["auto","\u81EA\u52A8"]);function nd(t){let e=t?.trim();if(e)return my.has(e.toLowerCase())?Nt:e}function l0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=td,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Nt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else d0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function u0(t,e,r,i){let o={};if(t.modelToken?o.model=t.model||Nt:d0(t.model)||(o.model=t.model),t.modelToken){let c={name:"coze",base_url:`${td}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=rd(e,r,i);Object.keys(d).length>0&&(c.http_headers=d),o.model_providers={coze:c},o.model_context_window=t.modelInfo?.contextWindow??ed}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function f0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function rd(t,e,r){let{ttEnv:i,usePpe:o}=Hi(t),c={};return i&&(c["x-tt-env"]=i),o&&(c["x-use-ppe"]=o),e&&(c["x-mock-scenario"]=e),r&&(c["x-coze-request-scene"]=r),c}function h0(t,e,r,i){if(!t.modelToken)return{};let o=rd(e,r,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
92
+ `)}}function id(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function sd(t){return t.model||Nt}function a0(t,e,r,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:r,maxTokens:i,api:"openai-completions"}}function x0(t,e,r,i,o){if(!t.modelToken)return null;let c=sd(t),d=rd(e,r,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let h=[a0(c,u,t.modelInfo?.contextWindow??ed,t.modelInfo?.maxOutput??o0)],x=new Set([c]);for(let w of i??[])!w||x.has(w)||(x.add(w),h.push(a0(w,["text"],ed,o0)));let m={baseUrl:`${td}/v1`,api:"openai-completions",apiKey:t.modelToken,models:h};return Object.keys(d).length>0&&(m.headers=d),m}var he=G("agent-handlers"),g0=5*1024*1024,Ey=1,vy=6,Sy=new Set(["node_modules",".git",".coze","dist","build",".next"]),Iy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ay=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,ky=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Ty(t){let e=t?.trim();return e?ky.test(e)||Ay.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Cy(t){return new Promise((e,r)=>{let i=st("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=d=>{o||(o=!0,d?r(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var _o=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Zn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Fe(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let x=xe(o,h.relPath,"SKILL.md");await fd(x).then(w=>w.isFile()).catch(()=>!1)&&(d.push(Ly(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",x=await k0(r,o,h),m=await T0(r,h);for(let w of[...x,...m])u.has(w.relPath)||(u.add(w.relPath),d.push(w.skill))}return{skills:d}}async addSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((h,x)=>[h.skillId,x])),u=[];for(let h of o){let x=await yo({agentId:r,workspace:i.workspace,framework:i.framework,skill:h});bo(c,d,x),u.push(h)}return await ui(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Zn(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!o.has(u.skillId)){d.push(u);continue}let h=xe(i.workspace,u.relPath);await cd(h,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await ui(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Zn(e._meta);if(!e.skillName)throw new A("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");he.info("_agent/publishSkill start",{agentId:r,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(r),o=i?.workspace??Fe(r).workspace,c=i?.framework??"claude-code",d=e.isGlobal??!1,u=await Dy(r,o,c,e.skillName,d);if(!u){let R=d?"global":"workspace";throw new A("SKILL_NOT_FOUND",`skill not found in ${R}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:m}=u,w=xe(h,"SKILL.md"),v=new xd.default;v.addLocalFolder(h,m);let _=v.toBuffer();if(_.length>m0)throw new A("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${m0}`);let E=await wo(w,{encoding:"utf8"}).then(R=>I0(R).description).catch(()=>{}),S={};this.opts.publishSkillToMarketplace?S=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...E?{description:E}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):he.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let I=S.version??"v1.0",k=S.skillId??e.skillId??S0(r,x);if(i&&!d){let R=i.skills??[],b=R.find(D=>D.relPath===x);b?(b.version=I,b.skillId=k):R.push({skillId:k,skillName:e.skillName,relPath:x,version:I,installedAt:Date.now(),...E?{description:E}:{}}),await ui(r,R)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:k,version:I}),{ok:!0,skillId:k,version:I}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let h=c.downstream;c.downstream=void 0,he.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),h.stop(r).catch(x=>he.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return he.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Ce(r);if(!i)throw new A("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return he.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await xr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw he.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new A("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await ze(i),he.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new A("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Ce(r))throw new A("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&zi(e.registry)&&o.push(`--registry=${e.registry}`);let c=Ty(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&Iy.test(d)&&o.push("--env",d);let u=await Cy(o);return he.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new A("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Ce(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await ze(i),he.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(he.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new A("IPC_BAD_REQUEST",`${ht.DELETE}: missing agentId`);let i=await Ce(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let d=Fe(r);return c==="cloud"?await cd(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await ze(i)),he.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Dr(e._meta,"_agent/switchModel"),!e.agentId)throw new A("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=nd(e.model)??Nt,i=await Ce(e.agentId);if(!i)throw new A("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await ze(i),he.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return he.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let c=o.model;o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,c).catch(u=>he.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(u)}));let d=[];for(let[u,h]of o.allSessionQueues())d.push(h.enqueue(async()=>{let x=o.sessions.get(u);x?.downstream&&(await x.downstream.stop(`switchModel: ${r}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(d),he.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:d.length}),{ok:!0}}async resetAgent(e){if(Dr(e._meta,ht.RESET),!e.agentId)throw new A("IPC_BAD_REQUEST",`${ht.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ht.RESET),await this.runDetailSync(e.agentId,ht.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),he.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await li(e,o)}async clearPersistedAcpSessionIds(e){let r=await Ce(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await ze(r)}async repairAgent(e){if(Dr(e._meta,ht.REPAIR),!e.agentId)throw new A("IPC_BAD_REQUEST",`${ht.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new A("IPC_BAD_REQUEST",`${ht.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){he.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ht.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){he.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){he.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Dr(e._meta,"_agent/getFileTree");let r=e._meta,i=Zn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await od(d).catch(()=>null);if(!u)throw new A("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await di(d,o))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=Ky(e.depth);return u.isDirectory()?{tree:await Wy(o,d,c,h)}:{tree:[{name:$y(c),path:D0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Dr(e._meta,"_agent/getFileContent");let r=Zn(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new A("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await od(o).catch(()=>null);if(!c||!c.isFile())throw new A("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await di(o,i))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>g0)throw new A("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${g0})`);let d=await wo(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:c.size}:{content:d.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await Ce(e).catch(()=>null))?.workspace??Fe(e).workspace}safeJoin(e,r){let i=ld(e,r||"."),o=hd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${_0}`))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Ce(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new A("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function E0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new A("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new A("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function pd(t){return t==="claude-code"?xe(".claude","skills"):xe(".agents","skills")}function v0(t){let e=_y();return t==="claude-code"?[xe(e,".claude","skills")]:t==="codex"?[xe(e,".agents","skills"),xe(e,".codex","skills")]:[xe(e,".agents","skills"),xe(e,".openclaw","skills")]}async function Ry(t,e,r,i){let o=async c=>fd(xe(c,"SKILL.md")).then(d=>d.isFile()).catch(()=>!1);if(!i){let c=xe(pd(e),r),d=xe(t,c);return await o(d)?{absDir:d,relPath:c}:null}for(let c of v0(e)){let d=xe(c,r);if(await o(d))return{absDir:d,relPath:d}}return null}async function Dy(t,e,r,i,o){let c=E0(i),d=await Ry(e,r,c,o);if(d)return{...d,dirName:c};let h=(o?await T0(t,r):await k0(t,e,r)).filter(w=>w.skill.skillName===i);if(h.length>1)throw new A("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${h.map(w=>p0(w.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=h[0];return x?{absDir:o?x.relPath:xe(e,x.relPath),relPath:x.relPath,dirName:p0(x.relPath)}:null}function S0(t,e){return(wy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function I0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
93
  ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
102
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function I0(t,e,r,i){let o=await m0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await ud(fe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let x=d.name,h=fe(r,x),m=fe(e,x,"SKILL.md"),w=await wo(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let I=S0(w);c.push({relPath:h,skill:{skillId:v0(t,h),skillName:I.name||x,...I.description?{description:I.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function A0(t,e,r,i){let{base:o,subdir:c}=Lr(r,t,e,i);return I0(t,fe(o,c),c,!1)}async function k0(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 Fy=3e4,zy=50*1024*1024,g0=10*1024*1024,Or=3e4;async function yo(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:m}=Lr(i,e,r,c),w=fe(m,x),I=fe(h,w);if(await od(I,{recursive:!0}),d){let S=Buffer.from(o.content,"utf8");Hi(S.length),await cd(fe(I,"SKILL.md"),S,"utf8")}else{let S=await Gy(o.downloadUrl);jy(S)?await Vy(S,I):Wy(S)?await Ky(S,I):await cd(fe(I,"SKILL.md"),S.toString("utf8"),"utf8")}let b={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 ne.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:w,source:d?"content":"downloadUrl"}),b}function bo(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function Uy(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 Hy(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 T0(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=Lt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((w,I)=>[w.skillId,I])),u=c.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"noop",count:0};let x=0,h=0,{base:m}=Lr(r.framework,t,r.workspace,e);ne.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:r.framework,prev:o,current:i,skillBase:m,builtinCount:u.length,builtinRelPaths:u.map(w=>w.relPath)});for(let w of u)try{let I=fe(m,w.relPath);ne.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:I}),await ad(I,{recursive:!0,force:!0});let b=await yo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Hy(w),...e?{paths:e}:{}});bo(c,d,b),x+=1}catch(I){h+=1,ne.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(I)})}return r.skills=c,h===0&&(r.skillsRefreshedForVersion=i),await ze(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 Gy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Hi(e);let r=qy(t);return Hi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await wo(e);return Hi(r.length),r}if(Ni(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Fy);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 Hi(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 Hi(t){if(t>zy)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function qy(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 jy(t){return t.length>=2&&t[0]===31&&t[1]===139}function Wy(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 Ky(t,e){let r,i;try{r=new xd.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||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(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=$y(i),c=dd(e);for(let d of i){if(ld(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let x=dd(e,u),h=fd(c,x);if(h.startsWith("..")||h==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await od(x,{recursive:!0});continue}await od(Iy(x),{recursive:!0});let m;try{m=d.getData()}catch(w){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await cd(x,m)}}function $y(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 Vy(t,e){await Yy(t);let r=Uf({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 y0(_0.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 Yy(t){let e=[],r=Cr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(h=>h==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Or}ms)`))},Or);try{await y0(_0.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 Jy=5e3;async function Xy(t,e,r,i){return C0(t,e,r,i,{count:0})}async function C0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await m0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(Cy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=Jy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let x=fe(e,u.name),h=Ay(fe(r,u.name)),m=null;try{m=await sd(x)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let w={name:u.name,path:P0(fd(t,x)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await C0(t,x,h,i-1,o)),d.push(w)}return d.sort((u,x)=>u.isDir!==x.isDir?u.isDir?-1:1:u.name.localeCompare(x.name)),d}function Zy(t){return!t||t<=0?ky:Math.min(t,Ty)}function Qy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function P0(t){return t.split(w0).join("/")}te();var In=j("agent-health-reporter"),eb=1e4,tb=3,Gi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??eb,this.livenessFailureThreshold=e.livenessFailureThreshold??tb}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),In.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),In.info("heartbeat stopped"))}async tick(){if(this.inFlight){In.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,In.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let d of this.opts.core.agents.values()){let u=nb(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:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,In.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(In.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){In.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){In.warn("onTickEnd hook failed",{err:String(r)})}}};function nb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}qt();import{mkdir as md,rm as eE,stat as tE}from"node:fs/promises";import{homedir as nE}from"node:os";import{join as cx}from"node:path";ln();import{existsSync as xb}from"node:fs";import{release as hb}from"node:os";import{basename as pb,isAbsolute as gb}from"node:path";function qi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Nr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Mr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function An(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ke();var Eo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function R0(t){return"method"in t&&"id"in t&&t.id!==void 0}function D0(t){return"method"in t&&!("id"in t)}function vo(t){return!("method"in t)&&"id"in t}var rb={AGENT_NOT_FOUND:X.AGENT_NOT_FOUND,AGENT_BUSY:X.AGENT_BUSY,AGENT_DISCONNECTED:X.AGENT_DISCONNECTED,AGENT_TIMEOUT:X.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:X.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:X.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:X.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:X.INTERNAL_ERROR,BRIDGE_INTERNAL:X.INTERNAL_ERROR,IPC_AUTH_FAILED:X.INTERNAL_ERROR,IPC_BAD_REQUEST:X.INVALID_REQUEST,METHOD_NOT_FOUND:X.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:X.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:X.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:X.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:X.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:X.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:X.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:X.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:X.FILE_TOO_LARGE,UNSUPPORTED_MIME:X.UNSUPPORTED_MIME,UPLOAD_FAILED:X.UPLOAD_FAILED,UPSTREAM_NOT_READY:X.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:X.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:X.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:X.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:X.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:X.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:X.SKILL_ZIP_TOO_LARGE};function ib(t){if(t!=null)return t instanceof Error?{name:t.name,message:ji(t.message)}:typeof t=="string"?ji(t):typeof t=="object"?ob(t):t}var sb=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function ji(t){let e=t;for(let[r,i]of sb)e=e.replace(r,i);return e}function ob(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=ji(i):e[r]=i;return e}function Wi(t){if(t instanceof T){let e=ib(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:rb[t.code]??X.INTERNAL_ERROR,message:ji(t.message),data:r}}return{code:X.INTERNAL_ERROR,message:ji(t instanceof Error?t.message:String(t))}}function O0(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 N0(t){return`${JSON.stringify(t)}
103
- `}var L0=10*1024*1024,So=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>L0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${L0} 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 B0={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission","session/set_mode":"session.setMode",initialize:"initialize"},TT=Object.fromEntries(Object.entries(B0).map(([t,e])=>[e,t])),ab={"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=B0[e]??cb(e),o=ab[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(x=>M0(r?.[x]??"")),u=db(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>M0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function cb(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function M0(t){return t.replace(/[:_\s]+/g,"-")}function db(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Jt();ar();Ke();te();Ce();import{execFileSync as lb,spawnSync as ub}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"),ub("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var hd=new Set;function F0(t){typeof t=="number"&&t>0&&hd.add(t)}function z0(t){typeof t=="number"&&hd.delete(t)}function U0(){for(let t of hd)$i(t,"SIGKILL")}var Fr="coze-bridge-daemon";function H0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return lb("pgrep",["-U",String(o),"-f",Fr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
105
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function G0(t,e){if(t.length===0)return;let r=e?.killFn??$i,i=e?.isAliveFn??Ki,o=e?.sleepFn??(u=>new Promise(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 fb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function q0(t,e){if(!e)return null;for(let r of fb)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function j0(t,e){return q0(t,e)}function W0(t,e){return q0(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 K0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let h=t.suspendedMs+o,m=r-t.startedAt-h;return{action:"suspend",suspendedDeltaMs:o,rearmMs:zr(m,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:zr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:zr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:zr(c,!1,e)}}var $0=Ye("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),mb=200,wb=40,_b=Ye("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),yb=Ye("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),bb=Ye("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Eb=Ye("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),vb=Ye("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Sb=Ye("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),V0=500;function Ib(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=V0?t:`${e.slice(0,V0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ab(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 Y0(t){try{return xb(t)}catch{return}}function kb(t,e){return{platform:process.platform,osRelease:hb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:gb(e.command)?Y0(e.command):void 0,cwd:e.cwd,cwdExists:Y0(e.cwd),envKeys:e.envKeys}}function Tb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${pb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var pt=class{constructor(e){this.opts=e;this.log=j(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new So({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new 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=Vf(process.env,this.opts.agentEnvFile??J().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=it(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,F0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>mb&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,z0(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=kb(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",Tb(c,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));$i(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||$i(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:vb,phase2GateMs:_b,livenessWindowMs:yb,absoluteMaxMs:bb,approvalMaxMs:Sb,suspendThresholdMs:Eb,...r};return this.call("session/prompt",e,$0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Nr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Mr(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(An(e,r))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,i=$0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=qi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let x=r.sessionId;return typeof x=="string"?x:void 0})();return new Promise((x,h)=>{let m={resolve:x,reject:h,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),I={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:zr(0,!1,o),sessionId:u};m.promptTimeout=I;let b=()=>{let S={startedAt:I.startedAt,lastActivityAt:I.lastActivityAt,firstFrameSeen:I.firstFrameSeen,hasActiveTool:I.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:I.suspendedMs,armedAt:I.armedAt,expectedIntervalMs:I.expectedIntervalMs},A=this.now(),k=K0(S,I.cfg,A),P=L=>{I.armedAt=A,I.expectedIntervalMs=L,m.timer=setTimeout(b,L)};if(k.action==="suspend"){I.suspendedMs+=k.suspendedDeltaMs,I.lastActivityAt=A,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:k.suspendedDeltaMs,suspendedMs:I.suspendedMs,...I.sessionId?{sessionId:I.sessionId}:{}}),P(k.rearmMs);return}if(k.action==="continue"){P(k.rearmMs);return}this.pending.delete(c),k.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:k.awaitingApproval,...I.sessionId?{sessionId:I.sessionId}:{}}),h(k.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${I.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${I.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...I.sessionId?{sessionId:I.sessionId}:{}}),h(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${I.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(b,I.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),h(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(w){m.timer&&clearTimeout(m.timer),this.pending.delete(c),h(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(N0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(vo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new 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:Ib(e.result)}),r.resolve(e.result));return}if(D0(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(R0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(An(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(An(e.id,Wi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=O0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=W0(this.framework,Ab(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(wb).join(`
106
- `),o=j0(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 Cb(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 Io=class extends pt{framework="claude-code";constructor(e){let{command:r,args:i}=si("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return Cb(e)}};ln();import{mkdtempSync as Pb,rmSync as Rb}from"node:fs";import{tmpdir as Db}from"node:os";import{join as Ob}from"node:path";var J0=["default","acceptEdits","plan","auto","bypassPermissions"],X0=["read-only","auto","full-access"];var Z0=["default","accept_edits","dont_ask"];function Nt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return J0.includes(e);case"codex":return X0.includes(e);case"hermes":return Z0.includes(e);case"openclaw":return!1}}function Ao(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Q0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function pd(t){switch(t){case"claude-code":return J0.join("/");case"codex":return X0.join("/");case"hermes":return Z0.join("/");case"openclaw":return""}}var ko=class extends pt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=si("codex",e.command,i),d=e.isolateCodexHome?Pb(Ob(Db(),"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}setSessionMode(e){let r=Nt("codex",e.modeId)?Ao(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(Lb(r)))}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Rb(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Lb(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=Q0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}te();var Nb=j("hermes-downstream"),To=class extends pt{framework="hermes";modelId;constructor(e){let r={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(r),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(r){Nb.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(r)})}}};Ke();var Mb=3e4,Ur=class extends pt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Mb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Gt();Ke();te();Ce();function gd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}ln();var kn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((r,i)=>{this.slots.push({task:e,resolve:r,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var Co=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new 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"}Jt();te();import{constants as ex}from"node:fs";import{access as Bb,readFile as Fb}from"node:fs/promises";import{delimiter as zb,dirname as Ub,join as tx}from"node:path";var Qe=j("framework-detector"),nx={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},Hb=[".exe",".cmd",".bat",".ps1"],Jn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??it,access:e.access??Bb,readFile:e.readFile??Fb}}async detect(e){let r=nx[e],i=await this.which(r);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return Qe.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(nx).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(zb).filter(Boolean),i=this.env.platform==="win32"?["",...Hb]:[""];for(let o of r)for(let c of i){let d=tx(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?ex.F_OK:ex.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 Qe.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 Qe.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let c=tx(Ub(o),"hermes-acp");return await this.isExecutable(c)?(Qe.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:c}),c):(Qe.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 Qe.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return Qe.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 Qe.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 Qe.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?(Qe.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}:(Qe.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return Qe.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 Qe.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||Qe.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){Qe.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&&(qb(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)}})}},Gb=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function qb(t){return t.replace(Gb,"")}import{homedir as jb}from"node:os";import{join as Wb}from"node:path";Gt();Jt();ar();Ke();te();async function sx(){let t=Wb(jb(),".openclaw/openclaw.json");return ur(t)}async function ox(){return(await sx())?.gateway?.auth?.token??""}var rx=j("openclaw.config"),Kb=[0,5e3,5e3],$b=Ye("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),ix="models.providers.",Po="agents.defaults.models",Ro=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new kn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Kb,this.cliTimeoutMs=e.cliTimeoutMs??$b}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,rx.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=it(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.runCliTolerant(["config","unset",r],["Config path not found","Nothing was changed"])))}catch(i){rx.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",`${ix}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${ix}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Po}[${e}]`,()=>this.runCli(["config","set",Po,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Po}[${e}]`,`${Po}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await sx())?.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"])))}};import{readFile as Vb,writeFile as Yb}from"node:fs/promises";import{join as Jb}from"node:path";var Xb=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
107
- `),Zb=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
108
- `);function Qb(t){return t.length===0?t:`${(t.endsWith(`
94
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function A0(t,e,r,i){let o=await w0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let c=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await fd(xe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=xe(r,h),m=xe(e,h,"SKILL.md"),w=await wo(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let v=I0(w);c.push({relPath:x,skill:{skillId:S0(t,x),skillName:v.name||h,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return c}async function k0(t,e,r){let i=pd(r);return A0(t,xe(e,i),i,!1)}async function T0(t,e){let r=[],i=new Set;for(let o of v0(e)){let c=await A0(t,o,o,!0);for(let d of c)i.has(d.relPath)||(i.add(d.relPath),r.push(d))}return r}var Py=3e4,Oy=50*1024*1024,m0=10*1024*1024,Lr=3e4;async function yo(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new A("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,d=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!d)throw new A("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=E0(o.skillName),h=pd(i),x=xe(h,u),m=xe(r,x);if(await ad(m,{recursive:!0}),c){let v=Buffer.from(o.content,"utf8");Gi(v.length),await dd(xe(m,"SKILL.md"),v,"utf8")}else{let v=await My(o.downloadUrl);Fy(v)?await Gy(v,m):zy(v)?await Uy(v,m):await dd(xe(m,"SKILL.md"),v.toString("utf8"),"utf8")}let w={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return he.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),w}function bo(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function Ly(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}function Ny(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function C0(t,e){let r=await Ce(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Lt,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((m,w)=>[m.skillId,w])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await ze(r,e),{status:"noop",count:0};let h=0,x=0;for(let m of u)try{await cd(xe(r.workspace,m.relPath),{recursive:!0,force:!0});let w=await yo({agentId:t,workspace:r.workspace,framework:r.framework,skill:Ny(m)});bo(c,d,w),h+=1}catch(w){x+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(w)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await ze(r,e),he.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function My(t){if(!t)throw new A("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Gi(e);let r=By(t);return Gi(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await wo(e);return Gi(r.length),r}if(zi(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),Py);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new A("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Gi(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new A("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Gi(t){if(t>Oy)throw new A("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function By(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new A("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function Fy(t){return t.length>=2&&t[0]===31&&t[1]===139}function zy(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function ud(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Uy(t,e){let r,i;try{r=new xd.default(t),i=r.getEntries()}catch(d){throw new A("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||ud(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new A("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new A("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new A("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=Hy(i),c=ld(e);for(let d of i){if(ud(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=ld(e,u),x=hd(c,h);if(x.startsWith("..")||x==="..")throw new A("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await ad(h,{recursive:!0});continue}await ad(yy(h),{recursive:!0});let m;try{m=d.getData()}catch(w){throw new A("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await dd(h,m)}}function Hy(t){let e;for(let r of t){let i=r.entryName;if(!i||ud(i))continue;let o=i.indexOf("/");if(o<=0)return;let c=i.slice(0,o+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function Gy(t,e){await qy(t);let r=Kf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new A("IPC_BAD_REQUEST",`tar extract timeout (${Lr}ms)`))},Lr);try{await b0(y0.from(t),r)}catch(c){throw c instanceof A?c:i?new A("IPC_BAD_REQUEST",`tar extract timeout (${Lr}ms)`):new A("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function qy(t){let e=[],r=Rr({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new A("IPC_BAD_REQUEST",`tar list timeout (${Lr}ms)`))},Lr);try{await b0(y0.from(t),r)}catch(c){throw i?new A("IPC_BAD_REQUEST",`tar list timeout (${Lr}ms)`):new A("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new A("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var jy=5e3;async function Wy(t,e,r,i){return R0(t,e,r,i,{count:0})}async function R0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await w0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(Sy.has(u.name)||u.isSymbolicLink())continue;if(o.count>=jy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=xe(e,u.name),x=by(xe(r,u.name)),m=null;try{m=await od(h)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let w={name:u.name,path:D0(hd(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await R0(t,h,x,i-1,o)),d.push(w)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function Ky(t){return!t||t<=0?Ey:Math.min(t,vy)}function $y(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function D0(t){return t.split(_0).join("/")}re();var Tn=G("agent-health-reporter"),Vy=1e4,Jy=3,qi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Vy,this.livenessFailureThreshold=e.livenessFailureThreshold??Jy}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Tn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Tn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Tn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Tn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let d of this.opts.core.agents.values()){let u=Zy(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),r.push(h)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Lt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Tn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(Tn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){Tn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){Tn.warn("onTickEnd hook failed",{err:String(r)})}}};function Zy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}xn();import{copyFile as hE,cp as xE,mkdir as Oo,readFile as pE,rm as gE,stat as Sd,writeFile as mE}from"node:fs/promises";import{homedir as fh}from"node:os";import{basename as wE,join as Yt}from"node:path";dn();import{existsSync as db}from"node:fs";import{release as lb}from"node:os";import{basename as ub,isAbsolute as fb}from"node:path";function ji(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Nr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Mr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Cn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ke();var Eo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function P0(t){return"method"in t&&"id"in t&&t.id!==void 0}function O0(t){return"method"in t&&!("id"in t)}function vo(t){return!("method"in t)&&"id"in t}var Xy={AGENT_NOT_FOUND:X.AGENT_NOT_FOUND,AGENT_BUSY:X.AGENT_BUSY,AGENT_DISCONNECTED:X.AGENT_DISCONNECTED,AGENT_TIMEOUT:X.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:X.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:X.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:X.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:X.INTERNAL_ERROR,BRIDGE_INTERNAL:X.INTERNAL_ERROR,IPC_AUTH_FAILED:X.INTERNAL_ERROR,IPC_BAD_REQUEST:X.INVALID_REQUEST,METHOD_NOT_FOUND:X.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:X.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:X.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:X.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:X.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:X.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:X.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:X.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:X.FILE_TOO_LARGE,UNSUPPORTED_MIME:X.UNSUPPORTED_MIME,UPLOAD_FAILED:X.UPLOAD_FAILED,UPSTREAM_NOT_READY:X.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:X.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:X.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:X.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:X.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:X.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:X.SKILL_ZIP_TOO_LARGE};function Yy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Wi(t.message)}:typeof t=="string"?Wi(t):typeof t=="object"?eb(t):t}var Qy=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Wi(t){let e=t;for(let[r,i]of Qy)e=e.replace(r,i);return e}function eb(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Wi(i):e[r]=i;return e}function Ki(t){if(t instanceof A){let e=Yy(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(r.reason=e.reason),{code:Xy[t.code]??X.INTERNAL_ERROR,message:Wi(t.message),data:r}}return{code:X.INTERNAL_ERROR,message:Wi(t instanceof Error?t.message:String(t))}}function L0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new A(r,o,{retriable:e?.retriable??!1,cause:c})}function M0(t){return`${JSON.stringify(t)}
95
+ `}var N0=10*1024*1024,So=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>N0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${N0} bytes`)}),[]}let r=this.buffer.split(`
96
+ `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var F0={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission","session/set_mode":"session.setMode",initialize:"initialize"},PT=Object.fromEntries(Object.entries(F0).map(([t,e])=>[e,t])),tb={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Br=class{seq=0;next(e,r){this.seq+=1;let i=F0[e]??nb(e),o=tb[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(h=>B0(r?.[h]??"")),u=rb(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>B0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function nb(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function B0(t){return t.replace(/[:_\s]+/g,"-")}function rb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}hn();import{readFileSync as ib}from"node:fs";var sb=384;async function gd(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await fn(t.agentEnvFile,r,{mode:sb})}function $i(t){try{let e=JSON.parse(ib(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Io(t,e,r={},i=o=>o){return{...i({...t,...$i(e)}),...r}}Zt();dr();Ke();re();Te();import{execFileSync as ob,spawnSync as ab}from"node:child_process";function Vi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Ji(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),ab("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var md=new Set;function z0(t){typeof t=="number"&&t>0&&md.add(t)}function U0(t){typeof t=="number"&&md.delete(t)}function H0(){for(let t of md)Ji(t,"SIGKILL")}var Fr="coze-bridge-daemon";function G0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return ob("pgrep",["-U",String(o),"-f",Fr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function q0(t,e){if(t.length===0)return;let r=e?.killFn??Ji,i=e?.isAliveFn??Vi,o=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(h=>i(h));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var cb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function j0(t,e){if(!e)return null;for(let r of cb)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function W0(t,e){return j0(t,e)}function K0(t,e){return j0(t,e)}function zr(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function $0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,m=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:zr(m,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:zr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:zr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:zr(c,!1,e)}}var V0=Xe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),hb=200,xb=40,pb=Xe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),gb=Xe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),mb=Xe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),wb=Xe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),_b=Xe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),yb=Xe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),J0=500;function bb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=J0?t:`${e.slice(0,J0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Eb(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:r}=t;if(typeof r=="string")e.push(r);else if(r&&typeof r=="object")try{e.push(JSON.stringify(r))}catch{}return e.join(" ")}function Z0(t){try{return db(t)}catch{return}}function vb(t,e){return{platform:process.platform,osRelease:lb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:fb(e.command)?Z0(e.command):void 0,cwd:e.cwd,cwdExists:Z0(e.cwd),envKeys:e.envKeys}}function Sb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${ub(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Mt=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new So({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Br;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new A("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=Io(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=st(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,z0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>hb&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,U0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,d=vb(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new A("AGENT_SPAWN_FAILED",Sb(c,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Ji(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Ji(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r){let i={firstUpdateMs:_b,phase2GateMs:pb,livenessWindowMs:gb,absoluteMaxMs:mb,approvalMaxMs:yb,suspendThresholdMs:wb,...r};return this.call("session/prompt",e,V0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Nr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Mr(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Cn(e,r))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,i=V0,o){if(!this.child||this.stopped)return Promise.reject(new A("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=ji(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let h=r.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let m={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),v={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:zr(0,!1,o),sessionId:u};m.promptTimeout=v;let _=()=>{let E={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},S=this.now(),I=$0(E,v.cfg,S),k=R=>{v.armedAt=S,v.expectedIntervalMs=R,m.timer=setTimeout(_,R)};if(I.action==="suspend"){v.suspendedMs+=I.suspendedDeltaMs,v.lastActivityAt=S,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:I.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),k(I.rearmMs);return}if(I.action==="continue"){k(I.rearmMs);return}this.pending.delete(c),I.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:I.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(I.awaitingApproval?new A("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new A("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new A("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(_,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(w){m.timer&&clearTimeout(m.timer),this.pending.delete(c),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new A("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(M0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(vo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new A("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:bb(e.result)}),r.resolve(e.result));return}if(O0(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(P0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Cn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(Cn(e.id,Ki(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=L0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=K0(this.framework,Eb(e));return i?new A(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new A("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(xb).join(`
98
+ `),o=W0(this.framework,i);return o?new A(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new A("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Ib(t){let e={};for(let[r,i]of Object.entries(t))i!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=i));return e}var Ao=class extends Mt{framework="claude-code";constructor(e){let{command:r,args:i}=ci("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return Ib(e)}};dn();import{spawn as Ab}from"node:child_process";import{closeSync as kb,existsSync as yd,mkdirSync as Tb,mkdtempSync as Cb,openSync as Rb,readFileSync as nh,readSync as Db,readdirSync as Pb,rmSync as Ob,statSync as Lb}from"node:fs";import{homedir as Nb,tmpdir as Mb}from"node:os";import{join as Ur}from"node:path";var X0=["default","acceptEdits","plan","auto","bypassPermissions"],Y0=["read-only","auto","full-access"];function Bt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return X0.includes(e);case"codex":return Y0.includes(e);case"openclaw":return!1}}function ko(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Q0(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function wd(t){switch(t){case"claude-code":return X0.join("/");case"codex":return Y0.join("/");case"openclaw":return""}}Te();var bd=9e4,Bb=64*1024,Fb=100;function zb(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?bd:Math.max(1,Math.floor(e*1e3))}function Ub(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?bd:Math.max(1,Math.floor(e))}function Hb(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[r,i]of Object.entries(t))typeof i=="string"&&(e[r]=i);return Object.keys(e).length>0?e:void 0}function eh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:bd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let r=typeof e.command=="string"?e.command.trim():"";if(!r)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,o=Hb(e.env);return{command:r,timeoutMs:e.timeout_ms===void 0?zb(e.timeout):Ub(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function _d(t){if(Array.isArray(t))return t.flatMap(i=>_d(i));if(!t||typeof t!="object"){let i=eh(t);return i?[i]:[]}let e=t;if(e.hooks)return _d(e.hooks);let r=eh(e);return r?[r]:[]}function Gb(t){let e=Ur(t,"hooks.json");if(!yd(e))return[];let r=JSON.parse(nh(e,"utf8")),o=r.hooks&&typeof r.hooks=="object"?r.hooks:r;return _d(o.Stop??o.stop)}function qb(t,e){let r=Ur(t,"sessions");if(!yd(r))return;let i=[],o=c=>{let d;try{d=Pb(c,{withFileTypes:!0})}catch{return}for(let u of d){let h=Ur(c,u.name);if(u.isDirectory())o(h);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:h,mtimeMs:Lb(h).mtimeMs})}catch{}}};o(r),i.sort((c,d)=>d.mtimeMs-c.mtimeMs);for(let c of i.slice(0,Fb))if(jb(c.path,e))return c.path}function jb(t,e){let r;try{r=Rb(t,"r");let i=Buffer.alloc(Bb),o=Db(r,i,0,i.length,0),c=i.subarray(0,o).toString("utf8");return c.includes(JSON.stringify(e))||c.includes(e)}catch{return!1}finally{if(r!==void 0)try{kb(r)}catch{}}}function Wb(t){return $i(t??Z().agentEnvFile)}function Kb(t){let e=t.trim();if(e.length>=2){let r=e[0];if((r==='"'||r==="'")&&e.endsWith(r)){let i=e.slice(1,-1);return r==='"'?i.replace(/\\n/g,`
99
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function $b(t){let e={};for(let r of t.split(/\r?\n/)){let i=r.trim();if(!i||i.startsWith("#"))continue;let o=i.startsWith("export ")?i.slice(7).trimStart():i,c=o.indexOf("=");if(c<=0)continue;let d=o.slice(0,c).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=Kb(o.slice(c+1)))}return e}function Vb(t){let e=Ur(t,"cozeloop.env");return yd(e)?$b(nh(e,"utf8")):{}}function th(t){let e=t?.trim();return e||void 0}function Jb(t){let e=Wb(t.agentEnvFile),r=th(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(r)return r;let i=th(t.env?.HOME??e.HOME??process.env.HOME)??Nb();return Ur(i,".codex")}var To=class extends Mt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ci("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Cb(Ur(Mb(),"coze-bridge-codex-home-")):Jb(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Tb(d,{recursive:!0});let h=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...h?{env:h}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async sessionPrompt(e){let r=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),r}setSessionMode(e){let r=Bt("codex",e.modeId)?ko(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:r})}onUpdate(e){super.onUpdate(r=>e(Zb(r)))}async runStopHooksBestEffort(e){let r=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!r)return;let i;try{i=Gb(r)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:r,err:String(d)});return}if(i.length===0)return;let o=qb(r,e),c=JSON.stringify({hook_event_name:"Stop",session_id:e,...o?{transcript_path:o}:{},trigger:"coze-bridge"});await Promise.all(i.map(async d=>{try{await this.runHookCommand(d,c)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:r,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,r){return new Promise((i,o)=>{let c=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=c?Vb(c):{},u=Io(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let h=Ab(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",m=setTimeout(()=>{h.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);h.stderr?.setEncoding("utf8"),h.stderr?.on("data",w=>{x+=w,x.length>4e3&&(x=x.slice(-4e3))}),h.on("error",w=>{clearTimeout(m),o(w)}),h.on("close",(w,v)=>{if(clearTimeout(m),w===0){i();return}o(new Error(`hook exited code=${w} signal=${v} stderr=${x.slice(-1e3)}`))}),h.stdin.end(`${r}
100
+ `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{Ob(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function Zb(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let r=Q0(e.currentModeId);return!r||r===e.currentModeId?t:{...t,update:{...t.update,currentModeId:r}}}Ke();var Xb=3e4,Hr=class extends Mt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Xb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};hn();Ke();re();Te();function Ed(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}dn();var Rn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((r,i)=>{this.slots.push({task:e,resolve:r,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var Co=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new Rn,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,i]of this.sessions)Gr(i),i.downstream&&(r.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Gr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Xt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Zt();re();import{constants as rh}from"node:fs";import{access as Yb}from"node:fs/promises";import{delimiter as Qb,join as eE}from"node:path";var St=G("framework-detector"),ih={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},tE=[".exe",".cmd",".bat",".ps1"],Xn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??st,access:e.access??Yb}}async detect(e){let r=ih[e],i=await this.which(r);if(!i)return St.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(ih).map(async i=>[i,await this.detect(i)])),r={};for(let[i,o]of e)o&&(r[i]=o);return r}async which(e){let r=this.env.pathEnv.split(Qb).filter(Boolean),i=this.env.platform==="win32"?["",...tE]:[""];for(let o of r)for(let c of i){let d=eE(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?rh.F_OK:rh.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return St.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return St.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return St.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return St.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(St.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(St.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return St.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return St.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||St.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){St.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(rE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,d,u=h=>{c||(c=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{o+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},nE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function rE(t){return t.replace(nE,"")}import{homedir as oh}from"node:os";import{join as Do}from"node:path";hn();Zt();dr();Ke();re();async function ah(){let t=Do(oh(),".openclaw/openclaw.json");return ln(t)}async function ch(){return(await ah())?.gateway?.auth?.token??""}var Yn=G("openclaw.config"),iE=[0,5e3,5e3],sE=Xe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),sh="models.providers.",Ro="agents.defaults.models",oE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function qr(t,e){let r=Array.isArray(t)?[...t]:[],i=new Set(r);for(let o of e)i.has(o)||(i.add(o),r.push(o));return r}var Po=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Rn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??iE,this.cliTimeoutMs=e.cliTimeoutMs??sE,this.openclawDir=e.openclawDir??Do(oh(),".openclaw")}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(d=>setTimeout(d,c));try{return await r()}catch(d){i=d,Yn.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new A("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=st(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?r():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",r],["Config path not found","Nothing was changed"])))}catch(i){Yn.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${sh}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${sh}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ro}[${e}]`,()=>this.runCli(["config","set",Ro,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ro}[${e}]`,`${Ro}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await ah())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,c=[];for(let d of Object.keys(i))d.startsWith(o)&&c.push(d.slice(o.length));return c}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}ensureAcpDeviceScopes(){return this.queue.enqueue(()=>this.ensureAcpDeviceScopesUnlocked())}async ensureAcpDeviceScopesUnlocked(){try{let e=Do(this.openclawDir,"identity","device.json"),i=(await ln(e))?.deviceId?.trim();if(!i)return Yn.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Do(this.openclawDir,"devices","paired.json"),c=await ln(o),d=c?.[i];if(!c||!d)return Yn.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,h=qr(qr(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(E=>E.startsWith("operator.")),x=qr([...oE],h),m=qr(d.scopes,x),w=qr(d.approvedScopes,x),v=u?qr(u.scopes,x):void 0;return m.length!==(d.scopes?.length??0)||w.length!==(d.approvedScopes?.length??0)||u!==void 0&&v?.length!==(u.scopes?.length??0)?(d.scopes=m,d.approvedScopes=w,u&&v&&(u.scopes=v),await fn(o,c,{mode:384}),Yn.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(Yn.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return Yn.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as aE,writeFile as cE}from"node:fs/promises";import{join as dE}from"node:path";var lE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
101
+ `),uE=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
102
+ `);function fE(t){return t.length===0?t:`${(t.endsWith(`
109
103
  `)?t.slice(0,-1):t).split(`
110
104
  `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
111
105
  `)}
112
- `}async function ax(t){let e=Jb(t,"HEARTBEAT.md"),r=await Vb(e,"utf8");return Qb(r)!==Xb?!1:(await Yb(e,Zb),!0)}var se=j("agent-manager"),_d="acceptEdits",ux="full-access",fx="read-only";function rE(t){return{INITIAL_AGENT_MODE:Ao(t)}}var iE=(t,e,r,i,o,c,d,u,x,h)=>{switch(t){case"claude-code":{let m={...o?{...i0(o),...a0(o,d,u)}:{},...x??{},IS_SANDBOX:"1"};return new Io({cwd:r,env:m,agentId:i})}case"codex":{let m=ux;h!==void 0&&(Nt("codex",h)?m=h:se.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let w=!!o,I={...o?{...o0(o),...s0(o,d,u)}:{},...rE(m),...w?{NO_BROWSER:"1"}:{},...x??{}};return new ko({cwd:r,agentId:i,...Object.keys(I).length>0?{env:I}:{},...w?{authMethodId:"api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ur({command:e,cwd:r,agentId:i,...c?{sessionName:gd(c)}:{}});case"hermes":return new To({command:e,cwd:r,agentId:i,...x&&Object.keys(x).length>0?{env:{...x}}:{},...o?.model?{modelId:o.model}:{}})}};function wd(t){return t==="claude-code"||t==="codex"}var sE={path:"",version:"cloud-deployed"},dx="openclaw_gateway_unavailable",oE="openclaw_default_agent_missing";function lx(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 aE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},cE=6e4,Do=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??iE,this.createTimeoutMs=e.createTimeoutMs??cE,this.detectorFactory=e.detectorFactory??(()=>new Jn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Ro({command:r})),this.openclawConfigDir=e.openclawConfigDir??cx(nE(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{se.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=cx(e,".env");if(await tE(r).then(c=>c.isFile()).catch(()=>!1)){se.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Bi({...process.env,...Mi(this.paths.agentEnvFile)});await ut(r,o,{mode:384}),se.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),se.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await 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")se.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(P=>se.warn("dispose stale agent failed (ignored)",{err:String(P)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")se.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(P=>se.warn("dispose drifted agent failed (ignored)",{err:String(P)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){se.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let P=await ve(e.agentId,this.paths).catch(()=>null);P&&(P.patToken=e.patToken,await ze(P,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){se.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let P=await ve(e.agentId,this.paths).catch(()=>null);P&&(P.modelInfo=e.modelInfo,await ze(P,this.paths))}return se.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 L=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${L}`)}let u=Fe(e.agentId,this.paths),x=o?"cloud":"local",h=e.framework==="openclaw"&&x==="local",m;h&&!r?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=m??(h?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),I=e.workspace??w??u.workspace,b=new AbortController,S=setTimeout(()=>b.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),A,k=!1;try{o&&wd(e.framework)&&await lr(e.framework,b.signal);let P=()=>{if(b.signal.aborted)throw b.signal.reason instanceof Error?b.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await md(u.root,{recursive:!0}),await md(I,{recursive:!0}),await md(u.logs,{recursive:!0}),P(),h||await xr(I,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(x==="cloud"?await Ha(I,"cloud"):await Ha(I,"local",_d)),P();let L=i,E=n0({model:e.model??L?.model}),D=Gf(e._meta)??L?.accountId,N=e.patToken??L?.patToken,z=x==="cloud"?e.modelInfo??L?.modelInfo:void 0;if(A=new Co({agentId:e.agentId,framework:e.framework,workspace:I,model:E.model??It,deployType:x,...D?{accountId:D}:{},...N?{patToken:N}:{},...z?{modelInfo:z}:{}}),A.status="ok",L?.sessions){let V=e.framework==="hermes"||x==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Z,oe]of Object.entries(L.sessions)){let ce={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?oe.permissionMode===void 0?(ce.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",se.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Z,framework:e.framework,fallback:ce.permissionMode})):Nt(e.framework,oe.permissionMode)?ce.permissionMode=oe.permissionMode:se.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Z,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&se.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Z,framework:e.framework,deployType:x}),oe.cozeGroupId&&(ce.cozeGroupId=oe.cozeGroupId),A.sessions.set(Z,ce)}let re=Object.keys(L.sessions).length;re>0&&se.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(A),k=!0;let B={agentId:e.agentId,framework:e.framework,workspace:I,cozeIdentity:e.cozeIdentity,createdAt:L?.createdAt??Date.now(),sessions:L?.sessions??{},model:E.model};if(x==="cloud"&&(B.deployType="cloud"),D&&(B.accountId=D),N&&(B.patToken=N),z&&(B.modelInfo=z),L?.skills&&(B.skills=L.skills),L?.agentName&&(B.agentName=L.agentName),L?.description&&(B.description=L.description),B.skillsRefreshedForVersion=L?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&x==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,I)):se.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await ax(I)&&se.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:I})}catch(V){se.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:I,err:String(V)})}}let Y=e.initialSkills??[];if(Y.length>0){let V=[...B.skills??[]],re=new Map(V.map((ce,R)=>[ce.skillId,R])),Z=await Promise.allSettled(Y.map(ce=>yo({agentId:e.agentId,workspace:I,framework:e.framework,skill:ce,paths:this.paths}))),oe=0;for(let[ce,R]of Z.entries()){let G=Y[ce];G&&(R.status==="fulfilled"?(bo(V,re,R.value),oe++):se.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(R.reason)}))}oe>0&&(B.skills=V,se.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:Y.length}))}return await ze(B,this.paths),se.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:x}),{ok:!0,agentId:e.agentId,workspace:I,framework:e.framework}}catch(P){throw se.error("agent create failed, rolling back",{agentId:e.agentId,err:String(P)}),k&&A&&(await A.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),se.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:P instanceof Error?P.stack:String(P)}),await eE(u.root,{recursive:!0,force:!0}).catch(L=>se.warn("rm agent dir failed (ignored)",{err:String(L)})),P instanceof T?P:new T("AGENT_SPAWN_FAILED",String(P),{cause:P})}finally{clearTimeout(S)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&wd(e.framework))u=sE;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`);wd(e.framework)&&!_s(e.framework)&&(se.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await lr(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 m={...this.buildBinShimPathEnv()};x&&(await x0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:c}),m.HERMES_HOME=Yn(e.agentId,this.paths)),h=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,c,m)}else{let m=e.sessions.get(i),w=Xt(e)?m?.permissionMode??ux:"full-access";h=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),w)}try{return await h.start(),await h.initialize(aE),h}catch(m){let w=h instanceof pt?h.getStderrTail():[];throw w.length>0&&se.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof T?m.code:"unknown",recentStderr:w}),await h.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,m)}}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",lx(o),{cause:{reason:dx}})}catch(o){se.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof T?i:new T("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};se.warn("openclaw default agent stale or missing, attempting lazy re-detect");let r=await this.detectorFactory().detect("openclaw");if(r?.defaultAgent?.id&&r.defaultAgent.workspace)return se.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new T("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:oE}})}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",lx(r),{cause:{reason:dx}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,x=gd(o);if(r.deployType==="local"){let w=await this.ensureOpenclawDefaultAgent();return new Ur({command:u,cwd:w.workspace,agentId:w.id,sessionName:x})}let h=await ox(),m;if(i?.modelToken){let w=ed(o),I=td(i),b=`${w}/${I}`;if(!this.ensuredProviders.has(b)){let S=this.getOpenclawConfig(),A=await S.getAllowlistModelsForProvider(w),k=c0(i,c,d,A);k&&(await S.ensureProvider(w,k),await S.addModelToAllowlist(b),this.ensuredProviders.add(b))}m=b}return new Ur({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:x,...h?{gatewayToken:h}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e,r){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=r??e.model;for(let c of e.sessions.keys()){let d=ed(c),u=`${d}/${o}`,x=!0;try{await i.removeProvider(d)}catch(h){x=!1,se.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(h)})}try{await i.removeModelFromAllowlist(u)}catch(h){x=!1,se.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(h)})}x&&this.ensuredProviders.delete(u)}}};import{randomUUID as mx}from"node:crypto";import{promises as pE}from"node:fs";import{basename as _x}from"node:path";Ke();te();import{promises as dE}from"node:fs";import{basename as lE}from"node:path";var xx=j("file-upload"),uE="/api/coze_claw/file/agent_upload",fE=6e4;async function hx(t,e={}){let i=`${Rr(Dr(e.handshakeBase))}${uE}`,o=e.timeoutMs??fE,c=await dE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Sn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},x=new AbortController,h=setTimeout(()=>x.abort(),o);xx.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:d,signal:x.signal}),w=m.headers.get("x-tt-logid")??"";if(!m.ok){let S=await m.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${w}: ${S.slice(0,200)}`)}let I=await m.json();if(I.code!==void 0&&I.code!==0)throw new T("UPLOAD_FAILED",`upload code=${I.code} msg=${I.msg??"-"} logid=${w}`);let b=I.data?.file?.file_url;if(!b)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(I).slice(0,200)}`);return xx.info("file upload ok",{uri:b,logid:w}),{uri:b}}catch(m){throw m instanceof T?m:m.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${lE(t.path)}`):new T("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(h)}}Ke();te();import{extname as xE}from"node:path";var hE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function px(t){let e=xE(t).toLowerCase();return hE[e]??"application/octet-stream"}Ce();var Oo=j("agent-send"),gx=50*1024*1024;function yx(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 bx(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&&(Oo.warn("sendAgentFileUpdate failed, retrying",{attempt:x+1,err:String(h)}),await new Promise(m=>setTimeout(m,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function Ex(t,e){let{session:r,runtime:i}=yx(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 pE.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>gx)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${gx}`);let c=await px(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??_x(t.path),u;try{u=await hx({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 Oo.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:mx(),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 bx(e,r,i,t.sessionId,x,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Oo.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 vx(t,e){let{session:r,runtime:i}=yx(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??_x(t.path),c={sessionUpdate:"group_file",messageId:mx(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await bx(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Oo.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 Sx(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}Jt();te();ln();var Mt=j("coze-cli-installer"),Ix="@coze/cli@latest",gE="coze",Ax="0.1.8",mE=5e3,wE=5e3,_E=9e4,kx=1e4,Yi=null,Lo=!1;async function bd(t,e={}){if(Lo)return;if(Yi)return Yi;let r=e.exec??$f;return Yi=(async()=>{try{let i=await yE(gE,r),o=!1;if(i){let d=await bE(r);if(d===void 0)Mt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Sx(d,Ax))Mt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Ax}),o=!0;else{Mt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Lo=!0;return}}let c=o?"upgrade-only":"full";Mt.info("coze-cli install start",{package:Ix,mode:c});try{await r("npm",["i","-g","--prefer-online",Ix],{timeout:_E,maxBuffer:10*1024*1024}),Mt.info("coze-cli install ok")}catch(d){Mt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Lo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:kx}),Mt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Mt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:kx}),Mt.info("coze auth login ok")}catch(d){Mt.warn("coze auth login failed",{err:String(d)});return}Lo=!0}finally{Yi=null}})(),Yi}async function yE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:mE});return za(i)}catch{return}}async function bE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:wE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}qt();Gt();Ce();var EE=10*6e4;function Tx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?EE:e}function No(t){return ur(t??J().configFile)}function Ji(t,e){return fr(e??J().configFile,t)}import{randomBytes as GE}from"node:crypto";ar();Ke();te();import{createReadStream as vE}from"node:fs";import{mkdir as SE,readFile as IE,realpath as AE,stat as kE,writeFile as TE}from"node:fs/promises";import{basename as CE,dirname as Ed,isAbsolute as PE,join as RE,relative as DE,resolve as Cx,sep as OE}from"node:path";import{createInterface as LE}from"node:readline";var Rx=j("fs-rpc"),Xi=Ye("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Dx(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Xi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Xi} bytes`);let i=await Lx(t.path,e);return await SE(Ed(i),{recursive:!0}),await TE(i,t.content,"utf8"),Rx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Ox(t,e){let r=await Lx(t.path,e),i=await kE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Xi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Xi} bytes`);let c;if(o&&i.size>Xi)c=await NE(r,t.line??1,t.limit);else{let d=await IE(r,"utf8");if(o){let u=d.split(`
113
- `),x=Math.max(0,(t.line??1)-1),h=typeof t.limit=="number"?x+t.limit:void 0;c=u.slice(x,h).join(`
114
- `)}else c=d}return Rx.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function NE(t,e,r){let i=LE({input:vE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let x of i)if(u>=o&&u<c&&d.push(x),u++,u>=c)break}finally{i.close()}return d.join(`
115
- `)}async function Lx(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([Px(Cx(e)),Px(Cx(t))]),o=DE(r,i);if(ME(o,OE,PE(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function ME(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Px(t){let e=[],r=t;for(;r!==Ed(r);)try{let i=await AE(r);return e.length?RE(i,...e.reverse()):i}catch{e.push(CE(r)),r=Ed(r)}return t}te();var Nx=j("prompt-multimodal"),Mx=10*1024*1024,BE=15e3,FE=6;async function Bx(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 zE(d))}}let o=Array.from({length:Math.min(FE,t.length)},()=>i());return await Promise.all(o),e}function Fx(t){return t.some(e=>e.type==="image")}async function zE(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 HE(e.uri),o=e.mimeType||UE(i)||"application/octet-stream";return Nx.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 Nx.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function UE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function HE(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>Mx)throw new Error(`image too large: ${o.byteLength} bytes (max ${Mx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}qt();Ke();te();var $=j("core"),qE=3e4,jE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,WE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",KE="\u5BA1\u6279\u5DF2\u8D85\u65F6",$E=3e4,Mo=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=Tx(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){$.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&$.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Vi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(An(o,{code:X.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:X.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:X.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(vo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&jE.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,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Mr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Mr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Mr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(o){$.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(An(r,Wi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new 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,m=ho(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,x,c,WE,h,m)}}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=VE();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=Xt(e)?qf(i._meta):void 0;if(u!==void 0&&!Nt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${pd(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 I=x.permissionMode;x.permissionMode=u,await this.persistSessionMapping(e);try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(b){throw x.permissionMode=I,await this.persistSessionMapping(e).catch(()=>{}),b}}let h=i._meta?.cozeTriggerMsgId;h?e.activeTriggers.set(x.acpSessionId,h):e.activeTriggers.delete(x.acpSessionId);let m=ho(i._meta);if(m?e.activeGroupIds.set(x.acpSessionId,m):e.activeGroupIds.delete(x.acpSessionId),m&&x.cozeGroupId!==m&&(x.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Fx(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await Bx(c.prompt);try{let I=await x.downstream.sessionPrompt({...c,sessionId:x.acpSessionId,prompt:w});return x.lastActiveAt=Date.now(),I}catch(I){if(I instanceof T&&I.code==="AGENT_APPROVAL_TIMEOUT"){let b=x.pendingPermission;b&&(b.downstream.respondAgentRequest(b.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(b.upstreamId),x.pendingPermission=void 0);let S=x.acpSessionId,A=S?e.activeTriggers.get(S):void 0,k=S?e.activeGroupIds.get(S):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,KE,A,k)}throw I}finally{if(e.activeTriggers.delete(x.acpSessionId),e.activeGroupIds.delete(x.acpSessionId),x.pendingPermission=void 0,x.reloadAfterTurn){x.reloadAfterTurn=!1;let I=x.downstream;I&&(x.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:x.acpSessionId}),I.stop("reload-after-turn").catch(b=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(b)})))}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=ho(i._meta);if(!d)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(!Nt(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${pd(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 m=h.permissionMode;if(h.permissionMode=u,await this.persistSessionMapping(e),h.downstream?.isAlive()&&h.acpSessionId)try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(w){throw h.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),w}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId: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 Xt(e)&&(e.framework==="hermes"?c.permissionMode=e.deployType==="cloud"?l0:u0:c.permissionMode=e.framework==="claude-code"?_d:fx),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ht.GEN_MODEL_TOKEN,i,$E);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,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 m=await x.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let h=await x.sessionNew({cwd:e.workspace});i.acpSessionId=h.sessionId,await this.persistSessionMapping(e)}}catch(h){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),await x.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,h}if(x.afterSessionEstablished&&i.acpSessionId&&await x.afterSessionEstablished(i.acpSessionId),Xt(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(Vi(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let d=e.activeTriggers.get(r.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Nr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Nr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(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(XE(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"&&Xt(e)){let m=d.currentModeId;Nt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(w=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof m=="string"&&!Nt(e.framework,m)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},x=e.activeTriggers.get(i);x&&(u.cozeTriggerMsgId=x);let h=e.activeGroupIds.get(i);h&&(u.cozeGroupId=h),this.upstream.send(Nr("session/update",{...r,sessionId:o,_meta:u})).catch(m=>$.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}$.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Dx(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Ox(c,o);r.respondAgentRequest(i.id,d)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Wi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,x=u?e.activeTriggers.get(u):void 0,h={cozeAgentId:e.agentId};x&&(h.cozeTriggerMsgId=x);let m=u?e.activeGroupIds.get(u):void 0;m&&(h.cozeGroupId=m);let w=u?this.reverseSessionId(e,u):void 0,I=w?e.sessions.get(w):void 0;I&&(I.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let b={...c,...w?{sessionId:w}:{},_meta:h};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(S=>({optionId:S.optionId,kind:S.kind,name:S.name}))}),this.upstream.send(qi(o,"session/request_permission",b)).catch(S=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(S)}),r.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(S)}`})})}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"&&YE(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 Eo(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=qE){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(qi(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&&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){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(An(e,{code:r,message:i,data:{bridgeVersion:Lt}}))}};function VE(){return GE(16).toString("hex")}function YE(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 JE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."],zx="Warning: ";function XE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let o=i.text.startsWith(zx)?i.text.slice(zx.length):i.text;return JE.some(c=>o.startsWith(c))}Gt();te();Ce();import{randomBytes as ZE}from"node:crypto";import{createServer as QE}from"node:http";var ev=1e6,Ux=j("ipc"),Bo=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=ZE(32).toString("hex");let e=QE((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(),Ux.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(o=>o?i(o):r())}),this.server=null)}async persistAuthFiles(){await ut(this.paths.portFile,String(this.port)),await ut(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Zi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Zi(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await tv(e)}catch(u){Zi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Zi(r,200,u??{ok:!0})}catch(u){Ux.error("IPC handler failed",{key:o,err:String(u)}),Zi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Zi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function tv(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>ev)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 E1=Ht(Nh(),1),v1=Ht(Ko(),1),S1=Ht(qr(),1),I1=Ht(Od(),1),A1=Ht(Md(),1),k1=Ht(Gd(),1),jh=Ht(Jo(),1),T1=Ht(qh(),1);var Wh=jh.default;Ke();te();var{FWS:j1}=np(),De=j("upstream.frontier"),ip="application/json",sp="none",W1=15e3;function K1(t){class e extends Wh{constructor(i){super(i,Jf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>De.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(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");De.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){De.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var 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){De.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Xf,...Sn(this.opts.ppeOverride)},r=K1(e),i=Qf(this.opts.urlOverride),o={url:i,ws:r,fpID:Yf,aID:po,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:ip,force:!0},payloadEncoding:{encoding:sp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new j1(o),d=!1,u=null,x,h,m=new Promise((b,S)=>{x=b,h=S}),w=b=>{d||(d=!0,u&&(clearTimeout(u),u=null),b?h(b):x())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let b=this.openCount===1;De.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:b,openCount:this.openCount}),b&&w();for(let S of this.connectHandlers)Promise.resolve(S({initial:b})).catch(A=>De.warn("onConnect handler threw (ignored)",{err:String(A)}))},c.onclose=b=>{this.opened=!1,De.info("frontier closed",{code:b.code,reason:b.reason,willReconnect:b.willReconnect})},c.onerror=b=>{De.warn("frontier error",{code:b.code,msg:b.message}),w(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${b.code} msg=${b.message??""}`))},c.onmessage=b=>this.handleMessage(b),this.fws=c;let I=this.opts.openTimeoutMs??W1;u=setTimeout(()=>{w(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${I}ms (handshake or upgrade slow)`))},I),await c.connect();try{await m}catch(b){try{c.close(1e3,"open failed")}catch(S){De.warn("fws close during start failure threw (ignored)",{err:String(S)})}throw this.fws=null,this.opened=!1,b}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){De.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw De.warn("frontier send refused: upstream not started",{method:i}),new T("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(De.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new 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;op(c)||De.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:ip,payloadEncoding:sp})}catch(u){throw De.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){De.debug("drop non-adapter frontier frame",{service:r});return}let i=Y1(e);if(!i){De.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){De.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){De.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;op(c)||De.info("frontier frame in",{logid:V1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:$1(i)}),Promise.resolve(this.handler(o)).catch(d=>De.warn("frontier frame handler threw",{err:String(d)}))}};function op(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var ap=2e3;function $1(t){return t.length<=ap?t:`${t.slice(0,ap)}...<truncated, total ${t.length} chars>`}function V1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function Y1(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}Ke();te();var Kd=j("skill-publish"),J1="/api/marketplace/product/skill/publish_with_assets",X1=15e4;async function cp(t,e={}){let i=`${Rr(Dr(e.handshakeBase))}${J1}`,o=e.timeoutMs??X1,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Sn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,x=setTimeout(()=>u.abort(),o);Kd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let h=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),m=h.headers.get("x-tt-logid")??"";if(!h.ok){let b=await h.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${h.status} logid=${m}: ${b.slice(0,200)}`)}let w=await h.json();if(Kd.info("skill publish response",{logid:m,httpStatus:h.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${m}`);let I={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(I.skillId=String(w.data.skill_id)),w.data?.version&&(I.version=w.data.version),Kd.info("skill publish ok",{logid:m,skillId:I.skillId??"",version:I.version??""}),I}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 $d=j("upstream.switchable"),sa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;$d.info("swap upstream",{reason:r});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw $d.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>$d.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};te();var Vd=j("upstream"),Yr=class{handler=null;async start(){Vd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Vd.info("NoopUpstream stopped",{reason:e})}async send(e){Vd.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ke();te();Gt();te();Ce();import{promises as Z1}from"node:fs";var dp=j("pat-token-store");async function oa(t=J()){try{let r=(await Z1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(dp.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"&&dp.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 ut(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as aa}from"node:fs";import{join as Q1}from"node:path";function eS(t,e){return`#!/bin/sh
106
+ `}async function dh(t){let e=dE(t,"HEARTBEAT.md"),r=await aE(e,"utf8");return fE(r)!==lE?!1:(await cE(e,uE),!0)}var ee=G("agent-manager"),_E=["hooks.json","cozeloop.env"],yE=["hooks"];async function bE(t,e){let r=Yt(Fe(t,e).root,"codex-home"),i=Yt(fh(),".codex");if(r!==i){await Oo(r,{recursive:!0});for(let o of yE){let c=Yt(i,o),d=Yt(r,o);try{await Sd(d);continue}catch{}try{await xE(c,d,{recursive:!0,errorOnExist:!0,filter:u=>{let h=wE(u);return!h.endsWith(".log")&&!h.includes(".bak")}}),ee.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ee.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of _E){let c=Yt(i,o),d=Yt(r,o);try{await Sd(d);continue}catch{}try{if(o==="cozeloop.env"){let h=(await pE(c,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
107
+ `);await mE(d,h,{mode:384})}else await hE(c,d);ee.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ee.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var Id="acceptEdits",hh="full-access",xh="read-only";function EE(t){return{INITIAL_AGENT_MODE:ko(t)}}var vE=(t,e,r,i,o,c,d,u,h,x,m,w)=>{switch(t){case"claude-code":{let v={...o?{...l0(o),...h0(o,d,u,w)}:{},...h??{},IS_SANDBOX:"1"};return new Ao({cwd:r,env:v,agentId:i})}case"codex":{let v=hh;x!==void 0&&(Bt("codex",x)?v=x:ee.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...o?{...f0(o),...u0(o,d,u,w)}:{},...EE(v),...o?{NO_BROWSER:"1"}:{},...h??{},...o?{COZELAB_ONBOARD_CLOUD:"true"}:{}},E=!!o;return new To({cwd:r,agentId:i,...Object.keys(_).length>0?{env:_}:{},...E?{authMethodId:"api-key",isolateCodexHome:!0,...m?{codexHomeDir:m}:{}}:{}})}case"openclaw":return new Hr({command:e,cwd:r,agentId:i,...c?{sessionName:Ed(c)}:{}})}};function vd(t){return t==="claude-code"||t==="codex"}function SE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(IE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
108
+ `)}
109
+ `}function IE(t){if(t.includes(`
110
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var AE={path:"",version:"cloud-deployed"},lh="openclaw_gateway_unavailable",kE="openclaw_default_agent_missing";function uh(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var TE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},CE=6e4,Lo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Map;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??vE,this.createTimeoutMs=e.createTimeoutMs??CE,this.detectorFactory=e.detectorFactory??(()=>new Xn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Po({command:r,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??Yt(fh(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{ee.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=Yt(e,".env");if(await Sd(r).then(c=>c.isFile()).catch(()=>!1)){ee.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=SE({...process.env,...$i(this.paths.agentEnvFile)});await un(r,o,{mode:384}),ee.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ee.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new A("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new A("IPC_BAD_REQUEST","framework required");let i=await Ce(e.agentId,this.paths).catch(()=>null),o=po(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new A("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")ee.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(k=>ee.warn("dispose stale agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")ee.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(k=>ee.warn("dispose drifted agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){ee.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let k=await Ce(e.agentId,this.paths).catch(()=>null);k&&(k.patToken=e.patToken,await ze(k,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){ee.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let k=await Ce(e.agentId,this.paths).catch(()=>null);k&&(k.modelInfo=e.modelInfo,await ze(k,this.paths))}return ee.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Fe(e.agentId,this.paths),h=o?"cloud":"local",x=e.framework==="openclaw"&&h==="local",m;x&&!r?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=m??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??w??u.workspace,_=new AbortController,E=setTimeout(()=>_.abort(new A("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),S,I=!1;try{o&&vd(e.framework)&&await hr(e.framework,_.signal);let k=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new A("AGENT_TIMEOUT","_agent/create aborted")};await Oo(u.root,{recursive:!0}),await Oo(v,{recursive:!0}),await Oo(u.logs,{recursive:!0}),k(),x||await xr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await qa(v,"cloud"):await qa(v,"local",Id)),k();let R=i,b=c0({model:e.model??R?.model}),D=Vf(e._meta)??R?.accountId,O=e.patToken??R?.patToken,F=h==="cloud"?e.modelInfo??R?.modelInfo:void 0;if(S=new Co({agentId:e.agentId,framework:e.framework,workspace:v,model:b.model??Nt,deployType:h,...D?{accountId:D}:{},...O?{patToken:O}:{},...F?{modelInfo:F}:{}}),S.status="ok",R?.sessions){let K=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,te]of Object.entries(R.sessions)){let oe={acpSessionId:te.acpSessionId,modelToken:te.modelToken,tokenGeneratedAt:te.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?te.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",ee.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Y,framework:e.framework,fallback:oe.permissionMode})):Bt(e.framework,te.permissionMode)?oe.permissionMode=te.permissionMode:ee.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:te.permissionMode}):te.permissionMode!==void 0&&ee.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:h}),te.cozeGroupId&&(oe.cozeGroupId=te.cozeGroupId),te.tokenGroupId&&(oe.tokenGroupId=te.tokenGroupId),te.requestScene&&(oe.requestScene=te.requestScene),S.sessions.set(Y,oe)}let ie=Object.keys(R.sessions).length;ie>0&&ee.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(S),I=!0;let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:R?.createdAt??Date.now(),sessions:R?.sessions??{},model:b.model};if(h==="cloud"&&(M.deployType="cloud"),D&&(M.accountId=D),O&&(M.patToken=O),F&&(M.modelInfo=F),R?.skills&&(M.skills=R.skills),R?.agentName&&(M.agentName=R.agentName),R?.description&&(M.description=R.description),M.skillsRefreshedForVersion=R?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ee.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await dh(v)&&ee.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(K){ee.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(K)})}}let V=e.initialSkills??[];if(V.length>0){let K=[...M.skills??[]],ie=new Map(K.map((oe,P)=>[oe.skillId,P])),Y=await Promise.allSettled(V.map(oe=>yo({agentId:e.agentId,workspace:v,framework:e.framework,skill:oe}))),te=0;for(let[oe,P]of Y.entries()){let U=V[oe];U&&(P.status==="fulfilled"?(bo(K,ie,P.value),te++):ee.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(P.reason)}))}te>0&&(M.skills=K,ee.info("initialSkills installed",{agentId:e.agentId,installed:te,requested:V.length}))}return await ze(M,this.paths),ee.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(k){throw ee.error("agent create failed, rolling back",{agentId:e.agentId,err:String(k)}),I&&S&&(await S.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await gE(u.root,{recursive:!0,force:!0}).catch(R=>ee.warn("rm agent dir failed (ignored)",{err:String(R)})),k instanceof A?k:new A("AGENT_SPAWN_FAILED",String(k),{cause:k})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,r,i,o,c,d){let h=this.config.frameworksCache?.[e.framework];if(!h)if(e.deployType==="cloud"&&vd(e.framework))h=AE;else throw new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);vd(e.framework)&&!bs(e.framework)&&(ee.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await hr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,m;if(e.framework==="openclaw")m=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:c,requestScene:d,command:h.path});else{let w=e.sessions.get(i),v=Xt(e)?w?.permissionMode??hh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await bE(e.agentId,this.paths),m=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),v,e.framework==="codex"&&e.deployType==="cloud"?Yt(Fe(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await m.start(),await m.initialize(TE),m}catch(w){let v=m instanceof Mt?m.getStderrTail():[];throw v.length>0&&ee.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof A?w.code:"unknown",recentStderr:v}),await m.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,h.path,w)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new A("AGENT_ENV_NOT_READY",uh(o),{cause:{reason:lh}})}catch(o){ee.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof A?i:new A("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};ee.warn("openclaw default agent stale or missing, attempting lazy re-detect");let r=await this.detectorFactory().detect("openclaw");if(r?.defaultAgent?.id&&r.defaultAgent.workspace)return ee.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new A("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:kE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new A("AGENT_ENV_NOT_READY",uh(r),{cause:{reason:lh}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,requestScene:u,command:h}=e,x=Ed(o);if(r.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Hr({command:h,cwd:v.workspace,agentId:v.id,sessionName:x})}let m=await ch();try{let v=this.getOpenclawConfig();await v.ensureAcpDeviceScopes()&&await v.restartGateway()}catch(v){ee.warn("acp device scope ensure failed (ignored)",{err:String(v)})}let w;if(i?.modelToken){let v=id(o),_=sd(i),E=`${v}/${_}`,S=JSON.stringify({modelConfig:i,cozeEnv:c,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(E)!==S){let I=this.getOpenclawConfig(),k=await I.getAllowlistModelsForProvider(v),R=x0(i,c,d,k,u);R&&(await I.ensureProvider(v,R),await I.addModelToAllowlist(E),this.ensuredProviders.set(E,S))}w=E}return new Hr({command:h,cwd:r.workspace,agentId:r.agentId,sessionName:x,...m?{gatewayToken:m}:{},...w?{slashModelOnStart:w}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e,r){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=r??e.model;for(let c of e.sessions.keys()){let d=id(c),u=`${d}/${o}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,ee.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,ee.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as _h}from"node:crypto";import{promises as ME}from"node:fs";import{basename as yh}from"node:path";Ke();re();import{promises as RE}from"node:fs";import{basename as DE}from"node:path";var ph=G("file-upload"),PE="/api/coze_claw/file/agent_upload",OE=6e4;async function gh(t,e={}){let i=`${Pr(Or(e.handshakeBase))}${PE}`,o=e.timeoutMs??OE,c=await RE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),o);ph.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),w=m.headers.get("x-tt-logid")??"";if(!m.ok){let E=await m.text().catch(()=>"");throw new A("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${w}: ${E.slice(0,200)}`)}let v=await m.json();if(v.code!==void 0&&v.code!==0)throw new A("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${w}`);let _=v.data?.file?.file_url;if(!_)throw new A("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(v).slice(0,200)}`);return ph.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(m){throw m instanceof A?m:m.name==="AbortError"?new A("UPLOAD_FAILED",`upload timeout (${o}ms) for ${DE(t.path)}`):new A("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(x)}}Ke();re();import{extname as LE}from"node:path";var NE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function mh(t){let e=LE(t).toLowerCase();return NE[e]??"application/octet-stream"}Te();var No=G("agent-send"),wh=50*1024*1024;function bh(t,e,r){let i=t.get(e);if(!i)throw new A("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new A("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new A("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function Eh(t,e,r,i,o,c){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,h<2&&(No.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(m=>setTimeout(m,5e3)))}throw new A("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function vh(t,e){let{session:r,runtime:i}=bh(e.core,t.agentId,t.sessionId);if(!await di(t.path,r.workspace))throw new A("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await ME.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new A("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>wh)throw new A("FILE_TOO_LARGE",`${o.size} bytes > limit ${wh}`);let c=await mh(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new A("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??yh(t.path),u;try{u=await gh({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw No.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof A?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:_h(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(e,r,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),No.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Sh(t,e){let{session:r,runtime:i}=bh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new A("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??yh(t.path),c={sessionUpdate:"group_file",messageId:_h(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Eh(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),No.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function Ih(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let d=r[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}Zt();re();dn();var Ft=G("coze-cli-installer"),Ah="@coze/cli@latest",BE="coze",kh="0.1.8",FE=5e3,zE=5e3,UE=9e4,Th=1e4,Zi=null,Mo=!1;async function kd(t,e={}){if(Mo)return;if(Zi)return Zi;let r=e.exec??e0;return Zi=(async()=>{try{let i=await HE(BE,r),o=!1;if(i){let d=await GE(r);if(d===void 0)Ft.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Ih(d,kh))Ft.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:kh}),o=!0;else{Ft.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Mo=!0;return}}let c=o?"upgrade-only":"full";Ft.info("coze-cli install start",{package:Ah,mode:c});try{await r("npm",["i","-g","--prefer-online",Ah],{timeout:UE,maxBuffer:10*1024*1024}),Ft.info("coze-cli install ok")}catch(d){Ft.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Mo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:Th}),Ft.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Ft.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:Th}),Ft.info("coze auth login ok")}catch(d){Ft.warn("coze auth login failed",{err:String(d)});return}Mo=!0}finally{Zi=null}})(),Zi}async function HE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:FE});return Ha(i)}catch{return}}async function GE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:zE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}hn();Te();var qE=10*6e4;function Ch(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?qE:e}function Bo(t){return ln(t??Z().configFile)}function Xi(t,e){return fn(e??Z().configFile,t)}import{randomBytes as dv}from"node:crypto";dr();Ke();re();import{createReadStream as jE}from"node:fs";import{mkdir as WE,readFile as KE,realpath as $E,stat as VE,writeFile as JE}from"node:fs/promises";import{basename as ZE,dirname as Td,isAbsolute as XE,join as YE,relative as QE,resolve as Rh,sep as ev}from"node:path";import{createInterface as tv}from"node:readline";var Ph=G("fs-rpc"),Yi=Xe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Oh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Yi)throw new A("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Yi} bytes`);let i=await Nh(t.path,e);return await WE(Td(i),{recursive:!0}),await JE(i,t.content,"utf8"),Ph.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Lh(t,e){let r=await Nh(t.path,e),i=await VE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Yi&&!o)throw new A("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Yi} bytes`);let c;if(o&&i.size>Yi)c=await nv(r,t.line??1,t.limit);else{let d=await KE(r,"utf8");if(o){let u=d.split(`
111
+ `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,x).join(`
112
+ `)}else c=d}return Ph.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function nv(t,e,r){let i=tv({input:jE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=o&&u<c&&d.push(h),u++,u>=c)break}finally{i.close()}return d.join(`
113
+ `)}async function Nh(t,e){if(typeof t!="string"||t.length===0)throw new A("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([Dh(Rh(e)),Dh(Rh(t))]),o=QE(r,i);if(rv(o,ev,XE(o)))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function rv(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Dh(t){let e=[],r=t;for(;r!==Td(r);)try{let i=await $E(r);return e.length?YE(i,...e.reverse()):i}catch{e.push(ZE(r)),r=Td(r)}return t}re();var Mh=G("prompt-multimodal"),Bh=10*1024*1024,iv=15e3,sv=6;async function Fh(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,d=t[c];d!==void 0&&(e[c]=await ov(d))}}let o=Array.from({length:Math.min(sv,t.length)},()=>i());return await Promise.all(o),e}function zh(t){return t.some(e=>e.type==="image")}async function ov(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!zi(e.uri))return t;try{let{buf:r,contentType:i}=await cv(e.uri),o=e.mimeType||av(i)||"application/octet-stream";return Mh.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:o}),{type:"image",data:r.toString("base64"),mimeType:o}}catch(r){return Mh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function av(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function cv(t){let e=new AbortController,r=setTimeout(()=>e.abort(),iv);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>Bh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Bh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}xn();Ke();re();var W=G("core"),lv=3e4,uv=/^(boe|ppe)_[A-Za-z0-9_-]+$/,fv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",hv="\u5BA1\u6279\u5DF2\u8D85\u65F6",xv=3e4,Fo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Br;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Ch(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Gr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(Cn(o,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:X.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new A("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(vo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&uv.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,c=Jf(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);c&&u!==c?(this.requestSceneBySession.set(d,c),W.info("cached request_scene for session",{sessionId:d,requestScene:c})):!c&&u!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let h=await u(e,this);r!==null&&await this.upstream.send(Mr(r,h));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Mr(r,u));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Mr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(u){W.error("handleFrame failed",{method:e.method,err:String(u)}),r!==null&&await this.upstream.send(Cn(r,Ki(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new A("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new A("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new A("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new A("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let h=o.sessions.get(c);if(h?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,m=go(r._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,fv,x,m)}}let d=Date.now(),u=!1;try{let h=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,h}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Xf(i);switch(r){case"session/new":{let c=pv();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Xt(e)?Zf(i._meta):void 0;if(u!==void 0&&!Bt(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${wd(e.framework)}`);let h=go(i._meta),x=this.requestSceneBySession.get(d),m=await this.ensureRuntime(e,d,h,x);if(u!==void 0&&m.permissionMode===void 0&&(m.permissionMode=u,await this.persistSessionMapping(e)),m.replySeq=0,await this.ensureDownstream(e,d,m),!m.downstream||!m.acpSessionId)throw new A("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&m.permissionMode!==void 0&&m.permissionMode!==u){let _=m.permissionMode;m.permissionMode=u,await this.persistSessionMapping(e);try{await m.downstream.setSessionMode({sessionId:m.acpSessionId,modeId:u})}catch(E){throw m.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),E}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(m.acpSessionId,w):e.activeTriggers.delete(m.acpSessionId),h?e.activeGroupIds.set(m.acpSessionId,h):e.activeGroupIds.delete(m.acpSessionId),h&&m.cozeGroupId!==h&&(m.cozeGroupId=h,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&zh(c.prompt))throw new A("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let v=await Fh(c.prompt);try{let _=await m.downstream.sessionPrompt({...c,sessionId:m.acpSessionId,prompt:v});return m.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof A&&_.code==="AGENT_APPROVAL_TIMEOUT"){let E=m.pendingPermission;E&&(E.downstream.respondAgentRequest(E.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(E.upstreamId),m.pendingPermission=void 0);let S=m.acpSessionId,I=S?e.activeTriggers.get(S):void 0,k=S?e.activeGroupIds.get(S):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,m,d,hv,I,k)}throw _}finally{if(e.activeTriggers.delete(m.acpSessionId),e.activeGroupIds.delete(m.acpSessionId),m.pendingPermission=void 0,m.reloadAfterTurn){m.reloadAfterTurn=!1;let _=m.downstream;_&&(m.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:m.acpSessionId}),_.stop("reload-after-turn").catch(E=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(E)})))}else m.downstream?.isAlive()&&this.armIdleTimer(e,d,m)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new A("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,h=go(i._meta);if(!d)throw new A("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Xt(e))throw e.framework==="openclaw"?new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new A("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Bt(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${wd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let m=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(w){throw x.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),w}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new A("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&c.push({downstream:u,acpSessionId:h,oldMode:d.oldMode,runtime:d.runtime})}for(let d of c)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let h of o)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r,i,o){let c=e.sessions.get(r);if(c){let h=c.cozeGroupId!==i,x=e.deployType==="cloud"&&c.tokenGroupId!==i,m=c.requestScene!==o;if(x&&(c.modelToken=await this.requestSessionToken(e.agentId,r,i),c.tokenGeneratedAt=Date.now(),c.tokenGroupId=i),x||m){Gr(c);let w=c.downstream;c.downstream=void 0,w&&await w.stop("request-context-changed")}return c.cozeGroupId=i,c.requestScene=o,(h||x||m)&&await this.persistSessionMapping(e),c}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return Xt(e)&&(u.permissionMode=e.framework==="claude-code"?Id:xh),e.sessions.set(r,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,r,i){let o={sessionId:r,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let c=await this.sendRequest(ht.GEN_MODEL_TOKEN,o,xv);if(!c?.modelToken)throw new A("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return c.modelToken}catch(c){throw c instanceof A&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new A("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,r,i){if(Gr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new A("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new A("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let h;try{let x=this.requestSceneBySession.get(r);x&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:r,requestScene:x}),h=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=h,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let m=await h.sessionNew({cwd:e.workspace});i.acpSessionId=m.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Xt(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Gr(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let d=e.activeTriggers.get(r.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Nr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Nr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(wv(r)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=r.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Xt(e)){let m=d.currentModeId;Bt(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(w=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof m=="string"&&!Bt(e.framework,m)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:m})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Nr("session/update",{...r,sessionId:o,_meta:u})).catch(m=>W.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await Oh(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await Lh(c,o);r.respondAgentRequest(i.id,d)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Ki(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let m=u?e.activeGroupIds.get(u):void 0;m&&(x.cozeGroupId=m);let w=u?this.reverseSessionId(e,u):void 0,v=w?e.sessions.get(w):void 0;v&&(v.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...c,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:w}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:w,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(ji(o,"session/request_permission",_)).catch(E=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),r.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&gv(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new Eo(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),d=e.get(c);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=lv){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(ji(o,e,r)).catch(h=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Xt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),o.tokenGroupId&&(c.tokenGroupId=o.tokenGroupId),o.requestScene&&(c.requestScene=o.requestScene),r.set(i,c)}await li(e.agentId,r,this.paths)}catch(r){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(Cn(e,{code:r,message:i,data:{bridgeVersion:Lt}}))}};function pv(){return dv(16).toString("hex")}function gv(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var mv=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."],Uh="Warning: ";function wv(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let o=i.text.startsWith(Uh)?i.text.slice(Uh.length):i.text;return mv.some(c=>o.startsWith(c))}hn();re();Te();import{randomBytes as _v}from"node:crypto";import{createServer as yv}from"node:http";var bv=1e6,Hh=G("ipc"),zo=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Z()}async start(){this.token=_v(32).toString("hex");let e=yv((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),Hh.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(o=>o?i(o):r())}),this.server=null)}async persistAuthFiles(){await un(this.paths.portFile,String(this.port)),await un(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Qi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Qi(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Ev(e)}catch(u){Qi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Qi(r,200,u??{ok:!0})}catch(u){Hh.error("IPC handler failed",{key:o,err:String(u)}),Qi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Qi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function Ev(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>bv)throw new Error("body too large");e.push(c)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var GS=qt(Bx(),1),qS=qt(Vo(),1),jS=qt(Kr(),1),WS=qt(zd(),1),KS=qt(Gd(),1),$S=qt(Vd(),1),Kx=qt(Yo(),1),VS=qt(Wx(),1);var $x=Kx.default;Ke();re();var{FWS:l1}=ip(),De=G("upstream.frontier"),op="application/json",ap="none",u1=15e3;function f1(t){class e extends $x{constructor(i){super(i,n0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>De.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(Fl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let d=Buffer.from(c.slice(0,128)).toString("hex");De.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){De.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var cs=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){De.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:r0,...kn(this.opts.ppeOverride)},r=f1(e),i=s0(this.opts.urlOverride),o={url:i,ws:r,fpID:t0,aID:mo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:op,force:!0},payloadEncoding:{encoding:ap,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new l1(o),d=!1,u=null,h,x,m=new Promise((_,E)=>{h=_,x=E}),w=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;De.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&w();for(let E of this.connectHandlers)Promise.resolve(E({initial:_})).catch(S=>De.warn("onConnect handler threw (ignored)",{err:String(S)}))},c.onclose=_=>{this.opened=!1,De.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{De.warn("frontier error",{code:_.code,msg:_.message}),w(new A("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let v=this.opts.openTimeoutMs??u1;u=setTimeout(()=>{w(new A("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await m}catch(_){try{c.close(1e3,"open failed")}catch(E){De.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){De.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw De.warn("frontier send refused: upstream not started",{method:i}),new A("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(De.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new A("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;cp(c)||De.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:op,payloadEncoding:ap})}catch(u){throw De.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new A("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){De.debug("drop non-adapter frontier frame",{service:r});return}let i=p1(e);if(!i){De.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){De.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){De.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;cp(c)||De.info("frontier frame in",{logid:x1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:h1(i)}),Promise.resolve(this.handler(o)).catch(d=>De.warn("frontier frame handler threw",{err:String(d)}))}};function cp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var dp=2e3;function h1(t){return t.length<=dp?t:`${t.slice(0,dp)}...<truncated, total ${t.length} chars>`}function x1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function p1(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}Ke();re();var Yd=G("skill-publish"),g1="/api/marketplace/product/skill/publish_with_assets",m1=15e4;async function lp(t,e={}){let i=`${Pr(Or(e.handshakeBase))}${g1}`,o=e.timeoutMs??m1,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);Yd.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),m=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new A("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${m}: ${_.slice(0,200)}`)}let w=await x.json();if(Yd.info("skill publish response",{logid:m,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new A("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${m}`);let v={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(v.skillId=String(w.data.skill_id)),w.data?.version&&(v.version=w.data.version),Yd.info("skill publish ok",{logid:m,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof A?x:x.name==="AbortError"?new A("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new A("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}re();var Qd=G("upstream.switchable"),aa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Qd.info("swap upstream",{reason:r});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw Qd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Qd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};re();var el=G("upstream"),Yr=class{handler=null;async start(){el.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){el.info("NoopUpstream stopped",{reason:e})}async send(e){el.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ke();re();hn();re();Te();import{promises as w1}from"node:fs";var up=G("pat-token-store");async function ca(t=Z()){try{let r=(await w1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(up.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):r}catch(e){let r=e?.code;return r!=="ENOENT"&&up.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ds(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await un(e.patTokenFile,t,{mode:384})}Te();Te();import{promises as da}from"node:fs";import{join as _1}from"node:path";function y1(t,e){return`#!/bin/sh
116
114
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
117
- `}function tS(t,e){return`@echo off\r
115
+ `}function b1(t,e){return`@echo off\r
118
116
  "${e}" "${t}" %*\r
119
- `}async function lp(t,e=J()){let r=e.binDir;await aa.mkdir(r,{recursive:!0});let i=Q1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?tS(t,o):eS(t,o);return await aa.readFile(i,"utf8").catch(()=>null)===c||(await aa.writeFile(i,c,"utf8"),process.platform!=="win32"&&await aa.chmod(i,493)),r}te();Ce();import{execSync as up}from"node:child_process";import{readFileSync as fp,unlinkSync as nS}from"node:fs";import{mkdir as rS,open as iS,readFile as xp,unlink as Yd,writeFile as sS}from"node:fs/promises";import{dirname as oS}from"node:path";var aS=j("single-instance"),cS=t=>new Promise(e=>setTimeout(e,t)),ca=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&&aS.warn("removing stale pid file",{stalePid:i}),await sS(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 xp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Yd(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 xp(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 rS(oS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await iS(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 cS(this.claimLockIntervalMs);continue}await Yd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Yd(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=fp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Fr)||r.includes("lib/index.js"))}catch{}try{let r=up(`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=up(`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{fp(this.pidFile,"utf8").trim()===String(this.selfPid)&&nS(this.pidFile)}catch{}})}};da();te();var nr=j("daemon.upstream-watchdog"),gS=12e4,mS=9e5,wS=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 la=class{constructor(e){this.opts=e;this.softMs=e.softMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",gS),this.hardMs=e.hardMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",mS),this.intervalMs=e.intervalMs??Xd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",wS),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 K=j("daemon");async function gp(){let t=J();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Rl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:R=>Fe(R,t).logs,listAgentIds:()=>ys(t)});try{let{writeFileSync:R}=await import("node:fs");R(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
117
+ `}async function fp(t,e=Z()){let r=e.binDir;await da.mkdir(r,{recursive:!0});let i=_1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?b1(t,o):y1(t,o);return await da.readFile(i,"utf8").catch(()=>null)===c||(await da.writeFile(i,c,"utf8"),process.platform!=="win32"&&await da.chmod(i,493)),r}re();Te();import{execSync as hp}from"node:child_process";import{readFileSync as xp,unlinkSync as E1}from"node:fs";import{mkdir as v1,open as S1,readFile as pp,unlink as tl,writeFile as I1}from"node:fs/promises";import{dirname as A1}from"node:path";var k1=G("single-instance"),T1=t=>new Promise(e=>setTimeout(e,t)),la=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Z().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Vi(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&k1.warn("removing stale pid file",{stalePid:i}),await I1(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return r.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),r}async release(){if(this.acquired){try{(await pp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await tl(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let r=await pp(e,"utf8"),i=Number.parseInt(r.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(r){if(r.code==="ENOENT")return null;throw r}}async withClaimLock(e){let r=`${this.pidFile}.lock`;await v1(A1(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await S1(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(r);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await T1(this.claimLockIntervalMs);continue}await tl(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await tl(r).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${r} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=xp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Fr)||r.includes("lib/index.js"))}catch{}try{let r=hp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Fr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=hp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{xp(this.pidFile,"utf8").trim()===String(this.selfPid)&&E1(this.pidFile)}catch{}})}};ua();re();var ir=G("daemon.upstream-watchdog"),M1=12e4,B1=9e5,F1=3e4;function rl(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var fa=class{constructor(e){this.opts=e;this.softMs=e.softMs??rl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",M1),this.hardMs=e.hardMs??rl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",B1),this.intervalMs=e.intervalMs??rl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",F1),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),ir.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&ir.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&ir.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,ir.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){ir.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:r,hardMs:this.hardMs}),this.opts.onFatal(r);return}r>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,ir.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>ir.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var q=G("daemon");async function wp(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Ml({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Fe(P,t).logs,listAgentIds:()=>Es(t)});try{let{writeFileSync:P}=await import("node:fs");P(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
120
118
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
121
119
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
122
- `)}catch{}}let e=new ca({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 No(),o=i??{};ms({pid:process.pid}),K.info(i?"loaded bridge config":"initialized bridge config");let c=new sa(new Yr),d=null,u=new Mo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(R,G,W,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(R,G,W,ee)}}),x=new Do({paths:t,config:o,registry:u});d=x;let h,m,w=null,I={},b,S=null,A=null,k=null,P=new kn;function L(R,G){return P.enqueue(()=>D(R,G))}function E(){A||(A=new la({isConnected:()=>c.isConnected()&&!(S?.isLivenessLost()??!1),forceReconnect:()=>k?L(k,{force:!0}):void 0,onFatal:R=>{if(process.env[ds]==="1"){K.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:R});return}K.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:R}),process.exit(1)}})),A.start()}async function D(R,G){let W=R,ee=W?.privatecode;if(!ee)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Ve=zi(W.env),pe=W.handshake_url,ge=W.frontier_url,kt=pp(W.env,pe,ge);if(k=W,!G?.force&&h===ee&&m===kt){let _e=await _S(t);return u.agents.size===0&&_e?(K.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),fa(t,x).catch(ke=>K.warn("connect-noop auto-revive error (ignored)",{err:String(ke)}))):K.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let wt=!!h&&h!==ee,rn=m!==void 0&&m!==kt,Ut=wt||rn,sn=await Xc({privatecode:ee,...pe?{endpoint:pe}:{},ppeOverride:Ve});if(Ut){K.warn("connect config switched, resetting agents",{pcChanged:wt,envChanged:rn,previousPc:h?ua(h):"",nextPc:ua(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 Yr,"connect switch").catch(()=>{})}w=sn.deviceId,ms({deviceId:w,pid:process.pid}),bd({patToken:ee,env:W.env}).catch(_e=>K.warn("coze-cli setup error (ignored)",{err:String(_e)}));let ei=new as({handshake:sn,privatecode:ee,...ge?{urlOverride:ge}:{},ppeOverride:Ve,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(ei,"connect"),h=ee,m=kt,I=Ve,b=pe,W.mock_scenario!==void 0&&(u.setMockScenario(W.mock_scenario),K.info("mock scenario set",{scenario:W.mock_scenario})),S||(S=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(_e=>K.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:Y})),S.start(),E(),Ut&&fa(t,x).catch(_e=>K.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),cs(ee,t).catch(_e=>K.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),K.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async R=>x.createAgent(R.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let N={},z=new _o({agents:u.agents,paths:t,publishSkillToMarketplace:async R=>{let G=u.agents.get(R.agentId)?.patToken??h;if(!G)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return cp({patToken:G,zip:R.zip,...R.skillId?{skillId:R.skillId}:{},skillName:R.skillName,...R.description?{description:R.description}:{},agentId:R.agentId,...R.accountId?{accountId:R.accountId}:{}},{handshakeBase:b,ppeOverride:I})},disposeAndMarkDisconnected:async(R,G)=>{let W=u.agents.get(R);if(W){await x.cleanupOpenclawSessionProviders(W).catch(Ve=>K.warn("cleanup openclaw providers failed (ignored)",{agentId:R,err:String(Ve)})),W.framework==="hermes"&&W.deployType==="cloud"&&await id(R,t).catch(Ve=>K.warn("cleanup hermes-home failed (ignored)",{agentId:R,err:String(Ve)}));let ee=!0;try{await W.dispose(`disconnect: ${G}`)}catch(Ve){ee=!1,K.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:R,err:String(Ve)}),W.status="error"}ee&&(W.status="disconnected",u.unregister(R),u.disconnectedAgents.add(R))}else u.disconnectedAgents.add(R)},disposeForDelete:async(R,G)=>{let W=u.agents.get(R);W&&(await x.cleanupOpenclawSessionProviders(W).catch(ee=>K.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:R,err:String(ee)})),W.framework==="hermes"&&W.deployType==="cloud"&&await id(R,t).catch(ee=>K.warn("cleanup hermes-home during delete failed (ignored)",{agentId:R,err:String(ee)})),await W.dispose(`delete: ${G}`).catch(ee=>K.warn("dispose during delete failed (ignored)",{agentId:R,err:String(ee)})),u.unregister(R)),u.disconnectedAgents.delete(R)},detailSyncer:async R=>{if(!N.ref)throw new Error("agent-detail-sync not initialized yet");await N.ref.syncOne(R)},cleanupOpenclawProviders:async(R,G)=>{await x.cleanupOpenclawSessionProviders(R,G)},openclawRepair:async(R,G)=>{await x.openclawRepair(R,G)},hermesReset:async(R,G)=>{let W=await ve(R).catch(()=>null);!W||W.framework!=="hermes"||W.deployType!=="cloud"||await f0({paths:t,agentId:R,model:W.model,modelInfo:W.modelInfo,cozeEnv:G,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:R=>u.hasPendingPermissionFor(R)});u.registerExtension("_agent/listSkills",R=>z.listSkills(R.params)),u.registerExtension("_agent/addSkills",R=>z.addSkills(R.params)),u.registerExtension("_agent/removeSkills",R=>z.removeSkills(R.params)),u.registerExtension("_agent/publishSkill",R=>z.publishSkill(R.params)),u.registerExtension("_agent/getFileTree",R=>z.getFileTree(R.params)),u.registerExtension("_agent/getFileContent",R=>z.getFileContent(R.params)),u.registerExtension("_agent/update",R=>z.updateAgent(R.params)),u.registerExtension("_agent/disconnect",R=>z.disconnectAgent(R.params)),u.registerExtension("_agent/switchModel",R=>z.switchModel(R.params)),u.registerExtension("_agent/reset",R=>z.resetAgent(R.params)),u.registerExtension("_agent/repair",R=>z.repairAgent(R.params)),u.registerExtension("_agent/delete",R=>z.deleteAgent(R.params)),u.registerExtension("_agent/upgrade",R=>z.upgradeBridge(R.params));let B=new vs({paths:t,handlers:z,agentManager:x,sendDetail:R=>u.sendRequest("_agent/detail",R)});N.ref=B;let Y=async R=>{await Promise.allSettled(R.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(W){K.warn("disconnect during authFailure handling failed (ignored)",{agentId:G.agentId,err:String(W)})}}))};c.onConnect(({initial:R})=>{K.info("frontier upstream connected, triggering detail sync",{initial:R}),B.syncAll(R?"initial-connect":"reconnect").catch(G=>K.warn("detail sync top-level error (ignored)",{err:String(G)}))});let V=new Bo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let R=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ds]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...R?{mockScenario:R}:{}}}},{method:"POST",path:"/pair",handler:async R=>{let G=R,W=G?.privatecode,ee=G?.pairing_code;if(!W||!ee)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ve=zi(G.env),pe=G.handshake_url,ge=G.frontier_url,kt=pp(G.env,pe,ge),wt=!!h&&h!==W,rn=m!==void 0&&m!==kt,Ut=wt||rn,sn=await Xc({privatecode:W,...pe?{endpoint:pe}:{},ppeOverride:Ve});if(Ut){K.warn("pair config switched, resetting agents",{pcChanged:wt,envChanged:rn,previousPc:h?ua(h):"",nextPc:ua(W),previousEnvKey:m??"",nextEnvKey:kt});for(let ke of[...u.agents.values()])await ke.dispose("pair config switch").catch(()=>{}),u.agents.delete(ke.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 Yr,"pair switch").catch(()=>{})}w=sn.deviceId,ms({deviceId:w,pid:process.pid}),bd({patToken:W,env:G.env}).catch(ke=>K.warn("coze-cli setup error (ignored)",{err:String(ke)}));let ei=new as({handshake:sn,privatecode:W,...ge?{urlOverride:ge}:{},ppeOverride:Ve,getPatTokenForAgent:ke=>u.agents.get(ke)?.patToken});await c.swap(ei,"pair");try{let ke=new Jn;o.frameworksCache=await ke.detectAll(),await Ji(o),K.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(ke){K.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ke)})}let _e=Object.keys(o.frameworksCache??{});try{let ke=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:W,frameworks:_e,_meta:{cozeDeviceId:w}});K.info("_agent/pair ok",{pairResult:ke}),h=W,m=kt,I=Ve,b=pe,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),K.info("mock scenario set",{scenario:G.mock_scenario})),cs(W,t).catch(Le=>K.warn("writePatToken after /pair failed (ignored)",{err:String(Le)})),S||(S=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(Le=>K.warn("detailSync.retryPending failed (ignored)",{err:String(Le)})),onAuthFailures:Y})),S.start(),E(),Ut&&fa(t,x).catch(Le=>K.warn("post-pair-switch auto-revive error (ignored)",{err:String(Le)}));let rr;return G.agent_id&&(rr=await bS(G.agent_id,t,x,Le=>u.sendRequest("_agent/detail",Le),W).catch(Le=>(K.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(Le)}),{ok:!1,agentId:G.agent_id??"",note:String(Le)}))),{ok:!0,note:"paired with cloud",...rr?{agent:rr}:{}}}catch(ke){return K.error("_agent/pair failed",{err:String(ke)}),{ok:!1,note:`pair failed: ${String(ke)}`}}}},{method:"POST",path:"/connect",handler:R=>L(R)},{method:"POST",path:"/_agent/create",handler:async R=>{let G=R;return{ok:!0,result:await x.createAgent(G)}}},{method:"POST",path:"/agent/send",handler:async R=>{let G=R;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 W=G;return await(W.groupFile?vx:Ex)(W,{core:u,patToken:h,handshakeBase:b,ppeOverride:I})}catch(W){if(W instanceof T)return{ok:!1,code:W.code,message:W.message};throw W}}},{method:"POST",path:"/reload",handler:async R=>{let G=R?.agent_id,W=await u.reloadAgents(G);return K.info("IPC /reload: recycled agent subprocesses",{agentId:G??"(all)",recycled:W}),{ok:!0,recycled:W}}},{method:"POST",path:"/shutdown",handler:async()=>(K.info("IPC /shutdown received"),setImmediate(()=>{ce.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:Z}=await V.start();try{await lp(t.libEntry,t)}catch(R){K.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(R)})}await u.start(),ES({paths:t,core:u,agentManager:x,detectAll:async()=>(o.frameworksCache=await new Jn().detectAll(),await Ji(o),o.frameworksCache)}).catch(R=>K.warn("startup warmup error (ignored)",{err:String(R)})),Hl().then(async()=>{let{probeAcpVersion:R}=await Promise.resolve().then(()=>(ln(),zl));for(let G of["claude-code","codex"]){let W=await R(G);W&&K.info("acp wrapper version",{framework:G,version:W})}}).catch(R=>K.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(R)}));let oe=null,ce={port:re,token:Z,core:u,ipc:V,shutdown(R){return oe||(K.info("daemon shutdown",{reason:R}),oe=(async()=>{S?.stop(),A?.stop(),await u.stop(R),await V.stop(),await e.release()})(),oe)}};for(let R of["SIGTERM","SIGINT"])process.on(R,()=>{ce.shutdown(R).then(()=>process.exit(0))});return process.on("exit",()=>U0()),process.on("unhandledRejection",R=>{K.error("unhandledRejection",{reason:R instanceof Error?R.message:String(R),stack:R instanceof Error?R.stack:void 0})}),process.on("uncaughtException",R=>{K.error("uncaughtException (will exit, supervisor will restart)",{message:R.message,stack:R.stack,name:R.name});try{process.stderr.write(`FATAL uncaughtException: ${R.stack??R.message}
123
- `)}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"}),SS({cliSpawned:process.env[ds]==="1",readPatToken:()=>oa(t),connect:L}).catch(R=>K.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(R)})),ce}async function _S(t){return ys(t).length>0}function ua(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function pp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function yS(t,e){let r=ys(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(qt(),Es));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 bS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(qt(),Es)),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 m=mp(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await r.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}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 ES(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 yS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await fa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await vS(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function fa(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(),Es));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=mp(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 vS(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 T0(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 SS(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 mp(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}da();Ce();import{readFile as wp}from"node:fs/promises";var nn=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:AS(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,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:IS(x)}}finally{clearTimeout(d)}}};async function xa(t){try{let[e,r]=await Promise.all([wp(t.portFile,"utf8"),wp(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 IS(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function AS(t){return t instanceof Error?t.message:String(t)}Jt();te();ar();import{spawn as kS}from"node:child_process";import{userInfo as yp}from"node:os";var Zd="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",TS=new Set(["bash","zsh","sh","dash","ksh"]),_p=Ye("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),CS=2e3;function PS(t,e=Zd){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(`
124
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function RS(){let t=(process.env.SHELL??"").trim()||(yp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return TS.has(e)?t:null}function DS(t){return new Promise(e=>{let r=`printf '%s' '${Zd}'; env; printf '%s' '${Zd}'`,i;try{i=kS(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??yp().homedir}})}catch{e(null);return}let o="",c=!1,d=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(x),clearTimeout(h),e(m))};i.stdout?.on("data",m=>{o+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let x=setTimeout(()=>d("SIGTERM"),_p),h=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},_p+CS)})}async function Qd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=RS();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??DS)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=PS(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Ce();function Pn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||r.push(c)}return{value:i,rest:r}}ln();import{chmod as OS,copyFile as bp,mkdir as vp,readFile as us,rename as Ep,rm as nl,stat as Sp,writeFile as LS}from"node:fs/promises";import{homedir as gO}from"node:os";import{dirname as NS,join as Oe,resolve as rl,sep as ls}from"node:path";import{fileURLToPath as MS}from"node:url";Jt();te();Ce();function Jr(t,e,r,i){nt(t.bridgeLogsDir,e,"dist-install",r,i)}function Ip(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function BS(){return{darwin:{arm64:Oe("vendor","aarch64-apple-darwin","bin","codex"),x64:Oe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Oe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Oe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Oe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Oe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function FS(t){let e=MS(t),r=NS(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=FS(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 S=JSON.parse(await us(o,"utf8"));c=S.version??"unknown",d=S.dependencies??{}}catch(S){throw Jr(e,"error","cannot read source package.json",{err:String(S)}),new Error(`cannot read source package.json: ${String(S)}`,{cause:S})}let u=ws.map(S=>({name:S,spec:d[S]??"latest"})),x=u.map(({name:S,spec:A})=>`${S}@${A}`),h=await No(e.configFile)??{},m=h.libVersion,w=await us(e.libEntry).then(()=>!0).catch(()=>!1),I=m===c,b=await Ap(e,u);if(I&&w&&b)return{kind:"already-current",libVersion:c};if(!I||!w){await vp(e.libDir,{recursive:!0}),await bp(i,e.libEntry),await bp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let S=rl(e.libDir,"package.json"),A=`${JSON.stringify({type:"module"},null,2)}
125
- `;await us(S,"utf8").catch(()=>null)!==A&&await LS(S,A)}return b||(t.installWrappers?await t.installWrappers(e,x):await HS(e,x,u)),h.libVersion=c,await Ji(h,e.configFile),Jr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),I&&w?{kind:"already-current",libVersion:c}:m?{kind:"version-changed",fromVersion:m,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Ap(t,e){for(let r of e){let i=Oe(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await us(i,"utf8"))}catch(d){return Jr(t,"debug","wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(d)}),!1}let c=o.version;if(!c)return Jr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!zS(c,r.spec))return Jr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await kp(Oe(t.libDir,"node_modules"))}function zS(t,e){let r=el(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=el(i.slice(1));if(!c)return!0;if(tl(r,c)<0)return!1;let d=US(c);return tl(r,d)<0}let o=el(i);return o?tl(r,o)===0:!0}function US(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function el(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function tl(t,e){for(let r=0;r<3;r++){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return 0}async function HS(t,e,r){await jS(t.installLock,async()=>{if(await Ap(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ls}.staging-${process.pid}-${i}`,c=Oe(o,"node_modules"),d=Oe(t.libDir,"node_modules");try{await vp(o,{recursive:!0}),await GS(e,o),await qS(c);let u=`${d}.trash-${i}`;await Ep(d,u).catch(()=>{}),await Ep(c,d),await nl(u,{recursive:!0,force:!0}).catch(()=>{}),Jr(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await nl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function GS(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=it("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 qS(t){for(let e of ws){let r=Oe(t,...e.split("/")),i=JSON.parse(await us(Oe(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=Oe(t,".bin",o),d=await Sp(c);process.platform!=="win32"&&!(d.mode&73)&&await OS(c,d.mode|73).catch(()=>{})}if(!await kp(t)){let e=Ip()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function kp(t){let e=Ip(),r=BS();if(!e||!r)return!0;let i=Oe(t,"@openai","codex"),o=Oe(t,...e.split("/")),c=[Oe(i,"package.json"),Oe(i,"bin","codex.js"),Oe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Oe(o,"package.json"),Oe(o,r)];return(await Promise.all(c.map(u=>Sp(u).then(x=>x.isFile()).catch(()=>!1)))).every(Boolean)}async function jS(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await nl(t,{force:!0}).catch(()=>{})}}Na();te();Ce();import{closeSync as Cp,fstatSync as Pp,openSync as Rp,readFileSync as WS,readSync as KS,readdirSync as $S,statSync as VS}from"node:fs";import{join as ha}from"node:path";var YS=new Set(["debug","info","warn","error"]);function Dp(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 d=Pn(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&&YS.has(c.value)?c.value:void 0,m={lines:x,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(m.agentId=r.value),i.value&&(m.date=i.value),h&&(m.level=h),d.value&&(m.grep=d.value),m}function JS(t,e){return t.agentId?ha(Fe(t.agentId,e).logs,cr("agent",t.date)):ha(e.bridgeLogsDir,cr("bridge",t.date))}function XS(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function ZS(t,e){let r;try{r=$S(t)}catch{return[]}let i=[];for(let o of r){let c=La(o,e);if(!c)continue;let d=0;try{d=VS(ha(t,o)).size}catch{}i.push({file:ha(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Op(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 Tp={debug:"90",info:"36",warn:"33",error:"31"},QS=new Set(["ts","level","module","msg"]);function e2(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Lp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=e2(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Tp[o]&&(c=`\x1B[${Tp[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])=>!QS.has(h)).map(([h,m])=>` ${h}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${x}`}function t2(t,e,r){let c=WS(t,"utf8").split(`
126
- `).filter(d=>d.length>0).filter(d=>Op(d,{level:e.level,grep:e.grep}));for(let d of XS(c,e.lines))process.stdout.write(`${Lp(d,{raw:e.raw,color:r})}
127
- `)}async function Np(t,e){let r=e.paths??J(),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=ZS(d,u);if(x.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
128
- `),1;for(let h of x)process.stdout.write(`${h.date} ${(h.size/1024).toFixed(1)}KB ${h.file}
129
- `);return 0}let o=t.date??Dn(new Date),c=JS({agentId:t.agentId,date:o},r);try{t2(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
120
+ `)}catch{}}let e=new la({processTitle:Fr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Bo(),o=i??{};ws({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new aa(new Yr),d=null,u=new Fo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,U,j,ne,Ve,le)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,U,j,ne,Ve,le)}}),h=new Lo({paths:t,config:o,registry:u});d=h;let x,m,w=null,v={},_,E=null,S=null,I=null,k=new Rn;function R(P,U){return k.enqueue(()=>D(P,U))}function b(){S||(S=new fa({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>I?R(I,{force:!0}):void 0,onFatal:P=>{if(process.env[ls]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),S.start()}async function D(P,U){let j=P,ne=j?.privatecode;if(!ne)throw new A("IPC_BAD_REQUEST","/connect requires privatecode");let Ve=Hi(j.env),le=j.handshake_url,pe=j.frontier_url,At=mp(j.env,le,pe);if(I=j,!U?.force&&x===ne&&m===At){let we=await z1(t);return u.agents.size===0&&we?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),xa(t,h).catch(Ae=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Ae)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let gt=!!x&&x!==ne,sn=m!==void 0&&m!==At,Gt=gt||sn,on=await Qc({privatecode:ne,...le?{endpoint:le}:{},ppeOverride:Ve});if(Gt){q.warn("connect config switched, resetting agents",{pcChanged:gt,envChanged:sn,previousPc:x?ha(x):"",nextPc:ha(ne)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Yr,"connect switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),kd({patToken:ne,env:j.env}).catch(we=>q.warn("coze-cli setup error (ignored)",{err:String(we)}));let ri=new cs({handshake:on,privatecode:ne,...pe?{urlOverride:pe}:{},ppeOverride:Ve,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await c.swap(ri,"connect"),x=ne,m=At,v=Ve,_=le,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),q.info("mock scenario set",{scenario:j.mock_scenario})),E||(E=new qi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(we=>q.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:V})),E.start(),b(),Gt&&xa(t,h).catch(we=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),ds(ne,t).catch(we=>q.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),q.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>h.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},F=new _o({agents:u.agents,publishSkillToMarketplace:async P=>{let U=u.agents.get(P.agentId)?.patToken??x;if(!U)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return lp({patToken:U,zip:P.zip,...P.skillId?{skillId:P.skillId}:{},skillName:P.skillName,...P.description?{description:P.description}:{},agentId:P.agentId,...P.accountId?{accountId:P.accountId}:{}},{handshakeBase:_,ppeOverride:v})},disposeAndMarkDisconnected:async(P,U)=>{let j=u.agents.get(P);if(j){await h.cleanupOpenclawSessionProviders(j).catch(Ve=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Ve)}));let ne=!0;try{await j.dispose(`disconnect: ${U}`)}catch(Ve){ne=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Ve)}),j.status="error"}ne&&(j.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,U)=>{let j=u.agents.get(P);j&&(await h.cleanupOpenclawSessionProviders(j).catch(ne=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(ne)})),await j.dispose(`delete: ${U}`).catch(ne=>q.warn("dispose during delete failed (ignored)",{agentId:P,err:String(ne)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(P)},cleanupOpenclawProviders:async(P,U)=>{await h.cleanupOpenclawSessionProviders(P,U)},openclawRepair:async(P,U)=>{await h.openclawRepair(P,U)},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>F.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>F.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>F.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>F.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>F.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>F.getFileContent(P.params)),u.registerExtension("_agent/update",P=>F.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>F.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>F.switchModel(P.params)),u.registerExtension("_agent/reset",P=>F.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>F.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>F.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>F.upgradeBridge(P.params));let M=new Is({paths:t,handlers:F,agentManager:h,sendDetail:P=>u.sendRequest("_agent/detail",P)});O.ref=M;let V=async P=>{await Promise.allSettled(P.map(async U=>{try{await F.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(j){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(j)})}}))};c.onConnect(({initial:P})=>{q.info("frontier upstream connected, triggering detail sync",{initial:P}),M.syncAll(P?"initial-connect":"reconnect").catch(U=>q.warn("detail sync top-level error (ignored)",{err:String(U)}))});let K=new zo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let P=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[ls]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let U=P,j=U?.privatecode,ne=U?.pairing_code;if(!j||!ne)throw new A("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ve=Hi(U.env),le=U.handshake_url,pe=U.frontier_url,At=mp(U.env,le,pe),gt=!!x&&x!==j,sn=m!==void 0&&m!==At,Gt=gt||sn,on=await Qc({privatecode:j,...le?{endpoint:le}:{},ppeOverride:Ve});if(Gt){q.warn("pair config switched, resetting agents",{pcChanged:gt,envChanged:sn,previousPc:x?ha(x):"",nextPc:ha(j),previousEnvKey:m??"",nextEnvKey:At});for(let Ae of[...u.agents.values()])await Ae.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ae.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Yr,"pair switch").catch(()=>{})}w=on.deviceId,ws({deviceId:w,pid:process.pid}),kd({patToken:j,env:U.env}).catch(Ae=>q.warn("coze-cli setup error (ignored)",{err:String(Ae)}));let ri=new cs({handshake:on,privatecode:j,...pe?{urlOverride:pe}:{},ppeOverride:Ve,getPatTokenForAgent:Ae=>u.agents.get(Ae)?.patToken});await c.swap(ri,"pair");try{let Ae=new Xn;o.frameworksCache=await Ae.detectAll(),await Xi(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ae){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ae)})}let we=Object.keys(o.frameworksCache??{});try{let Ae=await u.sendRequest("_agent/pair",{pairCode:ne,patToken:j,frameworks:we,_meta:{cozeDeviceId:w}});q.info("_agent/pair ok",{pairResult:Ae}),x=j,m=At,v=Ve,_=le,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),q.info("mock scenario set",{scenario:U.mock_scenario})),ds(j,t).catch(Oe=>q.warn("writePatToken after /pair failed (ignored)",{err:String(Oe)})),E||(E=new qi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>M.retryPending().catch(Oe=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Oe)})),onAuthFailures:V})),E.start(),b(),Gt&&xa(t,h).catch(Oe=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(Oe)}));let sr;return U.agent_id&&(sr=await H1(U.agent_id,t,h,Oe=>u.sendRequest("_agent/detail",Oe),j).catch(Oe=>(q.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Oe)}),{ok:!1,agentId:U.agent_id??"",note:String(Oe)}))),{ok:!0,note:"paired with cloud",...sr?{agent:sr}:{}}}catch(Ae){return q.error("_agent/pair failed",{err:String(Ae)}),{ok:!1,note:`pair failed: ${String(Ae)}`}}}},{method:"POST",path:"/connect",handler:P=>R(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let U=P;return{ok:!0,result:await h.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async P=>{let U=P;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new A("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=U;return await(j.groupFile?Sh:vh)(j,{core:u,patToken:x,handshakeBase:_,ppeOverride:v})}catch(j){if(j instanceof A)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async P=>{let U=P?.agent_id,j=await u.reloadAgents(U);return q.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ie,token:Y}=await K.start();try{await fp(t.libEntry,t)}catch(P){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),G1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new Xn().detectAll(),await Xi(o),o.frameworksCache)}).catch(P=>q.warn("startup warmup error (ignored)",{err:String(P)})),Kl().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(dn(),jl));for(let U of["claude-code","codex"]){let j=await P(U);j&&q.info("acp wrapper version",{framework:U,version:j})}}).catch(P=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let te=null,oe={port:ie,token:Y,core:u,ipc:K,shutdown(P){return te||(q.info("daemon shutdown",{reason:P}),te=(async()=>{E?.stop(),S?.stop(),await u.stop(P),await K.stop(),await e.release()})(),te)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{oe.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>H0()),process.on("unhandledRejection",P=>{q.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{q.error("uncaughtException (will exit, supervisor will restart)",{message:P.message,stack:P.stack,name:P.name});try{process.stderr.write(`FATAL uncaughtException: ${P.stack??P.message}
121
+ `)}catch{}process.exit(1)}),q.info("daemon ready",{port:ie,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),j1({cliSpawned:process.env[ls]==="1",readPatToken:()=>ca(t),connect:R}).catch(P=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),oe}async function z1(t){return Es(t).length>0}function ha(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function mp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function U1(t,e){let r=Es(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(xn(),Ss));for(let c of r){await o(c,t).catch(d=>q.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),q.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),q.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){q.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function H1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(xn(),Ss)),d=await c(t,e);if(d){if(d.deletedAt)throw new A("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let m=_p(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await r.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}q.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new A("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function G1(t){let e=t.logger??q;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await U1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await xa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await q1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function xa(t,e){let{readdir:r}=await import("node:fs/promises"),i;try{i=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(xn(),Ss));q.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let h;try{h=await o(u,t)}catch(x){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=_p(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return q.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function q1(t){let{readdir:e}=await import("node:fs/promises"),r;try{r=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(r.length===0)return{refreshed:0,total:0};let i=0;for(let o of r)try{(await C0(o,t)).status==="refreshed"&&(i+=1)}catch(c){q.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&q.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function j1(t){let e=t.logger??q;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function _p(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ua();Te();import{readFile as yp}from"node:fs/promises";var rn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let r=await pa(this.paths);if(!r)return{kind:"not-running"};try{let i=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...r,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:K1(i)}}}async request(e){let r=await pa(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),h=await u.text();return{status:u.status,body:W1(h)}}finally{clearTimeout(d)}}};async function pa(t){try{let[e,r]=await Promise.all([yp(t.portFile,"utf8"),yp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=r.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function W1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function K1(t){return t instanceof Error?t.message:String(t)}Zt();re();dr();import{spawn as $1}from"node:child_process";import{userInfo as Ep}from"node:os";var il="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",V1=new Set(["bash","zsh","sh","dash","ksh"]),bp=Xe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),J1=2e3;function Z1(t,e=il){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let d of o.split(`
122
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function X1(){let t=(process.env.SHELL??"").trim()||(Ep().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return V1.has(e)?t:null}function Y1(t){return new Promise(e=>{let r=`printf '%s' '${il}'; env; printf '%s' '${il}'`,i;try{i=$1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Ep().homedir}})}catch{e(null);return}let o="",c=!1,d=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(h),clearTimeout(x),e(m))};i.stdout?.on("data",m=>{o+=m.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let h=setTimeout(()=>d("SIGTERM"),bp),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},bp+J1)})}async function sl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=X1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??Y1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=Z1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Te();function On(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||r.push(c)}return{value:i,rest:r}}dn();import{chmod as Q1,copyFile as vp,mkdir as Ip,readFile as fs,rename as Sp,rm as cl,stat as Ap,writeFile as eI}from"node:fs/promises";import{homedir as g3}from"node:os";import{dirname as tI,join as Pe,resolve as dl,sep as us}from"node:path";import{fileURLToPath as nI}from"node:url";Zt();re();Te();function Qr(t,e,r,i){rt(t.bridgeLogsDir,e,"dist-install",r,i)}function kp(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function rI(){return{darwin:{arm64:Pe("vendor","aarch64-apple-darwin","bin","codex"),x64:Pe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Pe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Pe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Pe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Pe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function iI(t){let e=nI(t),r=tI(e),i=`${us}src${us}`;if(r.includes(i)||r.endsWith(`${us}src${us}cli`))return null;let o=dl(r,"index.js"),c=dl(r,"..","package.json");return{dist:o,pkgJson:c}}async function ll(t={}){let e=t.paths??Z(),r=iI(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let E=JSON.parse(await fs(o,"utf8"));c=E.version??"unknown",d=E.dependencies??{}}catch(E){throw Qr(e,"error","cannot read source package.json",{err:String(E)}),new Error(`cannot read source package.json: ${String(E)}`,{cause:E})}let u=ys.map(E=>({name:E,spec:d[E]??"latest"})),h=u.map(({name:E,spec:S})=>`${E}@${S}`),x=await Bo(e.configFile)??{},m=x.libVersion,w=await fs(e.libEntry).then(()=>!0).catch(()=>!1),v=m===c,_=await Tp(e,u);if(v&&w&&_)return{kind:"already-current",libVersion:c};if(!v||!w){await Ip(e.libDir,{recursive:!0}),await vp(i,e.libEntry),await vp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let E=dl(e.libDir,"package.json"),S=`${JSON.stringify({type:"module"},null,2)}
123
+ `;await fs(E,"utf8").catch(()=>null)!==S&&await eI(E,S)}return _||(t.installWrappers?await t.installWrappers(e,h):await aI(e,h,u)),x.libVersion=c,await Xi(x,e.configFile),Qr(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:m,toVersion:c}),v&&w?{kind:"already-current",libVersion:c}:m?{kind:"version-changed",fromVersion:m,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Tp(t,e){for(let r of e){let i=Pe(t.libDir,"node_modules",...r.name.split("/"),"package.json"),o;try{o=JSON.parse(await fs(i,"utf8"))}catch(d){return Qr(t,"debug","wrapper not ready: package.json read failed",{package:r.name,expected:r.spec,pkgJson:i,err:String(d)}),!1}let c=o.version;if(!c)return Qr(t,"debug","wrapper not ready: package.json \u7F3A version",{package:r.name,expected:r.spec,pkgJson:i}),!1;if(!sI(c,r.spec))return Qr(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:r.name,installed:c,expected:r.spec}),!1}return!!await Cp(Pe(t.libDir,"node_modules"))}function sI(t,e){let r=ol(t);if(!r)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let c=ol(i.slice(1));if(!c)return!0;if(al(r,c)<0)return!1;let d=oI(c);return al(r,d)<0}let o=ol(i);return o?al(r,o)===0:!0}function oI(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function ol(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function al(t,e){for(let r=0;r<3;r++){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return 0}async function aI(t,e,r){await lI(t.installLock,async()=>{if(await Tp(t,r))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${us}.staging-${process.pid}-${i}`,c=Pe(o,"node_modules"),d=Pe(t.libDir,"node_modules");try{await Ip(o,{recursive:!0}),await cI(e,o),await dI(c);let u=`${d}.trash-${i}`;await Sp(d,u).catch(()=>{}),await Sp(c,d),await cl(u,{recursive:!0,force:!0}).catch(()=>{}),Qr(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await cl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function cI(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=st("npm",r,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",h=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(h)}`))}),c.once("close",h=>{clearTimeout(u),h===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function dI(t){for(let e of ys){let r=Pe(t,...e.split("/")),i=JSON.parse(await fs(Pe(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=Pe(t,".bin",o),d=await Ap(c);process.platform!=="win32"&&!(d.mode&73)&&await Q1(c,d.mode|73).catch(()=>{})}if(!await Cp(t)){let e=kp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Cp(t){let e=kp(),r=rI();if(!e||!r)return!0;let i=Pe(t,"@openai","codex"),o=Pe(t,...e.split("/")),c=[Pe(i,"package.json"),Pe(i,"bin","codex.js"),Pe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Pe(o,"package.json"),Pe(o,r)];return(await Promise.all(c.map(u=>Ap(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function lI(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await cl(t,{force:!0}).catch(()=>{})}}Ba();re();Te();import{closeSync as Dp,fstatSync as Pp,openSync as Op,readFileSync as uI,readSync as fI,readdirSync as hI,statSync as xI}from"node:fs";import{join as ga}from"node:path";var pI=new Set(["debug","info","warn","error"]);function Lp(t){let e=t,r=On(e,"--agent-id");e=r.rest;let i=On(e,"--date");e=i.rest;let o=On(e,"-n","--lines");e=o.rest;let c=On(e,"--level");e=c.rest;let d=On(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),h=Number.isInteger(u)&&u>=0?u:200,x=c.value&&pI.has(c.value)?c.value:void 0,m={lines:h,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(m.agentId=r.value),i.value&&(m.date=i.value),x&&(m.level=x),d.value&&(m.grep=d.value),m}function gI(t,e){return t.agentId?ga(Fe(t.agentId,e).logs,lr("agent",t.date)):ga(e.bridgeLogsDir,lr("bridge",t.date))}function mI(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function wI(t,e){let r;try{r=hI(t)}catch{return[]}let i=[];for(let o of r){let c=Ma(o,e);if(!c)continue;let d=0;try{d=xI(ga(t,o)).size}catch{}i.push({file:ga(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function Np(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!zl(r,e.level))return!1}return!0}var Rp={debug:"90",info:"36",warn:"33",error:"31"},_I=new Set(["ts","level","module","msg"]);function yI(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Mp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=yI(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Rp[o]&&(c=`\x1B[${Rp[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",h=Object.entries(r).filter(([x])=>!_I.has(x)).map(([x,m])=>` ${x}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function bI(t,e,r){let c=uI(t,"utf8").split(`
124
+ `).filter(d=>d.length>0).filter(d=>Np(d,{level:e.level,grep:e.grep}));for(let d of mI(c,e.lines))process.stdout.write(`${Mp(d,{raw:e.raw,color:r})}
125
+ `)}async function Bp(t,e){let r=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Fe(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=wI(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
126
+ `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
127
+ `);return 0}let o=t.date??Nn(new Date),c=gI({agentId:t.agentId,date:o},r);try{bI(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
130
128
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
131
129
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
132
- `),1}return t.follow&&await i2(c,t,i),0}var n2=500;function r2(t){try{let e=Rp(t,"r");try{return Pp(e).size}finally{Cp(e)}}catch{return 0}}async function i2(t,e,r){let i=r2(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let x=Rp(t,"r");try{let h=Pp(x).size;if(h>i){let m=Buffer.allocUnsafe(h-i),w=KS(x,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{Cp(x)}}catch{}if(u){let x=(o+u).split(`
133
- `);o=x.pop()??"";for(let h of x)h.length>0&&Op(h,{level:e.level,grep:e.grep})&&process.stdout.write(`${Lp(h,{raw:e.raw,color:r})}
134
- `)}await new Promise(x=>setTimeout(x,n2))}}finally{process.off("SIGINT",d)}}import{basename as s2,resolve as o2}from"node:path";Ce();var a2=9e4,c2={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 d2(t){return c2[t]??1}async function Mp(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>
130
+ `),1}return t.follow&&await SI(c,t,i),0}var EI=500;function vI(t){try{let e=Op(t,"r");try{return Pp(e).size}finally{Dp(e)}}catch{return 0}}async function SI(t,e,r){let i=vI(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=Op(t,"r");try{let x=Pp(h).size;if(x>i){let m=Buffer.allocUnsafe(x-i),w=fI(h,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{Dp(h)}}catch{}if(u){let h=(o+u).split(`
131
+ `);o=h.pop()??"";for(let x of h)x.length>0&&Np(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Mp(x,{raw:e.raw,color:r})}
132
+ `)}await new Promise(h=>setTimeout(h,EI))}}finally{process.off("SIGINT",d)}}import{basename as II,resolve as AI}from"node:path";Te();var kI=9e4,TI={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1,SKILL_NOT_FOUND:1,SKILL_ZIP_TOO_LARGE:1};function CI(t){return TI[t]??1}async function Fp(t,e={}){let r=e.paths??Z();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
135
133
  `),4;if(t.groupFile&&!t.mimeType)return process.stderr.write(`Error: --group-file requires --mime <mimeType> (e.g. application/pdf, image/png). No local file is read in group-file mode, mime cannot be auto-detected.
136
- `),3;let i=await 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.
137
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:o2(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 l2(i,"/agent/send",o,a2)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
134
+ `),3;let i=await pa(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
135
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:AI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},c;try{c=await RI(i,"/agent/send",o,kI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
138
136
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
139
- `),d2(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
140
- `);else{let d=t.name??s2(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})
141
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${u2(c.bytes)})
142
- `)}return 0}async function l2(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 u2(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Kp=j("cli");function We(t,e){let{value:r,rest:i}=Pn(t,e);return{value:r,rest:i}}function ya(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
143
- `)}function N2(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:L}=We(e.slice(1),"--agent-id");return L?{mode:"reload",agentId:L}:{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 M2(e.slice(1));if(e[0]==="log")return{mode:"log",...Dp(e.slice(1))};if(e[0]==="connect")return B2(e.slice(1));if(e.includes("--status"))return ya("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ya("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return ya("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ya("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=We(r,"--pat-token");r=o;let{value:c,rest:d}=We(r,"--pair-code");r=d;let{value:u,rest:x}=We(r,"--env");r=x;let{value:h,rest:m}=We(r,"--handshake-url");r=m;let{value:w,rest:I}=We(r,"--frontier-url");r=I;let{value:b,rest:S}=We(r,"--mock-scenario");r=S;let{value:A}=We(r,"--agent-id"),k=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let P={mode:"pair",privatecode:i,pairingCode:c};return u&&(P.env=u),h&&(P.handshakeUrl=h),w&&(P.frontierUrl=w),b&&(P.mockScenario=b),A&&(P.agentId=A),k&&(P.skipRebuildEnv=!0),P}function M2(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=We(i,"--caption");i=c;let{value:d,rest:u}=We(i,"--name");i=u;let{value:x,rest:h}=We(i,"--agent-id");i=h;let{value:m,rest:w}=We(i,"--session-id");i=w;let{value:I,rest:b}=We(i,"--mime");i=b;let S=i.includes("--group-file");i=i.filter(P=>P!=="--group-file");let A=i.includes("--json"),k={mode:"send",kind:e,path:r,json:A};return o&&(k.caption=o),d&&(k.name=d),x&&(k.agentId=x),m&&(k.sessionId=m),S&&(k.groupFile=!0),I&&(k.mimeType=I),k}function B2(t){let e=t,{value:r,rest:i}=We(e,"--pat-token");e=i;let{value:o,rest:c}=We(e,"--env");e=c;let{value:d,rest:u}=We(e,"--handshake-url");e=u;let{value:x,rest:h}=We(e,"--frontier-url");e=h;let{value:m,rest:w}=We(e,"--mock-scenario");e=w;let I=e.includes("--skip-rebuild-env"),b={mode:"connect"};return r&&(b.privatecode=r),o&&(b.env=o),d&&(b.handshakeUrl=d),x&&(b.frontierUrl=x),m&&(b.mockScenario=m),I&&(b.skipRebuildEnv=!0),b}var F2=`
137
+ `),CI(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
138
+ `);else{let d=t.name??II(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
139
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${DI(c.bytes)})
140
+ `)}return 0}async function RI(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function DI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Vp=G("cli");function We(t,e){let{value:r,rest:i}=On(t,e);return{value:r,rest:i}}function Ea(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
141
+ `)}function tA(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:R}=We(e.slice(1),"--agent-id");return R?{mode:"reload",agentId:R}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return nA(e.slice(1));if(e[0]==="log")return{mode:"log",...Lp(e.slice(1))};if(e[0]==="connect")return rA(e.slice(1));if(e.includes("--status"))return Ea("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ea("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ea("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ea("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=We(r,"--pat-token");r=o;let{value:c,rest:d}=We(r,"--pair-code");r=d;let{value:u,rest:h}=We(r,"--env");r=h;let{value:x,rest:m}=We(r,"--handshake-url");r=m;let{value:w,rest:v}=We(r,"--frontier-url");r=v;let{value:_,rest:E}=We(r,"--mock-scenario");r=E;let{value:S}=We(r,"--agent-id"),I=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let k={mode:"pair",privatecode:i,pairingCode:c};return u&&(k.env=u),x&&(k.handshakeUrl=x),w&&(k.frontierUrl=w),_&&(k.mockScenario=_),S&&(k.agentId=S),I&&(k.skipRebuildEnv=!0),k}function nA(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=We(i,"--caption");i=c;let{value:d,rest:u}=We(i,"--name");i=u;let{value:h,rest:x}=We(i,"--agent-id");i=x;let{value:m,rest:w}=We(i,"--session-id");i=w;let{value:v,rest:_}=We(i,"--mime");i=_;let E=i.includes("--group-file");i=i.filter(k=>k!=="--group-file");let S=i.includes("--json"),I={mode:"send",kind:e,path:r,json:S};return o&&(I.caption=o),d&&(I.name=d),h&&(I.agentId=h),m&&(I.sessionId=m),E&&(I.groupFile=!0),v&&(I.mimeType=v),I}function rA(t){let e=t,{value:r,rest:i}=We(e,"--pat-token");e=i;let{value:o,rest:c}=We(e,"--env");e=c;let{value:d,rest:u}=We(e,"--handshake-url");e=u;let{value:h,rest:x}=We(e,"--frontier-url");e=x;let{value:m,rest:w}=We(e,"--mock-scenario");e=w;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),d&&(_.handshakeUrl=d),h&&(_.frontierUrl=h),m&&(_.mockScenario=m),v&&(_.skipRebuildEnv=!0),_}var iA=`
144
142
  coze-bridge - local bridge daemon for cloud Agent Service
145
143
 
146
144
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -221,57 +219,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
221
219
 
222
220
  Internal:
223
221
  <node> <entry> --daemon daemon mode (OS supervisor only)
224
- `.trimStart();async function $p(t=process.argv,e={}){let r=N2(t);switch(r.mode){case"help":return process.stdout.write(F2),0;case"version":return process.stdout.write(`${Lt}
225
- `),0;case"daemon":{try{await gp()}catch(i){return Kp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return z2(e);case"stop":return Yp(e);case"reload":return G2(r.agentId,e);case"log":return Np(r,e);case"update":return U2(e);case"purge":return j2(e);case"service-install":return W2(e);case"service-uninstall":return K2(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),$2(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),V2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Mp({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 Vp(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 z2(t){let e=t.paths??J(),r=new nn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
226
- `),1;if(i.kind==="stale")return await Vp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
222
+ `.trimStart();async function Jp(t=process.argv,e={}){let r=tA(t);switch(r.mode){case"help":return process.stdout.write(iA),0;case"version":return process.stdout.write(`${Lt}
223
+ `),0;case"daemon":{try{await wp()}catch(i){return Vp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return sA(e);case"stop":return Xp(e);case"reload":return cA(r.agentId,e);case"log":return Bp(r,e);case"update":return oA(e);case"purge":return lA(e);case"service-install":return uA(e);case"service-uninstall":return fA(e);case"pair":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),hA(r.privatecode,r.pairingCode,e,i,r.agentId,r.skipRebuildEnv)}case"connect":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),xA(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Fp({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function Zp(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function sA(t){let e=t.paths??Z(),r=new rn(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
224
+ `),1;if(i.kind==="stale")return await Zp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
227
225
  `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
228
226
  ${JSON.stringify(o.body,null,2)}
229
- `),0}async function Yp(t){let e=t.paths??J(),r=new nn(e),i=t.daemonSweep??(async()=>{let x=H0();return await G0(x),x}),o=async()=>{t.skipProcessKill||await i(e)},c=await xs(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(x){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(x)}
227
+ `),0}async function Xp(t){let e=t.paths??Z(),r=new rn(e),i=t.daemonSweep??(async()=>{let h=G0();return await q0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await xs(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
230
228
  `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
231
229
  `:`coze-bridge: not running
232
- `),0;if(u.kind==="stale")return await Vp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
230
+ `),0;if(u.kind==="stale")return await Zp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
233
231
  `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
234
- `),0}catch(x){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
235
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(x)}
236
- `),1)}}async function U2(t){return await Yp(t),(t.spawnNpx??H2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function H2(t){return new Promise(e=>{let r=it("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)}
237
- `),e(1)})})}async function G2(t,e){let r=new nn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
232
+ `),0}catch(h){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
233
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
234
+ `),1)}}async function oA(t){return await Xp(t),(t.spawnNpx??aA)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function aA(t){return new Promise(e=>{let r=st("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
235
+ `),e(1)})})}async function cA(t,e){let r=new rn(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
238
236
  `),1;try{let o=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
239
237
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
240
238
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
241
239
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
242
- `),1}}async function xs(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(qp(),Gp)),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??Y2,c=t.paths??J();if(r.kind==="connected"){if(!q2(r.body))return r;nt(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=>nt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(x)})),await Wp(c.pidFile,o)}let d=t.spawnDaemon??hp,u=await xs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let x=await jp(e,i,o);if(x.kind==="connected")return x;nt(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){nt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(x)})}nt(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 Wp(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)}
240
+ `),1}}async function xs(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Wp(),jp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Yp(t,e){let r=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??pA,c=t.paths??Z();if(r.kind==="connected"){if(!dA(r.body))return r;rt(c.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:r.body}),await e.request({method:"POST",path:"/shutdown"}).catch(h=>rt(c.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await $p(c.pidFile,o)}let d=t.spawnDaemon??gp,u=await xs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Kp(e,i,o);if(h.kind==="connected")return h;rt(c.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){rt(c.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}rt(c.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await $p(c.pidFile,o)}else u&&await u.install({activate:!1}).catch(h=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(h)}
243
241
  `));return process.stdout.write(`coze-bridge: starting daemon...
244
- `),await d({paths:t.paths}),jp(e,i,o)}function q2(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 j2(t){let e=new nn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
242
+ `),await d({paths:t.paths}),Kp(e,i,o)}function dA(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.nodeExecPath!="string"||typeof e.nodeArch!="string"?!1:e.nodeExecPath!==process.execPath||e.nodeArch!==process.arch}async function lA(t){let e=new rn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
245
243
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
246
244
  `)}await new Promise(d=>setTimeout(d,500))}let i=await xs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
247
245
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
248
- `)}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}
246
+ `)}let o=t.paths??Z(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
249
247
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
250
248
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
251
- `),0}async function W2(t){let e=await xs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
249
+ `),0}async function uA(t){let e=await xs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
252
250
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
253
251
  `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
254
- `),1}}async function K2(t){let e=await xs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
252
+ `),1}}async function fA(t){let e=await xs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
255
253
  `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
256
- `),1}}async function Xp(t,e,r){if(e)return nt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(nt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(nt(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
257
- `),nt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function $2(t,e,r,i={},o,c){let d=new nn(r.paths),u=r.paths??J(),x=await Xp(u,c,r.reconstructEnv??Qd);if(await Jc(u,x).catch(w=>nt(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}
258
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(b=>setTimeout(b,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
259
- `)}let h=await Jp(r,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
260
- `),1;let m={privatecode:t,pairing_code:e};i.env&&(m.env=i.env),i.handshakeUrl&&(m.handshake_url=i.handshakeUrl),i.frontierUrl&&(m.frontier_url=i.frontierUrl),i.mockScenario&&(m.mock_scenario=i.mockScenario),o&&(m.agent_id=o);try{let w=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let I=w.body.agent;return I&&!I.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${I.agentId}): ${I.note}
254
+ `),1}}async function Qp(t,e,r){if(e)return rt(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(rt(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(rt(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
255
+ `),rt(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function hA(t,e,r,i={},o,c){let d=new rn(r.paths),u=r.paths??Z(),h=await Qp(u,c,r.reconstructEnv??sl);if(await gd(u,h).catch(w=>rt(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!r.skipDistInstall){let w=await ll({paths:r.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
256
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
257
+ `)}let x=await Yp(r,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
258
+ `),1;let m={privatecode:t,pairing_code:e};i.env&&(m.env=i.env),i.handshakeUrl&&(m.handshake_url=i.handshakeUrl),i.frontierUrl&&(m.frontier_url=i.frontierUrl),i.mockScenario&&(m.mock_scenario=i.mockScenario),o&&(m.agent_id=o);try{let w=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let v=w.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
261
259
  `),1):(process.stdout.write(`\u5DF2\u914D\u5BF9\u8FDE\u63A5\u5B8C\u6210\uFF0C\u8BF7\u8FD4\u56DE\u5230 coze \u5E73\u53F0\u4E0A\u70B9\u51FB "\u6211\u5DF2\u6267\u884C"
262
260
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
263
261
  `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
264
- `),1}}async function V2(t,e,r={},i){let o=e.paths??J(),c=t??await oa(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 nn(e.paths),u=await Xp(o,i,e.reconstructEnv??Qd);if(await Jc(o,u).catch(m=>nt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await il({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
265
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(I=>setTimeout(I,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
266
- `)}let x=await Jp(e,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
267
- `),1;let h={privatecode:c};r.env&&(h.env=r.env),r.handshakeUrl&&(h.handshake_url=r.handshakeUrl),r.frontierUrl&&(h.frontier_url=r.frontierUrl),r.mockScenario&&(h.mock_scenario=r.mockScenario);try{let m=await d.request({method:"POST",path:"/connect",body:h,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
268
- `),t!==void 0&&await cs(c,o).catch(w=>Kp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
262
+ `),1}}async function xA(t,e,r={},i){let o=e.paths??Z(),c=t??await ca(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new rn(e.paths),u=await Qp(o,i,e.reconstructEnv??sl);if(await gd(o,u).catch(m=>rt(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await ll({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
263
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
264
+ `)}let h=await Yp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
265
+ `),1;let x={privatecode:c};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let m=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
266
+ `),t!==void 0&&await ds(c,o).catch(w=>Vp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
269
267
  `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
270
- `),1}}async function jp(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 Wp(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Ki(u))return;await e(i)}}function Y2(t){return new Promise(e=>setTimeout(e,t))}te();function J2(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function Zp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=J2(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
268
+ `),1}}async function Kp(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await r(200)}return t.probe(500)}async function $p(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Vi(u))return;await e(i)}}function pA(t){return new Promise(e=>setTimeout(e,t))}re();function gA(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function eg(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=gA(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
271
269
  `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
272
270
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
273
271
  npx -y coze-bridge@latest stop
274
272
  npx -y coze-bridge@latest connect
275
273
 
276
- `)}Zp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Dl("warn");$p(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
274
+ `)}eg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Bl("warn");Jp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
277
275
  `),process.exit(1)});