coze-bridge 0.2.0-beta.1 → 0.2.0-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 +85 -85
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var mg=Object.create;var Ea=Object.defineProperty;var wg=Object.getOwnPropertyDescriptor;var _g=Object.getOwnPropertyNames;var yg=Object.getPrototypeOf,Eg=Object.prototype.hasOwnProperty;var ue=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Qe=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ba=(t,e)=>{for(var r in e)Ea(t,r,{get:e[r],enumerable:!0})},bg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _g(e))!Eg.call(t,o)&&o!==r&&Ea(t,o,{get:()=>e[o],enumerable:!(i=wg(e,o))||i.enumerable});return t};var Ut=(t,e,r)=>(r=t!=null?mg(yg(t)):{},bg(e||!t||!t.__esModule?Ea(r,"default",{value:t,enumerable:!0}):r,t));function $e(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ir=Qe(()=>{"use strict"});import{createWriteStream as vg,mkdirSync as Sg,readdirSync as Ig,unlinkSync as Ag}from"node:fs";import{join as gd}from"node:path";function Pn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function sr(t,e){return`${t}-${e}.log`}function va(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function Tg(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 as(t,e,r,i){let o;try{o=Ig(t)}catch{return}for(let c of o){let d=va(c,e);if(d&&Tg(d,r,i))try{Ag(gd(t,c))}catch{}}}var Qr,Sa=Qe(()=>{"use strict";Qr=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Pn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{Sg(this.dir,{recursive:!0});let r=vg(gd(this.dir,sr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var wg=Object.create;var Ia=Object.defineProperty;var _g=Object.getOwnPropertyDescriptor;var yg=Object.getOwnPropertyNames;var bg=Object.getPrototypeOf,Eg=Object.prototype.hasOwnProperty;var ue=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var et=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Aa=(t,e)=>{for(var r in e)Ia(t,r,{get:e[r],enumerable:!0})},vg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yg(e))!Eg.call(t,o)&&o!==r&&Ia(t,o,{get:()=>e[o],enumerable:!(i=_g(e,o))||i.enumerable});return t};var Ut=(t,e,r)=>(r=t!=null?wg(bg(t)):{},vg(e||!t||!t.__esModule?Ia(r,"default",{value:t,enumerable:!0}):r,t));function $e(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var sr=et(()=>{"use strict"});import{createWriteStream as Sg,mkdirSync as Ig,readdirSync as Ag,unlinkSync as Tg}from"node:fs";import{join as _d}from"node:path";function Dn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function or(t,e){return`${t}-${e}.log`}function Ta(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function kg(t,e,r){let i=c=>{let[l,u,x]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,x??1)};return Math.floor((i(e)-i(t))/864e5)>r}function xs(t,e,r,i){let o;try{o=Ag(t)}catch{return}for(let c of o){let l=Ta(c,e);if(l&&kg(l,r,i))try{Tg(_d(t,c))}catch{}}}var ii,ka=et(()=>{"use strict";ii=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{Ig(this.dir,{recursive:!0});let r=Sg(_d(this.dir,or(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
9
  `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&as(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 kg,mkdirSync as Cg}from"node:fs";import{join as Rg}from"node:path";function wd(t){let e=t.retentionDays??Og,r=t.clock??(()=>Pn(new Date));ls={bridgeSink:new Qr(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new Qr(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();as(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])as(t.agentLogsDir(o),"agent",i,e)}function Lg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function _d(t){Ia=t}function yd(t){return or[Ia]<=or[t]}function Ed(t,e){let r=or[t];return r===void 0?!0:r>=or[e]}function ds(t){md={...t}}function bd(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`${Pn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function At(t,e,r,i,o){try{let c=`${JSON.stringify({ts:bd(new Date),level:e,module:r,msg:i,...o})}
11
- `;Cg(t,{recursive:!0}),kg(Rg(t,sr("bridge",Pn(new Date))),c)}catch{}}function Ng(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function cs(t,e,r,i,o){if(or[t]<or[Ia])return;let c=`${JSON.stringify({ts:bd(new Date),level:t,module:e,msg:r,...md,...i})}
12
- `;if(ls){let d=Ng(o,i),u=d?Lg(ls,d):ls.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Dg.write(c):Pg.write(c)}function H(t,e){return{debug:(r,i)=>cs("debug",t,r,i,e),info:(r,i)=>cs("info",t,r,i,e),warn:(r,i)=>cs("warn",t,r,i,e),error:(r,i)=>cs("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var or,Ia,Pg,Dg,md,Og,ls,te=Qe(()=>{"use strict";ir();Sa();or={debug:10,info:20,warn:30,error:40},Ia=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Pg=process.stdout,Dg=process.stderr,md={},Og=$e("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ls=null});var T,qe=Qe(()=>{"use strict";T=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Ad={};ba(Ad,{ACP_WRAPPER_NPM_PACKAGES:()=>ti,_resetAcpInstallerForTests:()=>Gg,_setBinaryPathCacheForTests:()=>Hg,buildAcpSpawn:()=>ni,ensureAcpInstalled:()=>ar,getAcpBinaryPath:()=>us,pickWhichLine:()=>ka,probeAcpVersion:()=>Ug,resolveAcpCommand:()=>Id});import{readFileSync as vd}from"node:fs";import{createRequire as Mg}from"node:module";import{dirname as Bg,resolve as Fg}from"node:path";function ka(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function zg(t){let e=Sd.resolve(`${t.npmPackage}/package.json`),r=Bg(e),i=JSON.parse(vd(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 Fg(r,o)}async function ar(t,e){let r=Ta[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ei.get(t);if(i)return i;try{let o=zg(r);return ei.set(t,o),Aa.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Aa.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 Ug(t){let e=Ta[t];if(e)try{let r=Sd.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(vd(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Aa.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function us(t){return ei.get(t)}function Id(t,e){if(e)return e;let r=us(t);if(!r)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ni(t,e,r){if(e)return{command:e,args:[...r]};let i=Id(t);return{command:process.execPath,args:[i,...r]}}function Gg(){ei.clear()}function Hg(t,e){ei.set(t,e)}var Aa,Ta,ti,Sd,ei,sn=Qe(()=>{"use strict";qe();te();Aa=H("agents.acp-installer"),Ta={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ti=Object.values(Ta).filter(t=>t!==void 0).map(t=>t.npmPackage),Sd=Mg(import.meta.url),ei=new Map});import{chmod as jg,mkdir as Wg,readFile as Kg,rename as $g,rm as Vg,writeFile as Jg}from"node:fs/promises";import{dirname as Zg}from"node:path";async function cr(t){try{let e=await Kg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function on(t,e,r){await Wg(Zg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Jg(i,e,{encoding:"utf8",mode:r?.mode}),await $g(i,t),r?.mode!==void 0&&await jg(t,r.mode)}catch(o){throw await Vg(i,{force:!0}).catch(()=>{}),o}}async function lr(t,e,r){await on(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var an=Qe(()=>{"use strict"});import{promises as Cd,readdirSync as Yg}from"node:fs";import{homedir as Xg}from"node:os";import{sep as Qg,join as Ae,resolve as Rd}from"node:path";function Q(t){let e=t??Xg(),r=Ae(e,".coze"),i=Ae(r,"bridge"),o=Ae(i,"lib"),c=Ae(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ae(o,"index.js"),binDir:Ae(i,"bin"),pidFile:Ae(i,"bridge.pid"),portFile:Ae(i,"bridge.port"),tokenFile:Ae(i,"bridge.token"),patTokenFile:Ae(i,"pat-token"),agentEnvFile:Ae(i,"agent-env.json"),logFile:Ae(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Ae(c,"daemon-stdio.log"),installLock:Ae(i,"install.lock"),configFile:Ae(i,"config.json"),agentsRoot:Ae(r,"agents")}}function Ve(t,e=Q()){let r=Ae(e.agentsRoot,t);return{root:r,config:Ae(r,"config.json"),workspace:Ae(r,"workspace"),logs:Ae(r,"logs")}}function fs(t=Q()){try{return Yg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ri(t,e){let r=await Cd.realpath(Rd(t)).catch(()=>null);if(!r)return!1;let i=await Cd.realpath(Rd(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+Qg)}var Oe=Qe(()=>{"use strict"});var xs={};ba(xs,{AGENT_CONFIG_FILE_MODE:()=>hs,enforceAgentConfigMode:()=>nm,loadAgentConfig:()=>Te,persistAgentSessions:()=>ii,persistAgentSkills:()=>si,saveAgentConfig:()=>Me});import{chmod as em,stat as tm}from"node:fs/promises";function Te(t,e){return cr(Ve(t,e).config)}function Me(t,e){return lr(Ve(t.agentId,e).config,t,{mode:hs})}async function nm(t,e){if(process.platform==="win32")return;let r=Ve(t,e).config;try{let i=await tm(r);if(!i.isFile())return;let o=i.mode&511;o!==hs&&(await em(r,hs),Pd.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Pd.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ii(t,e,r){let i=await Te(t,r);i&&(i.sessions=Object.fromEntries(e),await Me(i,r))}async function si(t,e,r){let i=await Te(t,r);i&&(i.skills=e,await Me(i,r))}var Pd,hs,cn=Qe(()=>{"use strict";an();te();Oe();Pd=H("agent-config"),hs=384});var Pa=oe((K2,Ld)=>{Ld.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 gs=oe(Md=>{var Nd={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 cm(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(Nd))Md[t]=cm(Nd[t])});var Gd=oe((V2,Ud)=>{var lm=ue("fs"),Le=ue("path"),Bd=Pa(),dm=gs(),um=typeof process=="object"&&process.platform==="win32",Fd=t=>typeof t=="object"&&t!==null,zd=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function be(t){this.sep=Le.sep,this.fs=lm,Fd(t)&&Fd(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Ud.exports=be;be.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(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 dm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};be.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var 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};be.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 p=Le.dirname(t);c.fs.exists(p,function(m){m||c.makeDir(p),c.fs.open(t,"w",438,function(_,v){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,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)})})})})}):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)})})})})})};be.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),p=e.fs.statSync(h);(!o||o.test(h))&&d.push(Le.normalize(h)+(p.isDirectory()?e.sep:"")),p.isDirectory()&&c&&(d=d.concat(r(h,o,c)))}),d}return r(t,void 0,!0)};be.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,p){if(h)return e(h);p&&(i.push(Le.normalize(u)+(p.isDirectory()?r.sep:"")),p.isDirectory()?r.findFilesAsync(u,function(m,_){if(m)return e(m);i=i.concat(_),--d||e(null,i)}):--d||e(null,i))})})})};be.prototype.getAttributes=function(){};be.prototype.setAttributes=function(){};be.crc32update=function(t,e){return zd[(t^e)&255]^t>>>8};be.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=be.crc32update(r,t[i++]);return~r>>>0};be.methodToString=function(t){switch(t){case Bd.STORED:return"STORED ("+t+")";case Bd.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};be.canonical=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.join(".",e)};be.zipnamefix=function(t){if(!t)return"";let e=Le.posix.normalize("/"+t.split("\\").join("/"));return Le.posix.join(".",e)};be.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};be.sanitize=function(t,e){t=Le.resolve(Le.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var 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)))};be.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};be.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};be.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};be.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};be.isWin=um;be.crcTable=zd});var qd=oe((J2,Hd)=>{var fm=ue("path");Hd.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=fm.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 Wd=oe((Z2,jd)=>{jd.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var fr=oe((Y2,ur)=>{ur.exports=Gd();ur.exports.Constants=Pa();ur.exports.Errors=gs();ur.exports.FileAttr=qd();ur.exports.decoder=Wd()});var $d=oe((X2,Kd)=>{var ln=fr(),z=ln.Constants;Kd.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,h=0,p=0,m=0,_=0,v=0,y=0,S=0;t|=ln.isWin?2560:768,r|=z.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,k=E=>Math.max(0,E)&65535,D=E=>Math.max(0,E)&255;return o=ln.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&z.FLG_EFS)>0},set flags_efs(E){E?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(E){E?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(E){switch(E){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=E},get time(){return ln.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=ln.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return D(o>>>8)},get crc(){return c},set crc(E){c=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return h},set fileNameLength(E){h=E},get extraLength(){return p},set extraLength(E){p=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return m},set commentLength(E){m=E},get diskNumStart(){return _},set diskNumStart(E){_=A(E)},get inAttr(){return v},set inAttr(E){v=A(E)},get attr(){return y},set attr(E){y=A(E)},get fileAttr(){return(y||0)>>16&4095},get offset(){return S},set offset(E){S=A(E)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+p+m},get realDataOffset(){return S+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var R=E.slice(S,S+z.LOCHDR);if(R.readUInt32LE(0)!==z.LOCSIG)throw ln.Errors.INVALID_LOC();I.version=R.readUInt16LE(z.LOCVER),I.flags=R.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=R.readUInt16LE(z.LOCHOW),I.time=R.readUInt32LE(z.LOCTIM),I.crc=R.readUInt32LE(z.LOCCRC),I.compressedSize=R.readUInt32LE(z.LOCSIZ),I.size=R.readUInt32LE(z.LOCLEN),I.fnameLen=R.readUInt16LE(z.LOCNAM),I.extraLen=R.readUInt16LE(z.LOCEXT);let L=S+z.LOCHDR+I.fnameLen,B=L+I.extraLen;return E.slice(L,B)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw ln.Errors.INVALID_CEN();t=E.readUInt16LE(z.CENVEM),e=E.readUInt16LE(z.CENVER),r=E.readUInt16LE(z.CENFLG),i=E.readUInt16LE(z.CENHOW),o=E.readUInt32LE(z.CENTIM),c=E.readUInt32LE(z.CENCRC),d=E.readUInt32LE(z.CENSIZ),u=E.readUInt32LE(z.CENLEN),h=E.readUInt16LE(z.CENNAM),p=E.readUInt16LE(z.CENEXT),m=E.readUInt16LE(z.CENCOM),_=E.readUInt16LE(z.CENDSK),v=E.readUInt16LE(z.CENATT),y=E.readUInt32LE(z.CENATX),S=E.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(z.LOCHDR);return E.writeUInt32LE(z.LOCSIG,0),E.writeUInt16LE(e,z.LOCVER),E.writeUInt16LE(r,z.LOCFLG),E.writeUInt16LE(i,z.LOCHOW),E.writeUInt32LE(o,z.LOCTIM),E.writeUInt32LE(c,z.LOCCRC),E.writeUInt32LE(d,z.LOCSIZ),E.writeUInt32LE(u,z.LOCLEN),E.writeUInt16LE(h,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+h+p+m);return E.writeUInt32LE(z.CENSIG,0),E.writeUInt16LE(t,z.CENVEM),E.writeUInt16LE(e,z.CENVER),E.writeUInt16LE(r,z.CENFLG),E.writeUInt16LE(i,z.CENHOW),E.writeUInt32LE(o,z.CENTIM),E.writeUInt32LE(c,z.CENCRC),E.writeUInt32LE(d,z.CENSIZ),E.writeUInt32LE(u,z.CENLEN),E.writeUInt16LE(h,z.CENNAM),E.writeUInt16LE(p,z.CENEXT),E.writeUInt16LE(m,z.CENCOM),E.writeUInt16LE(_,z.CENDSK),E.writeUInt16LE(v,z.CENATT),E.writeUInt32LE(y,z.CENATX),E.writeUInt32LE(S,z.CENOFF),E},toJSON:function(){let E=function(R){return R+" bytes"};return{made:t,version:e,flags:r,method:ln.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(h),extraLength:E(p),commentLength:E(m),diskNumStart:_,inAttr:v,attr:y,offset:S,centralHeaderSize:E(z.CENHDR+h+p+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Jd=oe((Q2,Vd)=>{var hr=fr(),_e=hr.Constants;Vd.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 hr.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=hr.readBigUInt64LE(c,_e.ZIP64SUB),e=hr.readBigUInt64LE(c,_e.ZIP64TOT),r=hr.readBigUInt64LE(c,_e.ZIP64SIZE),i=hr.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 Oa=oe(Da=>{Da.EntryHeader=$d();Da.MainHeader=Jd()});var Yd=oe((tI,Zd)=>{Zd.exports=function(t){var e=ue("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],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 p=0;p<c.length;p++){var m=c[p];m.copy(u,h),h+=m.length}i&&i(u)}),o.end(t)}}}});var Qd=oe((nI,Xd)=>{var hm=+(process.versions?process.versions.node:"").split(".")[0]||0;Xd.exports=function(t,e){var r=ue("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(h){d.push(h),u+=h.length}),c.on("end",function(){var h=Buffer.alloc(u),p=0;h.fill(0);for(var m=0;m<d.length;m++){var _=d[m];_.copy(h,p),p+=_.length}o&&o(h)}),c.end(t)}}}});var iu=oe((rI,ru)=>{"use strict";var{randomFillSync:eu}=ue("crypto"),xm=gs(),pm=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}),nu=(t,e)=>Math.imul(t,e)>>>0,tu=(t,e)=>pm[(t^e)&255]^t>>>8,oi=()=>typeof eu=="function"?eu(Buffer.alloc(12)):oi.node();oi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ms={genSalt:oi};function ws(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])}ws.prototype.updateKeys=function(t){let e=this.keys;return e[0]=tu(e[0],t),e[1]+=e[0]&255,e[1]=nu(e[1],134775813)+1,e[2]=tu(e[2],e[1]>>>24),t};ws.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return nu(t,t^1)>>8&255};function gm(t){let e=new ws(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 mm(t){let e=new ws(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 wm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=gm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw xm.WRONG_PASSWORD();return i(t.slice(12))}function _m(t){Buffer.isBuffer(t)&&t.length>=12?ms.genSalt=function(){return t.slice(0,12)}:t==="node"?ms.genSalt=oi.node:ms.genSalt=oi}function ym(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=mm(r),c=ms.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)}ru.exports={decrypt:wm,encrypt:ym,_salter:_m}});var su=oe(_s=>{_s.Deflater=Yd();_s.Inflater=Qd();_s.ZipCrypto=iu()});var Na=oe((sI,ou)=>{var ae=fr(),Em=Oa(),ve=ae.Constants,La=su();ou.exports=function(t,e){var r=new Em.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),p=!0;let m=t,_=typeof m.decoder=="object"?m.decoder:ae.decoder;p=_.hasOwnProperty("efs")?_.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 y(E){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ae.crc32(E)!==r.localHeader.crc)return!1}else{let R={},L=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(L)==ve.LOCSIG||e.readUInt32LE(L)==ve.CENSIG)throw ae.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(L)==ve.EXTSIG)R.crc=e.readUInt32LE(L+ve.EXTCRC),R.compressedSize=e.readUInt32LE(L+ve.EXTSIZ),R.size=e.readUInt32LE(L+ve.EXTLEN);else if(e.readUInt16LE(L+12)===19280)R.crc=e.readUInt32LE(L+ve.EXTCRC-4),R.compressedSize=e.readUInt32LE(L+ve.EXTSIZ-4),R.size=e.readUInt32LE(L+ve.EXTLEN-4);else throw ae.Errors.DESCRIPTOR_UNKNOWN();if(R.compressedSize!==r.compressedSize||R.size!==r.size||R.crc!==r.crc)throw ae.Errors.DESCRIPTOR_FAULTY();if(ae.crc32(E)!==R.crc)return!1}return!0}function S(E,R,L){if(typeof R>"u"&&typeof E=="string"&&(L=E,E=void 0),c)return E&&R&&R(Buffer.alloc(0),ae.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var B=v();if(B.length===0)return E&&R&&R(B),B;if(r.encrypted){if(typeof L!="string"&&!Buffer.isBuffer(L))throw ae.Errors.INVALID_PASS_PARAM();B=La.ZipCrypto.decrypt(B,r,L)}var M=Buffer.alloc(r.size);switch(r.method){case ae.Constants.STORED:if(B.copy(M),y(M))return E&&R&&R(M),M;throw E&&R&&R(M,ae.Errors.BAD_CRC()),ae.Errors.BAD_CRC();case ae.Constants.DEFLATED:var J=new La.Inflater(B,r.size);if(E)J.inflateAsync(function(V){V.copy(V,0),R&&(y(V)?R(V):R(V,ae.Errors.BAD_CRC()))});else{if(J.inflate(M).copy(M,0),!y(M))throw ae.Errors.BAD_CRC(`"${_.decode(i)}"`);return M}break;default:throw E&&R&&R(Buffer.alloc(0),ae.Errors.UNKNOWN_METHOD()),ae.Errors.UNKNOWN_METHOD()}}function I(E,R){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&R&&R(v()),v();if(d.length&&!c){var L;switch(r.method){case ae.Constants.STORED:return r.compressedSize=r.size,L=Buffer.alloc(d.length),d.copy(L),E&&R&&R(L),L;default:case ae.Constants.DEFLATED:var B=new La.Deflater(d);if(E)B.deflateAsync(function(J){L=Buffer.alloc(J.length),r.compressedSize=J.length,J.copy(L),R&&R(L)});else{var M=B.deflate();return r.compressedSize=M.length,M}B=null;break}}else if(E&&R)R(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,R){return ae.readBigUInt64LE(E,R)}function k(E){try{for(var R=0,L,B,M;R+4<E.length;)L=E.readUInt16LE(R),R+=2,B=E.readUInt16LE(R),R+=2,M=E.slice(R,R+B),R+=B,ve.ID_ZIP64===L&&D(M)}catch{throw ae.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(E){var R,L,B,M;E.length>=ve.EF_ZIP64_SCOMP&&(R=A(E,ve.EF_ZIP64_SUNCOMP),r.size===ve.EF_ZIP64_OR_32&&(r.size=R)),E.length>=ve.EF_ZIP64_RHO&&(L=A(E,ve.EF_ZIP64_SCOMP),r.compressedSize===ve.EF_ZIP64_OR_32&&(r.compressedSize=L)),E.length>=ve.EF_ZIP64_DSN&&(B=A(E,ve.EF_ZIP64_RHO),r.offset===ve.EF_ZIP64_OR_32&&(r.offset=B)),E.length>=ve.EF_ZIP64_DSN+4&&(M=E.readUInt32LE(ve.EF_ZIP64_DSN),r.diskNumStart===ve.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(E){i=ae.toBuffer(E,_.encode);var R=i[i.length-1];c=R===47||R===92,r.fileNameLength=i.length},get efs(){return typeof p=="function"?p(this.entryName):p},get extra(){return u},set extra(E){u=E,r.extraLength=E.length,k(E)},get comment(){return _.decode(o)},set comment(E){if(o=ae.toBuffer(E,_.encode),r.commentLength=o.length,o.length>65535)throw ae.Errors.COMMENT_TOO_LONG()},get name(){var E=_.decode(i);return c?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=ae.toBuffer(E,ae.decoder.encode),!c&&d.length?(r.size=d.length,r.method=ae.Constants.DEFLATED,r.crc=ae.crc32(E),r.changed=!0):r.method=ae.Constants.STORED},getData:function(E){return r.changed?d:S(!1,null,E)},getDataAsync:function(E,R){r.changed?E(d):S(!0,E,R)},set attr(E){r.attr=E},get attr(){return r.attr},set header(E){r.loadFromBinary(E)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var E=r.centralHeaderToBinary(),R=ae.Constants.CENHDR;return i.copy(E,R),R+=i.length,u.copy(E,R),R+=r.extraLength,o.copy(E,R),E},packLocalHeader:function(){let E=0;r.flags_efs=this.efs,r.extraLocalLength=h.length;let R=r.localHeaderToBinary(),L=Buffer.alloc(R.length+i.length+r.extraLocalLength);return R.copy(L,E),E+=R.length,i.copy(L,E),E+=i.length,h.copy(L,E),E+=h.length,L},toJSON:function(){let E=function(R){return"<"+(R&&R.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var lu=oe((oI,cu)=>{var au=Na(),bm=Oa(),je=fr();cu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new bm.MainHeader,d=!1,u=null;let h=new Set,p=e,{noSort:m,decoder:_}=p;t?S(p.readEntries):d=!0;function v(){let A=new Set;for(let k of Object.keys(i)){let D=k.split("/");if(D.pop(),!!D.length)for(let E=0;E<D.length;E++){let R=D.slice(0,E+1).join("/")+"/";A.add(R)}}for(let k of A)if(!(k in i)){let D=new au(p);D.entryName=k,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,h.add(D)}}function y(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/je.Constants.CENHDR)throw je.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,k=0;k<r.length;k++){var D=A,E=new au(p,t);E.header=t.slice(D,D+=je.Constants.CENHDR),E.entryName=t.slice(D,D+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(D,D+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(D,D+E.header.commentLength)),A+=E.header.centralHeaderSize,r[k]=E,i[E.entryName]=E}h.clear(),v()}function S(A){var k=t.length-je.Constants.ENDHDR,D=Math.max(0,k-65535),E=D,R=t.length,L=-1,B=0;for(typeof p.trailingSpace=="boolean"&&p.trailingSpace&&(D=0),k;k>=E;k--)if(t[k]===80){if(t.readUInt32LE(k)===je.Constants.ENDSIG){L=k,B=k,R=k+je.Constants.ENDHDR,E=k-je.Constants.END64HDR;continue}if(t.readUInt32LE(k)===je.Constants.END64SIG){E=D;continue}if(t.readUInt32LE(k)===je.Constants.ZIP64SIG){L=k,R=k+je.readBigUInt64LE(t,k+je.Constants.ZIP64SIZE)+je.Constants.ZIP64LEAD;break}}if(L==-1)throw je.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(L,R)),c.commentLength&&(o=t.slice(B+je.Constants.ENDHDR)),A&&y()}function I(){r.length>1&&!m&&r.sort((A,k)=>A.entryName.toLowerCase().localeCompare(k.entryName.toLowerCase()))}return{get entries(){return d||y(),r.filter(A=>!h.has(A))},get comment(){return _.decode(o)},set comment(A){o=je.toBuffer(A,_.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,k=!0){d||y();let D=i[A];this.getEntryChildren(D,k).map(R=>R.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let k=i[A],D=r.indexOf(k);D>=0&&(r.splice(D,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,k=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&k){let D=[],E=A.entryName;for(let R of r)R.entryName.startsWith(E)&&D.push(R);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let k=this.getEntryChildren(A);return k.includes(A)?k.length-1:k.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],k=[],D=0,E=0;c.size=0,c.offset=0;let R=0;for(let M of this.entries){let J=M.getCompressedData();M.header.offset=E;let V=M.packLocalHeader(),ne=V.length+J.length;E+=ne,A.push(V),A.push(J);let Y=M.packCentralHeader();k.push(Y),c.size+=Y.length,D+=ne+Y.length,R++}D+=c.mainHeaderSize,c.offset=E,c.totalEntries=R,E=0;let L=Buffer.alloc(D);for(let M of A)M.copy(L,E),E+=M.length;for(let M of k)M.copy(L,E),E+=M.length;let B=c.toBinary();return o&&o.copy(B,je.Constants.ENDHDR),B.copy(L,E),t=L,d=!1,L},toAsyncBuffer:function(A,k,D,E){try{d||y(),I();let R=[],L=[],B=0,M=0,J=0;c.size=0,c.offset=0;let V=function(ne){if(ne.length>0){let Y=ne.shift(),ie=Y.entryName+Y.extra.toString();D&&D(ie),Y.getCompressedDataAsync(function(se){E&&E(ie),Y.header.offset=M;let P=Y.packLocalHeader(),G=P.length+se.length;M+=G,R.push(P),R.push(se);let K=Y.packCentralHeader();L.push(K),c.size+=K.length,B+=G+K.length,J++,V(ne)})}else{B+=c.mainHeaderSize,c.offset=M,c.totalEntries=J,M=0;let Y=Buffer.alloc(B);R.forEach(function(se){se.copy(Y,M),M+=se.length}),L.forEach(function(se){se.copy(Y,M),M+=se.length});let ie=c.toBinary();o&&o.copy(ie,je.Constants.ENDHDR),ie.copy(Y,M),t=Y,d=!1,A(Y)}};V(Array.from(this.entries))}catch(R){k(R)}}}}});var fu=oe((aI,uu)=>{var Ee=fr(),ye=ue("path"),vm=Na(),Sm=lu(),Dn=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),du=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Im=(...t)=>Ee.findLast(t,e=>typeof e=="function"),Am={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};uu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Am);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 Sm(r,i),{canonical:d,sanitize:u,zipnamefix:h}=Ee;function p(y){if(y&&c){var S;if(typeof y=="string"&&(S=c.getEntry(ye.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(S=c.getEntry(y.entryName)),S)return S}return null}function m(y){let{join:S,normalize:I,sep:A}=ye.posix;return S(ye.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function _(y){return y instanceof RegExp?(function(S){return function(I){return S.test(I)}})(y):typeof y!="function"?()=>!0:y}let v=(y,S)=>{let I=S.slice(-1);return I=I===o.sep?o.sep:"",ye.relative(y,S)+I};return{readFile:function(y,S){var I=p(y);return I&&I.getData(S)||null},childCount:function(y){let S=p(y);if(S)return c.getChildCount(S)},readFileAsync:function(y,S){var I=p(y);I?I.getDataAsync(S):S(null,"getEntry failed for:"+y)},readAsText:function(y,S){var I=p(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(S||"utf8")}return""},readAsTextAsync:function(y,S,I){var A=p(y);A?A.getDataAsync(function(k,D){if(D){S(k,D);return}k&&k.length?S(k.toString(I||"utf8")):S("")}):S("")},deleteFile:function(y,S=!0){var I=p(y);I&&c.deleteFile(I.entryName,S)},deleteEntry:function(y){var S=p(y);S&&c.deleteEntry(S.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,S){var I=p(y);I&&(I.comment=S)},getZipEntryComment:function(y){var S=p(y);return S&&S.comment||""},updateFile:function(y,S){var I=p(y);I&&I.setData(S)},addLocalFile:function(y,S,I,A){if(o.fs.existsSync(y)){S=S?m(S):"";let k=ye.win32.basename(ye.win32.normalize(y));S+=I||k;let D=o.fs.statSync(y),E=D.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);D.isDirectory()&&(S+=o.sep),this.addFile(S,E,A,D)}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,S){y=typeof y=="object"?y:{localPath:y};let I=ye.resolve(y.localPath),{comment:A}=y,{zipPath:k,zipName:D}=y,E=this;o.fs.stat(I,function(R,L){if(R)return S(R,!1);k=k?m(k):"";let B=ye.win32.basename(ye.win32.normalize(I));if(k+=D||B,L.isFile())o.fs.readFile(I,function(M,J){return M?S(M,!1):(E.addFile(k,J,A,L),setImmediate(S,void 0,!0))});else if(L.isDirectory())return k+=o.sep,E.addFile(k,Buffer.alloc(0),A,L),setImmediate(S,void 0,!0)})},addLocalFolder:function(y,S,I){if(I=_(I),S=S?m(S):"",y=ye.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),k=this;if(A.length)for(let D of A){let E=ye.join(S,v(y,D));I(E)&&k.addLocalFile(D,ye.dirname(E))}}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,S,I,A){A=_(A),I=I?m(I):"",y=ye.normalize(y);var k=this;o.fs.open(y,"r",function(D){if(D&&D.code==="ENOENT")S(void 0,Ee.Errors.FILE_NOT_FOUND(y));else if(D)S(void 0,D);else{var E=o.findFiles(y),R=-1,L=function(){if(R+=1,R<E.length){var B=E[R],M=v(y,B).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(B,function(J,V){J&&S(void 0,J),V.isFile()?o.fs.readFile(B,function(ne,Y){ne?S(void 0,ne):(k.addFile(I+M,Y,"",V),L())}):(k.addFile(I+M+"/",Buffer.alloc(0),"",V),L())}):process.nextTick(()=>{L()})}else S(!0,void 0)};L()}})},addLocalFolderAsync2:function(y,S){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=ye.resolve(m(y.localPath));let{zipPath:A,filter:k,namefix:D}=y;k instanceof RegExp?k=(function(L){return function(B){return L.test(B)}})(k):typeof k!="function"&&(k=function(){return!0}),A=A?m(A):"",D=="latin1"&&(D=L=>L.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=L=>L);let E=L=>ye.join(A,D(v(localPath,L))),R=L=>ye.win32.basename(ye.win32.normalize(D(L)));o.fs.open(localPath,"r",function(L){L&&L.code==="ENOENT"?S(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):L?S(void 0,L):o.findFilesAsync(localPath,function(B,M){if(B)return S(B);M=M.filter(J=>k(E(J))),M.length||S(void 0,!1),setImmediate(M.reverse().reduce(function(J,V){return function(ne,Y){if(ne||Y===!1)return setImmediate(J,ne,!1);I.addLocalFileAsync({localPath:V,zipPath:ye.dirname(E(V)),zipName:R(V)},J)}},S))})})},addLocalFolderPromise:function(y,S){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},S),(k,D)=>{k&&A(k),D&&I(this)})})},addFile:function(y,S,I,A){y=h(y);let k=p(y),D=k!=null;D||(k=new vm(i),k.entryName=y),k.comment=I||"";let E=typeof A=="object"&&A instanceof o.fs.Stats;E&&(k.header.time=A.mtime);var R=k.isDirectory?16:0;let L=k.isDirectory?16384:32768;return E?L|=4095&A.mode:typeof A=="number"?L|=4095&A:L|=k.isDirectory?493:420,R=(R|L<<16)>>>0,k.attr=R,k.setData(S),D||c.setEntry(k),k},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return p(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,S,I,A,k,D){A=Dn(!1,A),k=Dn(!1,k),I=Dn(!0,I),D=du(k,D);var E=p(y);if(!E)throw Ee.Errors.NO_ENTRY();var R=d(E.entryName),L=u(S,D&&!E.isDirectory?D:I?R:ye.basename(R));if(E.isDirectory){var B=c.getEntryChildren(E);return B.forEach(function(V){if(V.isDirectory)return;var ne=V.getData();if(!ne)throw Ee.Errors.CANT_EXTRACT_FILE();var Y=d(V.entryName),ie=u(S,I?Y:ye.basename(Y));let se=k?V.header.fileAttr:void 0;o.writeFileTo(ie,ne,A,se)}),!0}var M=E.getData(c.password);if(!M)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(L)&&!A)throw Ee.Errors.CANT_OVERRIDE();let J=k?y.header.fileAttr:void 0;return o.writeFileTo(L,M,A,J),!0},test:function(y){if(!c)return!1;for(var S in c.entries)try{if(S.isDirectory)continue;var I=c.entries[S].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,S,I,A){if(I=Dn(!1,I),A=du(I,A),S=Dn(!1,S),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(k){var D=u(y,d(k.entryName));if(k.isDirectory){o.makeDir(D);return}var E=k.getData(A);if(!E)throw Ee.Errors.CANT_EXTRACT_FILE();let R=I?k.header.fileAttr:void 0;o.writeFileTo(D,E,S,R);try{o.fs.utimesSync(D,k.header.time,k.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,S,I,A){if(A=Im(S,I,A),I=Dn(!1,I),S=Dn(!1,S),!A)return new Promise((L,B)=>{this.extractAllToAsync(y,S,I,function(M){M?B(M):L(this)})});if(!c){A(Ee.Errors.NO_ZIP());return}y=ye.resolve(y);let k=L=>u(y,ye.normalize(d(L.entryName))),D=(L,B)=>new Error(L+': "'+B+'"'),E=[],R=[];c.entries.forEach(L=>{L.isDirectory?E.push(L):R.push(L)});for(let L of E){let B=k(L),M=I?L.header.fileAttr:void 0;try{o.makeDir(B),M&&o.fs.chmodSync(B,M),o.fs.utimesSync(B,L.header.time,L.header.time)}catch{A(D("Unable to create folder",B))}}R.reverse().reduce(function(L,B){return function(M){if(M)L(M);else{let J=ye.normalize(d(B.entryName)),V=u(y,J);B.getDataAsync(function(ne,Y){if(Y)L(Y);else if(!ne)L(Ee.Errors.CANT_EXTRACT_FILE());else{let ie=I?B.header.fileAttr:void 0;o.writeFileToAsync(V,ne,S,ie,function(se){se||L(D("Unable to write file",V)),o.fs.utimes(V,B.header.time,B.header.time,function(P){P?L(D("Unable to set times",V)):L()})})}})}}},A)()},writeZip:function(y,S){if(arguments.length===1&&typeof y=="function"&&(S=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof S=="function"&&S(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,S){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},S);return new Promise((k,D)=>{!y&&i.filename&&(y=i.filename),y||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let R=L=>L?k(L):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(y,E,I,A,R)},D)})},toBufferPromise:function(){return new Promise((y,S)=>{c.toAsyncBuffer(y,S)})},toBuffer:function(y,S,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,S,I,A),null):c.compressToBuffer()}}}});import{execFile as D_,spawn as O_,spawnSync as IA}from"node:child_process";import{promisify as L_}from"node:util";function M_(t){if(process.platform!=="win32")return!1;if(Df.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Df,"").toLowerCase();return N_.has(r)}function Of(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return M_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function nt(t,e=[],r={}){return O_(t,e,Of(t,r))}function Lf(t,e=[],r={}){return B_(t,e,Of(t,r))}var N_,Df,B_,$t=Qe(()=>{"use strict";N_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Df=/\.(cmd|bat|ps1)$/i;B_=L_(D_)});var Jt=oe((fR,wh)=>{"use strict";var gh=["nodebuffer","arraybuffer","fragments"],mh=typeof Blob<"u";mh&&gh.push("blob");wh.exports={BINARY_TYPES:gh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:mh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $i=oe((hR,Ao)=>{"use strict";var{EMPTY_BUFFER:gb}=Jt(),ul=Buffer[Symbol.species];function mb(t,e){if(t.length===0)return gb;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 ul(r.buffer,r.byteOffset,i):r}function _h(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function yh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function wb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function fl(t){if(fl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ul(t):ArrayBuffer.isView(t)?e=new ul(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),fl.readOnly=!1),e}Ao.exports={concat:mb,mask:_h,toArrayBuffer:wb,toBuffer:fl,unmask:yh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");Ao.exports.mask=function(e,r,i,o,c){c<48?_h(e,r,i,o,c):t.mask(e,r,i,o,c)},Ao.exports.unmask=function(e,r){e.length<32?yh(e,r):t.unmask(e,r)}}catch{}});var vh=oe((xR,bh)=>{"use strict";var Eh=Symbol("kDone"),hl=Symbol("kRun"),xl=class{constructor(e){this[Eh]=()=>{this.pending--,this[hl]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[hl]()}[hl](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Eh])}}};bh.exports=xl});var zr=oe((pR,Th)=>{"use strict";var Vi=ue("zlib"),Sh=$i(),_b=vh(),{kStatusCode:Ih}=Jt(),yb=Buffer[Symbol.species],Eb=Buffer.from([0,0,255,255]),ko=Symbol("permessage-deflate"),Zt=Symbol("total-length"),Br=Symbol("callback"),Tn=Symbol("buffers"),Fr=Symbol("error"),To,pl=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,!To){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;To=new _b(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[Br];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){To.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){To.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[ko]=this,this._inflate[Zt]=0,this._inflate[Tn]=[],this._inflate.on("error",vb),this._inflate.on("data",Ah)}this._inflate[Br]=i,this._inflate.write(e),r&&this._inflate.write(Eb),this._inflate.flush(()=>{let c=this._inflate[Fr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Sh.concat(this._inflate[Tn],this._inflate[Zt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Zt]=0,this._inflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Zt]=0,this._deflate[Tn]=[],this._deflate.on("data",bb)}this._deflate[Br]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Sh.concat(this._deflate[Tn],this._deflate[Zt]);r&&(c=new yb(c.buffer,c.byteOffset,c.length-4)),this._deflate[Br]=null,this._deflate[Zt]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Th.exports=pl;function bb(t){this[Tn].push(t),this[Zt]+=t.length}function Ah(t){if(this[Zt]+=t.length,this[ko]._maxPayload<1||this[Zt]<=this[ko]._maxPayload){this[Tn].push(t);return}this[Fr]=new RangeError("Max payload size exceeded"),this[Fr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fr][Ih]=1009,this.removeListener("data",Ah),this.reset()}function vb(t){if(this[ko]._inflate=null,this[Fr]){this[Br](this[Fr]);return}t[Ih]=1007,this[Br](t)}});var Ur=oe((gR,Co)=>{"use strict";var{isUtf8:kh}=ue("buffer"),{hasBlob:Sb}=Jt(),Ib=[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 Ab(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function gl(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 Tb(t){return Sb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Co.exports={isBlob:Tb,isValidStatusCode:Ab,isValidUTF8:gl,tokenChars:Ib};if(kh)Co.exports.isValidUTF8=function(t){return t.length<24?gl(t):kh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");Co.exports.isValidUTF8=function(e){return e.length<32?gl(e):t(e)}}catch{}});var El=oe((mR,Nh)=>{"use strict";var{Writable:kb}=ue("stream"),Ch=zr(),{BINARY_TYPES:Cb,EMPTY_BUFFER:Rh,kStatusCode:Rb,kWebSocket:Pb}=Jt(),{concat:ml,toArrayBuffer:Db,unmask:Ob}=$i(),{isValidStatusCode:Lb,isValidUTF8:Ph}=Ur(),Ro=Buffer[Symbol.species],ft=0,Dh=1,Oh=2,Lh=3,wl=4,_l=5,Po=6,yl=class extends kb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Cb[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[Pb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ft}_write(e,r,i){if(this._opcode===8&&this._state==ft)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Ro(i.buffer,i.byteOffset+e,i.length-e),new Ro(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 Ro(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ft:this.getInfo(e);break;case Dh:this.getPayloadLength16(e);break;case Oh:this.getPayloadLength64(e);break;case Lh:this.getMask();break;case wl:this.getData(e);break;case _l:case Po: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[Ch.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=Dh:this._payloadLength===127?this._state=Oh: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=Lh:this._state=wl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wl}getData(e){let r=Rh;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&&Ob(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=_l,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[Ch.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===ft&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ft;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=ml(i,r):this._binaryType==="arraybuffer"?o=Db(ml(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ft):(this._state=Po,setImmediate(()=>{this.emit("message",o,!0),this._state=ft,this.startLoop(e)}))}else{let o=ml(i,r);if(!this._skipUTF8Validation&&!Ph(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===_l||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ft):(this._state=Po,setImmediate(()=>{this.emit("message",o,!1),this._state=ft,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Rh),this.end();else{let i=e.readUInt16BE(0);if(!Lb(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Ro(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ph(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=ft;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ft):(this._state=Po,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ft,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[Rb]=o,d}};Nh.exports=yl});var Sl=oe((_R,Fh)=>{"use strict";var{Duplex:wR}=ue("stream"),{randomFillSync:Nb}=ue("crypto"),{types:{isUint8Array:Mb}}=ue("util"),Mh=zr(),{EMPTY_BUFFER:Bb,kWebSocket:Fb,NOOP:zb}=Jt(),{isBlob:Gr,isValidStatusCode:Ub}=Ur(),{mask:Bh,toBuffer:Vn}=$i(),ht=Symbol("kByteLength"),Gb=Buffer.alloc(4),Do=8*1024,Jn,Hr=Do,St=0,Hb=1,qb=2,bl=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=zb,this[Fb]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||Gb,r.generateMask?r.generateMask(i):(Hr===Do&&(Jn===void 0&&(Jn=Buffer.alloc(Do)),Nb(Jn,0,Do),Hr=0),i[0]=Jn[Hr++],i[1]=Jn[Hr++],i[2]=Jn[Hr++],i[3]=Jn[Hr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[ht]!==void 0?u=r[ht]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let h=u;u>=65536?(c+=8,h=127):u>125&&(c+=2,h=126);let p=Buffer.allocUnsafe(o?u+c:c);return p[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(p[0]|=64),p[1]=h,h===126?p.writeUInt16BE(u,2):h===127&&(p[2]=p[3]=0,p.writeUIntBE(u,4,6)),r.mask?(p[1]|=128,p[c-4]=i[0],p[c-3]=i[1],p[c-2]=i[2],p[c-1]=i[3],d?[p,e]:o?(Bh(e,i,p,c,u),[p]):(Bh(e,i,e,0,u),[p,e])):[p,e]}close(e,r,i,o){let c;if(e===void 0)c=Bb;else{if(typeof e!="number"||!Ub(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(Mb(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[ht]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[ht]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==St?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[ht]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==St?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[Mh.extensionName],c=r.binary?2:1,d=r.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):Gr(e)?(u=e.size,h=!1):(e=Vn(e),u=e.length,h=Vn.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 p={[ht]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:h,rsv1:d};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,p,i]):this.getBlobData(e,this._compress,p,i):this._state!==St?this.enqueue([this.dispatch,e,this._compress,p,i]):this.dispatch(e,this._compress,p,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[ht],this._state=qb,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(vl,this,u,o);return}this._bufferedBytes-=i[ht];let d=Vn(c);r?this.dispatch(d,r,i,o):(this._state=St,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(jb,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Mh.extensionName];this._bufferedBytes+=i[ht],this._state=Hb,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");vl(this,h,o);return}this._bufferedBytes-=i[ht],this._state=St,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ht],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ht],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Fh.exports=bl;function vl(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 jb(t,e,r){vl(t,e,r),t.onerror(e)}});var $h=oe((yR,Kh)=>{"use strict";var{kForOnEventAttribute:Ji,kListener:Il}=Jt(),zh=Symbol("kCode"),Uh=Symbol("kData"),Gh=Symbol("kError"),Hh=Symbol("kMessage"),qh=Symbol("kReason"),qr=Symbol("kTarget"),jh=Symbol("kType"),Wh=Symbol("kWasClean"),Yt=class{constructor(e){this[qr]=null,this[jh]=e}get target(){return this[qr]}get type(){return this[jh]}};Object.defineProperty(Yt.prototype,"target",{enumerable:!0});Object.defineProperty(Yt.prototype,"type",{enumerable:!0});var Zn=class extends Yt{constructor(e,r={}){super(e),this[zh]=r.code===void 0?0:r.code,this[qh]=r.reason===void 0?"":r.reason,this[Wh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[zh]}get reason(){return this[qh]}get wasClean(){return this[Wh]}};Object.defineProperty(Zn.prototype,"code",{enumerable:!0});Object.defineProperty(Zn.prototype,"reason",{enumerable:!0});Object.defineProperty(Zn.prototype,"wasClean",{enumerable:!0});var jr=class extends Yt{constructor(e,r={}){super(e),this[Gh]=r.error===void 0?null:r.error,this[Hh]=r.message===void 0?"":r.message}get error(){return this[Gh]}get message(){return this[Hh]}};Object.defineProperty(jr.prototype,"error",{enumerable:!0});Object.defineProperty(jr.prototype,"message",{enumerable:!0});var Zi=class extends Yt{constructor(e,r={}){super(e),this[Uh]=r.data===void 0?null:r.data}get data(){return this[Uh]}};Object.defineProperty(Zi.prototype,"data",{enumerable:!0});var Wb={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Ji]&&o[Il]===e&&!o[Ji])return;let i;if(t==="message")i=function(c,d){let u=new Zi("message",{data:d?c:c.toString()});u[qr]=this,Oo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Zn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[qr]=this,Oo(e,this,u)};else if(t==="error")i=function(c){let d=new jr("error",{error:c,message:c.message});d[qr]=this,Oo(e,this,d)};else if(t==="open")i=function(){let c=new Yt("open");c[qr]=this,Oo(e,this,c)};else return;i[Ji]=!!r[Ji],i[Il]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Il]===e&&!r[Ji]){this.removeListener(t,r);break}}};Kh.exports={CloseEvent:Zn,ErrorEvent:jr,Event:Yt,EventTarget:Wb,MessageEvent:Zi};function Oo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Lo=oe((ER,Vh)=>{"use strict";var{tokenChars:Yi}=Ur();function Mt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Kb(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,h=-1,p=-1,m=-1,_=0;for(;_<t.length;_++)if(p=t.charCodeAt(_),d===void 0)if(m===-1&&Yi[p]===1)h===-1&&(h=_);else if(_!==0&&(p===32||p===9))m===-1&&h!==-1&&(m=_);else if(p===59||p===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);p===44?(Mt(e,y,r),r=Object.create(null)):d=y,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(m===-1&&Yi[p]===1)h===-1&&(h=_);else if(p===32||p===9)m===-1&&h!==-1&&(m=_);else if(p===59||p===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_),Mt(r,t.slice(h,m),!0),p===44&&(Mt(e,d,r),r=Object.create(null),d=void 0),h=m=-1}else if(p===61&&h!==-1&&m===-1)u=t.slice(h,_),h=m=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(o){if(Yi[p]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);h===-1?h=_:i||(i=!0),o=!1}else if(c)if(Yi[p]===1)h===-1&&(h=_);else if(p===34&&h!==-1)c=!1,m=_;else if(p===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(p===34&&t.charCodeAt(_-1)===61)c=!0;else if(m===-1&&Yi[p]===1)h===-1&&(h=_);else if(h!==-1&&(p===32||p===9))m===-1&&(m=_);else if(p===59||p===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1&&(m=_);let y=t.slice(h,m);i&&(y=y.replace(/\\/g,""),i=!1),Mt(r,u,y),p===44&&(Mt(e,d,r),r=Object.create(null),d=void 0),u=void 0,h=m=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(h===-1||c||p===32||p===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=_);let v=t.slice(h,m);return d===void 0?Mt(e,v,r):(u===void 0?Mt(r,v,!0):i?Mt(r,u,v.replace(/\\/g,"")):Mt(r,u,v),Mt(e,d,r)),e}function $b(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(", ")}Vh.exports={format:$b,parse:Kb}});var Fo=oe((SR,ox)=>{"use strict";var Vb=ue("events"),Jb=ue("https"),Zb=ue("http"),Yh=ue("net"),Yb=ue("tls"),{randomBytes:Xb,createHash:Qb}=ue("crypto"),{Duplex:bR,Readable:vR}=ue("stream"),{URL:Al}=ue("url"),kn=zr(),ev=El(),tv=Sl(),{isBlob:nv}=Ur(),{BINARY_TYPES:Jh,CLOSE_TIMEOUT:rv,EMPTY_BUFFER:No,GUID:iv,kForOnEventAttribute:Tl,kListener:sv,kStatusCode:ov,kWebSocket:Ge,NOOP:Xh}=Jt(),{EventTarget:{addEventListener:av,removeEventListener:cv}}=$h(),{format:lv,parse:dv}=Lo(),{toBuffer:uv}=$i(),Qh=Symbol("kAborted"),kl=[8,13],Xt=["CONNECTING","OPEN","CLOSING","CLOSED"],fv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends Vb{constructor(e,r,i){super(),this._binaryType=Jh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=No,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]),ex(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Jh.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 ev({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 tv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[Ge]=this,c[Ge]=this,e[Ge]=this,o.on("conclude",pv),o.on("drain",gv),o.on("error",mv),o.on("message",wv),o.on("ping",_v),o.on("pong",yv),c.onerror=Ev,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",rx),e.on("data",Bo),e.on("end",ix),e.on("error",sx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[kn.extensionName]&&this._extensions[kn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),nx(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){Cl(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||No,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){Cl(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||No,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){Cl(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[kn.extensionName]||(o.compress=!1),this._sender.send(e||No,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:Xt.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:Xt.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:Xt.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:Xt.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:Xt.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:Xt.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:Xt.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:Xt.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[Tl])return e[sv];return null},set(e){for(let r of this.listeners(t))if(r[Tl]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Tl]:!0})}})});me.prototype.addEventListener=av;me.prototype.removeEventListener=cv;ox.exports=me;function ex(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:rv,protocolVersion:kl[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,!kl.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${kl.join(", ")})`);let c;if(e instanceof Al)c=e;else try{c=new Al(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",h;if(c.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?h="The URL's pathname is empty":c.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;Mo(t,I);return}let p=d?443:80,m=Xb(16).toString("base64"),_=d?Jb.request:Zb.request,v=new Set,y;if(o.createConnection=o.createConnection||(d?xv:hv),o.defaultPort=o.defaultPort||p,o.port=c.port||p,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&&(y=new kn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=lv({[kn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!fv.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let S;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,k]of Object.entries(I))i.headers[A.toLowerCase()]=k}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),S=t._req=_(o),t._redirects&&t.emit("redirect",t.url,S)}else S=t._req=_(o);o.timeout&&S.on("timeout",()=>{at(t,S,"Opening handshake has timed out")}),S.on("error",I=>{S===null||S[Qh]||(S=t._req=null,Mo(t,I))}),S.on("response",I=>{let A=I.headers.location,k=I.statusCode;if(A&&o.followRedirects&&k>=300&&k<400){if(++t._redirects>o.maxRedirects){at(t,S,"Maximum redirects exceeded");return}S.abort();let D;try{D=new Al(A,e)}catch{let R=new SyntaxError(`Invalid URL: ${A}`);Mo(t,R);return}ex(t,D,r,i)}else t.emit("unexpected-response",S,I)||at(t,S,`Unexpected server response: ${I.statusCode}`)}),S.on("upgrade",(I,A,k)=>{if(t.emit("upgrade",I),t.readyState!==me.CONNECTING)return;S=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){at(t,A,"Invalid Upgrade header");return}let E=Qb("sha1").update(m+iv).digest("base64");if(I.headers["sec-websocket-accept"]!==E){at(t,A,"Invalid Sec-WebSocket-Accept header");return}let R=I.headers["sec-websocket-protocol"],L;if(R!==void 0?v.size?v.has(R)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":v.size&&(L="Server sent no subprotocol"),L){at(t,A,L);return}R&&(t._protocol=R);let B=I.headers["sec-websocket-extensions"];if(B!==void 0){if(!y){at(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=dv(B)}catch{at(t,A,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(M);if(J.length!==1||J[0]!==kn.extensionName){at(t,A,"Server indicated an extension that was not requested");return}try{y.accept(M[kn.extensionName])}catch{at(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[kn.extensionName]=y}t.setSocket(A,k,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,t):S.end()}function Mo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function hv(t){return t.path=t.socketPath,Yh.connect(t)}function xv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Yh.isIP(t.host)?"":t.host),Yb.connect(t)}function at(t,e,r){t._readyState=me.CLOSING;let i=new Error(r);Error.captureStackTrace(i,at),e.setHeader?(e[Qh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Mo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Cl(t,e,r){if(e){let i=nv(e)?e.size:uv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Xt[t.readyState]})`);process.nextTick(r,i)}}function pv(t,e){let r=this[Ge];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Ge]!==void 0&&(r._socket.removeListener("data",Bo),process.nextTick(tx,r._socket),t===1005?r.close():r.close(t,e))}function gv(){let t=this[Ge];t.isPaused||t._socket.resume()}function mv(t){let e=this[Ge];e._socket[Ge]!==void 0&&(e._socket.removeListener("data",Bo),process.nextTick(tx,e._socket),e.close(t[ov])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Zh(){this[Ge].emitClose()}function wv(t,e){this[Ge].emit("message",t,e)}function _v(t){let e=this[Ge];e._autoPong&&e.pong(t,!this._isServer,Xh),e.emit("ping",t)}function yv(t){this[Ge].emit("pong",t)}function tx(t){t.resume()}function Ev(t){let e=this[Ge];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,nx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function nx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function rx(){let t=this[Ge];if(this.removeListener("close",rx),this.removeListener("data",Bo),this.removeListener("end",ix),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[Ge]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Zh),t._receiver.on("finish",Zh))}function Bo(t){this[Ge]._receiver.write(t)||this.pause()}function ix(){let t=this[Ge];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function sx(){let t=this[Ge];this.removeListener("error",sx),this.on("error",Xh),t&&(t._readyState=me.CLOSING,this.destroy())}});var dx=oe((AR,lx)=>{"use strict";var IR=Fo(),{Duplex:bv}=ue("stream");function ax(t){t.emit("close")}function vv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function cx(t){this.removeListener("error",cx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Sv(t,e){let r=!0,i=new bv({...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(ax,i);return}let d=!1;t.once("error",function(h){d=!0,c(h)}),t.once("close",function(){d||c(o),process.nextTick(ax,i)}),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",vv),i.on("error",cx),i}lx.exports=Sv});var Rl=oe((TR,ux)=>{"use strict";var{tokenChars:Iv}=Ur();function Av(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&&Iv[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}ux.exports={parse:Av}});var _x=oe((CR,mx)=>{"use strict";var Tv=ue("events"),zo=ue("http"),{Duplex:kR}=ue("stream"),{createHash:kv}=ue("crypto"),fx=Lo(),Yn=zr(),Cv=Rl(),Rv=Fo(),{CLOSE_TIMEOUT:Pv,GUID:Dv,kWebSocket:Ov}=Jt(),Lv=/^[+/0-9A-Za-z]{22}==$/,hx=0,xx=1,gx=2,Pl=class extends Tv{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:Pv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Rv,...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=zo.createServer((i,o)=>{let c=zo.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=Nv(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=hx}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===gx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xi,this);return}if(e&&this.once("close",e),this._state!==xx)if(this._state=xx,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Xi,this):process.nextTick(Xi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Xi(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,o){r.on("error",px);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Xn(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){Xn(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Lv.test(c)){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qi(r,400);return}let h=e.headers["sec-websocket-protocol"],p=new Set;if(h!==void 0)try{p=Cv.parse(h)}catch{Xn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&m!==void 0){let v=new Yn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=fx.parse(m);y[Yn.extensionName]&&(v.accept(y[Yn.extensionName]),_[Yn.extensionName]=v)}catch{Xn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(y,S,I,A)=>{if(!y)return Qi(r,S||401,I,A);this.completeUpgrade(_,c,p,e,r,i,o)});return}if(!this.options.verifyClient(v))return Qi(r,401)}this.completeUpgrade(_,c,p,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[Ov])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>hx)return Qi(c,503);let p=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${kv("sha1").update(r+Dv).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;_&&(p.push(`Sec-WebSocket-Protocol: ${_}`),m._protocol=_)}if(e[Yn.extensionName]){let _=e[Yn.extensionName].params,v=fx.format({[Yn.extensionName]:[_]});p.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=e}this.emit("headers",p,o),c.write(p.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&xs(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 Rg,mkdirSync as Cg}from"node:fs";import{join as Dg}from"node:path";function bd(t){let e=t.retentionDays??Og,r=t.clock??(()=>Dn(new Date));ps={bridgeSink:new ii(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new ii(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();xs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])xs(t.agentLogsDir(o),"agent",i,e)}function Ng(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function Ed(t){Ra=t}function vd(t){return ar[Ra]<=ar[t]}function Sd(t,e){let r=ar[t];return r===void 0?!0:r>=ar[e]}function gs(t){yd={...t}}function Id(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)),l=e(o%60);return`${Dn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function At(t,e,r,i,o){try{let c=`${JSON.stringify({ts:Id(new Date),level:e,module:r,msg:i,...o})}
11
+ `;Cg(t,{recursive:!0}),Rg(Dg(t,or("bridge",Dn(new Date))),c)}catch{}}function Mg(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function hs(t,e,r,i,o){if(ar[t]<ar[Ra])return;let c=`${JSON.stringify({ts:Id(new Date),level:t,module:e,msg:r,...yd,...i})}
12
+ `;if(ps){let l=Mg(o,i),u=l?Ng(ps,l):ps.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Lg.write(c):Pg.write(c)}function H(t,e){return{debug:(r,i)=>hs("debug",t,r,i,e),info:(r,i)=>hs("info",t,r,i,e),warn:(r,i)=>hs("warn",t,r,i,e),error:(r,i)=>hs("error",t,r,i,e),child:r=>H(`${t}.${r}`,e),forAgent:r=>H(t,r)}}var ar,Ra,Pg,Lg,yd,Og,ps,ne=et(()=>{"use strict";sr();ka();ar={debug:10,info:20,warn:30,error:40},Ra=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Pg=process.stdout,Lg=process.stderr,yd={},Og=$e("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ps=null});var k,je=et(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Rd={};Aa(Rd,{ACP_WRAPPER_NPM_PACKAGES:()=>oi,_resetAcpInstallerForTests:()=>Hg,_setBinaryPathCacheForTests:()=>qg,buildAcpSpawn:()=>ai,ensureAcpInstalled:()=>cr,getAcpBinaryPath:()=>ms,pickWhichLine:()=>Pa,probeAcpVersion:()=>Gg,resolveAcpCommand:()=>kd});import{readFileSync as Ad}from"node:fs";import{createRequire as Bg}from"node:module";import{dirname as zg,resolve as Fg}from"node:path";function Pa(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function Ug(t){let e=Td.resolve(`${t.npmPackage}/package.json`),r=zg(e),i=JSON.parse(Ad(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 Fg(r,o)}async function cr(t,e){let r=Da[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=si.get(t);if(i)return i;try{let o=Ug(r);return si.set(t,o),Ca.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Ca.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(o)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:o})}}async function Gg(t){let e=Da[t];if(e)try{let r=Td.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Ad(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Ca.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function ms(t){return si.get(t)}function kd(t,e){if(e)return e;let r=ms(t);if(!r)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ai(t,e,r){if(e)return{command:e,args:[...r]};let i=kd(t);return{command:process.execPath,args:[i,...r]}}function Hg(){si.clear()}function qg(t,e){si.set(t,e)}var Ca,Da,oi,Td,si,sn=et(()=>{"use strict";je();ne();Ca=H("agents.acp-installer"),Da={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},oi=Object.values(Da).filter(t=>t!==void 0).map(t=>t.npmPackage),Td=Bg(import.meta.url),si=new Map});import{chmod as Wg,mkdir as Kg,readFile as $g,rename as Vg,rm as Jg,writeFile as Yg}from"node:fs/promises";import{dirname as Zg}from"node:path";async function lr(t){try{let e=await $g(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function on(t,e,r){await Kg(Zg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Yg(i,e,{encoding:"utf8",mode:r?.mode}),await Vg(i,t),r?.mode!==void 0&&await Wg(t,r.mode)}catch(o){throw await Jg(i,{force:!0}).catch(()=>{}),o}}async function dr(t,e,r){await on(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var an=et(()=>{"use strict"});import{promises as Pd,readdirSync as Xg}from"node:fs";import{homedir as Qg}from"node:os";import{sep as em,join as Te,resolve as Ld}from"node:path";function Q(t){let e=t??Qg(),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 Ve(t,e=Q()){let r=Te(e.agentsRoot,t);return{root:r,config:Te(r,"config.json"),workspace:Te(r,"workspace"),logs:Te(r,"logs")}}function ws(t=Q()){try{return Xg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ci(t,e){let r=await Pd.realpath(Ld(t)).catch(()=>null);if(!r)return!1;let i=await Pd.realpath(Ld(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+em)}var Le=et(()=>{"use strict"});var ys={};Aa(ys,{AGENT_CONFIG_FILE_MODE:()=>_s,enforceAgentConfigMode:()=>rm,loadAgentConfig:()=>ke,persistAgentSessions:()=>li,persistAgentSkills:()=>di,saveAgentConfig:()=>Be});import{chmod as tm,stat as nm}from"node:fs/promises";function ke(t,e){return lr(Ve(t,e).config)}function Be(t,e){return dr(Ve(t.agentId,e).config,t,{mode:_s})}async function rm(t,e){if(process.platform==="win32")return;let r=Ve(t,e).config;try{let i=await nm(r);if(!i.isFile())return;let o=i.mode&511;o!==_s&&(await tm(r,_s),Od.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Od.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function li(t,e,r){let i=await ke(t,r);i&&(i.sessions=Object.fromEntries(e),await Be(i,r))}async function di(t,e,r){let i=await ke(t,r);i&&(i.skills=e,await Be(i,r))}var Od,_s,cn=et(()=>{"use strict";an();ne();Le();Od=H("agent-config"),_s=384});var Na=ae(($2,Bd)=>{Bd.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 Es=ae(Fd=>{var zd={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 lm(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(zd))Fd[t]=lm(zd[t])});var jd=ae((J2,qd)=>{var dm=ue("fs"),Oe=ue("path"),Ud=Na(),um=Es(),fm=typeof process=="object"&&process.platform==="win32",Gd=t=>typeof t=="object"&&t!==null,Hd=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 ve(t){this.sep=Oe.sep,this.fs=dm,Gd(t)&&Gd(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}qd.exports=ve;ve.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var l;try{l=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(l&&l.isFile())throw um.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};ve.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var l=Oe.dirname(t);o.fs.existsSync(l)||o.makeDir(l);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};ve.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!r)return o(!1);c.fs.stat(t,function(u,x){if(l&&x.isDirectory())return o(!1);var h=Oe.dirname(t);c.fs.exists(h,function(m){m||c.makeDir(h),c.fs.open(t,"w",438,function(w,S){w?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(_,v){c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):S?c.fs.write(S,e,0,e.length,0,function(){c.fs.close(S,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};ve.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let x=Oe.join(i,u),h=e.fs.statSync(x);(!o||o.test(x))&&l.push(Oe.normalize(x)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&c&&(l=l.concat(r(x,o,c)))}),l}return r(t,void 0,!0)};ve.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=Oe.join(t,u),r.fs.stat(u,function(x,h){if(x)return e(x);h&&(i.push(Oe.normalize(u)+(h.isDirectory()?r.sep:"")),h.isDirectory()?r.findFilesAsync(u,function(m,w){if(m)return e(m);i=i.concat(w),--l||e(null,i)}):--l||e(null,i))})})})};ve.prototype.getAttributes=function(){};ve.prototype.setAttributes=function(){};ve.crc32update=function(t,e){return Hd[(t^e)&255]^t>>>8};ve.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=ve.crc32update(r,t[i++]);return~r>>>0};ve.methodToString=function(t){switch(t){case Ud.STORED:return"STORED ("+t+")";case Ud.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ve.canonical=function(t){if(!t)return"";let e=Oe.posix.normalize("/"+t.split("\\").join("/"));return Oe.join(".",e)};ve.zipnamefix=function(t){if(!t)return"";let e=Oe.posix.normalize("/"+t.split("\\").join("/"));return Oe.posix.join(".",e)};ve.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]};ve.sanitize=function(t,e){t=Oe.resolve(Oe.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Oe.normalize(Oe.join(t,r.slice(i,o).join(Oe.sep)));if(c.indexOf(t)===0)return c}return Oe.normalize(Oe.join(t,Oe.basename(e)))};ve.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};ve.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ve.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ve.fromDate2DOS=function(t){let e=0,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};ve.isWin=fm;ve.crcTable=Hd});var Kd=ae((Y2,Wd)=>{var xm=ue("path");Wd.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=xm.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 Vd=ae((Z2,$d)=>{$d.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var xr=ae((X2,fr)=>{fr.exports=jd();fr.exports.Constants=Na();fr.exports.Errors=Es();fr.exports.FileAttr=Kd();fr.exports.decoder=Vd()});var Yd=ae((Q2,Jd)=>{var ln=xr(),U=ln.Constants;Jd.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,l=0,u=0,x=0,h=0,m=0,w=0,S=0,_=0,v=0;t|=ln.isWin?2560:768,r|=U.FLG_EFS;let I={extraLen:0},T=b=>Math.max(0,b)>>>0,R=b=>Math.max(0,b)&65535,P=b=>Math.max(0,b)&255;return o=ln.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return r},set flags(b){r=b},get flags_efs(){return(r&U.FLG_EFS)>0},set flags_efs(b){b?r|=U.FLG_EFS:r&=~U.FLG_EFS},get flags_desc(){return(r&U.FLG_DESC)>0},set flags_desc(b){b?r|=U.FLG_DESC:r&=~U.FLG_DESC},get method(){return i},set method(b){switch(b){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=b},get time(){return ln.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=ln.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=T(b)},get timeHighByte(){return P(o>>>8)},get crc(){return c},set crc(b){c=T(b)},get compressedSize(){return l},set compressedSize(b){l=T(b)},get size(){return u},set size(b){u=T(b)},get fileNameLength(){return x},set fileNameLength(b){x=b},get extraLength(){return h},set extraLength(b){h=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return m},set commentLength(b){m=b},get diskNumStart(){return w},set diskNumStart(b){w=T(b)},get inAttr(){return S},set inAttr(b){S=T(b)},get attr(){return _},set attr(b){_=T(b)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(b){v=T(b)},get encrypted(){return(r&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+x+h+m},get realDataOffset(){return v+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var C=b.slice(v,v+U.LOCHDR);if(C.readUInt32LE(0)!==U.LOCSIG)throw ln.Errors.INVALID_LOC();I.version=C.readUInt16LE(U.LOCVER),I.flags=C.readUInt16LE(U.LOCFLG),I.flags_desc=(I.flags&U.FLG_DESC)>0,I.method=C.readUInt16LE(U.LOCHOW),I.time=C.readUInt32LE(U.LOCTIM),I.crc=C.readUInt32LE(U.LOCCRC),I.compressedSize=C.readUInt32LE(U.LOCSIZ),I.size=C.readUInt32LE(U.LOCLEN),I.fnameLen=C.readUInt16LE(U.LOCNAM),I.extraLen=C.readUInt16LE(U.LOCEXT);let L=v+U.LOCHDR+I.fnameLen,z=L+I.extraLen;return b.slice(L,z)},loadFromBinary:function(b){if(b.length!==U.CENHDR||b.readUInt32LE(0)!==U.CENSIG)throw ln.Errors.INVALID_CEN();t=b.readUInt16LE(U.CENVEM),e=b.readUInt16LE(U.CENVER),r=b.readUInt16LE(U.CENFLG),i=b.readUInt16LE(U.CENHOW),o=b.readUInt32LE(U.CENTIM),c=b.readUInt32LE(U.CENCRC),l=b.readUInt32LE(U.CENSIZ),u=b.readUInt32LE(U.CENLEN),x=b.readUInt16LE(U.CENNAM),h=b.readUInt16LE(U.CENEXT),m=b.readUInt16LE(U.CENCOM),w=b.readUInt16LE(U.CENDSK),S=b.readUInt16LE(U.CENATT),_=b.readUInt32LE(U.CENATX),v=b.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(U.LOCHDR);return b.writeUInt32LE(U.LOCSIG,0),b.writeUInt16LE(e,U.LOCVER),b.writeUInt16LE(r,U.LOCFLG),b.writeUInt16LE(i,U.LOCHOW),b.writeUInt32LE(o,U.LOCTIM),b.writeUInt32LE(c,U.LOCCRC),b.writeUInt32LE(l,U.LOCSIZ),b.writeUInt32LE(u,U.LOCLEN),b.writeUInt16LE(x,U.LOCNAM),b.writeUInt16LE(I.extraLen,U.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(U.CENHDR+x+h+m);return b.writeUInt32LE(U.CENSIG,0),b.writeUInt16LE(t,U.CENVEM),b.writeUInt16LE(e,U.CENVER),b.writeUInt16LE(r,U.CENFLG),b.writeUInt16LE(i,U.CENHOW),b.writeUInt32LE(o,U.CENTIM),b.writeUInt32LE(c,U.CENCRC),b.writeUInt32LE(l,U.CENSIZ),b.writeUInt32LE(u,U.CENLEN),b.writeUInt16LE(x,U.CENNAM),b.writeUInt16LE(h,U.CENEXT),b.writeUInt16LE(m,U.CENCOM),b.writeUInt16LE(w,U.CENDSK),b.writeUInt16LE(S,U.CENATT),b.writeUInt32LE(_,U.CENATX),b.writeUInt32LE(v,U.CENOFF),b},toJSON:function(){let b=function(C){return C+" bytes"};return{made:t,version:e,flags:r,method:ln.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(l),size:b(u),fileNameLength:b(x),extraLength:b(h),commentLength:b(m),diskNumStart:w,inAttr:S,attr:_,offset:v,centralHeaderSize:b(U.CENHDR+x+h+m)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Xd=ae((eI,Zd)=>{var hr=xr(),ye=hr.Constants;Zd.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 hr.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=hr.readBigUInt64LE(c,ye.ZIP64SUB),e=hr.readBigUInt64LE(c,ye.ZIP64TOT),r=hr.readBigUInt64LE(c,ye.ZIP64SIZE),i=hr.readBigUInt64LE(c,ye.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(ye.ENDHDR+o);return c.writeUInt32LE(ye.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,ye.ENDSUB),c.writeUInt16LE(e,ye.ENDTOT),c.writeUInt32LE(r,ye.ENDSIZ),c.writeUInt32LE(i,ye.ENDOFF),c.writeUInt16LE(o,ye.ENDCOM),c.fill(" ",ye.ENDHDR),c},toJSON:function(){let c=function(l,u){let x=l.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 Ba=ae(Ma=>{Ma.EntryHeader=Yd();Ma.MainHeader=Xd()});var eu=ae((nI,Qd)=>{Qd.exports=function(t){var e=ue("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],l=0;o.on("data",function(u){c.push(u),l+=u.length}),o.on("end",function(){var u=Buffer.alloc(l),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 nu=ae((rI,tu)=>{var hm=+(process.versions?process.versions.node:"").split(".")[0]||0;tu.exports=function(t,e){var r=ue("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),l=[],u=0;c.on("data",function(x){l.push(x),u+=x.length}),c.on("end",function(){var x=Buffer.alloc(u),h=0;x.fill(0);for(var m=0;m<l.length;m++){var w=l[m];w.copy(x,h),h+=w.length}o&&o(x)}),c.end(t)}}}});var au=ae((iI,ou)=>{"use strict";var{randomFillSync:ru}=ue("crypto"),pm=Es(),gm=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}),su=(t,e)=>Math.imul(t,e)>>>0,iu=(t,e)=>gm[(t^e)&255]^t>>>8,ui=()=>typeof ru=="function"?ru(Buffer.alloc(12)):ui.node();ui.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 vs={genSalt:ui};function Ss(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])}Ss.prototype.updateKeys=function(t){let e=this.keys;return e[0]=iu(e[0],t),e[1]+=e[0]&255,e[1]=su(e[1],134775813)+1,e[2]=iu(e[2],e[1]>>>24),t};Ss.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return su(t,t^1)>>8&255};function mm(t){let e=new Ss(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 Ss(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let l=e.next();i[o++]=c^l,e.updateKeys(c)}return i}}function _m(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=mm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw pm.WRONG_PASSWORD();return i(t.slice(12))}function ym(t){Buffer.isBuffer(t)&&t.length>=12?vs.genSalt=function(){return t.slice(0,12)}:t==="node"?vs.genSalt=ui.node:vs.genSalt=ui}function bm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=wm(r),c=vs.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return o(c,l),o(t,l,12)}ou.exports={decrypt:_m,encrypt:bm,_salter:ym}});var cu=ae(Is=>{Is.Deflater=eu();Is.Inflater=nu();Is.ZipCrypto=au()});var Fa=ae((oI,lu)=>{var ce=xr(),Em=Ba(),Se=ce.Constants,za=cu();lu.exports=function(t,e){var r=new Em.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),x=Buffer.alloc(0),h=!0;let m=t,w=typeof m.decoder=="object"?m.decoder:ce.decoder;h=w.hasOwnProperty("efs")?w.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(x=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function _(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let C={},L=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(L)==Se.LOCSIG||e.readUInt32LE(L)==Se.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(L)==Se.EXTSIG)C.crc=e.readUInt32LE(L+Se.EXTCRC),C.compressedSize=e.readUInt32LE(L+Se.EXTSIZ),C.size=e.readUInt32LE(L+Se.EXTLEN);else if(e.readUInt16LE(L+12)===19280)C.crc=e.readUInt32LE(L+Se.EXTCRC-4),C.compressedSize=e.readUInt32LE(L+Se.EXTSIZ-4),C.size=e.readUInt32LE(L+Se.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==r.compressedSize||C.size!==r.size||C.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==C.crc)return!1}return!0}function v(b,C,L){if(typeof C>"u"&&typeof b=="string"&&(L=b,b=void 0),c)return b&&C&&C(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=S();if(z.length===0)return b&&C&&C(z),z;if(r.encrypted){if(typeof L!="string"&&!Buffer.isBuffer(L))throw ce.Errors.INVALID_PASS_PARAM();z=za.ZipCrypto.decrypt(z,r,L)}var B=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(z.copy(B),_(B))return b&&C&&C(B),B;throw b&&C&&C(B,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var J=new za.Inflater(z,r.size);if(b)J.inflateAsync(function(V){V.copy(V,0),C&&(_(V)?C(V):C(V,ce.Errors.BAD_CRC()))});else{if(J.inflate(B).copy(B,0),!_(B))throw ce.Errors.BAD_CRC(`"${w.decode(i)}"`);return B}break;default:throw b&&C&&C(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(b,C){if((!l||!l.length)&&Buffer.isBuffer(e))return b&&C&&C(S()),S();if(l.length&&!c){var L;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,L=Buffer.alloc(l.length),l.copy(L),b&&C&&C(L),L;default:case ce.Constants.DEFLATED:var z=new za.Deflater(l);if(b)z.deflateAsync(function(J){L=Buffer.alloc(J.length),r.compressedSize=J.length,J.copy(L),C&&C(L)});else{var B=z.deflate();return r.compressedSize=B.length,B}z=null;break}}else if(b&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function T(b,C){return ce.readBigUInt64LE(b,C)}function R(b){try{for(var C=0,L,z,B;C+4<b.length;)L=b.readUInt16LE(C),C+=2,z=b.readUInt16LE(C),C+=2,B=b.slice(C,C+z),C+=z,Se.ID_ZIP64===L&&P(B)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(b){var C,L,z,B;b.length>=Se.EF_ZIP64_SCOMP&&(C=T(b,Se.EF_ZIP64_SUNCOMP),r.size===Se.EF_ZIP64_OR_32&&(r.size=C)),b.length>=Se.EF_ZIP64_RHO&&(L=T(b,Se.EF_ZIP64_SCOMP),r.compressedSize===Se.EF_ZIP64_OR_32&&(r.compressedSize=L)),b.length>=Se.EF_ZIP64_DSN&&(z=T(b,Se.EF_ZIP64_RHO),r.offset===Se.EF_ZIP64_OR_32&&(r.offset=z)),b.length>=Se.EF_ZIP64_DSN+4&&(B=b.readUInt32LE(Se.EF_ZIP64_DSN),r.diskNumStart===Se.EF_ZIP64_OR_16&&(r.diskNumStart=B))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,w.encode);var C=i[i.length-1];c=C===47||C===92,r.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,R(b)},get comment(){return w.decode(o)},set comment(b){if(o=ce.toBuffer(b,w.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var b=w.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){l=ce.toBuffer(b,ce.decoder.encode),!c&&l.length?(r.size=l.length,r.method=ce.Constants.DEFLATED,r.crc=ce.crc32(b),r.changed=!0):r.method=ce.Constants.STORED},getData:function(b){return r.changed?l:v(!1,null,b)},getDataAsync:function(b,C){r.changed?b(l):v(!0,b,C)},set attr(b){r.attr=b},get attr(){return r.attr},set header(b){r.loadFromBinary(b)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var b=r.centralHeaderToBinary(),C=ce.Constants.CENHDR;return i.copy(b,C),C+=i.length,u.copy(b,C),C+=r.extraLength,o.copy(b,C),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=x.length;let C=r.localHeaderToBinary(),L=Buffer.alloc(C.length+i.length+r.extraLocalLength);return C.copy(L,b),b+=C.length,i.copy(L,b),b+=i.length,x.copy(L,b),b+=x.length,L},toJSON:function(){let b=function(C){return"<"+(C&&C.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:b(e),data:b(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var fu=ae((aI,uu)=>{var du=Fa(),vm=Ba(),We=xr();uu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new vm.MainHeader,l=!1,u=null;let x=new Set,h=e,{noSort:m,decoder:w}=h;t?v(h.readEntries):l=!0;function S(){let T=new Set;for(let R of Object.keys(i)){let P=R.split("/");if(P.pop(),!!P.length)for(let b=0;b<P.length;b++){let C=P.slice(0,b+1).join("/")+"/";T.add(C)}}for(let R of T)if(!(R in i)){let P=new du(h);P.entryName=R,P.attr=16,P.temporary=!0,r.push(P),i[P.entryName]=P,x.add(P)}}function _(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/We.Constants.CENHDR)throw We.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var T=c.offset,R=0;R<r.length;R++){var P=T,b=new du(h,t);b.header=t.slice(P,P+=We.Constants.CENHDR),b.entryName=t.slice(P,P+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(P,P+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(P,P+b.header.commentLength)),T+=b.header.centralHeaderSize,r[R]=b,i[b.entryName]=b}x.clear(),S()}function v(T){var R=t.length-We.Constants.ENDHDR,P=Math.max(0,R-65535),b=P,C=t.length,L=-1,z=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(P=0),R;R>=b;R--)if(t[R]===80){if(t.readUInt32LE(R)===We.Constants.ENDSIG){L=R,z=R,C=R+We.Constants.ENDHDR,b=R-We.Constants.END64HDR;continue}if(t.readUInt32LE(R)===We.Constants.END64SIG){b=P;continue}if(t.readUInt32LE(R)===We.Constants.ZIP64SIG){L=R,C=R+We.readBigUInt64LE(t,R+We.Constants.ZIP64SIZE)+We.Constants.ZIP64LEAD;break}}if(L==-1)throw We.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(L,C)),c.commentLength&&(o=t.slice(z+We.Constants.ENDHDR)),T&&_()}function I(){r.length>1&&!m&&r.sort((T,R)=>T.entryName.toLowerCase().localeCompare(R.entryName.toLowerCase()))}return{get entries(){return l||_(),r.filter(T=>!x.has(T))},get comment(){return w.decode(o)},set comment(T){o=We.toBuffer(T,w.encode),c.commentLength=o.length},getEntryCount:function(){return l?r.length:c.diskEntries},forEach:function(T){this.entries.forEach(T)},getEntry:function(T){return l||_(),i[T]||null},setEntry:function(T){l||_(),r.push(T),i[T.entryName]=T,c.totalEntries=r.length},deleteFile:function(T,R=!0){l||_();let P=i[T];this.getEntryChildren(P,R).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(T){l||_();let R=i[T],P=r.indexOf(R);P>=0&&(r.splice(P,1),delete i[T],c.totalEntries=r.length)},getEntryChildren:function(T,R=!0){if(l||_(),typeof T=="object")if(T.isDirectory&&R){let P=[],b=T.entryName;for(let C of r)C.entryName.startsWith(b)&&P.push(C);return P}else return[T];return[]},getChildCount:function(T){if(T&&T.isDirectory){let R=this.getEntryChildren(T);return R.includes(T)?R.length-1:R.length}return 0},compressToBuffer:function(){l||_(),I();let T=[],R=[],P=0,b=0;c.size=0,c.offset=0;let C=0;for(let B of this.entries){let J=B.getCompressedData();B.header.offset=b;let V=B.packLocalHeader(),re=V.length+J.length;b+=re,T.push(V),T.push(J);let Z=B.packCentralHeader();R.push(Z),c.size+=Z.length,P+=re+Z.length,C++}P+=c.mainHeaderSize,c.offset=b,c.totalEntries=C,b=0;let L=Buffer.alloc(P);for(let B of T)B.copy(L,b),b+=B.length;for(let B of R)B.copy(L,b),b+=B.length;let z=c.toBinary();return o&&o.copy(z,We.Constants.ENDHDR),z.copy(L,b),t=L,l=!1,L},toAsyncBuffer:function(T,R,P,b){try{l||_(),I();let C=[],L=[],z=0,B=0,J=0;c.size=0,c.offset=0;let V=function(re){if(re.length>0){let Z=re.shift(),se=Z.entryName+Z.extra.toString();P&&P(se),Z.getCompressedDataAsync(function(oe){b&&b(se),Z.header.offset=B;let D=Z.packLocalHeader(),G=D.length+oe.length;B+=G,C.push(D),C.push(oe);let K=Z.packCentralHeader();L.push(K),c.size+=K.length,z+=G+K.length,J++,V(re)})}else{z+=c.mainHeaderSize,c.offset=B,c.totalEntries=J,B=0;let Z=Buffer.alloc(z);C.forEach(function(oe){oe.copy(Z,B),B+=oe.length}),L.forEach(function(oe){oe.copy(Z,B),B+=oe.length});let se=c.toBinary();o&&o.copy(se,We.Constants.ENDHDR),se.copy(Z,B),t=Z,l=!1,T(Z)}};V(Array.from(this.entries))}catch(C){R(C)}}}}});var pu=ae((cI,hu)=>{var Ee=xr(),be=ue("path"),Sm=Fa(),Im=fu(),Pn=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),xu=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Am=(...t)=>Ee.findLast(t,e=>typeof e=="function"),Tm={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};hu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Tm);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 Im(r,i),{canonical:l,sanitize:u,zipnamefix:x}=Ee;function h(_){if(_&&c){var v;if(typeof _=="string"&&(v=c.getEntry(be.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=c.getEntry(_.entryName)),v)return v}return null}function m(_){let{join:v,normalize:I,sep:T}=be.posix;return v(be.isAbsolute(_)?"/":".",I(T+_.split("\\").join(T)+T))}function w(_){return _ instanceof RegExp?(function(v){return function(I){return v.test(I)}})(_):typeof _!="function"?()=>!0:_}let S=(_,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",be.relative(_,v)+I};return{readFile:function(_,v){var I=h(_);return I&&I.getData(v)||null},childCount:function(_){let v=h(_);if(v)return c.getChildCount(v)},readFileAsync:function(_,v){var I=h(_);I?I.getDataAsync(v):v(null,"getEntry failed for:"+_)},readAsText:function(_,v){var I=h(_);if(I){var T=I.getData();if(T&&T.length)return T.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var T=h(_);T?T.getDataAsync(function(R,P){if(P){v(R,P);return}R&&R.length?v(R.toString(I||"utf8")):v("")}):v("")},deleteFile:function(_,v=!0){var I=h(_);I&&c.deleteFile(I.entryName,v)},deleteEntry:function(_){var v=h(_);v&&c.deleteEntry(v.entryName)},addZipComment:function(_){c.comment=_},getZipComment:function(){return c.comment||""},addZipEntryComment:function(_,v){var I=h(_);I&&(I.comment=v)},getZipEntryComment:function(_){var v=h(_);return v&&v.comment||""},updateFile:function(_,v){var I=h(_);I&&I.setData(v)},addLocalFile:function(_,v,I,T){if(o.fs.existsSync(_)){v=v?m(v):"";let R=be.win32.basename(be.win32.normalize(_));v+=I||R;let P=o.fs.statSync(_),b=P.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);P.isDirectory()&&(v+=o.sep),this.addFile(v,b,T,P)}else throw Ee.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=be.resolve(_.localPath),{comment:T}=_,{zipPath:R,zipName:P}=_,b=this;o.fs.stat(I,function(C,L){if(C)return v(C,!1);R=R?m(R):"";let z=be.win32.basename(be.win32.normalize(I));if(R+=P||z,L.isFile())o.fs.readFile(I,function(B,J){return B?v(B,!1):(b.addFile(R,J,T,L),setImmediate(v,void 0,!0))});else if(L.isDirectory())return R+=o.sep,b.addFile(R,Buffer.alloc(0),T,L),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=w(I),v=v?m(v):"",_=be.normalize(_),o.fs.existsSync(_)){let T=o.findFiles(_),R=this;if(T.length)for(let P of T){let b=be.join(v,S(_,P));I(b)&&R.addLocalFile(P,be.dirname(b))}}else throw Ee.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,T){T=w(T),I=I?m(I):"",_=be.normalize(_);var R=this;o.fs.open(_,"r",function(P){if(P&&P.code==="ENOENT")v(void 0,Ee.Errors.FILE_NOT_FOUND(_));else if(P)v(void 0,P);else{var b=o.findFiles(_),C=-1,L=function(){if(C+=1,C<b.length){var z=b[C],B=S(_,z).split("\\").join("/");B=B.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),T(B)?o.fs.stat(z,function(J,V){J&&v(void 0,J),V.isFile()?o.fs.readFile(z,function(re,Z){re?v(void 0,re):(R.addFile(I+B,Z,"",V),L())}):(R.addFile(I+B+"/",Buffer.alloc(0),"",V),L())}):process.nextTick(()=>{L()})}else v(!0,void 0)};L()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=be.resolve(m(_.localPath));let{zipPath:T,filter:R,namefix:P}=_;R instanceof RegExp?R=(function(L){return function(z){return L.test(z)}})(R):typeof R!="function"&&(R=function(){return!0}),T=T?m(T):"",P=="latin1"&&(P=L=>L.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=L=>L);let b=L=>be.join(T,P(S(localPath,L))),C=L=>be.win32.basename(be.win32.normalize(P(L)));o.fs.open(localPath,"r",function(L){L&&L.code==="ENOENT"?v(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):L?v(void 0,L):o.findFilesAsync(localPath,function(z,B){if(z)return v(z);B=B.filter(J=>R(b(J))),B.length||v(void 0,!1),setImmediate(B.reverse().reduce(function(J,V){return function(re,Z){if(re||Z===!1)return setImmediate(J,re,!1);I.addLocalFileAsync({localPath:V,zipPath:be.dirname(b(V)),zipName:C(V)},J)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,T)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(R,P)=>{R&&T(R),P&&I(this)})})},addFile:function(_,v,I,T){_=x(_);let R=h(_),P=R!=null;P||(R=new Sm(i),R.entryName=_),R.comment=I||"";let b=typeof T=="object"&&T instanceof o.fs.Stats;b&&(R.header.time=T.mtime);var C=R.isDirectory?16:0;let L=R.isDirectory?16384:32768;return b?L|=4095&T.mode:typeof T=="number"?L|=4095&T:L|=R.isDirectory?493:420,C=(C|L<<16)>>>0,R.attr=C,R.setData(v),P||c.setEntry(R),R},getEntries:function(_){return c.password=_,c?c.entries:[]},getEntry:function(_){return h(_)},getEntryCount:function(){return c.getEntryCount()},forEach:function(_){return c.forEach(_)},extractEntryTo:function(_,v,I,T,R,P){T=Pn(!1,T),R=Pn(!1,R),I=Pn(!0,I),P=xu(R,P);var b=h(_);if(!b)throw Ee.Errors.NO_ENTRY();var C=l(b.entryName),L=u(v,P&&!b.isDirectory?P:I?C:be.basename(C));if(b.isDirectory){var z=c.getEntryChildren(b);return z.forEach(function(V){if(V.isDirectory)return;var re=V.getData();if(!re)throw Ee.Errors.CANT_EXTRACT_FILE();var Z=l(V.entryName),se=u(v,I?Z:be.basename(Z));let oe=R?V.header.fileAttr:void 0;o.writeFileTo(se,re,T,oe)}),!0}var B=b.getData(c.password);if(!B)throw Ee.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(L)&&!T)throw Ee.Errors.CANT_OVERRIDE();let J=R?_.header.fileAttr:void 0;return o.writeFileTo(L,B,T,J),!0},test:function(_){if(!c)return!1;for(var v in c.entries)try{if(v.isDirectory)continue;var I=c.entries[v].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,v,I,T){if(I=Pn(!1,I),T=xu(I,T),v=Pn(!1,v),!c)throw Ee.Errors.NO_ZIP();c.entries.forEach(function(R){var P=u(_,l(R.entryName));if(R.isDirectory){o.makeDir(P);return}var b=R.getData(T);if(!b)throw Ee.Errors.CANT_EXTRACT_FILE();let C=I?R.header.fileAttr:void 0;o.writeFileTo(P,b,v,C);try{o.fs.utimesSync(P,R.header.time,R.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,T){if(T=Am(v,I,T),I=Pn(!1,I),v=Pn(!1,v),!T)return new Promise((L,z)=>{this.extractAllToAsync(_,v,I,function(B){B?z(B):L(this)})});if(!c){T(Ee.Errors.NO_ZIP());return}_=be.resolve(_);let R=L=>u(_,be.normalize(l(L.entryName))),P=(L,z)=>new Error(L+': "'+z+'"'),b=[],C=[];c.entries.forEach(L=>{L.isDirectory?b.push(L):C.push(L)});for(let L of b){let z=R(L),B=I?L.header.fileAttr:void 0;try{o.makeDir(z),B&&o.fs.chmodSync(z,B),o.fs.utimesSync(z,L.header.time,L.header.time)}catch{T(P("Unable to create folder",z))}}C.reverse().reduce(function(L,z){return function(B){if(B)L(B);else{let J=be.normalize(l(z.entryName)),V=u(_,J);z.getDataAsync(function(re,Z){if(Z)L(Z);else if(!re)L(Ee.Errors.CANT_EXTRACT_FILE());else{let se=I?z.header.fileAttr:void 0;o.writeFileToAsync(V,re,v,se,function(oe){oe||L(P("Unable to write file",V)),o.fs.utimes(V,z.header.time,z.header.time,function(D){D?L(P("Unable to set times",V)):L()})})}})}}},T)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=c.compressToBuffer();if(I){var T=o.writeFileTo(_,I,!0);typeof v=="function"&&v(T?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:T}=Object.assign({overwrite:!0},v);return new Promise((R,P)=>{!_&&i.filename&&(_=i.filename),_||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let C=L=>L?R(L):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,b,I,T,C)},P)})},toBufferPromise:function(){return new Promise((_,v)=>{c.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,T){return typeof _=="function"?(c.toAsyncBuffer(_,v,I,T),null):c.compressToBuffer()}}}});import{execFile as L_,spawn as O_,spawnSync as AA}from"node:child_process";import{promisify as N_}from"node:util";function B_(t){if(process.platform!=="win32")return!1;if(Nf.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Nf,"").toLowerCase();return M_.has(r)}function Mf(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return B_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function rt(t,e=[],r={}){return O_(t,e,Mf(t,r))}function Bf(t,e=[],r={}){return z_(t,e,Mf(t,r))}var M_,Nf,z_,$t=et(()=>{"use strict";M_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Nf=/\.(cmd|bat|ps1)$/i;z_=N_(L_)});var Jt=ae((xC,Ex)=>{"use strict";var yx=["nodebuffer","arraybuffer","fragments"],bx=typeof Blob<"u";bx&&yx.push("blob");Ex.exports={BINARY_TYPES:yx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Xi=ae((hC,Po)=>{"use strict";var{EMPTY_BUFFER:mE}=Jt(),pl=Buffer[Symbol.species];function wE(t,e){if(t.length===0)return mE;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 pl(r.buffer,r.byteOffset,i):r}function vx(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function Sx(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function _E(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function gl(t){if(gl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pl(t):ArrayBuffer.isView(t)?e=new pl(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),gl.readOnly=!1),e}Po.exports={concat:wE,mask:vx,toArrayBuffer:_E,toBuffer:gl,unmask:Sx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");Po.exports.mask=function(e,r,i,o,c){c<48?vx(e,r,i,o,c):t.mask(e,r,i,o,c)},Po.exports.unmask=function(e,r){e.length<32?Sx(e,r):t.unmask(e,r)}}catch{}});var Tx=ae((pC,Ax)=>{"use strict";var Ix=Symbol("kDone"),ml=Symbol("kRun"),wl=class{constructor(e){this[Ix]=()=>{this.pending--,this[ml]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ml]()}[ml](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ix])}}};Ax.exports=wl});var Ur=ae((gC,Dx)=>{"use strict";var Qi=ue("zlib"),kx=Xi(),yE=Tx(),{kStatusCode:Rx}=Jt(),bE=Buffer[Symbol.species],EE=Buffer.from([0,0,255,255]),Oo=Symbol("permessage-deflate"),Yt=Symbol("total-length"),zr=Symbol("callback"),Tn=Symbol("buffers"),Fr=Symbol("error"),Lo,_l=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,!Lo){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Lo=new yE(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[zr];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){Lo.add(o=>{this._decompress(e,r,(c,l)=>{o(),i(c,l)})})}compress(e,r,i){Lo.add(o=>{this._compress(e,r,(c,l)=>{o(),i(c,l)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Qi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Qi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[Oo]=this,this._inflate[Yt]=0,this._inflate[Tn]=[],this._inflate.on("error",SE),this._inflate.on("data",Cx)}this._inflate[zr]=i,this._inflate.write(e),r&&this._inflate.write(EE),this._inflate.flush(()=>{let c=this._inflate[Fr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=kx.concat(this._inflate[Tn],this._inflate[Yt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yt]=0,this._inflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Qi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Qi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[Yt]=0,this._deflate[Tn]=[],this._deflate.on("data",vE)}this._deflate[zr]=i,this._deflate.write(e),this._deflate.flush(Qi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=kx.concat(this._deflate[Tn],this._deflate[Yt]);r&&(c=new bE(c.buffer,c.byteOffset,c.length-4)),this._deflate[zr]=null,this._deflate[Yt]=0,this._deflate[Tn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};Dx.exports=_l;function vE(t){this[Tn].push(t),this[Yt]+=t.length}function Cx(t){if(this[Yt]+=t.length,this[Oo]._maxPayload<1||this[Yt]<=this[Oo]._maxPayload){this[Tn].push(t);return}this[Fr]=new RangeError("Max payload size exceeded"),this[Fr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fr][Rx]=1009,this.removeListener("data",Cx),this.reset()}function SE(t){if(this[Oo]._inflate=null,this[Fr]){this[zr](this[Fr]);return}t[Rx]=1007,this[zr](t)}});var Gr=ae((mC,No)=>{"use strict";var{isUtf8:Px}=ue("buffer"),{hasBlob:IE}=Jt(),AE=[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 TE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function yl(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 kE(t){return IE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}No.exports={isBlob:kE,isValidStatusCode:TE,isValidUTF8:yl,tokenChars:AE};if(Px)No.exports.isValidUTF8=function(t){return t.length<24?yl(t):Px(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");No.exports.isValidUTF8=function(e){return e.length<32?yl(e):t(e)}}catch{}});var Il=ae((wC,Fx)=>{"use strict";var{Writable:RE}=ue("stream"),Lx=Ur(),{BINARY_TYPES:CE,EMPTY_BUFFER:Ox,kStatusCode:DE,kWebSocket:PE}=Jt(),{concat:bl,toArrayBuffer:LE,unmask:OE}=Xi(),{isValidStatusCode:NE,isValidUTF8:Nx}=Gr(),Mo=Buffer[Symbol.species],xt=0,Mx=1,Bx=2,zx=3,El=4,vl=5,Bo=6,Sl=class extends RE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||CE[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[PE]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=xt}_write(e,r,i){if(this._opcode===8&&this._state==xt)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Mo(i.buffer,i.byteOffset+e,i.length-e),new Mo(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 Mo(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 Mx:this.getPayloadLength16(e);break;case Bx:this.getPayloadLength64(e);break;case zx:this.getMask();break;case El:this.getData(e);break;case vl:case Bo: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[Lx.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=Mx:this._payloadLength===127?this._state=Bx: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=zx:this._state=El}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=El}getData(e){let r=Ox;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&&OE(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=vl,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[Lx.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(l);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let l=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(l);return}this._fragments.push(c)}this.dataMessage(r),this._state===xt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=xt;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=bl(i,r):this._binaryType==="arraybuffer"?o=LE(bl(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=xt):(this._state=Bo,setImmediate(()=>{this.emit("message",o,!0),this._state=xt,this.startLoop(e)}))}else{let o=bl(i,r);if(!this._skipUTF8Validation&&!Nx(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===vl||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=xt):(this._state=Bo,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,Ox),this.end();else{let i=e.readUInt16BE(0);if(!NE(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Mo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Nx(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=Bo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xt,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(l,this.createError),l.code=c,l[DE]=o,l}};Fx.exports=Sl});var kl=ae((yC,Hx)=>{"use strict";var{Duplex:_C}=ue("stream"),{randomFillSync:ME}=ue("crypto"),{types:{isUint8Array:BE}}=ue("util"),Ux=Ur(),{EMPTY_BUFFER:zE,kWebSocket:FE,NOOP:UE}=Jt(),{isBlob:Hr,isValidStatusCode:GE}=Gr(),{mask:Gx,toBuffer:Vn}=Xi(),ht=Symbol("kByteLength"),HE=Buffer.alloc(4),zo=8*1024,Jn,qr=zo,St=0,qE=1,jE=2,Al=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=UE,this[FE]=void 0}static frame(e,r){let i,o=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||HE,r.generateMask?r.generateMask(i):(qr===zo&&(Jn===void 0&&(Jn=Buffer.alloc(zo)),ME(Jn,0,zo),qr=0),i[0]=Jn[qr++],i[1]=Jn[qr++],i[2]=Jn[qr++],i[3]=Jn[qr++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||l)&&r[ht]!==void 0?u=r[ht]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!l);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],l?[h,e]:o?(Gx(e,i,h,c,u),[h]):(Gx(e,i,e,0,u),[h,e])):[h,e]}close(e,r,i,o){let c;if(e===void 0)c=zE;else{if(typeof e!="number"||!GE(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(BE(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let l={[ht]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,c,!1,l,o]):this.sendFrame(t.frame(c,l),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Hr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[ht]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Hr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Hr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[ht]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Hr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==St?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let o=this._extensions[Ux.extensionName],c=r.binary?2:1,l=r.compress,u,x;typeof e=="string"?(u=Buffer.byteLength(e),x=!1):Hr(e)?(u=e.size,x=!1):(e=Vn(e),u=e.length,x=Vn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=o._threshold),this._compress=l):(l=!1,c=0),r.fin&&(this._firstFragment=!0);let h={[ht]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:x,rsv1:l};Hr(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==St?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[ht],this._state=jE,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Tl,this,u,o);return}this._bufferedBytes-=i[ht];let l=Vn(c);r?this.dispatch(l,r,i,o):(this._state=St,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(WE,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Ux.extensionName];this._bufferedBytes+=i[ht],this._state=qE,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let x=new Error("The socket was closed while data was being compressed");Tl(this,x,o);return}this._bufferedBytes-=i[ht],this._state=St,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ht],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ht],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Hx.exports=Al;function Tl(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 WE(t,e,r){Tl(t,e,r),t.onerror(e)}});var Zx=ae((bC,Yx)=>{"use strict";var{kForOnEventAttribute:es,kListener:Rl}=Jt(),qx=Symbol("kCode"),jx=Symbol("kData"),Wx=Symbol("kError"),Kx=Symbol("kMessage"),$x=Symbol("kReason"),jr=Symbol("kTarget"),Vx=Symbol("kType"),Jx=Symbol("kWasClean"),Zt=class{constructor(e){this[jr]=null,this[Vx]=e}get target(){return this[jr]}get type(){return this[Vx]}};Object.defineProperty(Zt.prototype,"target",{enumerable:!0});Object.defineProperty(Zt.prototype,"type",{enumerable:!0});var Yn=class extends Zt{constructor(e,r={}){super(e),this[qx]=r.code===void 0?0:r.code,this[$x]=r.reason===void 0?"":r.reason,this[Jx]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[qx]}get reason(){return this[$x]}get wasClean(){return this[Jx]}};Object.defineProperty(Yn.prototype,"code",{enumerable:!0});Object.defineProperty(Yn.prototype,"reason",{enumerable:!0});Object.defineProperty(Yn.prototype,"wasClean",{enumerable:!0});var Wr=class extends Zt{constructor(e,r={}){super(e),this[Wx]=r.error===void 0?null:r.error,this[Kx]=r.message===void 0?"":r.message}get error(){return this[Wx]}get message(){return this[Kx]}};Object.defineProperty(Wr.prototype,"error",{enumerable:!0});Object.defineProperty(Wr.prototype,"message",{enumerable:!0});var ts=class extends Zt{constructor(e,r={}){super(e),this[jx]=r.data===void 0?null:r.data}get data(){return this[jx]}};Object.defineProperty(ts.prototype,"data",{enumerable:!0});var KE={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[es]&&o[Rl]===e&&!o[es])return;let i;if(t==="message")i=function(c,l){let u=new ts("message",{data:l?c:c.toString()});u[jr]=this,Fo(e,this,u)};else if(t==="close")i=function(c,l){let u=new Yn("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[jr]=this,Fo(e,this,u)};else if(t==="error")i=function(c){let l=new Wr("error",{error:c,message:c.message});l[jr]=this,Fo(e,this,l)};else if(t==="open")i=function(){let c=new Zt("open");c[jr]=this,Fo(e,this,c)};else return;i[es]=!!r[es],i[Rl]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Rl]===e&&!r[es]){this.removeListener(t,r);break}}};Yx.exports={CloseEvent:Yn,ErrorEvent:Wr,Event:Zt,EventTarget:KE,MessageEvent:ts};function Fo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Uo=ae((EC,Xx)=>{"use strict";var{tokenChars:ns}=Gr();function Mt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function $E(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,l,u,x=-1,h=-1,m=-1,w=0;for(;w<t.length;w++)if(h=t.charCodeAt(w),l===void 0)if(m===-1&&ns[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 _=t.slice(x,m);h===44?(Mt(e,_,r),r=Object.create(null)):l=_,x=m=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(m===-1&&ns[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),Mt(r,t.slice(x,m),!0),h===44&&(Mt(e,l,r),r=Object.create(null),l=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(ns[h]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);x===-1?x=w:i||(i=!0),o=!1}else if(c)if(ns[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&&ns[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 _=t.slice(x,m);i&&(_=_.replace(/\\/g,""),i=!1),Mt(r,u,_),h===44&&(Mt(e,l,r),r=Object.create(null),l=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 S=t.slice(x,m);return l===void 0?Mt(e,S,r):(u===void 0?Mt(r,S,!0):i?Mt(r,u,S.replace(/\\/g,"")):Mt(r,u,S),Mt(e,l,r)),e}function VE(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(l=>l===!0?o:`${o}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Xx.exports={format:VE,parse:$E}});var jo=ae((IC,dh)=>{"use strict";var JE=ue("events"),YE=ue("https"),ZE=ue("http"),th=ue("net"),XE=ue("tls"),{randomBytes:QE,createHash:ev}=ue("crypto"),{Duplex:vC,Readable:SC}=ue("stream"),{URL:Cl}=ue("url"),kn=Ur(),tv=Il(),nv=kl(),{isBlob:rv}=Gr(),{BINARY_TYPES:Qx,CLOSE_TIMEOUT:iv,EMPTY_BUFFER:Go,GUID:sv,kForOnEventAttribute:Dl,kListener:ov,kStatusCode:av,kWebSocket:He,NOOP:nh}=Jt(),{EventTarget:{addEventListener:cv,removeEventListener:lv}}=Zx(),{format:dv,parse:uv}=Uo(),{toBuffer:fv}=Xi(),rh=Symbol("kAborted"),Pl=[8,13],Xt=["CONNECTING","OPEN","CLOSING","CLOSED"],xv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,we=class t extends JE{constructor(e,r,i){super(),this._binaryType=Qx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Go,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){Qx.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 tv({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 nv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[He]=this,c[He]=this,e[He]=this,o.on("conclude",gv),o.on("drain",mv),o.on("error",wv),o.on("message",_v),o.on("ping",yv),o.on("pong",bv),c.onerror=Ev,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",ah),e.on("data",qo),e.on("end",ch),e.on("error",lh),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[kn.extensionName]&&this._extensions[kn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),oh(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){Ll(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Go,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){Ll(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Go,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){Ll(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[kn.extensionName]||(o.compress=!1),this._sender.send(e||Go,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){at(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,"CONNECTING",{enumerable:!0,value:Xt.indexOf("CONNECTING")});Object.defineProperty(we.prototype,"CONNECTING",{enumerable:!0,value:Xt.indexOf("CONNECTING")});Object.defineProperty(we,"OPEN",{enumerable:!0,value:Xt.indexOf("OPEN")});Object.defineProperty(we.prototype,"OPEN",{enumerable:!0,value:Xt.indexOf("OPEN")});Object.defineProperty(we,"CLOSING",{enumerable:!0,value:Xt.indexOf("CLOSING")});Object.defineProperty(we.prototype,"CLOSING",{enumerable:!0,value:Xt.indexOf("CLOSING")});Object.defineProperty(we,"CLOSED",{enumerable:!0,value:Xt.indexOf("CLOSED")});Object.defineProperty(we.prototype,"CLOSED",{enumerable:!0,value:Xt.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[Dl])return e[ov];return null},set(e){for(let r of this.listeners(t))if(r[Dl]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Dl]:!0})}})});we.prototype.addEventListener=cv;we.prototype.removeEventListener=lv;dh.exports=we;function ih(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:iv,protocolVersion:Pl[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,!Pl.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Pl.join(", ")})`);let c;if(e instanceof Cl)c=e;else try{c=new Cl(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let l=c.protocol==="wss:",u=c.protocol==="ws+unix:",x;if(c.protocol!=="ws:"&&!l&&!u?x=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?x="The URL's pathname is empty":c.hash&&(x="The URL contains a fragment identifier"),x){let I=new SyntaxError(x);if(t._redirects===0)throw I;Ho(t,I);return}let h=l?443:80,m=QE(16).toString("base64"),w=l?YE.request:ZE.request,S=new Set,_;if(o.createConnection=o.createConnection||(l?pv:hv),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&&(_=new kn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=dv({[kn.extensionName]:_.offer()})),r.length){for(let I of r){if(typeof I!="string"||!xv.test(I)||S.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");S.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[T,R]of Object.entries(I))i.headers[T.toLowerCase()]=R}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),v=t._req=w(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=w(o);o.timeout&&v.on("timeout",()=>{at(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[rh]||(v=t._req=null,Ho(t,I))}),v.on("response",I=>{let T=I.headers.location,R=I.statusCode;if(T&&o.followRedirects&&R>=300&&R<400){if(++t._redirects>o.maxRedirects){at(t,v,"Maximum redirects exceeded");return}v.abort();let P;try{P=new Cl(T,e)}catch{let C=new SyntaxError(`Invalid URL: ${T}`);Ho(t,C);return}ih(t,P,r,i)}else t.emit("unexpected-response",v,I)||at(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,T,R)=>{if(t.emit("upgrade",I),t.readyState!==we.CONNECTING)return;v=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){at(t,T,"Invalid Upgrade header");return}let b=ev("sha1").update(m+sv).digest("base64");if(I.headers["sec-websocket-accept"]!==b){at(t,T,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],L;if(C!==void 0?S.size?S.has(C)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":S.size&&(L="Server sent no subprotocol"),L){at(t,T,L);return}C&&(t._protocol=C);let z=I.headers["sec-websocket-extensions"];if(z!==void 0){if(!_){at(t,T,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let B;try{B=uv(z)}catch{at(t,T,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(B);if(J.length!==1||J[0]!==kn.extensionName){at(t,T,"Server indicated an extension that was not requested");return}try{_.accept(B[kn.extensionName])}catch{at(t,T,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[kn.extensionName]=_}t.setSocket(T,R,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function Ho(t,e){t._readyState=we.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function hv(t){return t.path=t.socketPath,th.connect(t)}function pv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=th.isIP(t.host)?"":t.host),XE.connect(t)}function at(t,e,r){t._readyState=we.CLOSING;let i=new Error(r);Error.captureStackTrace(i,at),e.setHeader?(e[rh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ho,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ll(t,e,r){if(e){let i=rv(e)?e.size:fv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Xt[t.readyState]})`);process.nextTick(r,i)}}function gv(t,e){let r=this[He];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[He]!==void 0&&(r._socket.removeListener("data",qo),process.nextTick(sh,r._socket),t===1005?r.close():r.close(t,e))}function mv(){let t=this[He];t.isPaused||t._socket.resume()}function wv(t){let e=this[He];e._socket[He]!==void 0&&(e._socket.removeListener("data",qo),process.nextTick(sh,e._socket),e.close(t[av])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function eh(){this[He].emitClose()}function _v(t,e){this[He].emit("message",t,e)}function yv(t){let e=this[He];e._autoPong&&e.pong(t,!this._isServer,nh),e.emit("ping",t)}function bv(t){this[He].emit("pong",t)}function sh(t){t.resume()}function Ev(t){let e=this[He];e.readyState!==we.CLOSED&&(e.readyState===we.OPEN&&(e._readyState=we.CLOSING,oh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function oh(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ah(){let t=this[He];if(this.removeListener("close",ah),this.removeListener("data",qo),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[He]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",eh),t._receiver.on("finish",eh))}function qo(t){this[He]._receiver.write(t)||this.pause()}function ch(){let t=this[He];t._readyState=we.CLOSING,t._receiver.end(),this.end()}function lh(){let t=this[He];this.removeListener("error",lh),this.on("error",nh),t&&(t._readyState=we.CLOSING,this.destroy())}});var hh=ae((TC,xh)=>{"use strict";var AC=jo(),{Duplex:vv}=ue("stream");function uh(t){t.emit("close")}function Sv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function fh(t){this.removeListener("error",fh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Iv(t,e){let r=!0,i=new vv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,l){let u=!l&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(uh,i);return}let l=!1;t.once("error",function(x){l=!0,c(x)}),t.once("close",function(){l||c(o),process.nextTick(uh,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,l)});return}t.send(o,l)},i.on("end",Sv),i.on("error",fh),i}xh.exports=Iv});var Ol=ae((kC,ph)=>{"use strict";var{tokenChars:Av}=Gr();function Tv(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let l=t.charCodeAt(o);if(i===-1&&Av[l]===1)r===-1&&(r=o);else if(o!==0&&(l===32||l===9))i===-1&&r!==-1&&(i=o);else if(l===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}ph.exports={parse:Tv}});var Eh=ae((CC,bh)=>{"use strict";var kv=ue("events"),Wo=ue("http"),{Duplex:RC}=ue("stream"),{createHash:Rv}=ue("crypto"),gh=Uo(),Zn=Ur(),Cv=Ol(),Dv=jo(),{CLOSE_TIMEOUT:Pv,GUID:Lv,kWebSocket:Ov}=Jt(),Nv=/^[+/0-9A-Za-z]{22}==$/,mh=0,wh=1,yh=2,Nl=class extends kv{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:Pv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Dv,...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=Wo.createServer((i,o)=>{let c=Wo.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=Mv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,l)=>{this.handleUpgrade(o,c,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=mh}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(rs,this);return}if(e&&this.once("close",e),this._state!==wh)if(this._state=wh,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(rs,this):process.nextTick(rs,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{rs(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",_h);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Xn(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){Xn(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Nv.test(c)){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){is(r,400);return}let x=e.headers["sec-websocket-protocol"],h=new Set;if(x!==void 0)try{h=Cv.parse(x)}catch{Xn(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 S=new Zn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=gh.parse(m);_[Zn.extensionName]&&(S.accept(_[Zn.extensionName]),w[Zn.extensionName]=S)}catch{Xn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let S={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(S,(_,v,I,T)=>{if(!_)return is(r,v||401,I,T);this.completeUpgrade(w,c,h,e,r,i,o)});return}if(!this.options.verifyClient(S))return is(r,401)}this.completeUpgrade(w,c,h,e,r,i,o)}completeUpgrade(e,r,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[Ov])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>mh)return is(c,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Rv("sha1").update(r+Lv).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[Zn.extensionName]){let w=e[Zn.extensionName].params,S=gh.format({[Zn.extensionName]:[w]});h.push(`Sec-WebSocket-Extensions: ${S}`),m._extensions=e}this.emit("headers",h,o),c.write(h.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",px),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(Xi,this)})),u(m,o)}};mx.exports=Pl;function Nv(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Xi(t){t._state=gx,t.emit("close")}function px(){this.destroy()}function Qi(t,e,r,i){r=r||zo.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} ${zo.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",_h),m.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(rs,this)})),u(m,o)}};bh.exports=Nl;function Mv(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 rs(t){t._state=yh,t.emit("close")}function _h(){this.destroy()}function is(t,e,r,i){r=r||Wo.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} ${Wo.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 Xn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,Xn),t.emit("wsClientError",d,r,e)}else Qi(r,i,o,c)}});var Dx=oe(Re=>{"use strict";var N=U;(function(t,e){let r=U,i=t();for(;;)try{if(parseInt(r(1426))/1*(parseInt(r(1577))/2)+parseInt(r(1642))/3*(-parseInt(r(542))/4)+parseInt(r(842))/5*(-parseInt(r(553))/6)+parseInt(r(827))/7+-parseInt(r(1022))/8*(parseInt(r(799))/9)+parseInt(r(765))/10+parseInt(r(706))/11*(parseInt(r(1062))/12)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Ko,187497);function U(t,e){t=t-229;let r=Ko(),i=r[t];if(U.ALcmvC===void 0){var o=function(h){let p="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",_="";for(let v=0,y,S,I=0;S=h.charAt(I++);~S&&(y=v%4?y*64+S:S,v++%4)?m+=String.fromCharCode(255&y>>(-2*v&6)):0)S=p.indexOf(S);for(let v=0,y=m.length;v<y;v++)_+="%"+("00"+m.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(_)};U.IeDyFx=o,U.xHqULK={},U.ALcmvC=!0}let c=r[0],d=t+c,u=U.xHqULK[d];return u?i=u:(i=U.IeDyFx(i),U.xHqULK[d]=i),i}var qv=Object[N(911)+N(700)],jv=Object["getOwnPr"+N(905)+N(661)],Tx=(t,e)=>function(){return t&&(e=(0,t[{JbaEr:function(c,d){return c(d)}}[N(1540)](jv,t)[0]])(t=0)),e},Wv=(t,e)=>{let r=N,i={slQZo:function(c,d,u,h){return c(d,u,h)}};for(var o in e)i[r(382)](qv,t,o,{get:e[o],enumerable:!0})};function Kv(){return bx||(bx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function $v(){let t=N;return vx||(vx=[IDBCursor[t(1621)+"e"][t(715)],IDBCursor[t(1621)+"e"].continue,IDBCursor[t(1621)+"e"]["continue"+t(285)+"ey"]])}function Vv(t){let e=N,r={FKCSr:function(o){return o()},MgnHP:function(o,c){return o(c)},qvqoa:"success",ereTs:function(o,c){return o instanceof c}},i=new Promise((o,c)=>{let d=U,u={FOZkL:function(_,v){return _(v)},HMjrP:function(_){return r.FKCSr(_)},eSxuZ:function(_,v){return r[U(1117)](_,v)}},h=()=>{let _=U;t[_(637)+_(1414)+_(1643)](_(1456),p),t["removeEv"+_(1414)+"ner"]("error",m)},p=()=>{let _=U;u[_(1765)](o,u[_(1765)](Ft,t[_(351)])),u.HMjrP(h)},m=()=>{let _=U;u.eSxuZ(c,t.error),u[_(1204)](h)};t[d(1634)+"Listener"](r[d(640)],p),t[d(1634)+d(274)](d(385),m)});return i[e(1125)](o=>{let c=e;r[c(1187)](o,IDBCursor)&&Ol[c(693)](o,t)})[e(1741)](()=>{}),jo[e(693)](i,t),i}function Jv(t){let e=N,r={bYBIa:function(o,c,d){return o(c,d)},fBWNV:function(o,c){return o(c)},mnXcr:function(o,c){return o!==c},HakFN:e(1359),biQFt:function(o){return o()},CRgDB:e(242)+e(1271),CdCTh:e(514)+e(1706),VGkKJ:e(777)+e(793),eFhOK:e(332)+"OR",iuWEa:e(1622),CmfbA:e(1421)+"or",iQaxz:function(o){return o()},PHbnN:e(1313),UixQU:e(1420),FgORK:e(950),YQiCV:e(385),qObNy:e(1040)};if(qo[e(1083)](t))return;let i=new Promise((o,c)=>{let d=e,u={SJFeC:r[d(1546)]};if(r.UixQU===r[d(1297)]){let{offset:h}=_0x31cb36(_0x22985a,_0x15700a);_0x239cce=h;let p={cursor_name:"",cursor:0,service:0},{value:m,offset:_}=_0x37bc8b(_0x50b798,_0x940e5e);p[d(461)]=m,_0x103515=_;let{value:v,offset:y}=_0x376844(_0xb9f66d,_0x4e758e);_0x403194=y,p[d(918)+d(392)]=_0x3d6903(_0x4485c3,_0x439493,_0x47375a+v),_0x2c05b2+=v;let{value:S,offset:I}=r[d(753)](_0x20a65e,_0x3dd732,_0x31494a);p[d(1207)]=S[d(1506)](),_0x15af1b=I,_0x1bba30[d(710)](p)}else{let h=()=>{let _=d;t[_(637)+"entListe"+_(1643)](u.SJFeC,p),t["removeEv"+_(1414)+_(1643)](_(385),m),t.removeEventListener(_(1040),m)},p=()=>{let _=d,v={ceQQe:function(y,S){return r[U(1158)](y,S)}};if(r.mnXcr(_(1359),r[_(1403)]))return v[_(393)](_0x18bc4c,_0x1a9941[_(411)](_0x3fd30f(this),_0xd6a227));r[_(1162)](o),h()},m=()=>{let _=d,v={ANAXD:r[_(1413)],glduh:r[_(1135)],RRTBd:_(330)+_(1102)+"R",RrlMI:r[_(1678)],KPPFn:r[_(984)]};if(r[_(1401)]!==r[_(1401)])return _0x3e9279[_0x3db40d["NATIVE_E"+_(1271)]=5001]=v.ANAXD,_0x1a01c1[_0x5c836a[v[_(1115)]]=5002]=v[_(1115)],_0x31d09c[_0x5ed9b6[v[_(1384)]]=5003]=_(330)+"IES_ERROR",_0x38c9b1[_0x38f3d8[v.RrlMI]=5004]=_(777)+_(793),_0xe9ba30[_0x56c1ff[v[_(1151)]]=5005]=v.KPPFn,_0x3ce470;c(t.error||new DOMException(r[_(1059)],r.CmfbA)),r.iQaxz(h)};t[d(1634)+d(274)](d(1313),p),t[d(1634)+"Listener"](r[d(1668)],m),t[d(1634)+"Listener"](r[d(1011)],m)}});qo.set(t,i)}function Zv(t){Wo={jhYXn:function(r,i){return r(i)}}.jhYXn(t,Wo)}function Yv(t){let e=N,r={mOFes:function(i,o){return i(o)},absea:function(i,o){return i(o)},rkyMU:function(i,o){return i(o)},fqFEQ:function(i,o){return i(o)},unDnW:function(i,o){return i===o},ThRAt:e(938)+e(431),CLMZJ:function(i){return i()}};return r[e(1766)](t,IDBDatabase[e(1621)+"e"]["transact"+e(1228)])&&!(r.ThRAt in IDBTransaction[e(1621)+"e"])?function(i,...o){let c=e,d=t[c(1290)](es(this),i,...o);return Dl[c(693)](d,i[c(1378)]?i[c(1378)]():[i]),r.mOFes(Ft,d)}:r.CLMZJ($v)[e(415)](t)?function(...i){let o=e;return t[o(411)](r[o(1163)](es,this),i),Ft(Ol.get(this))}:function(...i){let o=e;return r[o(357)](Ft,t[o(411)](r[o(847)](es,this),i))}}function Xv(t){let e=N,r={LXvhr:function(i,o){return i===o},oikYT:function(i,o){return i(o)},csIjO:function(i,o){return i instanceof o},zhJyS:function(i,o,c){return i(o,c)},kBZbq:function(i){return i()}};return r.LXvhr(typeof t,e(302))?r[e(1132)](Yv,t):(r[e(1769)](t,IDBTransaction)&&r[e(1132)](Jv,t),r.zhJyS(kx,t,r.kBZbq(Kv))?new Proxy(t,Wo):t)}function Ft(t){let e=N,r={wtQIU:function(o,c){return o instanceof c},OafDg:function(o,c){return o(c)},ZQELu:function(o,c){return o!==c}};if(r[e(1408)](t,IDBRequest))return r[e(800)](Vv,t);if(Go[e(1083)](t))return Go[e(502)](t);let i=Xv(t);return r.ZQELu(i,t)&&(Go.set(t,i),jo.set(i,t)),i}var kx,bx,vx,Ol,qo,Dl,Go,jo,Wo,es,Sx=Tx({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={zlaAf:function(r,i){return r>>>i},DnVZj:function(r,i){return r&i},kYaYr:function(r,i){return r&i},FzcCE:function(r,i){return r&i},FIuiP:function(r,i){return r&i},KShzC:function(r,i){return r>>>i},TTEMP:function(r,i){return r!==i},wrpBS:"yILxM",aiVlx:t(1617),DlGOA:function(r,i){return r instanceof i},ZjIwt:"liaVB",QWKRq:t(1227),edDyX:t(938)+"oreNames",uuvqs:function(r,i){return r(i)},ELAIe:function(r,i){return r===i},hnGSx:t(635),oPMID:function(r,i){return r in i}};kx=(r,i)=>i[t(675)](o=>r instanceof o),Ol=new WeakMap,qo=new WeakMap,Dl=new WeakMap,Go=new WeakMap,jo=new WeakMap,Wo={get(r,i,o){let c=t;if(e.TTEMP(e[c(787)],e[c(318)])){if(e.DlGOA(r,IDBTransaction))if(e[c(1325)](e.ZjIwt,e[c(286)]))_0x1a2257[c(1407)+c(261)]="",_0x62a1b4[c(1282)](_0x5e2139);else{if(i===e[c(521)])return qo[c(502)](r);if(i===e[c(557)])return r["objectSt"+c(431)]||Dl[c(502)](r);if(i===c(635))return o[c(938)+c(431)][1]?void 0:o.objectStore(o[c(938)+c(431)][0])}return e[c(1518)](Ft,r[i])}else return _0x1c101f[c(1134)+"Code"](255&this[c(622)],e[c(1728)](this[c(622)],8)&255,e[c(1275)](e[c(1728)](this[c(622)],16),255),this[c(622)]>>>24,e[c(1494)](255,this[c(353)]),e[c(1560)](this[c(353)]>>>8,255),e[c(1224)](e[c(856)](this[c(353)],16),255),e[c(1728)](this[c(353)],24))},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e.DlGOA(r,IDBTransaction)&&(e.ELAIe(i,e[o(521)])||i===e.hnGSx)?!0:e[o(1582)](i,r)}},es=r=>jo[t(502)](r)}}),Cx={};Wv(Cx,{deleteDB:()=>e1,openDB:()=>Qv,unwrap:()=>es,wrap:()=>Ft});function Qv(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=N,u={BrZJU:function(m,_,v,y,S){return m(_,v,y,S)},GOlEp:d(1073),gbHzL:d(1100)+d(1200),Rkmnf:function(m,_){return m(_)},uzBkG:d(1663)+d(1441),YTBPv:d(604)},h=indexedDB[d(439)](t,e),p=u[d(1619)](Ft,h);return i&&h["addEvent"+d(274)](u[d(766)],m=>{let _=d;u.BrZJU(i,Ft(h[_(351)]),m[_(756)+"on"],m[_(1679)+"on"],Ft(h[_(1216)+"ion"]))}),r&&h[d(1634)+d(274)](u.YTBPv,()=>r()),p[d(1125)](m=>{let _=d;c&&m[_(1634)+_(274)](u.GOlEp,()=>c()),o&&m["addEvent"+_(274)](u[_(691)],()=>o())})[d(1741)](()=>{}),p}function e1(t,{blocked:e}={}){let r=N,i={yhxMs:r(604),TFPdW:function(c,d){return c(d)}},o=indexedDB[r(951)+r(1177)](t);return e&&o[r(1634)+r(274)](i[r(650)],()=>e()),i.TFPdW(Ft,o)[r(1125)](()=>{})}function Ix(t,e){let r=N,i={vpimk:r(1362)+"e",eGZln:r(1657),YDHWy:function(h,p){return h instanceof p},cOJCG:function(h,p){return h in p},vTHGf:function(h,p){return h===p},WvkDV:r(323),KhzMK:function(h,p){return h!==p},RiZvx:function(h,p){return h in p}};if(!(i[r(1075)](t,IDBDatabase)&&!i.cOJCG(e,t)&&i[r(1624)](typeof e,i[r(1592)])))return;if(Ho[r(502)](e))return Ho[r(502)](e);let o=e.replace(/FromIndex$/,""),c=i[r(1562)](e,o),d=Px[r(415)](o);if(!i[r(1584)](o,(c?IDBIndex:IDBObjectStore)[r(1621)+"e"])||!(d||Rx.includes(o)))return;let u=async function(h,...p){let m=r,_=this[m(1216)+"ion"](h,d?i.vpimk:i.eGZln),v=_[m(635)];return c&&(v=v.index(p[m(1731)]())),(await Promise[m(1547)]([v[o](...p),d&&_[m(1227)]]))[0]};return Ho[r(693)](e,u),u}var Rx,Px,Ho,t1=Tx({"node_modules/idb/build/index.js"(){let t=N,e={dtmNs:t(408),RzeYr:"getAllKeys",aSExs:t(1353),ekitb:"add",SXYsP:t(813),RrnFY:t(958)};Sx(),Sx(),Rx=[t(502),e[t(615)],t(342),e[t(1036)],t(727)],Px=[e.aSExs,e.ekitb,e[t(1391)],e[t(1682)]],Ho=new Map,Zv(r=>({...r,get:(i,o,c)=>Ix(i,o)||r[t(502)](i,o,c),has:(i,o)=>!!Ix(i,o)||r[t(1083)](i,o)}))}}),n1={idb:function(t){let e=N;t[e(1493)]=Promise[e(1215)]()[e(1125)](()=>(t1(),Cx))[e(1125)](function(r){return r})}},Ax={};function Bt(t){let e=N,r={clOCa:e(666)+"4",JfhhW:function(u,h){return u!==h}},i=r[e(1357)][e(992)]("|"),o=0;for(;;){switch(i[o++]){case"0":var c=Ax[t];continue;case"1":var d=Ax[t]={exports:{}};continue;case"2":if(r[e(1342)](void 0,c))return c.exports;continue;case"3":n1[t](d,d.exports,Bt);continue;case"4":return d[e(1493)]}break}}Bt.d=(t,e)=>{let r=U;for(var i in e)Bt.o(e,i)&&!Bt.o(t,i)&&Object[r(911)+r(700)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Bt.o=(e,r)=>Object[t(1621)+"e"]["hasOwnPr"+t(700)][t(1290)](e,r)})(),(()=>{let t=N,e={EHDYF:function(r,i){return r!=i},gpNJr:t(1013),tFMpk:t(549)+"le"};Bt.r=r=>{let i=t;e[i(1773)](i(844)+"d",typeof Symbol)&&Symbol[i(860)+"Tag"]&&Object.defineProperty(r,Symbol[i(860)+i(1683)],{value:e.gpNJr}),Object[i(911)+i(700)](r,e[i(732)],{value:!0})}})();var Ce={};(()=>{let t=N,e={NqhBE:function(a,n){return a(n)},ILycw:function(a,n){return a+n},gvFFa:function(a,n){return a+n},KsOrl:function(a,n){return a*n},OSxhO:function(a,n){return a+n},ppZHj:function(a,n,s){return a(n,s)},yaKXz:function(a,n,s){return a(n,s)},qZqkg:function(a,n){return a+n},slove:t(1091),WwONY:t(592),gPcqI:function(a,n){return a(n)},iNjUY:"0000000000000000"+t(440)+"00000000",KImXJ:function(a,n){return a instanceof n},bqxdF:t(1269)+t(1424),lWNOE:function(a,n){return a+n},cPJQO:function(a,n){return a&n},ETcXq:function(a,n){return a>>>n},seWur:t(1236),fYsLH:function(a,n){return a>n},OyrZz:function(a,n){return a<n},JHWOm:function(a,n){return a-n},BvwaL:function(a,n){return a!==n},ItXob:function(a,n){return a<n},fPFuq:function(a,n){return a===n},kOvru:function(a,n){return a-n},mfZQK:function(a,n){return a(n)},XZpdA:function(a,n){return a===n},VsEuC:t(1514),enJBf:function(a,n,s){return a(n,s)},hXiII:function(a,n){return a!==n},SQqpo:"NimdU",WGgQi:function(a,n,s){return a(n,s)},Muihc:function(a,n){return a<<n},bbmzZ:function(a,n){return a>>>n},mxBDm:t(1363),QqlSF:function(a,n){return a(n)},zEJLI:function(a,n){return a>>>n},FSeor:function(a,n){return a(n)},kHNrx:"Missing "+t(1124)+t(1370)+t(775),gByfc:t(708)+t(1124)+" field: "+t(1254),RnUjK:function(a){return a()},eXuWP:function(a,n){return a(n)},HIeEw:function(a,n){return a>n},icVqJ:t(786)+"too large",vIUDW:function(a,n){return a>=n},srmrF:function(a,n){return a&n},OOCoq:function(a,n,s,l){return a(n,s,l)},tLRDl:function(a,n){return a+n},TuOJU:function(a,n){return a!==n},NveQk:"YCtky",EerRJ:function(a,n,s){return a(n,s)},CYUkK:function(a,n,s){return a(n,s)},HZqgV:function(a,n,s){return a(n,s)},DewEN:t(1708),oLSTe:function(a,n,s){return a(n,s)},rqAsg:"YbYSo",QlkPM:function(a,n){return a(n)},fgWiX:function(a,n,s){return a(n,s)},apYQO:function(a,n,s){return a(n,s)},riAHM:function(a,n){return a!==n},qbcqF:function(a,n,s){return a(n,s)},QSHaf:function(a,n,s){return a(n,s)},kvBSQ:function(a,n,s){return a(n,s)},VSvTh:function(a,n){return a!==n},rZfKJ:function(a,n,s){return a(n,s)},wFDXC:function(a,n,s){return a(n,s)},JlCzV:function(a,n,s){return a(n,s)},rtIsH:function(a,n){return a(n)},aVYrF:"10|0|5|9"+t(1272)+t(231),feUZX:t(461),XpYhX:"header",FETUV:t(571)+"name",KWLtu:t(1569),IZdkB:t(1333)+t(1749),xnaBc:t(671),IlMgY:t(1368),PpzWD:function(a,n){return a>>>n},GTylg:function(a,n){return a(n)},czqTu:function(a,n,s){return a(n,s)},VWDbo:function(a,n){return a(n)},GnoFl:function(a,n){return a(n)},YSQbW:function(a,n){return a===n},GZeip:t(708)+t(1124)+t(1370)+t(1613),dvknS:t(708)+t(1124)+t(1370)+"LogID",ZZvvH:"Missing "+t(1124)+t(1370)+t(461),SBLmb:t(708)+"required"+t(1370)+t(1568),lzTyK:function(a,n){return a(n)},SXOpv:function(a,n){return a+n},PqdBl:function(a,n){return a(n)},rBGak:function(a,n){return a+n},faTXc:function(a,n){return a!==n},jqxyL:t(441),ugRnC:function(a,n){return a===n},rnFKF:function(a,n){return a>=n},uYKlJ:function(a,n){return a!==n},braEJ:t(1772),gegeO:function(a,n){return a>n},Rsnur:"Read pas"+t(1462),HQNmS:function(a,n,s){return a(n,s)},lQmcI:function(a,n){return a(n)},fBZzF:function(a,n){return a===n},iTMJh:t(315),IdeEf:function(a,n,s){return a(n,s)},aunSu:t(385),OlTCc:function(a,n){return a===n},WGkSf:function(a,n){return a&n},whkhU:function(a,n){return a===n},FPOdV:function(a,n){return a&n},gcswZ:function(a,n){return a+n},YJSIT:function(a,n){return a!==n},ExOGt:function(a,n){return a&n},TGqZE:function(a,n){return a|n},MMuwF:function(a,n){return a&n},HIZrw:function(a,n){return a==n},qieyL:function(a,n){return a+n},TErYF:function(a,n){return a+n},yVuUE:function(a,n){return a&n},gJhJV:function(a,n){return a|n},pBNPv:t(664),zbWep:function(a,n){return a<<n},WtbSm:function(a,n){return a&n},rUNkp:function(a,n){return a<n},iWwij:function(a,n){return a<=n},XzaoY:function(a,n){return a==n},IfIso:function(a,n){return a+n},MRMAj:function(a,n){return a+n},SfbOG:function(a,n){return a+n},QsjsB:function(a,n){return a+n},Ukqil:function(a,n){return a&n},LfIKo:function(a,n){return a|n},sUbGa:function(a,n){return a<<n},SrquF:function(a,n){return a|n},NgWyo:function(a,n){return a|n},BnzVt:function(a,n){return a<<n},QmMtX:function(a,n){return a&n},UsVtX:function(a,n){return a>n},utWFh:function(a,n){return a+n},UfmPz:function(a,n){return a<n},FEDHn:function(a,n){return a>=n},HNvMu:function(a,n){return a<=n},SieUT:function(a,n){return a<n},AeARH:function(a,n){return a+n},awboE:function(a,n){return a<n},XTQEf:function(a,n,s){return a(n,s)},PSqOp:function(a,n){return a<n},cpXlm:function(a,n){return a>=n},kYuCE:function(a,n){return a<n},DAViY:function(a,n){return a+n},sGOnc:function(a,n){return a<n},yEwtc:function(a,n){return a|n},OpEni:function(a,n){return a>>n},MlTOZ:function(a,n){return a|n},cjevw:function(a,n){return a>>n},HiEDt:function(a,n){return a|n},mKEAj:function(a,n){return a&n},ZBANW:function(a,n){return a+n},VpCHV:function(a,n,s){return a(n,s)},dAENu:function(a,n){return a===n},MSjVh:"QvMIN",mRYTs:function(a,n){return a<n},yaHFC:function(a,n){return a&n},rueSu:function(a,n){return a|n},QVFhm:function(a,n){return a&n},mFvWK:function(a,n){return a(n)},fpGxh:function(a,n){return a&n},lXQnl:function(a,n){return a&n},TAzvD:function(a,n){return a<<n},FKhxz:function(a,n){return a&n},WYKgn:function(a,n){return a&n},wFLMJ:function(a,n){return a&n},bYBQD:function(a,n){return a(n)},pVsRo:function(a,n){return a&n},txyyC:function(a,n){return a&n},tNLVt:function(a,n){return a!==n},PACYu:t(358),rXcMW:t(726),PriEY:function(a,n){return a(n)},LYbVB:function(a,n){return a<<n},lNgVB:t(1006),ElXJM:function(a,n){return a!==n},jjAfR:t(1521),mhJSM:function(a,n){return a|n},iVdii:function(a,n){return a|n},wcwSp:function(a,n){return a<<n},qaEbI:function(a,n){return a===n},xmmhm:function(a,n){return a!==n},ewieg:t(406),uHVgA:function(a,n){return a>>>n},wzsRo:function(a,n){return a>>>n},Llurg:function(a,n){return a>>>n},FJjyd:function(a,n){return a===n},JTCnq:function(a,n){return a<n},tEHIN:function(a,n){return a<n},nFkLG:function(a,n){return a<n},wXLex:function(a,n){return a&n},HNeWn:function(a,n){return a&n},zJXpj:function(a,n){return a!==n},qUqmE:function(a,n){return a|n},LTiOD:function(a,n){return a>>>n},upYSO:function(a,n){return a!==n},bQfnE:function(a,n){return a>>>n},xPGlN:function(a,n){return a|n},aUSjI:function(a,n){return a>>>n},teCVK:function(a,n){return a|n},udpaJ:function(a,n){return a!==n},KTYDn:function(a,n){return a>>>n},oHkCI:function(a,n){return a&n},RigNU:function(a,n){return a!==n},tNlOj:function(a,n){return a+n},VAzdA:function(a,n){return a>>>n},hMTJp:function(a,n){return a&n},uOvji:function(a,n){return a>n},vnzBU:function(a,n){return a(n)},bVKAB:function(a,n){return a===n},DMIkW:t(1340),tZDtj:t(564),BIfDw:function(a,n){return a+n},PBjDY:function(a,n){return a|n},TOuTk:function(a,n){return a|n},SogGn:function(a,n){return a<<n},nhBHH:function(a,n){return a<<n},cbcTd:function(a,n){return a|n},aVzjK:function(a,n){return a<<n},wFeSQ:function(a,n){return a<<n},FXOZi:function(a,n){return a|n},SLUTJ:function(a,n){return a<<n},MlyNU:function(a,n){return a>>>n},jIkMH:function(a,n){return a|n},AQxfd:function(a,n){return a<<n},DEECQ:function(a,n){return a<<n},daowh:function(a,n){return a<<n},Mrcgw:function(a,n){return a>>>n},RbOuh:function(a,n){return a|n},DQxva:function(a,n){return a<<n},wNWtb:function(a,n){return a&n},EmAjp:function(a,n){return a+n},ADODX:function(a,n){return a+n},ZuXXi:function(a,n){return a(n)},bkLER:"JBUWl",UeYsi:"oZcpq",bPWDl:function(a,n){return a>=n},iiydU:function(a,n){return a%n},cfbMc:function(a,n){return a|n},eyHTc:function(a,n){return a/n},MxmQQ:function(a,n){return a!==n},fUvDV:t(1220),ZNjKH:function(a,n){return a>>>n},SSJaf:function(a,n){return a*n},ZTbqb:function(a,n){return a>>>n},WcxUX:"VRQUS",ZQjTN:function(a,n){return a>>>n},rrwJI:function(a,n){return a&n},SzgWY:function(a,n){return a&n},PpAHc:function(a,n){return a+n},yOLnC:function(a,n){return a>>>n},eIKZp:function(a,n){return a+n},TIoEI:function(a,n){return a>>>n},pmCNE:function(a,n){return a<<n},aZedo:function(a,n){return a<<n},ohYRY:function(a,n){return a!==n},IWFwY:function(a,n){return a===n},ALszQ:function(a,n){return a===n},VWpTo:function(a,n){return a(n)},Ukbmk:function(a,n){return a<<n},iRbxc:function(a,n){return a&n},MRECK:t(1094),Dkqym:function(a,n){return a===n},xUTdi:function(a,n){return a===n},pFxaT:function(a,n){return a+n},xTdwe:function(a,n){return a>>>n},NiXCA:function(a,n){return a&n},MmveK:function(a,n){return a>>>n},pbigq:function(a,n){return a>>>n},CAsQf:function(a,n){return a>>>n},LyGjp:function(a,n){return a&n},dfnOX:function(a,n){return a>>>n},aTYJC:function(a,n){return a&n},OPIpP:function(a,n){return a&n},OlWwY:"NATIVE_E"+t(1271),vMmVh:t(514)+"NG_ERROR",zCyKq:"MAX_RETRIES_ERROR",DKBFm:"MESSAGE_"+t(793),PnbLb:t(332)+"OR",gHVxz:t(1106),FEhdW:function(a,n,s){return a(n,s)},uTSPV:t(1073),pEJQH:t(719),FmDVu:t(1323),EPKpp:function(a,n){return a!==n},AzmiZ:"JwrCJ",kfgZt:t(1008),MfoOQ:t(1264),OAxbc:"KYPpt",Hedws:function(a,n){return a!==n},wksNs:function(a,n){return a>=n},gAtCr:function(a,n,s){return a(n,s)},pmxkG:function(a,n){return a!==n},imMbk:"KmGpG",moDiO:t(413),NdZoY:function(a,n){return a==n},QYIHe:t(275),tYZkL:function(a,n){return a instanceof n},KOCGw:function(a,n){return a===n},nZtTB:function(a,n){return a===n},lilMJ:t(439),bjKRS:function(a,n,s){return a(n,s)},zBDEA:"SlshN",FUceT:function(a,n,s){return a(n,s)},lywIh:t(1528),sOZWW:"mykSQ",Ezccu:t(1507),mYRCt:function(a,n){return a(n)},YiLng:function(a,n){return a<<n},Eqlps:function(a,n){return a(n)},UTbjN:function(a,n){return a||n},iTOqX:t(998),DNKGr:t(630),WgfUj:function(a,n){return a+n},lTuqU:function(a,n){return a!==n},FBjHt:t(237),oxMiv:function(a,n){return a===n},PvNsA:"ZEoPC",weCXC:t(1672),FqEHf:"PWkoa",lngJT:t(826),zZRnV:t(568),WjMMS:t(703),lieKB:"XFEgu",BqyRz:t(1009),PhVod:function(a,n){return a||n},cBErU:function(a,n){return a||n},YfWTx:function(a,n){return a!=n},OWdXH:t(844)+"d",MZzaV:t(550)+"3",ZOHaH:function(a,n){return a||n},Umtfp:function(a,n){return a!=n},syPbD:function(a,n){return a(n)},sgOUl:function(a,n){return a(n)},faDIU:t(959)+t(1113),byGFi:"1|7|0|9|"+t(1545)+"|4|5|2",shAAV:"curvalue",vtBCb:function(a,n,s,l){return a(n,s,l)},kIhix:t(387),yDEcz:function(a,n){return a<n},ubXlZ:function(a,n){return a===n},NlTlR:function(a,n){return a&n},ndBbv:function(a,n){return a===n},oGyLN:function(a,n){return a<n},NLrxv:function(a,n){return a<=n},MyAgw:function(a,n){return a<n},Poypg:function(a,n){return a<n},QZavt:function(a,n){return a&n},aUBGj:function(a,n){return a&n},NbRER:function(a,n){return a&n},pgDUL:function(a,n){return a|n},sKDzW:function(a,n){return a&n},TjouD:function(a,n){return a<<n},QgBca:function(a,n){return a&n},gnXbx:function(a,n){return a+n},GfdSe:function(a,n){return a>>n},AaXJo:function(a,n){return a+n},eZOpV:function(a,n){return a<n},oPrSF:function(a,n){return a<n},rZOXU:function(a,n){return a|n},Oqdew:function(a,n){return a>>n},cQzQI:function(a,n){return a|n},kAehm:function(a,n){return a&n},LjrtU:function(a,n){return a===n},nvsep:function(a,n){return a+n},OoFXj:t(249)+t(698),rpmkU:function(a,n){return a&n},AESfA:function(a,n){return a&n},dmmrn:function(a,n){return a>>n},aWhpp:function(a,n){return a+n},uLkhg:function(a,n){return a<<n},KFLqJ:function(a,n){return a|n},RlWwt:function(a,n){return a>>n},ADhPR:function(a,n){return a||n},kBaPw:"VbLRl",xSlQW:function(a,n){return a==n},nTXxR:t(323),CSagP:function(a,n,s,l){return a(n,s,l)},xQHlP:function(a,n){return a!=n},UQrNl:function(a,n){return a instanceof n},Yabhg:function(a,n){return a!=n},cutPe:t(1316)+t(489),NCmuc:t(1759)+"in;chars"+t(987),LnrxY:t(1054),dkVsh:t(1719),cwJNP:"boe",PGqAI:t(981),WkQDr:"&jscallb"+t(1567)+"tierJSONP",CYheN:t(755),MagEL:t(424),muvry:t(1620),RvABz:function(a,n,s){return a(n,s)},ojphQ:t(1232),qWxky:t(877),jAksn:function(a,n){return a===n},nweIQ:t(1665),upyWX:function(a,n){return a<n},Bctuq:function(a,n){return a!==n},cpjMA:function(a,n){return a-n},gsNqd:"srJTN",aSiOr:"qedgK",gXhDN:"mzxOo",SfPrk:t(458),UrnSM:function(a,n){return a instanceof n},PaBYi:t(1227),nvLuQ:t(938)+"oreNames",pjVmd:function(a,n){return a(n)},zFFxk:"GUqJz",XQOVJ:"cdiVx",QsTYa:function(a,n){return a||n},liJzG:function(a,n){return a||n},vBjVB:function(a,n,s,l){return a(n,s,l)},GxrmK:function(a,n){return a!==n},ZiFdx:t(1398),ywzCo:function(a,n){return a||n},LtzEu:function(a,n){return a(n)},JHtCX:t(1388)+"reason",EqzSo:function(a,n){return a!==n},bYQKi:t(1383),DTLdy:"lZyVH",QZtFt:function(a,n){return a||n},SrjET:t(1574)+t(398)+"s",Umvwo:t(1456),wYand:function(a,n,s){return a(n,s)},utOpY:t(1193),DRORV:function(a,n){return a||n},BAewC:function(a,n){return a||n},FEsTM:function(a,n){return a!=n},yTsgl:function(a,n){return a!=n},FNNex:t(714)+t(915)+"d",khLSI:function(a){return a()},vOoWg:t(1422),rMCZj:function(a,n){return a!==n},qjthJ:t(1581),GKRiA:"BrGyd",GbKwI:function(a,n){return a(n)},QJxol:function(a,n,s,l){return a(n,s,l)},tfzuN:t(1168)+t(1717)+"ck",bRYBV:t(1168)+t(862)+t(1573),hVLVt:t(988),qAMoo:function(a,n){return a&&n},Gyioe:t(311),FOCpX:"ack_code",BWost:t(589),viTJw:function(a,n){return a(n)},kHyFF:function(a,n){return a instanceof n},QgIDr:"applicat"+t(489)+t(1334)+"=utf-8",qmnhL:"online",mvwGB:t(1374),VRNyF:t(886),WiNRQ:t(1123),QqQXw:t(617),hJvBl:function(a,n){return a>n},zCbYK:function(a,n){return a|n},nHprh:function(a,n){return a||n},skdmk:t(1712),wilGX:function(a,n){return a+n},mTQuz:function(a,n){return a+n},aBYQD:" + ",iXWFD:" > ",JeVTL:function(a,n){return a&n},fptcF:function(a,n){return a===n},rhziU:"omwLr",VKZdG:"IDWgI",WGwfL:function(a,n){return a<n},jAsfz:function(a,n,s){return a(n,s)},jTDEx:function(a,n){return a>>>n},VfCvQ:function(a,n){return a+n},KSHAk:function(a,n,s,l){return a(n,s,l)},twiTh:function(a,n){return a+n},wccxf:function(a,n){return a+n},DDugZ:function(a,n,s,l){return a(n,s,l)},TSDem:function(a,n){return a|n},xEkTH:function(a,n){return a|n},RXZha:function(a,n){return a+n},EVXMA:function(a,n){return a<<n},uFMlO:function(a,n){return a+n},EWVlD:function(a,n){return a<<n},bGNud:function(a,n){return a+n},ekbfc:function(a,n){return a+n},lrCmw:function(a,n){return a>>>n},KKCJY:function(a,n){return a&n},UtlbU:function(a,n){return a+n},KxxpD:function(a,n){return a+n},gljOP:function(a,n){return a&n},zNKpP:function(a,n){return a+n},KYhkD:function(a,n){return a+n},UfEez:function(a,n){return a&n},MTrfB:function(a,n){return a+n},QojKs:function(a,n){return a+n},EqLRZ:function(a,n){return a>>n},khoeo:function(a,n){return a|n},PuDwe:function(a,n){return a&n},uSMTR:t(1724),vcohX:t(1002),yzYzR:function(a,n){return a<n},UwBUs:function(a,n){return a|n},ECvtJ:function(a,n){return a&n},yWAsv:function(a,n){return a+n},rGmyz:t(1676)+t(1302)+t(625),xonLt:function(a,n,s){return a(n,s)},tPNjz:function(a,n){return a+n},eMkhR:"FILE_NOT"+t(1718),qiyhM:function(a,n){return a===n},YPZGI:t(597),MoDWN:t(298)+t(1727),hYClH:t(449),wIikh:"INSTANT",DFWpN:function(a,n){return a(n)},vcvjt:t(1606)+t(233),vBwqq:function(a,n){return a+n},NOQZj:t(1566),qTwEu:t(825),irAiz:function(a,n){return a||n},nrjba:function(a,n,s){return a(n,s)},sLmnq:t(1168)+t(230),yFgKl:function(a,n,s){return a(n,s)},ERFPS:"x_fronti"+t(977),HVjbO:t(1287)+"s",giekG:"x-msg-cu"+t(643)+"e",kjFuM:function(a,n){return a(n)},PNpWQ:function(a,n){return a>n},SXytW:t(304),EpmBG:function(a,n){return a===n},RzYUl:t(1735),zQIOi:function(a){return a()},SyQdg:function(a){return a()},FnoVr:function(a){return a()},wUGJs:function(a){return a()},mfwga:function(a,n){return a===n},KdbjT:t(295),Waezj:t(356),rFFmy:function(a,n){return a&&n},VQcAR:function(a,n,s){return a(n,s)},OqOef:function(a){return a()},vuhHw:function(a){return a()},Stcnw:function(a,n){return a!==n},EGBdz:function(a,n){return a!==n},bGzHp:t(260),vhMdv:t(327),TQuSx:function(a,n,s){return a(n,s)},XIvkd:function(a,n,s){return a(n,s)},rNWWD:function(a,n){return a==n},YKtnS:function(a,n,s,l){return a(n,s,l)},CRkif:function(a,n,s){return a(n,s)},CINqc:t(743),LWhMm:function(a,n){return a!==n},JHAJo:t(820),XTnML:t(948)+"fer",cpBMM:t(1487),WtyFa:function(a,n){return a==n},GMfyq:"please p"+t(790)+"alid url",Yoeti:t(839)+t(1218)+t(945)+"ct",PWFuw:t(368),DSIzA:t(1361),qtrUT:t(728),gBPxF:function(a,n){return a&n},qTwAG:function(a,n){return a(n)},TJMgB:function(a,n){return a===n},HRfvm:t(1139),bwmeD:t(1251),kjXga:t(310),YMTGb:t(309),XIWgZ:t(1112),QAoVV:t(1757),PikpF:"device_id",AsrDf:function(a,n){return a||n},ZfRHQ:t(865)+"rovide b"+t(1131)+"viceID or ttwID",PcRCU:"function",RErnb:t(697),ElFcV:t(990),svAOH:"rhGDF",NYzIn:function(a,n,s){return a(n,s)},YRyZR:t(863),hlviM:function(a,n,s){return a(n,s)},kDZGi:function(a,n,s){return a(n,s)},UasDZ:function(a,n){return a(n)},HdrJW:function(a,n){return a(n)},AVTQe:t(1332)+">",xalbm:"RGvOt",WKWmt:function(a,n){return a-n},WyWan:function(a,n){return a!==n},ncFlH:function(a,n,s){return a(n,s)},UIMuu:"ping_onc"+t(1222)+"t",xgQPE:function(a,n){return a(n)},lnmSe:"kKfhp",Xghia:function(a,n,s){return a(n,s)},ATjxz:t(258),wcxUc:function(a,n,s){return a(n,s)},VyhOk:function(a,n){return a!==n},GLsJM:t(246),QcWld:function(a,n,s){return a(n,s)},xuaTR:t(835),TgUFP:function(a,n){return a===n},gEVOv:t(1194),broKo:t(390),ZlLWP:t(1013),FyWWR:t(549)+"le",MDljm:t(627),iMvTR:t(1557),HeyLq:"0|2|5|4|"+t(1270),yZBYO:function(a,n){return a===n},cLOyQ:function(a,n){return a===n},vGgtd:t(579)+"s alread"+t(548),GmqJO:"close, w"+t(1314)+t(932)+"nitialized",fVaHz:t(354),UCTUo:t(865)+t(740)+t(574)+t(1450)+"a must b"+t(754)+t(603)+t(642)+t(554),rvdDs:t(1045),PRkzV:function(a,n){return a instanceof n},LdNbF:function(a,n){return a instanceof n},mAWGH:function(a,n){return a(n)},wjhwR:function(a,n){return a(n)},bYOQd:t(865)+"rovide a"+t(979)+"ervice",wVZAF:function(a,n){return a instanceof n},RLrgO:t(238),QqTwg:"VFfBS",DBivt:function(a,n){return a||n},ECFNa:t(1468)+t(1310)+t(586),EXtzg:function(a,n){return a(n)},WTqxT:t(897),jpGJT:t(733),zLblk:function(a,n){return a*n},KCQCr:function(a,n){return a!=n},Uontu:t(859),SpkVm:function(a,n){return a!=n},GWmKE:function(a,n){return a===n},qJwbh:t(477),VuGFa:function(a,n){return a===n},Irsth:function(a,n){return a!=n},yTALY:function(a,n){return a!=n},ifyfG:function(a,n){return a!=n},NFEgY:function(a,n){return a!=n},DyfWs:"Dedicate"+t(1565)+t(373)+"pe",GdWps:function(a,n){return a!=n},qLEdo:function(a,n){return a!=n},Bvarc:function(a,n){return a!=n},IQZLf:function(a,n){return a!=n},NUwAI:function(a,n,s){return a(n,s)},YeimM:t(1005)+t(1554)};Bt.r(Ce),Bt.d(Ce,{FWS:()=>hg,CustomErrorEvent:()=>Ql,createCloseEvent:()=>pt,ReconnectEvent:()=>Xl,createErrorEvent:()=>ct,decodedFrame:()=>en,createOpenEvent:()=>sd,CustomCloseEvent:()=>ed,createReconnectEvent:()=>da,FrontierMessageEvent:()=>nd,encodeFrame:()=>zt,createMessageEvent:()=>id,OpenEvent:()=>rd,ErrorCode:()=>nn,Event:()=>tr,MessageEvent:()=>td});let r="";function i(a=""){let n=t,s="02",l=""+Date[n(516)](),f=r||(r=e.NqhBE(h,a)),x=Math[n(405)]().toString(16)[n(1445)](-6);return e[n(331)](e[n(331)](s,l),f)+x}function o(){let a=t;return e[a(1659)](e.KsOrl(1e4,Date.now()),Math.floor(1e4*Math[a(405)]()))}function c(a){let n=t;return e[n(1086)](e.NqhBE(Array,8).join("0"),e[n(1324)](parseInt,a,10)[n(860)](2))[n(1445)](-8)}function d(a){let n=t;return(e[n(1052)](Array,4)[n(369)]("0")+e[n(683)](parseInt,a,2).toString(16))[n(1445)](-4)}function u(a){let n=t,s=a[n(992)](/\./).map(x=>c(x)),l=[];return l[0]=e[n(1052)](d,e[n(1549)](s[0],s[1])),l[1]=d(s[2]+s[3]),["0000",e[n(797)],e[n(797)],e[n(797)],e[n(797)],e[n(262)],l[0],l[1]][n(369)]("")}function h(a){let n=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[n(1778)](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(1778)](a);return s?e[n(1571)](u,a):l?e.NqhBE(p,a):e[n(744)]}function p(a){let n=t,s={okWLk:function(C,O){return e[U(985)](C,O)},PAbtM:function(C,O){return C>>>O},pttVR:function(C,O){return C>>>O},Tqojh:function(C,O){return e[U(301)](C,O)},DBBlz:function(C,O){return e[U(985)](C,O)}},l="",f=[],x=0,w=0,b=!0,g=e[n(797)];if(a[n(845)]("::")>-1){let C=a[n(992)]("::");for(let F=0;F<C.length;F++)if(n(361)!==e.seWur){let j=C[F];if(e[n(902)](j[n(845)](":"),0)){let W=j.split(":");b&&(x=W.length),w+=W[n(421)];for(let le=0;e[n(896)](le,W[n(421)]);le++)if(W[le][n(421)]!==4){let Ke=g[n(738)+"g"](0,e[n(1461)](4,W[le][n(421)])),rt=Ke[n(1480)](W[le]);f[n(710)](rt)}else f.push(W[le]);b=!1}else{if(e[n(1042)](4,j[n(421)])){let W=g[n(738)+"g"](0,4-j[n(421)]),le=W[n(1480)](j);f[n(710)](le)}else f[n(710)](j);b&&(x+=1),w+=1,b=!1}}else{let j=this[n(353)],W=this[n(622)];return[j>>>24,s[n(1393)](s[n(1513)](j,16),255),s[n(1744)](j,8)&255,s[n(1393)](255,j),s[n(1691)](W,24),s[n(1393)](W>>>16,255),s[n(628)](s.pttVR(W,8),255),s[n(628)](255,W)]}let O="";for(let F=0;F<8-w;F++)O=O[n(1480)](g);for(let F=0;e.ItXob(F,f[n(421)]);F++)e[n(1118)](F,x)&&(l=l.concat(O)),l=l[n(1480)](f[F]);return l}if(n(908)==="fKXJJ"){let C=_0x1d7a0a.length&&_0x4a7854[0];if(e[n(632)](C,_0x5cfa69))throw C;let O=new _0x484b87(e[n(695)]+(C?e[n(541)](" (",C.message)+")":""));throw O[n(920)]=C,C}else{let C=a[n(992)](":");for(let O=0;O<C[n(421)];O++){let F=C[O];if(C[O][n(421)]!==4){let j=g[n(738)+"g"](0,e[n(416)](4,C[O].length)),W=j[n(1480)](F);l=l[n(1480)](W)}else l=l[n(1480)](F)}return l}}function m(a,n){let s=t,l={KnlIT:function(f,x){return e.mfZQK(f,x)},CLahh:function(f){return f()},goWFJ:function(f,x){return e[U(688)](f,x)},KYdBD:function(f,x){return e[U(688)](f,x)},cKhHP:function(f,x){return e[U(1549)](f,x)}};if(e[s(1118)](e[s(1502)],s(1436)))HWvKzi[s(677)](_0x58c90f,_0x5d788b[s(385)]),HWvKzi.CLahh(_0x537ef3);else{let f=a[s(775)];e[s(1042)](void 0,f)&&(e[s(1324)](pe,n,10),e.enJBf(G,n,f));let x=a[s(1254)];if(x!==void 0){if(e[s(624)](e[s(836)],e[s(836)]))return l[s(1446)](-1,this[s(622)])&&l[s(1532)](-1,this[s(353)])?_0x3e1331[s(1409)](0,0,this[s(1018)]):l[s(1532)](-1,this.low)?_0x3a021e.fromBits(0,this[s(353)]+1,this.unsigned):_0x23fd9b[s(1409)](l[s(889)](this.low,1),this[s(353)],this[s(1018)]);e.WGgQi(pe,n,18),e[s(1267)](G,n,x)}}}function _(a){let n=t,s={GLvLB:function(l,f){return e.ETcXq(l,f)},fMCXJ:function(l,f){return e.Muihc(l,f)},bAvfC:function(l,f){return l&f},PVgMn:function(l,f){return l<f},hitkm:function(l,f){return l|f},xZqJH:function(l,f){return e[U(1707)](l,f)},xsGHu:function(l,f){return e[U(301)](l,f)},pSwrl:function(l,f){return l|f}};if(e[n(688)](n(894),e[n(858)])){let l={LewZC:function(x,w){return s.GLvLB(x,w)},lqzbO:function(x,w){return s[n(1762)](x,w)},Xyvyo:function(x,w){return s[n(446)](x,w)},umFUX:function(x,w){return x&w},AtOhS:function(x,w){return s[n(1230)](x,w)},QNRBS:function(x,w){return s[n(1615)](x,w)},AOzch:function(x,w){return s.PVgMn(x,w)},svezr:function(x,w){return s.xZqJH(x,w)},CYNyR:function(x,w){return x<<w},BXFof:function(x,w){return s.hitkm(x,w)},eQriP:function(x,w){return x<w},BHNdG:function(x,w){return s.hitkm(x,w)},NzLiR:function(x,w){return s[n(748)](x,w)},WdEOC:function(x,w){return s[n(917)](x,w)},mnAVH:function(x,w){return x<<w},lUmNM:function(x,w){return s.pSwrl(x,w)}},f=4294967295;return function(x,w,b=!0){let g=n,C=(g(1341)+g(467)+g(381)+"6")[g(992)]("|"),O=0;for(;;){switch(C[O++]){case"0":f=l[g(1182)](f|l.lqzbO(l[g(1014)](15,x[w]),28),0);continue;case"1":f=l[g(1182)](l[g(1754)](127,x[w]),0);continue;case"2":if(l.AtOhS(x[w++],128))return{value:b?f:l[g(1460)](0,f),offset:w};continue;case"3":if(l[g(600)](x[w++],128))return{value:b?f:0|f,offset:w};continue;case"4":f=l.svezr(l[g(1460)](f,l[g(1320)](l[g(1754)](127,x[w]),14)),0);continue;case"5":if((w+=5)>x[g(421)])throw w=x[g(421)],_0x1e2f84(w,10,x.length);continue;case"6":return{value:b?f:l[g(1739)](0,f),offset:w};case"7":if(x[w++]<128)return{value:b?f:0|f,offset:w};continue;case"8":if(l.AtOhS(x[w++],128))return{value:b?f:l[g(1460)](0,f),offset:w};continue;case"9":if(l[g(1012)](x[w++],128))return{value:b?f:l.BHNdG(0,f),offset:w};continue;case"10":f=l.NzLiR(l.WdEOC(f,l[g(861)](127&x[w],21)),0);continue;case"11":f=l[g(654)](f,l[g(1276)](127&x[w],7))>>>0;continue}break}}}else{let l={};e:for(;!e[n(1571)](V,a);){let f=e[n(731)](xe,a);switch(e[n(1690)](f,3)){case 0:break e;case 1:l[n(775)]=P(a,e.FSeor(xe,a));break;case 2:l[n(1254)]=e[n(683)](P,a,e[n(731)](xe,a));break;default:e[n(1324)](k,a,e.cPJQO(7,f))}}if(e[n(1118)](void 0,l[n(775)]))throw new Error(e[n(1095)]);if(e[n(688)](void 0,l[n(1254)]))throw new Error(e.gByfc);return l}}function v(a){let n=t,s=e[n(1247)](R);return e[n(683)](y,a,s),e.eXuWP(M,s)}function y(a,n){let s=t,l={yyIir:function(f,x){return e[U(1086)](f,x)},ppXLQ:function(f,x){return e[U(947)](f,x)},rNodL:function(f,x){return e.ETcXq(f,x)},GDalz:function(f,x){return e[U(1659)](f,x)},trgkp:function(f,x){return e[U(947)](f,x)}};if(e[s(1428)](s(1782),e.NveQk)){let f=a[s(1613)];f!==void 0&&(pe(n,8),e[s(288)](xt,n,f));let x=a.LogID;x!==void 0&&(e[s(325)](pe,n,16),e[s(806)](xt,n,x));let w=a[s(461)];if(e[s(624)](void 0,w))if(e[s(1042)](s(1708),e[s(922)])){if(e.HIeEw(_0x17afd5,_0x5186e7))throw new _0x18aa36(e[s(375)]);let rt=3;for(;e[s(613)](rt,0);){let gt=e[s(933)](255,_0x213f53);e.OOCoq(_0xff6d10,gt,_0x1b1b06,e[s(1296)](_0x3da9b7,rt)),_0x925a6d>>>=8,rt--}return e[s(1296)](_0x520895,4)}else e[s(531)](pe,n,24),e[s(325)](xt,n,e[s(690)](D,w));let b=a.method;b!==void 0&&(e.enJBf(pe,n,32),xt(n,D(b)));let g=a.headers;if(e[s(1042)](void 0,g))for(let rt of g){if(e[s(624)](e[s(1689)],e[s(1689)]))return this[s(1018)]?l[s(1262)](l[s(926)](l[s(1202)](this[s(353)],0),_0x1069a4),this.low>>>0):l[s(762)](l[s(1327)](this[s(353)],_0x199bd3),l[s(1202)](this[s(622)],0));{pe(n,42);let gt=R();m(rt,gt),pe(n,gt.limit),e[s(806)](K,n,gt),e[s(1652)](L,gt)}}let C=a[s(389)+"ncoding"];e[s(1042)](void 0,C)&&(e[s(1578)](pe,n,50),e[s(943)](G,n,C));let O=a[s(1169)+s(445)];e.riAHM(void 0,O)&&(e.qbcqF(pe,n,58),e[s(1267)](G,n,O));let F=a.payload;F!==void 0&&(e[s(434)](pe,n,66),e.kvBSQ(pe,n,F[s(421)]),e[s(1470)](se,n,F));let j=a[s(983)];e.VSvTh(void 0,j)&&(e[s(470)](pe,n,74),e[s(957)](G,n,j));let W=a["serverTi"+s(1027)];e[s(1428)](void 0,W)&&(e.apYQO(pe,n,82),e[s(634)](G,n,W));let le=a[s(1103)];e[s(578)](void 0,le)&&(e[s(259)](pe,n,90),e[s(531)](G,n,le));let Ke=a[s(1317)+"e"];Ke!==void 0&&(pe(n,96),e.EerRJ(xt,n,e[s(1023)](D,Ke)))}else try{this[s(1281)]?.close(),this[s(1281)]=void 0}catch(f){_0x131849[s(1282)](f)}}function S(a){let n=t;if(e[n(1118)](n(671),e[n(840)]))return e.mfZQK(I,e.eXuWP(B,a));{let s=e[n(1397)].split("|"),l=0;for(;;){switch(s[l++]){case"0":_0x39ad5b=e[n(546)](_0x5b5325,0,_0x27f113,_0x37af49);continue;case"1":_0x40f433=e[n(546)](_0x5ec305,_0xac84d2[n(435)+"er"](_0x13da96[n(1207)]||_0xe6a33c),_0x493d80,_0x2c4643);continue;case"2":_0x3dc527[n(1282)](n(1119),_0x5de42c);continue;case"3":_0x3617b0=e[n(546)](_0x43497c,_0x331b51[n(918)+n(392)],_0x14ef4d,_0x5736bf);continue;case"4":_0x363b6f.log(e[n(773)],_0x4dd5dd);continue;case"5":_0x5a5e91.log(e[n(689)],_0xd9a592);continue;case"6":_0x3ebaf6=e.OOCoq(_0x3b39ef,_0x2234b6[_0xcf1ec6[n(918)+n(392)]],_0x43659c,_0x13eb34);continue;case"7":_0x2d0960[n(1282)](e[n(1703)],_0x34dd19);continue;case"8":_0xbda327[n(1282)](e.KWLtu,_0xe3357d);continue;case"9":_0x4c09fb=_0x2d8f95(_0x424519,_0x106198,_0x161b8c[n(461)]||0);continue;case"10":_0x5c247e[n(1282)](e[n(923)],_0x1a84a9,_0x23fbca[n(461)]);continue}break}}}function I(a){let n=t;if(e[n(1170)]===e.IlMgY){let s={};e:for(;!V(a);){let l=e[n(1652)](xe,a);switch(e[n(1474)](l,3)){case 0:break e;case 1:s[n(1613)]=e[n(325)](It,a,!0);break;case 2:s[n(952)]=It(a,!0);break;case 3:s[n(461)]=xe(a);break;case 4:s[n(1568)]=xe(a);break;case 5:{let f=e[n(1486)](A,a);(s[n(1003)]||(s[n(1003)]=[]))[n(710)](e[n(731)](_,a)),a[n(1524)]=f;break}case 6:s[n(389)+n(1250)]=e[n(288)](P,a,e[n(690)](xe,a));break;case 7:s[n(1169)+n(445)]=e[n(1324)](P,a,e[n(1652)](xe,a));break;case 8:s.payload=e.czqTu(ie,a,xe(a));break;case 9:s.LogIDNew=e[n(1267)](P,a,xe(a));break;case 10:s[n(559)+n(1027)]=P(a,e[n(543)](xe,a));break;case 11:s.msgID=e[n(634)](P,a,xe(a));break;case 12:s.frameType=e[n(972)](xe,a);break;default:e[n(1470)](k,a,7&l)}}if(e[n(781)](void 0,s[n(1613)]))throw new Error(e.GZeip);if(s[n(952)]===void 0)throw new Error(e[n(1390)]);if(s.service===void 0)throw new Error(e[n(307)]);if(s[n(1568)]===void 0)throw new Error(e[n(1710)]);return s}else this[n(1775)+"s"]=_0xcfe6aa,this[n(867)+"es"]=_0x4e3a82,this[n(1495)+"ndex"]=0,this[n(648)+"ndpointT"+n(1709)+"t"]=0}function A(a){let n=t,s=e.lzTyK(xe,a),l=a[n(1524)];return a[n(1524)]=e.SXOpv(a[n(843)],s),l}function k(a,n){let s=t;switch(n){case 0:for(;e.cPJQO(128,ee(a)););break;case 2:J(a,e[s(425)](xe,a));break;case 5:e[s(288)](J,a,4);break;case 1:J(a,8);break;default:throw new Error(e.rBGak(s(1304)+s(1431)+s(1484),n))}}function D(a){return a|=0,{low:a,high:a>>31,unsigned:a>=0}}let E=[];function R(){let a=t;if(e[a(639)](e[a(1155)],a(1713))){let n=E[a(1080)]();return n?(n[a(843)]=n[a(1524)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}else return _0x442fef?_0xd1c718[a(1366)+a(960)](_0x4fd7a1,_0x457b32):_0x11718b[a(1366)+"sBE"](_0x3dce6f,_0x106752)}function L(a){E.push(a)}function B(a){return{bytes:a,offset:0,limit:a[t(421)]}}function M(a){let n=t,s=a.bytes,l=a[n(1524)];return e[n(662)](s[n(421)],l)?s:s[n(1758)](0,l)}function J(a,n){let s=t;if(a[s(843)]+n>a[s(1524)])throw new Error(s(879)+s(1462));a.offset+=n}function V(a){let n=t;return e[n(388)](a[n(843)],a[n(1524)])}function ne(a,n){let s=t;if(e[s(391)](e.braEJ,e[s(1599)]))try{return!!this[s(1281)]}catch(l){return _0x48b903[s(1282)](l),!1}else{let l=a[s(644)],f=a[s(843)],x=a[s(1524)],w=e.OSxhO(f,n);if(e.HIeEw(w,l[s(421)])){let b=new Uint8Array(e[s(947)](2,w));b[s(693)](l),a[s(644)]=b}return a[s(843)]=w,e[s(1541)](w,x)&&(a.limit=w),f}}function Y(a,n){let s=t,l=a[s(843)];if(e[s(855)](e[s(541)](l,n),a[s(1524)]))throw new Error(e[s(676)]);return a[s(843)]+=n,l}function ie(a,n){let s=t,l=e[s(365)](Y,a,n);return a[s(644)][s(1758)](l,e[s(1485)](l,n))}function se(a,n){let s=t,l={kVQgP:function(f,x,w){return e[U(971)](f,x,w)},IzXwR:function(f,x,w){return e[U(531)](f,x,w)},ssuoE:function(f,x){return e[U(1681)](f,x)}};if(e[s(1198)](e[s(1146)],e[s(1146)])){let f=e[s(456)](ne,a,n[s(421)]);a[s(644)].set(n,f)}else DbUVzm[s(760)](_0x21f250,_0x5d0da3,32),DbUVzm.IzXwR(_0x5e4804,_0x25ae67,DbUVzm.ssuoE(_0x3c472d,_0x156cde))}function P(a,n){let s=t,l=Y(a,n),f=String[s(1134)+s(1459)],x=a.bytes,w="\uFFFD",b="";for(let g=0;e[s(482)](g,n);g++){let C=x[g+l],O,F,j,W;if(e[s(1175)](e[s(679)](128,C),0))b+=e[s(690)](f,C);else if(e.whkhU(e.FPOdV(224,C),192))e.SXOpv(g,1)>=n?b+=w:(O=x[e[s(1246)](g+l,1)],e.YJSIT(e[s(1752)](192,O),128)?b+=w:(W=e[s(1021)](e[s(933)](31,C)<<6,e[s(982)](63,O)),W<128?b+=w:(b+=e.lQmcI(f,W),g++)));else if(e[s(1268)](240&C,224))if(e[s(613)](e[s(816)](g,2),n))b+=w;else if(O=x[e[s(565)](e.OSxhO(g,l),1)],F=x[e[s(870)](e.gvFFa(g,l),2)],e[s(1042)](e[s(453)](e.gJhJV(O,F<<8),49344),32896))b+=w;else if(e.ugRnC(e.pBNPv,e.pBNPv))W=e[s(407)]((15&C)<<12|e[s(1007)](e.FPOdV(63,O),6),e[s(236)](63,F)),e[s(412)](W,2048)||e[s(388)](W,55296)&&e[s(1648)](W,57343)?b+=w:(b+=e[s(609)](f,W),g+=2);else{let le=e[s(1578)](_0x2be300,e[s(967)],{message:_0x1a2944[s(1361)],code:_0x59794e[s(332)+"OR"],error:_0xd664f4});this[s(1479)+"hErrorEv"+s(1110)](le)}else e[s(443)](e.cPJQO(248,C),240)?e.vIUDW(e.IfIso(g,3),n)?b+=w:(O=x[e[s(699)](e[s(1549)](g,l),1)],F=x[e.TErYF(e[s(1147)](g,l),2)],j=x[e.rBGak(e[s(270)](g,l),3)],e[s(587)](e.Ukqil(e.LfIKo(e[s(407)](O,e.Muihc(F,8)),e[s(1779)](j,16)),12632256),8421504)?b+=w:(W=e[s(433)](e[s(1090)](e.BnzVt(e[s(453)](7,C),18),e[s(1298)](e[s(1587)](63,O),12))|(63&F)<<6,63&j),e.rUNkp(W,65536)||e[s(1299)](W,1114111)?b+=w:(W-=65536,b+=e[s(971)](f,(W>>10)+55296,e[s(1755)](e[s(453)](1023,W),56320)),g+=3))):b+=w}return b}function G(a,n){let s=t,l=n[s(421)],f=0;for(let b=0;e[s(1595)](b,l);b++){let g=n[s(283)+"At"](b);e[s(1655)](g,55296)&&e[s(1197)](g,56319)&&e.SieUT(e[s(541)](b,1),l)&&(g=e[s(1461)](e.AeARH(g<<10,n[s(283)+"At"](++b)),56613888)),f+=e[s(412)](g,128)?1:e[s(412)](g,2048)?2:e[s(946)](g,65536)?3:4}e[s(511)](pe,a,f);let x=e[s(288)](ne,a,f),w=a[s(644)];for(let b=0;e[s(1171)](b,l);b++){let g=n[s(283)+"At"](b);e[s(1512)](g,55296)&&g<=56319&&e[s(784)](e[s(1659)](b,1),l)&&(g=e[s(376)](g<<10,n.charCodeAt(++b))-56613888),e[s(1595)](g,128)?w[x++]=g:(e[s(1172)](g,2048)?w[x++]=e[s(893)](e[s(453)](e[s(1531)](g,6),31),192):(e.awboE(g,65536)?w[x++]=e.MlTOZ(e[s(982)](e[s(1531)](g,12),15),224):(w[x++]=e[s(1531)](g,18)&7|240,w[x++]=e[s(1531)](g,12)&63|128),w[x++]=e[s(1658)](g,6)&63|128),w[x++]=e[s(1293)](e[s(1365)](63,g),128))}}function K(a,n){let s=t,l=e[s(888)](ne,a,n.limit),f=a[s(644)],x=n[s(644)];for(let w=0,b=n[s(1524)];e[s(482)](w,b);w++)f[e.ZBANW(w,l)]=x[w]}function ee(a){let n=t;return a[n(644)][e[n(1309)](Y,a,1)]}function Xe(a,n){let s=t,l=e[s(1309)](ne,a,1);a[s(644)][l]=n}function xe(a){let n=t,s=0,l=0,f;do if(e[n(965)](e[n(1647)],n(1448)))f=ee(a),e.mRYTs(s,32)&&(l|=e[n(890)](e[n(1263)](127,f),s)),s+=7;else return e[n(1655)](_0x3bcfde[n(843)],_0x20506b.limit);while(128&f);return l}function pe(a,n){let s=t;for(n>>>=0;n>=128;)Xe(a,e[s(1331)](e[s(1637)](127,n),128)),n>>>=7;Xe(a,n)}function It(a,n){let s=t,l=0,f=0,x=0,w;if(w=e[s(801)](ee,a),l=127&w,e[s(1166)](128,w)&&(w=e.PqdBl(ee,a),l|=e[s(1007)](e[s(505)](127,w),7),e[s(1335)](128,w)&&(w=ee(a),l|=e.TAzvD(e[s(925)](127,w),14),128&w&&(w=e[s(690)](ee,a),l|=e[s(1779)](e[s(626)](127,w),21),e.wFLMJ(128,w)&&(w=e.bYBQD(ee,a),f=e.pVsRo(127,w),e[s(641)](128,w)&&(w=ee(a),f|=e.BnzVt(127&w,7),e[s(1752)](128,w)&&(w=e[s(1023)](ee,a),f|=(127&w)<<14,128&w)))))))if(e[s(1715)](e[s(685)],e[s(1610)])){if(w=e[s(1016)](ee,a),f|=e[s(577)](e[s(1637)](127,w),21),e[s(1166)](128,w)){if(e.whkhU(e.lNgVB,"RzMsY"))return;if(w=ee(a),x=e[s(479)](127,w),128&w)if(e[s(1051)](e.jjAfR,e.jjAfR)){let b=e[s(1578)](_0x14de16,_0x314a35,_0x3dd5c9[s(421)]);_0x5cfc32[s(644)][s(693)](_0x5d1a18,b)}else w=ee(a),x|=e[s(1779)](127&w,7)}}else{let b=_0x578713[s(1361)][s(427)];b&&_0x1f55ee[s(1440)+"rs"](b)}return{low:e[s(956)](l,e.Muihc(f,28)),high:e[s(850)](e[s(1690)](f,4),e[s(994)](x,24)),unsigned:n}}function xt(a,n){let s=t,l={NNTaN:function(f,x){return e[U(232)](f,x)}};if(e[s(1307)](e.ewieg,e[s(281)])){let f=_0x49b1a2(_0x681292);this._ws&&l[s(873)](this[s(942)][s(864)+"te"],this[s(1350)])&&(this[s(942)]&&this._ws.send(f),this[s(692)]("send_ack",_0x2be693))}else{let f=e[s(809)](n[s(622)],0),x=e[s(383)](e.mhJSM(e[s(809)](n[s(622)],28),e[s(994)](n[s(353)],4)),0),w=e[s(1529)](n.high,24),b=w===0?e[s(1082)](0,x)?e[s(412)](f,16384)?e.JTCnq(f,128)?1:2:f<2097152?3:4:e[s(380)](x,16384)?e.OyrZz(x,128)?5:6:e[s(380)](x,2097152)?7:8:e[s(1564)](w,128)?9:10,g=e[s(943)](ne,a,b),C=a[s(644)];switch(b){case 10:C[g+9]=e[s(343)](e[s(301)](w,7),1);case 9:C[g+8]=e[s(1051)](9,b)?e[s(1331)](128,w):e[s(876)](127,w);case 8:C[e[s(1549)](g,7)]=e[s(1184)](8,b)?e[s(1774)](e[s(1046)](x,21),128):e[s(809)](x,21)&127;case 7:C[e.lWNOE(g,6)]=e[s(1561)](7,b)?e[s(1331)](e[s(1529)](x,14),128):e.WYKgn(e[s(515)](x,14),127);case 6:C[e[s(279)](g,5)]=b!==6?e[s(1458)](e[s(774)](x,7),128):e[s(1166)](e[s(515)](x,7),127);case 5:C[e[s(1755)](g,4)]=e[s(624)](5,b)?e.teCVK(128,x):e[s(769)](127,x);case 4:C[e.utWFh(g,3)]=e.udpaJ(4,b)?e[s(407)](e.KTYDn(f,21),128):e[s(1520)](e[s(515)](f,21),127);case 3:C[g+2]=e[s(891)](3,b)?e[s(407)](e[s(383)](f,14),128):e[s(1335)](f>>>14,127);case 2:C[e.tNlOj(g,1)]=b!==2?e[s(893)](e.VAzdA(f,7),128):e.QmMtX(e[s(530)](f,7),127);case 1:C[g]=b!==1?e[s(1293)](128,f):e[s(1609)](127,f)}}}function en(a){let n=t,s={plUcR:function(l,f){return l<f},QKyzi:function(l,f){return e[U(607)](l,f)},ZmjcT:function(l,f){return l>f},METrj:function(l,f){return e.ZBANW(l,f)},RvTTs:function(l,f){return e.vnzBU(l,f)},Qxoms:function(l,f){return l&f},STbUT:function(l,f){return e[U(279)](l,f)},mEfnx:function(l,f){return l|f}};if(e[n(969)](e[n(1026)],n(1340)))return e.QlkPM(S,a);{if(s[n(803)](_0x4d1e12,1)||s[n(1650)](_0x468832,_0x25955a))return _0x421bcf(_0x175ba2);s[n(535)](s.METrj(_0x3c6893,_0x1f2eaa),_0x226efc)&&(_0x2bb3c3=s[n(1248)](_0xf0ca4,_0x5da436),_0x443210=0);let l=_0x5a8807[n(1290)](_0x2402d3,_0x4e52b5,_0x1b1e9f+=_0x412145);return s[n(1429)](7,_0x44ae97)&&(_0x5d0e57=s.STbUT(s[n(570)](7,_0x1c772c),1)),l}}function zt(a){let n=t;return e.faTXc("KDpzD",e[n(618)])?this[n(758)+n(1644)][n(1498)]((l,f)=>(l+=f&&f[n(1768)+"th"]||0,l),0)+(this[n(942)]?this[n(942)][n(229)+"Amount"]:0):v(a)}let tn=65536,Zr=t(536),we=e[t(1475)](tn,tn),Ie=e[t(457)](we,we),er=e.eyHTc(Ie,2),De=String[t(1621)+"e"].charCodeAt;class fe{constructor(n,s,l){let f=t,x={azuYH:function(w,b){return e[U(1509)](w,b)},iVIUh:function(w,b){return e[U(1658)](w,b)},Mvvdw:function(w,b){return e[U(1755)](w,b)},hZExI:function(w,b){return e[U(236)](w,b)}};e[f(662)](f(1121),f(569))?(_0x2c7624-=65536,_0x47ff07+=_0x5b2d10(JHwLLz[f(305)](JHwLLz.iVIUh(_0x4e7ece,10),55296),JHwLLz.Mvvdw(JHwLLz[f(498)](1023,_0xa93381),56320)),_0x3cc9d6+=3):(this[f(1212)]=!0,this[f(622)]=e[f(1293)](0,n),this.high=e[f(893)](0,s),this[f(1018)]=!!l)}static[t(1212)](n){let s=t;return n&&e[s(232)](!0,n[s(1212)])}static[t(1409)](n,s,l){return new fe(n,s,l)}static[t(1366)+"s"](n,s,l){let f=t;return l?fe[f(1366)+"sLE"](n,s):fe["fromByte"+f(1418)](n,s)}static[t(1366)+"sLE"](n,s){let l=t;return new fe(e.PBjDY(e[l(1349)](n[0],e[l(612)](n[1],8)),e.nhBHH(n[2],16))|e[l(921)](n[3],24),e.cbcTd(e[l(660)](n[4]|e[l(588)](n[5],8),n[6]<<16),e[l(1671)](n[7],24)),s)}static["fromByte"+t(1418)](n,s){let l=t;return new fe(e[l(1774)](e[l(1331)](n[4]<<24|n[5]<<16,e.aVzjK(n[6],8)),n[7]),e[l(660)](e[l(1240)](e[l(660)](e[l(1260)](n[0],24),n[1]<<16),e[l(588)](n[2],8)),n[3]),s)}static[t(848)](n){let s=t;return e.dAENu(n,Zr)?Yl:new fe(e.MlyNU(e[s(770)](De[s(1290)](n,0),e[s(680)](De.call(n,1),8))|e[s(916)](De[s(1290)](n,2),16)|e[s(1733)](De[s(1290)](n,3),24),0),e[s(1442)](e[s(484)](De[s(1290)](n,4)|e.SLUTJ(De[s(1290)](n,5),8)|De[s(1290)](n,6)<<16,e[s(673)](De[s(1290)](n,7),24)),0),!0)}[t(1231)](){let n=t;return String["fromChar"+n(1459)](255&this[n(622)],e[n(809)](this.low,8)&255,e[n(1335)](e[n(1474)](this[n(622)],16),255),e.VAzdA(this[n(622)],24),e.hMTJp(255,this[n(353)]),e[n(741)](e[n(1529)](this[n(353)],8),255),e.wzsRo(this[n(353)],16)&255,this[n(353)]>>>24)}static fromNumber(n,s=!0){let l=t,f={PFJZK:function(x,w){return x+w},vgGlD:function(x,w){return e.EmAjp(x,w)},fhbPm:function(x,w){return e.ADODX(x,w)}};if(e[l(1611)](isNaN,n))return s?Ip:Yl;if(s)if(e[l(587)](e[l(1280)],e.UeYsi)){if(e[l(1453)](n,Ie))return Tp}else{let w=""+_0x27b630[l(516)](),b=_0x416cf9||(_0x347c50=_0x2a31b7(_0x2f867f)),g=_0x4c3b4c[l(405)]()[l(860)](16)[l(1445)](-6);return HhCjZj.PFJZK(HhCjZj[l(651)](HhCjZj[l(1736)]("02",w),b),g)}else{if(e[l(1648)](n,-er))return kp;if(e[l(1453)](e.OSxhO(n,1),er))return Ap}return fe.fromBits(e[l(433)](e[l(364)](n,we),0),e[l(1109)](e[l(658)](n,we),0),s)}[t(1506)](){let n=t;if(e.MxmQQ(e[n(1434)],n(1220)))_0xf261a4.d=(s,l)=>{let f=n;for(var x in l)_0x31e826.o(l,x)&&!_0x1d7452.o(s,x)&&_0x454168[f(911)+f(700)](s,x,{enumerable:!0,get:l[x]})};else return this[n(1018)]?e[n(947)](e.ZNjKH(this[n(353)],0),we)+e[n(809)](this.low,0):e[n(1475)](this[n(353)],we)+e[n(810)](this[n(622)],0)}[t(1136)](){let n=t;return e[n(1589)]!=="zwhUc"?this.high===0&&this[n(622)]===0:_0x420e9d[n(1215)]()}[t(811)](n){let s=t;fe[s(1212)](n)||(n=fe[s(435)+"er"](n));let l=e[s(394)](this.high,16),f=e[s(343)](65535,this[s(353)]),x=e.Llurg(this[s(622)],16),w=e[s(779)](65535,this[s(622)]),b=e.uHVgA(n[s(353)],16),g=e[s(1662)](65535,n.high),C=e.Mrcgw(n.low,16),O=e[s(904)](65535,n[s(622)]),F=0,j=0,W=0,le=0;return le+=e[s(1417)](w,O),W+=e[s(1604)](le,16),le&=65535,W+=e[s(573)](x,C),j+=e.TIoEI(W,16),W&=65535,j+=f+g,F+=e.PpzWD(j,16),j&=65535,F+=e[s(699)](l,b),F&=65535,fe.fromBits(e.pmCNE(W,16)|le,e.xPGlN(e[s(582)](F,16),j),this[s(1018)])}[t(289)](n){let s=t;return fe[s(1212)](n)||(n=fe[s(435)+"er"](n)),e.ohYRY(this[s(1018)],n.unsigned)&&e[s(965)](e.ZQjTN(this[s(353)],31),1)&&e[s(1301)](n[s(353)]>>>31,1)?!1:this[s(353)]===n[s(353)]&&e[s(1491)](this.low,n[s(622)])}addOne(){let n=t,s={oAScI:function(l,f){return e[U(338)](l,f)},KJKPv:function(l,f){return e[U(374)](l,f)},CVVLd:function(l,f){return e[U(745)](l,f)},oyFBj:function(l,f){return e[U(745)](l,f)},cGJmq:function(l,f){return l(f)}};if(e.ohYRY("kBXbm",e[n(322)]))return e[n(1636)](-1,this[n(622)])&&e[n(1050)](-1,this[n(353)])?fe[n(1409)](0,0,this[n(1018)]):e.YSQbW(-1,this[n(622)])?fe.fromBits(0,e.pFxaT(this.high,1),this.unsigned):fe[n(1409)](e[n(279)](this[n(622)],1),this[n(353)],this[n(1018)]);_0x34ff4a=utAnvN[n(712)](_0x4dab29,_0x2f1ce2),_0x1632fd|=utAnvN.KJKPv(utAnvN[n(657)](127,_0x3e30f3),21),utAnvN[n(657)](128,_0x3ecd15)&&(_0x392bcb=_0x2781fe(_0x23e0e4),_0x52f0fb=utAnvN[n(1770)](127,_0x5933ca),128&_0x30a3d1&&(_0x577354=utAnvN[n(1199)](_0xc00939,_0x3bc92f),_0x2c406e|=utAnvN[n(1047)](utAnvN[n(657)](127,_0x1126b9),7)))}[t(885)](n){return n?this[t(805)+"E"]():this.toBytesBE()}[t(805)+"E"](){let n=t,s=this.high,l=this[n(622)];return[e[n(1263)](255,l),e[n(453)](l>>>8,255),e[n(1189)](l,16)&255,l>>>24,e.QmMtX(255,s),e[n(909)](e[n(301)](s,8),255),e[n(909)](s>>>16,255),s>>>24]}[t(409)+"E"](){let n=t,s=this[n(353)],l=this[n(622)];return[e.MmveK(s,24),e[n(937)](s,16)&255,e.wXLex(e[n(621)](s,8),255),e[n(544)](255,s),e[n(1358)](l,24),e[n(638)](e.yOLnC(l,16),255),e.OPIpP(l>>>8,255),e.yVuUE(255,l)]}}let Yl=new fe(0,0,!1),Ip=new fe(0,0,!0),Ap=fe[t(1409)](-1,2147483647,!1),Tp=fe[t(1409)](-1,-1,!0),kp=fe[t(1409)](0,-2147483648,!1);var nn=(function(a){let n=t;return a[a[e[n(1321)]]=5001]=e[n(1321)],a[a[e[n(874)]]=5002]=e[n(874)],a[a[e[n(1343)]]=5003]=n(330)+"IES_ERROR",a[a[e[n(1217)]]=5004]=e[n(1217)],a[a[e[n(749)]]=5005]=n(332)+"OR",a})({});class tr{constructor(n){let s=t;e[s(1307)](e[s(1482)],s(1344))?(this[s(1029)]=n,this[s(481)]=null):(this[s(1281)]?.[s(1073)](),this._qosDB=void 0)}}class Xl extends tr{constructor(n,s){let l=t;super(n),this[l(1361)]=s&&s[l(1361)]||null}}class Ql extends tr{constructor(n,s){let l=t,f={bgFTv:function(x,w,b){return e[U(595)](x,w,b)},LTdsM:e[l(263)]};if(e.upYSO(e[l(1526)],e.FmDVu)){let x="6|3|2|5|0|4|1"[l(992)]("|"),w=0;for(;;){switch(x[w++]){case"0":this.lineno=s&&s.lineno||0;continue;case"1":this[l(1058)]=s&&s[l(1058)]||5001;continue;case"2":this.colno=s&&s[l(723)]||0;continue;case"3":this.error=s&&s[l(385)]||null;continue;case"4":this[l(1361)]=s&&s[l(1361)]||"";continue;case"5":this[l(337)]=s&&s[l(337)]||"";continue;case"6":super(n);continue}break}}else{let x=this[l(1674)]["reconnectInterce"+l(1675)](_0x125828,_0x76e836);this[l(1479)+l(1122)+"ent"](f[l(912)](_0x2f78ca,f[l(563)],{code:_0x1ab780,reason:_0x64fb62,wasClean:!0,willReconnect:x})),x&&this[l(512)]()}}}class ed extends tr{constructor(n,s){let l=t;if(e[l(1077)](l(722),e[l(422)]))this[l(1656)]=!0,this[l(512)]();else{let f=(l(509)+"2").split("|"),x=0;for(;;){switch(f[x++]){case"0":super(n);continue;case"1":this[l(1058)]=s&&s.code||0;continue;case"2":this[l(291)+l(499)]=s&&s[l(291)+l(499)]||!1;continue;case"3":this.wasClean=s&&s[l(1165)]||!1;continue;case"4":this[l(490)]=s&&s[l(490)]||"";continue}break}}}}class td extends tr{constructor(n,s){let l=t;super(n),this[l(783)]=s&&s.data||null}}class nd extends td{constructor(n,s){let l=t;super(n),this.data=s&&s[l(783)]||null,this[l(1361)]=s&&s[l(1361)]||null}}class rd extends tr{constructor(n,s){let l=t;if(e.RigNU(e.kfgZt,e[l(1607)]))super(n),this.data=s&&s[l(783)]||null;else{let f=this[l(792)+l(1034)]?.[l(997)+"chMaxTries"](),x=this[l(792)+"tManager"]?.[l(1346)+"ntEndpoint"]();if(f&&!_0x5939f1[l(1361)]){let w="connect "+x+(l(1371)+l(815)+"es reached");this[l(1479)+l(857)+"ent"](e[l(1470)](_0x3b4320,l(385),{message:w,code:_0x16babe[l(330)+l(1102)+"R"],error:_0xbb5810}));return}this._ws&&this[l(942)][l(864)+"te"]===this.OPEN&&this[l(280)+l(818)](),this[l(1479)+l(857)+"ent"](e[l(259)](_0xec46df,l(385),{message:_0x63874f[l(1361)],code:_0x3ccb74.NATIVE_ERROR,error:_0x5680a5}))}}}function ct(a,{message:n,code:s,error:l}){return new Ql(a,{message:n,code:s,error:l})}function pt(a,{code:n,reason:s,wasClean:l,willReconnect:f}){return new ed(a,{code:n,reason:s,wasClean:l,willReconnect:f})}function id(a,{data:n,message:s}){return new nd(a,{data:n,message:s})}function sd(a,{data:n}){return new rd(a,{data:n})}function da(a,{message:n}){return new Xl(a,{message:n})}class od{constructor(n,s){let l=t;if(l(907)!==e[l(1473)])this[l(1775)+"s"]=n,this.maxRetries=s,this[l(1495)+"ndex"]=0,this["currentE"+l(1631)+"riesCount"]=0;else return this[l(1281)].clearStorageSync()}[t(334)+t(1467)+t(788)](){let n=t;this[n(1495)+n(1284)]=0,this[n(648)+n(1631)+"riesCount"]=0}[t(780)+"es"](){let n=t;this[n(648)+n(1631)+"riesCount"]=0}[t(1346)+"ntEndpoint"](){let n=t;return this[n(1775)+"s"][this[n(1495)+n(1284)]]}["getCurre"+t(1753)+t(271)+t(814)](){let n=t;return this[n(648)+n(1631)+n(1709)+"t"]}["checkRea"+t(1433)+"es"](){let n=t;return e[n(802)](n(1178),n(1178))?this._ws?this[n(942)][n(1294)]:"":!!(e[n(420)](this[n(1495)+n(1284)],this.endpoints[n(421)])||e[n(688)](this.currentIndex,this[n(1775)+"s"][n(421)]-1)&&this[n(648)+n(1631)+"riesCount"]===this[n(867)+"es"])}[t(296)+t(1466)+t(872)+t(1481)+t(583)](){let n=t,s={vtctm:function(l,f,x){return e.gAtCr(l,f,x)},vAZaj:function(l,f){return e[U(394)](l,f)},pEUof:function(l,f){return l<<f}};if(e[n(1455)](e[n(1490)],e[n(533)]))return e[n(966)](this[n(1495)+n(1284)],this[n(1775)+"s"].length)?!0:e[n(1299)](this[n(648)+n(1631)+"riesCount"],this[n(867)+"es"]);{let{value:l,offset:f}=s[n(1499)](_0x26e910,_0x5bdca9,_0x380b4e);_0x4a300e=f,_0x29e1ea=s[n(735)](s[n(464)](_0x4bd3ca,8),0),_0x169695+=l}}["replaceB"+t(1776)+"pointAndUpdateCo"+t(900)](){let n=t;return this["currentE"+n(1631)+n(1709)+"t"]=1,this["currentI"+n(1284)]++,this[n(1775)+"s"][this["currentI"+n(1284)]]}[t(1346)+t(1753)+t(1742)+t(623)](){let n=t;if(n(275)===e.QYIHe)return this[n(648)+n(1631)+n(1709)+"t"]++,this["getCurre"+n(1753)+"nt"]();{let s=(n(1190)+"4")[n(992)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(1056)+n(961)]?.[n(1645)+n(1214)]();continue;case"1":this[n(792)+n(1034)]?.[n(334)+"pointCon"+n(788)]();continue;case"2":this[n(1656)]=!0;continue;case"3":this[n(1435)+n(1544)]=!1;continue;case"4":this[n(512)]();continue}break}}}}let nr=(e.KCQCr(e.OWdXH,typeof globalThis)&&t(859)===globalThis[t(1188)+"tor"].name||e[t(459)](e[t(501)],typeof window)&&e[t(969)](e[t(1558)],window["construc"+t(1572)][t(1569)]))&&e.OWdXH!=typeof document,Rn=e[t(1093)](e[t(501)],typeof globalThis)&&(e[t(1563)](e[t(1257)],globalThis[t(1188)+"tor"][t(1569)])||e[t(821)](t(1055)+t(1565)+t(373)+"pe",globalThis[t(1188)+t(1572)][t(1569)]))&&e[t(1660)](e[t(501)],typeof tt),Yr=(e[t(1743)](t(844)+"d",typeof globalThis)&&t(477)===globalThis[t(1188)+t(1572)].name||e[t(1447)](e.OWdXH,typeof globalThis)||e[t(1661)](e[t(501)],typeof globalThis)&&!!globalThis[t(1379)+t(701)])&&e[t(534)](e[t(501)],typeof wx),Xr=e[t(929)](e[t(501)],typeof globalThis)&&(e[t(798)](e[t(1497)],globalThis["construc"+t(1572)][t(1569)])||e[t(871)](t(944)+t(1740)+t(1004),globalThis["construc"+t(1572)][t(1569)])||e[t(662)](t(1033)+t(974)+"balScope",globalThis[t(1188)+t(1572)][t(1569)]))&&e[t(1093)](e.OWdXH,typeof self),Cp=e[t(1716)](e[t(501)],typeof globalThis)&&e[t(1257)]===globalThis[t(1188)+t(1572)].name&&e[t(1030)](e[t(501)],typeof global)&&e[t(1491)](e[t(1257)],global[t(1188)+"tor"][t(1569)])&&e[t(378)](e[t(501)],typeof process)&&!!process[t(999)];class ua{constructor(){let n=t;this[n(581)+"rs"]={}}emit(n,...s){let l=t,f=this[l(581)+"rs"][n];if(f)f[l(1445)]()[l(1076)](x=>x.fn[l(411)](x[l(1699)],s));else if(e.aunSu===n&&!this[l(1070)]){let x=s[l(421)]&&s[0];if(e[l(252)](x,Error))throw x;let w=new Error(e.bqxdF+(x?" ("+x[l(1361)]+")":""));throw w[l(920)]=x,x}return this}[t(1781)](n,s){let l=t;if(n===void 0)this[l(581)+"rs"]={};else if(e[l(455)](void 0,s))this[l(581)+"rs"][n]=null;else{let f=this[l(581)+"rs"][n];if(f)for(let x=0;e[l(1171)](x,f.length);)e[l(996)](f[x].fn,s)?f[l(367)](x,1):++x}return this}on(n,s,l){let f=t;return(this[f(581)+"rs"][n]||(this[f(581)+"rs"][n]=[])).push({fn:s,ctx:l||this}),this}}class Rp extends ua{[t(555)+t(333)+t(1469)](n){let s=t;if(e[s(1312)]!==e[s(1312)])this[s(837)](e[s(1105)],e[s(1160)](_0x1fe273,e[s(1105)],{..._0x49ae53,data:_0x282cd4[s(1133)]||""}));else return n.errMsg||n.errNo?(s(1695)+" "+(n[s(1133)]||"")+s(647)+(n.errNo||""))[s(822)]():JSON[s(1126)+"y"](n)}constructor(n,s,l){let f=t;super(),this[f(567)]=null,Yr&&wx[f(1697)+f(1651)]&&(this[f(567)]=wx[f(1697)+"ocket"]({url:n,protocols:s,header:l,fail:this[f(475)+"ocketFai"+f(575)].bind(this),success:this[f(475)+f(707)+"cessHandler"].bind(this)})),Rn&&tt[f(1697)+f(1651)]&&(this._socket=tt.connectSocket({url:n,protocols:s,header:l,fail:this[f(475)+f(1373)+"lHandler"][f(608)](this),success:this[f(475)+f(707)+f(321)+f(846)][f(608)](this)}))}[t(475)+t(707)+t(321)+t(846)](){let n=t;Promise.resolve()[n(1125)](()=>{let s=n;this[s(1677)+s(345)]()})}[t(475)+t(1373)+t(575)](n){let s=t;Promise[s(1215)]()[s(1125)](()=>{let l=s,f=e[l(244)](ct,e[l(967)],{message:this[l(555)+l(333)+l(1469)](n)});this[l(837)](e.aunSu,f);let x=e[l(1324)](pt,e[l(263)],{reason:this["_formatE"+l(333)+l(1469)](n)});this[l(837)](e[l(263)],x)})}_addWsListeners(){let n=t,s={ncGKZ:function(l){return l()},ZMTbd:function(l,f){return e[U(1428)](l,f)},AlSpX:e.lywIh,svrFk:e[n(757)],WZhBz:n(439),qNYxS:e[n(263)],qmCul:function(l,f,x){return e.oLSTe(l,f,x)},KZGIQ:function(l,f,x){return l(f,x)},eMbZy:e[n(967)]};e[n(391)]("mBzJi",e[n(1154)])?(this._DBName=_0x1b424f,this._pathKey=_0x312bb1,this[n(1281)]=_0x10ff65?_0x2ae08c:_0x33716e?_0x47fdb2:null):(this._socket.onOpen(l=>{let f=n,x={LrwRG:function(w){return s[U(1031)](w)}};s[f(566)](s[f(1085)],s.svrFk)?this[f(837)](s[f(1508)],sd(s.WZhBz,{...l,data:l[f(1133)]||""})):(wYHfco[f(1308)](_0xb2555a),_0xf06db3())}),this._socket[n(656)](l=>{let f=n;this[f(837)](s[f(1099)],s.qmCul(pt,s[f(1099)],{...l}))}),this[n(567)].onMessage(l=>{let f=n;this[f(837)]("message",s.KZGIQ(id,f(1361),{...l}))}),this._socket[n(1725)](l=>{let f=n;this[f(837)](s[f(326)],ct(s[f(326)],{...l,message:l[f(1133)]||""}))}))}[t(584)](n){let s=t,l={tUeDW:function(f,x){return e[U(955)](f,x)},mvJag:function(f,x){return e[U(1259)](f,x)},TbkbH:function(f,x){return f&x},CfrzJ:function(f,x){return e[U(346)](f,x)},nUEyW:function(f,x,w){return f(x,w)},cZBIs:"error",tMfiK:function(f,x){return e[U(1410)](f,x)},NwTUU:function(f,x){return f!==x},EHfMh:s(975)};if(e[s(632)](n,Uint8Array))if(e[s(1734)]===e[s(1107)])_0x201fd2=_0x38e122(_0x56c229),_0x16b704|=(127&_0x248300)<<14,128&_0x2a3583&&(_0x3cca25=TtwTAw[s(852)](_0x176265,_0x3b18b4),_0x1b6a74|=TtwTAw[s(672)](TtwTAw[s(1239)](127,_0x3cf569),21),TtwTAw.TbkbH(128,_0x41fa0)&&(_0x50f5b3=_0x531775(_0x36be20),_0x5e7138=TtwTAw[s(1239)](127,_0x418e83),128&_0x173f7c&&(_0x524c35=TtwTAw[s(300)](_0x54817c,_0x8ab5a3),_0x26a168|=TtwTAw.mvJag(127&_0x1410f6,7))));else{let f=n[s(1746)][s(1445)](n[s(1627)+"et"],e.WgfUj(n.byteLength,n.byteOffset));this[s(567)]&&this[s(567)][s(584)]({data:f,fail:x=>{let w=s;this.emit("error",l[w(348)](ct,l[w(1542)],{message:this[w(555)+"rrorMess"+w(1469)](x)}))}})}else this[s(567)]&&this[s(567)].send({data:n,fail:f=>{let x=s,w={MeZTg:function(b,g){return l.tMfiK(b,g)},sffCA:function(b,g){return l.tMfiK(b,g)},JJxZI:x(844)+"d"};if(l.NwTUU(x(975),l[x(1670)])){if(_0x48cfb4)return new _0x198ef5(_0x9b27bc.url,_0x49294a[x(1294)]);if(w[x(649)](_0x28fea9,_0x10709e))return new _0x4d9334(_0x277532[x(297)],_0x585a18.protocol,_0x255347[x(1003)]);if(w[x(1583)](_0x1902cd,_0x318af2)&&w[x(320)]!=typeof _0x568006&&_0x30349e)return new _0x5bafee(_0x3f6783.url,_0x19f179[x(1294)+"s"])}else this[x(837)]("error",l[x(348)](ct,l[x(1542)],{message:this[x(555)+x(333)+"age"](f)}))}})}[t(1073)](n,s){let l=t;this[l(567)]&&this[l(567)][l(1073)]({code:n,reason:s})}["addEvent"+t(274)](n,s){let l=t;if(e[l(1694)](e.FBjHt,e[l(366)]))return this._isMiniTT||this._isMiniWX?this[l(528)+l(585)+l(1570)]:(this[l(980)+"er"]||this._isWorker)&&this[l(1674)][l(795)+l(576)+"nged"]?_0x2b4c5b[l(1392)]:!0;this.on(n,s)}["removeEv"+t(1414)+"ner"](n,s){let l=t;e[l(1141)](e[l(487)],e[l(1347)])?this[l(1035)+"T"]||this[l(551)+"X"]?this["_onPageN"+l(1078)+l(510)]():this[l(980)+"er"]&&this[l(1575)+l(1687)+l(274)]():this[l(1781)](n,s)}get[t(864)+"te"](){let n=t;return this[n(567)][n(864)+"te"]}get[t(606)+"pe"](){let n=t;if(e.FqEHf===e[n(659)])this[n(653)+n(814)]=_0x113e6f,this.count=0;else return this[n(567)].binaryType}set[t(606)+"pe"](n){}get url(){let n=t;return e[n(1628)]===e.lieKB?(_0x1cf0b0[n(1282)](e.zZRnV,_0x16978a,_0x3929e6,_0x561f8d),this[n(1281)].set({cursor_name:_0x11e45f,cursor:_0x3c1681,service:_0x7ef264})):this[n(567)].url}get[t(1294)](){let n=t;return this[n(567)][n(1294)]}get extensions(){return this[t(567)].extensions}get[t(229)+t(1273)](){let n=t;if(e[n(802)](e[n(1530)],e.BqyRz))this.on(_0x5c9b1d,_0x5990ec);else return 0}}function Pp(a,n){let s=t;if(n)return new n(a[s(297)],a[s(1294)]);if(e.PhVod(Yr,Rn))return new Rp(a[s(297)],a[s(1294)],a.headers);if(e[s(883)](nr,Xr)&&e[s(1743)](e[s(501)],typeof WebSocket)&&WebSocket)return new WebSocket(a[s(297)],a.protocols)}function Dp(a){let n=t,s=e[n(448)][n(992)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(e.ZOHaH(nr,Xr)&&e.Umtfp(n(844)+"d",typeof WebSocket)&&WebSocket)return!0;continue;case"1":if(Yr&&wx["connectS"+n(1651)])return!0;continue;case"2":if(a)return!0;continue;case"3":return!1;case"4":if(Rn&&tt[n(1697)+"ocket"])return!0;continue}break}}function ad(a,n,s){let l=t,f={OkVQV:function(b,g){return b<=g},yOazq:l(1143)+l(601)+l(968)+l(432)+"process",QeOdE:function(b,g){return e[l(996)](b,g)},eJOoH:function(b,g){return b+g}},x=-1;async function w(b){let g=l;return f.OkVQV(b,x)?Promise[g(1191)](new Error(f[g(525)])):(x=b,f[g(1279)](b,s.length)?Promise[g(1215)]():s[b][g(608)](a)(n,w[g(608)](null,f[g(776)](b,1))))}e[l(731)](w,0)}function cd(a){let n=t,s={YnYAU:e[n(480)],PATqB:e[n(963)],awNeF:n(1569),DhqOg:function(l,f,x,w){return e[n(403)](l,f,x,w)},UMuwX:e[n(1703)]};if(e[n(235)]===e[n(235)]){let l=0,f=0;for(let x=0;x<a[n(421)];++x)f=a[n(283)+"At"](x),f<128?l+=1:e[n(901)](f,2048)?l+=2:e[n(251)](e[n(935)](64512,f),55296)&&e.ndBbv(64512&a[n(283)+"At"](e[n(565)](x,1)),56320)?(++x,l+=4):l+=3;return l}else{let[l,f]=e[n(1523)](_0x159d67,_0x1107c7),x=e.sgOUl(_0x59752c,l),w=0;return _0x2c2d80.forEach(b=>{let g=n,C=s[g(1510)][g(992)]("|"),O=0;for(;;){switch(C[O++]){case"0":_0x1535ef[g(1282)](g(418),w);continue;case"1":_0x39d825[g(1282)]("cursor.service",b,b[g(461)]);continue;case"2":_0x258c97.log(s[g(1406)],w);continue;case"3":_0x359347[g(1282)](g(461),w);continue;case"4":_0x58461f[g(1282)](s[g(1505)],w);continue;case"5":w=s[g(1376)](_0x557055,_0x5c995c[g(435)+"er"](b[g(1207)]||_0x55a69b),x,w);continue;case"6":w=s[g(1376)](_0x43472f,f[b[g(918)+g(392)]],x,w);continue;case"7":w=s[g(1376)](_0xc59247,0,x,w);continue;case"8":w=s[g(1376)](_0x2df7e8,b[g(918)+g(392)],x,w);continue;case"9":w=s[g(1376)](_0x1aee33,x,w,b[g(461)]||0);continue;case"10":_0x17a7f8.log(s[g(1079)],w);continue}break}}),{frameType:_0x13244e,headers:[{key:e[n(340)],value:_0xe810b9}],payload:x}}}function ld(a,n,s){let l=t;if(e[l(1395)](e[l(416)](s,n),1))return"";let f="";for(let x=n;e.yDEcz(x,s);){let w=a[x++];if(e[l(1098)](w,127))f+=String.fromCharCode(w);else if(e[l(388)](w,192)&&e[l(828)](w,224))f+=String[l(1134)+l(1459)](e.srmrF(31,w)<<6|e[l(741)](63,a[x++]));else if(w>=224&&e[l(335)](w,240))f+=String[l(1134)+"Code"](e[l(770)](e[l(1458)](e.TAzvD(e[l(1303)](15,w),12),e[l(588)](e[l(851)](63,a[x++]),6)),e.NbRER(63,a[x++])));else if(e[l(1453)](w,240)){let b=e[l(995)](e.RbOuh(e.cfbMc(e[l(673)](e[l(679)](7,w),18),e[l(1255)](63,a[x++])<<12),e[l(730)](e[l(471)](63,a[x++]),6)),63&a[x++])-65536;f+=String[l(1134)+l(1459)](e.gnXbx(55296,e[l(545)](b,10))),f+=String[l(1134)+l(1459)](e[l(386)](56320,1023&b))}}return f}function fa(a,n,s){let l=t,f=s,x,w;for(let b=0;e.eZOpV(b,a[l(421)]);++b)if(x=a[l(283)+"At"](b),e[l(513)](x,128))n[s++]=x;else if(x<2048)n[s++]=e[l(1068)](e[l(1065)](x,6),192),n[s++]=e[l(436)](e.kAehm(63,x),128);else if(e[l(1491)](e.WtbSm(64512,x),55296)&&e.LjrtU(64512&(w=a[l(283)+"At"](e[l(978)](b,1))),56320)){let g=e[l(1061)].split("|"),C=0;for(;;){switch(g[C++]){case"0":n[s++]=e[l(1780)](63,x)|128;continue;case"1":n[s++]=e[l(1104)](e.AESfA(e.cjevw(x,12),63),128);continue;case"2":n[s++]=e.dmmrn(x,6)&63|128;continue;case"3":x=e[l(377)](65536+e.uLkhg(1023&x,10),e[l(769)](1023,w));continue;case"4":n[s++]=e[l(1065)](x,18)|240;continue;case"5":++b;continue}break}}else n[s++]=e[l(1229)](e.cjevw(x,12),224),n[s++]=e[l(1458)](e.RlWwt(x,6)&63,128),n[s++]=e[l(1293)](63&x,128);return e.kOvru(s,f)}async function dd(a){let n=t;if(e[n(450)]!==e.kBaPw){let s=this[n(1281)]["getStora"+n(936)+"nc"](this[n(468)]),l=_0x3bbecf.parse(e.ADhPR(s,"{}"));return _0x2d584e[n(1427)](l)}else{if(e.xSlQW(e[n(804)],typeof a)){let s=new Uint8Array(e.mfZQK(cd,a));return e[n(764)](fa,a,s,0),s}return a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a[n(1746)],a[n(1627)+"et"],a[n(1768)+"th"])}}function Op(a){let n=t;try{return e[n(746)](e[n(804)],typeof a)&&(e[n(1277)](a,ArrayBuffer)||a[n(1746)]&&e[n(1277)](a[n(1746)],ArrayBuffer))||e[n(1318)]("string",typeof a)?"":(JSON[n(519)](a),e[n(1274)])}catch{return e[n(804)]==typeof a?e[n(1048)]:""}}let Lp=(a,n)=>{let s=t;if(e[s(1694)](e[s(763)],e[s(1430)]))switch(a){case s(1576):case s(1237):return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}else return Re[s(1281)]?.[s(502)](_0x231ae1)};class Np{constructor(n){let s=t;this["maxLossC"+s(814)]=n,this[s(727)]=0}addCount(){this.count++}[t(997)+t(508)+"nt"](){let n=t;return e[n(613)](this[n(727)],this["maxLossC"+n(814)])}resetCounter(n=0){let s=t;this[s(653)+"ount"]=n,this[s(727)]=0}}async function Mp(a){let n=t,s={lFLGl:function(l,f){return l(f)},YpsJd:"unknown "+n(490),AAWfw:e[n(1711)],NwUDN:function(l,f){return e.uYKlJ(l,f)},OVrkL:n(931),jdbSp:e.PGqAI,ZXHje:function(l,f){return e[n(255)](l,f)},FpCpz:e[n(1501)],TYRHL:function(l,f){return e[n(996)](l,f)},cbSve:e[n(930)],ysvuU:e[n(949)],qNyMn:function(l,f){return e[n(972)](l,f)}};return new Promise(l=>{let f=n;if(s[f(808)](s[f(1527)],s[f(1527)]))this[f(402)+f(349)]();else{if(!nr)return s[f(1405)](l,s.YpsJd);try{let x=document[f(1537)+f(734)](s.jdbSp);window[f(831)+f(1266)]=w=>{let b=f;document[b(1020)][b(1483)+b(1496)](x),window["frontier"+b(1266)]=void 0,s[b(1405)](l,w&&w.msg||s[b(590)])},x[f(1029)]=f(1606)+"ascript",x[f(678)]=s[f(1439)](a[f(265)](/^ws/,f(1566)),s.FpCpz);try{if(s.TYRHL(s.cbSve,s[f(1551)]))switch(_0x12e0d2){case kZjxWN[f(919)]:case f(1237):return{[f(1543)+_0x23c099]:1,"x-tt-env":_0x37699d};default:return{}}else document.body[f(1286)+"ild"](x)}catch{document[f(1020)][f(1483)+f(1496)](x)}}catch{window[f(831)+f(1266)]=void 0,s[f(539)](l,s[f(590)])}}})}function rn(a,n,s){let l=t;return!!a?.[l(1028)](f=>f[l(775)]===n&&f.value===s)}function rr(a,n){return a?.[t(1028)](l=>l.key===n)?.value}let ha=null;async function Bp(){let a=t;return ha||(ha=Promise.resolve()[a(1125)](Bt[a(608)](Bt,e.muvry))),ha}class Fp extends ua{constructor(n,s){let l=t;super(),this[l(785)]=n,this[l(1111)]=s,this[l(1281)]=void 0,this[l(485)+l(1043)]=null}async[t(832)](){await this[t(593)]()}async[t(593)](){let n=t;if(e.qaEbI(e[n(1503)],"rAnGh"))_0x288fba.o=(s,l)=>_0x42653e[n(1621)+"e"][n(240)+"operty"].call(s,l);else{if(this[n(1281)])return;if(this[n(485)+n(1043)])return this["_initPro"+n(1043)];try{if(n(877)!==e[n(739)]){let s=e[n(1210)](_0x1e5993,_0x304f8f,1);_0x5332c3[n(644)][s]=_0x31b6d5}else{let s=this._dbName,l=this[n(1111)];this[n(485)+n(1043)]=(async()=>{let f=n,{openDB:x}=await Bp();this[f(1281)]=await e[f(403)](x,"frontier_"+s,1,{upgrade(w){let b=f;w[b(954)+b(1245)+"e"](s,{keyPath:l})}})})(),await this[n(485)+n(1043)]}}catch(s){console.log(s)}finally{this["_initPro"+n(1043)]=null}}}async[t(502)](n){let s=t;try{return await this[s(593)](),this[s(1281)]?.[s(502)](this[s(785)],n)}catch(l){console[s(1282)](l)}}async[t(693)](n,s){let l=t;return e[l(1623)](e.nweIQ,"Xadfn")?(await this[l(593)](),this[l(1281)]?.[l(1353)](this[l(785)],n)):_0x3aa877||(_0x30a5db=[_0x165772,_0x5afdfb,_0x3d0e9e,_0x846489,_0x335f4f])}async del(n){let s=t,l={upOpZ:function(f,x){return e.upyWX(f,x)},xCwUz:function(f,x){return e[U(1525)](f,x)},PUkAG:function(f,x){return e[U(1696)](f,x)}};try{return await this[s(593)](),this._qosDB?.[s(813)](this[s(785)],n)}catch(f){if(e[s(1141)](e[s(463)],e[s(526)])){let x=_0x692f6c[s(992)](":");_0x334cdb&&(_0x242d5f=x[s(421)]),_0x3bc85b+=x.length;for(let w=0;yhljBh[s(1738)](w,x.length);w++)if(yhljBh[s(1156)](4,x[w][s(421)])){let b=_0x4c0c77[s(738)+"g"](0,yhljBh[s(268)](4,x[w].length)),g=b[s(1480)](x[w]);_0xb5d8d3.push(g)}else _0x13fbe1[s(710)](x[w]);_0x365412=!1}else console.log(f)}}async clear(){let n=t;try{return await this[n(593)](),this._qosDB?.clear(this[n(785)])}catch(s){console[n(1282)](s)}}async keys(){let n=t;return await this[n(593)](),this[n(1281)]?.[n(694)+"ys"](this._dbName)}async[t(342)](){let n=t;return await this[n(593)](),this[n(1281)]?.[n(342)](this[n(785)])}async[t(1598)](){let n=t;if(e[n(1471)](n(1684),e[n(1603)]))this[n(942)]&&this[n(942)][n(1073)](_0x72c653,_0x132c05);else try{this[n(1281)]?.[n(1073)](),this[n(1281)]=void 0}catch(s){console[n(1282)](s)}}get isReady(){let n=t;if(e[n(662)](e[n(282)],"qbHka"))try{return!!this._qosDB}catch(s){return console[n(1282)](s),!1}else this[n(1677)+n(345)]()}}class zp{constructor(n,s){let l=t;this[l(1285)]=n,this[l(1667)]=s,this[l(1281)]=localStorage}async[t(832)](){}get _prefix(){let n=t,s={CwOeo:function(l,f){return e[U(1152)](l,f)},HnAWA:function(l,f){return l===f},RTrvv:e.PaBYi,wFWMj:function(l,f){return e[U(455)](l,f)},XmKYt:e[n(1241)],SOxmh:n(635),VxpCU:function(l,f){return e[n(1019)](l,f)}};if(e[n(1715)](e[n(866)],e[n(1164)]))return n(831)+"_"+this[n(1285)];if(JtMUpe.CwOeo(_0x489d81,_0x364d55)){if(JtMUpe.HnAWA(_0x9822c2,JtMUpe[n(1205)]))return _0x3e737a.get(_0x543ce5);if(JtMUpe[n(500)](_0x4dd992,JtMUpe[n(1630)]))return _0x56ba4d[n(938)+n(431)]||_0x39db4a[n(502)](_0x5e752e);if(_0x498403===JtMUpe[n(303)])return _0x263e59["objectSt"+n(431)][1]?void 0:_0x94a63f[n(938)+n(928)](_0x1acfff[n(938)+"oreNames"][0])}return JtMUpe[n(709)](_0x2d6b99,_0x1ad2a5[_0x3d5029])}async[t(502)](n){let s=t,l=this._qosDB[s(1183)](this[s(468)]);return JSON.parse(e.QsTYa(l,"{}"))[n]}async[t(693)](n,s){let l=t,f=this[l(1281)][l(1183)](this[l(468)]),x=JSON[l(519)](e[l(269)](f,"{}"));return x[s||n[this[l(1667)]]]=n,this[l(1281)][l(720)](this[l(468)],JSON[l(1126)+"y"](x)),s||n[this._pathKey]}async[t(716)](n){let s=t,l={xoDKN:function(f,x,w,b){return e[U(1701)](f,x,w,b)}};if(e[s(1386)](e[s(1261)],"lQdmq")){let f=this._qosDB[s(1183)](this[s(468)]),x=JSON[s(519)](e.ywzCo(f,"{}"));return x[n]=void 0,this[s(1281)][s(720)](this._prefix,JSON[s(1126)+"y"](x))}else l[s(465)](_0x5ba1ad,this,_0x29a157,[_0x59ec59,_0x2e9682,_0x52c34c])}async clear(){let n=t;return this[n(1281)][n(958)]()}async keys(){let n=t;if(e[n(243)](e[n(1352)],e.DTLdy)){let s=this[n(1281)][n(1183)](this[n(468)]),l=JSON[n(519)](e[n(580)](s,"{}"));return Object[n(1427)](l)}else _0x198dee[n(1020)][n(1483)+n(1496)](_0x4a26ff),_0x4e4445.frontierJSONP=void 0,e[n(254)](_0x293c7f,_0x224cf0&&_0x42b766[n(1771)]||e[n(1010)])}async[t(342)](){let n=t;if(e[n(1077)](e[n(1167)],n(1193)))this["_clearPi"+n(1535)](),this.emit(e[n(518)],e[n(1693)]),this[n(1382)+n(552)+"Id"]=e[n(1590)](_0x3e51e7,this[n(686)][n(608)](this),_0x28ed42);else{let s=this[n(1281)][n(1183)](this[n(468)]),l=JSON[n(519)](s||"{}");return Object[n(476)](l)}}closeDB(){return Promise[t(1215)]()}get isReady(){return!!this._qosDB}}class Up{constructor(n,s){let l=t;this[l(1285)]=n,this[l(1667)]=s,this[l(1281)]=Rn?tt:Yr?wx:null}async[t(832)](){}get[t(468)](){return"frontier_"+this[t(1285)]}async[t(502)](n){let s=t,l=this._qosDB["getStora"+s(986)](this[s(468)]);return JSON[s(519)](e[s(1553)](l,"{}"))[n]}async[t(693)](n,s){let l=t,f=this[l(1281)]["getStora"+l(986)](this._prefix),x=JSON[l(519)](f||"{}");return x[s||n[this[l(1667)]]]=n,this[l(1281)]["setStora"+l(986)](this[l(468)],JSON[l(1126)+"y"](x)),s||n[this._pathKey]}async[t(716)](n){let s=t,l=this[s(1281)]["getStora"+s(986)](this[s(468)]),f=JSON[s(519)](l||"{}");return f[n]=void 0,this._qosDB[s(962)+s(986)](this[s(468)],JSON[s(1126)+"y"](f))}async clear(){let n=t;return this[n(1281)]["clearSto"+n(591)]()}async[t(1427)](){let n=t,s=this[n(1281)][n(838)+n(936)+"nc"](this[n(468)]),l=JSON[n(519)](e[n(1685)](s,"{}"));return Object[n(1427)](l)}async getAll(){let n=t,s=this[n(1281)][n(838)+"geInfoSync"](this[n(468)]),l=JSON[n(519)](s||"{}");return Object[n(476)](l)}[t(1598)](){return Promise[t(1215)]()}get[t(1649)](){return!!this[t(1281)]}}function ud(a,n){let s=t;if(Rn||Rn)return new Up(a,n);if(e[s(696)](nr,Xr)&&e.FEsTM(s(844)+"d",typeof indexedDB))return new Fp(a,n);if(e[s(768)](nr,Xr)&&e.yTsgl(e.OWdXH,typeof localStorage))return new zp(a,n);throw new Error(e[s(1329)])}class Gp{constructor(){let n=t;this[n(402)+"lTimeoutId"]=null,this[n(402)+"l"]=36e5,this._qosDB=e[n(325)](ud,n(234),"message_id")}async["_interva"+t(349)](){let n=t,s={FrCfy:function(l,f){return l(f)},qnich:function(l){return e.khLSI(l)}};n(1692)===e[n(1389)]?(this._isInit=!1,s[n(1594)](_0x112d66,this[n(512)+n(767)+n(670)]),s[n(1633)](_0x3c37fc)):(clearInterval(this[n(402)+n(410)+"Id"]),this[n(402)+n(410)+"Id"]=e[n(1160)](setInterval,()=>{let l=n;this[l(1534)+l(724)]()},this[n(402)+"l"]))}async[t(832)](){let n=t;await this[n(1281)].openDB().then(()=>{let s=n;this[s(402)+s(349)]()})}async[t(1534)+t(724)](){let n=t,s={wqPep:e[n(967)]};e[n(1635)](e[n(1756)],e.GKRiA)?(await this[n(1281)]?.[n(342)]()||[]).filter(({timestamp:x})=>x<Date[n(516)]())[n(1076)](x=>{let w=n;this[w(1281)]?.[w(716)](x[w(1688)+"id"])}):(_0x1f42c1[n(637)+n(1414)+n(1643)](n(1456),_0x260821),_0xad439b["removeEv"+n(1414)+n(1643)](uAcPNS[n(667)],_0x5495cc))}async del(n){let s=t;return this[s(1281)]?.[s(716)](n)}async set(n,s){return this._qosDB?.set({message_id:n,timestamp:s})}async[t(502)](n){let s=t;return this[s(1281)]?.[s(502)](n)}async closeDB(){let n=t;e.GbKwI(clearInterval,this[n(402)+n(410)+"Id"]),await this[n(1281)]?.closeDB()}get[t(1649)](){let n=t;return this[n(1281)]?.[n(1649)]}}function xa(a){let n=t,s=!!this[n(1674)].enableQoS;if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[n(247)](rn,a[n(1361)].headers,"x_fronti"+n(892),"2"),f=l&&e[n(546)](rn,a[n(1361)][n(1003)],e.tfzuN,"1"),x=l&&e[n(403)](rn,a[n(1361)][n(1003)],n(1168)+"er_is_ack","1"),w=x?e[n(595)](rr,a.message.headers,e[n(1664)])?.[n(992)](",").filter(Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:f,isAckCleanupMessage:x,ackMsgIds:w}}async function fd(){let a=t;return this[a(462)+a(1225)]||(this[a(462)+"ger"]=new Gp),this[a(462)+a(1225)][a(1649)]||await this[a(462)+"ger"][a(832)](),this["_QoSMana"+a(1225)]}async function Hp(a,n){let s=t,{enableAutoAck:l}=this[s(1674)],f=rn(a[s(1361)][s(1003)],s(771),"1"),x=e[s(546)](rn,a[s(1361)][s(1003)],e[s(273)],"1"),w=xa[s(1290)](this,a);if(e[s(1423)](l,f)){let{SeqID:b,LogID:g,service:C,LogIDNew:O,method:F}=a[s(1361)];this[s(384)]({SeqID:b,LogID:g,LogIDNew:O,service:C,method:F,headers:[{key:s(988),value:"1"},{key:e[s(1454)],value:O||""},{key:e[s(927)],value:"0"}]})}x&&!w[s(682)]&&this[s(1479)+s(1539)+s(976)](a),e[s(1247)](n)}async function qp(a,n){let s=t;this[s(692)](e[s(1258)],a[s(1361)]),e[s(1247)](n)}async function jp(a,n){let s=t,l=e[s(1488)](en,await dd(a.data));try{if(e[s(632)](l[s(427)],Uint8Array)){let f=e[s(632)](this[s(1674)][s(389)+"ncoding"],Object)?{force:!!this[s(1674)][s(389)+"ncoding"][s(429)],encoding:this[s(1674)][s(389)+s(1250)][s(336)]?this[s(1674)].payloadEncoding[s(336)][s(265)](/\s/g,"")[s(1394)+s(1443)]():""}:{force:!1,encoding:this._options[s(389)+s(1250)]?this[s(1674)][s(389)+s(1250)][s(265)](/\s/g,"")[s(1394)+s(1443)]():""},x=l.payloadEncoding?l[s(389)+s(1250)][s(265)](/\s/g,"")[s(1394)+s(1443)]():"",w=e[s(665)](this[s(1674)][s(1169)+s(445)],Object)?{force:!!this[s(1674)][s(1169)+"ype"][s(429)],type:this[s(1674)].payloadType[s(1029)]?this[s(1674)]["payloadT"+s(445)][s(1029)][s(265)](/\s/g,"")["toLowerC"+s(1443)]():""}:{force:!1,type:this[s(1674)][s(1169)+s(445)]?this[s(1674)][s(1169)+s(445)][s(265)](/\s/g,"")["toLowerC"+s(1443)]():""},b=l.payloadType?l[s(1169)+s(445)][s(265)](/\s/g,"")[s(1394)+s(1443)]():"",g=w.force?w[s(1029)]:b||w[s(1029)],C=f[s(429)]?f[s(336)]:x||f[s(336)],O=[s(1759)+s(466)+"et=utf-8",e[s(1274)],e[s(1289)],e.nTXxR],F=[s(1402)+"e",s(1181)];this[s(1674)]["enableTr"+s(239)+"extPayload"]&&O[s(415)](g)&&(!C||F[s(415)](C))?l.textPayload=e[s(403)](ld,l[s(427)],0,l.payload[s(1768)+"th"]):l[s(1407)+s(261)]=""}else l[s(1407)+s(261)]=""}catch(f){l[s(1407)+"oad"]="",console.log(f)}a.message=l,n()}function Wp(a,n,s){let l=t,f={ncDph:e[l(1142)],KmQKD:e[l(1148)],zrTWS:e[l(1161)],MmqKH:e[l(1096)],bKIeS:e[l(1185)],NRtQZ:function(C,O){return e[l(784)](C,O)},BzjYR:function(C,O){return e[l(492)](C,O)},WcJhS:function(C,O){return e[l(1488)](C,O)},smZRQ:function(C,O){return e.lWNOE(C,O)},WBVJx:function(C,O){return C&O},uOJKK:function(C,O){return e[l(347)](C,O)}},x=e[l(772)](s,8192),w=x>>>1,b=null,g=x;return function(C){let O=l;if(f[O(363)]===f.bKIeS)this._isBrowser&&_0x3b99fd["removeEv"+O(1414)+O(1643)](f[O(396)],this[O(284)+"nLine"]),this._isBrowser&&_0x48b89a[O(637)+"entListener"](O(368),this[O(284)+"ffLine"]),this[O(980)+"er"]&&_0x37c27[O(637)+O(1414)+O(1643)](f[O(884)],this[O(619)+O(725)]),this._isBrowser&&_0x5d24da[O(637)+"entListener"](f.zrTWS,this[O(619)+"ageShow"]);else{if(f[O(1425)](C,1)||f[O(1025)](C,w))return f[O(761)](a,C);f[O(1025)](f[O(1700)](g,C),x)&&(b=a(x),g=0);let F=n.call(b,g,g+=C);return f[O(506)](7,g)&&(g=f[O(517)](7,g)+1),F}}}let Kp=4294967295;function $p(a,n,s){let l=t;if(e.whkhU(e[l(751)],"lgFte"))return RangeError(e.nvsep(e[l(331)](e[l(561)](e[l(833)](l(399)+"t of ran"+l(1616),a),e[l(854)]),n||1),e[l(1336)])+s);{let f=this[l(1281)].getItem(this[l(468)]),x=_0x220936.parse(e[l(1553)](f,"{}"));return x[_0x5c88f8||_0x2c4130[this[l(1667)]]]=_0x3dae19,this._qosDB[l(720)](this[l(468)],_0x19b910[l(1126)+"y"](x)),_0x2360cd||_0x4d8441[this[l(1667)]]}}function Vp(a,n,s){let l=t;if(s>Kp)throw new Error(l(786)+"too large");let f=3;for(;f>=0;){let x=e[l(277)](255,s);e.vtBCb(ga,x,a,n+f),s>>>=8,f--}return e[l(386)](n,4)}function Jp(a,n){let s=t;if(e.fptcF(e[s(1037)],e[s(527)]))return this._qosDB[s(958)]();{let l=0,f=n,x=n+4;for(;e.WGwfL(f,x);){let{value:w,offset:b}=e.jAsfz(pa,a,f);f=b,l=e[s(1597)](e.LYbVB(l,8),0),l+=w}return{value:l,offset:x}}}function Zp(a,n,s){let l=t;return a?a[l(421)]<40?e[l(1419)](e[l(294)](fa,a,n,s),s):n[l(1747)+"e"]?e.twiTh(n[l(1747)+"e"](a,s),s):n.write?e[l(816)](n[l(1130)](a,s),s):e.wccxf(e[l(705)](fa,a,n,s),s):s}function Yp(a,n){let s=t,l=new fe(e[s(1614)](e[s(1109)](e[s(497)](e[s(612)](a[n+4],24),a[e[s(1295)](n,5)]<<16),e[s(718)](a[e[s(248)](n,6)],8)),a[e.ILycw(n,7)]),e.LYbVB(a[n+0],24)|a[n+1]<<16|e[s(1145)](a[n+2],8)|a[e[s(652)](n,3)],!0);return n+=8,{value:l,offset:e[s(1764)](n,8)}}function Xp(a,n,s){let l=t,f=a.low,x=a[l(353)];return n[s]=e[l(882)](x,24),n[s+1]=e[l(747)](e.pbigq(x,16),255),n[e[l(721)](s,2)]=x>>>8&255,n[e[l(1243)](s,3)]=e[l(1639)](255,x),n[e.zNKpP(s,4)]=f>>>24,n[e[l(1039)](s,5)]=e[l(1464)](f>>>16,255),n[e[l(1755)](s,6)]=f>>>8&255,n[s+7]=e[l(236)](255,f),s+=8,s}function pa(a,n){let s=t;return a[s(1536)+"8"]?{value:a[s(1536)+"8"](n),offset:e[s(1157)](n,1)}:{value:255&a[n],offset:e[s(1296)](n,1)}}function ga(a,n,s){return n[t(442)+"t8"]?n.writeUint8(a,s):n[s]=255&a,e.QojKs(s,1)}let Qp=function(a){let n=t;if(e[n(639)](e[n(906)],e[n(1515)]))return new Uint8Array(a);e[n(828)](_0x2380bd,65536)?_0x35dec1[_0x19f854++]=e[n(745)](e[n(1092)](_0x890396,12),15)|224:(_0x1d39a2[_0x1e2494++]=e[n(1748)](e.PuDwe(_0x39020b>>18,7),240),_0x10c11d[_0x470186++]=e.xPGlN(e[n(925)](e[n(545)](_0x448ce1,12),63),128)),_0x2a2ba5[_0x16f26e++]=e[n(1614)](e[n(1303)](e[n(1092)](_0x246a05,6),63),128)},eg=e[t(1201)](e[t(501)],typeof Buffer)?Buffer[t(1517)+t(1221)]:e[t(1044)](Wp,Qp,Uint8Array[t(1621)+"e"][t(1758)]),tg=16,ma=32;function ng(a){let n=t,s=0,l={};for(let f=0;e[n(784)](f,a[n(421)]);f++)l[a[f]["cursor_n"+n(392)]]=e[n(1488)](cd,a[f]["cursor_n"+n(392)]),s+=e[n(1249)](14,l[a[f][n(918)+n(392)]]);return[s,l]}function hd(a,n,s){let l=t,f={aLQVq:e[l(1138)],vOTgh:function(C,O,F,j){return e[l(546)](C,O,F,j)},fbVeh:e[l(1472)],IOxWw:e[l(1703)],VTkIs:e.feUZX,aFtuL:e[l(963)],AjLSP:l(418)},[x,w]=e.eXuWP(ng,a),b=e.viTJw(eg,x),g=0;return a.forEach(C=>{let O=l,F=f[O(447)][O(992)]("|"),j=0;for(;;){switch(F[j++]){case"0":g=Vp(b,g,C[O(461)]||0);continue;case"1":g=f[O(1001)](Xp,fe[O(435)+"er"](C[O(1207)]||n),b,g);continue;case"2":console[O(1282)]("cursor.service",C,C[O(461)]);continue;case"3":console[O(1282)](f[O(404)],g);continue;case"4":g=ga(w[C.cursor_name],b,g);continue;case"5":g=Zp(C[O(918)+O(392)],b,g);continue;case"6":console.log(f[O(417)],g);continue;case"7":console[O(1282)](f[O(313)],g);continue;case"8":g=f[O(1001)](ga,0,b,g);continue;case"9":console[O(1282)](f[O(1238)],g);continue;case"10":console[O(1282)](f.AjLSP,g);continue}break}}),{frameType:ma,headers:[{key:e[l(340)],value:s}],payload:b}}function rg(a){let n=t,s=0,l=[];for(;s<a[n(1768)+"th"];){let{offset:f}=e[n(1210)](pa,a,s);s=f;let x={cursor_name:"",cursor:0,service:0},{value:w,offset:b}=Jp(a,s);x[n(461)]=w,s=b;let{value:g,offset:C}=e[n(245)](pa,a,s);s=C,x[n(918)+n(392)]=ld(a,s,e[n(1328)](s,g)),s+=g;let{value:O,offset:F}=e[n(1632)](Yp,a,s);x.cursor=O[n(1506)](),s=F,l[n(710)](x)}return l}function ig(){let a=t;return{frameType:ma,headers:[{key:"cursor_f"+a(1113),value:e[a(426)]}],payload:void 0}}class sg{constructor(n,s,l){let f=t;this["_cursorN"+f(646)]=n,this._cursorFileName=s,this[f(758)+f(1519)]=l,this[f(1281)]=ud(this["_cursorN"+f(646)],f(918)+f(392))}async[t(832)](){await this[t(1281)].openDB()}async getCursors(){let n=t,s={RUGBV:function(l,f){return e[U(947)](l,f)}};if(e[n(290)](e[n(924)],e[n(924)])){if(!this[n(1281)][n(1649)])return;let l=this[n(758)+"Strategy"],f=await this[n(1281)][n(342)]();switch(console[n(1282)](e[n(903)],f),l){case e[n(1149)]:return f&&f[n(421)]?e[n(546)](hd,f,0,this[n(1292)+n(520)]):void 0;case e[n(881)]:return;case n(1487):return f&&f[n(421)]?e[n(1701)](hd,f,0,this[n(1292)+n(520)]):ig()}}else{let l=new _0x539797(YxVqTN[n(267)](2,_0x55ce28));l[n(693)](_0x19f56c),_0x1b9722[n(644)]=l}}async[t(693)](n,s,l){let f=t;return console[f(1282)](e[f(1380)],n,s,l),this[f(1281)][f(693)]({cursor_name:n,cursor:s,service:l})}async[t(1440)+"rs"](n){let s=t,l=e[s(731)](rg,n);for(let f of l)console[s(1282)]("setcursor",l),await this[s(1281)][s(693)](f)}async[t(502)](n){let s=t;if(e[s(684)](e[s(299)],"kUTTw"))return(await this._qosDB[s(502)](n))?.[s(1207)];{let l={Oygwy:function(x,w){return e.DFWpN(x,w)}},f=_0x3d9b79[s(1537)+s(734)](e[s(1192)]);_0x5e5ed0[s(831)+s(1266)]=x=>{let w=s;_0x521b94.body[w(1483)+"ild"](f),_0x4ebda5[w(831)+w(1266)]=void 0,l.Oygwy(_0x43a9f6,x&&x[w(1771)]||w(1388)+w(490))},f[s(1029)]=e[s(752)],f[s(678)]=e.vBwqq(_0x3f7be7[s(265)](/^ws/,e[s(973)]),e[s(1501)]);try{_0x5d6edf.body[s(1286)+"ild"](f)}catch{_0xeb1c06[s(1020)][s(1483)+s(1496)](f)}}}async[t(1598)](){await this[t(1281)].closeDB()}["updateCu"+t(491)+t(1084)](n){this._cursorFileName=n}get[t(1649)](){let n=t;return this._qosDB[n(1649)]}}let og=e[t(913)];async function xd(a){let n=t;if(!this[n(1674)][n(1492)+"S"])return null;let{aID:s,fpID:l,messageStrategy:f}=this[n(1674)],x=e[n(681)](a,og);try{return this[n(494)+n(1337)]?a&&this["_cursorM"+n(1337)][n(401)+"rsorFile"+n(1084)](a):this["_cursorM"+n(1337)]=new sg(l+"_"+s+"_"+x,x,f),this[n(494)+n(1337)].isReady||await this["_cursorM"+n(1337)].openDB(),this[n(494)+"anager"]}catch{return null}}async function ag(a,n){let s=t,l=e.CSagP(rn,a[s(1361)][s(1003)],"code","-1"),f=rn(a[s(1361)][s(1003)],"is_ack","1"),x=e[s(1586)](rr,a[s(1361)].headers,e[s(1720)]),w=e[s(1686)](Number,e[s(352)](rr,a[s(1361)][s(1003)],e[s(713)]))||0,b=xa.call(this,a),g=rn(a[s(1361)][s(1003)],e[s(272)],"2"),C=e[s(456)](rr,a[s(1361)][s(1003)],e[s(503)]),O=e[s(532)](Number,e[s(683)](rr,a[s(1361)][s(1003)],"x-msg-cu"+s(1476)+"ue"));if(b[s(682)])return e[s(529)](n);let F=b[s(1330)+s(1640)]?await fd.call(this):null;if(e[s(492)](a[s(1361)][s(461)],0)&&f&&!l||e[s(610)](a.message.service,0)){if(x&&b[s(1330)+s(1640)]&&F)return!!!await F[s(502)](x)&&(e[s(624)](e[s(1489)],e.SXytW)?_0x2a9649[s(693)](_0x3ee32b,_0xe2182a):(this[s(1479)+s(1278)+s(687)](a),await F[s(693)](x,e[s(1243)](Date.now(),w)))),e.khLSI(n);if(g){let j=await xd.call(this);if(!j)return e[s(791)](e[s(1415)],e[s(1415)])?(this[s(1479)+"hMessage"+s(687)](a),e[s(474)](n)):new _0x1baf06(_0x25d890,_0xedb7f1,_0x501530);let W=await j[s(502)](C)??-1;if(e.Poypg(W,O))this[s(1479)+s(1278)+"Event"](a),j[s(693)](C,O,a.message[s(461)]);else throw new Error(s(355)+" message cursor "+O+(s(1377)+"than local cursor ")+W);return e[s(1211)](n)}return this[s(1479)+"hMessage"+s(687)](a),e[s(1714)](n)}}async function cg(a,n){let s=t,l=xa[s(1290)](this,a);if(!l[s(1330)+"sage"])return e[s(1247)](n);let f=await fd.call(this);if(l[s(834)+s(1698)+"age"]&&l[s(537)+"s"][s(421)])for(let x of l.ackMsgIds)await f.del(x);e[s(702)](n)}async function lg(a,n){let s=t;if(e[s(1223)](e[s(1559)],e.Waezj))return _0x749541[_0x5f32dc]=_0x32b16b,!0;{let l=a[s(1361)][s(1317)+"e"]===tg,f=e.IWFwY(a.message.frameType,ma);if(e[s(1760)](!l,!f))return n();let x=e[s(1015)](rr,a[s(1361)][s(1003)],e[s(340)]);if(!x)return e[s(474)](n);let w=await xd.call(this,x);if(!w)return e[s(1477)](n);if(l){let b=await w[s(1128)+"rs"](),g={frameType:b?.["frameType"],SeqID:fe.fromNumber(this[s(1339)]++),LogID:fe[s(435)+"er"](this[s(1674)][s(1326)+s(250)]()),service:9e3,method:5,headers:b?.[s(1003)],payload:b?.[s(427)]},C=e[s(1052)](v,g);this[s(942)]&&this[s(942)][s(864)+"te"]&&this[s(942)].send(C)}if(f){let b=a[s(1361)][s(427)];b&&w[s(1440)+"rs"](b)}}}let dg=async function(a,n){let s=t;this._isInit=!1,e[s(690)](clearTimeout,this[s(512)+"ionTimeoutId"]),e[s(704)](n)},ug=async function(a,n){let s=t;if(!this[s(942)]||e.Stcnw(this._ws[s(864)+"te"],this[s(1350)]))return e[s(702)](n);let{pingInterval:l}=this._options;this["_endpoin"+s(1034)]?.[s(334)+s(1467)+s(788)]();for(let x=0;x<this[s(758)+s(1644)][s(421)];x++){let w=this[s(758)+"Queue"][x];if(this[s(942)].readyState===this[s(1350)]&&w!==null)this[s(942)]&&this[s(942)].send(w),this["_message"+s(1644)][x]=null;else break}this[s(758)+s(1644)]=this._messageQueue[s(875)](x=>!!x),this[s(1382)+s(552)+"Id"]=e[s(1444)](setTimeout,()=>this[s(686)](),l),this[s(1479)+"hOpenEvent"](a),this[s(980)+"er"]&&this._ws&&(this[s(942)][s(606)+"pe"]=this["_binaryT"+s(445)]);let f=this["_endpoin"+s(1034)]?.["getCurre"+s(1753)+"nt"]();this[s(692)]("open "+f+s(940)),n()},fg=async function(a,n){let s=t;if(e.EGBdz(e[s(1751)],"rwqbj")){let{type:l}=_0x149059;this.emit(l,_0x4f3fed)}else{let l=this[s(792)+"tManager"]?.[s(1346)+s(1753)+"nt"]();this._debug(s(1608)+l),e[s(1477)](n)}};class hg extends ua{constructor(n){let s=t,l={mDjHL:function(b,g,C,O){return e.KSHAk(b,g,C,O)},ElYLb:function(b,g,C){return e[U(352)](b,g,C)},SOywS:"error",oungW:function(b,g){return e.dAENu(b,g)},JzjQK:s(312),QJYhO:function(b,g){return b===g},WUEFf:e[s(750)],QtfPp:e[s(1693)],BPUvO:function(b,g,C){return e.TQuSx(b,g,C)},CkmIY:function(b,g,C){return e[s(1387)](b,g,C)},baHTB:function(b,g){return e[s(688)](b,g)},ROcSy:"idb",JlMjX:function(b,g){return e.rNWWD(b,g)},Wvsvi:function(b,g,C,O){return e[s(341)](b,g,C,O)},uTOKU:function(b,g){return e[s(252)](b,g)},LPzGS:function(b,g,C){return e[s(1057)](b,g,C)},DhZfa:e[s(263)],bwBVG:function(b,g){return b!==g},OIOxC:e[s(1283)],SLwaz:s(835),CFYPo:function(b,g){return e[s(587)](b,g)},cYwyb:function(b,g){return b(g)},TTDiZ:function(b,g){return e[s(899)](b,g)},rHqqC:e[s(1516)],unFtG:function(b,g,C){return b(g,C)}};super(),this[s(528)+s(585)+"line"]=!0,this[s(980)+"er"]=nr,this[s(1348)]=Cp,this[s(1035)+"T"]=Rn,this[s(551)+"X"]=Yr,this[s(1369)+"r"]=Xr,this[s(758)+s(1644)]=[],this[s(792)+s(1034)]=null,this[s(1435)+"osed"]=!1,this[s(1053)+"ype"]=e[s(1242)],this[s(512)+"Lock"]=!1,this[s(512)+s(767)+s(670)]=null,this[s(1385)+"ctTimeou"+s(941)]=null,this[s(1382)+s(552)+"Id"]=null,this[s(1339)]=0,this[s(1656)]=!1,this[s(599)]="",this[s(462)+"ger"]=null,this[s(494)+s(1337)]=null,this[s(1056)+s(961)]=null,this._protocols="pbbp2",this[s(1140)]=3,this[s(514)+"NG"]=0,this[s(1350)]=1,this[s(556)]=2,this[s(1705)]=b=>{let g=s;try{l[g(1306)](ad,this,b,[dg,ug,fg])}catch(C){let O=l[g(1412)](ct,l[g(1074)],{message:C[g(1361)],code:nn.OPEN_ERROR,error:C});this[g(1479)+g(857)+"ent"](O)}},this._onMessage=async b=>{let g=s;if(l[g(1176)]("qALHr",g(430)))return new _0x4da67c(_0x50fcb1,{data:_0x42d97e,message:_0x1dda7b});{let{pingInterval:C,pingFrequency:O}=this[g(1674)];if((b[g(783)]==="hi"&&l[g(782)]===O||l.QJYhO(l[g(1108)],O))&&(this[g(1101)+g(1535)](),this[g(837)](g(1574)+g(398)+"s",l[g(1173)]),this[g(1382)+g(552)+"Id"]=l.BPUvO(setTimeout,this[g(686)][g(608)](this),C)),b[g(783)]==="hi")return;try{ad(this,b,[jp,Hp,cg,lg,ag,qp])}catch(F){let j=l[g(1412)](ct,l[g(1074)],{message:F[g(1361)],code:nn["MESSAGE_"+g(793)],error:F});this[g(1479)+"hErrorEv"+g(1110)](j)}}},this[s(1579)]=b=>{let g=s,C=this[g(792)+g(1034)]?.[g(997)+"chMaxTries"](),O=this[g(792)+g(1034)]?.[g(1346)+g(1753)+"nt"]();if(C&&!b[g(1361)]){let F=g(1653)+O+" fail, max retries reached";this["_dispatc"+g(857)+g(1110)](l[g(1338)](ct,l[g(1074)],{message:F,code:nn[g(330)+g(1102)+"R"],error:b}));return}this[g(942)]&&l[g(1226)](this._ws[g(864)+"te"],this[g(1350)])&&this[g(280)+g(818)](),this[g(1479)+g(857)+"ent"](ct("error",{message:b[g(1361)],code:nn[g(242)+g(1271)],error:b}))},this._onClose=async b=>{let g=s,C={doBeS:l[g(934)],gWvsh:function(F,j){return l[g(493)](F,j)},gohpe:function(F,j,W,le){return l[g(344)](F,j,W,le)},GcdMs:function(F,j){return l[g(241)](F,j)}};this["_clearTi"+g(1234)](),this[g(1101)+g(1535)](),this[g(370)+g(1585)+"rs"](),this[g(942)]=null,this[g(512)+"Lock"]=!1;let O=this[g(792)+g(1034)]?.[g(997)+g(1433)+"es"]();if(!O&&this[g(452)+"orOnline"]()&&!this[g(1435)+g(1544)]){let F=this[g(792)+"tManager"]?.[g(1346)+g(1753)+"nt"](),j=this[g(1674)][g(1049)+g(1356)+g(1675)](b[g(1058)],b[g(490)]);this["_dispatc"+g(1122)+"ent"](l.LPzGS(pt,l[g(1704)],{code:1006,reason:b[g(490)]||g(1465)+"ng faile"+g(253)+g(1116)+g(1449)+g(572)+F,willReconnect:j})),j&&this[g(512)]();return}if(b[g(1058)]!==1e3&&this["_readyCl"+g(1544)])if(l[g(469)](l.OIOxC,g(306))){this[g(1479)+g(1122)+g(1110)](pt(l.DhZfa,{code:1e3,reason:l[g(1209)]})),this["_endpoin"+g(1034)]?.[g(334)+g(1467)+"fig"](),this[g(1056)+g(961)]?.["resetCou"+g(1214)]();return}else return _0x4be8ec||(_0x111be6=_0x3e4809.resolve()[g(1125)](_0x592988[g(608)](_0x1a4017,WhBIyx[g(1180)]))),_0x2412e5;if(l[g(1017)](1e3,b[g(1058)])&&O){let F=this[g(792)+"tManager"]?.["getCurre"+g(1753)+"nt"](),j=b.reason;j||(j=await l[g(1723)](Mp,this._url)),j=g(1465)+g(596)+"d, "+j+(g(1319)+g(1120))+F+(g(1451)+g(807)+g(789)),this[g(1479)+g(1122)+"ent"](pt(l[g(1704)],{code:b[g(1058)],reason:j}));let W=g(1653)+F+(g(1371)+g(815)+g(1364)+"ed");this[g(1479)+"hErrorEv"+g(1110)](l[g(629)](ct,g(385),{message:W,code:nn["MAX_RETR"+g(1102)+"R"]})),this[g(792)+g(1034)]?.[g(334)+g(1467)+"fig"](),this[g(1056)+g(961)]?.[g(1645)+g(1214)]();return}if(l.TTDiZ(1e3,b[g(1058)])&&!b[g(490)])if(l[g(1017)](l[g(1438)],l[g(1438)])){if(WhBIyx[g(1730)](g(323),typeof _0x325da6)){let F=new _0x2045f3(_0x2610ce(_0xfc86b3));return WhBIyx.gohpe(_0x3b7493,_0xa69f42,F,0),F}return WhBIyx.GcdMs(_0x2a1a17,_0x5a2152)?new _0x110338(_0x49aed4):new _0x5004aa(_0x51411b[g(1746)],_0x11d267.byteOffset,_0x37bcc7.byteLength)}else{let F=this[g(792)+"tManager"]?.[g(1346)+"ntEndpoint"]();this[g(1479)+"hCloseEv"+g(1110)](l.unFtG(pt,g(1073),{code:b[g(1058)],reason:g(1465)+g(596)+g(253)+g(1116)+g(1449)+g(572)+F})),this["_endpoin"+g(1034)]?.[g(334)+g(1467)+"fig"](),this["_pingLos"+g(961)]?.["resetCou"+g(1214)]();return}this[g(1479)+g(1122)+g(1110)](b),this[g(792)+g(1034)]?.[g(334)+"pointConfig"](),this["_pingLos"+g(961)]?.resetCounter()},this[s(496)]=null,this[s(1070)]=null,this[s(636)+"e"]=null,this.onopen=null,this[s(1345)+s(1310)]=null,this[s(1552)+s(328)]=null,this[s(737)+s(329)+s(1548)+"ct"]=null,this._handleOnLine=this[s(284)+s(1654)][s(608)](this),this[s(284)+s(869)]=this[s(284)+s(869)].bind(this),this._handlePageHide=this["_handleP"+s(725)][s(608)](this),this[s(619)+s(1729)]=this[s(619)+s(1729)][s(608)](this),this[s(1674)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(750)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1213)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:x}=n,w=Array[s(257)](f)?f:e[s(1504)](e[s(804)],typeof f)?[f]:[];if(!w||e.Dkqym(0,w[s(421)]))throw new Error(e[s(495)]);if(!Dp(x))throw new Error(s(865)+s(1680)+"s params"+s(1381)+s(371)+s(1360)+s(819)+s(1591));Object[s(1087)](this[s(1674)],n),this[s(792)+"tManager"]=new od(w,this[s(1674)][s(867)+"es"]),this[s(1056)+"sCounter"]=new Np(this[s(1674)][s(878)+s(483)]),this[s(1674)][s(256)+s(939)]&&(this._isInit=!0,this[s(512)]()),this[s(1674)]["listenNe"+s(576)+"nged"]&&(this._isMiniTT||this[s(551)+"X"]?this[s(1452)+s(1078)+s(510)]():this[s(980)+"er"]&&this[s(1575)+"balEvent"+s(274)]())}[t(284)+t(1654)](){let n=t;this[n(1674)][n(395)+n(817)+"nect"]||this[n(1435)+n(1544)]||this[n(1602)+"econnect"]()}[t(284)+t(869)](){let n=t;this[n(1404)+n(1097)+"t"]();let s=da(n(1049)+"t",{message:e[n(524)]});this[n(737)+n(329)+n(1548)+"ct"]&&this[n(737)+n(329)+"yReconnect"](s)}[t(1575)+t(1687)+t(274)](){let n=t;this[n(980)+"er"]&&window[n(1634)+n(274)](e.qmnhL,this[n(284)+n(1654)]),this[n(980)+"er"]&&window[n(1634)+n(274)](e[n(620)],this[n(284)+n(869)]),this[n(980)+"er"]&&window.addEventListener(e[n(1148)],this[n(619)+n(725)]),this[n(980)+"er"]&&window[n(1634)+n(274)](n(886),this[n(619)+n(1729)])}[t(1322)+t(1687)+t(274)](){let n=t;this[n(980)+"er"]&&window[n(637)+"entListe"+n(1643)](e.qmnhL,this[n(284)+"nLine"]),this[n(980)+"er"]&&window["removeEv"+n(1414)+n(1643)](e[n(620)],this[n(284)+n(869)]),this._isBrowser&&window["removeEventListe"+n(1643)](n(1374),this[n(619)+n(725)]),this[n(980)+"er"]&&window[n(637)+"entListe"+n(1643)](e[n(1161)],this[n(619)+n(1729)])}[t(619)+t(725)](n){let s=t,l={ZmRpS:e[s(1105)],HPISc:s(1073),csTzY:e[s(362)]};if(!n[s(540)+"d"])if(e.LWhMm(e[s(1618)],e.qtrUT)){if(!this[s(942)])return;this._ws["removeEv"+s(1414)+"ner"](l[s(1522)],this[s(1705)]),this[s(942)][s(637)+s(1414)+s(1643)](l[s(350)],this[s(1600)]),this[s(942)][s(637)+s(1414)+s(1643)](l.csTzY,this._onMessage),this[s(942)][s(637)+s(1414)+s(1643)]("error",this[s(1579)])}else this[s(980)+"er"]&&window[s(637)+s(1414)+s(1643)](e.mvwGB,this[s(619)+s(725)]),this[s(980)+"er"]&&window["removeEv"+s(1414)+s(1643)](e.VRNyF,this[s(619)+s(1729)]),this[s(1073)]();this[s(980)+"er"]&&window[s(637)+s(1414)+s(1643)](e[s(1142)],this[s(284)+s(1654)]),this[s(980)+"er"]&&window[s(637)+"entListe"+s(1643)](e[s(620)],this[s(284)+s(869)])}["_handleP"+t(1729)](n){let s=t,l={YbHmC:function(f,x){return f<<x},XXxuD:function(f,x){return e[U(1081)](f,x)},Mwtsx:function(f,x){return f<x},GidiN:function(f,x){return e[U(717)](f,x)}};n[s(540)+"d"]&&(e.TJMgB(e[s(1288)],s(1139))?(this[s(452)+s(736)]()&&(!this[s(942)]||this[s(942)].readyState!==this.OPEN||e[s(1042)](this[s(942)].readyState,this[s(514)+"NG"]))&&this[s(284)+s(1654)](),this[s(980)+"er"]&&window[s(1634)+s(274)](e[s(1142)],this["_handleO"+s(1654)]),this[s(980)+"er"]&&window[s(1634)+s(274)]("offline",this[s(284)+"ffLine"])):(_0x116107=TkXAII[s(444)](TkXAII[s(742)](31,_0x436078),6)|63&_0x86344,TkXAII[s(953)](_0x179808,128)?_0x18a84f+=_0x239dc6:(_0x2e29ae+=TkXAII[s(397)](_0xf0b43e,_0x52f3ee),_0x5ba053++)))}async[t(970)+t(1400)](n){let s=t,{fpID:l,deviceID:f,bddID:x,ttwID:w,accessKey:b,aID:g,customParams:C={},enableAutoAck:O,enableQoS:F,QoSLevel:j,env:W}=this[s(1674)],le,Ke,rt;this[s(980)+"er"]||this[s(551)+"X"]||this[s(1035)+"T"]?(le=location&&e[s(1538)](e[s(558)],location[s(1294)])?e[s(1256)]:e[s(1372)],Ke=n.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),rt=/^wss(.*:\/\/)/[s(1778)](n)?n:""+le+Ke):(le=e[s(1256)],Ke=n[s(265)](/(^http)((?:[s]*:\/\/))/,""),rt=/(^ws)((?:[s]*:\/\/))/[s(1778)](Ke)?Ke:""+le+Ke);let gt=x?e[s(1745)]:w?e[s(547)]:e.PikpF,pd=x||w||f;if(e[s(1396)](!pd,!gt))throw new Error(e[s(379)]);let xg=e[s(443)](e[s(454)],typeof C)?await e.khLSI(C):C,pg=W?Lp(W[s(849)],W.xTTEnv):{},wa=Object.assign({device_platform:e[s(1144)],version_code:s(1416)+"0",access_key:b,fpid:l,aid:g,[gt]:pd,xsack:O?1:0,xaack:O?1:0,xsqos:F?1:0,qos_level:F?j:void 0,qos_sdk_version:2,...pg},xg),gg=Object[s(1427)](wa)[s(1498)]((_a,ya)=>wa[ya]!==void 0?""+_a+(_a?"&":"?")+ya+"="+wa[ya]:_a,"");return rt+"/ws/v2"+gg}async[t(512)](){let n=t;if(!(this[n(512)+n(611)]||this[n(1435)+n(1544)])){this["_connect"+n(611)]=!0;try{if(e[n(232)](e[n(605)],e[n(1208)]))return n(831)+"_"+this[n(1285)];{let s=this[n(792)+n(1034)]?.["checkCur"+n(1466)+n(872)+n(1481)+n(583)](),{timeoutInterval:l}=this._options;if(s){let x=this[n(792)+n(1034)]?.[n(1346)+n(1753)+"nt"](),w=this[n(792)+n(1034)]?.[n(1159)+n(1776)+n(1612)+n(1060)+n(900)](),b=this[n(792)+n(1034)]?.["getCurrentEndpoi"+n(271)+n(814)]();if(w){let g=n(1653)+x+(n(478)+n(1451)+n(807)+n(1638)+n(1069)+n(1186)+n(1041))+w+(n(1127)+"y"),C=e[n(438)](ct,e[n(967)],{message:g,code:nn[n(330)+"IES_ERROR"]});this[n(692)](g),this[n(1479)+n(857)+n(1110)](C),this[n(599)]=await this[n(970)+n(1400)](w),this[n(692)](n(1653)+w+" "+b+" times"),this["_removeW"+n(1585)+"rs"]()}else{let g=n(1653)+x+(n(478)+n(1451)+"tries re"+n(789));this[n(692)](g),this[n(1479)+n(857)+n(1110)](e.oLSTe(ct,e[n(967)],{message:g,code:nn.MAX_RETRIES_ERROR}));return}}else{let x=this[n(792)+n(1034)]?.[n(1346)+n(1753)+n(1742)+"ateCount"](),w=this[n(792)+n(1034)]?.["getCurre"+n(1753)+"ntTriesCount"]();this._url=await this[n(970)+n(1400)](e.ADhPR(x,"")),this[n(692)](n(1653)+x+" "+w+" times"),this[n(370)+n(1585)+"rs"]()}if(this[n(1656)])this[n(1656)]=!1;else{let x=e[n(1219)](da,n(1049)+"t",{message:e.YRyZR});this["onStartR"+n(1310)]&&this[n(1345)+n(1310)](x)}let f=this._endpointManager?.[n(1346)+"ntEndpoi"+n(271)+n(814)]()||0;f>1&&await this[n(633)](f-1),this[n(692)](n(1465)+"ng url: "+this._url+(n(1666)+n(293))+this[n(1367)+"ls"]),this[n(942)]=e[n(598)](Pp,{url:this[n(599)],protocols:[this[n(1367)+"ls"]],headers:this._options[n(1355)+n(1038)+"s"][n(631)+n(486)]},this[n(1674)].ws),(this[n(980)+"er"]||this[n(1369)+"r"])&&this._ws&&(this[n(942)][n(606)+"pe"]=this[n(1053)+"ype"]),this[n(1677)+n(345)](),this[n(512)+"ionTimeo"+n(670)]=e[n(523)](setTimeout,this[n(616)+"ut"][n(608)](this),l)}}catch(s){throw this["_connect"+n(611)]=!1,s}}}[t(1150)+t(1234)](){let n=t;e.lQmcI(clearTimeout,this[n(512)+n(767)+n(670)]),this[n(512)+n(767)+n(670)]=null}["_clearPi"+t(1535)](){let n=t;e[n(1411)](clearTimeout,this["_pingPon"+n(552)+"Id"]),e[n(1533)](clearTimeout,this[n(1385)+n(1625)+n(941)]),this[n(1382)+n(552)+"Id"]=null,this[n(1385)+n(1625)+n(941)]=null}[t(692)](...n){let s=t;this[s(1674)][s(1457)]&&console[s(1282)][s(411)](console,[e[s(1195)],...n])}[t(316)+t(292)+"e"](n){let s=t,l={VyHjk:e[s(967)],LRqeg:function(f,x,w){return e.enJBf(f,x,w)}};if(e[s(419)]!==e[s(419)])this[s(837)](PQCwfT[s(1732)],PQCwfT[s(880)](_0x391fbd,PQCwfT[s(1732)],{message:this[s(555)+s(333)+s(1469)](_0x4c3f2)}));else{let{initReconnectInterval:f,maxReconnectInterval:x,reconnectIntervalGrowFactor:w}=this[s(1674)],b=e[s(947)](f,Math[s(562)](w,e[s(812)](n,1)));return e[s(1541)](b,x)?x:b}}[t(686)](){let n=t;if(this[n(942)]&&this[n(942)][n(864)+"te"]===this.CONNECTING){this[n(1101)+n(1535)](),this["_pingPon"+n(552)+"Id"]=setTimeout(this[n(686)][n(608)](this),this._options[n(1750)+n(823)]);return}if(!this[n(942)]||e[n(1763)](this[n(942)][n(864)+"te"],this[n(1350)]))return void this[n(1602)+n(1310)]();this[n(942)]&&this[n(942)][n(584)]("hi"),this[n(1385)+n(1625)+n(941)]=e[n(428)](setTimeout,this[n(1602)+n(1310)+n(1463)][n(608)](this),this._options[n(1265)+n(914)+n(1399)])}[t(1602)+t(1310)+t(1463)](){let n=t;this[n(1056)+n(961)]?.[n(778)](),this[n(837)](e.UIMuu,n(897)),this[n(1056)+"sCounter"]?.["checkRea"+n(508)+"nt"]()?this["_handleR"+n(1310)]():this[n(686)]()}["_navigat"+t(736)](){let n=t;return this._isMiniTT||this[n(551)+"X"]?this[n(528)+"igatorOn"+n(1570)]:(this[n(980)+"er"]||this[n(1369)+"r"])&&this[n(1674)]["listenNe"+n(576)+n(1593)]?navigator.onLine:!0}[t(1602)+t(1310)](){let n=t;!this[n(452)+"orOnline"]()||this[n(1435)+"osed"]||(this[n(792)+n(1034)]?.["resetEnd"+n(1467)+n(788)](),this[n(1056)+n(961)]?.[n(1645)+n(1214)](),this._ws?this[n(280)+"ect"](1001,n(824)+n(645)+n(1049)+n(324)+n(1354),!0):this._connect())}["_onPageNetWorkCh"+t(510)](){let n=t,s={LVXiJ:function(l,f){return e.GTylg(l,f)},rUMog:e[n(1693)],AFoiW:e[n(518)],CriVs:e[n(663)],GoecV:function(l,f){return e[n(372)](l,f)},fRluT:function(l,f,x){return l(f,x)}};if(n(1137)!==e[n(488)]){let l={nJzPE:function(w,b){return s[n(1174)](w,b)},IULbQ:n(897),ObnpR:s.AFoiW,ChQdV:s[n(414)]};this._clearPingTimer(),this[n(1382)+"gTimeoutId"]=s[n(898)](_0xe3d5a0,this[n(686)].bind(this),this._options[n(1750)+n(823)]);let f=()=>{let w=n;s.LVXiJ(_0x212075,s[w(1626)]),this.off(s[w(1351)],f),this.off(s.CriVs,x)},x=()=>{let w=n;l[w(437)](_0x1794d2,l[w(1375)]),this.off(l[w(1088)],f),this[w(1781)](l[w(910)],x)};this.on("ping_onc"+n(398)+"s",f),this.on(s[n(414)],x),this[n(686)]()}else this._isMiniTT?tt[n(759)+n(1072)+n(1200)](({isConnected:l})=>{let f=n;this[f(528)+f(585)+f(1570)]=l,l?this[f(284)+"nLine"]():this[f(284)+f(869)]()}):this[n(551)+"X"]&&wx[n(759)+n(1072)+"hange"](({isConnected:l})=>{let f=n;this[f(528)+f(585)+f(1570)]=l,l?this[f(284)+"nLine"]():this[f(284)+f(869)]()})}[t(633)](n){let s={IWwHA:function(l,f,x){return e[U(1629)](l,f,x)}};return new Promise(l=>{let f=U;s.IWwHA(setTimeout,l,this[f(316)+"rvalValue"](n))})}[t(280)+t(818)](n=1e3,s="",l=!1){let f=t;this[f(942)]&&this[f(1404)+f(1097)+"t"](n,s,l)}[t(616)+"ut"](){let n=t,s=this[n(792)+n(1034)]?.[n(1346)+n(1753)+"nt"]();this._debug(n(1653)+s+n(478)),this[n(280)+n(818)](1001,n(1252)+" try rec"+n(594)+"g",!0)}_sendAck(n){let s=t,l=e[s(400)](zt,n);this._ws&&e[s(1118)](this[s(942)][s(864)+"te"],this[s(1350)])&&(this[s(942)]&&this[s(942)][s(584)](l),this[s(692)](e.ATjxz,n))}["_removeW"+t(1585)+"rs"](){let n=t;this[n(942)]&&(this._ws[n(637)+n(1414)+n(1643)](n(439),this[n(1705)]),this[n(942)][n(637)+n(1414)+"ner"](e[n(263)],this[n(1600)]),this[n(942)][n(637)+n(1414)+n(1643)](e[n(362)],this[n(522)+"ge"]),this[n(942)][n(637)+n(1414)+n(1643)](e[n(967)],this[n(1579)]))}[t(1677)+t(345)](){let n=t;this[n(942)]&&(this[n(942)][n(1634)+"Listener"](e[n(1105)],this._onOpen),this[n(942)]["addEvent"+n(274)](e[n(263)],this._onClose),this[n(942)].addEventListener(e.DSIzA,this._onMessage),this[n(942)][n(1634)+"Listener"](n(385),this[n(1579)]))}_wsInstanceClose(n=1e3,s=""){let l=t;try{this[l(942)]&&this[l(942)][l(1073)](n,s)}catch{}}["_destroy"+t(1097)+"t"](n=1e3,s="",l=!1){let f=t;if(this[f(1101)+"ngTimer"](),this._clearTimer(),this[f(370)+f(1585)+"rs"](),this[f(1253)+"nceClose"](1e3,s),this["_connect"+f(611)]=!1,l&&this[f(452)+"orOnline"]()&&!this[f(1435)+f(1544)]){if(this[f(792)+f(1034)]?.["checkRea"+f(1433)+"es"]()){let w=this[f(792)+f(1034)]?.[f(1346)+f(1753)+"nt"]();this[f(1479)+f(1122)+f(1110)](e[f(841)](pt,f(1073),{code:1006,reason:f(1653)+w+(f(478)+f(1451)+f(807)+f(789)),wasClean:!0}))}else if(e[f(1432)](e.GLsJM,"VuiKr")){let w=this[f(1674)]["reconnectInterce"+f(1675)](n,s);this[f(1479)+"hCloseEvent"](e[f(1066)](pt,e[f(263)],{code:n,reason:s,wasClean:!0,willReconnect:w})),w&&this[f(512)]()}else return;return}this._navigatorOnline()||this[f(1435)+f(1544)]?this["_dispatchCloseEv"+f(1110)](pt(e.uTSPV,{code:n,reason:e[f(1777)]})):this[f(1479)+f(1122)+"ent"](e[f(1267)](pt,e[f(263)],{code:1006,reason:f(824)+"ay, netw"+f(1196)+f(473)})),this._ws=null,this[f(792)+f(1034)]?.["resetEnd"+f(1467)+f(788)](),this[f(1056)+"sCounter"]?.[f(1645)+f(1214)]()}[t(1479)+"hOpenEvent"](n){let s=t;e.TgUFP(s(1767),e.gEVOv)?this[s(1281)]?.[s(716)](_0x2a83fe.message_id):(this[s(837)](e[s(1105)],n),this[s(1315)]&&this.onopen(n))}[t(1479)+"hMessage"+t(687)](n){let s=t;this[s(837)](e[s(362)],n),this.onmessage&&this[s(636)+"e"](n)}_dispatchAckMessageEvent(n){let s=t;this.emit(e[s(1179)],n),this["onReceiv"+s(328)]&&this[s(1552)+s(328)](n)}[t(1479)+t(857)+t(1110)](n){let s=t;this[s(837)](s(385),n),this[s(1070)]&&this[s(1070)](n)}[t(1479)+t(1122)+"ent"](n){let s=t;this[s(837)](e[s(263)],n),this[s(496)]&&this[s(496)](n)}get[t(606)+"pe"](){let n=t;return this[n(942)]?this[n(942)][n(606)+"pe"]:this[n(1053)+n(445)]}set binaryType(n){let s=t;this[s(1053)+s(445)]=n,this[s(942)]&&(this[s(942)].binaryType=n)}get retryCount(){let n=t;return this[n(792)+"tManager"]?.[n(1346)+n(1753)+"ntTriesC"+n(814)]()||0}get bufferedAmount(){let n=t;if(e[n(391)](e.MDljm,e[n(472)])){let s=this._messageQueue[n(1498)]((l,f)=>(l+=f&&f[n(1768)+"th"]||0,l),0);return e[n(1549)](s,this[n(942)]?this[n(942)]["buffered"+n(1273)]:0)}else FFsRtY[n(989)](FFsRtY.OWdXH,typeof _0x4a237f)&&_0xf5c49d[n(860)+n(1683)]&&_0x46311e[n(911)+n(700)](_0x231220,_0x3dd32c[n(860)+"Tag"],{value:FFsRtY.ZlLWP}),_0x30fa82[n(911)+n(700)](_0xeca263,FFsRtY[n(1063)],{value:!0})}get[t(278)+"ns"](){let n=t;return this[n(942)]?this[n(942)][n(278)+"ns"]:""}get protocol(){return this[t(942)]?this._ws.protocol:""}get[t(864)+"te"](){let n=t;return this[n(942)]?this[n(942)][n(864)+"te"]:this._options[n(256)+"cOpen"]?this.CONNECTING:this[n(1140)]}get[t(297)](){let n=t;return this[n(942)]?this._ws.url:this[n(599)]}close(n=1e3,s){let l=t,f=e[l(1555)][l(992)]("|"),x=0;for(;;){switch(f[x++]){case"0":this["_readyCl"+l(1544)]=!0;continue;case"1":if(e[l(1206)](this[l(942)].readyState,this[l(1140)])||e[l(1114)](this[l(942)][l(864)+"te"],this.CLOSING))return void this[l(692)](e[l(964)]);continue;case"2":this[l(1150)+"mer"]();continue;case"3":this[l(1404)+"WebSocket"](n,s);continue;case"4":this[l(1322)+l(1687)+l(274)]();continue;case"5":this[l(1101)+l(1535)]();continue;case"6":this._QoSManager?.[l(1598)]();continue;case"7":if(!this[l(942)])return void this[l(692)](e[l(1596)]);continue}break}}async[t(584)](n,s){let l=t,f={ZjGew:function(x,w){return e.kOvru(x,w)}};if(e[l(791)](l(354),e[l(668)])){if(e.WtyFa(null,n))throw new Error(e[l(1244)]);e[l(1268)](e.rvdDs,typeof n)&&(n=JSON[l(1126)+"y"](n)),e[l(989)](e[l(804)],typeof n)&&!e.PRkzV(n,ArrayBuffer)&&!(n[l(1746)]&&e.LdNbF(n[l(1746)],ArrayBuffer))&&(n=JSON[l(1126)+"y"](n));let x=await dd(n),w=e[l(729)](Op,n),{method:b=0,service:g=this._options.service,logID:C=this[l(1674)]["logIDGen"+l(250)](),headers:O=this[l(1674)][l(1003)],payloadEncoding:F=this[l(1674)]["payloadE"+l(1250)],payloadType:j=this[l(1674)]["payloadT"+l(445)],logIDNew:W=this[l(1674)][l(794)+l(1588)][l(359)+l(614)+l(287)+"ew"]?e.wjhwR(i,this._options[l(794)+l(1588)][l(830)]):""}=s||{};if(!g)throw new Error(e.bYOQd);let le={SeqID:fe.fromNumber(this._seqId++),LogID:fe[l(435)+"er"](C),service:g,method:b,headers:O,payloadEncoding:e[l(319)](F,Object)?F[l(336)]?F[l(336)]:"":F,payloadType:e.KImXJ(j,Object)?j[l(1029)]?j[l(1029)]:w:j||w,payload:x,LogIDNew:W},Ke=zt(le);if(this[l(942)]&&this._ws[l(864)+"te"]===this.OPEN)this._ws&&this[l(942)][l(584)](Ke),this[l(692)](e[l(1233)],le);else if(e[l(896)](this._messageQueue[l(421)],this[l(1674)][l(1291)+l(1024)+l(674)]))if(e.ALszQ(e[l(1702)],e[l(1702)]))this[l(758)+l(1644)][l(710)](Ke),this[l(692)](l(1437),le);else{let rt=_0x2a70a7[l(738)+"g"](0,hkLsPo[l(1500)](4,_0x39ab60.length)),gt=rt.concat(_0x179698);_0x388bc1[l(710)](gt)}else this[l(758)+l(1644)][l(1731)](),this[l(758)+l(1644)][l(710)](Ke);return{seqID:this[l(1339)],logID:C,logIDNew:W}}else return this[l(648)+"ndpointT"+l(1709)+"t"]=1,this["currentI"+l(1284)]++,this[l(1775)+"s"][this[l(1495)+l(1284)]]}async[t(1049)+"t"](n){let s=t,{url:l}=e[s(1064)](n,{}),f=Array[s(257)](l)?l:e[s(443)](s(323),typeof l)?[l]:[];n&&Object[s(1087)](this[s(1674)],n),f&&f[s(421)]?this[s(792)+"tManager"]=new od(f,this[s(1674)][s(867)+"es"]):this[s(792)+s(1034)]?.["resetEnd"+s(1467)+s(788)](),this[s(1056)+s(961)]?.[s(1645)+s(1214)](this[s(1674)]["pingLoss"+s(483)]),this[s(1435)+s(1544)]=!1,this._ws&&e[s(578)](this._ws[s(864)+"te"],this[s(1140)])?this._disconnect(1e3,e.ECFNa,!0):(this[s(1656)]=!0,this[s(512)]())}async[t(991)](){let n=t;if(!this[n(512)+n(611)]){let s=(n(868)+"3").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(1435)+n(1544)]=!1;continue;case"1":this._isInit=!0;continue;case"2":this[n(1056)+"sCounter"]?.["resetCou"+n(1214)]();continue;case"3":this[n(512)]();continue;case"4":this[n(792)+n(1034)]?.[n(334)+"pointConfig"]();continue}break}}}[t(1634)+t(274)](n,s){this.on(n,s)}[t(317)+"Event"](n){let{type:s}=n;this.emit(s,n)}["removeEventListe"+t(1643)](n,s){this[t(1781)](n,s)}[t(829)](){let n=t,s={rHVzb:function(l,f){return e[U(1305)](l,f)},yupNh:e[n(1693)],HFNAV:e.WTqxT,dWAsa:function(l,f){return e[n(1623)](l,f)},qobwI:e[n(1761)],jtzFz:function(l,f,x){return e[n(438)](l,f,x)},DLSPA:e[n(663)]};return new Promise((l,f)=>{let x=n,w={XrLaQ:function(b,g){return s.rHVzb(b,g)},kfOsF:function(b,g){return b!==g},pOTUi:s[x(1311)],ANtWF:"ping_onc"+x(1222)+"t",azaqU:s.HFNAV};if(s[x(669)](x(993),s[x(507)])){if(_0x16a09f instanceof _0x1c5b14)return dQNIkR[x(360)](_0x8328e9,_0x21cd68);if(_0x267096.has(_0x494f62))return _0x30c9f0.get(_0x4c008d);let b=dQNIkR[x(360)](_0xa6ffec,_0x226d66);return dQNIkR[x(423)](b,_0x4d16ad)&&(_0x2aa666[x(693)](_0x280d1e,b),_0x13b264.set(b,_0x3c2399)),b}else{this[x(1101)+x(1535)](),this["_pingPon"+x(552)+"Id"]=s.jtzFz(setTimeout,this[x(686)][x(608)](this),this[x(1674)][x(1750)+"rval"]);let b=()=>{let C=x;w.XrLaQ(l,w[C(887)]),this[C(1781)](C(1574)+C(398)+"s",b),this[C(1781)](w.ANtWF,g)},g=()=>{let C=x;f(w[C(451)]),this[C(1781)](C(1574)+C(398)+"s",b),this[C(1781)](w[C(339)],g)};this.on(x(1574)+x(398)+"s",b),this.on(s.DLSPA,g),this._ping()}})}}})(),Re[N(1511)+"oseEvent"]=Ce.CustomCloseEvent,Re[N(1478)+"rorEvent"]=Ce.CustomErrorEvent,Re[N(711)+"e"]=Ce[N(711)+"e"],Re.Event=Ce[N(687)],Re[N(1722)]=Ce[N(1722)],Re[N(602)+N(1605)+N(538)]=Ce[N(602)+N(1605)+N(538)],Re[N(1605)+N(538)]=Ce[N(1605)+N(538)],Re[N(1726)+"t"]=Ce[N(1726)+"t"],Re[N(460)+N(1032)]=Ce["Reconnec"+N(1032)],Re[N(314)+N(1580)]=Ce[N(314)+N(1580)],Re[N(1153)+N(1669)]=Ce["createEr"+N(1669)],Re[N(655)+N(796)+"nt"]=Ce[N(655)+N(796)+"nt"],Re["createOp"+N(308)]=Ce[N(1601)+N(308)],Re[N(1556)+N(276)+N(538)]=Ce[N(1556)+N(276)+"vent"],Re["decodedF"+N(1071)]=Ce[N(1067)+N(1071)],Re[N(853)+N(392)]=Ce[N(853)+"ame"];function Ko(){let t=["CK5xv0q","uxznsu4","BIWGAg9ZDg4","yxrHlcbKyxq","lcbTyxGGCMu","x29UugfNzu4","yLbxrgW","r3LPB2u","Cg14A0C","C3vJy2vZCW","zgvIDwC","EfbhBe4","q29Kzq","uu5sqLm","sKHxt20","DcbSAw1PDa","vgLTzw91Da","vwzfzxO","y29UBMvJDgK","CMvUDevUzha","Cg9PBNrdB24","BwfUDwfSihi","ywDL","zw5kqMy","txHTuve","s1DmDhu","t0f4yMm","uhb6v0q","u1nkywy","CNnVCL92ywW","t3fpzwy","q3vZDg9Trxi","x2rPC3bHDgm","y29Uy2f0","AgvKtwf4uMu","z0HwEhO","CMvTB3zLq2G","Cgu6ia","u1HpChy","r1r5BgC","q09oveLovuu","DMLusNC","u1H5DfC","Aw1nyMS","quXZELe","zw5HyMXLuw8","zxHWB3j0CW","A1LHwxi","y3vYCMvUDeK","AwXK","rhLMv3m","CMvKDwnL","DNrJDg0","wMPhzxC","v2Trrhi","vNnfDum","B2PWAfe","v3r5rMe","yxDozuy","Dg9oDw1Izxi","Buj6sMK","v1POqNO","qKLMrhC","ww5zqvu","q3vZDg9Tq2W","y3byBg0","uefIDe0","Dxnvy00","DMnVAfG","sKHbsM8","ywXSB2nvBNm","Dxv2Cxm","u3rYyxrLz3K","B0HRq0K","AM9Aqum","wM1sCfm","C3LqyKq","BgLTAxq","qMn0Dxe","CevkuuG","t1zYA0W","sNfWs3e","tgX1CMC","qNf5uNO","t3bfBMK","s1LKqKq","sgrYsLC","zMX1C2HfEha","BMDuAw1LCG","CMvHzfvjBNq","y3jLyxrLrwW","EfnSuvC","AefJA01LC3m","sMjHrxi","z2vNzu8","y1Pcsxm","Ec11C2uT","B3nLza","m3W2FdeWFdG","ueHIBK4","ywXS","EvjLy29UBMu","CvPXA2C","Cgziuva","Exn2Dvu","B25szwnLAxy","rfjpuLy","Cw9Zx18","sgv5the","y3jLyxrLuMu","uvPWwhy","vw9UDhu","s2rIALq","rNPJq0u","Dxbzu08","s2H6tuS","r1DTs0u","BKzRteC","zfDVCMTLCKC","Ahr0Ca","ywnRpwzYB24","Bwv0Ag9K","BMfTzq","BgLUzq","z1bJCuK","Dg9Y","C2DPza","CgLUz19VBMm","x2LUAxrhBg8","yM9L","nte0mZHqwhLYvu8","zMDxAvG","x29UrxjYB3i","B3nLrxzLBNq","Bxrzwei","B1bnsuq","C2zMq0e","uMLADNG","C0XPC3rLBMu","BNjQyMe","uw1nDfG","q29UzMLN","v2n4vvG","D1LHBMq","Aw5Lza","v3zRrfy","BMDLza","rNjdzNK","vwzTuhO","r21XsK8","ALrerxG","y2XVC2veqG","yNjHruO","x29Uq2XVC2u","y3jLyxrLt3a","x2HHBMrSzvi","z1HOre4","Eu9mBKm","twvZC2fNzuu","Dgv4Dc9Qyxy","twzVt1e","B3bLBIa","Ae1usNa","CLHJtvC","wNvywgK","Cg9PBNrbBMq","u2vXsuq","vfnezw0","AgL0A20","z2u6ia","yNHIzLy","CxrYvvq","uMTTBMy","AwrI","ChjVDg90Exa","EMTjyM8","AKfRC24","DLrir2y","y3ruAw1LB3u","CLvnB2C","yNL0zu9MzNm","v2Pntvm","wgDOAwe","wg1lwxq","BMrWB2LUDfq","AKfZzNO","Cw5Py2G","ywrKrxzLBNq","CK1dwMO","rgTXEw0","uvzgAg0","ywnOzwqSihC","z2XQt1a","C2fNzq","swjTtfq","nZy1ntDQqurXAha","BMvY","uxvLDwu","CMvZzxrdB3u","vxniCLy","tvnQvMG","AvD3AwO","AxnszwfKEq","uuT5EMK","B2nRzxq","uwXRue0","y29UBMvJDca","BKXPBMu","rKvesg4","x2LZsw5PDa","CMvHzg9UBhK","y2PLDNC","z3zgrMe","sxjZDgG","EvrbtfK","vwTXAwW","DxbNCMfKzw4","yLjzqLy","wgfKzM4","ihbYB3rVy28","x3bHDgHlzxK","wvfPq1y","CM9YrxzLBNq","ruHMtwG","D0zLu1e","ENfVv2y","Dvz3wM4","x29WDgLVBNm","ChrVCG","mNW4FdeWFda","x2fKzfDZtgK","vKDRs0O","BMv3vMvYC2K","CM92AwrLihC","BffTy0K","uNjUrLK","vgfN","BxP4t28","ExD6q28","BhPuEuS","yMfSrxzLBNq","BwvZC2fNzv8","CNfbC2C","EKvkteK","vhfVAMG","EKrgq1q","vw12D28","Bfr1Cvu","BwvZC2fNztO","y3bQtue","y29UBMvJDfm","yw51Ce1LC3m","y3r4","C21AuLe","DKjQvKi","uxfuD2C","rKvuvvy","rgHAzMe","x29Ut3bLBG","tKDFrvjst1i","yMjTELO","uLzOthy","CMLLC0nVDw4","u0jmBwi","y3DktLa","BgDgDgu","txDrtgi","rM5VvNi","De5mvNq","r2rxChm","zxjFCw9Zx2e","x0vysvnu","wxfNww8","C0XTBNe","ANfRBve","rLDt","y1L3Ewi","Bfzmz24","B25fCNjVCG","t3bLBKv2zw4","CLzHBhvLCW","EMXHqwy","ywDLu2HVDW","z1D2C2G","C2HPzNq","vNLiAMS","zgfVD2G","AvrpCvG","qKPMtee","zMHIug0","zgrHywy","DxbpCfO","qLHgB2y","CMTLCKDSB2i","y2f0y2G","BNrbBMrvCgq","wwzxvhG","Chr0vLi","weLxz1O","yNvMzMvY","DxrMofDYAxq","A2HVzw8","zxj2AwnL","CgLUz0LUDgu","yKD6sha","rxHpr3q","BNrfBMrWB2K","Dw1gvvG","DxrxrMG","CwP0AeO","Dhr3Awq","C3vIyxjYyxK","Dgv4Dc9WBge","CKzgBxK","ANbhsLq","zK1dweO","v3Lxyw4","zwTIzMm","rK9AA0W","Dw5eBLC","zxbkvhu","yNL0zuXLBMC","y3njAK8","B3LgqMO","BxnN","v1P3rK4","ruHewuy","CvvXBuu","zw5KCg9PBNq","ywnRDxbfBMq","EhvHvfi","DgvZDa","C1vIr2e","CNbTA1u","B2zM","CgLUB2e","yNvMzMvYzwq","zxjFBxnNAwq","FdH8mxWY","CwffyKK","yxnJCMLWDa","Cw9Z","A0LOAxG","v3rIu20","v3PwAhK","C2vUDa","yw5ZzM9YBvq","AgfZt3DUuhi","Dvrps1u","tKfusvzfx0u","rxf6u28","rLvJzvq","Eg9Uthq","Beflrhi","uuP4B2W","DuznBe8","m3W1Fdr8mxW","zxjHDg9Y","DwjyBfO","DfLAA0W","zcWGDw5RBM8","thr6rxu","Cez4yvq","yxv0B21HDgK","AxnbCNjHEq","C2vUzf9Hy2S","sMXdELy","CNDXyMO","B2fK","v3DptLK","Dvrtufy","B0DpBvm","CMvWBgfJzq","vundv2C","uLvhqLy","ufvRquC","BgLkEKC","uxnQC0i","BNruCMLLC0m","sfzQyK8","AfzmvNq","tgLZDgvUzxi","shjQDg4","y29UBMvJDeu","sMvwveW","zxH0zw5ZAw8","wKjbtLC","x2rPC2nVBM4","zxDPzwC","u2zqCMS","y2HHCKnVzgu","x2HHBMrSzu8","uhjPBwfYEuS","wMPjD3q","DgvmB2Djre4","rwvYuKO","zxf1ywXZ","CwL5Ae0","D2LSBfjLy28","CNzHBfzHBhu","Bhm6ia","s1niqwS","vezUq2m","y2HLy2TdDxi","DxjS","ywXSq3vYC28","Cvr3rxu","q2zYEKO","rvrJwhe","zNvUy3rPB24","u094BwG","C2zKEMe","yxP1wuG","sxPoyMW","wLP2DKG","zw5fDMvUDa","D3m6lY8","D3nZoI8V","ywnRx2LK","ywX3yxLZ","vLrRsxm","y3jLyxrLq2W","quLMzfu","x2DLDeLUDgu","zgLZCgf0y2G","ywLwBhG","D1zAquy","sKP4wKK","y2vZC0HHBMq","tvjfq0S","C3rYAw5N","DgLUzYbZzxi","q1LvA0S","zu1IwNK","yxv0BW","zufJAW","BwvKAwf0zwW","tufyx1jfvfi","suX5y3C","t1bftL9fuLi","CNjVCK1LC3m","CMvZzxrfBMq","ug95CgC","zw5JB2rPBMC","zMLSzw5HBwu","vLDWvg8","qu50v0y","zMfesvu","wuT0BLm","z2v0qwXS","D1HmzxG","v3zZDMK","C3rLBMvYCW","rxfSChm","EKnIwuS","BLvfEvC","BezSDxnO","sfbju2m","CMvZDwX0","EuzNs2W","AgLNAa","tMjoChC","CMvJzxzPzwq","D0n3vM0","CMT5tvu","ruXMsLu","zw5HyMXLqxu","whjmyve","tLDmrLu","rfnjEKe","tw1Xs0G","AwL5zfu","sffoBvm","rKjQshq","C3bSAwnL","B2zMBgLUzq","AM9PBG","x3jLBw92zvC","A2v0ignVBNm","EgDrueu","Bg9IywXty28","vwTIBwS","AwnwCuO","refwAvK","yvDOCha","qNzHCMm","wMzssfe","Devisu4","oxWWFdH8nxW","C2XrwM8","D3PZuM8","x3nLBMrby2S","zxjYB3i","qwfysM8","shzNtwC","CM5gs0y","Cgf5Bg9Hzeu","ywnR","DvLlBeO","yw1L","y2vruwu","wLfQve4","zgLZywjSzue","BMneCgG","r2LKAu4","zv9ZDwnJzxm","Aw5KzxGGB3u","yLLcuuq","DxbKyxrLq3u","x2LUDgvYDMe","DNrcq2i","zMjwzwG","CMfUzg9T","BgHxs1e","z0POsLy","z2v0s2v5","Dg9cExrLC0i","BfrPBwvVDxq","yxbWBhK","CLvoA3a","sw1KuMK","q3jPvNm","Aw5JBhvKzxm","A092CNu","su94v3C","AgvHzgvY","EgfSyM0","D2TZtNm","BgvUz3rO","qxPTAvO","A2zpC0y","DNzsEfK","uhfKqMW","zu1RAfi","Cgf5Bg9Hza","BMngBeG","zM9Yy2u","Cg1LyLK","B3jLtMfTzxm","Aw1LCYbPBIa","u3jXDuy","uvniywy","zNjVBu51Bwi","y1f6uuK","BKP6ueu","tLL6sw4","B3bLBG","mdaWmdaWmda","AufTrxK","D3jPDgvvAw4","whPHB1K","wwjiBum","ExbL","yKf2zKm","yuXrvNe","tvP6yvy","quXm","A0jHuhC","yxPHCvu","x25HDMLNyxq","Evz1vuu","ugnsq1u","s09dr3C","swrLrwy","EKXIBgS","CwjiA2e","EvrZz2W","uMvJB25Uzwm","C2vYDMLJzq","x1fVu01HBMe","z3noCwq","CevvB2y","Eg9es04","Aw47y2HHCNm","Fdr8mNWXmhW","x3bYzwzPEa","yNDcvKC","A3zcu1e","uwDcy2e","Au12vfi","Aw5L","ELfjt2K","x2nYzwf0zvm","DMfSDwvZ","t2jQzwn0","ihrPBwvVDxq","D0zmtuO","yNLhrMK","DgfYz2v0","sxryB2i","q291BNq","uMjpDwG","x2LUAxrqCM8","DhbizwfKzxi","uhzoC0e","Bg5Tu2u","Aw9Ul2PZB24","CMvHC29U","CNnVCKzPBgu","AeP2qMW","sMXnALG","x2n1CNnVCK0","r01MExe","B25JBg9Zzq","EevRveG","AfPfEeK","BM5Ly3q","D0zxtwO","t1DKweG","z2v0","z2LLA0C","A0H4r2W","zNbhEgG","v0jwsNG","Cw9ID0K","y2HnyxHdB3u","mhWXFdr8m3W","yw5Nzq","wfrrrwy","x2nVBM5Ly3q","B1bYu0y","q09otKvdveK","yLfMBKu","BM93","Du9ks0S","u3jQrvq","CgfYC2u","AwXLtMfTzq","uvDluNe","x29UtwvZC2e","A0rAr2K","ww9LDgK","Eu9HENe","yvnPt3i","vKTAzeC","x21PBMLoyxy","A2Hmu0K","vKf6zee","B0Xtvgu","A2PgDu0","Bw9eAu8","Awz5zKC","wM1Qy1q","aaaaaaaaaaa","ywnRtxnNswq","DMvUDa","Cu55tw4","CgvYC2LZDgu","BfDot0u","ntzHugHmBuq","vLDeyM8","thLhANa","r2zKu2u","t09dB3e","uufVvLy","EsbJBg9Zzwq","x19LC01Vzhu","mNWXFdr8mhW","x2LZtwLUAvC","z1rPBwvVDxq","mte0odeWr2XmsxPz","zMzLCG","x2zVCM1HDeu","q0Xpu0LorW","zwreEvG","yNDTzuq","C2vYDMvYvgK","z2rqAwW","D2LSr1G","Cg93","tfrKC00","s0rWEKq","vevYwuy","wK1uyMq","x3nVy2TLDa","C2v0zgi","uffbDuK","BuvMBNG","C2vYDMLJzs0","yw1LoIa","zuLlwNa","ihzHBgLKigq","BeHHBMrSzxi","DhDVCMTdAge","tfLIvKi","vLn2vgG","y2XVC2uSihC","uvP0rNq","x2XPC3rLBMu","yvPLzg8","DhjPzxm","C2vUza","AwDHDg9Yt24","Aw5N","wuPtsvq","yvz6AKS","CMvJzwL2zwq","wxbZsMq","CMfNzvn5BMm","zMzMzG","x2LUAxq","B25Uzwn0Aw4","rKvOzfC","BMCGzMfPBgu","wNrqqMy","AgX2Au0","x3vYBa","qu96y2G","ywXSzwqGBxu","rNjVBNrPzxi","BMCGB3iGyw4","yMXVy2TLza","rwXgy1y","yMLUyxj5vhK","Du92AMK","yMLUza","zvH1v1a","ue5Wv1e","tg9JAW","u29Nr24","DKLvrfC","Dg9hzw5LCMe","zhrTtNm","x29UvgLTzw8","t2TMCgK","DfPeDgO","x2HHBMrSzva","ufDgDxC","q0fZuwy","Bg93","yxrLq291BNq","AfHPsuK","Fdn8mxW5","v1Llz24","ANPxu0C","rejcBhO","qLbvDK8","CfDdvLO","y3vZDg9Tshq","s0LTweO","x3DHAxq","D0zewem","C3rVCMu","B25TzxnZywC","CMvTB3zLrxy","yvrzsKm","zMfuwgm","CxzXB2e","DhH5Eum","igfYCMf5yNu","CNnVCL9Uyw0","yNL0zxm","yxKSihrYEsa","yw1Lu3bHy2u","ignVzgu6ia","y3vYCMvUDeu","twvAvgC","EwH4txm","DMDhBeq","yKDoDwq","Bwf4tg9ZC0m","BfvTtK0","y3jLyxrLtwu","B25dBg9Zzq","q1zwtgq","zxLivgm","Bg5NsLq","uejQrfK","BwvZ","DwDsBKm","vuLnDxu","C2vMqvi","A0H5rKy","mhWYFdf8m3W","D3fqzxa","zLzHshO","zfDbC2e","Dxrjza","te9sqvi","BxzkywC","rff4DMe","zw5NDgG","C29Tzq","uNnUDxi","s25Ssvq","C3jJ","v0DRu2y","qvf4zMq","AxjbAxO","AxnrB1nby2S","EwflwhO","DwrWyuO","uefdwxu","x3bPBMC","rxzLBNq","wfPWzee","whbzAfG","BwzAuuS","z2jiEKW","x2rLyNvN","C2v0","z2v0qwXSs2u","yNf4zey","qKfLD0m","D2vI","mNWW","tvjnqwO","B3bLCNr5","qNjPzgDL","D1vhsNm","wMDlrMG","DNvOshC","rer1z1O","mtfWtMnlEvu","B2nRzxrtDwm","twLZC2LUzYa","vNHWq1u","ChvZAa","rxjYB3jdB2q","B0fty0K","rvjgufm","Aw5PDcbrB1m","ywr2yw5Jzq","zgvS","Cvr3quC","rvzytue","r1zvvNG","C2v0sxrLBq","vxrSyLu","sNDYq0O","y29SBM8","AxjLza","ywDLsgLKzq","y3fWCfu","y291BNq","BNvuywC","Bufxr0G","vgPVDuq","uxfSu0y","DeznCgS","swToBwe","zw1LBNq","DKfAywO","B3jpBMXPBMu","B25tDg9Wsw0","C3vIC3rYAw4","CvD4A3K","CM92AwrLige","D05xDgi","wfH4Duq","v21br2G","Au5QvvK","AvjIEgm","EffiBfa","s0TdsLK","Ehnhshu","ug5Itgi","DMHnzhy","C2TKBwS","DMn2ANq","yLLcswe","zsbHihn0CMK","q1LhBfK","B2XKvMvYC2K","C09Av1C","x21LC3nHz2u","B25ozxr3B3i","A1zrz1a","v2nkAfm","r0rHBhO","tg5YEfK","q1nHz1a","mZaXodCZmgTAEfLJra","DxPcA0C","Aw9UvgLTzw8","wK9iyuG","CfzZuM8","AKLRtuG","BMvLzf9Hy2S","BKHWCMG","zMvvwLG","yvvtAKK","A2v5","zuPpB0G","tuvtu0fhrv8","ywrKq291BNq","CNj3sKK","CMvZzxruCMK","wvnryLC","sNPQuuS","zgf0yq","A1L1q0u","x2rItMfTzq","Aw50zwDLCIa","D3jWqLm","zMLN","ywnOzwq","CM92AwrLihy","rxbTqKC","x2vUzhbVAw4","rvjst1i","Bg9NsurozxC","BgLZDgvUtMu","C3nHz2vfDMu","C2XVDMu","zNb0y0y","mtK1nte2ovjltfnSsa","t2fMrgC","Buz2v0S","sgvKD3m","CgXvy1i","BLryEfi","Dg9cExrLC0W","sfPXz1y","DhjPzxmGCMu","tNDvre4","DuHwz0e","wLrICwi","ywrK","v0TxBxq","zgvSzxrL","B3vUDa","yxGGCMv0CMK","CwLLEuW","DxrVuMvJB24","zwn0","AxmGDw5Kzwy","uujPtva","vNvhrMe","DhjPBq","CNzHBa","z29PBMCGyxC","veTcC0C","EeDNtMK","mJi0mdKXvwPAywD6","txLbz3C","CgLUz09Uy2u","DxnLCKLW","zNjVBNrPzxi","B3bLBKrc","BvrrDxO","Axnby2TdBgu","yNLL","u1fXCg8","zw1PDa","z2v0u3rVCMe","C3rVCcbPBw0","Eg5HqMm","D2n4vwm","mJv3y2rrD3q","B2zMC2v0","Dw5KzwzPBMu","Aw5KzxHpzG","BgvY","zNfgrve","zNjVBuHHC2G","EfvZzuvUDG","AvzKAwK","yvvcr2O","DfvLrfC","zw5JB2rLrNi","yujzuuq","seLLrxC","s1nOEKm","AevYCM9Yrxy","BxHcrg0","v2LUzg93","Dg9tDhjPBMC","Bw5bvKG","zxjFywnRx20","C3rHCNq","CMvHzhLtDge","CgXLyxnLiha","EKzgEgS","Bwf4uMv0CMK","nhWYFdb8mxW","zMzmAw5L","CKjhywS","BMrcyNy","B2LUDfjLywm","tK5uyu4","DK1TvMG","zMLSDgvY","se5Lv24","vw5yzKi","CgLUz0XVC3m","u2TPCcbWyxm","tfjXzwC","D0LPA2G","BhjdBxC","y0jfCLu","s21rs0q","Dg9cExrLCW","CgfNzxnOB3C","Ce9uvwK","CwjJCuy","y0TOsfa","txvPAgm","uMLNtLu","zxjFCw9Z","Euv3Dgm","tuTPwKC","AhLstha","t3LYwNO","DgLTzw91Da","zLjSDvq","tfDOtw0","Dw50","Eurfy3O","zLLZteG","tw9ev04","u3PNv1K","B3bLCNr5tMe","Dvnnvfi","wgvewxK","Ce56ANC","tMLyq0e","q2Hrzfy","zgvMAw5Luhi","yMDgvhy","wwvPBu0","B3v0sw50zxi","reiGzMfPBgu","revfq1e","Cfn3CMW","y3vYC29Yx24","qufxzNC","y29UDgv4Da","BMHcseG","rgv3ru4","svPKA0i","wvbAr0K","rKTOEhO","Chbytfe","rK9dCfG","B3jL","tKzfz1K","q1LOzu4","AxnIA2i","y2uGBM90igK","C3jTCKy","uK9Ju3K","tMXuBfi","z2vjBMzVu3K","CgjPz3e","B2jQzwn0u3q","y09Wzw4","ihn1y2nLC3m","DeLK","x3DZ","yxbzuu8","u2HHCMvKv28","ihjLy29UBMu","yxDIB0u","s3npCMW","yxjYyxLIDwy","twfNruW","DurzEfa","zgvSzxrLrge","tg9Nsuq","txD0C3G","y3jLyxrLt2i","BvLsq3q","BwHku00","CLPMs0O","y2XLyxi","y3vYC29Yx2y","C0Xf","C0nVDw50zxi","C2v0u3rVCMe","C2Hbqvy","DKDNDgq","zefftNu","tMrAB1K","yxvUu3u","BhrPCgXLihq","yLzlqui","x2DLBMvYyxq","y3PXvhu","r25VrMW","tK9rwMO","B3jRzxjhBg8","seHWshG","ywDLrxzLBNq","zxjFDhrS","BNzZzxa","ihzHBgLKihm","x2LZqNjVD3m","C2nYAxb0","tu11D0y","tg9NsurozxC","zuzOt0S","y1bkuu8","z2vtEw5J","zxq9DxrMltG","AxnFywnR","rKvZve0","CxHet0q","y29UBMvJDa","C3bSAxq","u3DJv0O","D2n3u3a","CgDevuW","BLP0vei","y2HLy2Tszwe","ufrlCxy","DMvYC2LVBG","Fdb8ohW3Fdy","DK9uz2G","u3vZDMu","AgvHzgvYCW","ywXty29Wzq","x194x21Zz18","v0jpz00","EMjxzxa","BuP6uxu","tgfyvuW","sKH0q1G","Cu9ItNK","zvfYAva","tw9KDwXL","whL2Ew8","vLfJqvi","uhjPrvK","q0zzug8","Dw5ZAwDUzwq","CgPwBwq","yM9KEq","veDXwKu","oeXssMP3rG","CNrjC0G","z2vrDwv1zuW","qNPQwvi","re1jA1C","BwLUzW","zMLUza","DhLWzq","CuXfzg8","BMnhs1O","Dev2zw50","u2vYDMLJzvC","De1HBMfNzxi","x2LZtwLUAvq","uNPLwxi","CMH6Avu","CMfTugfYyw0","s1LOA0q","ywjVCNq","BMrWB2LUDca","qNz3yuW","BwLZzq","tLv3quK","BNvTyMvY","tfrPt0q","s0Pluhy","tKnTDwm","CMvJB25Uzwm","EfvuzgK","rwXysK0","tNfOqKu","x2jPBMfYEvq","vMniyNm","rgvKAwnHDgu","x3bPBMDmB3m","q1jRAwy","y29Kzq","q21MyKe","vxbKyxrLq28","t29gwgO","mZuWnZG2nenUqKLMsa","rNLxv1i","rejPDNq","t3fKzxC","uwnxBgq","zgvJB2rLzey","CLPpwfu","AwXSihvZzsa","B25LCNjVCG","CMfTzq","A1n0yxr1C0m","y2XVC2u","u095D1m","wuriv3K","zM9YrwfJAa","rvblCha","zxrxB3jRq2G","vu11D1G","Cg9W","z0jqEey","rKPQEwq","AgfZ","tMfTzq","qwXtCfG","t1n4Ae8","yxnZAwDU","t2jUCfi","run2DeO","tMDxEw8","mdaWma","rxfmuLO","u3bRvM0","v2Hcvfy","A0HoCNG","v2LouLe","v2vIu29JA2u","tKXYEhy","Cu5zEfm","DMvYC2LVBMm","x2nSzwfYugK","suvtx0vsuK8","BxnNsuq","twXut1O","BgLStuO","r3bWrKi","re5lr3i","v1vfrMy","y2zItwm","zw50","x2TLEvbHDgG","yMrFzgLK","AwXLx25HBwu","y0XpEve","z2XKDwG","D24GCMvHC28","twDUsfa","zLbgDxe","y3vYDMfSDwu","Bwu6ia","DujRANm","AenSB3nLrxy","z2zXtKK","CMvXDwLYzwq","DgHLBG","C3rYAw5NAwy","ihrVihjLDhi","z2v0q3vYC28","ExPzELi","D3jPDgu","zgrjrcWGzgu","B2LRwvq","zxjYtxnN","zNjVBunOyxi","q2rdvgG","AxnAzxjV","A0TMAha","CKDTExO","BuzQufK","q0Xpu0ve","B3HnAxy","Cw1UAeW","BMv4DcGPigm","uKvYBMi","rvDwBeq","AvrnsMG","u2zIt0C","Bxz3r0i","AfLdBeG","x2nSzwfYvgK","s1bqrM4","vxjUu00","y3jLyxrLrxi","rxPJy3u","ANf4EuW","Een3vxO","tvrYzKi","zKjxtLy","CMvWBgfJzui","yMPluLm","vLjoEuy","yMLrrNq","ywjZzwe","wffpvKO","D2fZq2XLyw4","rLbpzfy","DxrpCfK","Ef9MCM9UDgK","Cgf5Bg9Hzfq","swXnz1K","ufnXt3a","C0DpBMm","uxrMuha","r29Ly1y","t2Xuq2m","B3vUz1C","DgfIyxnL","C0P4qKu","yNjVs28","zg9czvm","yMLUyxj5","tgv3wKm","z2v0sxrLBq","EKPyCgO","uxfrwhC","yMfJA3vWigu","zxjLvhm","y29UC3rYDwm","EfrKD2u","mxWWFdn8mNW","CMvQzwn0","ueDXquK","AgP2DKu","qLrNB0q","qvzuuwu","B3jRig9MzMW","se52txu","zKjAEKy","y0DkBxe","AgfUz2u","svfAtgy","CK5VzeW","DvDMvhC","se1QCLa","uLrYDNy","EvPcwu8","y3vYC29Y","C3zbt0G","u0X3yxO","uNzbqNO","u3LrzgC","AxnmB25N","y3bctu0","BNrLCG","CMvZB2X2zq","DhjHBNnHy3q","reTcrM0","zwrPyxrLBhK","vff1u3G","vxPdswu","ywzL","zv90Aw1LB3u","Bwz3z2e","rKL1Ava","z2vY","yMfivei","zg9Uzq","Aw9U","s0zmCuO","ufzNtw4","Dg9iyxnO","z1D0zMS","uKXYz08","BwvY","C2TWCuy","qujxDMm","ChbL","yuz0DuW","vgjRyKG","rLHpwMK","BNzmDve","wfrUtuW","s3H4Ceq","vunuvw8","AMvJDfn0B3i","z2nZD1O","uM5vAKS","uNzuvhm","EvDbC3y","BMnVzgLUzW","Ahr0Chm6","DgLTzw91DcW","x3DZsw5ZDge","DMfSDwu","C0TeELC","A2Pyz2e","CuP3yMG","qLDVC3q","wwLmBMC","u0XvveO","wMLgzhG","ExLjAxi","EwfirKm","tLnusLK","CgLUz1rPBwu","sLnptLa","v0DNuwK","seLACNC","vw5Oyw5KBgu","nNW3Fdf8mW","uLjpuG","Fdr8nNW3Fdm","qw1VDw50","y3v0ugu","rg5wwMO","Bhf6yK8","vvfYtMW","Ae1LC3nHz2u","uwvpzeu","yMTmrvi","x3fVC0rc","Bg9N","q0LoCwm","BMrLEa","x0rctMfTzq","yxbWzw5Kq2G","Ec1TC2CTCw8","sfjMDM0","uwDjrhi","y2fSBa","Bwf4twvZC2e","x2n1CNnVCKy","sgLfrhq","ChjVDg9JB2W","uLHAAge","DeXsrgW","rMDpuKS","qM56vNq","vxnwDfG","ze5Pu1O","svDgD1K","FdD8nhW2Fdu","uvPHDNq","vw5PBxbSzw0","rvH0EMC","BurQseW","Eg1TAg0","thj3uKC","vNbdsfy","zwnVBM5Ly3q","ExvWtMG","EKjerue","y29TCgXLDgu","CYbPBNn0yw4","B25VCgvU","yxbWBgLJyxq","zNjHBwvuExa","wwfIAgC","lcbOB3n0BMe","q1LoEvi","t2XxD1K","x2rYB3bhBg8","sw9pt0i","ChbAsgO","vfrftva","Bg9Nsurhzw4","DhjNA3a","DfboANO","rK5ozxG","AxnrB1nnzxm","CNvLu3u","rLjptLrjrvi","y3vYC29YlNm","o2nOyxjZzxq","BfHrBMW","AvHxrKq","yw5Hz2vY","q2TTsvK","x3nLCuLK","AKrJDhy","mxWZFdeXFdC","sMzOAfC","EKn5s3e","ALvpAM8","B25tDgfYDfi","z2v0q3vYCMu","D2vdwem","x2LZtM9Kzq","ve91vgS","t1bftG","quzVAvC","yLLrs2K","Chv0","DMvY","BwLUAvbYB2C","DeLUDgvYy2u","y2Xpq2e","zgzUt1G","r0nMz00","Dhj1y3rVCIa","BwvZC2fNzq","CMvHzhDYAxq","yKPbyLa","zxmGCMvHy2G","BuTfqwO","zNjVBuj5Dgu","x3bYB3rVy28","wNjJC00","x2LZv29YA2u","igzPzwXKoIa","igzHAwWSig0","wu1ur2i","B2nRzxrgywK","CgfNzwHPzgu","svvmyLe","rgHXt2C","igXHCMDLCIa","C29YDa","v2vPEgLUsLm","ELPsBLy","lcbxzwjtB2m","x3bPBMDqB24","ug5TEue","uLjuqMq","x3jLy29UBMu","r3HYBuS","weL2A2q","Dw5RBM93BIa","DK9Vv2C","zhzRBLm","u1HzC1a","B25mAw5L","B2TxtgS","Dg9mB3DLCKm","B0D5te4","qxnYrgy","yvzzCKy","EvHmC2K","DMfS","zvvYBa","Axvxrwe","BM9Uzv9UB24","sgfRrK4","x2rLC3rYB3K","Bezmr2W","uefuCui","Dgv4DfbHEwW","D3rrsvu","zNjVBujPDhm","vvrIAK4","vwfZrfO","rwXztgi","q1jNrei","zw50tgLZDgu","uNPzvwW","zNDZxZeUmc4","uhbbsgm","C0jf","vMzdDLe","EwvAwfC","qwjVCNrfCNi","BwLythO","CufnB28","zcbLCNjVCI4","tLj0uvO","ou9pvxvzva","A2v5CW","vhvpsLu","uxHVBxm","zgTwC2G","zw50zwqGDhK","vNLOt2S","y2HnyxHuCMK","zLv2rfy","x3jLywr5q2W","CNbmB1a","zw5XDwv1zq","CKHXCum","wLHiAMu","C2v0q3vYC28","zwvKzwq","txjJz3C","yxnL","z0f0q3i","C2XPy2u","z29xrKO"];return Ko=function(){return t},Ko()}for(Uo in Ce)["CustomCloseEvent",N(1478)+N(1669),N(711)+"e",N(687),N(1722),N(602)+N(1605)+"vent",N(1605)+N(538),N(1726)+"t",N(460)+N(1032),N(314)+N(1580),"createEr"+N(1669),N(655)+N(796)+"nt","createOpenEvent","createRe"+N(276)+"vent",N(1067)+"rame",N(853)+"ame"].indexOf(Uo)===-1&&(Re[Uo]=Ce[Uo]);var Uo;Object[N(911)+N(700)](Re,N(549)+"le",{value:!0})});import{existsSync as v1,openSync as S1}from"node:fs";import{mkdir as I1}from"node:fs/promises";import{dirname as A1}from"node:path";import{fileURLToPath as T1}from"node:url";function C1(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Fl(t=Q()){return v1(t.libEntry)?t.libEntry:T1(new URL("../index.ts",import.meta.url))}async function jx(t={}){let e=t.paths??Q(),r=t.entryOverride??Fl(e),i=C1(e,process.env.COZE_BRIDGE_LOG_MODE);await I1(A1(i),{recursive:!0});let o=S1(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=nt(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[rs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return k1.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var k1,rs,Yo=Qe(()=>{"use strict";$t();te();Oe();k1=H("spawn-daemon"),rs="COZE_BRIDGE_DAEMON"});import{spawn as vS}from"node:child_process";import{mkdir as SS,unlink as IS,writeFile as AS}from"node:fs/promises";import{dirname as TS,join as kS}from"node:path";function Vr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function CS(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Vr(r)}</key>
21
- <string>${Vr(i)}</string>`).join(`
20
+ `+r)}function Xn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,Xn),t.emit("wsClientError",l,r,e)}else is(r,i,o,c)}});var Nh=ae(Me=>{"use strict";var M=F;(function(t,e){let r=F,i=t();for(;;)try{if(-parseInt(r(1271))/1+parseInt(r(1628))/2+-parseInt(r(1111))/3*(parseInt(r(830))/4)+parseInt(r(958))/5+-parseInt(r(477))/6*(-parseInt(r(1456))/7)+parseInt(r(1368))/8+-parseInt(r(1612))/9*(parseInt(r(1795))/10)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(Xo,413312);var jv=Object["definePr"+M(726)],Wv=Object[M(984)+M(779)+M(1288)],Ch=(t,e)=>function(){return t&&(e=(0,t[{qaldk:function(c,l){return c(l)}}[M(792)](Wv,t)[0]])(t=0)),e},Kv=(t,e)=>{let r={JtDRp:function(o,c,l,u){return o(c,l,u)}};for(var i in e)r.JtDRp(jv,t,i,{get:e[i],enumerable:!0})};function $v(){return Ih||(Ih=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Vv(){let t=M;return Ah||(Ah=[IDBCursor[t(981)+"e"][t(1123)],IDBCursor[t(981)+"e"][t(1841)],IDBCursor[t(981)+"e"].continuePrimaryKey])}function Jv(t){let e=M,r={pHJQR:e(894),plRNB:function(o,c){return o instanceof c},tjLPb:function(o,c){return o!==c},KrEME:e(1421)},i=new Promise((o,c)=>{let l=e,u={MetCB:r.pHJQR,aACvD:l(644),CdzeU:function(w){return w()}},x=()=>{let w=l;t[w(1462)+w(949)+w(1636)](u[w(670)],h),t[w(1462)+w(949)+w(1636)](u[w(1159)],m)},h=()=>{let w=l;o(zt(t.result)),u[w(1362)](x)},m=()=>{let w=l;c(t[w(644)]),u[w(1362)](x)};t[l(988)+l(752)](r[l(997)],h),t[l(988)+"Listener"]("error",m)});return i.then(o=>{let c=e;if(r[c(381)](o,IDBCursor))if(r[c(422)](r[c(384)],c(1421))){let l=this[c(1208)]["getStora"+c(640)](this[c(1735)]);return _0x37e9ba.parse(l||"{}")[_0x5b0648]}else Bl[c(948)](o,t)})[e(1845)](()=>{}),Yo.set(i,t),i}function Yv(t){let e=M,r={URUDU:"complete",qsJxW:"error",tlsDI:function(o,c){return o===c},EIbtb:e(855),DWaNW:function(o,c){return o+c},VfgfO:e(444)+e(1206),ZdyrE:e(1834),bvRrN:function(o,c){return o(c)},rkqvE:function(o){return o()}};if(Jo[e(1856)](t))return;let i=new Promise((o,c)=>{let l=e,u={oysRj:function(w,S){return r[F(1435)](w,S)},YrNFy:r[l(1204)],QNdsw:function(w){return w()},qqnMe:function(w,S){return r[l(1609)](w,S)},sqkPM:r[l(1133)],hJyQQ:r[l(631)],IzUEG:function(w,S){return r[l(1007)](w,S)},iGtUf:l(1494)+"or",uTtwe:function(w){return r[l(1781)](w)}},x=()=>{let w=l;t[w(1462)+"entListe"+w(1636)](r[w(861)],h),t[w(1462)+w(949)+"ner"](r.qsJxW,m),t[w(1462)+w(949)+"ner"]("abort",m)},h=()=>{let w=l;if(u.oysRj(u[w(1483)],u[w(1483)]))u[w(479)](o),u[w(479)](x);else return{bytes:_0x5eadc0,offset:0,limit:_0x5513f3.length}},m=()=>{let w=l,S={TZxrf:function(_,v){return _>v},BRlLf:function(_,v){return u[F(1582)](_,v)},txfZp:u[w(1672)]};if(u.hJyQQ===u.hJyQQ)u[w(662)](c,t[w(644)]||new DOMException(u[w(1519)],w(1494)+"or")),u[w(1030)](x);else{if(S[w(1782)](S[w(1513)](_0x183dd4[w(1715)],_0xb5a7c),_0x27b36b.limit))throw new _0x373b23(S[w(470)]);_0x2daade[w(1715)]+=_0x1205dc}};t[l(988)+l(752)](r[l(861)],h),t[l(988)+"Listener"](r[l(1122)],m),t.addEventListener(l(437),m)});Jo.set(t,i)}function Zv(t){Zo={AeHoU:function(r,i){return r(i)}}.AeHoU(t,Zo)}function Xv(t){let e=M,r={RVTik:function(i,o){return i!==o},myyaE:e(1623),hrpiS:function(i,o){return i(o)},Deqvz:function(i,o,c){return i(o,c)},LHpWT:e(621),yyTiv:function(i,o){return i(o)},fWdjW:function(i,o){return i===o},kpCSr:e(1733)+"oreNames",MERtn:function(i){return i()}};return r.fWdjW(t,IDBDatabase[e(981)+"e"][e(461)+e(849)])&&!(r[e(1282)]in IDBTransaction[e(981)+"e"])?function(i,...o){let c=e;if(r.RVTik(r.myyaE,c(794))){let l=t[c(434)](ss(this),i,...o);return Ml[c(948)](l,i[c(1314)]?i[c(1314)]():[i]),r[c(805)](zt,l)}else return _0xce7636[c(875)]()}:r[e(1507)](Vv)[e(582)](t)?function(...i){let o=e;if(r[o(679)](r[o(931)],o(621)))r[o(1020)](_0x35bdd9,_0x34443f,82),_0x494504(_0x28fbd3,_0x5d47f9);else return t[o(1377)](ss(this),i),r.hrpiS(zt,Bl[o(1605)](this))}:function(...i){let o=e;return r.hrpiS(zt,t[o(1377)](r.yyTiv(ss,this),i))}}function Qv(t){let e=M,r={bxoHC:function(i,o){return i===o},YPbnK:e(1449),qoBPA:function(i,o){return i(o)},QLhRM:function(i,o){return i instanceof o}};return r.bxoHC(typeof t,r[e(528)])?r.qoBPA(Xv,t):(r[e(672)](t,IDBTransaction)&&Yv(t),Dh(t,$v())?new Proxy(t,Zo):t)}function zt(t){let e=M,r={ukLqJ:function(o,c){return o instanceof c},KfTOd:function(o,c){return o(c)},JNvSq:function(o,c){return o(c)},ULRdH:function(o,c){return o!==c}};if(r[e(463)](t,IDBRequest))return r[e(615)](Jv,t);if($o[e(1856)](t))return $o[e(1605)](t);let i=r[e(951)](Qv,t);return r[e(1707)](i,t)&&($o[e(948)](t,i),Yo.set(i,t)),i}var Dh,Ih,Ah,Bl,Jo,Ml,$o,Yo,Zo,ss,Th=Ch({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={MopbF:function(r){return r()},UftIE:function(r){return r()},aHWOI:t(1817),yXGHX:t(1262),dyCzK:function(r,i){return r===i},FbLNL:"objectSt"+t(1162),BgHci:function(r,i){return r!==i},awtuq:t(1807),KAQIH:function(r,i){return r!==i},uMyIQ:t(1126),HtBhy:function(r,i){return r instanceof i},oaWmQ:function(r,i){return r===i},FFQhA:function(r,i){return r in i}};Dh=(r,i)=>i.some(o=>r instanceof o),Bl=new WeakMap,Jo=new WeakMap,Ml=new WeakMap,$o=new WeakMap,Yo=new WeakMap,Zo={get(r,i,o){let c=t;if(e[c(1871)]!==e[c(1871)])VMgNcL[c(727)](_0x1af2ea),VMgNcL[c(545)](_0x5433a4);else{if(r instanceof IDBTransaction){if(i===e[c(1242)])return Jo.get(r);if(e[c(1833)](i,e[c(1778)]))return r.objectStoreNames||Ml[c(1605)](r);if(e.dyCzK(i,c(1522)))return e.BgHci(c(1807),e.awtuq)?_0x117b84[c(1733)+c(1162)][1]?void 0:_0x2d84f3[c(1733)+c(1862)](_0x568236[c(1733)+c(1162)][0]):o.objectStoreNames[1]?void 0:o[c(1733)+c(1862)](o[c(1733)+"oreNames"][0])}return zt(r[i])}},set(r,i,o){let c=t;return e[c(1478)](e[c(1215)],e[c(1215)])?this[c(977)+"T"]||this._isMiniWX?this[c(1025)+c(482)+c(1766)]:(this[c(1305)+"er"]||this._isWorker)&&this[c(1611)][c(1201)+c(1815)+c(1021)]?_0x4f4fb7[c(1822)]:!0:(r[i]=o,!0)},has(r,i){let o=t;return e[o(1774)](r,IDBTransaction)&&(e[o(1833)](i,e[o(1242)])||e[o(1805)](i,o(1522)))?!0:e[o(539)](i,r)}},ss=r=>Yo[t(1605)](r)}}),Ph={};function F(t,e){t=t-367;let r=Xo(),i=r[t];if(F.RADyZC===void 0){var o=function(x){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",m="",w="";for(let S=0,_,v,I=0;v=x.charAt(I++);~v&&(_=S%4?_*64+v:v,S++%4)?m+=String.fromCharCode(255&_>>(-2*S&6)):0)v=h.indexOf(v);for(let S=0,_=m.length;S<_;S++)w+="%"+("00"+m.charCodeAt(S).toString(16)).slice(-2);return decodeURIComponent(w)};F.tQrBXH=o,F.HdbqEa={},F.RADyZC=!0}let c=r[0],l=t+c,u=F.HdbqEa[l];return u?i=u:(i=F.tQrBXH(i),F.HdbqEa[l]=i),i}Kv(Ph,{deleteDB:()=>tS,openDB:()=>eS,unwrap:()=>ss,wrap:()=>zt});function eS(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let l=M,u={GzaFK:function(m,w,S,_,v){return m(w,S,_,v)},uFtrX:function(m,w){return m(w)},lUFdF:function(m,w){return m(w)},mTKGE:l(605),zRjce:l(568)+l(480),SqiQg:l(1071)+l(695)},x=indexedDB[l(435)](t,e),h=zt(x);return i&&x[l(988)+"Listener"](u[l(831)],m=>{let w=l;u.GzaFK(i,u[w(1055)](zt,x[w(1851)]),m[w(1736)+"on"],m[w(607)+"on"],u[w(506)](zt,x[w(461)+"ion"]))}),r&&x[l(988)+"Listener"](l(1345),()=>r()),h[l(1732)](m=>{let w=l;c&&m[w(988)+w(752)](u[w(1548)],()=>c()),o&&m["addEvent"+w(752)](u[w(1873)],()=>o())})[l(1845)](()=>{}),h}function tS(t,{blocked:e}={}){let r=M,i=indexedDB["deleteDa"+r(1472)](t);return e&&i.addEventListener("blocked",()=>e()),zt(i).then(()=>{})}function kh(t,e){let r=M,i={wjRER:"readwrite",HsOSW:r(1312),FWrOa:function(x,h){return x instanceof h},JluhN:function(x,h){return x!==h},XSRtt:function(x,h){return x in h}};if(!(i[r(953)](t,IDBDatabase)&&!(e in t)&&typeof e===r(448)))return;if(Vo[r(1605)](e))return Vo[r(1605)](e);let o=e[r(1663)](/FromIndex$/,""),c=i[r(1015)](e,o),l=Oh[r(582)](o);if(!i[r(438)](o,(c?IDBIndex:IDBObjectStore)[r(981)+"e"])||!(l||Lh[r(582)](o)))return;let u=async function(x,...h){let m=r,w=this[m(461)+m(849)](x,l?i[m(1464)]:i[m(1776)]),S=w[m(1522)];return c&&(S=S[m(544)](h.shift())),(await Promise[m(808)]([S[o](...h),l&&w.done]))[0]};return Vo[r(948)](e,u),u}var Lh,Oh,Vo,nS=Ch({"node_modules/idb/build/index.js"(){let t=M,e={BYHNj:function(r){return r()},VSRTn:t(1605),wKKuj:"getKey",AzriG:t(1124),ZUtse:"getAllKeys",fkKwt:"add",DbYHe:t(1648),rslqm:function(r,i){return r(i)}};e[t(705)](Th),e[t(705)](Th),Lh=[e[t(1129)],e[t(983)],e.AzriG,e.ZUtse,"count"],Oh=[t(825),e[t(692)],e[t(1461)],t(1363)],Vo=new Map,e[t(1235)](Zv,r=>({...r,get:(i,o,c)=>kh(i,o)||r[t(1605)](i,o,c),has:(i,o)=>!!kh(i,o)||r[t(1856)](i,o)}))}}),rS={idb:function(t){let e=M,r={CMXpM:function(i,o){return i+o},gykDC:function(i,o){return i+o},TOULN:function(i,o){return i||o},CfHeS:" > ",vmQhs:e(1814)};t[e(623)]=Promise[e(875)]().then(()=>(nS(),Ph))[e(1732)](function(i){let o=e,c={tfwdv:function(l,u){return l(u)},vCpyF:function(l,u){return r[F(1253)](l,u)},ciZgn:function(l,u){return r[F(1481)](l,u)},GGCwo:o(878),yhJIi:function(l,u){return r[o(1497)](l,u)},HdRAA:r[o(453)]};return r[o(1748)]==="HlryD"?c[o(776)](_0x1557c4,c[o(1512)](c[o(1512)](c[o(1083)]("index ou"+o(1310)+o(1515),_0xea6abf),c[o(1108)])+c[o(982)](_0x491418,1)+c[o(1813)],_0x4429dc)):i})}},Rh={};function Bt(t){let e=M,r={KsWnV:function(u,x){return u!==x}},i=(e(889)+"4")[e(609)]("|"),o=0;for(;;){switch(i[o++]){case"0":rS[t](c,c[e(623)],Bt);continue;case"1":if(r[e(1545)](void 0,l))return l[e(623)];continue;case"2":var c=Rh[t]={exports:{}};continue;case"3":var l=Rh[t];continue;case"4":return c.exports}break}}Bt.d=(t,e)=>{let r=F;for(var i in e)Bt.o(e,i)&&!Bt.o(t,i)&&Object[r(1058)+r(726)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Bt.o=(e,r)=>Object[t(981)+"e"]["hasOwnPr"+t(726)][t(434)](e,r)})(),(()=>{let t=M,e={nbEyn:function(r,i){return r!=i},JtlAo:t(492)+"d",shYGX:t(1256),CWeLq:t(1840)+"le"};Bt.r=r=>{let i=t;e[i(1226)](e[i(1684)],typeof Symbol)&&Symbol[i(1077)+i(1078)]&&Object[i(1058)+i(726)](r,Symbol[i(1077)+"Tag"],{value:e[i(524)]}),Object.defineProperty(r,e[i(1745)],{value:!0})}})();var Ce={};(()=>{let t=M,e={TGCDB:function(a,n){return a(n)},uXfeF:function(a,n){return a+n},eNxCf:function(a,n){return a===n},uiksi:t(885),IDgQP:t(1652),bDEFh:function(a,n){return a*n},uLXKV:function(a,n){return a+n},oQInK:function(a,n,s){return a(n,s)},JjzHH:function(a,n){return a(n)},yXAaW:function(a,n){return a===n},UbvdC:"PMCWE",VpEuy:function(a,n){return a(n)},uzkgi:t(452),CGjND:t(1239),bQxsF:function(a,n,s){return a(n,s)},mNAcN:function(a,n){return a(n)},ozOLC:function(a,n){return a|n},EAOcB:function(a,n){return a&n},PQicq:function(a,n){return a<=n},tvmFQ:function(a,n){return a>n},lnQFR:function(a,n){return a<n},nEPLs:"bKoGd",scoyS:function(a,n){return a<n},aMzDq:function(a,n){return a!==n},GaSxe:function(a,n){return a-n},FDliv:"enKcl",RuZhF:function(a,n){return a<n},EmDTL:function(a,n){return a===n},gNedi:function(a,n){return a!==n},RgGJJ:function(a,n){return a||n},vVMJM:t(378),woFve:function(a,n,s){return a(n,s)},HEHeN:function(a,n,s){return a(n,s)},unuWo:function(a,n){return a!==n},lsVwD:function(a,n){return a(n)},FCKCl:function(a,n){return a(n)},bSzhH:function(a,n){return a>>>n},xejsl:function(a,n,s){return a(n,s)},uTqsg:function(a,n){return a(n)},diupJ:function(a,n){return a(n)},tKXXu:function(a,n,s){return a(n,s)},oBLRW:function(a,n){return a===n},tyoAZ:function(a){return a()},vODzU:function(a,n,s,d){return a(n,s,d)},QKpoa:function(a,n,s){return a(n,s)},zQUST:function(a,n){return a(n)},WLGEX:function(a,n){return a!==n},yeLJN:function(a,n,s){return a(n,s)},wXKsi:t(815),QcyOf:function(a,n,s){return a(n,s)},fmjOn:function(a,n){return a(n)},gaRLn:t(1145),naxoC:function(a,n,s){return a(n,s)},RXnTG:function(a,n,s){return a(n,s)},WYolQ:function(a,n){return a(n)},feBCe:function(a,n){return a===n},tEDvX:t(1452),oFxss:function(a,n,s){return a(n,s)},Ejxmw:function(a){return a()},QRoVX:function(a,n){return a(n)},PZoVs:function(a,n,s){return a(n,s)},dnMEr:function(a,n,s){return a(n,s)},iDqYX:function(a,n){return a!==n},ZChVH:function(a,n){return a!==n},aRQgF:function(a,n,s){return a(n,s)},MGLBN:function(a,n,s){return a(n,s)},YfETU:function(a,n){return a===n},HHLPN:t(1764),ZTcSN:function(a,n){return a!==n},TfjDL:t(797),pRSLx:function(a,n,s){return a(n,s)},EjiuN:function(a,n){return a(n)},bNHYk:function(a,n){return a(n)},wDSbu:function(a,n){return a(n)},Xwxwy:function(a,n){return a(n)},kSwLy:function(a,n,s){return a(n,s)},vQAPr:function(a,n){return a(n)},jHhhM:function(a,n){return a&n},zCoWS:"Missing required field: SeqID",tVlDz:t(1309)+t(1784)+t(1089)+"LogID",KyQFr:function(a,n){return a===n},WhRNI:t(1309)+"required"+t(1089)+t(1875),lXOEr:"Missing required"+t(1089)+"method",bygeI:function(a,n){return a+n},EXogt:function(a,n){return a&n},MnDkn:function(a,n){return a(n)},rVxMZ:function(a,n,s){return a(n,s)},vDwkd:t(1347)+"ented ty"+t(1763),xHUBT:function(a,n){return a+n},slOUI:function(a,n,s){return a(n,s)},uNxHO:function(a,n){return a>>n},PRkuN:function(a,n){return a!==n},qzsfk:function(a,n){return a&n},CXqEk:function(a,n){return a|n},laGVb:function(a,n){return a<<n},KFJTK:function(a,n){return a&n},ocqNn:function(a,n){return a&n},BoNub:function(a,n){return a<n},SvWlv:function(a,n){return a!==n},nwJUt:t(720),Mtmfp:function(a,n){return a===n},HuLeN:t(758),jDUCm:function(a,n){return a>n},GQMeT:function(a,n){return a+n},OAMbc:"Skip past limit",LjliS:function(a,n){return a>=n},uzbtg:function(a,n){return a+n},kYAni:function(a,n){return a*n},lbNae:t(1352),ngIqs:"Read pas"+t(1206),YrPKK:function(a,n,s){return a(n,s)},CGING:function(a,n){return a===n},lHrgt:function(a,n){return a>=n},zvzpu:function(a,n){return a+n},tsNVh:function(a,n){return a+n},TbonK:function(a,n){return a!==n},ANOuU:function(a,n){return a&n},qHBLu:function(a,n){return a|n},TkvXJ:function(a,n){return a<<n},hSjbA:function(a,n){return a&n},tSxCN:function(a,n){return a==n},VRadr:function(a,n){return a>=n},EBBrj:function(a,n){return a+n},lqBxp:function(a,n){return a|n},jAOvy:function(a,n){return a<<n},TYQpB:function(a,n){return a|n},stEaO:function(a,n){return a&n},MNcJm:function(a,n){return a>=n},cOflU:function(a,n){return a<=n},NXkiJ:function(a,n){return a>=n},ISxxH:function(a,n){return a+n},KMHUL:function(a,n){return a+n},GtQCu:function(a,n){return a!==n},eRUia:function(a,n){return a|n},dZnNX:function(a,n){return a|n},EQVjH:function(a,n){return a<<n},Ilron:function(a,n){return a&n},wPuaR:function(a,n){return a&n},FmqBm:function(a,n){return a&n},ooGOf:function(a,n){return a>n},cSqkE:function(a,n){return a+n},LCmXw:function(a,n){return a+n},xVcZm:function(a,n){return a&n},RCOvc:t(1844)+t(377)+"e",xSxVS:function(a,n){return a&n},AyQGk:function(a,n){return a+n},IiHyn:function(a,n,s){return a(n,s)},CHUPM:function(a,n){return a<n},RMSbK:function(a,n){return a>=n},JHTqB:function(a,n){return a<=n},NJwdd:function(a,n){return a<n},HYMih:function(a,n){return a+n},gfIbD:function(a,n){return a>=n},vPMJN:function(a,n){return a+n},VDhGp:function(a,n){return a|n},LezSV:function(a,n){return a&n},DIkyY:t(1397),lvHzv:function(a,n){return a>>n},pgvPV:"sPXuw",OLwmF:t(1509),wAbCC:function(a,n){return a|n},XxBhQ:function(a,n){return a+n},zksve:function(a,n,s){return a(n,s)},OoXFy:function(a,n){return a(n)},OMSDF:function(a,n){return a<n},nbLyj:function(a,n){return a<<n},XdImz:function(a,n){return a!==n},sbyeK:t(1885),sFnQw:function(a,n){return a>=n},gJafn:function(a,n){return a-n},SLrqv:function(a,n){return a<n},GMOOU:function(a,n){return a&n},RjKIA:function(a,n){return a<<n},AXrWO:function(a,n){return a&n},lQTgC:function(a,n){return a&n},WMvzD:function(a,n){return a&n},QqAlI:function(a,n){return a&n},fNnzP:function(a,n){return a&n},yKgIc:function(a,n){return a&n},XssxP:function(a,n){return a<<n},LVVev:function(a,n){return a&n},QjOdP:function(a,n){return a<<n},fUIrZ:function(a,n){return a<<n},DWCXh:function(a,n){return a|n},lBjtd:function(a,n){return a>>>n},jgcIG:function(a,n){return a<<n},EcBnF:function(a,n){return a>>>n},iPdhh:function(a,n){return a<n},HVvGw:function(a,n){return a<n},TKrPy:function(a,n){return a<n},HkSDk:function(a,n,s){return a(n,s)},uOzXB:function(a,n){return a+n},oqmkE:function(a,n){return a!==n},EduPC:function(a,n){return a|n},tVsfY:function(a,n){return a&n},oyXbj:function(a,n){return a+n},WfeIV:function(a,n){return a&n},SCIln:function(a,n){return a|n},dXkWV:function(a,n){return a>>>n},Cdsqw:function(a,n){return a+n},JrfAa:function(a,n){return a!==n},IHtlX:function(a,n){return a>>>n},jVHkE:function(a,n){return a&n},pOxwN:function(a,n){return a>>>n},Upmhw:function(a,n){return a!==n},oppdm:function(a,n){return a|n},WECJG:function(a,n){return a&n},rKFRP:function(a,n){return a+n},ghRwq:function(a,n){return a|n},bVaTm:function(a,n){return a>>>n},CmEIG:function(a,n){return a&n},POKGC:function(a,n){return a|n},crRMx:"close",GqrTm:function(a,n){return a!==n},qNlAk:t(472),cZdGc:function(a,n){return a(n)},ZnXlt:function(a,n){return a!==n},PZzvr:function(a,n){return a|n},rQGMr:t(1343)+"reason",XphsH:t(1263),NvDIZ:"&jscallb"+t(1717)+t(920)+"P",mdmbi:function(a,n){return a!==n},nwRCY:"DiVHu",KoGVl:function(a,n){return a|n},avjcX:function(a,n){return a<<n},gzYtU:function(a,n){return a<<n},xRvjS:function(a,n){return a<<n},IbhDq:t(1427),TMXMj:function(a,n){return a!==n},KiFWm:t(1796),lafGz:function(a,n){return a|n},sIyLd:function(a,n){return a<<n},vdcKk:function(a,n){return a<<n},mQvod:function(a,n){return a<<n},jNInR:function(a,n){return a<<n},voBUX:function(a,n){return a<<n},ygPXD:function(a,n){return a<<n},JLodX:function(a,n){return a>>>n},XXKUv:function(a,n){return a|n},wdYOa:function(a,n){return a<<n},xsZhE:function(a,n){return a<<n},CVNQC:function(a,n){return a&n},isoTI:function(a,n){return a>>>n},ASIGi:function(a,n){return a&n},LTmdu:function(a,n){return a>>>n},DrJMH:function(a,n){return a>>>n},zxcMd:function(a,n){return a%n},hCZjl:function(a,n){return a/n},JFkSj:function(a,n){return a+n},iiRSh:function(a,n){return a>>>n},hEvTu:function(a,n){return a>>>n},uLFMe:function(a,n){return a===n},yrRLL:function(a,n){return a&n},FEiLC:function(a,n){return a>>>n},zNqtX:function(a,n){return a+n},gqQqj:function(a,n){return a>>>n},nGNTV:function(a,n){return a+n},teLkq:function(a,n){return a+n},cDatK:function(a,n){return a<<n},zEILA:function(a,n){return a<<n},ZjQrg:function(a,n){return a===n},wDQSk:function(a,n){return a===n},kahYK:function(a,n){return a===n},FyQXf:"HUoKo",tlzLs:function(a,n){return a===n},BgFTo:t(1171),cwKqx:function(a,n){return a&n},IUotP:function(a,n){return a>>>n},SdQCS:function(a,n){return a>>>n},hOgGm:t(701),CZxha:"pagehide",FfpIi:t(804),IhNmB:function(a,n){return a>>>n},lYGWZ:function(a,n){return a&n},nPhCb:function(a,n){return a>>>n},XgLYG:function(a,n){return a&n},HPZKU:function(a,n){return a>>>n},TrKPW:t(939)+"5|2",Wlesk:t(1161)+t(742),rHqJD:"NATIVE_ERROR",ZBTwt:t(852)+t(671),PURdE:t(710)+t(1625)+"R",iQrVs:"OPEN_ERROR",Ntmro:function(a,n){return a===n},KhMnD:"xcrmZ",eGZOk:function(a,n){return a===n},pmYyw:t(1687),wynnX:function(a,n){return a!==n},CveOR:"ItZWF",qpyyE:t(1603),dtFsL:t(1530),fnFZw:"VEWeb",SlJxV:function(a,n){return a===n},xJXrj:function(a,n){return a instanceof n},cZhYT:function(a,n){return a+n},AIuyE:t(570)+"d error.",yNxzE:function(a,n){return a+n},jqDWT:function(a,n){return a+n},vIsgO:function(a,n){return a<<n},waXuA:function(a,n){return a<<n},xoJLl:function(a,n){return a|n},fKamL:function(a,n){return a<<n},DiPZG:function(a,n){return a<<n},JRjtW:t(1838),RiaCS:function(a,n){return a<n},gznfx:function(a,n){return a===n},HNVJA:function(a,n,s){return a(n,s)},rPyJq:"error",cXVrH:t(435),NWfsZ:function(a,n,s){return a(n,s)},WXbYP:t(612),gsknv:function(a,n){return a&n},zZAma:function(a,n){return a&n},uIDuA:function(a,n){return a&n},CvGZT:function(a,n){return a>>>n},Oubhz:function(a,n){return a>>>n},XRAke:t(414),jkcDu:"zajSO",njpeH:function(a){return a()},gXFfl:function(a,n){return a===n},jrCIk:t(1546),ngurf:t(1691),ImsAr:function(a,n){return a||n},vyIji:function(a,n){return a||n},Qwcmy:function(a,n){return a!=n},xxDSR:"undefined",HfeoR:function(a,n){return a||n},zyTaM:function(a,n){return a!=n},OOoZy:function(a,n){return a(n)},IQrbU:function(a,n){return a<n},yoVTa:function(a,n){return a<n},uEUsO:function(a,n){return a&n},NNBYF:function(a,n){return a-n},PfJqJ:function(a,n){return a<=n},wJAND:function(a,n){return a<n},VZOhI:function(a,n){return a|n},VOpRq:function(a,n){return a|n},XwlRb:function(a,n){return a&n},mEiJT:function(a,n){return a&n},NbnNy:function(a,n){return a&n},xcHaS:function(a,n){return a>=n},cdKZb:function(a,n){return a|n},keKUE:function(a,n){return a<<n},qfDuT:function(a,n){return a&n},efIyN:function(a,n){return a<n},ptzDT:function(a,n){return a|n},mZjhJ:t(930)+t(1102),ImVBJ:function(a,n){return a>>n},WmgMS:function(a,n){return a|n},VqhEa:function(a,n){return a&n},QHPmC:function(a,n){return a|n},BRERP:function(a,n){return a>>n},upKYP:function(a,n){return a|n},mHhcK:function(a,n){return a>>n},eCyEZ:function(a,n){return a|n},gdOME:function(a,n){return a&n},qkcxg:function(a,n){return a-n},sukSb:function(a,n){return a==n},PdWyZ:"string",qzAyD:function(a,n){return a(n)},EzMfV:function(a,n){return a!=n},lXQaI:function(a,n){return a!=n},gCSZG:t(424)+t(1549),mHKDS:function(a,n){return a+n},SJilP:t(1205),Uylih:"VvFTx",TgAva:function(a,n){return a!==n},FViBF:t(890),iLVSV:t(791),Kbbsv:function(a,n){return a(n)},MHDyg:function(a,n){return a!==n},tRUqN:t(1117),CiDYt:function(a,n){return a!==n},kSeYs:t(760),bSLEz:function(a,n,s){return a(n,s)},BTtZu:function(a,n){return a>>>n},ajzNN:function(a,n){return a>>>n},nSreH:function(a,n){return a&n},GXtNt:function(a,n){return a>>>n},RkjqG:function(a,n){return a+n},GfTJG:function(a,n){return a+n},Wxkug:t(1373),mBDWG:"vEULk",NqStk:t(1706),tFgVM:t(1262),irpxG:function(a,n){return a===n},CGjVD:t(778),yGHGW:function(a,n){return a===n},ixASB:t(565),NeTrr:function(a,n){return a!==n},HgHkf:t(712),DYSIJ:function(a,n){return a||n},aAEru:function(a,n){return a||n},cRAMP:"muBBD",NQTam:t(743),uiXuI:t(1170),syjTp:t(1499),gMSDP:"qos",rqdql:t(1539)+"id",TjRLf:t(416),zDWmZ:function(a,n){return a===n},ODkEG:t(643),SfLPI:"kQUSV",KKUvw:t(1450),nauTi:function(a,n){return a!==n},KVzca:"dJRKH",WsDMy:function(a,n){return a===n},ufpCy:t(431),GLAQR:function(a,n,s){return a(n,s)},uyKnI:function(a,n){return a!==n},NhKkQ:t(1298),DUOAp:t(1486),eqOEi:function(a,n){return a(n)},AxuJc:function(a,n){return a!==n},pHWDp:t(702),SNTaJ:t(1712),zsqMn:t(902)+"er_qos",iKFMK:function(a,n,s,d){return a(n,s,d)},cdFad:t(902)+t(566)+"ck",OaAvO:function(a,n,s,d){return a(n,s,d)},hhlWe:"x_fronti"+t(1147)+"k",UIuiS:function(a,n,s){return a(n,s)},jygiv:function(a,n,s,d){return a(n,s,d)},ltwWx:t(1237),copts:function(a,n,s,d){return a(n,s,d)},wFkgX:function(a,n){return a&&n},SGKeq:t(641),pGxiI:t(1354),CwenK:function(a){return a()},oOmho:function(a,n){return a!==n},sLrgl:t(1690),DgCmf:"JRXem",RlCqp:function(a){return a()},NXDSV:t(568)+t(480),hAjAf:t(823)+t(1772)+"et=utf-8",rOTgG:"applicat"+t(1549)+";charset"+t(1730),CRGag:"binary",ubXkv:t(803),xfGOA:function(a,n){return a<n},gEocF:function(a,n){return a>n},PuSMW:function(a,n){return a(n)},RVijE:function(a,n){return a>n},Nzugj:function(a,n){return a+n},fakam:function(a,n){return a(n)},TQoCe:function(a,n){return a&n},Hnapn:function(a,n){return a||n},kIwgH:t(588),NmLNK:t(1112),YXNZo:function(a,n){return a+n},rmEFy:t(1203)+t(1310)+t(1515),cNcYx:t(878),kDdFL:function(a,n){return a>=n},iFhsj:t(764),VyxhO:function(a,n){return a+n},jgbdz:function(a,n,s){return a(n,s)},usZRw:function(a,n){return a<<n},eGkvC:t(635)+"0",JNoLm:function(a,n,s,d){return a(n,s,d)},qRMcw:function(a,n){return a+n},BWmUw:function(a,n){return a+n},QHmDe:function(a,n){return a+n},ZAePT:function(a,n){return a+n},bZPmv:function(a,n){return a<<n},Xerpw:function(a,n){return a+n},gePWN:function(a,n){return a+n},KamZq:function(a,n){return a+n},HWSsf:function(a,n){return a>>>n},UZGWP:function(a,n){return a>>>n},HACGK:function(a,n){return a>>>n},lujyu:function(a,n){return a+n},BSncz:function(a,n){return a+n},ChMAS:t(1554),SjKnc:function(a,n){return a&n},sNMib:function(a,n){return a&n},fbGGg:function(a,n){return a<n},cNTRz:function(a,n,s,d){return a(n,s,d)},cUrke:function(a,n){return a>>>n},mBOrp:function(a,n){return a&n},DtuWc:function(a,n){return a<<n},WPgKu:function(a,n){return a|n},FoJvR:function(a,n){return a!==n},PemYm:t(1577),Allkg:function(a,n){return a(n)},BLRBf:t(1329)+t(767),VBTBT:"header",aGirP:function(a,n,s,d){return a(n,s,d)},mGNiq:t(1465)+t(1823),TqVps:function(a,n,s,d){return a(n,s,d)},YqzFE:function(a,n,s,d){return a(n,s,d)},KZPTg:"curvalue",AxwWq:"cursor_f"+t(398),SHSdO:function(a,n,s,d){return a(n,s,d)},KOpLF:function(a,n,s){return a(n,s)},kHtpV:function(a,n){return a===n},Bjcjf:"VjtFY",MRKbs:function(a,n,s){return a(n,s)},nNEuz:t(629)+t(1005),WqBCT:t(1850)+"rValues",wxEQx:t(1330),UDpPa:t(1770),FTzvI:function(a,n,s,d){return a(n,s,d)},kzPSZ:t(1692),BBAmS:function(a,n){return a(n)},GKfyE:t(894),vpySB:t(387)+t(1024)+"s",GOOWY:t(387)+t(841)+"t",mXiiv:function(a,n){return a===n},twPGH:t(1453),uiZbE:t(421),WsLtQ:function(a,n){return a===n},HfPfY:"nRptG",oxWHj:t(1726),gTqHB:t(441),ugGKj:t(1626),euFYB:"x_fronti"+t(1709),QGQXL:function(a,n,s){return a(n,s)},CYpGh:function(a,n,s,d){return a(n,s,d)},yiKLf:t(840)+"s",ApXcx:function(a,n,s){return a(n,s)},xnniE:t(1527)+t(771)+"e",lkrSg:function(a,n){return a(n)},ZeNOt:function(a,n,s){return a(n,s)},WrXag:t(1527)+"rsor_value",jFnux:function(a,n){return a>n},xLtUF:function(a,n){return a>n},fWqeR:t(1861),pgygj:function(a){return a()},CiOuV:function(a){return a()},GdHsk:function(a){return a()},fvZyB:function(a,n){return a===n},cLWnC:function(a,n){return a===n},ViaCY:function(a,n,s){return a(n,s)},pvKSe:function(a){return a()},GsUwB:function(a){return a()},hJArE:function(a,n){return a(n)},csTWC:function(a,n){return a(n)},vGRpU:function(a,n){return a!==n},MQFtU:function(a){return a()},hVcNT:function(a,n,s,d){return a(n,s,d)},xVHaO:function(a,n){return a||n},awiVq:function(a,n){return a!==n},yaxVt:t(1190),ZSUUx:"uvTlw",Mesie:function(a,n,s){return a(n,s)},tPoFE:t(826),vrtki:function(a,n){return a===n},nWEzI:t(745)+"fer",xVkMC:t(860),knPJp:t(769)+t(1591)+t(375),pleBd:function(a,n){return a(n)},vBLdQ:function(a,n){return a===n},egteB:t(862),SVoKt:t(1632)+"t",YTIqs:"stop imm"+t(966)+t(925)+"ct",oEgxh:t(1454),PFXpB:t(1744),KDotG:function(a,n){return a!==n},QfRzn:t(659),NRKpB:"KCxEx",LcnXV:t(532),zomYr:t(1855),lDdom:t(437),DBgaX:t(976),lkpry:function(a,n){return a!==n},HgsxM:function(a,n){return a==n},BzJfy:t(1138),NZApg:t(1192),ofdqn:t(854),VOYrS:t(1346),wTSmY:function(a,n){return a||n},eMxaV:"please p"+t(845)+t(1413)+t(1783)+t(562),wcUca:function(a,n,s){return a(n,s)},VKXwK:t(645),LQzjl:"fws_1.0.0",lHKRn:function(a,n){return a>>>n},sxkfs:function(a,n){return a<n},ncTrS:function(a,n){return a|n},iMMAE:function(a,n){return a<<n},utFVF:function(a,n){return a<<n},dXYba:function(a,n){return a&n},HnPbZ:function(a,n){return a>n},wkPPC:function(a,n,s,d){return a(n,s,d)},bRyMi:function(a,n){return a+n},zNnDp:function(a,n){return a+n},EGIfG:function(a,n){return a+n},gEjbm:function(a,n){return a&n},EPofC:"uhJgN",LOGHy:t(1536),EryGy:function(a,n){return a!==n},BIDni:t(1540),zmCWN:function(a,n,s){return a(n,s)},RnWGX:function(a,n,s){return a(n,s)},bSeLi:"FRONTIER>",GLkck:function(a,n,s){return a(n,s)},JGoQY:function(a,n,s){return a(n,s)},aotUu:t(945)+t(1677)+"reconnec"+t(1223)+t(1746),yUDoV:t(468),twVjY:t(558),mgLbC:t(1042)+" try rec"+t(1514)+"g",aezzb:t(1581),NUrWJ:t(889)+"4",WxaBf:t(1280),DswuS:"lYljH",gXLxN:function(a,n,s){return a(n,s)},zGSIF:function(a,n,s){return a(n,s)},GTUWC:"going aw"+t(753)+t(1810)+t(369),rrFCg:t(625),TvipZ:t(502),YHLCs:t(1819),erqTc:function(a,n){return a+n},lrcTB:function(a,n){return a===n},YilGR:t(868),wloNA:t(667),Comlm:function(a,n){return a(n)},DKDaI:function(a,n){return a<<n},zImAY:function(a,n){return a&n},mGiub:t(1399),EtTPH:t(1254),OOWIO:t(573)+t(1897)+t(717)+t(510)+"ed",Khryt:function(a,n){return a===n},hcWaV:t(573)+t(1118)+t(389),dFZdG:t(769)+"rovide a"+t(1045)+"ata, dat"+t(1479)+t(1325)+t(912)+t(1342)+t(1202),kfJBK:"number",dINST:function(a,n){return a instanceof n},opZdY:function(a,n){return a(n)},dKqku:t(1172),AGAGj:function(a,n){return a<n},XKaED:function(a,n){return a>>n},XqnEy:function(a,n){return a&n},AlbCX:function(a,n){return a|n},UCarQ:function(a,n){return a|n},UQAYi:function(a,n){return a>>n},EuTcD:function(a,n){return a!==n},EyuWQ:"manual r"+t(1316)+t(844),rXcyl:t(876),BQhEX:t(986),UCvzk:function(a,n){return a+n},aVefE:t(1267),RjHhJ:t(1238)+"2",SiVpH:function(a,n){return a(n)},vHexN:function(a,n){return a===n},blJLo:function(a,n){return a(n)},cHBZN:"\0\0\0\0\0\0\0\0",ETuPA:function(a,n){return a*n},KMONz:function(a,n){return a!=n},SqezN:t(1559),gKOTw:function(a,n){return a!=n},YFVHR:function(a,n){return a===n},EzyOt:t(405),wkSmI:function(a,n){return a===n},fDimy:function(a,n){return a!=n},NFEOg:function(a,n){return a!=n},nEAwO:function(a,n){return a!=n},smLNe:function(a,n){return a!=n},hAVAg:function(a,n){return a!=n},rWzRl:t(1333)+"dWorkerG"+t(483)+"pe",awKSc:t(578)+t(1178)+t(371),oQhQE:function(a,n){return a===n},aVeWF:function(a,n){return a!=n},vMmLo:function(a,n){return a===n},kItsc:function(a,n){return a!=n}};Bt.r(Ce),Bt.d(Ce,{FWS:()=>gg,CustomErrorEvent:()=>rd,createCloseEvent:()=>gt,ReconnectEvent:()=>nd,createErrorEvent:()=>ct,decodedFrame:()=>en,createOpenEvent:()=>ld,CustomCloseEvent:()=>id,createReconnectEvent:()=>ga,FrontierMessageEvent:()=>od,encodeFrame:()=>Ft,createMessageEvent:()=>cd,OpenEvent:()=>ad,ErrorCode:()=>nn,Event:()=>tr,MessageEvent:()=>sd});let r="";function i(a=""){let n=t,s="02",d=""+Date[n(1344)](),f=r||(r=e[n(462)](x,a)),g=Math[n(904)]()[n(1077)](16)[n(433)](-6);return e[n(927)](e.uXfeF(e[n(927)](s,d),f),g)}function o(){let a=t;if(e[a(485)](e.uiksi,e[a(1825)]))this._ws&&this[a(1704)].send(_0x1ee4a7),this[a(406)+a(553)][_0x3bf26e]=null;else return e[a(927)](e.bDEFh(1e4,Date[a(1344)]()),Math[a(883)](1e4*Math[a(904)]()))}function c(a){let n=t;return e[n(927)](e[n(462)](Array,8)[n(1887)]("0"),parseInt(a,10).toString(2))[n(433)](-8)}function l(a){let n=t;return e[n(1832)](e[n(462)](Array,4).join("0"),e[n(1307)](parseInt,a,2).toString(16))[n(433)](-4)}function u(a){let n=t,s={QqyCy:function(d,f){return e[F(1689)](d,f)},UvuCk:function(d,f){return e.uLXKV(d,f)}};if(e.yXAaW(n(1026),e[n(460)])){let d=a[n(609)](/\./).map(E=>c(E)),f=[];return f[0]=l(e[n(927)](d[0],d[1])),f[1]=e[n(848)](l,d[2]+d[3]),[e.uzkgi,e.uzkgi,e.uzkgi,e[n(874)],e[n(874)],e[n(1293)],f[0],f[1]].join("")}else{let d=s[n(721)](_0x1183e2,_0x3e9b9f),f=_0x1428b0[n(1166)];return _0x3195e4[n(1166)]=s[n(1842)](_0x1a2b8b[n(1715)],d),f}}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}/[n(1526)](a),d=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[n(1526)](a);return s?e.TGCDB(u,a):d?e[n(1689)](h,a):n(397)+n(397)+"00000000"+n(397)}function h(a){let n=t,s={jWvuA:function(A,O,N){return e[F(1561)](A,O,N)},ugOlY:function(A,O,N){return A(O,N)},AMUzO:function(A,O){return e[F(1550)](A,O)},uhheu:function(A,O){return e[F(1374)](A,O)},XNroU:function(A,O){return A<<O},izqRW:function(A,O){return e[F(1659)](A,O)},HjQlD:function(A,O){return e[F(1062)](A,O)}},d="",f=[],g=0,E=0,y=!0,p=e.uzkgi;if(e[n(495)](a[n(555)]("::"),-1)){let A=a.split("::");for(let N=0;e[n(1858)](N,A[n(386)]);N++){let j=A[N];if(e.tvmFQ(j[n(555)](":"),0))if(e[n(485)](e[n(587)],e[n(587)])){let q=j.split(":");y&&(g=q.length),E+=q[n(386)];for(let te=0;e[n(1227)](te,q[n(386)]);te++)if(e[n(1608)](4,q[te][n(386)])){let Ye=p[n(713)+"g"](0,e[n(664)](4,q[te].length)),xe=Ye[n(1063)](q[te]);f[n(1664)](xe)}else f[n(1664)](q[te]);y=!1}else s[n(567)](_0x201bdc,_0x4aff65,96),s.ugOlY(_0x4869ed,_0x15d9f1,s[n(873)](_0x1ba95b,_0xdaa940));else if(e[n(493)](n(1169),e[n(1218)]))_0x537ba4=s[n(755)](s.uhheu(s[n(1541)](15&_0x3264b1,12),(63&_0xdd4e7a)<<6),s.izqRW(63,_0x58e4fb)),_0x331378<2048||_0x3d6da8>=55296&&s[n(1302)](_0x2868f1,57343)?_0x472beb+=_0x5cc10f:(_0x28751a+=s[n(873)](_0x563578,_0x169001),_0x497be8+=2);else{if(j[n(386)]!==4){let q=p[n(713)+"g"](0,e[n(664)](4,j[n(386)])),te=q.concat(j);f[n(1664)](te)}else f[n(1664)](j);y&&(g+=1),E+=1,y=!1}}let O="";for(let N=0;e.scoyS(N,8-E);N++)O=O[n(1063)](p);for(let N=0;e.RuZhF(N,f[n(386)]);N++)e.EmDTL(N,g)&&(d=d[n(1063)](O)),d=d[n(1063)](f[N]);return d}{let A=a.split(":");for(let O=0;O<A[n(386)];O++){let N=A[O];if(e.gNedi(4,A[O][n(386)])){let j=p.substring(0,e[n(664)](4,A[O][n(386)])),q=j[n(1063)](N);d=d[n(1063)](q)}else d=d[n(1063)](N)}return d}}function m(a,n){let s=t,d=a[s(1557)];if(e[s(1245)](void 0,d))if(e[s(1608)](e[s(1569)],e.vVMJM)){let g=this[s(1208)][s(1756)](this[s(1735)]),E=_0x33fca7.parse(e[s(744)](g,"{}"));return E[_0x30e96d||_0x338de7[this[s(1455)]]]=_0x8e4237,this._qosDB[s(1895)](this[s(1735)],_0x3353a3[s(665)+"y"](E)),_0xc14963||_0x56b9b1[this[s(1455)]]}else e[s(1644)](ge,n,10),e[s(1811)](G,n,d);let f=a[s(1180)];e[s(1445)](void 0,f)&&(ge(n,18),G(n,f))}function w(a){let n=t,s={};e:for(;!e[n(455)](V,a);){let d=e[n(1047)](pe,a);switch(e[n(1439)](d,3)){case 0:break e;case 1:s[n(1557)]=e[n(1295)](D,a,e[n(909)](pe,a));break;case 2:s[n(1180)]=D(a,e.diupJ(pe,a));break;default:e[n(768)](R,a,e[n(1659)](7,d))}}if(s[n(1557)]===void 0)throw new Error(n(1309)+n(1784)+n(1089)+n(1557));if(e.oBLRW(void 0,s.value))throw new Error(n(1309)+n(1784)+n(1089)+n(1180));return s}function S(a){let n=t,s=e[n(1727)](C);return _(a,s),e[n(909)](B,s)}function _(a,n){let s=t,d={ueRBl:function(xe,lt){return e[F(1463)](xe,lt)}},f=a[s(1337)];e[s(969)](void 0,f)&&(e.yeLJN(ge,n,8),pt(n,f));let g=a.LogID;if(e[s(1608)](void 0,g))if(e.unuWo(e.wXKsi,e[s(1186)])){let xe=0,lt=[];for(;e[s(593)](xe,_0x1bb490[s(1386)+"th"]);){let{offset:ei}=e[s(1561)](_0x1179c3,_0x141534,xe);xe=ei;let ir={cursor_name:"",cursor:0,service:0},{value:Sa,offset:ti}=e[s(1307)](_0x3d1921,_0x43052d,xe);ir[s(1875)]=Sa,xe=ti;let{value:fs,offset:ni}=e.tKXXu(_0x2c1cff,_0x1cf5de,xe);xe=ni,ir["cursor_n"+s(1005)]=e[s(865)](_0xf5efde,_0x5334db,xe,e[s(927)](xe,fs)),xe+=fs;let{value:ri,offset:mg}=e[s(1391)](_0x44beee,_0x337159,xe);ir[s(1868)]=ri[s(847)](),xe=mg,lt[s(1664)](ir)}return lt}else e[s(1579)](ge,n,16),pt(n,g);let E=a[s(1875)];e[s(1445)](void 0,E)&&(ge(n,24),pt(n,e[s(1109)](P,E)));let y=a[s(1096)];if(e[s(1608)](void 0,y))if(e.yXAaW(e[s(940)],"eZxek"))e[s(733)](ge,n,32),e.RXnTG(pt,n,e[s(577)](P,y));else{if(_0x48967f instanceof _0x15279f)return _0x4a90a6(_0x35bda9);if(_0x31b2ee[s(1856)](_0xba504))return _0x5c97b4.get(_0x2a2e04);let xe=TSeHEU.ueRBl(_0x1862ca,_0x1f62db);return xe!==_0x3c1a3f&&(_0x41f142[s(948)](_0x9a7a96,xe),_0x4c0725.set(xe,_0x2c1fee)),xe}let p=a[s(1219)];if(e[s(1245)](void 0,p))for(let xe of p)if(e[s(1621)](e.tEDvX,e[s(1867)])){e[s(1434)](ge,n,42);let lt=e[s(1257)](C);m(xe,lt),ge(n,lt[s(1166)]),K(n,lt),e.QRoVX(L,lt)}else _0x32255a[s(1705)][s(656)+s(1110)](_0x42e3bb);let A=a[s(1846)+s(817)];A!==void 0&&(e.PZoVs(ge,n,50),e.dnMEr(G,n,A));let O=a[s(1660)+s(1889)];e[s(613)](void 0,O)&&(e[s(1391)](ge,n,58),G(n,O));let N=a[s(775)];e[s(1622)](void 0,N)&&(e.tKXXu(ge,n,66),e[s(1613)](ge,n,N[s(386)]),e.MGLBN(oe,n,N));let j=a.LogIDNew;e.unuWo(void 0,j)&&(e[s(1157)](e[s(1056)],s(1764))?(e[s(1391)](ge,n,74),G(n,j)):(_0x5e89f7=_0x132808.charCodeAt(_0xc8c773),e[s(1858)](_0x20348d,128)?_0x5c1bd0+=1:_0x57afff<2048?_0x4f1751+=2:e.EAOcB(64512,_0x1c4e52)===55296&&e[s(1659)](64512,_0x134f49[s(741)+"At"](e[s(927)](_0xe2b206,1)))===56320?(++_0x1e020b,_0x4436c8+=4):_0x137294+=3));let q=a["serverTi"+s(782)];e[s(1622)](void 0,q)&&(e[s(768)](ge,n,82),e[s(1811)](G,n,q));let te=a[s(1654)];e[s(1622)](void 0,te)&&(e[s(1613)](ge,n,90),e[s(768)](G,n,te));let Ye=a.frameType;e[s(1150)](void 0,Ye)&&(e[s(979)]===e[s(979)]?(e.aRQgF(ge,n,96),e[s(932)](pt,n,e.EjiuN(P,Ye))):(_0x4f981a(_0x4d0c9e,10),e.bQxsF(_0x5718f2,_0x1f1f0a,_0x430f32)))}function v(a){return e[t(1047)](I,z(a))}function I(a){let n=t,s={};e:for(;!e.JjzHH(V,a);){let d=pe(a);switch(e[n(1439)](d,3)){case 0:break e;case 1:s[n(1337)]=It(a,!0);break;case 2:s[n(1016)]=It(a,!0);break;case 3:s[n(1875)]=e.WYolQ(pe,a);break;case 4:s[n(1096)]=e[n(1550)](pe,a);break;case 5:{let f=e[n(1870)](T,a);(s[n(1219)]||(s[n(1219)]=[])).push(w(a)),a.limit=f;break}case 6:s[n(1846)+n(817)]=D(a,pe(a));break;case 7:s.payloadType=e[n(1434)](D,a,e.lsVwD(pe,a));break;case 8:s.payload=e[n(1434)](se,a,e[n(1128)](pe,a));break;case 9:s[n(907)]=e[n(530)](D,a,e[n(884)](pe,a));break;case 10:s[n(370)+"ming"]=e.PZoVs(D,a,e[n(918)](pe,a));break;case 11:s[n(1654)]=e[n(633)](D,a,e[n(1859)](pe,a));break;case 12:s[n(481)+"e"]=e[n(462)](pe,a);break;default:R(a,e[n(773)](7,d))}}if(e[n(1157)](void 0,s[n(1337)]))throw new Error(e.zCoWS);if(s[n(1016)]===void 0)throw new Error(e.tVlDz);if(e.KyQFr(void 0,s[n(1875)]))throw new Error(e[n(972)]);if(e[n(485)](void 0,s[n(1096)]))throw new Error(e[n(1191)]);return s}function T(a){let n=t,s=pe(a),d=a[n(1166)];return a[n(1166)]=e[n(1396)](a[n(1715)],s),d}function R(a,n){let s=t;switch(n){case 0:for(;e[s(1525)](128,e[s(1022)](ee,a)););break;case 2:e[s(1391)](J,a,pe(a));break;case 5:J(a,4);break;case 1:e[s(1553)](J,a,8);break;default:throw new Error(e[s(1477)]+n)}}function P(a){let n=t,s={NGXiU:function(d,f){return e.xHUBT(d,f)},oBrSM:function(d,f){return e[F(1022)](d,f)},bUkmE:function(d,f,g){return e[F(1152)](d,f,g)}};return n(465)!=="emZgZ"?(a|=0,{low:a,high:e.uNxHO(a,31),unsigned:a>=0}):NtofLC[n(1384)](NtofLC[n(696)](_0x315eb2,8)[n(1887)]("0"),NtofLC.bUkmE(_0x2167e4,_0x2dbe3e,10)[n(1077)](2))[n(433)](-8)}let b=[];function C(){let a=t;if(e[a(1075)](a(812),e[a(518)])){let n=b[a(585)]();return n?(n[a(1715)]=n[a(1166)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}else _0x837a94=_0xd7ac40[_0x52c1dc+_0x30d186+1],_0x13d9f9=_0xc57b4f[e[a(927)](e.uXfeF(_0x36657d,_0x32e07b),2)],e[a(729)](e.qzsfk(e[a(429)](_0x2ce408,e[a(488)](_0x1cc727,8)),49344),32896)?_0x464847+=_0x428dd7:(_0x427854=e.laGVb(e[a(1135)](15,_0x4973cd),12)|e[a(1659)](63,_0x2368dc)<<6|e[a(1667)](63,_0x5dffda),e[a(1146)](_0x5e20d9,2048)||_0x1bb2dc>=55296&&_0x295a05<=57343?_0x2f2646+=_0x1ac524:(_0x22b3e4+=e.WYolQ(_0x56572a,_0x54972d),_0x269a33+=2))}function L(a){let n=t,s={IVldC:function(d,f){return e[F(462)](d,f)}};if(e.Mtmfp("uQYuu",e[n(1459)]))b[n(1664)](a);else return s[n(536)](_0xad5e9a,_0x5008a6)}function z(a){return{bytes:a,offset:0,limit:a.length}}function B(a){let n=t,s=a[n(1103)],d=a.limit;return e[n(1046)](s[n(386)],d)?s:s[n(1466)](0,d)}function J(a,n){let s=t;if(e[s(1510)](e.GQMeT(a[s(1715)],n),a[s(1166)]))throw new Error(e[s(1378)]);a.offset+=n}function V(a){let n=t;return e[n(707)](a[n(1715)],a.limit)}function re(a,n){let s=t,d=a[s(1103)],f=a[s(1715)],g=a[s(1166)],E=e[s(871)](f,n);if(e[s(1510)](E,d[s(386)])){let y=new Uint8Array(e[s(1754)](2,E));y.set(d),a[s(1103)]=y}return a.offset=E,e[s(495)](E,g)&&(a[s(1166)]=E),f}function Z(a,n){let s=t;if(e.SvWlv(e[s(517)],e[s(517)]))return new _0x347e4c(_0x333907,{data:_0x42c5c1});{let d=a[s(1715)];if(d+n>a[s(1166)])throw new Error(e[s(1177)]);return a[s(1715)]+=n,d}}function se(a,n){let s=t,d=e[s(1350)](Z,a,n);return a[s(1103)][s(1466)](d,e[s(871)](d,n))}function oe(a,n){let s=t,d=e.woFve(re,a,n[s(386)]);a[s(1103)].set(n,d)}function D(a,n){let s=t,d=e[s(1613)](Z,a,n),f=String[s(1665)+"Code"],g=a[s(1103)],E="\uFFFD",y="";for(let p=0;p<n;p++){let A=g[e[s(1832)](p,d)],O,N,j,q;e[s(580)](e[s(900)](128,A),0)?y+=e[s(455)](f,A):e[s(1104)](224&A,192)?e[s(1552)](e[s(1721)](p,1),n)?y+=E:(O=g[e[s(1471)](e.uzbtg(p,d),1)],e.TbonK(e.ANOuU(192,O),128)?y+=E:(q=e[s(1800)](e[s(1589)](e[s(1135)](31,A),6),e.hSjbA(63,O)),q<128?y+=E:(y+=e[s(884)](f,q),p++))):e[s(1562)](240&A,224)?e.VRadr(e.uzbtg(p,2),n)?y+=E:(O=g[e[s(965)](e[s(871)](p,d),1)],N=g[e[s(1493)](e[s(1630)](p,d),2)],e[s(1445)](e[s(1426)](O,e[s(681)](N,8))&49344,32896)?y+=E:(q=e[s(1426)](e[s(385)](e.TkvXJ(e.stEaO(15,A),12),e[s(681)](63&O,6)),63&N),e[s(1146)](q,2048)||e[s(1264)](q,55296)&&e[s(1484)](q,57343)?y+=E:(y+=e[s(577)](f,q),p+=2))):e[s(1562)](e.ocqNn(248,A),240)?e[s(1236)](e.bygeI(p,3),n)?y+=E:(O=g[p+d+1],N=g[e[s(1832)](e[s(1324)](p,d),2)],j=g[e.KMHUL(e[s(1396)](p,d),3)],e[s(1174)](e[s(385)](e[s(429)](O,e[s(1589)](N,8)),j<<16)&12632256,8421504)?y+=E:(q=e[s(1270)](e[s(516)](e.EQVjH(e.Ilron(7,A),18),e[s(914)](63,O)<<12)|e[s(681)](e[s(1057)](63,N),6),e.FmqBm(63,j)),q<65536||e[s(1097)](q,1114111)?y+=E:(q-=65536,y+=e[s(1152)](f,e[s(1348)](e[s(674)](q,10),55296),e[s(1601)](e[s(1101)](1023,q),56320)),p+=3))):y+=E}return y}function G(a,n){let s=t,d={tDTsG:function(p,A){return e[F(1510)](p,A)},UZPVt:e[s(881)],DCXtR:function(p,A){return e[s(1264)](p,A)},UMIyh:function(p,A){return e[s(1281)](p,A)},xQXrh:function(p,A,O,N){return p(A,O,N)},NxsWG:function(p,A){return e[s(985)](p,A)},EgXxl:s(612),QuyxG:function(p,A,O){return e[s(1116)](p,A,O)}},f=n.length,g=0;for(let p=0;e[s(999)](p,f);p++){let A=n[s(741)+"At"](p);e.RMSbK(A,55296)&&e[s(1416)](A,56319)&&e[s(556)](e[s(549)](p,1),f)&&(A=e[s(664)](e[s(766)](e[s(947)](A,10),n.charCodeAt(++p)),56613888)),g+=e[s(593)](A,128)?1:A<2048?2:A<65536?3:4}e[s(700)](ge,a,g);let E=e.oFxss(re,a,g),y=a[s(1103)];for(let p=0;p<f;p++){let A=n[s(741)+"At"](p);if(e[s(383)](A,55296)&&A<=56319&&e[s(960)](p,1)<f&&(A=e[s(664)](e.zvzpu(e[s(947)](A,10),n[s(741)+"At"](++p)),56613888)),e.CHUPM(A,128))y[E++]=A;else{if(e[s(1227)](A,2048))y[E++]=e[s(1286)](e[s(1647)](e.uNxHO(A,6),31),192);else if(e[s(602)](s(1397),e.DIkyY)){if(e[s(556)](A,65536))y[E++]=e.dZnNX(e[s(1135)](e.lvHzv(A,12),15),224);else if(e.CGING(e[s(1571)],e.OLwmF)){if(d[s(458)](_0x5d60b9,_0x40ea0d))throw new _0xf2935c(d[s(968)]);let O=3;for(;d[s(1531)](O,0);){let N=d[s(666)](255,_0x5df7f6);d.xQXrh(_0x340264,N,_0x3ddfb0,d.NxsWG(_0x2a5185,O)),_0x5b231f>>>=8,O--}return d[s(1331)](_0x40db8e,4)}else y[E++]=e[s(898)](e[s(709)](A>>18,7),240),y[E++]=e.qHBLu(A>>12&63,128);y[E++]=e[s(1270)](e[s(1281)](e[s(674)](A,6),63),128)}else this.emit(d[s(1451)],d[s(1187)](_0x4afbec,d[s(1451)],{..._0x1099ec}));y[E++]=e[s(1286)](e.qzsfk(63,A),128)}}}function K(a,n){let s=t,d=e.QKpoa(re,a,n[s(1166)]),f=a.bytes,g=n[s(1103)];for(let E=0,y=n[s(1166)];E<y;E++)f[e[s(688)](E,d)]=g[E]}function ee(a){return a.bytes[Z(a,1)]}function Qe(a,n){let s=t,d=e[s(1137)](re,a,1);a[s(1103)][d]=n}function pe(a){let n=t,s=0,d=0,f;do f=e[n(1437)](ee,a),e[n(1888)](s,32)&&(d|=e[n(1585)](127&f,s)),s+=7;while(e[n(1135)](128,f));return d}function ge(a,n){let s=t;if(e[s(891)](e[s(756)],e[s(756)]))return _0x4b7332?.[s(638)](d=>d[s(1557)]===_0x88ef4b)?.value;for(n>>>=0;e[s(1355)](n,128);)Qe(a,e[s(1426)](e.EAOcB(127,n),128)),n>>>=7;e.slOUI(Qe,a,n)}function It(a,n){let s=t,d={aFodN:function(p,A){return p>=A},exrLH:function(p,A){return e.zvzpu(p,A)},HvQRm:function(p,A){return e[F(1708)](p,A)},vatOv:function(p,A){return e[F(1808)](p,A)},OtbJV:function(p,A){return e.VDhGp(p,A)},hsvsm:function(p,A){return p&A},tgssd:function(p,A){return p>>A},ucGvN:function(p,A){return e[F(674)](p,A)},PdxZT:function(p,A){return e.wAbCC(p,A)},TntIn:function(p,A){return p>>A}},f=0,g=0,E=0,y;if(y=e[s(1109)](ee,a),f=e[s(1659)](127,y),e.GMOOU(128,y)&&(y=ee(a),f|=e[s(1826)](127&y,7),e[s(1101)](128,y)&&(y=e[s(1859)](ee,a),f|=e.jAOvy(e[s(509)](127,y),14),e.lQTgC(128,y)&&(y=ee(a),f|=e[s(681)](e[s(1755)](127,y),21),e.FmqBm(128,y)&&(y=e[s(563)](ee,a),g=e[s(1135)](127,y),e[s(1210)](128,y)&&(y=e.zQUST(ee,a),g|=e.fNnzP(127,y)<<7,e[s(709)](128,y)&&(y=e[s(1463)](ee,a),g|=e[s(900)](127,y)<<14,e[s(906)](128,y))))))))if(s(994)!=="jmzfQ"){let p=_0xeae55e.charCodeAt(_0x4bed12);YzryWU.aFodN(p,55296)&&p<=56319&&YzryWU[s(451)](_0x1d3124,1)<_0x176bd3&&(p=YzryWU.HvQRm((p<<10)+_0x431f34[s(741)+"At"](++_0x6db96a),56613888)),YzryWU[s(1048)](p,128)?_0x59effb[_0x24ded3++]=p:(YzryWU[s(1048)](p,2048)?_0x248d72[_0x24c797++]=YzryWU[s(1614)](YzryWU.hsvsm(YzryWU[s(1188)](p,6),31),192):(YzryWU[s(1048)](p,65536)?_0x3ff44c[_0x7dd26e++]=YzryWU[s(1614)](YzryWU.hsvsm(YzryWU.tgssd(p,12),15),224):(_0xd538d3[_0x18b617++]=YzryWU[s(1299)](p,18)&7|240,_0x3c7c55[_0x4a9673++]=YzryWU[s(1258)](YzryWU[s(1866)](p>>12,63),128)),_0x10d06e[_0x2f1a07++]=YzryWU.hsvsm(YzryWU[s(1261)](p,6),63)|128),_0x57d136[_0x4284c1++]=YzryWU[s(1258)](YzryWU[s(1866)](63,p),128))}else y=ee(a),g|=e[s(1468)](127&y,21),e[s(914)](128,y)&&(y=ee(a),E=e[s(900)](127,y),e[s(592)](128,y)&&(y=ee(a),E|=e[s(1032)](e[s(1755)](127,y),7)));return{low:e[s(1374)](f,e[s(1423)](g,28)),high:e.DWCXh(e[s(1753)](g,4),e[s(937)](E,24)),unsigned:n}}function pt(a,n){let s=t,d=e[s(1753)](n[s(1246)],0),f=e[s(1624)](e[s(1286)](e.lBjtd(n[s(1246)],28),e.jgcIG(n[s(1120)],4)),0),g=n[s(1120)]>>>24,E=e[s(1621)](0,g)?e[s(602)](0,f)?e[s(1864)](d,16384)?e.HVvGw(d,128)?1:2:e.TKrPy(d,2097152)?3:4:e[s(1146)](f,16384)?e.HVvGw(f,128)?5:6:e[s(1794)](f,2097152)?7:8:g<128?9:10,y=e.HkSDk(re,a,E),p=a[s(1103)];switch(E){case 10:p[e[s(1085)](y,9)]=e[s(1439)](g,7)&1;case 9:p[e[s(960)](y,8)]=e[s(714)](9,E)?e[s(1882)](128,g):e.tVsfY(127,g);case 8:p[e[s(965)](y,7)]=E!==8?e[s(429)](e[s(1439)](f,21),128):f>>>21&127;case 7:p[e[s(722)](y,6)]=e[s(714)](7,E)?f>>>14|128:e[s(436)](f>>>14,127);case 6:p[e[s(1832)](y,5)]=e[s(891)](6,E)?e[s(1588)](f>>>7,128):e[s(464)](e[s(619)](f,7),127);case 5:p[e.Cdsqw(y,4)]=e[s(737)](5,E)?128|f:e[s(1742)](127,f);case 4:p[y+3]=e.iDqYX(4,E)?e[s(1082)](d,21)|128:e.jVHkE(e[s(668)](d,21),127);case 3:p[y+2]=e[s(699)](3,E)?e[s(415)](e[s(1753)](d,14),128):e[s(1279)](d>>>14,127);case 2:p[e[s(858)](y,1)]=E!==2?e[s(1158)](e.bVaTm(d,7),128):e.CmEIG(d>>>7,127);case 1:p[y]=e.SvWlv(1,E)?e[s(557)](128,d):127&d}}function en(a){return v(a)}function Ft(a){let n=t,s={nBYII:e.crRMx,TzWvO:function(d,f,g){return e[F(1137)](d,f,g)}};if(e[n(1686)](e[n(1339)],"AnKiY"))this[n(1595)](s.nBYII,s[n(821)](_0x5ccd9e,s[n(1606)],{..._0x52c5fc}));else return e[n(1119)](S,a)}let tn=65536,Zr=e[t(799)],_e=e.ETuPA(tn,tn),Ae=_e*_e,er=e[t(1874)](Ae,2),Pe=String[t(981)+"e"][t(741)+"At"];class fe{constructor(n,s,d){let f=t;if(e[f(1635)]("oZSUT",f(1389)))this[f(1447)]=!0,this.low=e[f(491)](0,n),this[f(1120)]=e[f(898)](0,s),this.unsigned=!!d;else try{this._ws&&this._ws[f(605)](_0x5c6b29,_0x334cc1)}catch{}}static isLong(n){return n&&e[t(1046)](!0,n.isLong)}static[t(784)](n,s,d){let f=t,g={mNXlJ:e[f(1367)],odLXg:"text/jav"+f(1199),NUlUc:e[f(401)],ttotz:e[f(1640)]};if(e[f(1019)](e[f(1289)],e.nwRCY)){let E={KViZv:function(p,A){return p(A)},hsony:g[f(1835)]},y=_0x58c634[f(1422)+"ement"](f(890));_0x5b75d3["frontier"+f(575)]=p=>{let A=f;_0x3b0fac.body["removeCh"+A(1110)](y),_0x17eae3[A(952)+A(575)]=void 0,E[A(761)](_0x4c065c,p&&p[A(703)]||E.hsony)},y[f(1361)]=g[f(419)],y[f(1308)]=_0x3945c2[f(1663)](/^ws/,g[f(1698)])+g[f(1197)];try{_0xb6afc5[f(1705)][f(656)+f(1110)](y)}catch{_0x3e9d5e[f(1705)][f(908)+f(1110)](y)}}else return new fe(n,s,d)}static[t(459)+"s"](n,s,d){let f=t;return d?fe[f(459)+f(484)](n,s):fe["fromByte"+f(624)](n,s)}static["fromByte"+t(484)](n,s){let d=t;return new fe(e[d(1560)](e[d(1790)](e[d(898)](n[0],n[1]<<8),e[d(1438)](n[2],16)),n[3]<<24),e[d(1158)](n[4],e[d(947)](n[5],8))|e[d(1738)](n[6],16)|e.xRvjS(n[7],24),s)}static[t(459)+t(624)](n,s){let d=t,f={jjfMw:e.IbhDq};if(e.TMXMj(e[d(1824)],d(642)))return new fe(e.qHBLu(e[d(1857)](e[d(1426)](e.xRvjS(n[4],24),n[5]<<16),e[d(1655)](n[6],8)),n[7]),e[d(385)](e[d(535)](n[0],24)|e[d(838)](n[1],16)|n[2]<<8,n[3]),s);switch(_0x1513da){case f[d(1890)]:case d(583):return{[d(651)+_0x27deec]:1,"x-tt-env":_0x56e2f4};default:return{}}}static[t(1431)](n){let s=t;return e[s(602)](n,Zr)?td:new fe(e[s(647)](e[s(1158)](Pe[s(434)](n,0)|e[s(1674)](Pe.call(n,1),8),e[s(1604)](Pe[s(434)](n,2),16))|e[s(1336)](Pe[s(434)](n,3),24),0),e[s(1419)](e[s(491)](e[s(618)](Pe[s(434)](n,4),e[s(1848)](Pe.call(n,5),8)),e[s(681)](Pe[s(434)](n,6),16))|e[s(929)](Pe[s(434)](n,7),24),0),!0)}[t(1710)](){let n=t;return String["fromChar"+n(473)](e[n(1697)](255,this[n(1246)]),e[n(682)](this.low>>>8,255),e.EcBnF(this[n(1246)],16)&255,e.isoTI(this[n(1246)],24),e[n(1281)](255,this[n(1120)]),e[n(1755)](this[n(1120)]>>>8,255),e[n(1027)](e.LTmdu(this.high,16),255),e[n(1080)](this.high,24))}static fromNumber(n,s=!0){let d=t;if(isNaN(n))return s?kp:td;if(s){if(n>=Ae)return Cp}else{if(n<=-er)return Dp;if(e[d(1277)](n+1,er))return Rp}return fe[d(784)](e[d(1560)](e[d(1797)](n,_e),0),e[d(1874)](n,_e)|0,s)}[t(847)](){let n=t;return this[n(1898)]?e[n(403)](e.bDEFh(e.JLodX(this[n(1120)],0),_e),e[n(1596)](this[n(1246)],0)):e.LCmXw(e[n(1086)](this[n(1120)],_e),e[n(622)](this[n(1246)],0))}[t(1371)](){let n=t;return this[n(1120)]===0&&e.uLFMe(0,this[n(1246)])}[t(833)](n){let s=t;fe[s(1447)](n)||(n=fe[s(531)+"er"](n));let d=this[s(1120)]>>>16,f=65535&this.high,g=e[s(647)](this.low,16),E=e[s(1607)](65535,this[s(1246)]),y=e[s(622)](n[s(1120)],16),p=e[s(1210)](65535,n[s(1120)]),A=e[s(1818)](n[s(1246)],16),O=e.xVcZm(65535,n.low),N=0,j=0,q=0,te=0;return te+=e.zNqtX(E,O),q+=e.gqQqj(te,16),te&=65535,q+=e[s(1728)](g,A),j+=q>>>16,q&=65535,j+=e[s(688)](f,p),N+=j>>>16,j&=65535,N+=e.teLkq(d,y),N&=65535,fe.fromBits(e[s(415)](e.cDatK(q,16),te),e.DWCXh(e[s(1633)](N,16),j),this[s(1898)])}[t(395)](n){let s=t;return fe[s(1447)](n)||(n=fe[s(531)+"er"](n)),e[s(1150)](this[s(1898)],n[s(1898)])&&e.ZjQrg(this.high>>>31,1)&&e.wDQSk(e[s(1596)](n[s(1120)],31),1)?!1:this.high===n[s(1120)]&&e[s(1802)](this.low,n.low)}[t(1393)](){let n=t;if(e.WLGEX(e[n(1259)],e.FyQXf))this[n(1777)+"s"]=_0x1bb6a7,this[n(846)+"es"]=_0x444042,this["currentI"+n(851)]=0,this[n(770)+n(1521)+n(499)+"t"]=0;else return e[n(580)](-1,this[n(1246)])&&e.uLFMe(-1,this[n(1120)])?fe.fromBits(0,0,this[n(1898)]):e[n(576)](-1,this[n(1246)])?fe[n(784)](0,this[n(1120)]+1,this[n(1898)]):fe[n(784)](e[n(722)](this[n(1246)],1),this.high,this[n(1898)])}[t(835)](n){return n?this[t(634)+"E"]():this.toBytesBE()}[t(634)+"E"](){let n=t,s={hgCGC:function(d,f){return e[F(1622)](d,f)},NhkKa:function(d,f){return e[F(1708)](d,f)}};if(e[n(954)]!==n(754)){let d=this[n(1120)],f=this.low;return[e[n(1027)](255,f),e[n(439)](e[n(533)](f,8),255),e[n(1742)](f>>>16,255),e.IUotP(f,24),e[n(1667)](255,d),e[n(647)](d,8)&255,e[n(1647)](e[n(622)](d,16),255),e.SdQCS(d,24)]}else{if(tvxdjG.hgCGC(4,_0x7c524e[n(386)])){let d=_0x31af45[n(713)+"g"](0,tvxdjG[n(598)](4,_0x1319ba[n(386)])),f=d[n(1063)](_0x31b49c);_0x4d017d.push(f)}else _0x4279a4[n(1664)](_0x3ee875);_0x509ea2&&(_0x4ad7e6+=1),_0xe7ab44+=1,_0x104b12=!1}}[t(505)+"E"](){let n=t,s={ZkPMC:e.hOgGm,OGKen:e.CZxha,JMjhr:n(1744)};if(n(1010)===e[n(490)])this._isBrowser&&_0x5b7c55["addEvent"+n(752)](n(1454),this[n(630)+n(1156)]),this[n(1305)+"er"]&&_0x58c742[n(988)+n(752)](s[n(1154)],this._handleOffLine),this[n(1305)+"er"]&&_0x232323[n(988)+n(752)](s.OGKen,this["_handleP"+n(895)]),this[n(1305)+"er"]&&_0x37188a[n(988)+"Listener"](s.JMjhr,this[n(1031)+n(1313)]);else{let d=this[n(1120)],f=this[n(1246)];return[e.IHtlX(d,24),e[n(1753)](d,16)&255,e[n(1003)](d,8)&255,e[n(1415)](255,d),e.DrJMH(f,24),e.xSxVS(e[n(639)](f,16),255),e[n(1140)](e[n(685)](f,8),255),e[n(1667)](255,f)]}}}let td=new fe(0,0,!1),kp=new fe(0,0,!0),Rp=fe[t(784)](-1,2147483647,!1),Cp=fe[t(784)](-1,-1,!0),Dp=fe.fromBits(0,-2147483648,!1);var nn=(function(a){let n=t,s=e[n(880)][n(609)]("|"),d=0;for(;;){switch(s[d++]){case"0":a[a[n(1161)+n(742)]=5002]=e[n(1332)];continue;case"1":a[a[e[n(1584)]]=5001]=e[n(1584)];continue;case"2":return a;case"3":a[a[e.ZBTwt]=5004]="MESSAGE_"+n(671);continue;case"4":a[a[e[n(432)]]=5003]=e[n(432)];continue;case"5":a[a[e[n(594)]]=5005]=e[n(594)];continue}break}})({});class tr{constructor(n){let s=t;this.type=n,this[s(1446)]=null}}class nd extends tr{constructor(n,s){let d=t;super(n),this.message=s&&s[d(612)]||null}}class rd extends tr{constructor(n,s){let d=t;super(n),this[d(644)]=s&&s[d(644)]||null,this.colno=s&&s.colno||0,this[d(596)]=s&&s[d(596)]||"",this[d(388)]=s&&s[d(388)]||0,this[d(612)]=s&&s[d(612)]||"",this[d(441)]=s&&s[d(441)]||5001}}class id extends tr{constructor(n,s){let d=t,f="3|0|1|4|2"[d(609)]("|"),g=0;for(;;){switch(f[g++]){case"0":this[d(441)]=s&&s[d(441)]||0;continue;case"1":this.reason=s&&s[d(1087)]||"";continue;case"2":this[d(507)+d(1670)]=s&&s[d(507)+d(1670)]||!1;continue;case"3":super(n);continue;case"4":this.wasClean=s&&s[d(1641)]||!1;continue}break}}}class sd extends tr{constructor(n,s){let d=t;super(n),this[d(916)]=s&&s.data||null}}class od extends sd{constructor(n,s){let d=t;super(n),this[d(916)]=s&&s.data||null,this[d(612)]=s&&s[d(612)]||null}}class ad extends tr{constructor(n,s){let d=t;super(n),this[d(916)]=s&&s[d(916)]||null}}function ct(a,{message:n,code:s,error:d}){return new rd(a,{message:n,code:s,error:d})}function gt(a,{code:n,reason:s,wasClean:d,willReconnect:f}){let g=t;if(e[g(1225)](e[g(1050)],g(786)))_0x4f6fdf[g(948)](_0x4c4305,_0xf21807);else return new id(a,{code:n,reason:s,wasClean:d,willReconnect:f})}function cd(a,{data:n,message:s}){return new od(a,{data:n,message:s})}function ld(a,{data:n}){return new ad(a,{data:n})}function ga(a,{message:n}){return new nd(a,{message:n})}class dd{constructor(n,s){let d=t;this.endpoints=n,this.maxRetries=s,this[d(1088)+d(851)]=0,this["currentE"+d(1521)+"riesCount"]=0}[t(1482)+t(1318)+"fig"](){let n=t;if(e[n(551)](e[n(1250)],e.pmYyw))this[n(1088)+"ndex"]=0,this["currentE"+n(1521)+n(499)+"t"]=0;else return this[n(1404)][n(1163)]}[t(867)+"es"](){let n=t;this["currentE"+n(1521)+n(499)+"t"]=0}[t(591)+t(1683)+"nt"](){let n=t;return this.endpoints[this[n(1088)+n(851)]]}[t(591)+t(1683)+t(1615)+t(1248)](){let n=t;return this[n(770)+n(1521)+n(499)+"t"]}[t(423)+t(975)+"es"](){let n=t;if(e[n(1247)](e[n(1638)],e[n(1638)]))_0x525bc4&&this[n(534)+n(1328)][n(1294)+n(1319)+n(1011)](_0x2e386c);else return!!(e[n(383)](this["currentI"+n(851)],this[n(1777)+"s"][n(386)])||e[n(941)](this["currentI"+n(851)],e[n(664)](this.endpoints[n(386)],1))&&e[n(1157)](this["currentE"+n(1521)+"riesCount"],this.maxRetries))}[t(1767)+t(828)+t(1642)+t(391)+t(1405)](){let n=t;return this[n(1088)+n(851)]==this[n(1777)+"s"].length?!0:this["currentE"+n(1521)+n(499)+"t"]>this.maxRetries}["replaceBackupEndpointAndUpdateCo"+t(963)](){let n=t;return e[n(602)](e[n(404)],n(1167))?this[n(1404)][n(503)+"pe"]:(this["currentEndpointT"+n(499)+"t"]=1,this["currentI"+n(851)]++,this.endpoints[this[n(1088)+n(851)]])}[t(591)+"ntEndpoi"+t(529)+"ateCount"](){let n=t;return this[n(770)+n(1521)+n(499)+"t"]++,this[n(591)+n(1683)+"nt"]()}}let nr=(e[t(1578)](t(492)+"d",typeof globalThis)&&e.eGZOk(e.SqezN,globalThis["construc"+t(1491)].name)||e[t(1884)](e.xxDSR,typeof window)&&window[t(400)+t(1491)][t(1823)]==="Window")&&e[t(1018)](e[t(882)],typeof document),Cn=e[t(1380)](e[t(882)],typeof globalThis)&&(e[t(1184)](e[t(1487)],globalThis[t(400)+t(1491)].name)||e[t(1407)]("Dedicate"+t(1e3)+t(483)+"pe",globalThis[t(400)+t(1491)].name))&&e[t(1241)](e.xxDSR,typeof tt),Xr=(e.NFEOg(t(492)+"d",typeof globalThis)&&e[t(1487)]===globalThis[t(400)+t(1491)][t(1823)]||t(492)+"d"==typeof globalThis||e[t(1301)](e.xxDSR,typeof globalThis)&&!!globalThis[t(1224)+t(1751)])&&e[t(1341)](e[t(882)],typeof wx),Qr=e[t(610)](e[t(882)],typeof globalThis)&&(e[t(572)](e.rWzRl,globalThis[t(400)+"tor"][t(1823)])||e.awKSc===globalThis[t(400)+t(1491)][t(1823)]||e[t(409)](t(1002)+"orkerGlo"+t(443),globalThis[t(400)+"tor"][t(1823)]))&&e[t(1380)](e[t(882)],typeof self),Pp=e[t(882)]!=typeof globalThis&&e[t(1876)](e[t(1487)],globalThis[t(400)+t(1491)][t(1823)])&&e[t(732)](e[t(882)],typeof global)&&e.vMmLo(t(405),global.constructor.name)&&e[t(1044)](e[t(882)],typeof process)&&!!process[t(1240)];class ma{constructor(){this._listeners={}}[t(1595)](n,...s){let d=t;if(e.gNedi(e.dtFsL,e[d(1222)])){let f=this[d(410)+"rs"][n];if(f)f[d(433)]().forEach(g=>g.fn[d(1377)](g[d(866)],s));else if(e.SlJxV(d(644),n)&&!this.onerror){let g=s[d(386)]&&s[0];if(e[d(1001)](g,Error))throw g;let E=new Error(e.cZhYT(e.AIuyE,g?e[d(1617)](e[d(652)](" (",g[d(612)]),")"):""));throw E[d(1723)]=g,g}return this}else this["_dispatchMessage"+d(1570)](_0x3bfaff),_0x1379d2[d(948)](_0x1681e9,_0x574636,_0x3e56a6[d(612)][d(1875)])}[t(1616)](n,s){let d=t;if(e[d(551)](e[d(1228)],e.JRjtW)){if(n===void 0)this[d(410)+"rs"]={};else if(e.SlJxV(void 0,s))this._listeners[n]=null;else{let f=this[d(410)+"rs"][n];if(f)for(let g=0;e[d(418)](g,f.length);)e[d(1291)](f[g].fn,s)?f[d(1836)](g,1):++g}return this}else return new _0x578aa9(e.qHBLu(e.vIsgO(_0x3bc92b[4],24)|e[d(1848)](_0x3680a9[5],16),e[d(1315)](_0x535f83[6],8))|_0x342758[7],e[d(807)](e.fKamL(_0x15be19[0],24)|e[d(853)](_0x4bd489[1],16),e[d(853)](_0x466182[2],8))|_0x599577[3],_0x18feb1)}on(n,s,d){let f=t;return(this._listeners[n]||(this[f(410)+"rs"][n]=[]))[f(1664)]({fn:s,ctx:d||this}),this}}class Lp extends ma{[t(780)+"rrorMess"+t(1033)](n){let s=t;return n.errMsg||n[s(1107)]?("message: "+(n[s(678)]||"")+" code: "+(n.errNo||""))[s(946)]():JSON[s(665)+"y"](n)}constructor(n,s,d){let f=t;super(),this[f(1404)]=null,Xr&&wx[f(430)+f(584)]&&(this[f(1404)]=wx["connectS"+f(584)]({url:n,protocols:s,header:d,fail:this["_createSocketFai"+f(739)].bind(this),success:this[f(426)+"ocketSuc"+f(1409)+f(1006)][f(964)](this)})),Cn&&tt.connectSocket&&(this[f(1404)]=tt[f(430)+f(584)]({url:n,protocols:s,header:d,fail:this[f(426)+f(1251)+f(739)][f(964)](this),success:this["_createS"+f(1173)+f(1409)+"ler"][f(964)](this)}))}[t(426)+t(1173)+t(1409)+t(1006)](){let n=t;Promise[n(875)]()[n(1732)](()=>{this[n(1014)+"steners"]()})}[t(426)+t(1251)+t(739)](n){let s=t;Promise[s(875)]()[s(1732)](()=>{let d=s,f=e.HNVJA(ct,e[d(1529)],{message:this[d(780)+d(1179)+d(1033)](n)});this.emit(e[d(1529)],f);let g=e[d(1579)](gt,e.crRMx,{reason:this[d(780)+"rrorMessage"](n)});this[d(1595)](e[d(923)],g)})}[t(1014)+t(1093)](){let n=t,s={SKnmW:e.cXVrH,SVsqv:function(d,f,g){return e[F(411)](d,f,g)},rbUay:e[n(1037)]};this[n(1404)][n(1565)](d=>{let f=n;this[f(1595)](s[f(513)],s.SVsqv(ld,s[f(513)],{...d,data:d[f(678)]||""}))}),this._socket[n(1658)](d=>{let f=n;this.emit(f(605),e[f(733)](gt,e[f(923)],{...d}))}),this[n(1404)][n(1175)+"e"](d=>{let f=n;this[f(1595)](s[f(1793)],cd(f(612),{...d}))}),this[n(1404)].onError(d=>{let f=n;this[f(1595)](f(644),ct("error",{...d,message:d.errMsg||""}))})}send(n){let s=t,d={SPfsC:s(644)};if(e[s(1703)]===e[s(1508)])return _0x563af2[s(1665)+"Code"](e[s(689)](255,this[s(1246)]),e[s(1317)](e[s(1419)](this[s(1246)],8),255),this[s(1246)]>>>16&255,e.dXkWV(this[s(1246)],24),e[s(1489)](255,this[s(1120)]),this[s(1120)]>>>8&255,e[s(747)](e[s(1806)](this[s(1120)],16),255),e[s(899)](this.high,24));if(e.xJXrj(n,Uint8Array)){let f=n[s(522)][s(433)](n[s(691)+"et"],e.uLXKV(n.byteLength,n[s(691)+"et"]));this[s(1404)]&&this[s(1404)][s(1049)]({data:f,fail:g=>{let E=s;this.emit(e[E(1529)],e[E(733)](ct,E(644),{message:this[E(780)+E(1179)+E(1033)](g)}))}})}else this[s(1404)]&&this[s(1404)].send({data:n,fail:f=>{let g=s;this.emit(d[g(600)],ct(d[g(600)],{message:this[g(780)+g(1179)+g(1033)](f)}))}})}[t(605)](n,s){let d=t;this._socket&&this._socket[d(605)]({code:n,reason:s})}[t(988)+t(752)](n,s){this.on(n,s)}[t(1462)+t(949)+t(1636)](n,s){this[t(1616)](n,s)}get readyState(){let n=t;return this[n(1404)][n(1537)+"te"]}get[t(503)+"pe"](){let n=t;return this._socket[n(503)+"pe"]}set binaryType(n){}get[t(1081)](){let n=t;if(e[n(1791)](e.jrCIk,e.ngurf))_0x51943b(_0x364cae[n(644)]),NGKNDN[n(611)](_0x46c505);else return this[n(1404)][n(1081)]}get[t(1163)](){let n=t;return this[n(1404)][n(1163)]}get[t(1181)+"ns"](){let n=t;return this[n(1404)][n(1181)+"ns"]}get["buffered"+t(1694)](){return 0}}function Op(a,n){let s=t;if(n)return new n(a.url,a[s(1163)]);if(e.ImsAr(Xr,Cn))return new Lp(a[s(1081)],a[s(1163)],a[s(1219)]);if(e[s(924)](nr,Qr)&&e[s(995)](e.xxDSR,typeof WebSocket)&&WebSocket)return new WebSocket(a[s(1081)],a[s(1163)+"s"])}function Np(a){let n=t,s=(n(1131)+"3")[n(609)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(e[n(1675)](nr,Qr)&&e[n(1380)](e[n(882)],typeof WebSocket)&&WebSocket)return!0;continue;case"1":if(Xr&&wx["connectS"+n(584)])return!0;continue;case"2":if(a)return!0;continue;case"3":return!1;case"4":if(Cn&&tt[n(430)+n(584)])return!0;continue}break}}function ud(a,n,s){let d={fQtFJ:function(E,y){return e[F(1630)](E,y)}},f=-1;async function g(E){let y=F;return E<=f?Promise.reject(new Error("next() c"+y(1511)+y(1074)+y(1785)+y(1669))):(f=E,E===s[y(386)]?Promise.resolve():s[E][y(964)](a)(n,g[y(964)](null,d[y(1207)](E,1))))}e.OOoZy(g,0)}function fd(a){let n=t,s=0,d=0;for(let f=0;e[n(1488)](f,a[n(386)]);++f)d=a[n(741)+"At"](f),e.iPdhh(d,128)?s+=1:e[n(1023)](d,2048)?s+=2:e[n(1104)](e[n(1232)](64512,d),55296)&&e[n(580)](e[n(1598)](64512,a[n(741)+"At"](e[n(1085)](f,1))),56320)?(++f,s+=4):s+=3;return s}function xd(a,n,s){let d=t;if(e[d(418)](e.NNBYF(s,n),1))return"";let f="";for(let g=n;g<s;){let E=a[g++];if(e[d(1100)](E,127))f+=String.fromCharCode(E);else if(E>=192&&e[d(1146)](E,224))f+=String[d(1665)+d(473)](e[d(709)](31,E)<<6|63&a[g++]);else if(e.RMSbK(E,224)&&e.wJAND(E,240))f+=String[d(1665)+d(473)](e[d(1714)](e[d(1524)](e[d(731)](15,E)<<12,e.mEiJT(63,a[g++])<<6),e.NbnNy(63,a[g++])));else if(e[d(673)](E,240)){let y=e[d(1857)](e.cdKZb(e.KFJTK(7,E)<<18,e[d(1490)](e[d(1279)](63,a[g++]),12))|e.nbLyj(e.hSjbA(63,a[g++]),6),63&a[g++])-65536;f+=String[d(1665)+d(473)](e[d(1523)](55296,y>>10)),f+=String[d(1665)+d(473)](56320+e[d(658)](1023,y))}}return f}function wa(a,n,s){let d=t,f=s,g,E;for(let y=0;e[d(1448)](y,a[d(386)]);++y)if(g=a[d(741)+"At"](y),g<128)n[s++]=g;else if(g<2048)n[s++]=e[d(1646)](e.uNxHO(g,6),192),n[s++]=63&g|128;else if((64512&g)===55296&&e.wDQSk(e[d(914)](64512,E=a[d(741)+"At"](y+1)),56320)){let p=e.mZjhJ.split("|"),A=0;for(;;){switch(p[A++]){case"0":n[s++]=e[d(541)](63,g)|128;continue;case"1":n[s++]=e[d(1069)](g,18)|240;continue;case"2":++y;continue;case"3":n[s++]=e[d(1052)](e.WMvzD(g>>6,63),128);continue;case"4":g=e[d(1666)](65536+(e[d(816)](1023,g)<<10),e.ANOuU(1023,E));continue;case"5":n[s++]=e[d(1125)](e[d(1667)](e.BRERP(g,12),63),128);continue}break}}else n[s++]=e.upKYP(g>>12,224),n[s++]=e[d(1882)](e.cwKqx(e[d(1517)](g,6),63),128),n[s++]=e[d(1029)](e[d(677)](63,g),128);return e[d(990)](s,f)}async function hd(a){let n=t;if(e[n(1220)](e[n(1801)],typeof a)){let s=new Uint8Array(e.qzAyD(fd,a));return e.vODzU(wa,a,s,0),s}return e[n(1001)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}function Mp(a){let n=t;try{return e.EzMfV("string",typeof a)&&(e[n(1001)](a,ArrayBuffer)||a.buffer&&e.xJXrj(a.buffer,ArrayBuffer))||e[n(1044)](n(448),typeof a)?"":(JSON.parse(a),e[n(1115)])}catch{return e[n(1220)](e.PdWyZ,typeof a)?"text/pla"+n(1772)+n(649):""}}let Bp=(a,n)=>{let s=t;switch(a){case"boe":case"ppe":return{[s(651)+a]:1,"x-tt-env":n};default:return{}}};class zp{constructor(n){let s=t;this["maxLossC"+s(1248)]=n,this[s(1469)]=0}[t(1091)](){let n=t,s={tvOGZ:function(d,f){return d>f},IrFjN:function(d,f){return e[F(1039)](d,f)},Ejfxh:n(683)+"t limit"};if(e[n(969)]("yIODd",e[n(1575)]))this.count++;else{let d=_0x2726c3[n(1715)];if(bioBox.tvOGZ(bioBox[n(1583)](d,_0x130989),_0x54cdfd[n(1166)]))throw new _0x5d985e(bioBox[n(637)]);return _0x16c2e4.offset+=_0x27fc83,d}}[t(423)+t(1752)+"nt"](){let n=t;return n(1619)!==e[n(1441)]?this[n(1469)]>=this[n(1364)+n(1248)]:((this[n(410)+"rs"][_0x1ad58a]||(this._listeners[_0x4bb642]=[])).push({fn:_0x3a3524,ctx:_0xf85644||this}),this)}resetCounter(n=0){let s=t;this["maxLossC"+s(1248)]=n,this.count=0}}async function Fp(a){let n=t,s={ODgLO:function(d,f,g){return d(f,g)},AtEWg:function(d,f){return e[F(1168)](d,f)},VZipk:function(d,f){return e[F(1437)](d,f)},zDAwC:e[n(1009)],smfjw:"text/jav"+n(1199),Dpjzb:e[n(401)],WSUEB:e[n(1640)],zPzwA:e[n(1367)]};return new Promise(d=>{let f=n,g={pDDVF:function(E,y,p){return s[F(693)](E,y,p)},POGpm:function(E,y,p){return E(y,p)},oALcs:function(E,y){return s[F(961)](E,y)},Jutny:"TgZlP",QCFvu:"unknown reason"};if(!nr)return s[f(787)](d,f(1343)+f(1087));try{let E=document[f(1422)+f(1879)](s[f(1762)]);window[f(952)+"JSONP"]=y=>{let p=f;if(g[p(1320)](g.Jutny,"TgZlP")){let A=_0x2417d9[p(1557)];A!==void 0&&(DfuRMK[p(1572)](_0x438629,_0x1e6ad4,10),DfuRMK.POGpm(_0x36123f,_0x30ad11,A));let O=_0x3ad96a[p(1180)];O!==void 0&&(DfuRMK[p(893)](_0x4d3449,_0x4894ee,18),DfuRMK[p(893)](_0x36f074,_0x55e33f,O))}else document.body[p(908)+p(1110)](E),window[p(952)+"JSONP"]=void 0,d(y&&y[p(703)]||g[p(813)])},E[f(1361)]=s[f(1592)],E[f(1308)]=a[f(1663)](/^ws/,s[f(1211)])+s[f(1164)];try{document[f(1705)][f(656)+f(1110)](E)}catch{document[f(1705)][f(908)+f(1110)](E)}}catch{window["frontier"+f(575)]=void 0,s[f(787)](d,s[f(772)])}})}function rn(a,n,s){let d=t;return!!a?.[d(638)](f=>f[d(1557)]===n&&f[d(1180)]===s)}function rr(a,n){return a?.[t(638)](d=>d.key===n)?.value}let _a=null;async function Up(){let a=t;return _a||(_a=Promise[a(875)]()[a(1732)](Bt.bind(Bt,e[a(697)]))),_a}class Gp extends ma{constructor(n,s){let d=t;super(),this[d(897)]=n,this[d(1095)]=s,this[d(1208)]=void 0,this[d(1260)+d(1418)]=null}async[t(466)](){await this[t(818)]()}async[t(818)](){let n=t;if(!this[n(1208)]){if(this[n(1260)+n(1418)])return this[n(1260)+n(1418)];try{let s=this[n(897)],d=this[n(1095)];this[n(1260)+n(1418)]=(async()=>{let f=n,g={LTEMO:function(y,p){return e[F(941)](y,p)}},{openDB:E}=await e[f(611)](Up);this[f(1208)]=await e.vODzU(E,"frontier_"+s,1,{upgrade(y){let p=f;g[p(1079)](p(1068),p(1881))||y[p(800)+p(1498)+"e"](s,{keyPath:d})}})})(),await this[n(1260)+"mise"]}catch(s){console[n(802)](s)}finally{this[n(1260)+n(1418)]=null}}}async[t(1605)](n){let s=t,d={dUIBc:function(f,g){return e[F(1725)](f,g)}};if(e.MHDyg(e.tRUqN,s(872)))try{if(e[s(1671)](e[s(1059)],e.kSeYs))d.dUIBc(_0x48d63a,this[s(1702)+s(457)+"Id"]),d[s(734)](_0x4f4372,this["_reconnectTimeou"+s(1383)]),this._pingPongTimeoutId=null,this[s(527)+s(998)+s(1383)]=null;else return await this._init(),this._qosDB?.[s(1605)](this[s(897)],n)}catch(f){console[s(802)](f)}else return _0x2921cc[s(1733)+"oreNames"]||_0x53f0ac[s(1605)](_0x2f8d5f)}async[t(948)](n,s){let d=t;return await this._init(),this[d(1208)]?.[d(825)](this[d(897)],n)}async[t(1194)](n){let s=t;if(e.eGZOk(e[s(500)],e.Wxkug))try{if(e[s(941)](e[s(581)],e[s(1759)])){let d={VSiLk:function(f,g,E){return e[s(1116)](f,g,E)},fWULZ:e[s(1529)],tpmqZ:function(f,g,E){return e[s(1458)](f,g,E)},dzSNh:e[s(923)]};_0x3002da[s(875)]()[s(1732)](()=>{let f=s,g=d.VSiLk(_0x5a2d90,d.fWULZ,{message:this[f(780)+"rrorMessage"](_0xc29340)});this[f(1595)](d[f(888)],g);let E=d.tpmqZ(_0x4827d5,d[f(1143)],{reason:this[f(780)+f(1179)+"age"](_0x16dca3)});this[f(1595)](d[f(1143)],E)})}else return await this[s(818)](),this[s(1208)]?.[s(1648)](this[s(897)],n)}catch(d){console[s(802)](d)}else{_0x344470[s(1447)](_0x4d1c07)||(_0x2e4847=_0x26ef75[s(531)+"er"](_0xdc9e9e));let d=e[s(606)](this.high,16),f=e[s(1697)](65535,this[s(1120)]),g=e[s(552)](this[s(1246)],16),E=65535&this[s(1246)],y=e[s(1411)](_0x9333af.high,16),p=e.nSreH(65535,_0x3519ef[s(1120)]),A=e[s(1439)](_0x29ce80[s(1246)],16),O=e[s(1232)](65535,_0x569ab3.low),N=0,j=0,q=0,te=0;return te+=E+O,q+=e.GXtNt(te,16),te&=65535,q+=e[s(1749)](g,A),j+=e[s(899)](q,16),q&=65535,j+=e[s(446)](f,p),N+=e[s(668)](j,16),j&=65535,N+=e.GfTJG(d,y),N&=65535,_0x6a1fe3.fromBits(q<<16|te,e[s(385)](e[s(922)](N,16),j),this[s(1898)])}}async[t(1363)](){let n=t;try{return await this[n(818)](),this._qosDB?.[n(1363)](this[n(897)])}catch(s){console[n(802)](s)}}async[t(1594)](){let n=t,s={zNydM:function(d,f){return d===f},UzdMy:e[n(440)],dtLJA:function(d,f){return e.YfETU(d,f)},oHHNz:"store",zHYjk:function(d,f){return d(f)}};if(e[n(572)](e[n(1555)],n(778)))return await this[n(818)](),this._qosDB?.[n(901)+"ys"](this[n(897)]);if(_0x456e04 instanceof _0x2b92e6){if(zPvsTh[n(1892)](_0x20039b,zPvsTh[n(1650)]))return _0x598df3[n(1605)](_0x3502a0);if(zPvsTh[n(399)](_0x157563,n(1733)+n(1162)))return _0x21d2da[n(1733)+n(1162)]||_0x45f948[n(1605)](_0x56bcf5);if(zPvsTh[n(399)](_0x1c601f,zPvsTh[n(956)]))return _0x51a5fe[n(1733)+n(1162)][1]?void 0:_0x6d7564[n(1733)+n(1862)](_0x5af5a3["objectSt"+n(1162)][0])}return zPvsTh[n(1217)](_0x404bc6,_0x282caf[_0x4d183e])}async getAll(){let n=t;if(e.yGHGW(e[n(1765)],e.ixASB))return await this[n(818)](),this[n(1208)]?.getAll(this._dbName);_0x500b0d["removeEventListe"+n(1636)](n(894),_0x43d597),_0x43b13b[n(1462)+n(949)+n(1636)](NGKNDN[n(1529)],_0x5b3e16)}async closeDB(){let n=t;try{this[n(1208)]?.[n(605)](),this[n(1208)]=void 0}catch(s){console.log(s)}}get[t(655)](){let n=t;try{return!!this[n(1208)]}catch(s){return console.log(s),!1}}}class Hp{constructor(n,s){let d=t;this[d(469)]=n,this[d(1455)]=s,this[d(1208)]=localStorage}async[t(466)](){}get _prefix(){let n=t;return n(952)+"_"+this[n(469)]}async[t(1605)](n){let s=t;if(e[s(632)](s(712),e[s(915)]))return this[s(1704)]?this[s(1704)].protocol:"";{let d=this[s(1208)][s(1756)](this[s(1735)]);return JSON[s(694)](e.DYSIJ(d,"{}"))[n]}}async[t(948)](n,s){let d=t,f=this[d(1208)][d(1756)](this._prefix),g=JSON[d(694)](e.aAEru(f,"{}"));return g[s||n[this[d(1455)]]]=n,this[d(1208)][d(1895)](this[d(1735)],JSON[d(665)+"y"](g)),s||n[this[d(1455)]]}async del(n){let s=t,d=this[s(1208)][s(1756)](this[s(1735)]),f=JSON[s(694)](d||"{}");return f[n]=void 0,this[s(1208)][s(1895)](this[s(1735)],JSON[s(665)+"y"](f))}async[t(1363)](){let n=t;return this[n(1208)][n(1363)]()}async[t(1594)](){let n=t,s=this[n(1208)][n(1756)](this[n(1735)]),d=JSON[n(694)](e.aAEru(s,"{}"));return Object.keys(d)}async[t(1124)](){let n=t;if(e[n(393)]!==e[n(393)])return this[n(1208)]?.[n(948)]({message_id:_0x172b68,timestamp:_0x25fb70});{let s=this[n(1208)][n(1756)](this[n(1735)]),d=JSON[n(694)](s||"{}");return Object[n(1568)](d)}}[t(1185)](){return Promise[t(875)]()}get isReady(){let n=t,s={YYUJS:n(614)+"OR",uxgLj:e.rHqJD,crsmh:e[n(1332)],lAKQJ:e.PURdE,TMhOM:e[n(738)]};if(n(1460)===e[n(730)]){let d=(n(1729)+"1|0")[n(609)]("|"),f=0;for(;;){switch(d[f++]){case"0":return _0x422319;case"1":_0x361ab1[_0x2e7924[ZVclhx[n(1176)]]=5005]=ZVclhx.YYUJS;continue;case"2":_0x1bac70[_0x3c5d3c[ZVclhx.uxgLj]=5001]=n(1618)+n(1651);continue;case"3":_0x228ed2[_0x234e75[ZVclhx[n(373)]]=5002]=ZVclhx[n(373)];continue;case"4":_0x49ad81[_0x524685[ZVclhx[n(1775)]]=5003]=ZVclhx[n(1775)];continue;case"5":_0x134ae2[_0x5a3180[n(852)+n(671)]=5004]=ZVclhx[n(1894)];continue}break}}else return!!this[n(1208)]}}class qp{constructor(n,s){let d=t;this[d(469)]=n,this[d(1455)]=s,this[d(1208)]=Cn?tt:Xr?wx:null}async openDB(){}get[t(1735)](){let n=t;return n(952)+"_"+this[n(469)]}async[t(1605)](n){let s=t,d=this[s(1208)][s(822)+s(640)](this._prefix);return JSON[s(694)](e.HfeoR(d,"{}"))[n]}async set(n,s){let d=t,f={ahkgb:function(g,E){return e[F(1888)](g,E)},hNqQY:function(g,E){return g!==E},bmXCb:function(g,E){return e.GaSxe(g,E)}};if(e[d(921)]===e[d(921)]){let g=this[d(1208)][d(822)+"geSync"](this[d(1735)]),E=JSON[d(694)](g||"{}");return E[s||n[this._pathKey]]=n,this[d(1208)][d(1036)+"geSync"](this[d(1735)],JSON[d(665)+"y"](E)),s||n[this[d(1455)]]}else{let g=_0x39ce9e.split(":");for(let E=0;XvVgtp[d(1076)](E,g[d(386)]);E++){let y=g[E];if(XvVgtp[d(1099)](4,g[E][d(386)])){let p=_0x2c298e[d(713)+"g"](0,XvVgtp[d(547)](4,g[E][d(386)])),A=p.concat(y);_0x1bffa9=_0x392326.concat(A)}else _0x2836b8=_0x53ab8b[d(1063)](y)}return _0x24d797}}async del(n){let s=t,d=this[s(1208)][s(822)+s(640)](this[s(1735)]),f=JSON[s(694)](d||"{}");return f[n]=void 0,this._qosDB[s(1036)+"geSync"](this[s(1735)],JSON[s(665)+"y"](f))}async[t(1363)](){let n=t;return this[n(1208)][n(1535)+n(1500)]()}async[t(1594)](){let n=t,s=this[n(1208)]["getStora"+n(1064)+"nc"](this[n(1735)]),d=JSON[n(694)](s||"{}");return Object[n(1594)](d)}async[t(1124)](){let n=t,s=this._qosDB[n(822)+n(1064)+"nc"](this[n(1735)]),d=JSON[n(694)](s||"{}");return Object[n(1568)](d)}closeDB(){return Promise.resolve()}get[t(655)](){return!!this._qosDB}}function pd(a,n){let s=t;if(e.syjTp!==s(834)){if(e.DYSIJ(Cn,Cn))return new qp(a,n);if((nr||Qr)&&e[s(882)]!=typeof indexedDB)return new Gp(a,n);if((nr||Qr)&&e.xxDSR!=typeof localStorage)return new Hp(a,n);throw new Error(s(1043)+s(1496)+"d")}else this[s(1014)+s(1093)]()}class jp{constructor(){let n=t;this["_interva"+n(589)+"Id"]=null,this._interval=36e5,this[n(1208)]=pd(e.gMSDP,e[n(515)])}async[t(1872)+t(1610)](){let n=t;e.zDWmZ(e[n(408)],e[n(540)])?(this[n(471)+n(1278)]?.[n(1091)](),this.emit(n(387)+n(841)+"t",e[n(554)]),this[n(471)+n(1278)]?.[n(423)+n(1752)+"nt"]()?this["_handleR"+n(1316)]():this[n(1365)]()):(e[n(1128)](clearInterval,this[n(1872)+n(589)+"Id"]),this[n(1872)+"lTimeoutId"]=setInterval(()=>{let s=n;this[s(1372)+s(1351)]()},this[n(1872)+"l"]))}async[t(466)](){let n=t,s={vjYcx:function(d,f,g){return d(f,g)},EVYTA:e[n(923)],PTbMq:function(d,f,g){return e[n(1896)](d,f,g)},yvPPP:e[n(798)],QDtFh:function(d,f,g){return e[n(1561)](d,f,g)},liKkd:n(945)+n(753)+"ork offl"+n(369)};if(e.nauTi("fSQVT",e[n(942)]))await this[n(1208)][n(466)]()[n(1732)](()=>{this["_interva"+n(1610)]()});else{if(this[n(1105)+n(1390)](),this._clearTimer(),this[n(617)+n(653)+"rs"](),this[n(824)+n(1287)](1e3,_0x3cc375),this[n(538)+"Lock"]=!1,_0xee947e&&this[n(519)+n(1306)]()&&!this[n(412)+n(1849)]){if(this[n(1144)+n(938)]?.["checkRea"+n(975)+"es"]()){let f=this["_endpoin"+n(938)]?.["getCurre"+n(1683)+"nt"]();this[n(1060)+n(832)+n(1789)](s[n(1829)](_0x57e936,s.EVYTA,{code:1006,reason:n(1209)+f+(n(1359)+n(1576)+n(1430)+n(680)),wasClean:!0}))}else{let f=this[n(1611)][n(1632)+"tInterceptor"](_0x20d505,_0x4fe916);this[n(1060)+"hCloseEv"+n(1789)](s[n(620)](_0x4ec805,n(605),{code:_0x447db7,reason:_0x33de5d,wasClean:!0,willReconnect:f})),f&&this[n(538)]()}return}this["_navigat"+n(1306)]()||this["_readyCl"+n(1849)]?this["_dispatchCloseEv"+n(1789)](_0x424d22(n(605),{code:_0x5e3fae,reason:s[n(859)]})):this[n(1060)+n(832)+n(1789)](s.QDtFh(_0x1e98bf,s.EVYTA,{code:1006,reason:s[n(1504)]})),this[n(1704)]=null,this["_endpoin"+n(938)]?.[n(1482)+n(1318)+n(1812)](),this[n(471)+n(1278)]?.[n(396)+n(1580)]()}}async flushExpired(){let n=t;(await this[n(1208)]?.[n(1124)]()||[])[n(1798)](({timestamp:f})=>f<Date.now())[n(711)](f=>{let g=n;this[g(1208)]?.[g(1194)](f.message_id)})}async[t(1194)](n){let s=t,d={EkOTX:function(f,g){return e.zQUST(f,g)}};return e[s(413)](e[s(1370)],e[s(1370)])?this._qosDB?.del(n):(_0x51d61c&&(_0x2dce0d=(0,_0x2afa01[XexLRv[s(1593)](_0x3c23d9,_0x2ed5d8)[0]])(_0x38b5cb=0)),_0x68410f)}async set(n,s){let d=t,f={dhbmZ:function(g,E,y){return e[F(1296)](g,E,y)}};if(e.uyKnI(e[d(1534)],e[d(601)]))return this._qosDB?.[d(948)]({message_id:n,timestamp:s});this._intervalTimeoutId=null,this._interval=36e5,this[d(1208)]=dkHyOk[d(1412)](_0x522626,d(1321),d(1539)+"id")}async[t(1605)](n){let s=t;return this[s(1208)]?.[s(1605)](n)}async closeDB(){let n=t;clearInterval(this[n(1872)+"lTimeoutId"]),await this._qosDB?.[n(1185)]()}get[t(655)](){let n=t;return this[n(1208)]?.[n(655)]}}function ya(a){let n=t,s={Yrtda:function(d,f){return d==f},BUhvW:e[n(1801)],Aigxh:function(d,f){return e[n(1828)](d,f)}};if(e[n(1854)](e.pHWDp,e[n(1786)])){let d=!!this._options.enableQoS;if(!d)return{enabled:d,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let f=e.vODzU(rn,a[n(612)][n(1219)],e[n(814)],"2"),g=f&&e[n(887)](rn,a[n(612)][n(1219)],e[n(1474)],"1"),E=f&&e.OaAvO(rn,a.message[n(1219)],e[n(525)],"1"),y=E?e[n(1830)](rr,a[n(612)][n(1219)],"x_fronti"+n(1480)+n(795))?.[n(609)](",")[n(1798)](Boolean)||[]:[];return{enabled:d,isQoSMessage:f,isQoSAck:g,isAckCleanupMessage:E,ackMsgIds:y}}else{if(iDFnzq[n(1148)](iDFnzq.BUhvW,typeof _0x4f1097)){let d=new _0x5c0508(iDFnzq.Aigxh(_0x220aa4,_0x4734b9));return _0x29f32f(_0x4e0849,d,0),d}return _0xf76c12 instanceof _0x1e0a03?new _0x673423(_0x4a2aa2):new _0x151348(_0x3d113d[n(522)],_0x2f3cdb[n(691)+"et"],_0x55d14b[n(1386)+"th"])}}async function gd(){let a=t;return this[a(836)+a(801)]||(this[a(836)+a(801)]=new jp),this[a(836)+a(801)][a(655)]||await this[a(836)+a(801)][a(466)](),this[a(836)+a(801)]}async function Wp(a,n){let s=t,d={SprQa:function(p,A,O,N){return p(A,O,N)},uyWjX:function(p,A){return e[F(965)](p,A)}},{enableAutoAck:f}=this[s(1611)],g=e[s(1495)](rn,a.message.headers,e.ltwWx,"1"),E=e[s(1274)](rn,a.message[s(1219)],s(1626),"1"),y=ya[s(434)](this,a);if(e[s(1740)](f,g))if(e[s(1247)](s(725),"uAshz")){let p=255&_0x58f16f;d[s(1366)](_0x56087d,p,_0x30c2cb,d[s(654)](_0x4942dd,_0x49c9c8)),_0x3d1768>>>=8,_0xc05897--}else{let{SeqID:p,LogID:A,service:O,LogIDNew:N,method:j}=a[s(612)];this[s(806)]({SeqID:p,LogID:A,LogIDNew:N,service:O,method:j,headers:[{key:s(1626),value:"1"},{key:e[s(1139)],value:N||""},{key:e[s(1400)],value:"0"}]})}E&&!y[s(974)]&&this["_dispatc"+s(1428)+"ageEvent"](a),e[s(967)](n)}async function Kp(a,n){let s=t;e[s(1012)](e[s(1268)],e.DgCmf)?(this._debug(s(1681),a[s(612)]),e[s(735)](n)):(this._DBName=_0x1417bb,this[s(1455)]=_0x2d4120,this[s(1208)]=_0x1c149b?_0x31282f:_0x5a2413?_0x4ca3fa:null)}async function $p(a,n){let s=t,d={FwHDW:e[s(923)],bIspT:e[s(870)]},f=e[s(1022)](en,await hd(a.data));try{if(e[s(1001)](f[s(775)],Uint8Array)){let g=this._options[s(1846)+"ncoding"]instanceof Object?{force:!!this[s(1611)][s(1846)+s(817)].force,encoding:this[s(1611)][s(1846)+"ncoding"][s(1283)]?this[s(1611)][s(1846)+s(817)][s(1283)][s(1663)](/\s/g,"")[s(586)+"ase"]():""}:{force:!1,encoding:this[s(1611)][s(1846)+s(817)]?this._options[s(1846)+s(817)][s(1663)](/\s/g,"")["toLowerC"+s(715)]():""},E=f[s(1846)+s(817)]?f[s(1846)+s(817)][s(1663)](/\s/g,"")[s(586)+s(715)]():"",y=e[s(1001)](this._options.payloadType,Object)?{force:!!this._options[s(1660)+s(1889)].force,type:this[s(1611)][s(1660)+"ype"][s(1361)]?this[s(1611)]["payloadT"+s(1889)].type[s(1663)](/\s/g,"")["toLowerC"+s(715)]():""}:{force:!1,type:this[s(1611)][s(1660)+s(1889)]?this[s(1611)][s(1660)+"ype"].replace(/\s/g,"")[s(586)+s(715)]():""},p=f[s(1660)+s(1889)]?f[s(1660)+s(1889)][s(1663)](/\s/g,"")[s(586)+"ase"]():"",A=y.force?y[s(1361)]:p||y[s(1361)],O=g[s(1265)]?g[s(1283)]:E||g[s(1283)],N=[e.hAjAf,e[s(1115)],e[s(597)],e[s(1801)]],j=[s(1693)+"e",e[s(1292)]];this._options[s(1130)+"ansformT"+s(790)+"ad"]&&N[s(582)](A)&&(!O||j[s(582)](O))?f[s(1773)+s(765)]=xd(f[s(775)],0,f[s(775)][s(1386)+"th"]):f[s(1773)+s(765)]=""}else f[s(1773)+s(765)]=""}catch(g){e[s(602)](e.ubXkv,e.ubXkv)?(f[s(1773)+s(765)]="",console[s(802)](g)):(_0x3e42d7&&_0x14deea["addEvent"+s(752)](aMHLDR[s(896)],()=>_0x55b6f0()),_0x52ff2f&&_0x145ecc[s(988)+s(752)](aMHLDR.bIspT,()=>_0x3b88c0()))}a.message=f,n()}function Vp(a,n,s){let d=t,f=e[d(627)](s,8192),g=e[d(1806)](f,1),E=null,y=f;return function(p){let A=d;if(e[A(626)](p,1)||e[A(935)](p,g))return e[A(783)](a,p);e.RVijE(e[A(1420)](y,p),f)&&(E=e.fakam(a,f),y=0);let O=n.call(E,y,y+=p);return e[A(1406)](7,y)&&(y=e[A(1158)](7,y)+1),O}}let Jp=4294967295;function Yp(a,n,s){let d=t,f={EikQE:e[d(382)]};if(e[d(1803)]!==e[d(1803)])this[d(1704)]&&this._ws[d(1049)](_0x6be2fc),this[d(1013)](f[d(829)],_0x330620);else return RangeError(e[d(1269)](e[d(1493)](e.YXNZo(e[d(1771)]+a+e[d(1792)],e[d(1675)](n,1)),d(1353)),s))}function Zp(a,n,s){let d=t,f={IcXGt:function(E,y){return e[F(1277)](E,y)}};if(e[d(839)](s,Jp))throw new Error(e[d(881)]);let g=3;for(;e[d(1193)](g,0);)if(e[d(869)]===e.iFhsj){let E=e[d(1057)](255,s);Ea(E,a,n+g),s>>>=8,g--}else if(cGapJz[d(521)](_0x3c2bf7,_0x20bd43))return _0x239c96;return e[d(716)](n,4)}function Xp(a,n){let s=t,d=0,f=n,g=e.XxBhQ(n,4);for(;e[s(1808)](f,g);){let{value:E,offset:y}=e[s(1432)](ba,a,f);f=y,d=e[s(1114)](d,8)>>>0,d+=E}return{value:d,offset:g}}function Qp(a,n,s){let d=t,f=e[d(1425)][d(609)]("|"),g=0;for(;;){switch(f[g++]){case"0":return e[d(1408)](wa,a,n,s)+s;case"1":if(n.utf8Write)return n[d(1392)+"e"](a,s)+s;continue;case"2":if(e[d(1146)](a[d(386)],40))return e[d(1682)](e[d(1274)](wa,a,n,s),s);continue;case"3":if(!a)return s;continue;case"4":if(n.write)return n[d(1395)](a,s)+s;continue}break}}function eg(a,n){let s=t,d=new fe(e[s(429)](e[s(1857)](e[s(1821)](a[e[s(863)](n,4)],24),a[e.QHmDe(n,5)]<<16)|e[s(1848)](a[e[s(719)](n,6)],8),a[e[s(1617)](n,7)]),e[s(1374)](a[e[s(716)](n,0)]<<24|e[s(992)](a[e.Xerpw(n,1)],16)|e.gzYtU(a[e[s(927)](n,2)],8),a[e[s(1414)](n,3)]),!0);return n+=8,{value:d,offset:n+8}}function tg(a,n,s){let d=t,f=a[d(1246)],g=a[d(1120)];return n[s]=g>>>24,n[e[d(1532)](s,1)]=e[d(541)](e[d(1134)](g,16),255),n[s+2]=e[d(1135)](e[d(1780)](g,8),255),n[e[d(636)](s,3)]=e[d(1667)](255,g),n[e.ZAePT(s,4)]=e[d(559)](f,24),n[s+5]=f>>>16&255,n[e[d(973)](s,6)]=e[d(773)](f>>>8,255),n[e.BSncz(s,7)]=e[d(1627)](255,f),s+=8,s}function ba(a,n){let s=t;if(e.irpxG(s(368),e[s(1544)])){let d=this[s(1144)+s(938)]?.[s(591)+s(1683)+"nt"](),f=this[s(1611)][s(1632)+s(1556)+s(1470)](_0x237ea5[s(441)],_0x3c00be.reason);this[s(1060)+s(832)+s(1789)](e.rVxMZ(_0x29e323,e.crRMx,{code:1006,reason:_0x392822[s(1087)]||"connecting faile"+s(1028)+s(1141)+s(476)+"ame: "+d,willReconnect:f})),f&&this[s(538)]();return}else return a[s(1847)+"8"]?{value:a[s(1847)+"8"](n),offset:e[s(652)](n,1)}:{value:e[s(1160)](255,a[n]),offset:e[s(911)](n,1)}}function Ea(a,n,s){let d=t;return n[d(1375)+"t8"]?n.writeUint8(a,s):n[s]=255&a,e[d(719)](s,1)}let ng=function(a){return new Uint8Array(a)},rg=e.kItsc(e[t(882)],typeof Buffer)?Buffer["allocUns"+t(1127)]:e[t(1492)](Vp,ng,Uint8Array[t(981)+"e"][t(1466)]),ig=16,va=32;function sg(a){let n=t;if(e.FoJvR(e.PemYm,e.PemYm))return _0x4b0cd8[n(1447)](_0xdc7b9)||(_0x2db9f2=_0xf300c5.fromNumber(_0xc47749)),e[n(1854)](this[n(1898)],_0x555070[n(1898)])&&e[n(1802)](this[n(1120)]>>>31,1)&&e[n(485)](e[n(1780)](_0x3373d5[n(1120)],31),1)?!1:this.high===_0x11839d[n(1120)]&&this[n(1246)]===_0x47b4ad.low;{let s=0,d={};for(let f=0;e.yoVTa(f,a[n(386)]);f++)d[a[f][n(629)+n(1005)]]=e.Allkg(fd,a[f]["cursor_n"+n(1005)]),s+=e[n(858)](14,d[a[f][n(629)+n(1005)]]);return[s,d]}}function md(a,n,s){let d=t,[f,g]=e[d(1017)](sg,a),E=e[d(1725)](rg,f),y=0;return a[d(711)](p=>{let A=d;console[A(802)](e.BLRBf,p,p[A(1875)]),y=e[A(542)](Ea,0,E,y),console[A(802)](e[A(1155)],y),y=e[A(1761)](Zp,E,y,p[A(1875)]||0),console.log(A(1875),y),y=e.aGirP(Ea,g[p[A(629)+A(1005)]],E,y),console.log(e.mGNiq,y),y=e.TqVps(Qp,p["cursor_n"+A(1005)],E,y),console[A(802)](A(1823),y),y=e.YqzFE(tg,fe[A(531)+"er"](p[A(1868)]||n),E,y),console[A(802)](e.KZPTg,y)}),{frameType:va,headers:[{key:e[d(1053)],value:s}],payload:E}}function og(a){let n=t,s=0,d=[];for(;e[n(1146)](s,a[n(1386)+"th"]);){let{offset:f}=ba(a,s);s=f;let g={cursor_name:"",cursor:0,service:0},{value:E,offset:y}=e.slOUI(Xp,a,s);g.service=E,s=y;let{value:p,offset:A}=ba(a,s);s=A,g["cursor_n"+n(1005)]=e[n(595)](xd,a,s,e[n(446)](s,p)),s+=p;let{value:O,offset:N}=e.KOpLF(eg,a,s);g[n(1868)]=O[n(847)](),s=N,d[n(1664)](g)}return d}function ag(){let a=t;if(e[a(1869)](a(616),e[a(504)])){let n="4|3|2|0|1"[a(609)]("|"),s=0;for(;;){switch(n[s++]){case"0":this._isInit=!0;continue;case"1":this[a(538)]();continue;case"2":this[a(412)+"osed"]=!1;continue;case"3":this["_pingLos"+a(1278)]?.["resetCou"+a(1580)]();continue;case"4":this["_endpoin"+a(938)]?.[a(1482)+a(1318)+a(1812)]();continue}break}}else return{frameType:va,headers:[{key:a(1394)+"ile_name",value:a(1631)+a(494)}],payload:void 0}}class cg{constructor(n,s,d){let f=t;this["_cursorN"+f(892)]=n,this[f(1629)+"ileName"]=s,this[f(406)+f(1673)]=d,this[f(1208)]=e[f(1899)](pd,this[f(402)+f(892)],e[f(543)])}async[t(466)](){let n=t;await this[n(1208)][n(466)]()}async[t(1750)+"rs"](){let n=t;if(!this._qosDB[n(655)])return;let s=this[n(406)+n(1673)],d=await this[n(1208)].getAll();switch(console[n(802)](e[n(376)],d),s){case n(706):return d&&d[n(386)]?e[n(865)](md,d,0,this[n(1629)+n(1718)]):void 0;case e.wxEQx:return;case e[n(751)]:return d&&d.length?e[n(687)](md,d,0,this["_cursorF"+n(1718)]):ag()}}async set(n,s,d){let f=t;return console[f(802)](e[f(1369)],n,s,d),this._qosDB[f(948)]({cursor_name:n,cursor:s,service:d})}async setCursors(n){let s=t,d=e[s(918)](og,n);for(let f of d)console[s(802)](s(1657)+"r",d),await this[s(1208)].set(f)}async[t(1605)](n){return(await this[t(1208)].get(n))?.cursor}async[t(1185)](){let n=t;await this._qosDB[n(1185)]()}["updateCu"+t(1319)+t(1011)](n){let s=t;this[s(1629)+s(1718)]=n}get[t(655)](){return this[t(1208)].isReady}}let lg="__x_msg_"+t(1252);async function wd(a){let n=t;if(!this[n(1611)][n(661)+"S"])return null;let{aID:s,fpID:d,messageStrategy:f}=this[n(1611)],g=e[n(955)](a,lg);try{return this[n(534)+"anager"]?e[n(512)](e.twPGH,e[n(1597)])?(e[n(740)](_0x3311f3,e.GKfyE),this[n(1616)](e[n(569)],_0x419232),this[n(1616)](e.GOOWY,_0x5694ec)):a&&this[n(534)+n(1328)][n(1294)+n(1319)+"Name"](a):this._cursorManager=new cg(d+"_"+s+"_"+g,g,f),this[n(534)+n(1328)][n(655)]||await this[n(534)+n(1328)][n(466)](),this[n(534)+"anager"]}catch{if(e[n(425)](e.HfPfY,e[n(1285)])){let E=_0x578fb5["deleteDa"+n(1472)](_0xbada5f);return _0xfaf9d2&&E[n(988)+"Listener"]("blocked",()=>_0x456770()),_0xd70384(E)[n(1732)](()=>{})}else return null}}async function dg(a,n){let s=t,d={iJObA:function(q,te,Ye){return q(te,Ye)}},f=rn(a[s(612)][s(1219)],e[s(793)],"-1"),g=rn(a[s(612)][s(1219)],e[s(1303)],"1"),E=e[s(1296)](rr,a.message[s(1219)],e[s(1216)]),y=e[s(1463)](Number,e[s(447)](rr,a[s(612)][s(1219)],s(902)+"er_ttl"))||0,p=ya[s(434)](this,a),A=e[s(750)](rn,a.message[s(1219)],e.yiKLf,"2"),O=e.ApXcx(rr,a[s(612)].headers,e.xnniE),N=e[s(1338)](Number,e.ZeNOt(rr,a[s(612)][s(1219)],e[s(1662)]));if(p[s(974)])return e[s(611)](n);let j=p["isQoSMes"+s(788)]?await gd[s(434)](this):null;if(e[s(374)](a[s(612)][s(1875)],0)&&g&&!f||e[s(842)](a[s(612)][s(1875)],0)){if(E&&p[s(1809)+"sage"]&&j)return!!!await j[s(1605)](E)&&(this["_dispatc"+s(1357)+s(1570)](a),await j[s(948)](E,Date[s(1344)]()+y)),e[s(611)](n);if(A){let q=await wd[s(434)](this);if(!q){if(e[s(1012)](e[s(1376)],s(944)))return this["_dispatc"+s(1357)+s(1570)](a),e[s(1092)](n);{let Ye=this["_endpoin"+s(938)]?.[s(591)+s(1683)+"nt"]();this[s(1060)+s(832)+s(1789)](d[s(950)](_0x34b4be,s(605),{code:1006,reason:"connect "+Ye+(s(1359)+", max re"+s(1430)+s(680)),wasClean:!0}))}}let te=await q[s(1605)](O)??-1;if(e[s(1858)](te,N))this[s(1060)+s(1357)+s(1570)](a),q[s(948)](O,N,a.message[s(1875)]);else throw new Error(s(1004)+" message"+s(1061)+N+(s(1070)+"than loc"+s(1290)+"r ")+te);return e[s(1092)](n)}return this["_dispatc"+s(1357)+"Event"](a),e[s(718)](n)}}async function ug(a,n){let s=t,d=ya[s(434)](this,a);if(!d.isQoSMessage)return e.GdHsk(n);let f=await gd[s(434)](this);if(d[s(498)+s(1276)+s(1033)]&&d[s(1349)+"s"][s(386)])for(let g of d.ackMsgIds)await f[s(1194)](g);n()}async function fg(a,n){let s=t,d=e[s(1720)](a[s(612)].frameType,ig),f=e[s(1891)](a.message[s(481)+"e"],va);if(!d&&!f)return e[s(407)](n);let g=e[s(1505)](rr,a[s(612)].headers,e.AxwWq);if(!g)return e.pvKSe(n);let E=await wd[s(434)](this,g);if(!E)return e.GsUwB(n);if(d){let y=await E[s(1750)+"rs"](),p={frameType:y?.["frameType"],SeqID:fe[s(531)+"er"](this[s(660)]++),LogID:fe[s(531)+"er"](this[s(1611)][s(810)+s(1637)]()),service:9e3,method:5,headers:y?.[s(1219)],payload:y?.[s(775)]},A=e[s(980)](S,p);this[s(1704)]&&this._ws.readyState&&this[s(1704)][s(1049)](A)}if(f){let y=a[s(612)][s(775)];y&&E[s(675)+"rs"](y)}}let xg=async function(a,n){let s=t;this[s(1485)]=!1,e[s(1558)](clearTimeout,this["_connectionTimeo"+s(1098)]),n()},hg=async function(a,n){let s=t;if(!this[s(1704)]||e.TgAva(this._ws[s(1537)+"te"],this[s(1008)]))return e[s(1257)](n);let{pingInterval:d}=this[s(1611)];this[s(1144)+s(938)]?.["resetEndpointCon"+s(1812)]();for(let g=0;e[s(1864)](g,this[s(406)+s(553)][s(386)]);g++){let E=this["_message"+s(553)][g];if(this[s(1704)][s(1537)+"te"]===this.OPEN&&e[s(1233)](null,E))this[s(1704)]&&this._ws[s(1049)](E),this[s(406)+s(553)][g]=null;else break}this[s(406)+s(553)]=this[s(406)+s(553)][s(1798)](g=>!!g),this._pingPongTimeoutId=e[s(733)](setTimeout,()=>this[s(1365)](),d),this[s(1060)+s(1284)+"nt"](a),this[s(1305)+"er"]&&this[s(1704)]&&(this._ws.binaryType=this[s(1716)+s(1889)]);let f=this._endpointManager?.[s(591)+s(1683)+"nt"]();this._debug("open "+f+s(1182)),e[s(1587)](n)},pg=async function(a,n){let s=t,d=this["_endpoin"+s(938)]?.getCurrentEndpoint();this[s(1013)](s(1142)+d),e[s(1356)](n)};class gg extends ma{constructor(n){let s=t,d={UmowL:function(y,p){return e[F(409)](y,p)},gEqUn:e[s(1501)],gFKGo:function(y,p){return e.vrtki(y,p)},nAgVH:"auto",xSbKK:s(894),YEePA:function(y,p){return y===p},neKtu:function(y,p,A,O){return e[s(1408)](y,p,A,O)},jjwnu:function(y,p,A){return e.MGLBN(y,p,A)},PLPZG:function(y,p,A){return e[s(1811)](y,p,A)},pBhAf:e.rPyJq};super(),this[s(1025)+s(482)+s(1766)]=!0,this[s(1305)+"er"]=nr,this[s(1877)]=Pp,this[s(977)+"T"]=Cn,this[s(1590)+"X"]=Xr,this._isWorker=Qr,this[s(406)+s(553)]=[],this[s(1144)+"tManager"]=null,this[s(412)+s(1849)]=!1,this["_binaryT"+s(1889)]=e.nWEzI,this["_connect"+s(746)]=!1,this["_connectionTimeo"+s(1098)]=null,this[s(527)+s(998)+"tId"]=null,this[s(1702)+s(457)+"Id"]=null,this[s(660)]=0,this[s(1485)]=!1,this[s(546)]="",this[s(836)+s(801)]=null,this[s(534)+"anager"]=null,this[s(471)+s(1278)]=null,this._protocols=e[s(1680)],this[s(1865)]=3,this[s(1161)+"NG"]=0,this[s(1008)]=1,this[s(910)]=2,this[s(380)]=y=>{let p=s;try{e[p(1410)](ud,this,y,[xg,hg,pg])}catch(A){let O=ct(e[p(1529)],{message:A[p(612)],code:nn[p(614)+"OR"],error:A});this[p(1060)+p(676)+p(1789)](O)}},this._onMessage=async y=>{let p=s,{pingInterval:A,pingFrequency:O}=this[p(1611)];if((y.data==="hi"&&d.UmowL(d.gEqUn,O)||d[p(1502)](d[p(1273)],O))&&(this[p(1105)+"ngTimer"](),this.emit(p(387)+p(1024)+"s",d.xSbKK),this["_pingPon"+p(457)+"Id"]=setTimeout(this[p(1365)][p(964)](this),A)),!d[p(698)]("hi",y[p(916)]))try{d[p(1645)](ud,this,y,[$p,Wp,ug,fg,dg,Kp])}catch(N){let j=d[p(1151)](ct,p(644),{message:N.message,code:nn[p(852)+p(671)],error:N});this[p(1060)+"hErrorEv"+p(1789)](j)}},this[s(1566)]=y=>{let p=s,A=this[p(1144)+p(938)]?.[p(423)+p(975)+"es"](),O=this["_endpoin"+p(938)]?.[p(591)+p(1683)+"nt"]();if(A&&!y.message){let N=p(1209)+O+(" fail, m"+p(526)+p(1323)+"ed");this[p(1060)+"hErrorEvent"](d[p(657)](ct,d[p(1520)],{message:N,code:nn["MAX_RETR"+p(1625)+"R"],error:y}));return}this._ws&&d.UmowL(this[p(1704)][p(1537)+"te"],this[p(1008)])&&this[p(850)+p(1649)](),this[p(1060)+"hErrorEv"+p(1789)](ct(d[p(1520)],{message:y.message,code:nn[p(1618)+"RROR"],error:y}))},this[s(1255)]=async y=>{let p=s,A={jYVWV:function(N,j){return e[F(1358)](N,j)}};this[p(1051)+p(1067)](),this[p(1105)+p(1390)](),this[p(617)+"sListeners"](),this[p(1704)]=null,this._connectLock=!1;let O=this[p(1144)+p(938)]?.[p(423)+p(975)+"es"]();if(!O&&this[p(519)+p(1306)]()&&!this[p(412)+p(1849)]){let N=this[p(1144)+"tManager"]?.[p(591)+p(1683)+"nt"](),j=this[p(1611)][p(1632)+p(1556)+"ptor"](y[p(441)],y[p(1087)]);this["_dispatc"+p(832)+p(1789)](gt(e.crRMx,{code:1006,reason:y[p(1087)]||p(590)+p(1734)+p(1028)+p(1141)+p(476)+"ame: "+N,willReconnect:j})),j&&this._connect();return}if(y.code!==1e3&&this[p(412)+"osed"]){this[p(1060)+p(832)+p(1789)](e[p(1492)](gt,e[p(923)],{code:1e3,reason:p(1450)})),this[p(1144)+p(938)]?.[p(1482)+"pointCon"+p(1812)](),this[p(471)+p(1278)]?.[p(396)+p(1580)]();return}if(e[p(759)](1e3,y.code)&&O)if(e[p(1233)](e[p(723)],e[p(467)])){let N=this[p(1144)+p(938)]?.[p(591)+p(1683)+"nt"](),j=y[p(1087)];j||(j=await e[p(783)](Fp,this[p(546)])),j=p(590)+"ng failed, "+j+(", hostna"+p(1747))+N+(", max re"+p(1430)+p(680)),this[p(1060)+p(832)+p(1789)](e.Mesie(gt,e[p(923)],{code:y[p(441)],reason:j}));let q="connect "+N+(p(748)+p(526)+"es reached");this[p(1060)+p(676)+p(1789)](e[p(1492)](ct,p(644),{message:q,code:nn["MAX_RETR"+p(1625)+"R"]})),this[p(1144)+p(938)]?.[p(1482)+p(1318)+p(1812)](),this[p(471)+p(1278)]?.["resetCou"+p(1580)]();return}else{let N=this[p(1208)][p(822)+"geInfoSync"](this._prefix),j=_0xe87f39[p(694)](bIVYor[p(1878)](N,"{}"));return _0x58a8c2[p(1594)](j)}if(e[p(714)](1e3,y[p(441)])&&!y[p(1087)]){let N=this._endpointManager?.[p(591)+p(1683)+"nt"]();this[p(1060)+p(832)+p(1789)](e[p(411)](gt,e[p(923)],{code:y[p(441)],reason:"connecti"+p(1734)+p(1028)+p(1141)+p(476)+p(1551)+N})),this[p(1144)+p(938)]?.["resetEnd"+p(1318)+"fig"](),this[p(471)+p(1278)]?.[p(396)+p(1580)]();return}this[p(1060)+"hCloseEv"+p(1789)](y),this[p(1144)+p(938)]?.[p(1482)+p(1318)+p(1812)](),this[p(471)+p(1278)]?.["resetCou"+p(1580)]()},this[s(1620)]=null,this[s(1600)]=null,this[s(1297)+"e"]=null,this[s(1880)]=null,this[s(1743)+s(1316)]=null,this["onReceiv"+s(1106)]=null,this[s(648)+s(1054)+s(1837)+"ct"]=null,this[s(630)+"nLine"]=this[s(630)+"nLine"].bind(this),this._handleOffLine=this["_handleO"+s(1843)].bind(this),this[s(1031)+s(895)]=this[s(1031)+s(895)].bind(this),this[s(1031)+"ageShow"]=this[s(1031)+s(1313)][s(964)](this),this[s(1611)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1874)](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:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(751)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:g}=n,E=Array[s(926)](f)?f:typeof f=="string"?[f]:[];if(!E||E[s(386)]===0)throw new Error(e[s(1444)]);if(!e[s(736)](Np,g))throw new Error(s(769)+"rovide w"+s(1065)+s(837)+"ket cons"+s(1198)+s(1073)+s(905));if(Object[s(1473)](this._options,n),this[s(1144)+s(938)]=new dd(E,this[s(1611)].maxRetries),this[s(471)+s(1278)]=new zp(this[s(1611)][s(628)+s(1443)]),this[s(1611)]["automati"+s(561)])if(e[s(548)](e[s(392)],e[s(392)]))this[s(1485)]=!0,this[s(538)]();else return new _0x29f8e9(_0x3db038);this._options[s(1201)+"tworkCha"+s(1021)]&&(this[s(977)+"T"]||this[s(1590)+"X"]?this[s(1066)+s(903)+s(1200)]():this[s(1305)+"er"]&&this["_initGlo"+s(420)+s(752)]())}[t(630)+t(1156)](){let n=t;this[n(1611)][n(650)+n(574)+n(537)]||this[n(412)+n(1849)]||this["_handleR"+n(1316)]()}[t(630)+t(1843)](){let n=t;this[n(1538)+"WebSocket"]();let s=e[n(1295)](ga,e[n(1382)],{message:e[n(1213)]});this[n(648)+n(1054)+n(1837)+"ct"]&&this["onStopIm"+n(1054)+n(1837)+"ct"](s)}[t(811)+t(420)+t(752)](){let n=t;this[n(1305)+"er"]&&window[n(988)+n(752)](e[n(843)],this[n(630)+n(1156)]),this[n(1305)+"er"]&&window[n(988)+n(752)](e[n(579)],this[n(630)+n(1843)]),this[n(1305)+"er"]&&window[n(988)+n(752)](e[n(809)],this["_handleP"+n(895)]),this[n(1305)+"er"]&&window["addEvent"+n(752)](e[n(1883)],this._handlePageShow)}[t(1402)+t(420)+t(752)](){let n=t;e.KDotG(e.QfRzn,e[n(445)])?(this[n(1305)+"er"]&&window[n(1462)+n(949)+n(1636)](e[n(843)],this[n(630)+"nLine"]),this[n(1305)+"er"]&&window[n(1462)+n(949)+n(1636)](n(701),this["_handleO"+n(1843)]),this[n(1305)+"er"]&&window[n(1462)+n(949)+n(1636)](e[n(809)],this[n(1031)+n(895)]),this[n(1305)+"er"]&&window.removeEventListener(e.PFXpB,this[n(1031)+n(1313)])):this[n(1629)+"ileName"]=_0x13e313}[t(1031)+t(895)](n){let s=t;e[s(417)]===e.LcnXV?(!n[s(1221)+"d"]&&(this[s(1305)+"er"]&&window[s(1462)+"entListener"](s(1757),this[s(1031)+s(895)]),this[s(1305)+"er"]&&window["removeEv"+s(949)+s(1636)](e[s(1883)],this["_handleP"+s(1313)]),this[s(605)]()),this[s(1305)+"er"]&&window[s(1462)+s(949)+s(1636)](e[s(843)],this[s(630)+s(1156)]),this[s(1305)+"er"]&&window[s(1462)+s(949)+"ner"](s(701),this[s(630)+s(1843)])):(this[s(1364)+"ount"]=_0x48d6d6,this.count=0)}["_handleP"+t(1313)](n){let s=t,d={FUKue:function(f,g){return f(g)},rFZPX:s(1494)+"or",hiJKu:function(f){return e[s(1257)](f)}};if(e.WsLtQ(e.DBgaX,s(976)))n[s(1221)+"d"]&&(this[s(519)+s(1306)]()&&(!this[s(1704)]||e[s(1247)](this[s(1704)].readyState,this[s(1008)])||e.lkpry(this[s(1704)].readyState,this[s(1161)+"NG"]))&&this["_handleO"+s(1156)](),this[s(1305)+"er"]&&window["addEvent"+s(752)](e[s(843)],this[s(630)+"nLine"]),this._isBrowser&&window["addEvent"+s(752)](e.hOgGm,this[s(630)+"ffLine"]));else{let f={KWcEC:NGKNDN[s(1886)],XNtFq:NGKNDN[s(1467)],oVVky:function(p){let A=s;return NGKNDN[A(1257)](p)}},g=()=>{let p=s;_0x25fbda[p(1462)+p(949)+p(1636)](f[p(486)],E),_0x352419[p(1462)+"entListe"+p(1636)](p(644),y),_0x24267e[p(1462)+p(949)+p(1636)](f[p(1533)],y)},E=()=>{f[s(690)](_0x17c619),g()},y=()=>{let p=s;BtVSwC.FUKue(_0x2ffd84,_0x22c78b[p(644)]||new _0x3196ed(BtVSwC[p(514)],BtVSwC[p(514)])),BtVSwC[p(1327)](g)};_0x2be5b5[s(988)+s(752)](s(1855),E),_0x1bb09b[s(988)+s(752)]("error",y),_0x596655[s(988)+s(752)](NGKNDN[s(1467)],y)}}async[t(1724)+t(996)](n){let s=t,{fpID:d,deviceID:f,bddID:g,ttwID:E,accessKey:y,aID:p,customParams:A={},enableAutoAck:O,enableQoS:N,QoSLevel:j,env:q}=this._options,te,Ye,xe;this[s(1305)+"er"]||this[s(1590)+"X"]||this[s(977)+"T"]?(te=location&&e[s(1839)](e.BzJfy,location[s(1163)])?e[s(762)]:e[s(1433)],Ye=n.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),xe=/^wss(.*:\/\/)/[s(1526)](n)?n:""+te+Ye):(te=e.NZApg,Ye=n.replace(/(^http)((?:[s]*:\/\/))/,""),xe=/(^ws)((?:[s]*:\/\/))/[s(1526)](Ye)?Ye:""+te+Ye);let lt=g?s(1475):E?e[s(1072)]:s(1820)+"d",ei=g||E||f;if(e.wTSmY(!ei,!lt))throw new Error(e[s(604)]);let ir=e[s(1839)](s(1449),typeof A)?await e.Ejxmw(A):A,Sa=q?e[s(978)](Bp,q.xUseEnv,q[s(1573)]):{},ti=Object[s(1473)]({device_platform:e[s(1084)],version_code:e.LQzjl,access_key:y,fpid:d,aid:p,[lt]:ei,xsack:O?1:0,xaack:O?1:0,xsqos:N?1:0,qos_level:N?j:void 0,qos_sdk_version:2,...Sa},ir),fs=Object[s(1594)](ti).reduce((ni,ri)=>ti[ri]!==void 0?""+ni+(ni?"&":"?")+ri+"="+ti[ri]:ni,"");return xe+s(1387)+fs}async[t(538)](){let n=t,s={MnrjW:function(d,f){return e[F(1417)](d,f)},Nuqyb:function(d,f){return e[F(1700)](d,f)},KlKCB:function(d,f){return e[F(1893)](d,f)},jWDVK:function(d,f){return e.iMMAE(d,f)},PJjUo:function(d,f){return e.yrRLL(d,f)},EbftZ:function(d,f){return e[F(1158)](d,f)},PnKxO:function(d,f){return e.DtuWc(d,f)},zQvxU:function(d,f){return d|f},GJVPp:function(d,f){return e.utFVF(d,f)},rXoTr:function(d,f){return e[F(1722)](d,f)},pOrGD:function(d,f){return e[F(934)](d,f)},FrpQW:function(d,f,g,E){return e[F(1322)](d,f,g,E)},Uklmc:function(d,f){return d|f},lhnoR:function(d,f){return e[F(1082)](d,f)},bTqkI:function(d,f){return e[F(1326)](d,f)},AYICG:function(d,f){return e[F(1489)](d,f)},NJcOy:function(d,f){return e[F(1852)](d,f)},GRfQo:function(d,f){return e[F(1027)](d,f)},froVh:function(d,f){return e.EGIfG(d,f)},RUSZy:function(d,f){return e[F(1038)](d,f)},OcPHA:function(d,f){return d&f}};if(!(this[n(538)+n(746)]||this[n(412)+n(1849)])){this["_connect"+n(746)]=!0;try{if(e[n(602)](e[n(1547)],e[n(749)])){let d=4294967295;return function(f,g,E=!0){let y=n;if(d=egzuLs.MnrjW(127&f[g],0),egzuLs[y(456)](f[g++],128))return{value:E?d:egzuLs[y(1403)](0,d),offset:g};if(d=egzuLs[y(550)](egzuLs[y(1403)](d,egzuLs[y(1853)](egzuLs.PJjUo(127,f[g]),7)),0),egzuLs.Nuqyb(f[g++],128))return{value:E?d:egzuLs[y(599)](0,d),offset:g};if(d=egzuLs[y(599)](d,egzuLs[y(857)](egzuLs[y(943)](127,f[g]),14))>>>0,egzuLs[y(456)](f[g++],128))return{value:E?d:0|d,offset:g};if(d=egzuLs[y(489)](d,egzuLs[y(1853)](127&f[g],21))>>>0,f[g++]<128)return{value:E?d:egzuLs[y(599)](0,d),offset:g};if(d=egzuLs[y(550)](egzuLs[y(489)](d,egzuLs[y(427)](egzuLs[y(1542)](15,f[g]),28)),0),f[g++]<128)return{value:E?d:egzuLs[y(599)](0,d),offset:g};if(egzuLs.pOrGD(g+=5,f[y(386)]))throw g=f[y(386)],egzuLs.FrpQW(_0x3d37aa,g,10,f[y(386)]);return{value:E?d:egzuLs[y(603)](0,d),offset:g}}}else{let d=this["_endpoin"+n(938)]?.[n(1767)+n(828)+n(1642)+n(391)+"tries"](),{timeoutInterval:f}=this[n(1611)];if(d)if(e.EryGy(e[n(1360)],n(1540))){let E=_0x4dcef3[n(1246)],y=_0x1c96e5[n(1120)];return _0x579b0c[_0xc3ef21]=egzuLs[n(1567)](y,24),_0x3d7fe8[egzuLs[n(1678)](_0x526f3b,1)]=egzuLs[n(663)](y>>>16,255),_0x3b5b7f[egzuLs[n(989)](_0x11b7da,2)]=egzuLs.AYICG(y>>>8,255),_0x3e896a[egzuLs[n(989)](_0x4e5329,3)]=egzuLs[n(959)](255,y),_0x3dfdd7[egzuLs[n(1678)](_0x3c150b,4)]=egzuLs[n(1567)](E,24),_0x187579[egzuLs.froVh(_0x5c0f29,5)]=egzuLs[n(933)](egzuLs[n(550)](E,16),255),_0x227bbf[egzuLs[n(1678)](_0x45630b,6)]=egzuLs[n(1567)](E,8)&255,_0x3ca489[_0x3d7711+7]=egzuLs.OcPHA(255,E),_0x3ff753+=8,_0x1b1859}else{let E=this[n(1144)+n(938)]?.[n(591)+n(1683)+"nt"](),y=this["_endpoin"+n(938)]?.[n(1335)+n(1543)+n(571)+"UpdateCo"+n(963)](),p=this[n(1144)+n(938)]?.[n(591)+n(1683)+n(1615)+n(1248)]();if(y){let A=n(1209)+E+(n(1359)+n(1576)+"tries reached, w"+n(1334)+n(1799)+"ndpoint ")+y+(n(1779)+"y"),O=e[n(1896)](ct,e.rPyJq,{message:A,code:nn[n(710)+n(1625)+"R"]});this[n(1013)](A),this[n(1060)+n(676)+n(1789)](O),this[n(546)]=await this["_generat"+n(996)](y),this[n(1013)](n(1209)+y+" "+p+n(523)),this[n(617)+n(653)+"rs"]()}else{let A=n(1209)+E+(n(1359)+", max re"+n(1430)+n(680));this[n(1013)](A),this[n(1060)+n(676)+n(1789)](e.zmCWN(ct,e.rPyJq,{message:A,code:nn[n(710)+n(1625)+"R"]}));return}}else{let E=this[n(1144)+"tManager"]?.[n(591)+n(1683)+"ntAndUpd"+n(1661)](),y=this[n(1144)+n(938)]?.["getCurre"+n(1683)+n(1615)+n(1248)]();this._url=await this[n(1724)+n(996)](e[n(1668)](E,"")),this[n(1013)]("connect "+E+" "+y+n(523)),this[n(617)+n(653)+"rs"]()}if(this[n(1485)])this[n(1485)]=!1;else{let E=e.YrPKK(ga,e.SVoKt,{message:n(886)});this[n(1743)+n(1316)]&&this[n(1743)+n(1316)](E)}let g=this["_endpoin"+n(938)]?.["getCurre"+n(1683)+n(1615)+n(1248)]()||0;e.RVijE(g,1)&&await this[n(796)](e.NNBYF(g,1)),this[n(1013)]("connecting url: "+this[n(546)]+(n(454)+n(1685))+this._protocols),this[n(1704)]=Op({url:this[n(546)],protocols:[this[n(1230)+"ls"]],headers:this[n(1611)][n(1760)+"ramParams"][n(1741)+"tpHeader"]},this._options.ws),(this[n(1305)+"er"]||this[n(497)+"r"])&&this[n(1704)]&&(this._ws[n(503)+"pe"]=this[n(1716)+"ype"]),this[n(1014)+n(1093)](),this["_connectionTimeo"+n(1098)]=e[n(1340)](setTimeout,this[n(879)+"ut"][n(964)](this),f)}}catch(d){throw this[n(538)+"Lock"]=!1,d}}}["_clearTi"+t(1067)](){let n=t;e[n(1463)](clearTimeout,this[n(538)+"ionTimeoutId"]),this[n(538)+n(1739)+n(1098)]=null}[t(1105)+t(1390)](){let n=t;clearTimeout(this[n(1702)+n(457)+"Id"]),clearTimeout(this[n(527)+n(998)+n(1383)]),this._pingPongTimeoutId=null,this["_reconnectTimeou"+n(1383)]=null}[t(1013)](...n){this[t(1611)].debug&&console.log.apply(console,[e.bSeLi,...n])}["_getInte"+t(970)+"e"](n){let s=t,{initReconnectInterval:d,maxReconnectInterval:f,reconnectIntervalGrowFactor:g}=this._options,E=d*Math[s(728)](g,n-1);return e[s(374)](E,f)?f:E}[t(1365)](){let n=t;if(this._ws&&this._ws[n(1537)+"te"]===this.CONNECTING){this["_clearPi"+n(1390)](),this[n(1702)+"gTimeoutId"]=e[n(1804)](setTimeout,this[n(1365)][n(964)](this),this._options[n(1442)+n(757)]);return}if(!this._ws||this._ws[n(1537)+"te"]!==this[n(1008)])return void this._handleReconnect();this[n(1704)]&&this[n(1704)][n(1049)]("hi"),this["_reconnectTimeou"+n(1383)]=e.JGoQY(setTimeout,this[n(1388)+n(1316)+"Timeout"].bind(this),this[n(1611)]["pingTime"+n(708)+n(1311)])}["_handleReconnect"+t(962)](){let n=t,s={LhHVl:e[n(1860)]};if(e.wynnX(e.yUDoV,e[n(1379)]))this[n(471)+"sCounter"]?.[n(1091)](),this[n(1595)](n(387)+n(841)+"t",e[n(554)]),this._pingLossCounter?.[n(423)+n(1752)+"nt"]()?this[n(1388)+"econnect"]():this._ping();else{if(!this[n(519)+n(1306)]()||this[n(412)+n(1849)])return;this["_endpoin"+n(938)]?.[n(1482)+"pointConfig"](),this["_pingLos"+n(1278)]?.[n(396)+n(1580)](),this[n(1704)]?this[n(850)+n(1649)](1001,s[n(1656)],!0):this[n(538)]()}}[t(519)+t(1306)](){let n=t;return this[n(977)+"T"]||this[n(1590)+"X"]?this[n(1025)+"igatorOnline"]:(this[n(1305)+"er"]||this._isWorker)&&this[n(1611)][n(1201)+n(1815)+n(1021)]?navigator[n(1822)]:!0}[t(1388)+t(1316)](){let n=t;!this["_navigat"+n(1306)]()||this[n(412)+n(1849)]||(this[n(1144)+n(938)]?.["resetEnd"+n(1318)+n(1812)](),this[n(471)+n(1278)]?.["resetCou"+n(1580)](),this[n(1704)]?this._disconnect(1001,"going aw"+n(1677)+"reconnecting ser"+n(1746),!0):this[n(538)]())}[t(1066)+t(903)+"ange"](){let n=t;this[n(977)+"T"]?tt[n(819)+n(669)+n(480)](({isConnected:s})=>{let d=n;this[d(1025)+"igatorOn"+d(1766)]=s,s?this[d(630)+"nLine"]():this[d(630)+d(1843)]()}):this._isMiniWX&&wx["onNetwor"+n(669)+n(480)](({isConnected:s})=>{let d=n;this["_miniNav"+d(482)+d(1766)]=s,s?this[d(630)+d(1156)]():this[d(630)+d(1843)]()})}_wait(n){let s={RNqIY:function(d,f,g){return e[F(442)](d,f,g)}};return new Promise(d=>{let f=F;s.RNqIY(setTimeout,d,this[f(608)+"rvalValue"](n))})}[t(850)+t(1649)](n=1e3,s="",d=!1){this._ws&&this._destroyWebSocket(n,s,d)}[t(879)+"ut"](){let n=t,s=this[n(1144)+n(938)]?.[n(591)+n(1683)+"nt"]();this[n(1013)](n(1209)+s+" timeout"),this[n(850)+n(1649)](1001,e[n(724)],!0)}[t(806)](n){let s=t,d=e.csTWC(Ft,n);this[s(1704)]&&this._ws.readyState===this[s(1008)]&&(this._ws&&this[s(1704)][s(1049)](d),this._debug(e.aezzb,n))}[t(617)+t(653)+"rs"](){let n=t,s=e[n(1769)][n(609)]("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(1704)][n(1462)+n(949)+n(1636)](e.WXbYP,this._onMessage);continue;case"1":this[n(1704)][n(1462)+n(949)+"ner"](e.cXVrH,this._onOpen);continue;case"2":this[n(1704)][n(1462)+"entListener"]("close",this[n(1255)]);continue;case"3":if(!this[n(1704)])return;continue;case"4":this[n(1704)][n(1462)+"entListe"+n(1636)](e[n(1529)],this[n(1566)]);continue}break}}[t(1014)+t(1093)](){let n=t;if(e[n(1854)](e[n(1639)],e[n(1165)])){if(!this[n(1704)])return;this[n(1704)][n(988)+n(752)](e[n(936)],this._onOpen),this[n(1704)][n(988)+n(752)](e.crRMx,this._onClose),this[n(1704)][n(988)+n(752)](e[n(1037)],this[n(1385)+"ge"]),this[n(1704)][n(988)+n(752)](e.rPyJq,this[n(1566)])}else this[n(1595)](e.rPyJq,_0x4f3ee2(e.rPyJq,{message:this[n(780)+n(1179)+n(1033)](_0x2b07e2)}))}[t(824)+t(1287)](n=1e3,s=""){let d=t;try{this._ws&&this[d(1704)].close(n,s)}catch{}}[t(1538)+t(1758)+"t"](n=1e3,s="",d=!1){let f=t;if(this["_clearPi"+f(1390)](),this[f(1051)+f(1067)](),this[f(617)+f(653)+"rs"](),this["_wsInsta"+f(1287)](1e3,s),this[f(538)+f(746)]=!1,d&&this[f(519)+"orOnline"]()&&!this["_readyCl"+f(1849)]){if(this[f(1144)+f(938)]?.[f(423)+f(975)+"es"]()){let E=this[f(1144)+f(938)]?.[f(591)+f(1683)+"nt"]();this[f(1060)+f(832)+f(1789)](e[f(1516)](gt,e.crRMx,{code:1006,reason:"connect "+E+(f(1359)+f(1576)+"tries re"+f(680)),wasClean:!0}))}else{let E=this._options["reconnec"+f(1556)+f(1470)](n,s);this[f(1060)+f(832)+f(1789)](e[f(1244)](gt,e[f(923)],{code:n,reason:s,wasClean:!0,willReconnect:E})),E&&this[f(538)]()}return}this[f(519)+f(1306)]()||this[f(412)+f(1849)]?this[f(1060)+f(832)+f(1789)](gt(e.crRMx,{code:n,reason:e[f(798)]})):this[f(1060)+"hCloseEvent"](e[f(449)](gt,e[f(923)],{code:1006,reason:e[f(1457)]})),this._ws=null,this[f(1144)+f(938)]?.["resetEnd"+f(1318)+"fig"](),this[f(471)+f(1278)]?.["resetCou"+f(1580)]()}[t(1060)+t(1284)+"nt"](n){let s=t;this[s(1595)](e[s(936)],n),this[s(1880)]&&this[s(1880)](n)}[t(1060)+t(1357)+t(1570)](n){let s=t;if(e.lkpry(e[s(686)],e.rrFCg))return _0xf8bb92[s(802)](s(1692),_0x44ef95,_0x16e4d2,_0x1c68ec),this[s(1208)][s(948)]({cursor_name:_0x4862d6,cursor:_0x408c86,service:_0x4e558c});this[s(1595)](e[s(1037)],n),this[s(1297)+"e"]&&this.onmessage(n)}[t(1060)+t(1428)+t(1195)](n){let s=t;this[s(1595)](e[s(1653)],n),this["onReceiv"+s(1106)]&&this[s(1563)+s(1106)](n)}[t(1060)+"hErrorEv"+t(1789)](n){let s=t;this[s(1595)](e.rPyJq,n),this[s(1600)]&&this[s(1600)](n)}[t(1060)+t(832)+t(1789)](n){let s=t,d={AfkIR:function(f,g){return f||g}};if(e[s(1676)]===e[s(1676)])this[s(1595)](e[s(923)],n),this.onclose&&this[s(1620)](n);else{let f=this[s(1208)][s(822)+s(640)](this[s(1735)]),g=_0x14a644.parse(ohRqtY.AfkIR(f,"{}"));return g[_0x57afdb]=void 0,this[s(1208)][s(1036)+s(640)](this[s(1735)],_0x4a7975[s(665)+"y"](g))}}get[t(503)+"pe"](){let n=t;return this[n(1704)]?this[n(1704)][n(503)+"pe"]:this[n(1716)+n(1889)]}set[t(503)+"pe"](n){let s=t;this[s(1716)+s(1889)]=n,this[s(1704)]&&(this._ws[s(503)+"pe"]=n)}get retryCount(){let n=t;return this["_endpoin"+n(938)]?.[n(591)+"ntEndpoi"+n(1615)+n(1248)]()||0}get["buffered"+t(1694)](){let n=t,s=this[n(406)+n(553)][n(1040)]((d,f)=>(d+=f&&f[n(1386)+"th"]||0,d),0);return e[n(1476)](s,this._ws?this[n(1704)].bufferedAmount:0)}get[t(1181)+"ns"](){let n=t;return this[n(1704)]?this._ws[n(1181)+"ns"]:""}get[t(1163)](){let n=t;return this._ws?this[n(1704)][n(1163)]:""}get[t(1537)+"te"](){let n=t,s={FcRXb:function(d,f,g,E){return e.TqVps(d,f,g,E)}};if(e.lrcTB(e[n(390)],e[n(1602)]))throw _0x2c6a34=_0x331373[n(386)],FdMpfK[n(1737)](_0xe1a8a0,_0x27bc2a,10,_0x185487.length);return this[n(1704)]?this[n(1704)].readyState:this[n(1611)][n(1424)+n(561)]?this[n(1161)+"NG"]:this[n(1865)]}get[t(1081)](){let n=t;return this[n(1704)]?this[n(1704)][n(1081)]:this._url}[t(605)](n=1e3,s){let d=t,f={ejutA:function(g,E){return e[F(1599)](g,E)},JDBMr:function(g,E){return e[F(971)](g,E)},RJXDy:function(g,E){return e.FmqBm(g,E)},PoWxz:function(g,E){return e.zImAY(g,E)},uuqcK:function(g,E){return e.lQTgC(g,E)}};if(e[d(1233)](e[d(987)],e[d(1094)])){if(this[d(412)+d(1849)]=!0,this._clearTimer(),this[d(1105)+d(1390)](),this[d(1402)+"balEventListener"](),this[d(836)+d(801)]?.[d(1185)](),!this[d(1704)])return void this._debug(e.OOWIO);if(this[d(1704)][d(1537)+"te"]===this[d(1865)]||e[d(1701)](this[d(1704)][d(1537)+"te"],this[d(910)]))return void this[d(1013)](e[d(1564)]);this[d(1538)+"WebSocket"](n,s)}else _0x896036=rWdekH[d(1688)](_0x44f350,_0x308b88),_0x10ca49|=rWdekH[d(646)](127&_0xe8c6b3,14),rWdekH[d(1643)](128,_0x42b3c3)&&(_0x593376=rWdekH[d(1688)](_0xb6be2e,_0x5e0103),_0x248e14|=rWdekH[d(646)](rWdekH[d(508)](127,_0x550d6c),21),rWdekH.PoWxz(128,_0x1630c8)&&(_0x4daa71=rWdekH[d(1688)](_0x401aca,_0x208187),_0x40701e=rWdekH[d(1113)](127,_0x4f7e7e),rWdekH[d(508)](128,_0x50efc2)&&(_0x2b3eea=_0x5a4b88(_0x54c541),_0xb6c7e0|=rWdekH[d(646)](rWdekH[d(508)](127,_0x1cf420),7))))}async send(n,s){let d=t;if(e[d(1562)](null,n))throw new Error(e.dFZdG);e.sukSb(e[d(1266)],typeof n)&&(n=JSON.stringify(n)),e[d(1380)](e[d(1801)],typeof n)&&!e[d(1001)](n,ArrayBuffer)&&!(n[d(522)]&&e[d(1272)](n[d(522)],ArrayBuffer))&&(n=JSON.stringify(n));let f=await e[d(684)](hd,n),g=Mp(n),{method:E=0,service:y=this[d(1611)][d(1875)],logID:p=this[d(1611)]["logIDGen"+d(1637)](),headers:A=this._options.headers,payloadEncoding:O=this[d(1611)][d(1846)+d(817)],payloadType:N=this[d(1611)][d(1660)+d(1889)],logIDNew:j=this._options[d(1440)+"Config"][d(919)+d(1679)+d(928)+"ew"]?e.QRoVX(i,this._options[d(1440)+d(917)][d(1212)]):""}=e.xVHaO(s,{});if(!y)throw new Error("please p"+d(1132)+" valid service");let q={SeqID:fe[d(531)+"er"](this[d(660)]++),LogID:fe.fromNumber(p),service:y,method:E,headers:A,payloadEncoding:O instanceof Object?O.encoding?O[d(1283)]:"":O,payloadType:e[d(1272)](N,Object)?N[d(1361)]?N[d(1361)]:g:N||g,payload:f,LogIDNew:j},te=Ft(q);return this._ws&&this[d(1704)].readyState===this[d(1008)]?(this[d(1704)]&&this._ws.send(te),this[d(1013)](e[d(382)],q)):this["_message"+d(553)][d(386)]<this[d(1611)]["maxMessa"+d(478)+d(394)]?(this[d(406)+d(553)].push(te),this[d(1013)](e[d(864)],q)):(this[d(406)+"Queue"][d(520)](),this[d(406)+d(553)][d(1664)](te)),{seqID:this[d(660)],logID:p,logIDNew:j}}async[t(1632)+"t"](n){let s=t,{url:d}=n||{},f=Array[s(926)](d)?d:e.sukSb(e[s(1801)],typeof d)?[d]:[];n&&Object[s(1473)](this[s(1611)],n),f&&f[s(386)]?this._endpointManager=new dd(f,this._options[s(846)+"es"]):this[s(1144)+"tManager"]?.[s(1482)+s(1318)+s(1812)](),this[s(471)+s(1278)]?.[s(396)+s(1580)](this[s(1611)][s(628)+s(1443)]),this[s(412)+s(1849)]=!1,this[s(1704)]&&e.EuTcD(this[s(1704)][s(1537)+"te"],this[s(1865)])?this._disconnect(1e3,e.EyuWQ,!0):e[s(409)](e[s(1768)],e[s(1229)])?(e[s(957)](_0x5bfa71,65536)?_0x51b937[_0x2bdb9d++]=e.AXrWO(e[s(1381)](_0x1474dd,12),15)|224:(_0x1bb97a[_0x2af9d7++]=e[s(429)](e[s(564)](_0x31540c>>18,7),240),_0x5d4e43[_0x5a82d0++]=e.AlbCX(_0x566aee>>12&63,128)),_0x1cef4d[_0x291c70++]=e[s(820)](e.UQAYi(_0x2d4ee1,6)&63,128)):(this[s(1485)]=!0,this[s(538)]())}async[t(475)](){let n=t;if(e[n(1802)](e[n(1090)],e[n(1090)])){if(!this["_connect"+n(746)]){let s=e[n(1189)][n(609)]("|"),d=0;for(;;){switch(s[d++]){case"0":this[n(1485)]=!0;continue;case"1":this[n(471)+n(1278)]?.["resetCou"+n(1580)]();continue;case"2":this._connect();continue;case"3":this[n(1144)+n(938)]?.[n(1482)+n(1318)+n(1812)]();continue;case"4":this._readyClosed=!1;continue}break}}}else{let s=this[n(410)+"rs"][_0x1879f5];if(s)s[n(433)]()[n(711)](d=>d.fn[n(1377)](d[n(866)],_0x310f93));else if(e[n(1869)](n(644),_0x199d74)&&!this[n(1600)]){let d=_0x571769[n(386)]&&_0x171b3d[0];if(e[n(1272)](d,_0x22ddbc))throw d;let f=new _0x5d7ec0(e[n(704)]("Unhandle"+n(991),d?e[n(1852)](e.oyXbj(" (",d[n(612)]),")"):""));throw f[n(1723)]=d,d}return this}}[t(988)+"Listener"](n,s){this.on(n,s)}[t(1831)+t(1570)](n){let s=t,{type:d}=n;this[s(1595)](d,n)}["removeEv"+t(949)+t(1636)](n,s){this[t(1616)](n,s)}[t(789)](){let n=t,s={QlXnV:function(d,f){return e[F(1196)](d,f)},zSCwq:n(1249),UVGZo:n(1275),YVdjK:function(d,f){return e[n(1304)](d,f)},NjYpI:e[n(1586)],GJewS:n(387)+n(1024)+"s",SJiRq:e[n(1528)]};return new Promise((d,f)=>{let g=n,E={gIYqI:function(A,O){return e[F(1034)](A,O)},yrbIP:g(416),dLoIk:"ping_onc"+g(1024)+"s"};this._clearPingTimer(),this["_pingPon"+g(457)+"Id"]=e[g(1553)](setTimeout,this[g(1365)][g(964)](this),this._options["pingInte"+g(757)]);let y=()=>{let A=g,O={dTlCD:function(N,j){return N(j)}};if(s[A(1731)](s.zSCwq,s[A(1788)])){let N={piijj:function(j,q){return xaxosw.dTlCD(j,q)}};return function(...j){let q=A;return _0x14bc9d[q(1377)](N[q(1136)](_0x39d010,this),j),_0x245d52(_0x19d4ad[q(1605)](this))}}else s[A(1503)](d,s[A(1518)]),this[A(1616)](s[A(827)],y),this.off(s[A(1429)],p)},p=()=>{let A=g;E.gIYqI(f,E[A(560)]),this[A(1616)](E[A(372)],y),this.off(A(387)+"e_timeout",p)};this.on(e[g(569)],y),this.on(e[g(1528)],p),this[g(1365)]()})}}})(),Me["CustomCl"+M(1035)]=Ce[M(1300)+M(1035)],Me[M(913)+"rorEvent"]=Ce[M(913)+M(785)],Me[M(1149)+"e"]=Ce[M(1149)+"e"],Me.Event=Ce[M(1570)],Me.FWS=Ce[M(1231)],Me["FrontierMessageE"+M(1214)]=Ce["Frontier"+M(1243)+"vent"],Me["MessageE"+M(1214)]=Ce[M(1243)+"vent"],Me[M(1863)+"t"]=Ce[M(1863)+"t"],Me["Reconnec"+M(496)]=Ce[M(1816)+M(496)],Me["createCl"+M(1035)]=Ce[M(993)+M(1035)],Me[M(1234)+M(785)]=Ce[M(1234)+M(785)],Me["createMe"+M(1436)+"nt"]=Ce[M(763)+"ssageEvent"],Me["createOp"+M(379)]=Ce[M(1401)+"enEvent"],Me[M(487)+"connectE"+M(1214)]=Ce[M(487)+M(777)+M(1214)],Me[M(428)+"rame"]=Ce[M(428)+M(1695)],Me[M(1713)+M(1005)]=Ce[M(1713)+M(1005)];for(Ko in Ce)[M(1300)+"oseEvent",M(913)+M(785),M(1149)+"e","Event",M(1231),M(856)+M(1243)+M(1214),M(1243)+M(1214),"OpenEvent",M(1816)+M(496),M(993)+"oseEvent",M(1234)+M(785),M(763)+M(1436)+"nt",M(1401)+"enEvent",M(487)+M(777)+M(1214),M(428)+"rame",M(1713)+M(1005)][M(555)](Ko)===-1&&(Me[Ko]=Ce[Ko]);var Ko;function Xo(){let t=["u0TREMm","renyDfi","s2fTwNe","we50rNe","tMHlA1e","y2XLyxjtDg8","uwfpvKe","CMvHzhLtDge","x2rLC3rYB3K","BwvZC2fNzv8","yvvZCuK","we5YB1u","CLHVvhi","ywnRDxbfBMq","q2Hnqvm","s3nxBLy","vLzQC2m","rvbVzKm","Bvrlr0u","Aw9Ul2PZB24","Bu5by04","yw1LoIa","BeHYz3q","CLz4tvO","ANv2yNu","q0DQvKq","DeLUDgvYy2u","A2v5","y3nuv0m","v2LUzg93","s29hvMW","yLf4C0y","Dfn4q04","B25szwnLAxy","Agnxyvy","B25pCgvU","x29UrxjYB3i","BgHUB1i","DMfSDwvZ","DLznsK0","rxzLBNq","CgD2ufy","CerevKy","Efrurw52","yxnfDwy","u0PPBfa","lcbTyxGGCMu","s2PdDxe","s01ptNO","uwn5t2y","BNrLCG","C2vUzf9Hy2S","CxfUtwu","sxjgAK4","CKHXsKq","BMjmEwO","r0TMEuu","tvfgDfu","u0njBg4","vgT2weO","x2LZtwLUAvC","CM92AwrLihy","C21MANC","rwTpvfG","A2v5CW","zw1PDa","AwLsu2G","DwLAyKu","DuvvC08","q29TBg0","B25LCNjVCG","tenTwhC","D2XVtKe","rMz5B1m","DM9cvvG","z2v0","BKjzsuK","ExjsteW","yu16rhe","rfDHtLC","BezSDxnO","x29WDgLVBNm","ota5CMjcDgDm","yvjrz0y","t3rIsLy","BNruCMLLC0m","B2zM","Eu54EKu","tKfusvzfx0u","vMf4tLi","B25JBg9Zzq","zMvcq2u","wKnOvKG","rwzmugq","rwncBKy","suvtx0vsuK8","AxnFywnR","DfzZzLK","mtuWmJuYC3fMwwTL","x2n1CNnVCKy","EeHvqLq","rKLmrv9ot1q","CMvJB25Uzwm","EKvjtee","Bg51CfG","wM5yBhq","BMvY","zxjHDg9Y","q3zLt1i","v3HHqMy","tNzesvO","D2fZq2XLyw4","B2LUDfjLywm","uKPyrhK","D29gDMu","BMvlDhu","Chr6rfq","tgv6u1y","zgvSzxrL","zwn0","vxPKtxK","uLjpuG","rLLyz1K","vhzPCfO","BxnNsuq","C0L5tgq","tgHivMW","C2v0y3vYC28","B25dBg9Zzq","rufpy0i","Cgf5Bg9Hzfq","yxrLq291BNq","v3jyywC","CMvWBgfJzq","ChvZAa","zNjVBunOyxi","DgvmA3e","B2nXtM4","sw1Zqxi","ChjVy2vZCW","BM5Ly3q","q2Lewxq","C3fRue0","u3rYyxrLz3K","AK5jBLi","sgzLB1i","wuHmq3m","yxKSihrYEsa","yLrXA0K","Dg9hzw5LCMe","EfzRtum","CMvJzwL2zwq","Cvjny3C","BNrfBMrWB2K","sNrSqw8","Bhm6ia","r3fYvg0","t3niDNa","zwP1Dee","sMP6seG","BLDQBM8","AurMtve","C2v0zgi","BM9Uzv9UB24","qw1VDw50","CMfTzq","zMjhr2C","qu5pDvu","tLvSvwm","BujpCNa","C3HRzNm","s2HYExq","x3bPBMDqB24","wfjbA2u","x3DZ","yM9KEq","vM5Tu3q","vuXszeG","z0PHzM4","zxjFBxnNAwq","Dg9iyxnO","DuflvxC","qw50z1C","zw5JB2rLrNi","vLPpAeK","B2zMC2v0","x2jPBMfYEvq","ywnRpwzYB24","AwXLtMfTzq","uKHoDNm","zNzAEui","ENz6Chu","zfHzyMe","y29UDgv4Da","x2DLBMvYyxq","s2jIC3y","rwXvseu","DhLVqvO","BKDovfy","mNWZFdr8nxW","pxv0zI04","uwXyBLy","DgHLBG","B2jQzwn0u3q","BMCGzMfPBgu","x3bYzwzPEa","B2XKvMvYC2K","rMnswgi","z3PzDfu","Aw9UvgLTzw8","D0zRz1G","y3vZDg9Tshq","Bffuz0m","B25tDgfYDfi","CgfNzxnOB3C","q1DLthe","DMvY","Bwu6ia","DM1rAhm","uMTQCuC","z2v0q3vYC28","qNjPzgDL","y2HnyxHdB3u","BejQDgq","A1LbBMK","v012EKq","z2v0sxrLBq","CgfNzwHPzgu","v2vIu29JA2u","tNftDgS","BwLUAvbYB2C","y05uuNO","EKrbD0m","Cgu6ia","rgnHzMq","AxHbu0i","BgLUzq","y2HLy2TdDxi","CLHJEwW","tLvYv0O","q09oveLovuu","CM1frNK","Aw47y2HHCNm","Dgv4DfbHEwW","shrcAhK","BefluuO","shnpu1C","zw5KCg9PBNq","rMjmtKW","ihrVihjLDhi","vvPhv1a","CMTXDKu","vfP4CMy","DMLJzuLeig8","CMvXDwLYzwq","Aw1LCYbPBIa","u05uyuO","uwvZC3G","vvzhwM8","zw50","rfDdwgG","z1HgzMW","y05JwxG","CMjvyxK","veTYuhK","mJqXnZbSA2PMvfG","zvnRr2e","ENHJtwq","zMLSDgvY","yMfJA3vWigu","CuHcthu","ugrxEvO","A2fOwuS","tM1mtKS","r0XRy2S","B2fxBve","q3zhwLq","A1D2CwC","u0XYCxy","AxnrB1nnzxm","B3jRig9MzMW","sevizu4","zMLN","sgrsque","AffqEeG","DhDVCMTdAge","uMvJB25Uzwm","rKDTAgy","rKvPtem","uNjIALG","zgv2AwnLx2K","DKLZz08","B25mAw5L","BMfTzq","s2Lgv20","surNuva","uMPlsue","uefvq0i","zxfprwK","DMPzy3G","vuL1Avm","zgLZCgf0y2G","DuXys1y","zhLdEKS","u3DUEgS","Bu5yBeO","C3bSAwnL","EvjLy29UBMu","t0vlquu","sgDZEe0","x19LC01Vzhu","y29UDgLUDwu","vxz1q2S","zMzmAw5L","Aw50zwDLCIa","y2f0y2G","Cgf5Bg9Hzeu","CMvHzfvjBNq","D2rzt2e","B3nLza","ywXSq3vYC28","CMvZDwX0","EK5Urha","ALDevKS","qxH1sMm","y29TCgXLDgu","AgfZ","BgfMr3O","Bg5rrLi","DLfbuhi","yw90vxu","BxLuweC","B3jL","t3bLBKv2zw4","AvbKAgG","q0Xpu0ve","Ahn2C20","DeveDLG","y3vYC29Y","A0H0Cfy","zgL1CeO","yuHxt0K","x2LUDgvYDMe","ELjQy2u","AenAAMW","C2vYDMLJzq","B1fOuuu","x2LZtM9Kzq","ALLwv1y","zw1LBNq","B25VCgvU","CfHHzMC","rwr1uem","uezyCei","z0TpvhC","AuDsD0q","EM9Twxi","AM9PBG","t01trey","ExbL","AMPMtxC","y0XxBKm","EK55ze0","BMnuCLm","ve1Ot00","C2v0sxrLBq","sgTtrgS","CYbPBNn0yw4","Dw5ZAwDUzwq","tvjlyNm","tLrSrum","yM1juMO","Aw5L","C2vYDMvYvgK","ywXty29Wzq","zeXVswS","y3jZBwG","AKzUDxG","ywXPzcb1CMW","v3fcq1q","Dg9VigXHCMC","B2zTvM0","zw5fDMvUDa","x29Ut3bLBG","CgXstKi","A0L3z0G","z2zjyKq","s3jftuu","vfLrCei","BgvUz3rO","CgLUz19VBMm","BgLUzw5V","EsbJBg9Zzwq","wwLSr1i","AgvKtwf4uMu","zwD0zui","y1jbtva","zw5NDgG","zxf1ywXZ","CMvZzxrdB3u","mdaWmdaWmda","AwXLx25HBwu","zhrmsKe","y29UC3rYDwm","whbOC0G","x2n1CNnVCK4","sKzRu2O","Cxb5Euu","t2jQzwn0","x21LC3nHz2u","r2riC2S","t0rRruC","D0rru2S","x2XPC3rLBMu","tLDMC1O","x3jLywr5q2W","v3netxK","uuTMAKm","B3bWzg0","DgLTzw91Da","tgnUwfy","uMLHq1m","B2rmwgC","yMfSrxzLBNq","AvfQzuO","DgPmugi","y2HLy2Tszwe","yxbWBgLJyxq","v3nmDfe","x2nYzwf0zvm","r0Pwuha","zgvJB2rLzey","q1HXrwS","y29UBMvJDfm","rhbTuuu","ufvszeu","C2XPy2u","y2fSBa","B3bLBG","v2zLsvy","ywjVCNq","wfnsDhq","y3DlCxG","DezNvK0","y29Kzq","ufPVvNm","yMfSu2nVCgu","u2TPCcbWyxm","tLjlCei","EK5XDfG","uuDrweW","C3rYAw5N","EKDtsuy","Fdj8oxW3Fdq","zxHYteG","mdaWma","q2zizvm","ihbYB3rVy28","BhnwD0q","tNvXEwi","z1rPBwvVDxq","DeruC0C","zNjVBuj5Dgu","vwj2zem","DhjHBNnHy3q","veDdrei","DwTmCuO","zK5UELa","B1frvKu","B3bLBKrc","wLnvvxG","y2jnywm","x0rctMfTzq","DhHMwNa","x3bPBMDmB3m","qw5lAvK","q29Kzq","C05nAwi","y29UBMvJDa","BIWGAg9ZDg4","mJK0vuXcCvnk","z2vrDwv1zuW","uu5KC3C","AgfUz2u","zNjHBwvuExa","AwDHDg9Yt24","Bg9IywXty28","C0Xf","zu54q2y","s1DJrum","y3jLyxrLuMu","BgfhvMi","ELf2Efu","rMzWswK","ufP6DNi","Dw5KzwzPBMu","EvHbyvC","x0vysvnu","DhzTrLe","Dev2zw50","x2LZv29YA2u","Axnby2TdBgu","CMLLC0nVDw4","v3HRDwC","v1bNs3u","ywnR","yMLUyxj5vhK","qMPJAMy","Dg9cExrLC0i","Bfvgzey","D2LSBfjLy28","ug9xEhO","qvHYv08","BML0AwfSAxO","Avv5B0m","BvHPAxy","u0TUBvC","CKzAufG","CNfKCwW","zfPUtLG","Bgjoywu","BNDkvxq","x25HDMLNyxq","C2HPzNq","swnyr3q","yNvMzMvY","ihrPBwvZ","C2Hzr1G","AgHSv2u","yxGGCMv0CMK","x3jLy29UBMu","wvbIBKS","BNrbBMrvCgq","EwvmsK4","zNjVBu51Bwi","D0rvrLu","svvVDfa","x2n1CNnVCK0","DMrJs2S","svzSzem","BMvJDa","x2nVBM5Ly3q","rKzrAee","u2zmueK","tMjUtNK","t2fbDK8","BK5fDxO","Aw5KzxG","vwz0suu","x3vYBa","yM1yq2i","DKjmzfe","sfLnAwG","tw5YALC","zuDAt2S","ywP6tK4","uxvLDwu","vgPstgy","Aw5KzxHpzG","tKP3zgq","ue9lr0m","wxDrEKS","sefdr0S","ExjIsva","y09Wzw4","CIb0DhDjra","uvjVvLG","whfUrxK","B0XRALC","zxjFCw9Zx2e","ALD2Due","DMvYC2LVBMm","DNb5u0i","vw5Oyw5KBgu","Cg9PBNrbBMq","AxjWEeC","y2XVC2uSihC","DxrVuMvJB24","sLnptLa","DgX6thm","v1LVBfe","u2HHCMvKv28","Ae9Nr20","rw1eveW","Bujev0C","Aw5JBhvKzxm","ChbL","B2nRzxq","Cg9W","Dg9mB3DLCKm","BKvqthm","C2vUDa","BfrPBwvVDxq","y29UBMvJDgK","z2v0q3vYCMu","tfzwzxy","uNvAAey","AvfYvNm","u0Htze8","zMLSzw5HBwu","CK9uz0C","tMHRs2e","rwjMDfO","u1bMC0m","rfvpqxa","B0jmuLC","vwTSBwm","zu14yvy","y2XVC2u","qLr0wNu","BMv3vMvYC2K","x2DLDeLUDgu","C3bSAxq","AefwqwC","BMPWzuG","BwvZC2fNzq","AurXwvG","t1bftL9fuLi","s2zut2q","EgzAqKu","x3jLBw92zvC","wfHlvxy","zfHRv1y","ufrItxe","rKruuNa","Aev2vhu","zxHWB3j0CW","C0jf","sKDsuwS","Egzht0e","sg5HCg4","CgLUz0XVC3m","y3vYC29Yx24","x2HHBMrSzu8","wMr5CKu","tMvuCNi","A1n3thK","Dg9cExrLC0W","m3WYFdf8nhW","wgvYChC","rwPMEgG","zMLUza","BLbOq2i","z2vtEw5J","ywnRx2LK","q0X6ANi","vwfmq0W","zxjYB3i","D2vI","sKrctxi","yLzHvg0","B25tDg9Wsw0","zxq9DxrMltG","zgLZywjSzue","Ec11C2uT","ANfev1q","C0XPC3rLBMu","DxLxALG","AxnszwfKEq","yxbWzw5Kq2G","ueXqwKC","CwzeDvq","tuvQtgW","x3nLCuLK","zw5HyMXLuw8","sxPvruC","qvLjq0C","r2ftEgu","C3rYAw5NAwy","vu1jEwG","vurnEfG","Ce94D04","A1n0yxr1C0m","twv0q0i","rvjst1i","uuXOuK0","Egniyvm","Du54se8","C2v0q3vYC28","AevYCM9Yrxy","z2rptuu","zxjYtxnN","uLzuAwS","ywnOzwq","AKfpDNK","q1zouum","uMvHzcbWyxm","B3bAzfK","sfbAs1u","CNjgq2C","rLr6DKK","whHcAfe","C3rfyu8","B1zwA3K","yNL0zu9MzNm","zMTlD3q","t0rNte8","CgfYC2u","zwvKzwq","B0jYu00","AuXwu1y","wuvLuee","vxbTAhC","tuDmqK4","B2zMBgLUzq","C0nfwuK","BxnN","vun2EMS","qLLitMO","quXm","tgPSAvm","B3v0sw50zxi","rM1XqM0","tufyx1jfvfi","zM9YrwfJAa","vxf1wLC","C3vIC3rYAw4","B3fTA0u","yxnL","vNL4Ae8","y2uGBM90igK","q2LpDvy","wKfLufq","vgTqEhG","uxf5q3K","B3LyyMO","Ewf4vNq","BwDmyKm","DufZAhO","B3bLCNr5","tw9WyKy","Cg93","ufjRDu4","tLfuyw0","whDSuMi","yvzLv0y","BMf4B0m","zfvjqMm","uMXdCxa","CgXLqMq","sNjMqwe","wKjuD3q","BeHHBMrSzxi","qKjbBvm","y2HHCKnVzgu","tKDFrvjst1i","EhL4z3a","uMDhsKO","yxjYyxLIDwy","tg9JAW","DuLeDue","igzHAwWSig0","te9hshK","q1LWr2G","vurWuge","tgLZDgvUzxi","yxKSig5LDhC","C3HIweK","DwHOzxu","C2j5zuS","CNzHBa","DvfzDxu","yxDPvNe","EgTnuwm","s1zPwNy","tLPbCgC","y3jLyxrLtwu","A1nbA0e","B2fK","s01ivuW","zxj2AwnL","DeTywhu","CgXLyxnLiha","y3vYCMvUDeu","CNnVCL9Uyw0","ELb6D0e","AKHOAe0","uLfTBfq","Cgf5Bg9Hza","Dgz3zhy","y29UBMvJDeu","ENPiqxu","B3bLCNr5tMe","x2zVCM1HDeu","Cu5wC2W","BwLUzW","uhvttvC","zNjVBujPDhm","CM9YrxzLBNq","AMD4y0y","vLPPCgS","C2fNzq","CgLUz09Uy2u","zxH0ugf5Bg8","AwrI","CwfSzgS","z1rXsei","vgTsrNi","C2DPza","x3DHAxq","zezOyLy","s0TvDNC","y0HcwK4","y3jLyxrLt2i","z2vY","Bg9N","vg9rqwW","s1jQwNu","AhjWAvm","x3nLBMrby2S","Eg9ktgW","ywXS","q1P4Age","Bg9Nsurhzw4","x2LUAxrhBg8","qLfhreC","uungDNu","ENnXtw4","twLVtvq","vNfOrwe","BMnVzgLUzW","x2LUAxq","B25ozxr3B3i","vunHCLe","vhPxDK8","z2v0u3rVCMe","Dgv4Dc9WBge","x3DZsw5ZDge","Chv0","ywX3yxLZ","r0PLD1m","CMvUDevUzha","rwLRuuu","mJy5mZG0teP5Dg9Z","u3fPuwC","AenSB3nLrxy","ywrK","swnss2O","Dg9cExrLCW","x1fVu01HBMe","lcbxzwjtB2m","Bvf2B2q","uLzPAKu","Ec1TC2CTCw8","zv90Aw1LB3u","EeX0vuy","B0vNEgG","Aw5N","CM92AwrLigi","Bwf4uMv0CMK","Dg9oDw1Izxi","vNbfDxK","Aw9U","x2rPC2nVBM4","BMrLEa","tuvtu0fhrv8","rgLqwKC","D3m6lY8","uvfNB1e","rNjVBNrPzxi","ug5lEe8","CKTguLa","Exzqufa","CgjICdi","vvjvrfu","rKLRDMq","qLDTvxC","zeTXA3u","DK9eELu","y3r4","CMvZzxruCMK","CNDoCwO","AuzOC2O","tLHeu1y","DxPIDgC","ENzMBxC","qu1vEK8","DxPRz2K","CMvZB2X2zq","swPYrhe","wwruEwS","icSG","x29UvgLTzw8","vhjlufC","uKnpDMm","EhHeu1i","zMXVB3i","D0rtyNu","zMjLz3O","C3rHCNq","AuTgtuS","zLDvtfO","m3WXFdj8mhW","C2nYAxb0","wgrjBxO","yw1Lu3bHy2u","ue9hCg0","C3vJy2vZCW","ywDLsgLKzq","rNDirfC","x2rItMfTzq","D0fIq0m","t3vIAhO","CxPZzMS","z2v0qwXSs2u","Ef9MCM9UDgK","zxrxB3jRq2G","CMfUzg9T","Aw5Lza","EuTNswm","tg9NsurozxC","CMvTB3zLq2G","DvrXC2C","q0Xpu0LorW","r2zusKC","BMCGB3iGyw4","q3vZDg9Trxi","AfnQyKe","sgDiA2y","zgf0yq","q29UzMLN","whD4D3K","zw5HyMXLqxu","DgLLCKPtt04","DwLyDuK","Efj2ALm","y3jstxG","DNLjAMK","ihjLy29UBMu","AxnbCNjHEq","DvHMzuy","DgvmB2Djre4","EhnAAeu","nhWYFdf8nxW","teHWv1q","CfjtthG","uLvtwNK","sg5qyLO","z0vVy0y","y1HwCKG","AMDJsuC","De1HBMfNzxi","mxWWFdr8m3W","z2fstg4","s3LrrNi","s1z6y2e","uePQvw8","uwjSEu4","z29PBMCGyxC","DhjPBq","rvfwAKG","C2v0","zw50tgLZDgu","AuPpyKe","sK52u3e","zNjVBNrPzxi","rLDYt2e","qMDgvg8","yuffCNu","B0HitNO","quDbr2O","mJCXndK1sezUu2vy","r1jMuw8","DLbnsK4","qxrfv2C","vgLTzw91Da","Dw50","yMLUza","rujcCMO","zwrPyxrLBhK","q3DLBKS","vvPqvNq","v0XhrvG","CNzHBfzHBhu","reTeyuK","v2HstKK","BhvQExu","AxnrB1nby2S","y2HnyxHuCMK","wu5mEvq","x2LZtwLUAvq","D2nvy2e","vgzQreW","AePbCKu","ChjVDg90Exa","EwHkswK","D0TlDwO","z2v0t3DUuhi","qxLrr2S","vxrhqNG","BuDPDwi","ywrKrxzLBNq","tKPJt3K","CwTJEgC","zcbLCNjVCI4","yLPqBxy","y3jLyxrLq2W","AM16zLe","uxDJBxK","zvvYBa","CeHkuvi","y3ruAw1LB3u","q0Hvue0","zfDVCMTLCKC","EePyCMO","u2vYDMLJzvC","swHoBui","CMvJzxzPzwq","yw1L","BgvY","yNzsCK4","t1bftG","rLzPqKy","z1bkEKO","tMfTzq","B09TAg8","x2rLyNvN","x2fKzfDZtgK","sMX1Ae4","tg9Nsuq","zMfRyw0","rxPnzLy","BwrTyMK","rgvXDNO","BMDLza","tw5eA24","Ew9wvge","zv9ZDwnJzxm","x21PBMLoyxy","ue1dv0u","qvnjr2K","zcWGDw5RBM8","zun5rvO","Dvr0D2u","x2HHBMrSzva","uwPpzfa","ywDL","u2LwCeG","B3nLrxzLBNq","C2v0u3rVCMe","v1HIwva","z0vQyM0","BuHlrfm","CMvKDwnL","rhr1v2m","DgLTzw91DcW","Aw5PDcbrB1m","BfHryuK","ihzHBgLKigq","txrTzNa","rKnlq2W","DMf0t3y","C2vUza","s2HnBKq","x2nSzwfYvgK","v21Ntvm","qxH3v3e","BwvKAwf0zwW","Duz0CLG","seHmue4","D1b1yvi","zgvMAw5Luhi","A1nLwxm","x2rPC3bHDgm","ign1CNnVCIa","uffPy3e","y29Uy2f0","z2vjBMzVu3K","CYbWyxjHBxm","x29UugfNzu4","BwvY","AxnTt3m","sw1wqKO","igXHCMDLCIa","DxbNCMfKzw4","vK9zCLm","AxmGDw5Kzwy","BhrPCgXLihq","u3zxBhy","ywHRz2i","Dg9tDhjPBMC","vgfN","tfrftu8","rhjktuG","DxjS","suH0BfG","y2LAz24","vKTyD0S","Du96wei","yKrfrMG","CMvHC29U","y3vYCMvUDeK","igzPzwXKoIa","yvzLzKu","ywrKq291BNq","CgD5z2O","C3rLBMvYCW","rxruueG","x2TLEvbHDgG","Bwv0Ag9K","B29ht2y","Dxrjza","Ae5XuvK","ugzkCuO","EfzJwM0","m3WW","yNL0zxm","q0DjtKC","x2nSzwfYugK","zufJAW","zxjYtM8","r0DdD28","zM1Qt24","AwXK","m29NDevSvq","DfHZu24","DxvXy0S","DxnAuNC","z0ntwKC","swLiEw4","BwL3tuO","CYbHBhjLywq","y1PKr2m","AgLNAa","D3rpyMG","CxnkEfC","ywr2yw5Jzq","z2v0qwXS","uuHqBum","tfLgtvi","ywzL","yK5iwwS","vLnsvg4","zw5HyMXLvhi","mNWXFdr8mhW","CM92AwrLige","vMzNzK8","sfDtC2y","s0zkveS","CgLPAMO","EMTZDMu","Ahr0Chm6","u0Dlzxe","wgDmwuC","D24GCMvHC28","B3bLBIa","zhPttMG","x2vUzhbVAw4","zvP4zwS","qM9oDwi","zxjFAxnFywm","wxj0zge","rxjYB3jdB2q","wLrJu04","AMP3BNu","C2XpvuK","FdH8mtb8m3W","wMTqtum","vKjuqLq","BKXPBMu","wwzfvfu","z2HsD3e","yufdDKq","u2PlBMm","q09otKvdveK","B3jLtMfTzxm","ChjVDg9JB2W","v1nvrui","rhn3Dvm","BgLTAxq","r296uhK","vgDbDMe","Cez1zgK","tLbuA04","whfdq2W","zw5XDwv1zq","B2nRzxrtDwm","r3rrq3u","B25nzxnZywC","wvLvsLm","BMDjCxm","CMTLCKDSB2i","CNjVCK1LC3m","DMfSDwu","zxH0zw5ZAw8","ihn1y2nLC3m","mtf8nxWWFde","wuzwsfi","y2XVC2veqG","D1HlC2K","uxv5EeC","DgDZC2q","uMPiAeO","BM90B1u","BfHprxi","D3nZoI8V","A0rKrKW","zgvS","ywDLrxzLBNq","DKHLEe4","DhrVDhO","Dhj1y3rVCIa","yxnJCMLWDa","yw5Nzq","BgLZDgvUtMu","zMzLCG","Aw5KzxGGB3u","ruLIDgi","u2XJAuW","DcbSAw1PDa","zLf0rKO","x3fVC0rc","y29UBMvJDca","uxfbBeK","rhbQEMi","DxnLCKLW","wvrjCxm","DMvUDa","Du15sve","zxvgwui","EKHzAMS","rKrSAxy","AgvHzgvYCW","C3vRu2i","CgvYC2LZDgu","zM5gwNC","DgLUzYbZzxi","v2vPEgLUsLm","tNrTCM8","BMjfEw4","C2nVEvm","sLjQDfC","qLfOrvG","x3bYB3rVy28","rLDt","q21fsuC","DKDsCfu","y3jLyxrLrxi","CNnSCw0","tLHRAuO","BMvLzf9Hy2S","m3WXFdr8mhW","zMzMzG","DMvYC2LVBG","zKrPBxK","EvHhsfG","twvZC2fNzuu","z1HmEe4","z05LzgK","Bg93","D3LUBLG","B3vUDa","uhn3t1G","Cg1zExC","B2nRzxrgywK","Cw9Zx18","q01yCe0","t0zzrLC","x29Uq2XVC2u","tw9KDwXL","rwP4BxC","ugr4wLq","rNLrwgy","x2LUAxrqCM8","vg50sw4","zg9Uzq","Ahr0Ca","tu5JsM0","zM9Yy2u","A2zkqKS","A1nkzM4","C0XYz2W","wvHowM8","zvjvAwe","nta0mtyWDNHlsvb6","zeLou1q","BKfNvKG","y29WDhm","t0XvAey","yw51Ce1LC3m","vLjHzhi","C0nVDw50zxi","v0vdsKC","EMXUv00","Efn4vLm","A3bdu3i","zw5JB2rPBMC","Ae9Wzw5fDMu","B3HxsgO","vKrOr3a","BMnLq2XVC2u","BwvZ","BNDsq1K","ywWGy3vYC28","z3PUzNG","q1jhywC","q0DQtKq","DxbKyxrLq3u","EgvQC2W","r0Xbuvi","B25TzxnZywC","qMTutvu","DwnhDK4","q3vZDg9Tq2W","BKvbD08","sgPrBeq","DwDhs2O","yMXktg8","x2LZqNjVD3m","B3jpBMXPBMu","B1fjBKS","C3jJ","twLZC2LUzYa","DcbVzIbYyw4","DMfS","CMvHzg9UBhK","ywDLu2HVDW","C29YDa","D2fyDue","zwnVBM5Ly3q","z3nRBNy","Cg9PBNrdB24","CNnVCKzPBgu","B0fmy3m","Cw9Z","D2Tquem","zxmGCMvHy2G","svn4EeG","zsbHihn0CMK","yLj5twK","AgLks3u","yw5Hz2vY","y3vYC29YlNm","su5tvefova","tNHZv0C","v2XLC2S","rgvKAwnHDgu","AwXSihvZzsa","CMvWBgfJzui","EwDqweq","u2vXsuq","BgTYu2C","Cu5SqwS","uM5xr1G","C21mtMu","igfYCMf5yNu","Dw5RBM93BIa","BM93","yMXVy2TLza","Dhr3Awq","vw5PBxbSzw0","y1nXA0u","ywnRtxnNswq","wxjqs0S","AxjLza","zg15v1a","id4G","ywnRx2nVzgu","C0zUuxC","r3nvD0i","Ae1LC3nHz2u","Efziyu8","ihrPBwvVDxq","qKLeBMK","DhLWzq","q2r6zvu","y2XLyxi","Bwf4tg9ZC0m","x3bPBMC","u3bYuwe","CLfhtxi","nty0otG4oejcBeHqqq","A3Pqu1O","DwzWq3K","AxnAzxjV","zMX1C2HfEha","txvhEw4","B3Pptem","D3jPDgvvAw4","zLDXzvi","yxbWBhK","t0fnyMm","DhDwALK","ENLuyu0","weTHruq","u1zVs3q","DeLK","tKDyAvu","x29UtwvZC2e","yNL0zuXLBMC","l3DZl3yY","x2HHBMrSzvi","AwvuyMq","BMDuAw1LCG","uuTWB2e","DxrMofDYAxq","ywrKt25L","y3vYC29Yx2y","D3jPDgu","yNLNzuK","EwjVvxG","y1vYA2u","EKfRDKC","CeD4AuK","y3jLyxrLt3a","x2rYB3bhBg8","s2Xlq0i","x3nVy2TLDa","DhjPzxm","vffVq2u","D2TtBuK","sK5Vtg0","y2vZC0HHBMq","AfzJtLq","AxnVveK","zgHIBvO","zgrjrcWGzgu","z2vqv04","BfLhv1O","sKHuCui","BeHluM4","BwLZzq","sKXVzfG","tNP1z2O","rvrbsfi","y3jLyxrLrwW","zLvjCLO","yxv0B21HDgK","zuDRDKm","BhfcEha","yM9L","AefJA01LC3m","u0PPuNe","DhjPzxmGCMu","zNjVBuHHC2G","AMDIzhO","B2zKCw4","B0z4C3m","DgXZreK","C3nHz2vfDMu","t29yrNK","yxzQy1G","yLn6AeG","Bg9NsurozxC","vxLSAwG","CgLUz0LUDgu","q291BNq","A25qsNa","Dw51v28","DgfYz2v0","AxnmB25N","zwzjEu4","zNvUy3rPB24","yNLL","rwDyEgW","CwjcD0e","qMHkz20","B25SAw5L","x3bHDgHlzxK","ntyXodjeseHJvgS","r1rvv0m","yLnmrxO","shvmzu4","AKfWuvu","rgjzsgu","CMvTB3zLrxy","ELfvu1q","D2Psrvi","C2vYDMLJzs0","C3vIyxjYyxK","BerKB20","whnZEfa","y291BNq","ChrVCG","DhnovMG","DgfIyxnL","yxnZAwDU","y2rgywq","yMrFzgLK","zxjXvgm","DKr3A2q","s0frsuG","ysbTDxn0igi","zxjFywnRx20","z3LRrem","CMvZzxrfBMq","wxjorNK","y09MBfu","x2LZsw5PDa","DeTesey","rxP5t3q","svfYyLu","ELPbBwe","A2vlvuu","Dg9Y","uLHUveC","r1fnzvq","qwjVCNrfCNi","ANLNAxy","reiGzMfPBgu","ve9vte4","AMvJDfn0B3i","vxndvuS","CMfNzvn5BMm","DfbVrKu","z0zlr28","wvzKAKS","BgLlA2q","vMLHq1K","sfrlsuC","tuvsDg4","AMTJrhu","tfnpALi","AKrvq20","ywXSzwqGBxu","DKnWEuy","qLjStgy","B25Uzwn0Aw4","z2u6ia","zg5nrxi","BuHOy0S","tMPzCeK","AuD0vwy","CejOqwy","BMrWB2LUDfq","C3rVCMu","y1POwvq","vK9WuNe","rvHVz3q","DgvZDa","Ec1TC2CTy3u","r09pv1K","CLb5sNe"];return Xo=function(){return t},Xo()}Object[M(1058)+M(726)](Me,M(1840)+"le",{value:!0})});import{existsSync as SS,openSync as IS}from"node:fs";import{mkdir as AS}from"node:fs/promises";import{dirname as TS}from"node:path";import{fileURLToPath as kS}from"node:url";function CS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Hl(t=Q()){return SS(t.libEntry)?t.libEntry:kS(new URL("../index.ts",import.meta.url))}async function $h(t={}){let e=t.paths??Q(),r=t.entryOverride??Hl(e),i=CS(e,process.env.COZE_BRIDGE_LOG_MODE);await AS(TS(i),{recursive:!0});let o=IS(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=rt(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[cs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return RS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var RS,cs,ra=et(()=>{"use strict";$t();ne();Le();RS=H("spawn-daemon"),cs="COZE_BRIDGE_DAEMON"});import{spawn as S1}from"node:child_process";import{mkdir as I1,unlink as A1,writeFile as T1}from"node:fs/promises";import{dirname as k1,join as R1}from"node:path";function Jr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function C1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Jr(r)}</key>
21
+ <string>${Jr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function RS(t,e){return new Promise((r,i)=>{let o=vS(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 $r,ss,ia,$l,dp=Qe(()=>{"use strict";te();$r=H("supervisor.launchd"),ss="ai.coze.bridge",ia=RS,$l={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function D1(t,e){return new Promise((r,i)=>{let o=S1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Vr,ds,da,Zl,xp=et(()=>{"use strict";ne();Vr=H("supervisor.launchd"),ds="ai.coze.bridge",da=D1,Zl={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>${ss}</string>
31
+ <string>${ds}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Vr(t.nodeBin)}</string>
35
- <string>${Vr(t.entry)}</string>
34
+ <string>${Jr(t.nodeBin)}</string>
35
+ <string>${Jr(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>${Vr(t.logFile)}</string>
45
+ <string>${Jr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Vr(t.logFile)}</string>${CS(t.env)}
47
+ <string>${Jr(t.logFile)}</string>${C1(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return kS(t.homeDir,"Library","LaunchAgents",`${ss}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await SS(TS(i),{recursive:!0}),await AS(i,this.renderConfig(t),"utf8"),$r.info("plist written",{plistPath:i,activate:r}),!r)return;await ia("launchctl",["unload","-w",i]).catch(c=>$r.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ia("launchctl",["load","-w",i]),$r.info("launchd job loaded",{label:ss});let o=process.getuid?.()??0;await ia("launchctl",["kickstart","-k",`gui/${o}/${ss}`]),$r.info("launchd job kickstarted",{label:ss,uid:o})},async uninstall(t){let e=this.configPath(t);await ia("launchctl",["unload","-w",e]).catch(r=>$r.warn("launchctl unload failed (ignored)",{err:String(r)})),await IS(e).catch(r=>{if(r.code!=="ENOENT")throw r}),$r.info("launchd job removed",{plistPath:e})}}});import{spawn as PS}from"node:child_process";import{mkdir as DS,unlink as OS,writeFile as LS}from"node:fs/promises";import{dirname as NS,join as up}from"node:path";function oa(t,e){return t.isRoot?e:["--user",...e]}function BS(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function aa(t,e){return new Promise((r,i)=>{let o=PS(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 sa,Jr,MS,Vl,fp=Qe(()=>{"use strict";te();sa=H("supervisor.systemd"),Jr="coze-bridge.service",MS="/etc/systemd/system";Vl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return R1(t.homeDir,"Library","LaunchAgents",`${ds}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await I1(k1(i),{recursive:!0}),await T1(i,this.renderConfig(t),"utf8"),Vr.info("plist written",{plistPath:i,activate:r}),!r)return;await da("launchctl",["unload","-w",i]).catch(c=>Vr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await da("launchctl",["load","-w",i]),Vr.info("launchd job loaded",{label:ds});let o=process.getuid?.()??0;await da("launchctl",["kickstart","-k",`gui/${o}/${ds}`]),Vr.info("launchd job kickstarted",{label:ds,uid:o})},async uninstall(t){let e=this.configPath(t);await da("launchctl",["unload","-w",e]).catch(r=>Vr.warn("launchctl unload failed (ignored)",{err:String(r)})),await A1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Vr.info("launchd job removed",{plistPath:e})}}});import{spawn as P1}from"node:child_process";import{mkdir as L1,unlink as O1,writeFile as N1}from"node:fs/promises";import{dirname as M1,join as hp}from"node:path";function fa(t,e){return t.isRoot?e:["--user",...e]}function z1(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function xa(t,e){return new Promise((r,i)=>{let o=P1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var ua,Yr,B1,Xl,pp=et(()=>{"use strict";ne();ua=H("supervisor.systemd"),Yr="coze-bridge.service",B1="/etc/systemd/system";Xl={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
- ${BS(t.env)}
62
+ ${z1(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?up(MS,Jr):up(t.homeDir,".config","systemd","user",Jr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await DS(NS(i),{recursive:!0}),await LS(i,this.renderConfig(t),"utf8"),sa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await aa("systemctl",oa(t,["daemon-reload"])),await aa("systemctl",oa(t,r?["enable","--now",Jr]:["enable",Jr])),sa.info("systemd unit enabled",{unitName:Jr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await aa("systemctl",oa(t,["disable","--now",Jr])).catch(r=>sa.warn("systemctl disable failed (ignored)",{err:String(r)})),await OS(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await aa("systemctl",oa(t,["daemon-reload"])).catch(()=>{}),sa.info("systemd unit removed",{unitPath:e})}}});import{spawn as FS}from"node:child_process";import{join as zS}from"node:path";function hp(t,e){return new Promise((r,i)=>{let o=FS(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 Jl,ca,Zl,xp=Qe(()=>{"use strict";te();Jl=H("supervisor.taskscheduler"),ca="CozeBridge",Zl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?hp(B1,Yr):hp(t.homeDir,".config","systemd","user",Yr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await L1(M1(i),{recursive:!0}),await N1(i,this.renderConfig(t),"utf8"),ua.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await xa("systemctl",fa(t,["daemon-reload"])),await xa("systemctl",fa(t,r?["enable","--now",Yr]:["enable",Yr])),ua.info("systemd unit enabled",{unitName:Yr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await xa("systemctl",fa(t,["disable","--now",Yr])).catch(r=>ua.warn("systemctl disable failed (ignored)",{err:String(r)})),await O1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await xa("systemctl",fa(t,["daemon-reload"])).catch(()=>{}),ua.info("systemd unit removed",{unitPath:e})}}});import{spawn as F1}from"node:child_process";import{join as U1}from"node:path";function gp(t,e){return new Promise((r,i)=>{let o=F1(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Ql,ha,ed,mp=et(()=>{"use strict";ne();Ql=H("supervisor.taskscheduler"),ha="CozeBridge",ed={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
66
66
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
67
67
  <RegistrationInfo>
68
68
  <Description>Coze Bridge daemon</Description>
@@ -86,50 +86,50 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return zS(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 hp("schtasks",["/Create","/SC","ONLOGON","/TN",ca,"/TR",r,"/RU",t.userName,"/F"]),Jl.info("task scheduler entry created",{task:ca,logFile:t.logFile})},async uninstall(t){await hp("schtasks",["/Delete","/TN",ca,"/F"]).catch(e=>Jl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Jl.info("task scheduler entry removed",{task:ca})}}});var pp={};ba(pp,{buildContext:()=>WS,getSupervisor:()=>HS,launchdSupervisor:()=>$l,systemdSupervisor:()=>Vl,taskSchedulerSupervisor:()=>Zl});import{homedir as US,userInfo as GS}from"node:os";function HS(t=process.platform){switch(t){case"darwin":return $l;case"linux":return Vl;case"win32":return Zl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function jS(){let t={};for(let e of qS){let r=process.env[e];r&&(t[e]=r)}return t}function WS(){let t=Q();return{nodeBin:process.execPath,entry:Fl(t),logFile:t.logFile,homeDir:US(),userName:GS().username,isRoot:process.getuid?.()===0,env:jS()}}var qS,gp=Qe(()=>{"use strict";Oe();Yo();dp();fp();xp();qS=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();sn();var Td=H("acp-installer-warmup"),qg=["claude-code","codex"];async function kd(t={}){let e=t.ensure??ar,i=(await Promise.allSettled(qg.map(async o=>{let c=await e(o);Td.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Td.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))})}cn();te();import{readdir as sm}from"node:fs/promises";import{mkdir as Dd,readFile as rm,writeFile as Od}from"node:fs/promises";import{join as Ca}from"node:path";var im={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function dr(t,e,r){await Dd(t,{recursive:!0});let i=im[e],o=Ca(t,i);return await Od(o,r??"","utf8"),o}async function Ra(t,e,r){let i=Ca(t,".claude");await Dd(i,{recursive:!0});let o=Ca(i,"settings.local.json"),c={};try{let u=await rm(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 Od(o,JSON.stringify(c,null,2),"utf8"),o}var Ze=H("agent-detail-sync"),om=6e4,am=5*6e4,ps=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await sm(r)}catch(o){Ze.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Ze.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Te(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Ze.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Ze.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Ze.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Ze.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Ze.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await Te(e,this.opts.paths);if(!i){Ze.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){Ze.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let p=this.retryQueue.get(e),m=p?Math.min(p.currentDelay*2,am):om;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(o.agentId&&o.agentId!==e){Ze.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"?(Ze.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Ze.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Ze.debug("detail sync: no diff",{agentId:e});return}await Me(i,this.opts.paths),Ze.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}),Ze.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await dr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Yc=Ut(fu(),1);import{createHash as H_}from"node:crypto";import{lstat as jc,mkdir as Wc,readFile as ao,readdir as Zf,rm as Kc,stat as $f,writeFile as $c}from"node:fs/promises";import{dirname as q_,join as We,normalize as j_,relative as Zc,resolve as Vc,sep as Yf}from"node:path";import{Readable as Xf}from"node:stream";import{pipeline as Qf}from"node:stream/promises";import Cm from"events";import et from"fs";import{EventEmitter as Cc}from"node:events";import $u from"node:stream";import{StringDecoder as Rm}from"node:string_decoder";import Zu from"node:path";import br from"node:fs";import{dirname as qm,parse as jm}from"path";import{EventEmitter as Xm}from"events";import dc from"assert";import{Buffer as Hn}from"buffer";import*as mu from"zlib";import Qm from"zlib";import{posix as pr}from"node:path";import{basename as Aw}from"node:path";import $s from"fs";import Rt from"fs";import Su from"path";import{win32 as Fw}from"node:path";import Pu from"path";import ff from"node:fs";import t_ from"node:assert";import{randomBytes as hf}from"node:crypto";import re from"node:fs";import Ne from"node:path";import xf from"fs";import no from"node:fs";import Si from"node:path";import ot from"node:fs";import c_ from"node:fs/promises";import Zs from"node:path";import{join as If}from"node:path";import st from"node:fs";import kf from"node:path";var Tm=Object.defineProperty,km=(t,e)=>{for(var r in e)Tm(t,r,{get:e[r],enumerable:!0})},hu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Pm=t=>!!t&&typeof t=="object"&&(t instanceof Wn||t instanceof $u||Dm(t)||Om(t)),Dm=t=>!!t&&typeof t=="object"&&t instanceof Cc&&typeof t.pipe=="function"&&t.pipe!==$u.Writable.prototype.pipe,Om=t=>!!t&&typeof t=="object"&&t instanceof Cc&&typeof t.write=="function"&&typeof t.end=="function",Gt=Symbol("EOF"),Ht=Symbol("maybeEmitEnd"),dn=Symbol("emittedEnd"),ys=Symbol("emittingEnd"),ai=Symbol("emittedError"),Es=Symbol("closed"),xu=Symbol("read"),bs=Symbol("flush"),pu=Symbol("flushChunk"),mt=Symbol("encoding"),xr=Symbol("decoder"),Be=Symbol("flowing"),ci=Symbol("paused"),_r=Symbol("resume"),Fe=Symbol("buffer"),Ye=Symbol("pipes"),ze=Symbol("bufferLength"),Ma=Symbol("bufferPush"),vs=Symbol("bufferShift"),Je=Symbol("objectMode"),Se=Symbol("destroyed"),Ba=Symbol("error"),Fa=Symbol("emitData"),gu=Symbol("emitEnd"),za=Symbol("emitEnd2"),Tt=Symbol("async"),Ua=Symbol("abort"),Ss=Symbol("aborted"),li=Symbol("signal"),On=Symbol("dataListeners"),it=Symbol("discarded"),di=t=>Promise.resolve().then(t),Lm=t=>t(),Nm=t=>t==="end"||t==="finish"||t==="prefinish",Mm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Bm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Vu=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[_r](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Fm=class extends Vu{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},zm=t=>!!t.objectMode,Um=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Wn=class extends Cc{[Be]=!1;[ci]=!1;[Ye]=[];[Fe]=[];[Je];[mt];[Tt];[xr];[Gt]=!1;[dn]=!1;[ys]=!1;[Es]=!1;[ai]=null;[ze]=0;[Se]=!1;[li];[Ss]=!1;[On]=0;[it]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");zm(e)?(this[Je]=!0,this[mt]=null):Um(e)?(this[mt]=e.encoding,this[Je]=!1):(this[Je]=!1,this[mt]=null),this[Tt]=!!e.async,this[xr]=this[mt]?new Rm(this[mt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Fe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ye]});let{signal:r}=e;r&&(this[li]=r,r.aborted?this[Ua]():r.addEventListener("abort",()=>this[Ua]()))}get bufferLength(){return this[ze]}get encoding(){return this[mt]}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}[Ua](){this[Ss]=!0,this.emit("abort",this[li]?.reason),this.destroy(this[li]?.reason)}get aborted(){return this[Ss]}set aborted(t){}write(t,e,r){if(this[Ss])return!1;if(this[Gt])throw new Error("write after end");if(this[Se])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[Tt]?di:Lm;if(!this[Je]&&!Buffer.isBuffer(t)){if(Bm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Mm(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[Be]&&this[ze]!==0&&this[bs](!0),this[Be]?this.emit("data",t):this[Ma](t),this[ze]!==0&&this.emit("readable"),r&&i(r),this[Be]):t.length?(typeof t=="string"&&!(e===this[mt]&&!this[xr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[mt]&&(t=this[xr].write(t)),this[Be]&&this[ze]!==0&&this[bs](!0),this[Be]?this.emit("data",t):this[Ma](t),this[ze]!==0&&this.emit("readable"),r&&i(r),this[Be]):(this[ze]!==0&&this.emit("readable"),r&&i(r),this[Be])}read(t){if(this[Se])return null;if(this[it]=!1,this[ze]===0||t===0||t&&t>this[ze])return this[Ht](),null;this[Je]&&(t=null),this[Fe].length>1&&!this[Je]&&(this[Fe]=[this[mt]?this[Fe].join(""):Buffer.concat(this[Fe],this[ze])]);let e=this[xu](t||null,this[Fe][0]);return this[Ht](),e}[xu](t,e){if(this[Je])this[vs]();else{let r=e;t===r.length||t===null?this[vs]():typeof r=="string"?(this[Fe][0]=r.slice(t),e=r.slice(0,t),this[ze]-=t):(this[Fe][0]=r.subarray(t),e=r.subarray(0,t),this[ze]-=t)}return this.emit("data",e),!this[Fe].length&&!this[Gt]&&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[Gt]=!0,this.writable=!1,(this[Be]||!this[ci])&&this[Ht](),this}[_r](){this[Se]||(!this[On]&&!this[Ye].length&&(this[it]=!0),this[ci]=!1,this[Be]=!0,this.emit("resume"),this[Fe].length?this[bs]():this[Gt]?this[Ht]():this.emit("drain"))}resume(){return this[_r]()}pause(){this[Be]=!1,this[ci]=!0,this[it]=!1}get destroyed(){return this[Se]}get flowing(){return this[Be]}get paused(){return this[ci]}[Ma](t){this[Je]?this[ze]+=1:this[ze]+=t.length,this[Fe].push(t)}[vs](){return this[Je]?this[ze]-=1:this[ze]-=this[Fe][0].length,this[Fe].shift()}[bs](t=!1){do;while(this[pu](this[vs]())&&this[Fe].length);!t&&!this[Fe].length&&!this[Gt]&&this.emit("drain")}[pu](t){return this.emit("data",t),this[Be]}pipe(t,e){if(this[Se])return t;this[it]=!1;let r=this[dn];return e=e||{},t===hu.stdout||t===hu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Ye].push(e.proxyErrors?new Fm(this,t,e):new Vu(this,t,e)),this[Tt]?di(()=>this[_r]()):this[_r]()),t}unpipe(t){let e=this[Ye].find(r=>r.dest===t);e&&(this[Ye].length===1?(this[Be]&&this[On]===0&&(this[Be]=!1),this[Ye]=[]):this[Ye].splice(this[Ye].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[it]=!1,this[On]++,!this[Ye].length&&!this[Be]&&this[_r]();else if(t==="readable"&&this[ze]!==0)super.emit("readable");else if(Nm(t)&&this[dn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ai]){let i=e;this[Tt]?di(()=>i.call(this,this[ai])):i.call(this,this[ai])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[On]=this.listeners("data").length,this[On]===0&&!this[it]&&!this[Ye].length&&(this[Be]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[On]=0,!this[it]&&!this[Ye].length&&(this[Be]=!1)),e}get emittedEnd(){return this[dn]}[Ht](){!this[ys]&&!this[dn]&&!this[Se]&&this[Fe].length===0&&this[Gt]&&(this[ys]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Es]&&this.emit("close"),this[ys]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Se&&this[Se])return!1;if(t==="data")return!this[Je]&&!r?!1:this[Tt]?(di(()=>this[Fa](r)),!0):this[Fa](r);if(t==="end")return this[gu]();if(t==="close"){if(this[Es]=!0,!this[dn]&&!this[Se])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ai]=r,super.emit(Ba,r);let o=!this[li]||this.listeners("error").length?super.emit("error",r):!1;return this[Ht](),o}else if(t==="resume"){let o=super.emit("resume");return this[Ht](),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[Ht](),i}[Fa](t){for(let r of this[Ye])r.dest.write(t)===!1&&this.pause();let e=this[it]?!1:super.emit("data",t);return this[Ht](),e}[gu](){return this[dn]?!1:(this[dn]=!0,this.readable=!1,this[Tt]?(di(()=>this[za]()),!0):this[za]())}[za](){if(this[xr]){let e=this[xr].end();if(e){for(let r of this[Ye])r.dest.write(e);this[it]||super.emit("data",e)}}for(let e of this[Ye])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Je]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Je]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Je])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[mt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Se,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[it]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Gt])return e();let i,o,c=p=>{this.off("data",d),this.off("end",u),this.off(Se,h),e(),o(p)},d=p=>{this.off("error",c),this.off("end",u),this.off(Se,h),this.pause(),i({value:p,done:!!this[Gt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Se,h),e(),i({done:!0,value:void 0})},h=()=>c(new Error("stream destroyed"));return new Promise((p,m)=>{o=m,i=p,this.once(Se,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[it]=!1;let t=!1,e=()=>(this.pause(),this.off(Ba,e),this.off(Se,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Ba,e),this.once(Se,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Se])return t?this.emit("error",t):this.emit(Se),this;this[Se]=!0,this[it]=!0,this[Fe].length=0,this[ze]=0;let e=this;return typeof e.close=="function"&&!this[Es]&&e.close(),t?this.emit("error",t):this.emit(Se),this}static get isStream(){return Pm}},Gm=et.writev,yn=Symbol("_autoClose"),Et=Symbol("_close"),ui=Symbol("_ended"),ce=Symbol("_fd"),Ga=Symbol("_finished"),Kt=Symbol("_flags"),Ha=Symbol("_flush"),cc=Symbol("_handleChunk"),lc=Symbol("_makeBuf"),bi=Symbol("_mode"),Is=Symbol("_needDrain"),Sr=Symbol("_onerror"),Ir=Symbol("_onopen"),qa=Symbol("_onread"),yr=Symbol("_onwrite"),En=Symbol("_open"),yt=Symbol("_path"),pn=Symbol("_pos"),kt=Symbol("_queue"),Er=Symbol("_read"),ja=Symbol("_readSize"),Wt=Symbol("_reading"),fi=Symbol("_remain"),Wa=Symbol("_size"),Ns=Symbol("_write"),Ln=Symbol("_writing"),Ms=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Rc=class extends Wn{[Gn]=!1;[ce];[yt];[ja];[Wt]=!1;[Wa];[fi];[yn];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[ce]=typeof e.fd=="number"?e.fd:void 0,this[yt]=t,this[ja]=e.readSize||16*1024*1024,this[Wt]=!1,this[Wa]=typeof e.size=="number"?e.size:1/0,this[fi]=this[Wa],this[yn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ce]=="number"?this[Er]():this[En]()}get fd(){return this[ce]}get path(){return this[yt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[En](){et.open(this[yt],"r",(t,e)=>this[Ir](t,e))}[Ir](t,e){t?this[Sr](t):(this[ce]=e,this.emit("open",e),this[Er]())}[lc](){return Buffer.allocUnsafe(Math.min(this[ja],this[fi]))}[Er](){if(!this[Wt]){this[Wt]=!0;let t=this[lc]();if(t.length===0)return process.nextTick(()=>this[qa](null,0,t));et.read(this[ce],t,0,t.length,null,(e,r,i)=>this[qa](e,r,i))}}[qa](t,e,r){this[Wt]=!1,t?this[Sr](t):this[cc](e,r)&&this[Er]()}[Et](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Sr](t){this[Wt]=!0,this[Et](),this.emit("error",t)}[cc](t,e){let r=!1;return this[fi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[fi]<=0)&&(r=!1,this[Et](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ce]=="number"&&this[Er](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Hm=class extends Rc{[En](){let t=!0;try{this[Ir](null,et.openSync(this[yt],"r")),t=!1}finally{t&&this[Et]()}}[Er](){let t=!0;try{if(!this[Wt]){this[Wt]=!0;do{let e=this[lc](),r=e.length===0?0:et.readSync(this[ce],e,0,e.length,null);if(!this[cc](r,e))break}while(!0);this[Wt]=!1}t=!1}finally{t&&this[Et]()}}[Et](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.closeSync(t),this.emit("close")}}},Ys=class extends Cm{readable=!1;writable=!0;[Gn]=!1;[Ln]=!1;[ui]=!1;[kt]=[];[Is]=!1;[yt];[bi];[yn];[ce];[Ms];[Kt];[Ga]=!1;[pn];constructor(t,e){e=e||{},super(e),this[yt]=t,this[ce]=typeof e.fd=="number"?e.fd:void 0,this[bi]=e.mode===void 0?438:e.mode,this[pn]=typeof e.start=="number"?e.start:void 0,this[yn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[pn]!==void 0?"r+":"w";this[Ms]=e.flags===void 0,this[Kt]=e.flags===void 0?r:e.flags,this[ce]===void 0&&this[En]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[ce]}get path(){return this[yt]}[Sr](t){this[Et](),this[Ln]=!0,this.emit("error",t)}[En](){et.open(this[yt],this[Kt],this[bi],(t,e)=>this[Ir](t,e))}[Ir](t,e){this[Ms]&&this[Kt]==="r+"&&t&&t.code==="ENOENT"?(this[Kt]="w",this[En]()):t?this[Sr](t):(this[ce]=e,this.emit("open",e),this[Ln]||this[Ha]())}end(t,e){return t&&this.write(t,e),this[ui]=!0,!this[Ln]&&!this[kt].length&&typeof this[ce]=="number"&&this[yr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[ui]?(this.emit("error",new Error("write() after end()")),!1):this[ce]===void 0||this[Ln]||this[kt].length?(this[kt].push(t),this[Is]=!0,!1):(this[Ln]=!0,this[Ns](t),!0)}[Ns](t){et.write(this[ce],t,0,t.length,this[pn],(e,r)=>this[yr](e,r))}[yr](t,e){t?this[Sr](t):(this[pn]!==void 0&&typeof e=="number"&&(this[pn]+=e),this[kt].length?this[Ha]():(this[Ln]=!1,this[ui]&&!this[Ga]?(this[Ga]=!0,this[Et](),this.emit("finish")):this[Is]&&(this[Is]=!1,this.emit("drain"))))}[Ha](){if(this[kt].length===0)this[ui]&&this[yr](null,0);else if(this[kt].length===1)this[Ns](this[kt].pop());else{let t=this[kt];this[kt]=[],Gm(this[ce],t,this[pn],(e,r)=>this[yr](e,r))}}[Et](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Ju=class extends Ys{[En](){let t;if(this[Ms]&&this[Kt]==="r+")try{t=et.openSync(this[yt],this[Kt],this[bi])}catch(e){if(e?.code==="ENOENT")return this[Kt]="w",this[En]();throw e}else t=et.openSync(this[yt],this[Kt],this[bi]);this[Ir](null,t)}[Et](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.closeSync(t),this.emit("close")}}[Ns](t){let e=!0;try{this[yr](null,et.writeSync(this[ce],t,0,t.length,this[pn])),e=!1}finally{if(e)try{this[Et]()}catch{}}}},Wm=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"]]),Km=t=>!!t.sync&&!!t.file,$m=t=>!t.sync&&!!t.file,Vm=t=>!!t.sync&&!t.file,Jm=t=>!t.sync&&!t.file,Zm=t=>!!t.file,Ym=t=>Wm.get(t)||t,Pc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Ym(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Pi=(t,e,r,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=Pc(c);if(o?.(h,d),Km(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if($m(h)){let p=e(h,d);return u?p.then(()=>u(),u):p}else if(Vm(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(h,d)}else if(Jm(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}),ew=Qm.constants||{ZLIB_VERNUM:4736},Dt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},ew)),tw=Hn.concat,wu=Object.getOwnPropertyDescriptor(Hn,"concat"),nw=t=>t,Ka=wu?.writable===!0||wu?.set!==void 0?t=>{Hn.concat=t?nw:tw}:t=>{},qn=Symbol("_superWrite"),As=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"}},$a=Symbol("flushFlag"),Dc=class extends Wn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof mu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new mu[e](t)}catch(r){throw new As(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 As(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return dc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[$a]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[qn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Hn.from(t,e)),this.#e)return;dc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Ka(!0);let d;try{let h=typeof t[$a]=="number"?t[$a]:this.#r;d=this.#t._processChunk(t,h),Ka(!1)}catch(h){Ka(!1),this.#o(new As(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 As(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[qn](Hn.from(h));for(let p=1;p<d.length;p++)u=this[qn](d[p])}else u=this[qn](Hn.from(d));return r&&r(),u}},Yu=class extends Dc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Dt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Dt.Z_FINISH,t.fullFlushFlag=Dt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Dt.Z_SYNC_FLUSH),dc(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 Yu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[qn](t){return this.#e?(this.#e=!1,t[9]=255,super[qn](t)):super[qn](t)}},iw=class extends Yu{constructor(t){super(t,"Unzip")}},Xu=class extends Dc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Dt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Dt.BROTLI_OPERATION_FLUSH,super(t,e)}},sw=class extends Xu{constructor(t){super(t,"BrotliCompress")}},ow=class extends Xu{constructor(t){super(t,"BrotliDecompress")}},Qu=class extends Dc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Dt.ZSTD_e_end,t.fullFlushFlag=Dt.ZSTD_e_flush,super(t,e)}},aw=class extends Qu{constructor(t){super(t,"ZstdCompress")}},cw=class extends Qu{constructor(t){super(t,"ZstdDecompress")}},lw=(t,e)=>{if(Number.isSafeInteger(t))t<0?uw(t,e):dw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},dw=(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]=ef(o):o===0?e[i-1]=0:(r=!0,e[i-1]=tf(o))}},fw=t=>{let e=t[0],r=e===128?xw(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=ef(c):c===0?d=c:(i=!0,d=tf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},xw=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},ef=t=>(255^t)&255,tf=t=>(255^t)+1&255,pw={};km(pw,{code:()=>Oc,isCode:()=>Bs,isName:()=>gw,name:()=>Xs,normalFsTypes:()=>nf});var Bs=t=>Xs.has(t),gw=t=>Oc.has(t),nf=new Set(["0","","1","2","3","4","5","6","7","D"]),Xs=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"]]),Oc=new Map(Array.from(Xs).map(t=>[t[1],t[0]])),jn=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=Nn(t,e+156,1),c=nf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Nn(t,e,100),this.mode=d?.mode??u?.mode??gn(t,e+100,8),this.uid=d?.uid??u?.uid??gn(t,e+108,8),this.gid=d?.gid??u?.gid??gn(t,e+116,8),this.size=d?.size??u?.size??gn(t,e+124,12),this.mtime=d?.mtime??u?.mtime??Va(t,e+136,12),this.cksum=gn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Bs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Nn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Nn(t,e+265,32),this.gname=d?.gname??u?.gname??Nn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??gn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??gn(t,e+337,8)??0,t[e+475]!==0){let p=Nn(t,e+345,155);this.path=p+"/"+this.path}else{let p=Nn(t,e+345,130);p&&(this.path=p+"/"+this.path),this.atime=r?.atime??i?.atime??Va(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Va(t,e+488,12)}let h=256;for(let p=e;p<e+148;p++)h+=t[p];for(let p=e+156;p<e+512;p++)h+=t[p];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=mw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Mn(t,e,100,o)||this.needPax,this.needPax=mn(t,e+100,8,this.mode)||this.needPax,this.needPax=mn(t,e+108,8,this.uid)||this.needPax,this.needPax=mn(t,e+116,8,this.gid)||this.needPax,this.needPax=mn(t,e+124,12,this.size)||this.needPax,this.needPax=Ja(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Mn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Mn(t,e+265,32,this.uname)||this.needPax,this.needPax=Mn(t,e+297,32,this.gname)||this.needPax,this.needPax=mn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=mn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Mn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Mn(t,e+345,155,c)||this.needPax:(this.needPax=Mn(t,e+345,130,c)||this.needPax,this.needPax=Ja(t,e+476,12,this.atime)||this.needPax,this.needPax=Ja(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,mn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Xs.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Oc.get(t));if(Bs(e)||e==="Unsupported")this.#e=e;else if(Bs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},mw=(t,e)=>{let r=t,i="",o,c=pr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=pr.dirname(r),r=pr.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=pr.join(pr.basename(i),r),i=pr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Nn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Va=(t,e,r)=>ww(gn(t,e,r)),ww=t=>t===void 0?void 0:new Date(t*1e3),gn=(t,e,r)=>Number(t[e])&128?fw(t.subarray(e,e+r)):yw(t,e,r),_w=t=>isNaN(t)?void 0:t,yw=(t,e,r)=>_w(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Ew={12:8589934591,8:2097151},mn=(t,e,r,i)=>i===void 0?!1:i>Ew[r]||i<0?(lw(i,t.subarray(e,e+r)),!0):(bw(t,e,r,i),!1),bw=(t,e,r,i)=>t.write(vw(i,r),e,r,"ascii"),vw=(t,e)=>Sw(Math.floor(t).toString(8),e),Sw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Ja=(t,e,r,i)=>i===void 0?!1:mn(t,e,r,i.getTime()/1e3),Iw=new Array(156).join("\0"),Mn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Iw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Ks=class rf{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 jn({path:("PaxHeader/"+Aw(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 rf(Tw(kw(e),r),i)}},Tw=(t,e)=>e?Object.assign({},e,t):t,kw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(Cw,Object.create(null)),Cw=(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},Rw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,X=Rw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Pw=class extends Wn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=X(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?X(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=X(t.path)),t.linkpath&&(t.linkpath=X(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},Qs=(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))},Dw=1024*1024,uc=Buffer.from([31,139]),fc=Buffer.from([40,181,47,253]),Ow=Math.max(uc.length,fc.length),lt=Symbol("state"),Bn=Symbol("writeEntry"),qt=Symbol("readEntry"),Za=Symbol("nextEntry"),_u=Symbol("processEntry"),Ct=Symbol("extendedHeader"),hi=Symbol("globalExtendedHeader"),un=Symbol("meta"),yu=Symbol("emitMeta"),ge=Symbol("buffer"),jt=Symbol("queue"),fn=Symbol("ended"),Ya=Symbol("emittedEnd"),Fn=Symbol("emit"),ke=Symbol("unzip"),Ts=Symbol("consumeChunk"),ks=Symbol("consumeChunkSub"),Xa=Symbol("consumeBody"),Eu=Symbol("consumeMeta"),bu=Symbol("consumeHeader"),xi=Symbol("consuming"),Qa=Symbol("bufferConcat"),Cs=Symbol("maybeEnd"),gr=Symbol("writing"),hn=Symbol("aborted"),Rs=Symbol("onDone"),zn=Symbol("sawValidEntry"),Ps=Symbol("sawNullBlock"),Ds=Symbol("sawEOF"),vu=Symbol("closeStream"),Lw=()=>!0,Ri=class extends Xm{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[jt]=[];[ge];[qt];[Bn];[lt]="begin";[un]="";[Ct];[hi];[fn]=!1;[ke];[hn]=!1;[zn];[Ps]=!1;[Ds]=!1;[gr]=!1;[xi]=!1;[Ya]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Rs,()=>{(this[lt]==="begin"||this[zn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Rs,t.ondone):this.on(Rs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Dw,this.filter=typeof t.filter=="function"?t.filter:Lw;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[vu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){Qs(this,t,e,r)}[bu](t,e){this[zn]===void 0&&(this[zn]=!1);let r;try{r=new jn(t,e,this[Ct],this[hi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Ps]?(this[Ds]=!0,this[lt]==="begin"&&(this[lt]="header"),this[Fn]("eof")):(this[Ps]=!0,this[Fn]("nullBlock"));else if(this[Ps]=!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[Bn]=new Pw(r,this[Ct],this[hi]);if(!this[zn])if(o.remain){let c=()=>{o.invalid||(this[zn]=!0)};o.on("end",c)}else this[zn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Fn]("ignoredEntry",o),this[lt]="ignore",o.resume()):o.size>0&&(this[un]="",o.on("data",c=>this[un]+=c),this[lt]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Fn]("ignoredEntry",o),this[lt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[lt]="body":(this[lt]="header",o.end()),this[qt]?this[jt].push(o):(this[jt].push(o),this[Za]())))}}}[vu](){queueMicrotask(()=>this.emit("close"))}[_u](t){let e=!0;if(!t)this[qt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[qt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Za]()),e=!1);return e}[Za](){do;while(this[_u](this[jt].shift()));if(this[jt].length===0){let t=this[qt];!t||t.flowing||t.size===t.remain?this[gr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Xa](t,e){let r=this[Bn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[lt]="header",this[Bn]=void 0,r.end()),o.length}[Eu](t,e){let r=this[Bn],i=this[Xa](t,e);return!this[Bn]&&r&&this[yu](r),i}[Fn](t,e,r){this[jt].length===0&&!this[qt]?this.emit(t,e,r):this[jt].push([t,e,r])}[yu](t){switch(this[Fn]("meta",this[un]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=Ks.parse(this[un],this[Ct],!1);break;case"GlobalExtendedHeader":this[hi]=Ks.parse(this[un],this[hi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[un].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[un].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[hn]=!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[hn])return r?.(),!1;if((this[ke]===void 0||this.brotli===void 0&&this[ke]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<Ow)return this[ge]=t,r?.(),!0;for(let d=0;this[ke]===void 0&&d<uc.length;d++)t[d]!==uc[d]&&(this[ke]=!1);let o=!1;if(this[ke]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<fc.length;d++)if(t[d]!==fc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[ke]===!1&&c)if(t.length<512)if(this[fn])this.brotli=!0;else return this[ge]=t,r?.(),!0;else try{new jn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[ke]===void 0||this[ke]===!1&&(this.brotli||o)){let d=this[fn];this[fn]=!1,this[ke]=this[ke]===void 0?new iw({}):o?new cw({}):new ow({}),this[ke].on("data",h=>this[Ts](h)),this[ke].on("error",h=>this.abort(h)),this[ke].on("end",()=>{this[fn]=!0,this[Ts]()}),this[gr]=!0;let u=!!this[ke][d?"end":"write"](t);return this[gr]=!1,r?.(),u}}this[gr]=!0,this[ke]?this[ke].write(t):this[Ts](t),this[gr]=!1;let i=this[jt].length>0?!1:this[qt]?this[qt].flowing:!0;return!i&&this[jt].length===0&&this[qt]?.once("drain",()=>this.emit("drain")),r?.(),i}[Qa](t){t&&!this[hn]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Cs](){if(this[fn]&&!this[Ya]&&!this[hn]&&!this[xi]){this[Ya]=!0;let t=this[Bn];if(t&&t.blockRemain){let e=this[ge]?this[ge].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ge]&&t.write(this[ge]),t.end()}this[Fn](Rs)}}[Ts](t){if(this[xi]&&t)this[Qa](t);else if(!t&&!this[ge])this[Cs]();else if(t){if(this[xi]=!0,this[ge]){this[Qa](t);let e=this[ge];this[ge]=void 0,this[ks](e)}else this[ks](t);for(;this[ge]&&this[ge]?.length>=512&&!this[hn]&&!this[Ds];){let e=this[ge];this[ge]=void 0,this[ks](e)}this[xi]=!1}(!this[ge]||this[fn])&&this[Cs]()}[ks](t){let e=0,r=t.length;for(;e+512<=r&&!this[hn]&&!this[Ds];)switch(this[lt]){case"begin":case"header":this[bu](t,e),e+=512;break;case"ignore":case"body":e+=this[Xa](t,e);break;case"meta":e+=this[Eu](t,e);break;default:throw new Error("invalid state: "+this[lt])}e<r&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[hn]||(this[ke]?(t&&this[ke].write(t),this[ke].end()):(this[fn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Cs]())),this}},vi=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},Nw=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=>[vi(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||jm(c).root||".",h;if(c===u)h=!1;else{let p=r.get(c);h=p!==void 0?p:o(qm(c),u)}return r.set(c,h),h};t.filter=i?(c,d)=>i(c,d)&&o(vi(c)):c=>o(vi(c))},Mw=t=>{let e=new Ri(t),r=t.file,i;try{i=br.openSync(r,"r");let o=br.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=br.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=br.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{br.closeSync(i)}catch{}}},Bw=(t,e)=>{let r=new Ri(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),br.stat(o,(u,h)=>{if(u)d(u);else{let p=new Rc(o,{readSize:i,size:h.size});p.on("error",d),p.pipe(r)}})})},Ar=Pi(Mw,Bw,t=>new Ri(t),t=>new Ri(t),(t,e)=>{e?.length&&sf(t,e),t.noResume||Nw(t)}),of=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:zw,parse:Iu}=Fw,Lc=t=>{let e="",r=Iu(t);for(;zw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Iu(t)}return[e,t]},eo=["|","<",">","?",":"],Nc=eo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Uw=new Map(eo.map((t,e)=>[t,Nc[e]])),Gw=new Map(Nc.map((t,e)=>[t,eo[e]])),Au=t=>eo.reduce((e,r)=>e.split(r).join(Uw.get(r)),t),Hw=t=>Nc.reduce((e,r)=>e.split(r).join(Gw.get(r)),t),af=(t,e)=>e?(t=X(t).replace(/^\.(\/|$)/,""),vi(e)+"/"+t):X(t),qw=16*1024*1024,Tu=Symbol("process"),ku=Symbol("file"),Cu=Symbol("directory"),hc=Symbol("symlink"),Ru=Symbol("hardlink"),pi=Symbol("header"),Fs=Symbol("read"),xc=Symbol("lstat"),zs=Symbol("onlstat"),pc=Symbol("onread"),gc=Symbol("onreadlink"),mc=Symbol("openfile"),wc=Symbol("onopenfile"),wn=Symbol("close"),Vs=Symbol("mode"),_c=Symbol("awaitDrain"),ec=Symbol("ondrain"),Pt=Symbol("prefix"),cf=class extends Wn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Pc(e);super(),this.path=X(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||qw,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=X(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?X(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Lc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=Hw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=X(r.absolute||Su.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[zs](o):this[xc]()}warn(t,e,r={}){return Qs(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[xc](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[zs](e)})}[zs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Kw(t),this.emit("stat",t),this[Tu]()}[Tu](){switch(this.type){case"File":return this[ku]();case"Directory":return this[Cu]();case"SymbolicLink":return this[hc]();default:return this.end()}}[Vs](t){return of(t,this.type==="Directory",this.portable)}[Pt](t){return af(t,this.prefix)}[pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new jn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[Vs](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 Ks({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)}[Cu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[pi](),this.end()}[hc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[gc](e)})}[gc](t){this.linkpath=X(t),this[pi](),this.end()}[Ru](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=X(Su.relative(this.cwd,t)),this.stat.size=0,this[pi](),this.end()}[ku](){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[Ru](e);this.linkCache.set(t,this.absolute)}if(this[pi](),this.stat.size===0)return this.end();this[mc]()}[mc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[wc](e)})}[wc](t){if(this.fd=t,this.#e)return this[wn]();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[Fs]()}[Fs](){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[wn](()=>this.emit("error",c));this[pc](d)})}[wn](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[pc](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[wn](()=>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[wn](()=>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[ec]():this[_c](()=>this[ec]())}[_c](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)}[ec](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[wn](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[Fs]()}},jw=class extends cf{sync=!0;[xc](){this[zs](Rt.lstatSync(this.absolute))}[hc](){this[gc](Rt.readlinkSync(this.absolute))}[mc](){this[wc](Rt.openSync(this.absolute,"r"))}[Fs](){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[pc](d),t=!1}finally{if(t)try{this[wn](()=>{})}catch{}}}[_c](t){t()}[wn](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},Ww=class extends Wn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return Qs(this,t,e,r)}constructor(t,e={}){let r=Pc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=X(t.path),this.mode=t.mode!==void 0?this[Vs](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?X(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Lc(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 jn({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 Ks({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)}[Vs](t){return of(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}},Kw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",$w=class vr{tail;head;length=0;static create(e=[]){return new vr(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++)Jw(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)Zw(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 vr;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 vr;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 vr;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 vr;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=Vw(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 Vw(t,e,r){let i=e,o=e?e.next:t.head,c=new Mc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Jw(t,e){t.tail=new Mc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Zw(t,e){t.head=new Mc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Mc=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}},Du=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Ou=Buffer.alloc(1024),Us=Symbol("onStat"),gi=Symbol("ended"),wt=Symbol("queue"),mi=Symbol("pendingLinks"),xn=Symbol("current"),Un=Symbol("process"),wi=Symbol("processing"),Os=Symbol("processJob"),_t=Symbol("jobs"),tc=Symbol("jobDone"),Gs=Symbol("addFSEntry"),Lu=Symbol("addTarEntry"),yc=Symbol("stat"),Ec=Symbol("readdir"),Hs=Symbol("onreaddir"),qs=Symbol("pipe"),Nu=Symbol("entry"),nc=Symbol("entryOpt"),js=Symbol("writeEntryClass"),lf=Symbol("write"),rc=Symbol("ondrain"),to=class extends Wn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[js];onWriteEntry;[wt];[mi]=new Map;[_t]=0;[wi]=!1;[gi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=X(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[js]=cf,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 sw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new aw(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[rc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[rc]);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[wt]=new $w,this[_t]=0,this.jobs=Number(t.jobs)||4,this[wi]=!1,this[gi]=!1}[lf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[gi]=!0,this[Un](),r&&r(),this}write(t){if(this[gi])throw new Error("write after end");return typeof t=="string"?this[Gs](t):this[Lu](t),this.flowing}[Lu](t){let e=X(Pu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Du(t.path,e);r.entry=new Ww(t,this[nc](r)),r.entry.on("end",()=>this[tc](r)),this[_t]+=1,this[wt].push(r)}this[Un]()}[Gs](t){let e=X(Pu.resolve(this.cwd,t));this[wt].push(new Du(t,e)),this[Un]()}[yc](t){t.pending=!0,this[_t]+=1;let e=this.follow?"stat":"lstat";$s[e](t.absolute,(r,i)=>{t.pending=!1,this[_t]-=1,r?this.emit("error",r):this[Us](t,i)})}[Us](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[xn])this[Os](t);else{let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);i?i.push(t):this[mi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[Un]()}[Ec](t){t.pending=!0,this[_t]+=1,$s.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[_t]-=1,e)return this.emit("error",e);this[Hs](t,r)})}[Hs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Un]()}[Un](){if(!this[wi]){this[wi]=!0;for(let t=this[wt].head;t&&this[_t]<this.jobs;t=t.next)if(this[Os](t.value),t.value.ignore){let e=t.next;this[wt].removeNode(t),t.next=e}this[wi]=!1,this[gi]&&this[wt].length===0&&this[_t]===0&&(this.zip?this.zip.end(Ou):(super.write(Ou),super.end()))}}get[xn](){return this[wt]&&this[wt].head&&this[wt].head.value}[tc](t){this[wt].shift(),this[_t]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);if(i){this[mi].delete(r);for(let o of i)o.pending=!1,this[Os](o)}}this[Un]()}[Os](t){if(t.pending&&t.pendingLink&&t===this[xn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[xn]&&!t.piped&&this[qs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Us](t,e):this[yc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Hs](t,e):this[Ec](t),!t.readdir)return}if(t.entry=this[Nu](t),!t.entry){t.ignore=!0;return}t===this[xn]&&!t.piped&&this[qs](t)}}}[nc](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}}[Nu](t){this[_t]+=1;try{return new this[js](t.path,this[nc](t)).on("end",()=>this[tc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[rc](){this[xn]&&this[xn].entry&&this[xn].entry.resume()}[qs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Gs](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={}){Qs(this,t,e,r)}},Bc=class extends to{sync=!0;constructor(t){super(t),this[js]=jw}pause(){}resume(){}[yc](t){let e=this.follow?"statSync":"lstatSync";this[Us](t,$s[e](t.absolute))}[Ec](t){this[Hs](t,$s.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[Gs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[lf](i)})}},Yw=(t,e)=>{let r=new Bc(t),i=new Ju(t.file,{mode:t.mode||438});r.pipe(i),df(r,e)},Xw=(t,e)=>{let r=new to(t),i=new Ys(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 uf(r,e).catch(c=>r.emit("error",c)),o},df=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ar({file:Zu.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},uf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ar({file:Zu.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},Qw=(t,e)=>{let r=new Bc(t);return df(r,e),r},e_=(t,e)=>{let r=new to(t);return uf(r,e).catch(i=>r.emit("error",i)),r},TI=Pi(Yw,Xw,Qw,e_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),n_=process.env.__FAKE_PLATFORM__||process.platform,pf=n_==="win32",{O_CREAT:gf,O_NOFOLLOW:Mu,O_TRUNC:mf,O_WRONLY:wf}=xf.constants,_f=Number(process.env.__FAKE_FS_O_FILENAME__)||xf.constants.UV_FS_O_FILEMAP||0,r_=pf&&!!_f,i_=512*1024,s_=_f|mf|gf|wf,Bu=!pf&&typeof Mu=="number"?Mu|mf|gf|wf:null,yf=Bu!==null?()=>Bu:r_?t=>t<i_?s_:"w":()=>"w",bc=(t,e,r)=>{try{return no.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},Js=(t,e,r,i)=>{no.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},o_=(t,e,r,i,o)=>{if(e.isDirectory())Ef(Si.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Si.resolve(t,e.name);Js(d,r,i,o)});else{let c=Si.resolve(t,e.name);Js(c,r,i,o)}},Ef=(t,e,r,i)=>{no.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 Js(t,e,r,i);let d=c.length,u=null,h=p=>{if(!u){if(p)return i(u=p);if(--d===0)return Js(t,e,r,i)}};for(let p of c)o_(t,p,e,r,h)})},a_=(t,e,r,i)=>{e.isDirectory()&&bf(Si.resolve(t,e.name),r,i),bc(Si.resolve(t,e.name),r,i)},bf=(t,e,r)=>{let i;try{i=no.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return bc(t,e,r);throw c}for(let o of i)a_(t,o,e,r);return bc(t,e,r)},vf=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"}},ro=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"}},l_=(t,e)=>{ot.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new vf(t,r?.code||"ENOTDIR")),e(r)})},d_=(t,e,r)=>{t=X(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),p=e.preserve,m=e.unlink,_=X(e.cwd),v=(S,I)=>{S?r(S):I&&h?Ef(I,d,u,A=>v(A)):c?ot.chmod(t,o,r):r()};if(t===_)return l_(t,v);if(p)return c_.mkdir(t,{mode:o,recursive:!0}).then(S=>v(null,S??void 0),v);let y=X(Zs.relative(_,t)).split("/");vc(_,y,o,m,_,void 0,v)},vc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),h=X(Zs.resolve(t+"/"+u));ot.mkdir(h,r,Sf(h,e,r,i,o,c,d))},Sf=(t,e,r,i,o,c,d)=>u=>{u?ot.lstat(t,(h,p)=>{if(h)h.path=h.path&&X(h.path),d(h);else if(p.isDirectory())vc(t,e,r,i,o,c,d);else if(i)ot.unlink(t,m=>{if(m)return d(m);ot.mkdir(t,r,Sf(t,e,r,i,o,c,d))});else{if(p.isSymbolicLink())return d(new ro(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,vc(t,e,r,i,o,c,d))},u_=t=>{let e=!1,r;try{e=ot.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new vf(t,r??"ENOTDIR")}},f_=(t,e)=>{t=X(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,p=e.unlink,m=X(e.cwd),_=S=>{S&&u&&bf(S,c,d),o&&ot.chmodSync(t,i)};if(t===m)return u_(m),_();if(h)return _(ot.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=X(Zs.relative(m,t)).split("/"),y;for(let S=v.shift(),I=m;S&&(I+="/"+S);S=v.shift()){I=X(Zs.resolve(I));try{ot.mkdirSync(I,i),y=y||I}catch{let A=ot.lstatSync(I);if(A.isDirectory())continue;if(p){ot.unlinkSync(I),ot.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new ro(I,I+"/"+v.join("/"))}}return _(y)},ic=Object.create(null),Fu=1e4,mr=new Set,h_=t=>{mr.has(t)?mr.delete(t):ic[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),mr.add(t);let e=ic[t],r=mr.size-Fu;if(r>Fu/10){for(let i of mr)if(mr.delete(i),delete ic[i],--r<=0)break}return e},x_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,p_=x_==="win32",g_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=If(i,r)),e.push(r||"/"),e},[]),m_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=p_?["win32 parallelization disabled"]:t.map(i=>vi(If(h_(i))));let r=new Set(t.map(i=>g_(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}},w_=()=>process.umask(),zu=Symbol("onEntry"),Sc=Symbol("checkFs"),Uu=Symbol("checkFs2"),Ic=Symbol("isReusable"),dt=Symbol("makeFs"),Ac=Symbol("file"),Tc=Symbol("directory"),Ws=Symbol("link"),Gu=Symbol("symlink"),Hu=Symbol("hardlink"),Ei=Symbol("ensureNoSymlink"),qu=Symbol("unsupported"),ju=Symbol("checkPath"),sc=Symbol("stripAbsolutePath"),_n=Symbol("mkdir"),Ue=Symbol("onError"),Ls=Symbol("pending"),Wu=Symbol("pend"),wr=Symbol("unpend"),oc=Symbol("ended"),ac=Symbol("maybeClose"),kc=Symbol("skip"),Ii=Symbol("doChown"),Ai=Symbol("uid"),Ti=Symbol("gid"),ki=Symbol("checkedCwd"),__=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ci=__==="win32",y_=1024,E_=(t,e)=>{if(!Ci)return re.unlink(t,e);let r=t+".DELETE."+hf(16).toString("hex");re.rename(t,r,i=>{if(i)return e(i);re.unlink(r,e)})},b_=t=>{if(!Ci)return re.unlinkSync(t);let e=t+".DELETE."+hf(16).toString("hex");re.renameSync(t,e),re.unlinkSync(e)},Ku=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Fc=class extends Ri{[oc]=!1;[ki]=!1;[Ls]=0;reservations=new m_;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[oc]=!0,this[ac]()},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:y_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ci,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=X(Ne.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:w_():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)}[ac](){this[oc]&&this[Ls]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[sc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Lc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Ci&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=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}[ju](t){let e=X(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=X(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[sc](t,"path")||!this[sc](t,"linkpath"))return!1;if(t.absolute=Ne.isAbsolute(t.path)?X(Ne.resolve(t.path)):X(Ne.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:X(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Ne.win32.parse(String(t.absolute));t.absolute=i+Au(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Au(t.path.slice(o.length))}return!0}[zu](t){if(!this[ju](t))return t.resume();switch(t_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Sc](t);default:return this[qu](t)}}[Ue](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[wr](),e.resume())}[_n](t,e,r){d_(X(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ii](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ai](t){return Ku(this.uid,t.uid,this.processUid)}[Ti](t){return Ku(this.gid,t.gid,this.processGid)}[Ac](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Ys(String(t.absolute),{flags:yf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&re.close(i.fd,()=>{}),i.write=()=>!0,this[Ue](u,t),e()});let o=1,c=u=>{if(u){i.fd&&re.close(i.fd,()=>{}),this[Ue](u,t),e();return}--o===0&&i.fd!==void 0&&re.close(i.fd,h=>{h?this[Ue](h,t):this[wr](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){o++;let p=t.atime||new Date,m=t.mtime;re.futimes(h,p,m,_=>_?re.utimes(u,p,m,v=>c(v&&_)):c())}if(typeof h=="number"&&this[Ii](t)){o++;let p=this[Ai](t),m=this[Ti](t);typeof p=="number"&&typeof m=="number"&&re.fchown(h,p,m,_=>_?re.chown(u,p,m,v=>c(v&&_)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[Ue](u,t),e()}),t.pipe(d)),d.pipe(i)}[Tc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[_n](String(t.absolute),r,i=>{if(i){this[Ue](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[wr](),t.resume())};t.mtime&&!this.noMtime&&(o++,re.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ii](t)&&(o++,re.chown(String(t.absolute),Number(this[Ai](t)),Number(this[Ti](t)),c)),c()})}[qu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Gu](t,e){let r=X(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ei](t,this.cwd,r,()=>this[Ws](t,String(t.linkpath),"symlink",e),i=>{this[Ue](i,t),e()})}[Hu](t,e){let r=X(Ne.resolve(this.cwd,String(t.linkpath))),i=X(String(t.linkpath)).split("/");this[Ei](t,this.cwd,i,()=>this[Ws](t,r,"link",e),o=>{this[Ue](o,t),e()})}[Ei](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Ne.resolve(e,c);re.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return o(new ro(d,Ne.resolve(d,r.join("/"))));this[Ei](t,d,r,i,o)})}[Wu](){this[Ls]++}[wr](){this[Ls]--,this[ac]()}[kc](t){this[wr](),t.resume()}[Ic](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ci}[Sc](t){this[Wu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Uu](t,r))}[Uu](t,e){let r=d=>{e(d)},i=()=>{this[_n](this.cwd,this.dmode,d=>{if(d){this[Ue](d,t),r();return}this[ki]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=X(Ne.dirname(String(t.absolute)));if(d!==this.cwd)return this[_n](d,this.dmode,u=>{if(u){this[Ue](u,t),r();return}c()})}c()},c=()=>{re.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[kc](t),r();return}if(d||this[Ic](t,u))return this[dt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,p=m=>this[dt](m??null,t,r);return h?re.chmod(String(t.absolute),Number(t.mode),p):p()}if(t.absolute!==this.cwd)return re.rmdir(String(t.absolute),h=>this[dt](h??null,t,r))}if(t.absolute===this.cwd)return this[dt](null,t,r);E_(String(t.absolute),h=>this[dt](h??null,t,r))})};this[ki]?o():i()}[dt](t,e,r){if(t){this[Ue](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Ac](e,r);case"Link":return this[Hu](e,r);case"SymbolicLink":return this[Gu](e,r);case"Directory":case"GNUDumpDir":return this[Tc](e,r)}}[Ws](t,e,r,i){re[r](e,String(t.absolute),o=>{o?this[Ue](o,t):(this[wr](),t.resume()),i()})}},_i=t=>{try{return[null,t()]}catch(e){return[e,null]}},Af=class extends Fc{sync=!0;[dt](t,e){return super[dt](t,e,()=>{})}[Sc](t){if(!this[ki]){let o=this[_n](this.cwd,this.dmode);if(o)return this[Ue](o,t);this[ki]=!0}if(t.absolute!==this.cwd){let o=X(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[_n](o,this.dmode);if(c)return this[Ue](c,t)}}let[e,r]=_i(()=>re.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[kc](t);if(e||this[Ic](t,r))return this[dt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?_i(()=>{re.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[dt](d,t)}let[o]=_i(()=>re.rmdirSync(String(t.absolute)));this[dt](o,t)}let[i]=t.absolute===this.cwd?[]:_i(()=>b_(String(t.absolute)));this[dt](i,t)}[Ac](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{re.closeSync(o)}catch(h){u=h}(d||u)&&this[Ue](d||u,t),e()},o;try{o=re.openSync(String(t.absolute),yf(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[Ue](d,t)),t.pipe(c)),c.on("data",d=>{try{re.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{re.futimesSync(o,u,h)}catch(p){try{re.utimesSync(String(t.absolute),u,h)}catch{d=p}}}if(this[Ii](t)){let u=this[Ai](t),h=this[Ti](t);try{re.fchownSync(o,Number(u),Number(h))}catch(p){try{re.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||p}}}i(d)})}[Tc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[_n](String(t.absolute),r);if(i){this[Ue](i,t),e();return}if(t.mtime&&!this.noMtime)try{re.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ii](t))try{re.chownSync(String(t.absolute),Number(this[Ai](t)),Number(this[Ti](t)))}catch{}e(),t.resume()}[_n](t,e){try{return f_(X(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Ei](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Ne.resolve(c,d);let[u,h]=_i(()=>re.lstatSync(c));if(u)return i();if(h.isSymbolicLink())return o(new ro(c,Ne.resolve(e,r.join("/"))))}i()}[Ws](t,e,r,i){let o=`${r}Sync`;try{re[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ue](c,t)}}},v_=t=>{let e=new Af(t),r=t.file,i=ff.statSync(r),o=t.maxReadSize||16*1024*1024;new Hm(r,{readSize:o,size:i.size}).pipe(e)},S_=(t,e)=>{let r=new Fc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),ff.stat(o,(u,h)=>{if(u)d(u);else{let p=new Rc(o,{readSize:i,size:h.size});p.on("error",d),p.pipe(r)}})})},Tf=Pi(v_,S_,t=>new Af(t),t=>new Fc(t),(t,e)=>{e?.length&&sf(t,e)}),I_=(t,e)=>{let r=new Bc(t),i=!0,o,c;try{try{o=st.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")o=st.openSync(t.file,"w+");else throw h}let d=st.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let m=0,_=0;m<512;m+=_){if(_=st.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(!_)break e}let h=new jn(u);if(!h.cksumValid)break;let p=512*Math.ceil((h.size||0)/512);if(c+p+512>d.size)break;c+=p,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,A_(t,r,c,o,e)}finally{if(i)try{st.closeSync(o)}catch{}}},A_=(t,e,r,i,o)=>{let c=new Ju(t.file,{fd:i,start:r});e.pipe(c),k_(e,o)},T_=(t,e)=>{e=Array.from(e);let r=new to(t),i=(o,c,d)=>{let u=(v,y)=>{v?st.close(o,S=>d(v)):d(null,y)},h=0;if(c===0)return u(null,0);let p=0,m=Buffer.alloc(512),_=(v,y)=>{if(v||y===void 0)return u(v);if(p+=y,p<512&&y)return st.read(o,m,p,m.length-p,h+p,_);if(h===0&&m[0]===31&&m[1]===139)return u(new Error("cannot append to compressed archives"));if(p<512)return u(null,h);let S=new jn(m);if(!S.cksumValid)return u(null,h);let I=512*Math.ceil((S.size??0)/512);if(h+I+512>c||(h+=I+512,h>=c))return u(null,h);t.mtimeCache&&S.mtime&&t.mtimeCache.set(String(S.path),S.mtime),p=0,st.read(o,m,0,512,h,_)};st.read(o,m,0,512,h,_)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(h,p)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",st.open(t.file,d,u);if(h||!p)return c(h);st.fstat(p,(m,_)=>{if(m)return st.close(p,()=>c(m));i(p,_.size,(v,y)=>{if(v)return c(v);let S=new Ys(t.file,{fd:p,start:y});r.pipe(S),S.on("error",c),S.on("close",o),C_(r,e)})})};st.open(t.file,d,u)})},k_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ar({file:kf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},C_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ar({file:kf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},yi=Pi(I_,T_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Zm(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")}),HI=Pi(yi.syncFile,yi.asyncFile,yi.syncNoFile,yi.asyncNoFile,(t,e=[])=>{yi.validate?.(t,e),R_(t)}),R_=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))};cn();var ut={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function io(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Cf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function so(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Rf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Pf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Kn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}$t();qe();te();Oe();qe();function Tr(t,e){if(io(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Di(t){return t.startsWith("http://")||t.startsWith("https://")}function kr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as OA}from"node:fs";import{dirname as NA,join as MA}from"node:path";import{fileURLToPath as FA}from"node:url";var Ot="0.2.0-beta.1";qe();te();var oo="1008033",Nf="1289";var Mf="pbbp2",Bf="https://www.coze.cn",Ff="/api/coze_claw/resource/get_frontier_key",F_="https://www.coze.cn",z_="wss://frontier.coze.cn";function Cr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??F_}function zf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??z_}function bn(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Li(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Oi=H("handshake");async function zc(t){let e=Cr(t.endpoint),r=t.timeoutMs??1e4,i=`${kr(e)}${Ff}?aid=${encodeURIComponent(oo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...bn(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Oi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),h=u.headers.get("x-tt-logid")??"",p=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=${h}: ${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=${h}`);let _=m.data??{},v=typeof _.access_key=="string"&&_.access_key||typeof _.accessKey=="string"&&_.accessKey||void 0,y=typeof _.device_id=="string"&&_.device_id||typeof _.deviceId=="string"&&_.deviceId||void 0;if(!v||!y){let S=JSON.stringify(m).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${S}`)}return Oi.info("handshake ok",{remoteDeviceId:y,logid:h,traceId:p}),{accessKey:v,deviceId:y}}catch(u){if(u instanceof T)throw Oi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Oi.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let h=u.cause;throw Oi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Uc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",bt="auto",Uf=15e4;function Gf(t){return{model:Gc(t.model)??bt,...t.modelToken?{modelToken:t.modelToken}:{}}}function U_(t){return!t||t===bt}var G_=new Set(["auto","\u81EA\u52A8"]);function Gc(t){let e=t?.trim();if(e)return G_.has(e.toLowerCase())?bt:e}function Hf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Uc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||bt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else U_(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function qf(t,e,r){return t.modelToken?{baseUrl:`${Uc}/v1`,providerName:"coze",headers:{Authorization:`Bearer ${t.modelToken}`,...Hc(e,r)}}:null}function jf(t){if(!t.modelToken)return{};let e={model:t.model||bt,model_context_window:t.modelInfo?.contextWindow??Uf};return{CODEX_CONFIG:JSON.stringify(e)}}function Hc(t,e){let{ttEnv:r,usePpe:i}=Li(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Wf(t,e,r){if(!t.modelToken)return{};let i=Hc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
- `)}}function qc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Kf(t,e,r){if(!t.modelToken)return null;let i=t.model||bt,o=Hc(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let d={baseUrl:`${Uc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:i,name:i,reasoning:!1,input:c,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??Uf,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(d.headers=o),d}var he=H("agent-handlers"),Vf=5*1024*1024,W_=1,K_=6,$_=new Set(["node_modules",".git",".coze","dist","build",".next"]),V_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,J_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Z_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Y_(t){let e=t?.trim();return e?Z_.test(e)||J_.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function X_(t){return new Promise((e,r)=>{let i=nt("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 co=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Kn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ve(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let h of c){let p=We(o,h.relPath,"SKILL.md");await $f(p).then(_=>_.isFile()).catch(()=>!1)&&(d.push(ny(h)),u.add(h.relPath))}if(e.scanLocal){let h=i?.framework??"claude-code",p=await Q_(r,o,h);for(let m of p)u.has(m.relPath)||(u.add(m.relPath),d.push(m.skill))}return{skills:d}}async addSkills(e){e._meta;let r=Kn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((h,p)=>[h.skillId,p])),u=[];for(let h of o){let p=await lo({agentId:r,workspace:i.workspace,framework:i.framework,skill:h});uo(c,d,p),u.push(h)}return await si(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Kn(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=We(i.workspace,u.relPath);await Kc(h,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await si(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Kn(e._meta);if(!e.skillName)throw new T("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??Ve(r).workspace,c=i?.framework??"claude-code",d=e0(e.skillName),u=We(Xc(c),d),h=We(o,u),p=We(h,"SKILL.md");if(!await $f(p).then(k=>k.isFile()).catch(()=>!1))throw new T("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let _=new Yc.default;_.addLocalFolder(h,d);let v=_.toBuffer();if(v.length>Jf)throw new T("SKILL_ZIP_TOO_LARGE",`skill zip ${v.length} bytes exceeds limit ${Jf}`);let y=await ao(p,{encoding:"utf8"}).then(k=>n0(k).description).catch(()=>{}),S={};this.opts.publishSkillToMarketplace?S=await this.opts.publishSkillToMarketplace({zip:v,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...y?{description:y}:{},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",A=S.skillId??e.skillId??t0(r,u);if(i){let k=i.skills??[],D=k.find(E=>E.relPath===u);D?(D.version=I,D.skillId=A):k.push({skillId:A,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),...y?{description:y}:{}}),await si(r,k)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:u,zipBytes:v.length,skillId:A,version:I}),{ok:!0,skillId:A,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(p=>he.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(p)}))}}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 Te(r);if(!i)throw new T("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 dr(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 T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Me(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 T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Te(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Di(e.registry)&&o.push(`--registry=${e.registry}`);let c=Y_(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&V_.test(d)&&o.push("--env",d);let u=await X_(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 T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Te(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Me(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 T("IPC_BAD_REQUEST",`${ut.DELETE}: missing agentId`);let i=await Te(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let d=Ve(r);return c==="cloud"?await Kc(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Me(i)),he.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(Tr(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Gc(e.model)??bt,i=await Te(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Me(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};o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o).catch(d=>he.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(d)}));let c=[];for(let[d,u]of o.allSessionQueues())c.push(u.enqueue(async()=>{let h=o.sessions.get(d);h?.downstream&&(await h.downstream.stop(`switchModel: ${r}`).catch(()=>{}),h.downstream=void 0)}));return await Promise.all(c),he.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:c.length}),{ok:!0}}async resetAgent(e){if(Tr(e._meta,ut.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ut.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ut.RESET),await this.runDetailSync(e.agentId,ut.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),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 ii(e,o)}async clearPersistedAcpSessionIds(e){let r=await Te(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Me(r)}async repairAgent(e){if(Tr(e._meta,ut.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${ut.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${ut.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){he.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ut.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,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){Tr(e._meta,"_agent/getFileTree");let r=e._meta,i=Kn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await jc(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 ri(d,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let h=xy(e.depth);return u.isDirectory()?{tree:await hy(o,d,c,h)}:{tree:[{name:py(c),path:s0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Tr(e._meta,"_agent/getFileContent");let r=Kn(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 jc(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 ri(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>Vf)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${Vf})`);let d=await ao(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 Te(e).catch(()=>null))?.workspace??Ve(e).workspace}safeJoin(e,r){let i=Vc(e,r||"."),o=Zc(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${Yf}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Te(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function e0(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 Xc(t){return t==="claude-code"?We(".claude","skills"):We(".agents","skills")}function t0(t,e){return(H_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function n0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
89
+ `},configPath(t){return U1(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",ha,"/TR",r,"/RU",t.userName,"/F"]),Ql.info("task scheduler entry created",{task:ha,logFile:t.logFile})},async uninstall(t){await gp("schtasks",["/Delete","/TN",ha,"/F"]).catch(e=>Ql.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Ql.info("task scheduler entry removed",{task:ha})}}});var wp={};Aa(wp,{buildContext:()=>K1,getSupervisor:()=>q1,launchdSupervisor:()=>Zl,systemdSupervisor:()=>Xl,taskSchedulerSupervisor:()=>ed});import{homedir as G1,userInfo as H1}from"node:os";function q1(t=process.platform){switch(t){case"darwin":return Zl;case"linux":return Xl;case"win32":return ed;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function W1(){let t={};for(let e of j1){let r=process.env[e];r&&(t[e]=r)}return t}function K1(){let t=Q();return{nodeBin:process.execPath,entry:Hl(t),logFile:t.logFile,homeDir:G1(),userName:H1().username,isRoot:process.getuid?.()===0,env:W1()}}var j1,_p=et(()=>{"use strict";Le();ra();xp();pp();mp();j1=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();sn();var Cd=H("acp-installer-warmup"),jg=["claude-code","codex"];async function Dd(t={}){let e=t.ensure??cr,i=(await Promise.allSettled(jg.map(async o=>{let c=await e(o);Cd.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&Cd.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))})}cn();ne();import{readdir as om}from"node:fs/promises";import{mkdir as Nd,readFile as im,writeFile as Md}from"node:fs/promises";import{join as La}from"node:path";var sm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ur(t,e,r){await Nd(t,{recursive:!0});let i=sm[e],o=La(t,i);return await Md(o,r??"","utf8"),o}async function Oa(t,e,r){let i=La(t,".claude");await Nd(i,{recursive:!0});let o=La(i,"settings.local.json"),c={};try{let u=await im(o,"utf8"),x=JSON.parse(u);typeof x=="object"&&x!==null&&!Array.isArray(x)&&(c=x)}catch{}let l=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=r)}return c.permissions=l,await Md(o,JSON.stringify(c,null,2),"utf8"),o}var Ze=H("agent-detail-sync"),am=6e4,cm=5*6e4,bs=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){Ze.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Ze.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await ke(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Ze.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){Ze.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),Ze.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Ze.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Ze.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await ke(e,this.opts.paths);if(!i){Ze.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(x){Ze.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,cm):am;this.retryQueue.set(e,{dueAt:Date.now()+m,currentDelay:m});return}if(o.agentId&&o.agentId!==e){Ze.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,l=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,l=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Ze.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Ze.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Ze.debug("detail sync: no diff",{agentId:e});return}await Be(i,this.opts.paths),Ze.info("detail sync: config updated",{agentId:e,identityChanged:l,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Ze.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await ur(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var tl=Ut(pu(),1);import{createHash as q_}from"node:crypto";import{lstat as Vc,mkdir as Jc,readFile as ho,readdir as Qf,rm as Yc,stat as Yf,writeFile as Zc}from"node:fs/promises";import{dirname as j_,join as Ke,normalize as W_,relative as el,resolve as Xc,sep as e0}from"node:path";import{Readable as t0}from"node:stream";import{pipeline as n0}from"node:stream/promises";import Cm from"events";import nt from"fs";import{EventEmitter as Lc}from"node:events";import Yu from"node:stream";import{StringDecoder as Dm}from"node:string_decoder";import Qu from"node:path";import vr from"node:fs";import{dirname as jm,parse as Wm}from"path";import{EventEmitter as Qm}from"events";import hc from"assert";import{Buffer as Hn}from"buffer";import*as yu from"zlib";import ew from"zlib";import{posix as gr}from"node:path";import{basename as Tw}from"node:path";import Qs from"fs";import Ct from"fs";import Tu from"path";import{win32 as Fw}from"node:path";import Ou from"path";import pf from"node:fs";import n_ from"node:assert";import{randomBytes as gf}from"node:crypto";import ie from"node:fs";import Ne from"node:path";import mf from"fs";import co from"node:fs";import Ri from"node:path";import ot from"node:fs";import l_ from"node:fs/promises";import no from"node:path";import{join as kf}from"node:path";import st from"node:fs";import Df from"node:path";var km=Object.defineProperty,Rm=(t,e)=>{for(var r in e)km(t,r,{get:e[r],enumerable:!0})},gu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Pm=t=>!!t&&typeof t=="object"&&(t instanceof Wn||t instanceof Yu||Lm(t)||Om(t)),Lm=t=>!!t&&typeof t=="object"&&t instanceof Lc&&typeof t.pipe=="function"&&t.pipe!==Yu.Writable.prototype.pipe,Om=t=>!!t&&typeof t=="object"&&t instanceof Lc&&typeof t.write=="function"&&typeof t.end=="function",Gt=Symbol("EOF"),Ht=Symbol("maybeEmitEnd"),dn=Symbol("emittedEnd"),As=Symbol("emittingEnd"),fi=Symbol("emittedError"),Ts=Symbol("closed"),mu=Symbol("read"),ks=Symbol("flush"),wu=Symbol("flushChunk"),mt=Symbol("encoding"),pr=Symbol("decoder"),ze=Symbol("flowing"),xi=Symbol("paused"),yr=Symbol("resume"),Fe=Symbol("buffer"),Xe=Symbol("pipes"),Ue=Symbol("bufferLength"),Ua=Symbol("bufferPush"),Rs=Symbol("bufferShift"),Je=Symbol("objectMode"),Ie=Symbol("destroyed"),Ga=Symbol("error"),Ha=Symbol("emitData"),_u=Symbol("emitEnd"),qa=Symbol("emitEnd2"),Tt=Symbol("async"),ja=Symbol("abort"),Cs=Symbol("aborted"),hi=Symbol("signal"),Ln=Symbol("dataListeners"),it=Symbol("discarded"),pi=t=>Promise.resolve().then(t),Nm=t=>t(),Mm=t=>t==="end"||t==="finish"||t==="prefinish",Bm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,zm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Zu=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[yr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Fm=class extends Zu{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)}},Um=t=>!!t.objectMode,Gm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Wn=class extends Lc{[ze]=!1;[xi]=!1;[Xe]=[];[Fe]=[];[Je];[mt];[Tt];[pr];[Gt]=!1;[dn]=!1;[As]=!1;[Ts]=!1;[fi]=null;[Ue]=0;[Ie]=!1;[hi];[Cs]=!1;[Ln]=0;[it]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Um(e)?(this[Je]=!0,this[mt]=null):Gm(e)?(this[mt]=e.encoding,this[Je]=!1):(this[Je]=!1,this[mt]=null),this[Tt]=!!e.async,this[pr]=this[mt]?new Dm(this[mt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Fe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Xe]});let{signal:r}=e;r&&(this[hi]=r,r.aborted?this[ja]():r.addEventListener("abort",()=>this[ja]()))}get bufferLength(){return this[Ue]}get encoding(){return this[mt]}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}[ja](){this[Cs]=!0,this.emit("abort",this[hi]?.reason),this.destroy(this[hi]?.reason)}get aborted(){return this[Cs]}set aborted(t){}write(t,e,r){if(this[Cs])return!1;if(this[Gt])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[Tt]?pi:Nm;if(!this[Je]&&!Buffer.isBuffer(t)){if(zm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Bm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Je]?(this[ze]&&this[Ue]!==0&&this[ks](!0),this[ze]?this.emit("data",t):this[Ua](t),this[Ue]!==0&&this.emit("readable"),r&&i(r),this[ze]):t.length?(typeof t=="string"&&!(e===this[mt]&&!this[pr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[mt]&&(t=this[pr].write(t)),this[ze]&&this[Ue]!==0&&this[ks](!0),this[ze]?this.emit("data",t):this[Ua](t),this[Ue]!==0&&this.emit("readable"),r&&i(r),this[ze]):(this[Ue]!==0&&this.emit("readable"),r&&i(r),this[ze])}read(t){if(this[Ie])return null;if(this[it]=!1,this[Ue]===0||t===0||t&&t>this[Ue])return this[Ht](),null;this[Je]&&(t=null),this[Fe].length>1&&!this[Je]&&(this[Fe]=[this[mt]?this[Fe].join(""):Buffer.concat(this[Fe],this[Ue])]);let e=this[mu](t||null,this[Fe][0]);return this[Ht](),e}[mu](t,e){if(this[Je])this[Rs]();else{let r=e;t===r.length||t===null?this[Rs]():typeof r=="string"?(this[Fe][0]=r.slice(t),e=r.slice(0,t),this[Ue]-=t):(this[Fe][0]=r.subarray(t),e=r.subarray(0,t),this[Ue]-=t)}return this.emit("data",e),!this[Fe].length&&!this[Gt]&&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[Gt]=!0,this.writable=!1,(this[ze]||!this[xi])&&this[Ht](),this}[yr](){this[Ie]||(!this[Ln]&&!this[Xe].length&&(this[it]=!0),this[xi]=!1,this[ze]=!0,this.emit("resume"),this[Fe].length?this[ks]():this[Gt]?this[Ht]():this.emit("drain"))}resume(){return this[yr]()}pause(){this[ze]=!1,this[xi]=!0,this[it]=!1}get destroyed(){return this[Ie]}get flowing(){return this[ze]}get paused(){return this[xi]}[Ua](t){this[Je]?this[Ue]+=1:this[Ue]+=t.length,this[Fe].push(t)}[Rs](){return this[Je]?this[Ue]-=1:this[Ue]-=this[Fe][0].length,this[Fe].shift()}[ks](t=!1){do;while(this[wu](this[Rs]())&&this[Fe].length);!t&&!this[Fe].length&&!this[Gt]&&this.emit("drain")}[wu](t){return this.emit("data",t),this[ze]}pipe(t,e){if(this[Ie])return t;this[it]=!1;let r=this[dn];return e=e||{},t===gu.stdout||t===gu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Xe].push(e.proxyErrors?new Fm(this,t,e):new Zu(this,t,e)),this[Tt]?pi(()=>this[yr]()):this[yr]()),t}unpipe(t){let e=this[Xe].find(r=>r.dest===t);e&&(this[Xe].length===1?(this[ze]&&this[Ln]===0&&(this[ze]=!1),this[Xe]=[]):this[Xe].splice(this[Xe].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[it]=!1,this[Ln]++,!this[Xe].length&&!this[ze]&&this[yr]();else if(t==="readable"&&this[Ue]!==0)super.emit("readable");else if(Mm(t)&&this[dn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[fi]){let i=e;this[Tt]?pi(()=>i.call(this,this[fi])):i.call(this,this[fi])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Ln]=this.listeners("data").length,this[Ln]===0&&!this[it]&&!this[Xe].length&&(this[ze]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Ln]=0,!this[it]&&!this[Xe].length&&(this[ze]=!1)),e}get emittedEnd(){return this[dn]}[Ht](){!this[As]&&!this[dn]&&!this[Ie]&&this[Fe].length===0&&this[Gt]&&(this[As]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ts]&&this.emit("close"),this[As]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Ie&&this[Ie])return!1;if(t==="data")return!this[Je]&&!r?!1:this[Tt]?(pi(()=>this[Ha](r)),!0):this[Ha](r);if(t==="end")return this[_u]();if(t==="close"){if(this[Ts]=!0,!this[dn]&&!this[Ie])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[fi]=r,super.emit(Ga,r);let o=!this[hi]||this.listeners("error").length?super.emit("error",r):!1;return this[Ht](),o}else if(t==="resume"){let o=super.emit("resume");return this[Ht](),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[Ht](),i}[Ha](t){for(let r of this[Xe])r.dest.write(t)===!1&&this.pause();let e=this[it]?!1:super.emit("data",t);return this[Ht](),e}[_u](){return this[dn]?!1:(this[dn]=!0,this.readable=!1,this[Tt]?(pi(()=>this[qa]()),!0):this[qa]())}[qa](){if(this[pr]){let e=this[pr].end();if(e){for(let r of this[Xe])r.dest.write(e);this[it]||super.emit("data",e)}}for(let e of this[Xe])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[mt]?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[it]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Gt])return e();let i,o,c=h=>{this.off("data",l),this.off("end",u),this.off(Ie,x),e(),o(h)},l=h=>{this.off("error",c),this.off("end",u),this.off(Ie,x),this.pause(),i({value:h,done:!!this[Gt]})},u=()=>{this.off("error",c),this.off("data",l),this.off(Ie,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(Ie,x),this.once("error",c),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[it]=!1;let t=!1,e=()=>(this.pause(),this.off(Ga,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(Ga,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[it]=!0,this[Fe].length=0,this[Ue]=0;let e=this;return typeof e.close=="function"&&!this[Ts]&&e.close(),t?this.emit("error",t):this.emit(Ie),this}static get isStream(){return Pm}},Hm=nt.writev,yn=Symbol("_autoClose"),bt=Symbol("_close"),gi=Symbol("_ended"),le=Symbol("_fd"),Wa=Symbol("_finished"),Kt=Symbol("_flags"),Ka=Symbol("_flush"),fc=Symbol("_handleChunk"),xc=Symbol("_makeBuf"),Ti=Symbol("_mode"),Ds=Symbol("_needDrain"),Ir=Symbol("_onerror"),Ar=Symbol("_onopen"),$a=Symbol("_onread"),br=Symbol("_onwrite"),bn=Symbol("_open"),yt=Symbol("_path"),pn=Symbol("_pos"),kt=Symbol("_queue"),Er=Symbol("_read"),Va=Symbol("_readSize"),Wt=Symbol("_reading"),mi=Symbol("_remain"),Ja=Symbol("_size"),Gs=Symbol("_write"),On=Symbol("_writing"),Hs=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Oc=class extends Wn{[Gn]=!1;[le];[yt];[Va];[Wt]=!1;[Ja];[mi];[yn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Gn]=!1,this[le]=typeof e.fd=="number"?e.fd:void 0,this[yt]=t,this[Va]=e.readSize||16*1024*1024,this[Wt]=!1,this[Ja]=typeof e.size=="number"?e.size:1/0,this[mi]=this[Ja],this[yn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[le]=="number"?this[Er]():this[bn]()}get fd(){return this[le]}get path(){return this[yt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[bn](){nt.open(this[yt],"r",(t,e)=>this[Ar](t,e))}[Ar](t,e){t?this[Ir](t):(this[le]=e,this.emit("open",e),this[Er]())}[xc](){return Buffer.allocUnsafe(Math.min(this[Va],this[mi]))}[Er](){if(!this[Wt]){this[Wt]=!0;let t=this[xc]();if(t.length===0)return process.nextTick(()=>this[$a](null,0,t));nt.read(this[le],t,0,t.length,null,(e,r,i)=>this[$a](e,r,i))}}[$a](t,e,r){this[Wt]=!1,t?this[Ir](t):this[fc](e,r)&&this[Er]()}[bt](){if(this[yn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ir](t){this[Wt]=!0,this[bt](),this.emit("error",t)}[fc](t,e){let r=!1;return this[mi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[mi]<=0)&&(r=!1,this[bt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[le]=="number"&&this[Er](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},qm=class extends Oc{[bn](){let t=!0;try{this[Ar](null,nt.openSync(this[yt],"r")),t=!1}finally{t&&this[bt]()}}[Er](){let t=!0;try{if(!this[Wt]){this[Wt]=!0;do{let e=this[xc](),r=e.length===0?0:nt.readSync(this[le],e,0,e.length,null);if(!this[fc](r,e))break}while(!0);this[Wt]=!1}t=!1}finally{t&&this[bt]()}}[bt](){if(this[yn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.closeSync(t),this.emit("close")}}},ro=class extends Cm{readable=!1;writable=!0;[Gn]=!1;[On]=!1;[gi]=!1;[kt]=[];[Ds]=!1;[yt];[Ti];[yn];[le];[Hs];[Kt];[Wa]=!1;[pn];constructor(t,e){e=e||{},super(e),this[yt]=t,this[le]=typeof e.fd=="number"?e.fd:void 0,this[Ti]=e.mode===void 0?438:e.mode,this[pn]=typeof e.start=="number"?e.start:void 0,this[yn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[pn]!==void 0?"r+":"w";this[Hs]=e.flags===void 0,this[Kt]=e.flags===void 0?r:e.flags,this[le]===void 0&&this[bn]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[le]}get path(){return this[yt]}[Ir](t){this[bt](),this[On]=!0,this.emit("error",t)}[bn](){nt.open(this[yt],this[Kt],this[Ti],(t,e)=>this[Ar](t,e))}[Ar](t,e){this[Hs]&&this[Kt]==="r+"&&t&&t.code==="ENOENT"?(this[Kt]="w",this[bn]()):t?this[Ir](t):(this[le]=e,this.emit("open",e),this[On]||this[Ka]())}end(t,e){return t&&this.write(t,e),this[gi]=!0,!this[On]&&!this[kt].length&&typeof this[le]=="number"&&this[br](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[gi]?(this.emit("error",new Error("write() after end()")),!1):this[le]===void 0||this[On]||this[kt].length?(this[kt].push(t),this[Ds]=!0,!1):(this[On]=!0,this[Gs](t),!0)}[Gs](t){nt.write(this[le],t,0,t.length,this[pn],(e,r)=>this[br](e,r))}[br](t,e){t?this[Ir](t):(this[pn]!==void 0&&typeof e=="number"&&(this[pn]+=e),this[kt].length?this[Ka]():(this[On]=!1,this[gi]&&!this[Wa]?(this[Wa]=!0,this[bt](),this.emit("finish")):this[Ds]&&(this[Ds]=!1,this.emit("drain"))))}[Ka](){if(this[kt].length===0)this[gi]&&this[br](null,0);else if(this[kt].length===1)this[Gs](this[kt].pop());else{let t=this[kt];this[kt]=[],Hm(this[le],t,this[pn],(e,r)=>this[br](e,r))}}[bt](){if(this[yn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Xu=class extends ro{[bn](){let t;if(this[Hs]&&this[Kt]==="r+")try{t=nt.openSync(this[yt],this[Kt],this[Ti])}catch(e){if(e?.code==="ENOENT")return this[Kt]="w",this[bn]();throw e}else t=nt.openSync(this[yt],this[Kt],this[Ti]);this[Ar](null,t)}[bt](){if(this[yn]&&typeof this[le]=="number"){let t=this[le];this[le]=void 0,nt.closeSync(t),this.emit("close")}}[Gs](t){let e=!0;try{this[br](null,nt.writeSync(this[le],t,0,t.length,this[pn])),e=!1}finally{if(e)try{this[bt]()}catch{}}}},Km=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"]]),$m=t=>!!t.sync&&!!t.file,Vm=t=>!t.sync&&!!t.file,Jm=t=>!!t.sync&&!t.file,Ym=t=>!t.sync&&!t.file,Zm=t=>!!t.file,Xm=t=>Km.get(t)||t,Nc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Xm(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Mi=(t,e,r,i,o)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let x=Nc(c);if(o?.(x,l),$m(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(x,l)}else if(Vm(x)){let h=e(x,l);return u?h.then(()=>u(),u):h}else if(Jm(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(x,l)}else if(Ym(x)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(x,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),tw=ew.constants||{ZLIB_VERNUM:4736},Pt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},tw)),nw=Hn.concat,bu=Object.getOwnPropertyDescriptor(Hn,"concat"),rw=t=>t,Ya=bu?.writable===!0||bu?.set!==void 0?t=>{Hn.concat=t?rw:nw}:t=>{},qn=Symbol("_superWrite"),Ps=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Za=Symbol("flushFlag"),Mc=class extends Wn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof yu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new yu[e](t)}catch(r){throw new Ps(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 Ps(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return hc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[Za]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[qn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Hn.from(t,e)),this.#e)return;hc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},Ya(!0);let l;try{let x=typeof t[Za]=="number"?t[Za]:this.#r;l=this.#t._processChunk(t,x),Ya(!1)}catch(x){Ya(!1),this.#o(new Ps(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 Ps(x,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let x=l[0];u=this[qn](Hn.from(x));for(let h=1;h<l.length;h++)u=this[qn](l[h])}else u=this[qn](Hn.from(l));return r&&r(),u}},ef=class extends Mc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Pt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Pt.Z_FINISH,t.fullFlushFlag=Pt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Pt.Z_SYNC_FLUSH),hc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},iw=class extends ef{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[qn](t){return this.#e?(this.#e=!1,t[9]=255,super[qn](t)):super[qn](t)}},sw=class extends ef{constructor(t){super(t,"Unzip")}},tf=class extends Mc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Pt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Pt.BROTLI_OPERATION_FLUSH,super(t,e)}},ow=class extends tf{constructor(t){super(t,"BrotliCompress")}},aw=class extends tf{constructor(t){super(t,"BrotliDecompress")}},nf=class extends Mc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Pt.ZSTD_e_end,t.fullFlushFlag=Pt.ZSTD_e_flush,super(t,e)}},cw=class extends nf{constructor(t){super(t,"ZstdCompress")}},lw=class extends nf{constructor(t){super(t,"ZstdDecompress")}},dw=(t,e)=>{if(Number.isSafeInteger(t))t<0?fw(t,e):uw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},uw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},fw=(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]=rf(o):o===0?e[i-1]=0:(r=!0,e[i-1]=sf(o))}},xw=t=>{let e=t[0],r=e===128?pw(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]),l;i?l=rf(c):c===0?l=c:(i=!0,l=sf(c)),l!==0&&(r-=l*Math.pow(256,e-o-1))}return r},pw=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},rf=t=>(255^t)&255,sf=t=>(255^t)+1&255,gw={};Rm(gw,{code:()=>Bc,isCode:()=>qs,isName:()=>mw,name:()=>io,normalFsTypes:()=>of});var qs=t=>io.has(t),mw=t=>Bc.has(t),of=new Set(["0","","1","2","3","4","5","6","7","D"]),io=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Bc=new Map(Array.from(io).map(t=>[t[1],t[0]])),jn=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=Nn(t,e+156,1),c=of.has(o),l=c?r:void 0,u=c?i:void 0;if(this.path=l?.path??Nn(t,e,100),this.mode=l?.mode??u?.mode??gn(t,e+100,8),this.uid=l?.uid??u?.uid??gn(t,e+108,8),this.gid=l?.gid??u?.gid??gn(t,e+116,8),this.size=l?.size??u?.size??gn(t,e+124,12),this.mtime=l?.mtime??u?.mtime??Xa(t,e+136,12),this.cksum=gn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),qs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Nn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=l?.uname??u?.uname??Nn(t,e+265,32),this.gname=l?.gname??u?.gname??Nn(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??gn(t,e+329,8)??0,this.devmin=l?.devmin??u?.devmin??gn(t,e+337,8)??0,t[e+475]!==0){let h=Nn(t,e+345,155);this.path=h+"/"+this.path}else{let h=Nn(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=r?.atime??i?.atime??Xa(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Xa(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=Mn(t,e,100,o)||this.needPax,this.needPax=mn(t,e+100,8,this.mode)||this.needPax,this.needPax=mn(t,e+108,8,this.uid)||this.needPax,this.needPax=mn(t,e+116,8,this.gid)||this.needPax,this.needPax=mn(t,e+124,12,this.size)||this.needPax,this.needPax=Qa(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Mn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Mn(t,e+265,32,this.uname)||this.needPax,this.needPax=Mn(t,e+297,32,this.gname)||this.needPax,this.needPax=mn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=mn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Mn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Mn(t,e+345,155,c)||this.needPax:(this.needPax=Mn(t,e+345,130,c)||this.needPax,this.needPax=Qa(t,e+476,12,this.atime)||this.needPax,this.needPax=Qa(t,e+488,12,this.ctime)||this.needPax);let l=256;for(let u=e;u<e+148;u++)l+=t[u];for(let u=e+156;u<e+512;u++)l+=t[u];return this.cksum=l,mn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:io.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Bc.get(t));if(qs(e)||e==="Unsupported")this.#e=e;else if(qs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},ww=(t,e)=>{let r=t,i="",o,c=gr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=gr.dirname(r),r=gr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=gr.join(gr.basename(i),r),i=gr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Nn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Xa=(t,e,r)=>_w(gn(t,e,r)),_w=t=>t===void 0?void 0:new Date(t*1e3),gn=(t,e,r)=>Number(t[e])&128?xw(t.subarray(e,e+r)):bw(t,e,r),yw=t=>isNaN(t)?void 0:t,bw=(t,e,r)=>yw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Ew={12:8589934591,8:2097151},mn=(t,e,r,i)=>i===void 0?!1:i>Ew[r]||i<0?(dw(i,t.subarray(e,e+r)),!0):(vw(t,e,r,i),!1),vw=(t,e,r,i)=>t.write(Sw(i,r),e,r,"ascii"),Sw=(t,e)=>Iw(Math.floor(t).toString(8),e),Iw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Qa=(t,e,r,i)=>i===void 0?!1:mn(t,e,r,i.getTime()/1e3),Aw=new Array(156).join("\0"),Mn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Aw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),Xs=class af{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 jn({path:("PaxHeader/"+Tw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,r,i=!1){return new af(kw(Rw(e),r),i)}},kw=(t,e)=>e?Object.assign({},e,t):t,Rw=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(Cw,Object.create(null)),Cw=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},Dw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,X=Dw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Pw=class extends Wn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=X(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?X(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=X(t.path)),t.linkpath&&(t.linkpath=X(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},so=(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))},Lw=1024*1024,pc=Buffer.from([31,139]),gc=Buffer.from([40,181,47,253]),Ow=Math.max(pc.length,gc.length),dt=Symbol("state"),Bn=Symbol("writeEntry"),qt=Symbol("readEntry"),ec=Symbol("nextEntry"),Eu=Symbol("processEntry"),Rt=Symbol("extendedHeader"),wi=Symbol("globalExtendedHeader"),un=Symbol("meta"),vu=Symbol("emitMeta"),me=Symbol("buffer"),jt=Symbol("queue"),fn=Symbol("ended"),tc=Symbol("emittedEnd"),zn=Symbol("emit"),Re=Symbol("unzip"),Ls=Symbol("consumeChunk"),Os=Symbol("consumeChunkSub"),nc=Symbol("consumeBody"),Su=Symbol("consumeMeta"),Iu=Symbol("consumeHeader"),_i=Symbol("consuming"),rc=Symbol("bufferConcat"),Ns=Symbol("maybeEnd"),mr=Symbol("writing"),xn=Symbol("aborted"),Ms=Symbol("onDone"),Fn=Symbol("sawValidEntry"),Bs=Symbol("sawNullBlock"),zs=Symbol("sawEOF"),Au=Symbol("closeStream"),Nw=()=>!0,Ni=class extends Qm{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[jt]=[];[me];[qt];[Bn];[dt]="begin";[un]="";[Rt];[wi];[fn]=!1;[Re];[xn]=!1;[Fn];[Bs]=!1;[zs]=!1;[mr]=!1;[_i]=!1;[tc]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ms,()=>{(this[dt]==="begin"||this[Fn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ms,t.ondone):this.on(Ms,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Lw,this.filter=typeof t.filter=="function"?t.filter:Nw;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[Au]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){so(this,t,e,r)}[Iu](t,e){this[Fn]===void 0&&(this[Fn]=!1);let r;try{r=new jn(t,e,this[Rt],this[wi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Bs]?(this[zs]=!0,this[dt]==="begin"&&(this[dt]="header"),this[zn]("eof")):(this[Bs]=!0,this[zn]("nullBlock"));else if(this[Bs]=!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[Bn]=new Pw(r,this[Rt],this[wi]);if(!this[Fn])if(o.remain){let c=()=>{o.invalid||(this[Fn]=!0)};o.on("end",c)}else this[Fn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[zn]("ignoredEntry",o),this[dt]="ignore",o.resume()):o.size>0&&(this[un]="",o.on("data",c=>this[un]+=c),this[dt]="meta"):(this[Rt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[zn]("ignoredEntry",o),this[dt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[dt]="body":(this[dt]="header",o.end()),this[qt]?this[jt].push(o):(this[jt].push(o),this[ec]())))}}}[Au](){queueMicrotask(()=>this.emit("close"))}[Eu](t){let e=!0;if(!t)this[qt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[qt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ec]()),e=!1);return e}[ec](){do;while(this[Eu](this[jt].shift()));if(this[jt].length===0){let t=this[qt];!t||t.flowing||t.size===t.remain?this[mr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[nc](t,e){let r=this[Bn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[dt]="header",this[Bn]=void 0,r.end()),o.length}[Su](t,e){let r=this[Bn],i=this[nc](t,e);return!this[Bn]&&r&&this[vu](r),i}[zn](t,e,r){this[jt].length===0&&!this[qt]?this.emit(t,e,r):this[jt].push([t,e,r])}[vu](t){switch(this[zn]("meta",this[un]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Rt]=Xs.parse(this[un],this[Rt],!1);break;case"GlobalExtendedHeader":this[wi]=Xs.parse(this[un],this[wi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Rt]??Object.create(null);this[Rt]=e,e.path=this[un].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Rt]||Object.create(null);this[Rt]=e,e.linkpath=this[un].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[xn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[xn])return r?.(),!1;if((this[Re]===void 0||this.brotli===void 0&&this[Re]===!1)&&t){if(this[me]&&(t=Buffer.concat([this[me],t]),this[me]=void 0),t.length<Ow)return this[me]=t,r?.(),!0;for(let l=0;this[Re]===void 0&&l<pc.length;l++)t[l]!==pc[l]&&(this[Re]=!1);let o=!1;if(this[Re]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<gc.length;l++)if(t[l]!==gc[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Re]===!1&&c)if(t.length<512)if(this[fn])this.brotli=!0;else return this[me]=t,r?.(),!0;else try{new jn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Re]===void 0||this[Re]===!1&&(this.brotli||o)){let l=this[fn];this[fn]=!1,this[Re]=this[Re]===void 0?new sw({}):o?new lw({}):new aw({}),this[Re].on("data",x=>this[Ls](x)),this[Re].on("error",x=>this.abort(x)),this[Re].on("end",()=>{this[fn]=!0,this[Ls]()}),this[mr]=!0;let u=!!this[Re][l?"end":"write"](t);return this[mr]=!1,r?.(),u}}this[mr]=!0,this[Re]?this[Re].write(t):this[Ls](t),this[mr]=!1;let i=this[jt].length>0?!1:this[qt]?this[qt].flowing:!0;return!i&&this[jt].length===0&&this[qt]?.once("drain",()=>this.emit("drain")),r?.(),i}[rc](t){t&&!this[xn]&&(this[me]=this[me]?Buffer.concat([this[me],t]):t)}[Ns](){if(this[fn]&&!this[tc]&&!this[xn]&&!this[_i]){this[tc]=!0;let t=this[Bn];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](Ms)}}[Ls](t){if(this[_i]&&t)this[rc](t);else if(!t&&!this[me])this[Ns]();else if(t){if(this[_i]=!0,this[me]){this[rc](t);let e=this[me];this[me]=void 0,this[Os](e)}else this[Os](t);for(;this[me]&&this[me]?.length>=512&&!this[xn]&&!this[zs];){let e=this[me];this[me]=void 0,this[Os](e)}this[_i]=!1}(!this[me]||this[fn])&&this[Ns]()}[Os](t){let e=0,r=t.length;for(;e+512<=r&&!this[xn]&&!this[zs];)switch(this[dt]){case"begin":case"header":this[Iu](t,e),e+=512;break;case"ignore":case"body":e+=this[nc](t,e);break;case"meta":e+=this[Su](t,e);break;default:throw new Error("invalid state: "+this[dt])}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[xn]||(this[Re]?(t&&this[Re].write(t),this[Re].end()):(this[fn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ns]())),this}},ki=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)},Mw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},cf=(t,e)=>{let r=new Map(e.map(c=>[ki(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||Wm(c).root||".",x;if(c===u)x=!1;else{let h=r.get(c);x=h!==void 0?h:o(jm(c),u)}return r.set(c,x),x};t.filter=i?(c,l)=>i(c,l)&&o(ki(c)):c=>o(ki(c))},Bw=t=>{let e=new Ni(t),r=t.file,i;try{i=vr.openSync(r,"r");let o=vr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=vr.readSync(i,l,0,o.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<o.size;){let x=vr.readSync(i,u,0,c,l);if(x===0)break;l+=x,e.write(u.subarray(0,x))}e.end()}}finally{if(typeof i=="number")try{vr.closeSync(i)}catch{}}},zw=(t,e)=>{let r=new Ni(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),vr.stat(o,(u,x)=>{if(u)l(u);else{let h=new Oc(o,{readSize:i,size:x.size});h.on("error",l),h.pipe(r)}})})},Tr=Mi(Bw,zw,t=>new Ni(t),t=>new Ni(t),(t,e)=>{e?.length&&cf(t,e),t.noResume||Mw(t)}),lf=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:Uw,parse:ku}=Fw,zc=t=>{let e="",r=ku(t);for(;Uw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=ku(t)}return[e,t]},oo=["|","<",">","?",":"],Fc=oo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Gw=new Map(oo.map((t,e)=>[t,Fc[e]])),Hw=new Map(Fc.map((t,e)=>[t,oo[e]])),Ru=t=>oo.reduce((e,r)=>e.split(r).join(Gw.get(r)),t),qw=t=>Fc.reduce((e,r)=>e.split(r).join(Hw.get(r)),t),df=(t,e)=>e?(t=X(t).replace(/^\.(\/|$)/,""),ki(e)+"/"+t):X(t),jw=16*1024*1024,Cu=Symbol("process"),Du=Symbol("file"),Pu=Symbol("directory"),mc=Symbol("symlink"),Lu=Symbol("hardlink"),yi=Symbol("header"),js=Symbol("read"),wc=Symbol("lstat"),Ws=Symbol("onlstat"),_c=Symbol("onread"),yc=Symbol("onreadlink"),bc=Symbol("openfile"),Ec=Symbol("onopenfile"),wn=Symbol("close"),eo=Symbol("mode"),vc=Symbol("awaitDrain"),ic=Symbol("ondrain"),Dt=Symbol("prefix"),uf=class extends Wn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Nc(e);super(),this.path=X(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||jw,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=X(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?X(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,l]=zc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=qw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=X(r.absolute||Tu.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[Ws](o):this[wc]()}warn(t,e,r={}){return so(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[wc](){Ct.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Ws](e)})}[Ws](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=$w(t),this.emit("stat",t),this[Cu]()}[Cu](){switch(this.type){case"File":return this[Du]();case"Directory":return this[Pu]();case"SymbolicLink":return this[mc]();default:return this.end()}}[eo](t){return lf(t,this.type==="Directory",this.portable)}[Dt](t){return df(t,this.prefix)}[yi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new jn({path:this[Dt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Dt](this.linkpath):this.linkpath,mode:this[eo](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Xs({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[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)}[Pu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[yi](),this.end()}[mc](){Ct.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[yc](e)})}[yc](t){this.linkpath=X(t),this[yi](),this.end()}[Lu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=X(Tu.relative(this.cwd,t)),this.stat.size=0,this[yi](),this.end()}[Du](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[Lu](e);this.linkCache.set(t,this.absolute)}if(this[yi](),this.stat.size===0)return this.end();this[bc]()}[bc](){Ct.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ec](e)})}[Ec](t){if(this.fd=t,this.#e)return this[wn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[js]()}[js](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Ct.read(t,e,r,i,o,(c,l)=>{if(c)return this[wn](()=>this.emit("error",c));this[_c](l)})}[wn](t=()=>{}){this.fd!==void 0&&Ct.close(this.fd,t)}[_c](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[wn](()=>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[wn](()=>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[ic]():this[vc](()=>this[ic]())}[vc](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)}[ic](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[wn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[js]()}},Ww=class extends uf{sync=!0;[wc](){this[Ws](Ct.lstatSync(this.absolute))}[mc](){this[yc](Ct.readlinkSync(this.absolute))}[bc](){this[Ec](Ct.openSync(this.absolute,"r"))}[js](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let l=Ct.readSync(e,r,i,o,c);this[_c](l),t=!1}finally{if(t)try{this[wn](()=>{})}catch{}}}[vc](t){t()}[wn](t=()=>{}){this.fd!==void 0&&Ct.closeSync(this.fd),t()}},Kw=class extends Wn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return so(this,t,e,r)}constructor(t,e={}){let r=Nc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=X(t.path),this.mode=t.mode!==void 0?this[eo](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?X(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[l,u]=zc(this.path);l&&typeof u=="string"&&(this.path=u,o=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new jn({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 Xs({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[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 df(t,this.prefix)}[eo](t){return lf(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},$w=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",Vw=class Sr{tail;head;length=0;static create(e=[]){return new Sr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)Yw(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)Zw(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new Sr;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new Sr;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Sr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new Sr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let l=0;o&&l<e;l++)o=o.next;let c=[];for(let l=0;o&&l<r;l++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let l of i)o=Jw(this,o,l);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function Jw(t,e,r){let i=e,o=e?e.next:t.head,c=new Uc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Yw(t,e){t.tail=new Uc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Zw(t,e){t.head=new Uc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Uc=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}},Nu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Mu=Buffer.alloc(1024),Ks=Symbol("onStat"),bi=Symbol("ended"),wt=Symbol("queue"),Ei=Symbol("pendingLinks"),hn=Symbol("current"),Un=Symbol("process"),vi=Symbol("processing"),Fs=Symbol("processJob"),_t=Symbol("jobs"),sc=Symbol("jobDone"),$s=Symbol("addFSEntry"),Bu=Symbol("addTarEntry"),Sc=Symbol("stat"),Ic=Symbol("readdir"),Vs=Symbol("onreaddir"),Js=Symbol("pipe"),zu=Symbol("entry"),oc=Symbol("entryOpt"),Ys=Symbol("writeEntryClass"),ff=Symbol("write"),ac=Symbol("ondrain"),ao=class extends Wn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Ys];onWriteEntry;[wt];[Ei]=new Map;[_t]=0;[vi]=!1;[bi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=X(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Ys]=uf,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 iw(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 cw(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[ac]()),this.on("resume",()=>e.resume())}else this.on("drain",this[ac]);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[wt]=new Vw,this[_t]=0,this.jobs=Number(t.jobs)||4,this[vi]=!1,this[bi]=!1}[ff](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[bi]=!0,this[Un](),r&&r(),this}write(t){if(this[bi])throw new Error("write after end");return typeof t=="string"?this[$s](t):this[Bu](t),this.flowing}[Bu](t){let e=X(Ou.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Nu(t.path,e);r.entry=new Kw(t,this[oc](r)),r.entry.on("end",()=>this[sc](r)),this[_t]+=1,this[wt].push(r)}this[Un]()}[$s](t){let e=X(Ou.resolve(this.cwd,t));this[wt].push(new Nu(t,e)),this[Un]()}[Sc](t){t.pending=!0,this[_t]+=1;let e=this.follow?"stat":"lstat";Qs[e](t.absolute,(r,i)=>{t.pending=!1,this[_t]-=1,r?this.emit("error",r):this[Ks](t,i)})}[Ks](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[hn])this[Fs](t);else{let r=`${e.dev}:${e.ino}`,i=this[Ei].get(r);i?i.push(t):this[Ei].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[Un]()}[Ic](t){t.pending=!0,this[_t]+=1,Qs.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[_t]-=1,e)return this.emit("error",e);this[Vs](t,r)})}[Vs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Un]()}[Un](){if(!this[vi]){this[vi]=!0;for(let t=this[wt].head;t&&this[_t]<this.jobs;t=t.next)if(this[Fs](t.value),t.value.ignore){let e=t.next;this[wt].removeNode(t),t.next=e}this[vi]=!1,this[bi]&&this[wt].length===0&&this[_t]===0&&(this.zip?this.zip.end(Mu):(super.write(Mu),super.end()))}}get[hn](){return this[wt]&&this[wt].head&&this[wt].head.value}[sc](t){this[wt].shift(),this[_t]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[Ei].get(r);if(i){this[Ei].delete(r);for(let o of i)o.pending=!1,this[Fs](o)}}this[Un]()}[Fs](t){if(t.pending&&t.pendingLink&&t===this[hn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[hn]&&!t.piped&&this[Js](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ks](t,e):this[Sc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Vs](t,e):this[Ic](t),!t.readdir)return}if(t.entry=this[zu](t),!t.entry){t.ignore=!0;return}t===this[hn]&&!t.piped&&this[Js](t)}}}[oc](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[zu](t){this[_t]+=1;try{return new this[Ys](t.path,this[oc](t)).on("end",()=>this[sc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[ac](){this[hn]&&this[hn].entry&&this[hn].entry.resume()}[Js](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[$s](c+i)});let e=t.entry,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={}){so(this,t,e,r)}},Gc=class extends ao{sync=!0;constructor(t){super(t),this[Ys]=Ww}pause(){}resume(){}[Sc](t){let e=this.follow?"statSync":"lstatSync";this[Ks](t,Qs[e](t.absolute))}[Ic](t){this[Vs](t,Qs.readdirSync(t.absolute))}[Js](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[$s](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[ff](i)})}},Xw=(t,e)=>{let r=new Gc(t),i=new Xu(t.file,{mode:t.mode||438});r.pipe(i),xf(r,e)},Qw=(t,e)=>{let r=new ao(t),i=new ro(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,l)=>{i.on("error",l),i.on("close",c),r.on("error",l)});return hf(r,e).catch(c=>r.emit("error",c)),o},xf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Tr({file:Qu.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},hf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Tr({file:Qu.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},e_=(t,e)=>{let r=new Gc(t);return xf(r,e),r},t_=(t,e)=>{let r=new ao(t);return hf(r,e).catch(i=>r.emit("error",i)),r},kI=Mi(Xw,Qw,e_,t_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),r_=process.env.__FAKE_PLATFORM__||process.platform,wf=r_==="win32",{O_CREAT:_f,O_NOFOLLOW:Fu,O_TRUNC:yf,O_WRONLY:bf}=mf.constants,Ef=Number(process.env.__FAKE_FS_O_FILENAME__)||mf.constants.UV_FS_O_FILEMAP||0,i_=wf&&!!Ef,s_=512*1024,o_=Ef|yf|_f|bf,Uu=!wf&&typeof Fu=="number"?Fu|yf|_f|bf:null,vf=Uu!==null?()=>Uu:i_?t=>t<s_?o_:"w":()=>"w",Ac=(t,e,r)=>{try{return co.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},to=(t,e,r,i)=>{co.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},a_=(t,e,r,i,o)=>{if(e.isDirectory())Sf(Ri.resolve(t,e.name),r,i,c=>{if(c)return o(c);let l=Ri.resolve(t,e.name);to(l,r,i,o)});else{let c=Ri.resolve(t,e.name);to(c,r,i,o)}},Sf=(t,e,r,i)=>{co.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return to(t,e,r,i);let l=c.length,u=null,x=h=>{if(!u){if(h)return i(u=h);if(--l===0)return to(t,e,r,i)}};for(let h of c)a_(t,h,e,r,x)})},c_=(t,e,r,i)=>{e.isDirectory()&&If(Ri.resolve(t,e.name),r,i),Ac(Ri.resolve(t,e.name),r,i)},If=(t,e,r)=>{let i;try{i=co.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Ac(t,e,r);throw c}for(let o of i)c_(t,o,e,r);return Ac(t,e,r)},Af=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},lo=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},d_=(t,e)=>{ot.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new Af(t,r?.code||"ENOTDIR")),e(r)})},u_=(t,e,r)=>{t=X(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,x=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),h=e.preserve,m=e.unlink,w=X(e.cwd),S=(v,I)=>{v?r(v):I&&x?Sf(I,l,u,T=>S(T)):c?ot.chmod(t,o,r):r()};if(t===w)return d_(t,S);if(h)return l_.mkdir(t,{mode:o,recursive:!0}).then(v=>S(null,v??void 0),S);let _=X(no.relative(w,t)).split("/");Tc(w,_,o,m,w,void 0,S)},Tc=(t,e,r,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),x=X(no.resolve(t+"/"+u));ot.mkdir(x,r,Tf(x,e,r,i,o,c,l))},Tf=(t,e,r,i,o,c,l)=>u=>{u?ot.lstat(t,(x,h)=>{if(x)x.path=x.path&&X(x.path),l(x);else if(h.isDirectory())Tc(t,e,r,i,o,c,l);else if(i)ot.unlink(t,m=>{if(m)return l(m);ot.mkdir(t,r,Tf(t,e,r,i,o,c,l))});else{if(h.isSymbolicLink())return l(new lo(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,Tc(t,e,r,i,o,c,l))},f_=t=>{let e=!1,r;try{e=ot.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new Af(t,r??"ENOTDIR")}},x_=(t,e)=>{t=X(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),x=e.preserve,h=e.unlink,m=X(e.cwd),w=v=>{v&&u&&If(v,c,l),o&&ot.chmodSync(t,i)};if(t===m)return f_(m),w();if(x)return w(ot.mkdirSync(t,{mode:i,recursive:!0})??void 0);let S=X(no.relative(m,t)).split("/"),_;for(let v=S.shift(),I=m;v&&(I+="/"+v);v=S.shift()){I=X(no.resolve(I));try{ot.mkdirSync(I,i),_=_||I}catch{let T=ot.lstatSync(I);if(T.isDirectory())continue;if(h){ot.unlinkSync(I),ot.mkdirSync(I,i),_=_||I;continue}else if(T.isSymbolicLink())return new lo(I,I+"/"+S.join("/"))}}return w(_)},cc=Object.create(null),Gu=1e4,wr=new Set,h_=t=>{wr.has(t)?wr.delete(t):cc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),wr.add(t);let e=cc[t],r=wr.size-Gu;if(r>Gu/10){for(let i of wr)if(wr.delete(i),delete cc[i],--r<=0)break}return e},p_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,g_=p_==="win32",m_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=kf(i,r)),e.push(r||"/"),e},[]),w_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=g_?["win32 parallelization disabled"]:t.map(i=>ki(kf(h_(i))));let r=new Set(t.map(i=>m_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")o.add(u);else for(let x of u)o.add(x)}for(let c of i){let l=this.#e.get(c),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(c);continue}else if(u.size===1){l.shift();let x=l[0];typeof x=="function"&&o.add(x)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},__=()=>process.umask(),Hu=Symbol("onEntry"),kc=Symbol("checkFs"),qu=Symbol("checkFs2"),Rc=Symbol("isReusable"),ut=Symbol("makeFs"),Cc=Symbol("file"),Dc=Symbol("directory"),Zs=Symbol("link"),ju=Symbol("symlink"),Wu=Symbol("hardlink"),Ai=Symbol("ensureNoSymlink"),Ku=Symbol("unsupported"),$u=Symbol("checkPath"),lc=Symbol("stripAbsolutePath"),_n=Symbol("mkdir"),Ge=Symbol("onError"),Us=Symbol("pending"),Vu=Symbol("pend"),_r=Symbol("unpend"),dc=Symbol("ended"),uc=Symbol("maybeClose"),Pc=Symbol("skip"),Ci=Symbol("doChown"),Di=Symbol("uid"),Pi=Symbol("gid"),Li=Symbol("checkedCwd"),y_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Oi=y_==="win32",b_=1024,E_=(t,e)=>{if(!Oi)return ie.unlink(t,e);let r=t+".DELETE."+gf(16).toString("hex");ie.rename(t,r,i=>{if(i)return e(i);ie.unlink(r,e)})},v_=t=>{if(!Oi)return ie.unlinkSync(t);let e=t+".DELETE."+gf(16).toString("hex");ie.renameSync(t,e),ie.unlinkSync(e)},Ju=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Hc=class extends Ni{[dc]=!1;[Li]=!1;[Us]=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[dc]=!0,this[uc]()},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:b_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Oi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=X(Ne.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:__():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Hu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[uc](){this[dc]&&this[Us]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[lc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=zc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Oi&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Ne.posix.dirname(t.path),x=Ne.posix.normalize(Ne.posix.join(u,l.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}[$u](t){let e=X(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=X(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[lc](t,"path")||!this[lc](t,"linkpath"))return!1;if(t.absolute=Ne.isAbsolute(t.path)?X(Ne.resolve(t.path)):X(Ne.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:X(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Ne.win32.parse(String(t.absolute));t.absolute=i+Ru(String(t.absolute).slice(i.length));let{root:o}=Ne.win32.parse(t.path);t.path=o+Ru(t.path.slice(o.length))}return!0}[Hu](t){if(!this[$u](t))return t.resume();switch(n_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[kc](t);default:return this[Ku](t)}}[Ge](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[_r](),e.resume())}[_n](t,e,r){u_(X(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ci](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Di](t){return Ju(this.uid,t.uid,this.processUid)}[Pi](t){return Ju(this.gid,t.gid,this.processGid)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new ro(String(t.absolute),{flags:vf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&ie.close(i.fd,()=>{}),i.write=()=>!0,this[Ge](u,t),e()});let o=1,c=u=>{if(u){i.fd&&ie.close(i.fd,()=>{}),this[Ge](u,t),e();return}--o===0&&i.fd!==void 0&&ie.close(i.fd,x=>{x?this[Ge](x,t):this[_r](),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,S=>c(S&&w)):c())}if(typeof x=="number"&&this[Ci](t)){o++;let h=this[Di](t),m=this[Pi](t);typeof h=="number"&&typeof m=="number"&&ie.fchown(x,h,m,w=>w?ie.chown(u,h,m,S=>c(S&&w)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[Ge](u,t),e()}),t.pipe(l)),l.pipe(i)}[Dc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[_n](String(t.absolute),r,i=>{if(i){this[Ge](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[_r](),t.resume())};t.mtime&&!this.noMtime&&(o++,ie.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ci](t)&&(o++,ie.chown(String(t.absolute),Number(this[Di](t)),Number(this[Pi](t)),c)),c()})}[Ku](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[ju](t,e){let r=X(Ne.relative(this.cwd,Ne.resolve(Ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ai](t,this.cwd,r,()=>this[Zs](t,String(t.linkpath),"symlink",e),i=>{this[Ge](i,t),e()})}[Wu](t,e){let r=X(Ne.resolve(this.cwd,String(t.linkpath))),i=X(String(t.linkpath)).split("/");this[Ai](t,this.cwd,i,()=>this[Zs](t,r,"link",e),o=>{this[Ge](o,t),e()})}[Ai](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Ne.resolve(e,c);ie.lstat(l,(u,x)=>{if(u)return i();if(x?.isSymbolicLink())return o(new lo(l,Ne.resolve(l,r.join("/"))));this[Ai](t,l,r,i,o)})}[Vu](){this[Us]++}[_r](){this[Us]--,this[uc]()}[Pc](t){this[_r](),t.resume()}[Rc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Oi}[kc](t){this[Vu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[qu](t,r))}[qu](t,e){let r=l=>{e(l)},i=()=>{this[_n](this.cwd,this.dmode,l=>{if(l){this[Ge](l,t),r();return}this[Li]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=X(Ne.dirname(String(t.absolute)));if(l!==this.cwd)return this[_n](l,this.dmode,u=>{if(u){this[Ge](u,t),r();return}c()})}c()},c=()=>{ie.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Pc](t),r();return}if(l||this[Rc](t,u))return this[ut](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let x=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=m=>this[ut](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[ut](x??null,t,r))}if(t.absolute===this.cwd)return this[ut](null,t,r);E_(String(t.absolute),x=>this[ut](x??null,t,r))})};this[Li]?o():i()}[ut](t,e,r){if(t){this[Ge](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Cc](e,r);case"Link":return this[Wu](e,r);case"SymbolicLink":return this[ju](e,r);case"Directory":case"GNUDumpDir":return this[Dc](e,r)}}[Zs](t,e,r,i){ie[r](e,String(t.absolute),o=>{o?this[Ge](o,t):(this[_r](),t.resume()),i()})}},Si=t=>{try{return[null,t()]}catch(e){return[e,null]}},Rf=class extends Hc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[kc](t){if(!this[Li]){let o=this[_n](this.cwd,this.dmode);if(o)return this[Ge](o,t);this[Li]=!0}if(t.absolute!==this.cwd){let o=X(Ne.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[_n](o,this.dmode);if(c)return this[Ge](c,t)}}let[e,r]=Si(()=>ie.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Pc](t);if(e||this[Rc](t,r))return this[ut](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?Si(()=>{ie.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](l,t)}let[o]=Si(()=>ie.rmdirSync(String(t.absolute)));this[ut](o,t)}let[i]=t.absolute===this.cwd?[]:Si(()=>v_(String(t.absolute)));this[ut](i,t)}[Cc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{ie.closeSync(o)}catch(x){u=x}(l||u)&&this[Ge](l||u,t),e()},o;try{o=ie.openSync(String(t.absolute),vf(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[Ge](l,t)),t.pipe(c)),c.on("data",l=>{try{ie.writeSync(o,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,x=t.mtime;try{ie.futimesSync(o,u,x)}catch(h){try{ie.utimesSync(String(t.absolute),u,x)}catch{l=h}}}if(this[Ci](t)){let u=this[Di](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{l=l||h}}}i(l)})}[Dc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[_n](String(t.absolute),r);if(i){this[Ge](i,t),e();return}if(t.mtime&&!this.noMtime)try{ie.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ci](t))try{ie.chownSync(String(t.absolute),Number(this[Di](t)),Number(this[Pi](t)))}catch{}e(),t.resume()}[_n](t,e){try{return x_(X(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[Ai](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Ne.resolve(c,l);let[u,x]=Si(()=>ie.lstatSync(c));if(u)return i();if(x.isSymbolicLink())return o(new lo(c,Ne.resolve(e,r.join("/"))))}i()}[Zs](t,e,r,i){let o=`${r}Sync`;try{ie[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ge](c,t)}}},S_=t=>{let e=new Rf(t),r=t.file,i=pf.statSync(r),o=t.maxReadSize||16*1024*1024;new qm(r,{readSize:o,size:i.size}).pipe(e)},I_=(t,e)=>{let r=new Hc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),pf.stat(o,(u,x)=>{if(u)l(u);else{let h=new Oc(o,{readSize:i,size:x.size});h.on("error",l),h.pipe(r)}})})},Cf=Mi(S_,I_,t=>new Rf(t),t=>new Hc(t),(t,e)=>{e?.length&&cf(t,e)}),A_=(t,e)=>{let r=new Gc(t),i=!0,o,c;try{try{o=st.openSync(t.file,"r+")}catch(x){if(x?.code==="ENOENT")o=st.openSync(t.file,"w+");else throw x}let l=st.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let m=0,w=0;m<512;m+=w){if(w=st.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 jn(u);if(!x.cksumValid)break;let h=512*Math.ceil((x.size||0)/512);if(c+h+512>l.size)break;c+=h,t.mtimeCache&&x.mtime&&t.mtimeCache.set(String(x.path),x.mtime)}i=!1,T_(t,r,c,o,e)}finally{if(i)try{st.closeSync(o)}catch{}}},T_=(t,e,r,i,o)=>{let c=new Xu(t.file,{fd:i,start:r});e.pipe(c),R_(e,o)},k_=(t,e)=>{e=Array.from(e);let r=new ao(t),i=(o,c,l)=>{let u=(S,_)=>{S?st.close(o,v=>l(S)):l(null,_)},x=0;if(c===0)return u(null,0);let h=0,m=Buffer.alloc(512),w=(S,_)=>{if(S||_===void 0)return u(S);if(h+=_,h<512&&_)return st.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 v=new jn(m);if(!v.cksumValid)return u(null,x);let I=512*Math.ceil((v.size??0)/512);if(x+I+512>c||(x+=I+512,x>=c))return u(null,x);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),h=0,st.read(o,m,0,512,x,w)};st.read(o,m,0,512,x,w)};return new Promise((o,c)=>{r.on("error",c);let l="r+",u=(x,h)=>{if(x&&x.code==="ENOENT"&&l==="r+")return l="w+",st.open(t.file,l,u);if(x||!h)return c(x);st.fstat(h,(m,w)=>{if(m)return st.close(h,()=>c(m));i(h,w.size,(S,_)=>{if(S)return c(S);let v=new ro(t.file,{fd:h,start:_});r.pipe(v),v.on("error",c),v.on("close",o),C_(r,e)})})};st.open(t.file,l,u)})},R_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Tr({file:Df.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},C_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Tr({file:Df.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},Ii=Mi(A_,k_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Zm(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")}),qI=Mi(Ii.syncFile,Ii.asyncFile,Ii.syncNoFile,Ii.asyncNoFile,(t,e=[])=>{Ii.validate?.(t,e),D_(t)}),D_=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))};cn();var ft={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function uo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Pf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function fo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Lf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Of(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Kn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}$t();je();ne();Le();je();function kr(t,e){if(uo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Bi(t){return t.startsWith("http://")||t.startsWith("https://")}function Rr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as OA}from"node:fs";import{dirname as MA,join as BA}from"node:path";import{fileURLToPath as FA}from"node:url";var Lt="0.2.0-beta.3";je();ne();var xo="1008033",zf="1289";var Ff="pbbp2",Uf="https://www.coze.cn",Gf="/api/coze_claw/resource/get_frontier_key",F_="https://www.coze.cn",U_="wss://frontier.coze.cn";function Cr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??F_}function Hf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??U_}function En(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 Fi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var zi=H("handshake");async function qc(t){let e=Cr(t.endpoint),r=t.timeoutMs??1e4,i=`${Rr(e)}${Gf}?aid=${encodeURIComponent(xo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...En(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),r);zi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),x=u.headers.get("x-tt-logid")??"",h=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let v=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${x}: ${v.slice(0,200)}`)}let m=await u.json();if(m.code!==void 0&&m.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${m.code} msg=${m.msg??"-"} logid=${x}`);let w=m.data??{},S=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!S||!_){let v=JSON.stringify(m).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${x}: ${v}`)}return zi.info("handshake ok",{remoteDeviceId:_,logid:x,traceId:h}),{accessKey:S,deviceId:_}}catch(u){if(u instanceof k)throw zi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw zi.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let x=u.cause;throw zi.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 k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var jc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Et="auto",qf=15e4;function jf(t){return{model:Wc(t.model)??Et,...t.modelToken?{modelToken:t.modelToken}:{}}}function G_(t){return!t||t===Et}var H_=new Set(["auto","\u81EA\u52A8"]);function Wc(t){let e=t?.trim();if(e)return H_.has(e.toLowerCase())?Et:e}function Wf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=jc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Et;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else G_(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Kf(t,e,r){return t.modelToken?{baseUrl:`${jc}/v1`,providerName:"coze",headers:{Authorization:`Bearer ${t.modelToken}`,...Kc(e,r)}}:null}function $f(t){if(!t.modelToken)return{};let e={model:t.model||Et,model_context_window:t.modelInfo?.contextWindow??qf};return{CODEX_CONFIG:JSON.stringify(e)}}function Kc(t,e){let{ttEnv:r,usePpe:i}=Fi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Vf(t,e,r){if(!t.modelToken)return{};let i=Kc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
92
+ `)}}function $c(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Jf(t,e,r){if(!t.modelToken)return null;let i=t.model||Et,o=Kc(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let l={baseUrl:`${jc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:i,name:i,reasoning:!1,input:c,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??qf,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(l.headers=o),l}var he=H("agent-handlers"),Zf=5*1024*1024,K_=1,$_=6,V_=new Set(["node_modules",".git",".coze","dist","build",".next"]),J_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Y_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Z_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function X_(t){let e=t?.trim();return e?Z_.test(e)||Y_.test(e)?e:(he.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Q_(t){return new Promise((e,r)=>{let i=rt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=l=>{o||(o=!0,l?r(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}var po=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=Kn(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ve(r).workspace,c=i?.skills??[],l=[],u=new Set;for(let x of c){let h=Ke(o,x.relPath,"SKILL.md");await Yf(h).then(w=>w.isFile()).catch(()=>!1)&&(l.push(ry(x)),u.add(x.relPath))}if(e.scanLocal){let x=i?.framework??"claude-code",h=await ey(r,o,x);for(let m of h)u.has(m.relPath)||(u.add(m.relPath),l.push(m.skill))}return{skills:l}}async addSkills(e){e._meta;let r=Kn(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((x,h)=>[x.skillId,h])),u=[];for(let x of o){let h=await go({agentId:r,workspace:i.workspace,framework:i.framework,skill:x});mo(c,l,h),u.push(x)}return await di(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=Kn(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],l=[];for(let u of c){if(!o.has(u.skillId)){l.push(u);continue}let x=Ke(i.workspace,u.relPath);await Yc(x,{recursive:!0,force:!0}),he.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await di(r,l),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=Kn(e._meta);if(!e.skillName)throw new k("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??Ve(r).workspace,c=i?.framework??"claude-code",l=r0(e.skillName),u=Ke(nl(c),l),x=Ke(o,u),h=Ke(x,"SKILL.md");if(!await Yf(h).then(R=>R.isFile()).catch(()=>!1))throw new k("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let w=new tl.default;w.addLocalFolder(x,l);let S=w.toBuffer();if(S.length>Xf)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${S.length} bytes exceeds limit ${Xf}`);let _=await ho(h,{encoding:"utf8"}).then(R=>s0(R).description).catch(()=>{}),v={};this.opts.publishSkillToMarketplace?v=await this.opts.publishSkillToMarketplace({zip:S,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,..._?{description:_}:{},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=v.version??"v1.0",T=v.skillId??e.skillId??i0(r,u);if(i){let R=i.skills??[],P=R.find(b=>b.relPath===u);P?(P.version=I,P.skillId=T):R.push({skillId:T,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),..._?{description:_}:{}}),await di(r,R)}return he.info("skill published",{agentId:r,skillName:e.skillName,relPath:u,zipBytes:S.length,skillId:T,version:I}),{ok:!0,skillId:T,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 l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,he.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let x=c.downstream;c.downstream=void 0,he.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l}),x.stop(r).catch(h=>he.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 he.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await ke(r);if(!i)throw new k("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 ur(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 k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Be(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 k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await ke(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Bi(e.registry)&&o.push(`--registry=${e.registry}`);let c=X_(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&J_.test(l)&&o.push("--env",l);let u=await Q_(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 k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await ke(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Be(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 k("IPC_BAD_REQUEST",`${ft.DELETE}: missing agentId`);let i=await ke(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let l=Ve(r);return c==="cloud"?await Yc(l.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Be(i)),he.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(kr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Wc(e.model)??Et,i=await ke(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Be(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};o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o).catch(l=>he.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(l)}));let c=[];for(let[l,u]of o.allSessionQueues())c.push(u.enqueue(async()=>{let x=o.sessions.get(l);x?.downstream&&(await x.downstream.stop(`switchModel: ${r}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(c),he.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:c.length}),{ok:!0}}async resetAgent(e){if(kr(e._meta,ft.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ft.RESET),await this.runDetailSync(e.agentId,ft.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),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,l]of i.sessions)o.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt});await li(e,o)}async clearPersistedAcpSessionIds(e){let r=await ke(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 Be(r)}async repairAgent(e){if(kr(e._meta,ft.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ft.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){he.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ft.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){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){kr(e._meta,"_agent/getFileTree");let r=e._meta,i=Kn(r),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await Vc(l).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await ci(l,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let x=py(e.depth);return u.isDirectory()?{tree:await hy(o,l,c,x)}:{tree:[{name:gy(c),path:c0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){kr(e._meta,"_agent/getFileContent");let r=Kn(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await Vc(o).catch(()=>null);if(!c||!c.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await ci(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>Zf)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${Zf})`);let l=await ho(o);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await ke(e).catch(()=>null))?.workspace??Ve(e).workspace}safeJoin(e,r){let i=Xc(e,r||"."),o=el(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${e0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return ke(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function r0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new k("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new k("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function nl(t){return t==="claude-code"?Ke(".claude","skills"):Ke(".agents","skills")}function i0(t,e){return(q_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function s0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
93
  ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
94
- `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function Q_(t,e,r){let i=Xc(r),o=We(e,i),c=await Zf(o,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let d=[];for(let u of c){if(!u.isDirectory())continue;let h=u.name,p=We(i,h),m=We(o,h,"SKILL.md"),_=await ao(m,{encoding:"utf8"}).catch(()=>null);if(_===null)continue;let v=n0(_);d.push({relPath:p,skill:{skillId:t0(t,p),skillName:v.name||h,...v.description?{description:v.description}:{}}})}return d}var ey=3e4,ty=50*1024*1024,Jf=10*1024*1024,Rr=3e4;async function lo(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new T("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 T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=e0(o.skillName),h=Xc(i),p=We(h,u),m=We(r,p);if(await Wc(m,{recursive:!0}),c){let v=Buffer.from(o.content,"utf8");Ni(v.length),await $c(We(m,"SKILL.md"),v,"utf8")}else{let v=await iy(o.downloadUrl);oy(v)?await dy(v,m):ay(v)?await cy(v,m):await $c(We(m,"SKILL.md"),v.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:p,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:p,source:c?"content":"downloadUrl"}),_}function uo(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 ny(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 ry(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 r0(t,e){let r=await Te(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Ot,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Me(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((m,_)=>[m.skillId,_])),u=c.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Me(r,e),{status:"noop",count:0};let h=0,p=0;for(let m of u)try{await Kc(We(r.workspace,m.relPath),{recursive:!0,force:!0});let _=await lo({agentId:t,workspace:r.workspace,framework:r.framework,skill:ry(m)});uo(c,d,_),h+=1}catch(_){p+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(_)})}return r.skills=c,p===0&&(r.skillsRefreshedForVersion=i),await Me(r,e),he.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:h,failed:p}),{status:"refreshed",count:h}}async function iy(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ni(e);let r=sy(t);return Ni(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await ao(e);return Ni(r.length),r}if(Di(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),ey);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new T("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Ni(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new T("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ni(t){if(t>ty)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function sy(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 oy(t){return t.length>=2&&t[0]===31&&t[1]===139}function ay(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 Jc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function cy(t,e){let r,i;try{r=new Yc.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||Jc(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(p=>p===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=ly(i),c=Vc(e);for(let d of i){if(Jc(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let h=Vc(e,u),p=Zc(c,h);if(p.startsWith("..")||p==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Wc(h,{recursive:!0});continue}await Wc(q_(h),{recursive:!0});let m;try{m=d.getData()}catch(_){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${_.message}`,{cause:_})}await $c(h,m)}}function ly(t){let e;for(let r of t){let i=r.entryName;if(!i||Jc(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 dy(t,e){await uy(t);let r=Tf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Rr}ms)`))},Rr);try{await Qf(Xf.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Rr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function uy(t){let e=[],r=Ar({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(p=>p==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Rr}ms)`))},Rr);try{await Qf(Xf.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Rr}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 fy=5e3;async function hy(t,e,r,i){return i0(t,e,r,i,{count:0})}async function i0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await Zf(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if($_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=fy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=We(e,u.name),p=j_(We(r,u.name)),m=null;try{m=await jc(h)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let _={name:u.name,path:s0(Zc(t,h)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(_.children=await i0(t,h,p,i-1,o)),d.push(_)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function xy(t){return!t||t<=0?W_:Math.min(t,K_)}function py(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function s0(t){return t.split(Yf).join("/")}te();var vn=H("agent-health-reporter"),gy=1e4,my=3,Mi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??gy,this.livenessFailureThreshold=e.livenessFailureThreshold??my}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()}),vn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),vn.info("heartbeat stopped"))}async tick(){if(this.inFlight){vn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,vn.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=wy(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:Ot,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,vn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(vn.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){vn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){vn.warn("onTickEnd hook failed",{err:String(r)})}}};function wy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}cn();import{mkdir as il,rm as fE,stat as hE}from"node:fs/promises";import{homedir as xE}from"node:os";import{join as ol}from"node:path";sn();import{existsSync as Py}from"node:fs";import{release as Dy}from"node:os";import{basename as Oy,isAbsolute as Ly}from"node:path";function Bi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Pr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Dr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Sn(t,e){return{jsonrpc:"2.0",id:t,error:e}}qe();var fo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Z={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function o0(t){return"method"in t&&"id"in t&&t.id!==void 0}function a0(t){return"method"in t&&!("id"in t)}function ho(t){return!("method"in t)&&"id"in t}var _y={AGENT_NOT_FOUND:Z.AGENT_NOT_FOUND,AGENT_BUSY:Z.AGENT_BUSY,AGENT_DISCONNECTED:Z.AGENT_DISCONNECTED,AGENT_TIMEOUT:Z.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Z.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Z.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Z.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Z.INTERNAL_ERROR,BRIDGE_INTERNAL:Z.INTERNAL_ERROR,IPC_AUTH_FAILED:Z.INTERNAL_ERROR,IPC_BAD_REQUEST:Z.INVALID_REQUEST,METHOD_NOT_FOUND:Z.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Z.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Z.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Z.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Z.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Z.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Z.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Z.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Z.FILE_TOO_LARGE,UNSUPPORTED_MIME:Z.UNSUPPORTED_MIME,UPLOAD_FAILED:Z.UPLOAD_FAILED,UPSTREAM_NOT_READY:Z.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Z.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Z.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Z.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Z.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Z.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Z.SKILL_ZIP_TOO_LARGE};function yy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Fi(t.message)}:typeof t=="string"?Fi(t):typeof t=="object"?by(t):t}var Ey=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Fi(t){let e=t;for(let[r,i]of Ey)e=e.replace(r,i);return e}function by(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Fi(i):e[r]=i;return e}function zi(t){if(t instanceof T){let e=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:_y[t.code]??Z.INTERNAL_ERROR,message:Fi(t.message),data:r}}return{code:Z.INTERNAL_ERROR,message:Fi(t instanceof Error?t.message:String(t))}}function c0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new T(r,o,{retriable:e?.retriable??!1,cause:c})}function d0(t){return`${JSON.stringify(t)}
95
- `}var l0=10*1024*1024,xo=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(`
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"},bT=Object.fromEntries(Object.entries(f0).map(([t,e])=>[e,t])),vy={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Or=class{seq=0;next(e,r){this.seq+=1;let i=f0[e]??Sy(e),o=vy[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(h=>u0(r?.[h]??"")),u=Iy(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>u0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Sy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function u0(t){return t.replace(/[:_\s]+/g,"-")}function Iy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}an();import{readFileSync as Ay}from"node:fs";var Ty=384;async function Qc(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await lr(t.agentEnvFile,r,{mode:Ty})}function el(t){try{let e=JSON.parse(Ay(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function h0(t,e,r={},i=o=>o){return{...i({...t,...el(e)}),...r}}$t();ir();qe();te();Oe();import{execFileSync as ky,spawnSync as Cy}from"node:child_process";function Ui(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Gi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Cy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var tl=new Set;function x0(t){typeof t=="number"&&t>0&&tl.add(t)}function p0(t){typeof t=="number"&&tl.delete(t)}function g0(){for(let t of tl)Gi(t,"SIGKILL")}var Lr="coze-bridge-daemon";function m0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return ky("pgrep",["-U",String(o),"-f",Lr],{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 w0(t,e){if(t.length===0)return;let r=e?.killFn??Gi,i=e?.isAliveFn??Ui,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 Ry=[{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:"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|agentclientprotocol)\/codex-acp|optional dependency was not installed|\.resolve is not a function/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function _0(t,e){if(!e)return null;for(let r of Ry)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function y0(t,e){return _0(t,e)}function E0(t,e){return _0(t,e)}function Nr(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 b0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let p=t.suspendedMs+o,m=r-t.startedAt-p;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Nr(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:Nr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Nr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Nr(c,!1,e)}}var v0=$e("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Ny=200,My=40,By=$e("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fy=$e("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zy=$e("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Uy=$e("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Gy=$e("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Hy=$e("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),S0=500;function qy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=S0?t:`${e.slice(0,S0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function jy(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 I0(t){try{return Py(t)}catch{return}}function Wy(t,e){return{platform:process.platform,osRelease:Dy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Ly(e.command)?I0(e.command):void 0,cwd:e.cwd,cwdExists:I0(e.cwd),envKeys:e.envKeys}}function Ky(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Oy(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Lt=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new xo({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Or;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;spawnEnv={};sanitizeEnv(e){return e}async start(){if(this.child)throw new T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=h0(process.env,this.opts.agentEnvFile??Q().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o));this.spawnEnv=r;let i=nt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,x0(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>Ny&&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,p0(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=Wy(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",Ky(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()));Gi(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Gi(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:Gy,phase2GateMs:By,livenessWindowMs:Fy,absoluteMaxMs:zy,approvalMaxMs:Hy,suspendThresholdMs:Uy,...r};return this.call("session/prompt",e,v0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Pr("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(Dr(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(Sn(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 T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Bi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let h=r.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,p)=>{let m={resolve:h,reject:p,timer:null,method:e,promptTimeout:null};if(o){let _=this.now(),v={cfg:o,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:Nr(0,!1,o),sessionId:u};m.promptTimeout=v;let y=()=>{let S={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},I=this.now(),A=b0(S,v.cfg,I),k=D=>{v.armedAt=I,v.expectedIntervalMs=D,m.timer=setTimeout(y,D)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),k(A.rearmMs);return}if(A.action==="continue"){k(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),p(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new T("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}:{}}),p(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(y,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}),p(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(d)}catch(_){m.timer&&clearTimeout(m.timer),this.pending.delete(c),p(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(d0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(ho(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:qy(e.result)}),r.resolve(e.result));return}if(a0(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(o0(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(Sn(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(Sn(e.id,zi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=c0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=E0(this.framework,jy(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(My).join(`
98
- `),o=y0(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 $y(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 po=class extends Lt{framework="claude-code";constructor(e){let{command:r,args:i}=ni("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return $y(e)}};sn();import{mkdtempSync as Yy,rmSync as Xy}from"node:fs";import{tmpdir as Qy}from"node:os";import{join as eE}from"node:path";import{readFileSync as T0}from"node:fs";import{homedir as Vy}from"node:os";import{join as A0}from"node:path";function k0(t){let e=t.CODEX_HOME?.trim()||A0(t.HOME?.trim()||Vy(),".codex");return A0(e,"config.toml")}function Jy(t){let e=null;for(let r=0;r<t.length;r++){let i=t[r];if(e)i===e&&(e=null);else if(i==='"'||i==="'")e=i;else if(i==="#")return t.slice(0,r)}return t}function Zy(t){let e=t.trim();if(e.length>=2){let r=e[0];if((r==='"'||r==="'")&&e[e.length-1]===r)return e.slice(1,-1)}return e}function C0(t){let e={},r={},i=e;for(let o of t.split(/\r?\n/)){let c=Jy(o).trim();if(!c)continue;let d=/^\[([^\]]+)\]$/.exec(c);if(d){let p=(d[1]??"").trim(),m=r[p]??{};r[p]=m,i=m;continue}let u=c.indexOf("=");if(u<=0)continue;let h=c.slice(0,u).trim();h&&(i[h]=Zy(c.slice(u+1)))}return{root:e,tables:r}}function R0(t){let e=t.root.model_provider;if(!e||e==="openai")return null;let r=t.tables[`model_providers.${e}`];return r?{providerId:e,baseUrl:r.base_url,envKey:r.env_key,bearerToken:r.experimental_bearer_token}:null}function P0(t){let e;try{e=T0(k0(t),"utf8")}catch{return null}return R0(C0(e))?.providerId??null}function D0(t){let e;try{e=T0(k0(t),"utf8")}catch{return null}let r=R0(C0(e));if(!r?.baseUrl)return null;let i=r.bearerToken||(r.envKey?t[r.envKey]?.trim():void 0);return i?{baseUrl:r.baseUrl,providerName:r.providerId,headers:{Authorization:`Bearer ${i}`}}:null}var go=class t extends Lt{framework="codex";authRequest;resolveLocalGatewayAuth;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ni("codex",e.command,i),d=e.isolateCodexHome?Yy(eE(Qy(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,h={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(h),this.authRequest=e.authRequest,this.resolveLocalGatewayAuth=e.resolveLocalGatewayAuth??!1,this.codexHomeDir=d}async initialize(e){let r=await super.initialize(e),i=this.authRequest??this.localGatewayAuthRequest();return i&&await this.call("authenticate",i),r}localGatewayAuthRequest(){if(!this.resolveLocalGatewayAuth)return null;let e=D0(this.spawnEnv);return e?(this.log.info("codex local: \u7528 config.toml custom provider \u8D70 gateway \u8BA4\u8BC1",{providerName:e.providerName,baseUrl:e.baseUrl}),{methodId:"gateway",_meta:{gateway:e}}):null}static MODE_ID_MAP={"read-only":"read-only",auto:"agent","full-access":"agent-full-access"};setSessionMode(e){let r=t.MODE_ID_MAP[e.modeId]??e.modeId;return super.setSessionMode({...e,modeId:r})}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Xy(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};qe();var tE=3e4,Mr=class extends Lt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},tE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var O0=["default","acceptEdits","plan","auto","bypassPermissions"],L0=["read-only","auto","full-access"];function In(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return O0.includes(e);case"codex":return L0.includes(e);case"openclaw":return!1}}function nl(t){switch(t){case"claude-code":return O0.join("/");case"codex":return L0.join("/");case"openclaw":return""}}an();qe();te();Oe();function rl(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}sn();var An=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 mo=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 An,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)Hi(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 Hi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Vt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}$t();te();import{constants as N0}from"node:fs";import{access as nE}from"node:fs/promises";import{delimiter as rE,join as iE}from"node:path";var vt=H("framework-detector"),M0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},sE=[".exe",".cmd",".bat",".ps1"],$n=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??nt,access:e.access??nE}}async detect(e){let r=M0[e],i=await this.which(r);if(!i)return vt.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[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(M0).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(rE).filter(Boolean),i=this.env.platform==="win32"?["",...sE]:[""];for(let o of r)for(let c of i){let d=iE(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?N0.F_OK:N0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return vt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return vt.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return vt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return vt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(vt.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}:(vt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return vt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return vt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||vt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},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){vt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(aE(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",p=>{o+=p.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",p=>u({code:p,stdout:o}))}catch{u(null)}})}},oE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function aE(t){return t.replace(oE,"")}import{homedir as cE}from"node:os";import{join as lE}from"node:path";an();$t();ir();qe();te();async function z0(){let t=lE(cE(),".openclaw/openclaw.json");return(await cr(t))?.gateway?.auth?.token??""}var B0=H("openclaw.config"),dE=[0,5e3,5e3],uE=$e("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),F0="models.providers.",wo="agents.defaults.models",_o=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new An;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??dE,this.cliTimeoutMs=e.cliTimeoutMs??uE}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,B0.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=nt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=p=>{d||(d=!0,clearTimeout(h),p())};o.stderr?.on("data",p=>{c+=p.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",p=>u(()=>i(p))),o.on("close",p=>u(()=>{p===0?r():i(new Error(`exit ${p}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(i){B0.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",`${F0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${F0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${wo}[${e}]`,()=>this.runCli(["config","set",wo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${wo}[${e}]`,`${wo}.${e}`)}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var de=H("agent-manager"),al="bypassPermissions",H0="full-access",q0="full-access";function pE(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}var gE=(t,e,r,i,o,c,d,u,h,p)=>{switch(t){case"claude-code":{let m={...o?{...Hf(o),...Wf(o,d,u)}:{},...h??{},IS_SANDBOX:"1"};return new po({cwd:r,env:m,agentId:i})}case"codex":{let m=H0;p!==void 0&&(In("codex",p)?m=p:de.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:p}));let _=o?null:P0(process.env),v={...o?jf(o):{},INITIAL_AGENT_MODE:pE(m),...process.env.COZE_BRIDGE_CODEX_APP_SERVER_LOGS==="1"?{APP_SERVER_LOGS:ol(r,"..","logs","codex-app-server")}:{},..._?{MODEL_PROVIDER:_}:{},...h??{}},y=o?qf(o,d,u):null,S=y?{methodId:"gateway",_meta:{gateway:y}}:void 0,I=!!o,A=!I&&process.env.COZE_BRIDGE_CODEX_LOCAL_GATEWAY_AUTH==="1";return new go({cwd:r,agentId:i,...Object.keys(v).length>0?{env:v}:{},...S?{authRequest:S}:{},...I?{isolateCodexHome:!0}:{},...A?{resolveLocalGatewayAuth:!0}:{}})}case"openclaw":return new Mr({command:e,cwd:r,agentId:i,...c?{sessionName:rl(c)}:{}})}};function sl(t){return t==="claude-code"||t==="codex"}function mE(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(wE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
94
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let l=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[l]=u)}return i}async function ey(t,e,r){let i=nl(r),o=Ke(e,i),c=await Qf(o,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let l=[];for(let u of c){if(!u.isDirectory())continue;let x=u.name,h=Ke(i,x),m=Ke(o,x,"SKILL.md"),w=await ho(m,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let S=s0(w);l.push({relPath:h,skill:{skillId:i0(t,h),skillName:S.name||x,...S.description?{description:S.description}:{}}})}return l}var ty=3e4,ny=50*1024*1024,Xf=10*1024*1024,Dr=3e4;async function go(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,l=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!l)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=r0(o.skillName),x=nl(i),h=Ke(x,u),m=Ke(r,h);if(await Jc(m,{recursive:!0}),c){let S=Buffer.from(o.content,"utf8");Ui(S.length),await Zc(Ke(m,"SKILL.md"),S,"utf8")}else{let S=await sy(o.downloadUrl);ay(S)?await uy(S,m):cy(S)?await ly(S,m):await Zc(Ke(m,"SKILL.md"),S.toString("utf8"),"utf8")}let w={skillId:o.skillId,skillName:o.skillName,relPath:h,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:h,source:c?"content":"downloadUrl"}),w}function mo(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 ry(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 iy(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 o0(t,e){let r=await ke(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 Be(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],l=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 Be(r,e),{status:"noop",count:0};let x=0,h=0;for(let m of u)try{await Yc(Ke(r.workspace,m.relPath),{recursive:!0,force:!0});let w=await go({agentId:t,workspace:r.workspace,framework:r.framework,skill:iy(m)});mo(c,l,w),x+=1}catch(w){h+=1,he.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(w)})}return r.skills=c,h===0&&(r.skillsRefreshedForVersion=i),await Be(r,e),he.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:x,failed:h}),{status:"refreshed",count:x}}async function sy(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ui(e);let r=oy(t);return Ui(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await ho(e);return Ui(r.length),r}if(Bi(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),ty);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Ui(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ui(t){if(t>ny)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function oy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function ay(t){return t.length>=2&&t[0]===31&&t[1]===139}function cy(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 Qc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function ly(t,e){let r,i;try{r=new tl.default(t),i=r.getEntries()}catch(l){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||Qc(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(h=>h===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let x=l.header.attr>>>16&61440;if(x!==0&&x!==32768&&x!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${x.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=dy(i),c=Xc(e);for(let l of i){if(Qc(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let x=Xc(e,u),h=el(c,x);if(h.startsWith("..")||h==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await Jc(x,{recursive:!0});continue}await Jc(j_(x),{recursive:!0});let m;try{m=l.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${w.message}`,{cause:w})}await Zc(x,m)}}function dy(t){let e;for(let r of t){let i=r.entryName;if(!i||Qc(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 uy(t,e){await fy(t);let r=Cf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Dr}ms)`))},Dr);try{await n0(t0.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Dr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function fy(t){let e=[],r=Tr({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(h=>h==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Dr}ms)`))},Dr);try{await n0(t0.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Dr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var xy=5e3;async function hy(t,e,r,i){return a0(t,e,r,i,{count:0})}async function a0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await Qf(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(V_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=xy){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let x=Ke(e,u.name),h=W_(Ke(r,u.name)),m=null;try{m=await Vc(x)}catch{continue}if(m.isSymbolicLink())continue;o.count++;let w={name:u.name,path:c0(el(t,x)),isDir:m.isDirectory(),size:m.size,modifiedAt:Math.floor(m.mtimeMs)};m.isDirectory()&&i>1&&(w.children=await a0(t,x,h,i-1,o)),l.push(w)}return l.sort((u,x)=>u.isDir!==x.isDir?u.isDir?-1:1:u.name.localeCompare(x.name)),l}function py(t){return!t||t<=0?K_:Math.min(t,$_)}function gy(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function c0(t){return t.split(e0).join("/")}ne();var vn=H("agent-health-reporter"),my=1e4,wy=3,Gi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??my,this.livenessFailureThreshold=e.livenessFailureThreshold??wy}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()}),vn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),vn.info("heartbeat stopped"))}async tick(){if(this.inFlight){vn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,vn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let l of this.opts.core.agents.values()){let u=_y(l);if(!u)continue;let x={agentId:l.agentId,status:u};l.patToken&&(x.patToken=l.patToken),l.accountId&&(x.accountId=l.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(l){this.consecutiveFailures+=1,vn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(vn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(l=>l.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(l){vn.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){vn.warn("onTickEnd hook failed",{err:String(r)})}}};function _y(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}cn();import{mkdir as cl,rm as xb,stat as hb}from"node:fs/promises";import{homedir as pb}from"node:os";import{join as dl}from"node:path";sn();import{existsSync as Py}from"node:fs";import{release as Ly}from"node:os";import{basename as Oy,isAbsolute as Ny}from"node:path";function Hi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Pr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Lr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Sn(t,e){return{jsonrpc:"2.0",id:t,error:e}}je();var wo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},Y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function l0(t){return"method"in t&&"id"in t&&t.id!==void 0}function d0(t){return"method"in t&&!("id"in t)}function _o(t){return!("method"in t)&&"id"in t}var yy={AGENT_NOT_FOUND:Y.AGENT_NOT_FOUND,AGENT_BUSY:Y.AGENT_BUSY,AGENT_DISCONNECTED:Y.AGENT_DISCONNECTED,AGENT_TIMEOUT:Y.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Y.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Y.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Y.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Y.INTERNAL_ERROR,BRIDGE_INTERNAL:Y.INTERNAL_ERROR,IPC_AUTH_FAILED:Y.INTERNAL_ERROR,IPC_BAD_REQUEST:Y.INVALID_REQUEST,METHOD_NOT_FOUND:Y.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Y.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Y.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Y.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Y.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Y.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Y.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Y.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Y.FILE_TOO_LARGE,UNSUPPORTED_MIME:Y.UNSUPPORTED_MIME,UPLOAD_FAILED:Y.UPLOAD_FAILED,UPSTREAM_NOT_READY:Y.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Y.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Y.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Y.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Y.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Y.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Y.SKILL_ZIP_TOO_LARGE};function by(t){if(t!=null)return t instanceof Error?{name:t.name,message:qi(t.message)}:typeof t=="string"?qi(t):typeof t=="object"?vy(t):t}var Ey=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function qi(t){let e=t;for(let[r,i]of Ey)e=e.replace(r,i);return e}function vy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=qi(i):e[r]=i;return e}function ji(t){if(t instanceof k){let e=by(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:yy[t.code]??Y.INTERNAL_ERROR,message:qi(t.message),data:r}}return{code:Y.INTERNAL_ERROR,message:qi(t instanceof Error?t.message:String(t))}}function u0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:l,...u}=e;c=u}return new k(r,o,{retriable:e?.retriable??!1,cause:c})}function x0(t){return`${JSON.stringify(t)}
95
+ `}var f0=10*1024*1024,yo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>f0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${f0} 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(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var p0={"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"},vT=Object.fromEntries(Object.entries(p0).map(([t,e])=>[e,t])),Sy={"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:[]},Or=class{seq=0;next(e,r){this.seq+=1;let i=p0[e]??Iy(e),o=Sy[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(x=>h0(r?.[x]??"")),u=Ay(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>h0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function Iy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function h0(t){return t.replace(/[:_\s]+/g,"-")}function Ay(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}an();import{readFileSync as Ty}from"node:fs";var ky=384;async function rl(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await dr(t.agentEnvFile,r,{mode:ky})}function il(t){try{let e=JSON.parse(Ty(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function g0(t,e,r={},i=o=>o){return{...i({...t,...il(e)}),...r}}$t();sr();je();ne();Le();import{execFileSync as Ry,spawnSync as Cy}from"node:child_process";function Wi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Ki(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Cy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var sl=new Set;function m0(t){typeof t=="number"&&t>0&&sl.add(t)}function w0(t){typeof t=="number"&&sl.delete(t)}function _0(){for(let t of sl)Ki(t,"SIGKILL")}var Nr="coze-bridge-daemon";function y0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Ry("pgrep",["-U",String(o),"-f",Nr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function b0(t,e){if(t.length===0)return;let r=e?.killFn??Ki,i=e?.isAliveFn??Wi,o=e?.sleepFn??(u=>new Promise(x=>setTimeout(x,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(x=>i(x));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var Dy=[{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:"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|agentclientprotocol)\/codex-acp|optional dependency was not installed|\.resolve is not a function/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function E0(t,e){if(!e)return null;for(let r of Dy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function v0(t,e){return E0(t,e)}function S0(t,e){return E0(t,e)}function Mr(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function I0(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:Mr(m,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Mr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Mr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Mr(c,!1,e)}}var A0=$e("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),My=200,By=40,zy=$e("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fy=$e("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Uy=$e("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Gy=$e("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hy=$e("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),qy=$e("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),T0=500;function jy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=T0?t:`${e.slice(0,T0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Wy(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 k0(t){try{return Py(t)}catch{return}}function Ky(t,e){return{platform:process.platform,osRelease:Ly(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Ny(e.command)?k0(e.command):void 0,cwd:e.cwd,cwdExists:k0(e.cwd),envKeys:e.envKeys}}function $y(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Oy(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Ot=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new yo({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Or;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;spawnEnv={};sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=g0(process.env,this.opts.agentEnvFile??Q().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o));this.spawnEnv=r;let i=rt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,m0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>My&&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,w0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,l=Ky(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:l}),this.failAllPending(new k("AGENT_SPAWN_FAILED",$y(c,l),{cause:l}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Ki(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Ki(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:Hy,phase2GateMs:zy,livenessWindowMs:Fy,absoluteMaxMs:Uy,approvalMaxMs:qy,suspendThresholdMs:Gy,...r};return this.call("session/prompt",e,A0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Pr("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(Lr(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(Sn(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=A0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=Hi(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(),S={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Mr(0,!1,o),sessionId:u};m.promptTimeout=S;let _=()=>{let v={startedAt:S.startedAt,lastActivityAt:S.lastActivityAt,firstFrameSeen:S.firstFrameSeen,hasActiveTool:S.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:S.suspendedMs,armedAt:S.armedAt,expectedIntervalMs:S.expectedIntervalMs},I=this.now(),T=I0(v,S.cfg,I),R=P=>{S.armedAt=I,S.expectedIntervalMs=P,m.timer=setTimeout(_,P)};if(T.action==="suspend"){S.suspendedMs+=T.suspendedDeltaMs,S.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:T.suspendedDeltaMs,suspendedMs:S.suspendedMs,...S.sessionId?{sessionId:S.sessionId}:{}}),R(T.rearmMs);return}if(T.action==="continue"){R(T.rearmMs);return}this.pending.delete(c),T.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:T.awaitingApproval,...S.sessionId?{sessionId:S.sessionId}:{}}),h(T.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${S.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${S.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...S.sessionId?{sessionId:S.sessionId}:{}}),h(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${S.cfg.livenessWindowMs}ms`)))};m.timer=setTimeout(_,S.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(m.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),h(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,m);try{this.writeFrame(l)}catch(w){m.timer&&clearTimeout(m.timer),this.pending.delete(c),h(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(x0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(_o(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new k("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:jy(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(l0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Sn(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(Sn(e.id,ji(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=u0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=S0(this.framework,Wy(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(By).join(`
98
+ `),o=v0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Vy(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 bo=class extends Ot{framework="claude-code";constructor(e){let{command:r,args:i}=ai("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 Vy(e)}};sn();import{mkdtempSync as Xy,rmSync as Qy}from"node:fs";import{tmpdir as eb}from"node:os";import{join as tb}from"node:path";import{readFileSync as C0}from"node:fs";import{homedir as Jy}from"node:os";import{join as R0}from"node:path";function D0(t){let e=t.CODEX_HOME?.trim()||R0(t.HOME?.trim()||Jy(),".codex");return R0(e,"config.toml")}function Yy(t){let e=null;for(let r=0;r<t.length;r++){let i=t[r];if(e)i===e&&(e=null);else if(i==='"'||i==="'")e=i;else if(i==="#")return t.slice(0,r)}return t}function Zy(t){let e=t.trim();if(e.length>=2){let r=e[0];if((r==='"'||r==="'")&&e[e.length-1]===r)return e.slice(1,-1)}return e}function P0(t){let e={},r={},i=e;for(let o of t.split(/\r?\n/)){let c=Yy(o).trim();if(!c)continue;let l=/^\[([^\]]+)\]$/.exec(c);if(l){let h=(l[1]??"").trim(),m=r[h]??{};r[h]=m,i=m;continue}let u=c.indexOf("=");if(u<=0)continue;let x=c.slice(0,u).trim();x&&(i[x]=Zy(c.slice(u+1)))}return{root:e,tables:r}}function L0(t){let e=t.root.model_provider;if(!e||e==="openai")return null;let r=t.tables[`model_providers.${e}`];return r?{providerId:e,baseUrl:r.base_url,envKey:r.env_key,bearerToken:r.experimental_bearer_token}:null}function O0(t){let e;try{e=C0(D0(t),"utf8")}catch{return null}return L0(P0(e))?.providerId??null}function N0(t){let e;try{e=C0(D0(t),"utf8")}catch{return null}let r=L0(P0(e));if(!r?.baseUrl)return null;let i=r.bearerToken||(r.envKey?t[r.envKey]?.trim():void 0);return i?{baseUrl:r.baseUrl,providerName:r.providerId,headers:{Authorization:`Bearer ${i}`}}:null}var Eo=class t extends Ot{framework="codex";authRequest;resolveLocalGatewayAuth;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ai("codex",e.command,i),l=e.isolateCodexHome?Xy(tb(eb(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(x),this.authRequest=e.authRequest,this.resolveLocalGatewayAuth=e.resolveLocalGatewayAuth??!1,this.codexHomeDir=l}async initialize(e){let r=await super.initialize(e),i=this.authRequest??this.localGatewayAuthRequest();return i&&await this.call("authenticate",i),r}localGatewayAuthRequest(){if(!this.resolveLocalGatewayAuth)return null;let e=N0(this.spawnEnv);return e?(this.log.info("codex local: \u7528 config.toml custom provider \u8D70 gateway \u8BA4\u8BC1",{providerName:e.providerName,baseUrl:e.baseUrl}),{methodId:"gateway",_meta:{gateway:e}}):null}static MODE_ID_MAP={"read-only":"read-only",auto:"agent","full-access":"agent-full-access"};setSessionMode(e){let r=t.MODE_ID_MAP[e.modeId]??e.modeId;return super.setSessionMode({...e,modeId:r})}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Qy(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};je();var nb=3e4,Br=class extends Ot{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}`}]},nb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var M0=["default","acceptEdits","plan","auto","bypassPermissions"],B0=["read-only","auto","full-access"];function In(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return M0.includes(e);case"codex":return B0.includes(e);case"openclaw":return!1}}function ol(t){switch(t){case"claude-code":return M0.join("/");case"codex":return B0.join("/");case"openclaw":return""}}an();je();ne();Le();function al(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}sn();var An=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 vo=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 An,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)$i(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 $i(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Vt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}$t();ne();import{constants as z0}from"node:fs";import{access as rb}from"node:fs/promises";import{delimiter as ib,join as sb}from"node:path";var vt=H("framework-detector"),F0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},ob=[".exe",".cmd",".bat",".ps1"],$n=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??rt,access:e.access??rb}}async detect(e){let r=F0[e],i=await this.which(r);if(!i)return vt.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,l]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(F0).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(ib).filter(Boolean),i=this.env.platform==="win32"?["",...ob]:[""];for(let o of r)for(let c of i){let l=sb(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?z0.F_OK:z0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return vt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return vt.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return vt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return vt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(vt.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}:(vt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return vt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return vt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||vt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let l=JSON.parse(c[0]);typeof l.gateway?.port=="number"&&(o.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(o.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(o.detail=l.rpc.error)}catch(l){vt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(cb(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,l,u=x=>{c||(c=!0,l&&clearTimeout(l),i(x))};try{let x=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});l=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)}})}},ab=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function cb(t){return t.replace(ab,"")}import{homedir as lb}from"node:os";import{join as db}from"node:path";an();$t();sr();je();ne();async function H0(){let t=db(lb(),".openclaw/openclaw.json");return(await lr(t))?.gateway?.auth?.token??""}var U0=H("openclaw.config"),ub=[0,5e3,5e3],fb=$e("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),G0="models.providers.",So="agents.defaults.models",Io=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new An;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??ub,this.cliTimeoutMs=e.cliTimeoutMs??fb}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(l=>setTimeout(l,c));try{return await r()}catch(l){i=l,U0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=rt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=h=>{l||(l=!0,clearTimeout(x),h())};o.stderr?.on("data",h=>{c+=h.toString("utf8")});let x=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);x.unref(),o.on("error",h=>u(()=>i(h))),o.on("close",h=>u(()=>{h===0?r():i(new Error(`exit ${h}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(i){U0.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${G0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${G0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${So}[${e}]`,()=>this.runCli(["config","set",So,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${So}[${e}]`,`${So}.${e}`)}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var de=H("agent-manager"),ul="acceptEdits",W0="full-access",K0="read-only";function gb(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}var mb=(t,e,r,i,o,c,l,u,x,h)=>{switch(t){case"claude-code":{let m={...o?{...Wf(o),...Vf(o,l,u)}:{},...x??{},IS_SANDBOX:"1"};return new bo({cwd:r,env:m,agentId:i})}case"codex":{let m=W0;h!==void 0&&(In("codex",h)?m=h:de.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let w=o?null:O0(process.env),S={...o?$f(o):{},INITIAL_AGENT_MODE:gb(m),...process.env.COZE_BRIDGE_CODEX_APP_SERVER_LOGS==="1"?{APP_SERVER_LOGS:dl(r,"..","logs","codex-app-server")}:{},...w?{MODEL_PROVIDER:w}:{},...x??{}},_=o?Kf(o,l,u):null,v=_?{methodId:"gateway",_meta:{gateway:_}}:void 0,I=!!o,T=!I&&process.env.COZE_BRIDGE_CODEX_LOCAL_GATEWAY_AUTH==="1";return new Eo({cwd:r,agentId:i,...Object.keys(S).length>0?{env:S}:{},...v?{authRequest:v}:{},...I?{isolateCodexHome:!0}:{},...T?{resolveLocalGatewayAuth:!0}:{}})}case"openclaw":return new Br({command:e,cwd:r,agentId:i,...c?{sessionName:al(c)}:{}})}};function ll(t){return t==="claude-code"||t==="codex"}function wb(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(_b(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
99
99
  `)}
100
- `}function wE(t){if(t.includes(`
101
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var _E={path:"",version:"cloud-deployed"},U0="openclaw_gateway_unavailable",yE="openclaw_default_agent_missing";function G0(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 EE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},bE=6e4,yo=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??gE,this.createTimeoutMs=e.createTimeoutMs??bE,this.detectorFactory=e.detectorFactory??(()=>new $n),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new _o({command:r})),this.openclawConfigDir=e.openclawConfigDir??ol(xE(),".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=>{de.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=ol(e,".env");if(await hE(r).then(c=>c.isFile()).catch(()=>!1)){de.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=mE({...process.env,...el(this.paths.agentEnvFile)});await on(r,o,{mode:384}),de.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),de.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await Te(e.agentId,this.paths).catch(()=>null),o=io(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")de.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(k=>de.warn("dispose stale agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")de.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(k=>de.warn("dispose drifted agent failed (ignored)",{err:String(k)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){de.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let k=await Te(e.agentId,this.paths).catch(()=>null);k&&(k.patToken=e.patToken,await Me(k,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){de.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let k=await Te(e.agentId,this.paths).catch(()=>null);k&&(k.modelInfo=e.modelInfo,await Me(k,this.paths))}return de.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 T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ve(e.agentId,this.paths),h=o?"cloud":"local",p=e.framework==="openclaw"&&h==="local",m;p&&!r?.revive&&(m=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=m??(p?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??_??u.workspace,y=new AbortController,S=setTimeout(()=>y.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&sl(e.framework)&&await ar(e.framework,y.signal);let k=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await il(u.root,{recursive:!0}),await il(v,{recursive:!0}),await il(u.logs,{recursive:!0}),k(),p||await dr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await Ra(v,"cloud"):await Ra(v,"local",al)),k();let D=i,E=Gf({model:e.model??D?.model}),R=Cf(e._meta)??D?.accountId,L=e.patToken??D?.patToken,B=h==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new mo({agentId:e.agentId,framework:e.framework,workspace:v,model:E.model??bt,deployType:h,...R?{accountId:R}:{},...L?{patToken:L}:{},...B?{modelInfo:B}:{}}),I.status="ok",D?.sessions){let V=h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,ie]of Object.entries(D.sessions)){let se={acpSessionId:ie.acpSessionId,modelToken:ie.modelToken,tokenGeneratedAt:ie.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?ie.permissionMode===void 0?(se.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",de.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Y,framework:e.framework,fallback:se.permissionMode})):In(e.framework,ie.permissionMode)?se.permissionMode=ie.permissionMode:de.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:ie.permissionMode}):ie.permissionMode!==void 0&&de.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:h}),ie.cozeGroupId&&(se.cozeGroupId=ie.cozeGroupId),I.sessions.set(Y,se)}let ne=Object.keys(D.sessions).length;ne>0&&de.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ne})}this.registry.register(I),A=!0;let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:E.model};h==="cloud"&&(M.deployType="cloud"),R&&(M.accountId=R),L&&(M.patToken=L),B&&(M.modelInfo=B),D?.skills&&(M.skills=D.skills),D?.agentName&&(M.agentName=D.agentName),D?.description&&(M.description=D.description),M.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&h==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):de.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let J=e.initialSkills??[];if(J.length>0){let V=[...M.skills??[]],ne=new Map(V.map((se,P)=>[se.skillId,P])),Y=await Promise.allSettled(J.map(se=>lo({agentId:e.agentId,workspace:v,framework:e.framework,skill:se}))),ie=0;for(let[se,P]of Y.entries()){let G=J[se];G&&(P.status==="fulfilled"?(uo(V,ne,P.value),ie++):de.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(P.reason)}))}ie>0&&(M.skills=V,de.info("initialSkills installed",{agentId:e.agentId,installed:ie,requested:J.length}))}return await Me(M,this.paths),de.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 de.error("agent create failed, rolling back",{agentId:e.agentId,err:String(k)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await fE(u.root,{recursive:!0,force:!0}).catch(D=>de.warn("rm agent dir failed (ignored)",{err:String(D)})),k instanceof T?k:new T("AGENT_SPAWN_FAILED",String(k),{cause:k})}finally{clearTimeout(S)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&sl(e.framework))u=_E;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);sl(e.framework)&&!us(e.framework)&&(de.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await ar(e.framework));let h=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,p;if(e.framework==="openclaw")p=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else{let m=e.sessions.get(i),_=Vt(e)?m?.permissionMode??H0:"full-access";p=this.factory(e.framework,u.path,e.workspace,e.agentId,h,i,o,c,this.buildBinShimPathEnv(),_)}try{return await p.start(),await p.initialize(EE),p}catch(m){let _=p instanceof Lt?p.getStderrTail():[];throw _.length>0&&de.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof T?m.code:"unknown",recentStderr:_}),await p.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",G0(o),{cause:{reason:U0}})}catch(o){de.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};de.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 de.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:yE}})}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",G0(r),{cause:{reason:U0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,h=rl(o);if(r.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Mr({command:u,cwd:v.workspace,agentId:v.id,sessionName:h})}let p=await z0(),m=i?Kf(i,c,d):null,_;if(m){let v=qc(o),S=m.models[0]?.id??bt,I=`${v}/${S}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(v,m),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}_=I}return new Mr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:h,...p?{gatewayToken:p}:{},..._?{slashModelOnStart:_}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let i of e.sessions.keys()){let o=qc(i),c=`${o}/${e.model}`,d=!0;try{await r.removeProvider(o)}catch(u){d=!1,de.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:o,err:String(u)})}try{await r.removeModelFromAllowlist(c)}catch(u){d=!1,de.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:c,err:String(u)})}d&&this.ensuredProviders.delete(c)}}};import{randomUUID as V0}from"node:crypto";import{promises as CE}from"node:fs";import{basename as J0}from"node:path";qe();te();import{promises as vE}from"node:fs";import{basename as SE}from"node:path";var j0=H("file-upload"),IE="/api/coze_claw/file/agent_upload",AE=6e4;async function W0(t,e={}){let i=`${kr(Cr(e.handshakeBase))}${IE}`,o=e.timeoutMs??AE,c=await vE.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",...bn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,p=setTimeout(()=>h.abort(),o);j0.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}),_=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=${_}: ${S.slice(0,200)}`)}let v=await m.json();if(v.code!==void 0&&v.code!==0)throw new T("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${_}`);let y=v.data?.file?.file_url;if(!y)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(v).slice(0,200)}`);return j0.info("file upload ok",{uri:y,logid:_}),{uri:y}}catch(m){throw m instanceof T?m:m.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${SE(t.path)}`):new T("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(p)}}qe();te();import{extname as TE}from"node:path";var kE={".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 K0(t){let e=TE(t).toLowerCase();return kE[e]??"application/octet-stream"}Oe();var Eo=H("agent-send"),$0=50*1024*1024;function Z0(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 Y0(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(p){u=p,h<2&&(Eo.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(p)}),await new Promise(m=>setTimeout(m,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function X0(t,e){let{session:r,runtime:i}=Z0(e.core,t.agentId,t.sessionId);if(!await ri(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await CE.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>$0)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${$0}`);let c=await K0(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??J0(t.path),u;try{u=await W0({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(p){throw Eo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:p instanceof T?p.code:"UNKNOWN",message:p instanceof Error?p.message:String(p)}),p}let h={sessionUpdate:"agent_file",messageId:V0(),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 Y0(e,r,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Eo.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 Q0(t,e){let{session:r,runtime:i}=Z0(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??J0(t.path),c={sessionUpdate:"group_file",messageId:V0(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Y0(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),Eo.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 eh(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}sn();$t();te();var Nt=H("coze-cli-installer"),th="@coze/cli@latest",RE="coze",nh="0.1.8",PE=5e3,DE=5e3,OE=9e4,rh=1e4,qi=null,bo=!1;async function ll(t,e={}){if(bo)return;if(qi)return qi;let r=e.exec??Lf;return qi=(async()=>{try{let i=await LE(RE,r),o=!1;if(i){let d=await NE(r);if(d===void 0)Nt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(eh(d,nh))Nt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:nh}),o=!0;else{Nt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),bo=!0;return}}let c=o?"upgrade-only":"full";Nt.info("coze-cli install start",{package:th,mode:c});try{await r("npm",["i","-g","--prefer-online",th],{timeout:OE,maxBuffer:10*1024*1024}),Nt.info("coze-cli install ok")}catch(d){Nt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){bo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:rh}),Nt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Nt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:rh}),Nt.info("coze auth login ok")}catch(d){Nt.warn("coze auth login failed",{err:String(d)});return}bo=!0}finally{qi=null}})(),qi}async function LE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:PE});return ka(i)}catch{return}}async function NE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:DE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}an();Oe();var ME=10*6e4;function ih(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ME:e}function vo(t){return cr(t??Q().configFile)}function ji(t,e){return lr(e??Q().configFile,t)}import{randomBytes as nb}from"node:crypto";ir();qe();te();import{createReadStream as BE}from"node:fs";import{mkdir as FE,readFile as zE,realpath as UE,stat as GE,writeFile as HE}from"node:fs/promises";import{basename as qE,dirname as dl,isAbsolute as jE,join as WE,relative as KE,resolve as sh,sep as $E}from"node:path";import{createInterface as VE}from"node:readline";var ah=H("fs-rpc"),Wi=$e("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function ch(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Wi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Wi} bytes`);let i=await dh(t.path,e);return await FE(dl(i),{recursive:!0}),await HE(i,t.content,"utf8"),ah.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function lh(t,e){let r=await dh(t.path,e),i=await GE(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Wi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Wi} bytes`);let c;if(o&&i.size>Wi)c=await JE(r,t.line??1,t.limit);else{let d=await zE(r,"utf8");if(o){let u=d.split(`
102
- `),h=Math.max(0,(t.line??1)-1),p=typeof t.limit=="number"?h+t.limit:void 0;c=u.slice(h,p).join(`
103
- `)}else c=d}return ah.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function JE(t,e,r){let i=VE({input:BE(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(`
104
- `)}async function dh(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([oh(sh(e)),oh(sh(t))]),o=KE(r,i);if(ZE(o,$E,jE(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function ZE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function oh(t){let e=[],r=t;for(;r!==dl(r);)try{let i=await UE(r);return e.length?WE(i,...e.reverse()):i}catch{e.push(qE(r)),r=dl(r)}return t}te();var uh=H("prompt-multimodal"),fh=10*1024*1024,YE=15e3,XE=6;async function hh(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 QE(d))}}let o=Array.from({length:Math.min(XE,t.length)},()=>i());return await Promise.all(o),e}function xh(t){return t.some(e=>e.type==="image")}async function QE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Di(e.uri))return t;try{let{buf:r,contentType:i}=await tb(e.uri),o=e.mimeType||eb(i)||"application/octet-stream";return uh.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 uh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function eb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function tb(t){let e=new AbortController,r=setTimeout(()=>e.abort(),YE);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>fh)throw new Error(`image too large: ${o.byteLength} bytes (max ${fh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}cn();qe();te();var $=H("core"),rb=3e4,ib=/^(boe|ppe)_[A-Za-z0-9_-]+$/,sb="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",ob="\u5BA1\u6279\u5DF2\u8D85\u65F6",ab=3e4,So=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Or;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=ih(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}),Hi(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(Sn(o,{code:Z.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:Z.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:Z.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(ho(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&&ib.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,Z.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(Dr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Dr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Dr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Z.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(Sn(r,zi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new T("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new T("AGENT_NOT_FOUND",`agent not found: ${i}`);let 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 p=r._meta?.cozeTriggerMsgId,m=so(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,h,c,sb,p,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{$.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}=Pf(i);switch(r){case"session/new":{let c=cb();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=Vt(e)?Rf(i._meta):void 0;if(u!==void 0&&!In(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${nl(e.framework)}`);let h=await this.ensureRuntime(e,d);if(u!==void 0&&h.permissionMode===void 0&&(h.permissionMode=u,await this.persistSessionMapping(e)),h.replySeq=0,await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&h.permissionMode!==void 0&&h.permissionMode!==u){let v=h.permissionMode;h.permissionMode=u,await this.persistSessionMapping(e);try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(y){throw h.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),y}}let p=i._meta?.cozeTriggerMsgId;p?e.activeTriggers.set(h.acpSessionId,p):e.activeTriggers.delete(h.acpSessionId);let m=so(i._meta);if(m?e.activeGroupIds.set(h.acpSessionId,m):e.activeGroupIds.delete(h.acpSessionId),m&&h.cozeGroupId!==m&&(h.cozeGroupId=m,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&xh(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await hh(c.prompt);try{let v=await h.downstream.sessionPrompt({...c,sessionId:h.acpSessionId,prompt:_});return h.lastActiveAt=Date.now(),v}catch(v){if(v instanceof T&&v.code==="AGENT_APPROVAL_TIMEOUT"){let y=h.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),h.pendingPermission=void 0);let S=h.acpSessionId,I=S?e.activeTriggers.get(S):void 0,A=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,h,d,ob,I,A)}throw v}finally{if(e.activeTriggers.delete(h.acpSessionId),e.activeGroupIds.delete(h.acpSessionId),h.pendingPermission=void 0,h.reloadAfterTurn){h.reloadAfterTurn=!1;let v=h.downstream;v&&(h.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:h.acpSessionId}),v.stop("reload-after-turn").catch(y=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(y)})))}else h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,h=so(i._meta);if(!d)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Vt(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(!In(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${nl(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let p=e.sessions.get(d)??await this.ensureRuntime(e,d);if(p.permissionMode===u)return{};let m=p.permissionMode;if(p.permissionMode=u,await this.persistSessionMapping(e),p.downstream?.isAlive()&&p.acpSessionId)try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(_){throw p.permissionMode=m,await this.persistSessionMapping(e).catch(()=>{}),_}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,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){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 Vt(e)&&(c.permissionMode=e.framework==="claude-code"?al:q0),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(ut.GEN_MODEL_TOKEN,i,ab);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(Hi(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 h;try{h=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(p){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),p}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}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(p){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(p)}),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 p=await h.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,await this.persistSessionMapping(e)}}catch(p){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(p)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,p}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),Vt(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(p){$.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(p)})}}armIdleTimer(e,r,i){if(Hi(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(Pr("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(Pr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(h=>$.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){$.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(ub(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"&&Vt(e)){let m=d.currentModeId;In(e.framework,m)&&c.permissionMode!==m?(c.permissionMode=m,this.persistSessionMapping(e).catch(_=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof m=="string"&&!In(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},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let p=e.activeGroupIds.get(i);p&&(u.cozeGroupId=p),this.upstream.send(Pr("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:Z.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await ch(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await lh(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,zi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,h=u?e.activeTriggers.get(u):void 0,p={cozeAgentId:e.agentId};h&&(p.cozeTriggerMsgId=h);let m=u?e.activeGroupIds.get(u):void 0;m&&(p.cozeGroupId=m);let _=u?this.reverseSessionId(e,u):void 0,v=_?e.sessions.get(_):void 0;v&&(v.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let y={...c,..._?{sessionId:_}:{},_meta:p};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:_}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(S=>({optionId:S.optionId,kind:S.kind,name:S.name}))}),this.upstream.send(Bi(o,"session/request_permission",y)).catch(S=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(S)}),r.respondAgentRequestError(i.id,{code:Z.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"&&lb(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 fo(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=rb){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(Bi(o,e,r)).catch(h=>{let p=this.pendingBridge.get(o);p&&(clearTimeout(p.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&&Vt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ii(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(Sn(e,{code:r,message:i,data:{bridgeVersion:Ot}}))}};function cb(){return nb(16).toString("hex")}function lb(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 db=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function ub(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:o}=i;return db.some(c=>o.startsWith(c))}an();te();Oe();import{randomBytes as fb}from"node:crypto";import{createServer as hb}from"node:http";var xb=1e6,ph=H("ipc"),Io=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Q()}async start(){this.token=fb(32).toString("hex");let e=hb((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(),ph.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 on(this.paths.portFile,String(this.port)),await on(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Ki(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){Ki(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await pb(e)}catch(u){Ki(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);Ki(r,200,u??{ok:!0})}catch(u){ph.error("IPC handler failed",{key:o,err:String(u)}),Ki(r,500,{error:u instanceof Error?u.message:String(u)})}}};function Ki(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function pb(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>xb)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 Mv=Ut(dx(),1),Bv=Ut(Lo(),1),Fv=Ut(zr(),1),zv=Ut(El(),1),Uv=Ut(Sl(),1),Gv=Ut(Rl(),1),yx=Ut(Fo(),1),Hv=Ut(_x(),1);var Ex=yx.default;qe();te();var{FWS:i1}=Dx(),Pe=H("upstream.frontier"),Lx="application/json",Nx="none",s1=15e3;function o1(t){class e extends Ex{constructor(i){super(i,Mf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Pe.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(yd("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");Pe.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Pe.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ts=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Pe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Bf,...bn(this.opts.ppeOverride)},r=o1(e),i=zf(this.opts.urlOverride),o={url:i,ws:r,fpID:Nf,aID:oo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Lx,force:!0},payloadEncoding:{encoding:Nx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new i1(o),d=!1,u=null,h,p,m=new Promise((y,S)=>{h=y,p=S}),_=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?p(y):h())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Pe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&_();for(let S of this.connectHandlers)Promise.resolve(S({initial:y})).catch(I=>Pe.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Pe.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Pe.warn("frontier error",{code:y.code,msg:y.message}),_(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let v=this.opts.openTimeoutMs??s1;u=setTimeout(()=>{_(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await m}catch(y){try{c.close(1e3,"open failed")}catch(S){Pe.warn("fws close during start failure threw (ignored)",{err:String(S)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Pe.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Pe.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?(Pe.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;Mx(c)||Pe.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:Lx,payloadEncoding:Nx})}catch(u){throw Pe.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){Pe.debug("drop non-adapter frontier frame",{service:r});return}let i=l1(e);if(!i){Pe.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Pe.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Pe.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;Mx(c)||Pe.info("frontier frame in",{logid:c1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:a1(i)}),Promise.resolve(this.handler(o)).catch(d=>Pe.warn("frontier frame handler threw",{err:String(d)}))}};function Mx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Bx=2e3;function a1(t){return t.length<=Bx?t:`${t.slice(0,Bx)}...<truncated, total ${t.length} chars>`}function c1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function l1(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}}qe();te();var Ll=H("skill-publish"),d1="/api/marketplace/product/skill/publish_with_assets",u1=15e4;async function Fx(t,e={}){let i=`${kr(Cr(e.handshakeBase))}${d1}`,o=e.timeoutMs??u1,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",...bn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),o);Ll.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 p=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),m=p.headers.get("x-tt-logid")??"";if(!p.ok){let y=await p.text().catch(()=>"");throw new T("UPLOAD_FAILED",`skill publish HTTP ${p.status} logid=${m}: ${y.slice(0,200)}`)}let _=await p.json();if(Ll.info("skill publish response",{logid:m,httpStatus:p.status,code:_.code,msg:_.msg,dataSkillId:_.data?.skill_id??"",dataVersion:_.data?.version??""}),_.code!==void 0&&_.code!==0)throw new T("UPLOAD_FAILED",`skill publish code=${_.code} msg=${_.msg??"-"} logid=${m}`);let v={};return _.data?.skill_id!==void 0&&_.data.skill_id!==""&&(v.skillId=String(_.data.skill_id)),_.data?.version&&(v.version=_.data.version),Ll.info("skill publish ok",{logid:m,skillId:v.skillId??"",version:v.version??""}),v}catch(p){throw p instanceof T?p:p.name==="AbortError"?new T("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new T("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(h)}}te();var Nl=H("upstream.switchable"),$o=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Nl.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 Nl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Nl.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 Ml=H("upstream"),Wr=class{handler=null;async start(){Ml.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Ml.info("NoopUpstream stopped",{reason:e})}async send(e){Ml.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};qe();te();an();te();Oe();import{promises as f1}from"node:fs";var zx=H("pat-token-store");async function Vo(t=Q()){try{let r=(await f1.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(zx.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"&&zx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ns(t,e=Q()){if(!t)throw new Error("writePatToken: empty patToken");await on(e.patTokenFile,t,{mode:384})}Oe();Oe();import{promises as Jo}from"node:fs";import{join as h1}from"node:path";function x1(t,e){return`#!/bin/sh
100
+ `}function _b(t){if(t.includes(`
101
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var yb={path:"",version:"cloud-deployed"},q0="openclaw_gateway_unavailable",bb="openclaw_default_agent_missing";function j0(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 Eb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},vb=6e4,Ao=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??mb,this.createTimeoutMs=e.createTimeoutMs??vb,this.detectorFactory=e.detectorFactory??(()=>new $n),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Io({command:r})),this.openclawConfigDir=e.openclawConfigDir??dl(pb(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{de.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=dl(e,".env");if(await hb(r).then(c=>c.isFile()).catch(()=>!1)){de.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=wb({...process.env,...il(this.paths.agentEnvFile)});await on(r,o,{mode:384}),de.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),de.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await ke(e.agentId,this.paths).catch(()=>null),o=uo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")de.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(R=>de.warn("dispose stale agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")de.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(R=>de.warn("dispose drifted agent failed (ignored)",{err:String(R)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){de.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let R=await ke(e.agentId,this.paths).catch(()=>null);R&&(R.patToken=e.patToken,await Be(R,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){de.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let R=await ke(e.agentId,this.paths).catch(()=>null);R&&(R.modelInfo=e.modelInfo,await Be(R,this.paths))}return de.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ve(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),S=e.workspace??w??u.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,T=!1;try{o&&ll(e.framework)&&await cr(e.framework,_.signal);let R=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await cl(u.root,{recursive:!0}),await cl(S,{recursive:!0}),await cl(u.logs,{recursive:!0}),R(),h||await ur(S,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(x==="cloud"?await Oa(S,"cloud"):await Oa(S,"local",ul)),R();let P=i,b=jf({model:e.model??P?.model}),C=Pf(e._meta)??P?.accountId,L=e.patToken??P?.patToken,z=x==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new vo({agentId:e.agentId,framework:e.framework,workspace:S,model:b.model??Et,deployType:x,...C?{accountId:C}:{},...L?{patToken:L}:{},...z?{modelInfo:z}:{}}),I.status="ok",P?.sessions){let V=x==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Z,se]of Object.entries(P.sessions)){let oe={acpSessionId:se.acpSessionId,modelToken:se.modelToken,tokenGeneratedAt:se.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?se.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",de.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Z,framework:e.framework,fallback:oe.permissionMode})):In(e.framework,se.permissionMode)?oe.permissionMode=se.permissionMode:de.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Z,framework:e.framework,value:se.permissionMode}):se.permissionMode!==void 0&&de.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Z,framework:e.framework,deployType:x}),se.cozeGroupId&&(oe.cozeGroupId=se.cozeGroupId),I.sessions.set(Z,oe)}let re=Object.keys(P.sessions).length;re>0&&de.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:re})}this.registry.register(I),T=!0;let B={agentId:e.agentId,framework:e.framework,workspace:S,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:b.model};x==="cloud"&&(B.deployType="cloud"),C&&(B.accountId=C),L&&(B.patToken=L),z&&(B.modelInfo=z),P?.skills&&(B.skills=P.skills),P?.agentName&&(B.agentName=P.agentName),P?.description&&(B.description=P.description),B.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Lt,e.framework==="openclaw"&&x==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,S)):de.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let J=e.initialSkills??[];if(J.length>0){let V=[...B.skills??[]],re=new Map(V.map((oe,D)=>[oe.skillId,D])),Z=await Promise.allSettled(J.map(oe=>go({agentId:e.agentId,workspace:S,framework:e.framework,skill:oe}))),se=0;for(let[oe,D]of Z.entries()){let G=J[oe];G&&(D.status==="fulfilled"?(mo(V,re,D.value),se++):de.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(D.reason)}))}se>0&&(B.skills=V,de.info("initialSkills installed",{agentId:e.agentId,installed:se,requested:J.length}))}return await Be(B,this.paths),de.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:x}),{ok:!0,agentId:e.agentId,workspace:S,framework:e.framework}}catch(R){throw de.error("agent create failed, rolling back",{agentId:e.agentId,err:String(R)}),T&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await xb(u.root,{recursive:!0,force:!0}).catch(P=>de.warn("rm agent dir failed (ignored)",{err:String(P)})),R instanceof k?R:new k("AGENT_SPAWN_FAILED",String(R),{cause:R})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&ll(e.framework))u=yb;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);ll(e.framework)&&!ms(e.framework)&&(de.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await cr(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{let m=e.sessions.get(i),w=Vt(e)?m?.permissionMode??W0:"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(Eb),h}catch(m){let w=h instanceof Ot?h.getStderrTail():[];throw w.length>0&&de.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof k?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 k("AGENT_ENV_NOT_READY",j0(o),{cause:{reason:q0}})}catch(o){de.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};de.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 de.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:bb}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new k("AGENT_ENV_NOT_READY",j0(r),{cause:{reason:q0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,x=al(o);if(r.deployType==="local"){let S=await this.ensureOpenclawDefaultAgent();return new Br({command:u,cwd:S.workspace,agentId:S.id,sessionName:x})}let h=await H0(),m=i?Jf(i,c,l):null,w;if(m){let S=$c(o),v=m.models[0]?.id??Et,I=`${S}/${v}`;if(!this.ensuredProviders.has(I)){let T=this.getOpenclawConfig();await T.ensureProvider(S,m),await T.addModelToAllowlist(I),this.ensuredProviders.add(I)}w=I}return new Br({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:x,...h?{gatewayToken:h}:{},...w?{slashModelOnStart:w}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let i of e.sessions.keys()){let o=$c(i),c=`${o}/${e.model}`,l=!0;try{await r.removeProvider(o)}catch(u){l=!1,de.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:o,err:String(u)})}try{await r.removeModelFromAllowlist(c)}catch(u){l=!1,de.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:c,err:String(u)})}l&&this.ensuredProviders.delete(c)}}};import{randomUUID as Z0}from"node:crypto";import{promises as Cb}from"node:fs";import{basename as X0}from"node:path";je();ne();import{promises as Sb}from"node:fs";import{basename as Ib}from"node:path";var $0=H("file-upload"),Ab="/api/coze_claw/file/agent_upload",Tb=6e4;async function V0(t,e={}){let i=`${Rr(Cr(e.handshakeBase))}${Ab}`,o=e.timeoutMs??Tb,c=await Sb.readFile(t.path),l=new FormData;l.append("agent_id",t.agentId),l.append("session_id",t.sessionId),l.append("file_name",t.name),l.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...En(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},x=new AbortController,h=setTimeout(()=>x.abort(),o);$0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let m=await fetch(i,{method:"POST",headers:u,body:l,signal:x.signal}),w=m.headers.get("x-tt-logid")??"";if(!m.ok){let v=await m.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${m.status} logid=${w}: ${v.slice(0,200)}`)}let S=await m.json();if(S.code!==void 0&&S.code!==0)throw new k("UPLOAD_FAILED",`upload code=${S.code} msg=${S.msg??"-"} logid=${w}`);let _=S.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(S).slice(0,200)}`);return $0.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(m){throw m instanceof k?m:m.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Ib(t.path)}`):new k("UPLOAD_FAILED",String(m),{cause:m})}finally{clearTimeout(h)}}je();ne();import{extname as kb}from"node:path";var Rb={".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 J0(t){let e=kb(t).toLowerCase();return Rb[e]??"application/octet-stream"}Le();var To=H("agent-send"),Y0=50*1024*1024;function Q0(t,e,r){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new k("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function ex(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&&(To.warn("sendAgentFileUpdate failed, retrying",{attempt:x+1,err:String(h)}),await new Promise(m=>setTimeout(m,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function tx(t,e){let{session:r,runtime:i}=Q0(e.core,t.agentId,t.sessionId);if(!await ci(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await Cb.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>Y0)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${Y0}`);let c=await J0(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let l=t.name??X0(t.path),u;try{u=await V0({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(h){throw To.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:h instanceof k?h.code:"UNKNOWN",message:h instanceof Error?h.message:String(h)}),h}let x={sessionUpdate:"agent_file",messageId:Z0(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:l,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await ex(e,r,i,t.sessionId,x,"agent file uploaded to cloud but sendAgentFileUpdate failed"),To.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function nx(t,e){let{session:r,runtime:i}=Q0(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??X0(t.path),c={sessionUpdate:"group_file",messageId:Z0(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ex(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),To.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 rx(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let l=r[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}sn();$t();ne();var Nt=H("coze-cli-installer"),ix="@coze/cli@latest",Db="coze",sx="0.1.8",Pb=5e3,Lb=5e3,Ob=9e4,ox=1e4,Vi=null,ko=!1;async function xl(t,e={}){if(ko)return;if(Vi)return Vi;let r=e.exec??Bf;return Vi=(async()=>{try{let i=await Nb(Db,r),o=!1;if(i){let l=await Mb(r);if(l===void 0)Nt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(rx(l,sx))Nt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:sx}),o=!0;else{Nt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),ko=!0;return}}let c=o?"upgrade-only":"full";Nt.info("coze-cli install start",{package:ix,mode:c});try{await r("npm",["i","-g","--prefer-online",ix],{timeout:Ob,maxBuffer:10*1024*1024}),Nt.info("coze-cli install ok")}catch(l){Nt.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(o){ko=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:ox}),Nt.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Nt.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:ox}),Nt.info("coze auth login ok")}catch(l){Nt.warn("coze auth login failed",{err:String(l)});return}ko=!0}finally{Vi=null}})(),Vi}async function Nb(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:Pb});return Pa(i)}catch{return}}async function Mb(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:Lb});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}an();Le();var Bb=10*6e4;function ax(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Bb:e}function Ro(t){return lr(t??Q().configFile)}function Ji(t,e){return dr(e??Q().configFile,t)}import{randomBytes as rE}from"node:crypto";sr();je();ne();import{createReadStream as zb}from"node:fs";import{mkdir as Fb,readFile as Ub,realpath as Gb,stat as Hb,writeFile as qb}from"node:fs/promises";import{basename as jb,dirname as hl,isAbsolute as Wb,join as Kb,relative as $b,resolve as cx,sep as Vb}from"node:path";import{createInterface as Jb}from"node:readline";var dx=H("fs-rpc"),Yi=$e("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function ux(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Yi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Yi} bytes`);let i=await xx(t.path,e);return await Fb(hl(i),{recursive:!0}),await qb(i,t.content,"utf8"),dx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function fx(t,e){let r=await xx(t.path,e),i=await Hb(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Yi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Yi} bytes`);let c;if(o&&i.size>Yi)c=await Yb(r,t.line??1,t.limit);else{let l=await Ub(r,"utf8");if(o){let u=l.split(`
102
+ `),x=Math.max(0,(t.line??1)-1),h=typeof t.limit=="number"?x+t.limit:void 0;c=u.slice(x,h).join(`
103
+ `)}else c=l}return dx.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function Yb(t,e,r){let i=Jb({input:zb(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let x of i)if(u>=o&&u<c&&l.push(x),u++,u>=c)break}finally{i.close()}return l.join(`
104
+ `)}async function xx(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([lx(cx(e)),lx(cx(t))]),o=$b(r,i);if(Zb(o,Vb,Wb(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Zb(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function lx(t){let e=[],r=t;for(;r!==hl(r);)try{let i=await Gb(r);return e.length?Kb(i,...e.reverse()):i}catch{e.push(jb(r)),r=hl(r)}return t}ne();var hx=H("prompt-multimodal"),px=10*1024*1024,Xb=15e3,Qb=6;async function gx(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,l=t[c];l!==void 0&&(e[c]=await eE(l))}}let o=Array.from({length:Math.min(Qb,t.length)},()=>i());return await Promise.all(o),e}function mx(t){return t.some(e=>e.type==="image")}async function eE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Bi(e.uri))return t;try{let{buf:r,contentType:i}=await nE(e.uri),o=e.mimeType||tE(i)||"application/octet-stream";return hx.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 hx.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function tE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function nE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Xb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>px)throw new Error(`image too large: ${o.byteLength} bytes (max ${px})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}cn();je();ne();var $=H("core"),iE=3e4,sE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,oE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",aE="\u5BA1\u6279\u5DF2\u8D85\u65F6",cE=3e4,Co=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Or;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=ax(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){$.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&$.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,l)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),$i(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(Sn(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(l=>$.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(_o(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&&sE.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Lr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Lr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Lr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(o){$.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(Sn(r,ji(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let x=o.sessions.get(c);if(x?.pendingPermission){let h=r._meta?.cozeTriggerMsgId,m=fo(r._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,x,c,oE,h,m)}}let l=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()-l,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Of(i);switch(r){case"session/new":{let c=lE();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,l=c.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Vt(e)?Lf(i._meta):void 0;if(u!==void 0&&!In(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${ol(e.framework)}`);let x=await this.ensureRuntime(e,l);if(u!==void 0&&x.permissionMode===void 0&&(x.permissionMode=u,await this.persistSessionMapping(e)),x.replySeq=0,await this.ensureDownstream(e,l,x),!x.downstream||!x.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&x.permissionMode!==void 0&&x.permissionMode!==u){let S=x.permissionMode;x.permissionMode=u,await this.persistSessionMapping(e);try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(_){throw x.permissionMode=S,await this.persistSessionMapping(e).catch(()=>{}),_}}let h=i._meta?.cozeTriggerMsgId;h?e.activeTriggers.set(x.acpSessionId,h):e.activeTriggers.delete(x.acpSessionId);let m=fo(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&&mx(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let w=await gx(c.prompt);try{let S=await x.downstream.sessionPrompt({...c,sessionId:x.acpSessionId,prompt:w});return x.lastActiveAt=Date.now(),S}catch(S){if(S instanceof k&&S.code==="AGENT_APPROVAL_TIMEOUT"){let _=x.pendingPermission;_&&(_.downstream.respondAgentRequest(_.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(_.upstreamId),x.pendingPermission=void 0);let v=x.acpSessionId,I=v?e.activeTriggers.get(v):void 0,T=v?e.activeGroupIds.get(v):void 0;return $.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,x,l,aE,I,T)}throw S}finally{if(e.activeTriggers.delete(x.acpSessionId),e.activeGroupIds.delete(x.acpSessionId),x.pendingPermission=void 0,x.reloadAfterTurn){x.reloadAfterTurn=!1;let S=x.downstream;S&&(x.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:x.acpSessionId}),S.stop("reload-after-turn").catch(_=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(_)})))}else x.downstream?.isAlive()&&this.armIdleTimer(e,l,x)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let x=e.getSessionQueue(l);x.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:x.size}),x.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,l=c.sessionId,u=c.modeId,x=fo(i._meta);if(!l)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Vt(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!In(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${ol(e.framework)}`);if(x)return await this.handleGroupSetMode(e,x,u);let h=e.sessions.get(l)??await this.ensureRuntime(e,l);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:l,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[l,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(o.length===0)return $.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 l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,x=l.runtime.acpSessionId;u?.isAlive()&&x&&c.push({downstream:u,acpSessionId:x,oldMode:l.oldMode,runtime:l.runtime})}for(let l of c)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let 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 Vt(e)&&(c.permissionMode=e.framework==="claude-code"?ul:K0),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ft.GEN_MODEL_TOKEN,i,cE);if(!o?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return o.modelToken}catch(o){throw o instanceof k&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new k("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,r,i){if($i(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let x;try{x=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(h){throw i.spawnFailCount=l+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),Vt(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($i(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 l=e.activeTriggers.get(r.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Pr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Pr("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(fE(r)){$.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=r.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&Vt(e)){let m=l.currentModeId;In(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"&&!In(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(Pr("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:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},l=await ux(c,o);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await fx(c,o);r.respondAgentRequest(i.id,l)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,ji(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,S=w?e.sessions.get(w):void 0;S&&(S.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let _={...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(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(Hi(o,"session/request_permission",_)).catch(v=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),r.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?($.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&dE(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 wo(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),l=e.get(c);if(l)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=iE){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(Hi(o,e,r)).catch(x=>{let h=this.pendingBridge.get(o);h&&(clearTimeout(h.timer),this.pendingBridge.delete(o)),l(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&&Vt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await li(e.agentId,r,this.paths)}catch(r){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(Sn(e,{code:r,message:i,data:{bridgeVersion:Lt}}))}};function lE(){return rE(16).toString("hex")}function dE(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 uE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function fE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:o}=i;return uE.some(c=>o.startsWith(c))}an();ne();Le();import{randomBytes as xE}from"node:crypto";import{createServer as hE}from"node:http";var pE=1e6,_x=H("ipc"),Do=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Q()}async start(){this.token=xE(32).toString("hex");let e=hE((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(),_x.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 on(this.paths.portFile,String(this.port)),await on(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 l=null;if(e.method==="POST")try{l=await gE(e)}catch(u){Zi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);Zi(r,200,u??{ok:!0})}catch(u){_x.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 gE(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>pE)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 Bv=Ut(hh(),1),zv=Ut(Uo(),1),Fv=Ut(Ur(),1),Uv=Ut(Il(),1),Gv=Ut(kl(),1),Hv=Ut(Ol(),1),vh=Ut(jo(),1),qv=Ut(Eh(),1);var Sh=vh.default;je();ne();var{FWS:sS}=Nh(),De=H("upstream.frontier"),Bh="application/json",zh="none",oS=15e3;function aS(t){class e extends Sh{constructor(i){super(i,Ff,{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(vd("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let l=Buffer.from(c.slice(0,128)).toString("hex");De.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){De.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var os=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:Uf,...En(this.opts.ppeOverride)},r=aS(e),i=Hf(this.opts.urlOverride),o={url:i,ws:r,fpID:zf,aID:xo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Bh,force:!0},payloadEncoding:{encoding:zh,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new sS(o),l=!1,u=null,x,h,m=new Promise((_,v)=>{x=_,h=v}),w=_=>{l||(l=!0,u&&(clearTimeout(u),u=null),_?h(_):x())};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 v of this.connectHandlers)Promise.resolve(v({initial:_})).catch(I=>De.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=_=>{this.opened=!1,De.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},c.onerror=_=>{De.warn("frontier error",{code:_.code,msg:_.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},c.onmessage=_=>this.handleMessage(_),this.fws=c;let S=this.opts.openTimeoutMs??oS;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${S}ms (handshake or upgrade slow)`))},S),await c.connect();try{await m}catch(_){try{c.close(1e3,"open failed")}catch(v){De.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let 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 k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(De.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;Fh(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:Bh,payloadEncoding:zh})}catch(u){throw De.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let 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=dS(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(l){De.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;Fh(c)||De.info("frontier frame in",{logid:lS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:cS(i)}),Promise.resolve(this.handler(o)).catch(l=>De.warn("frontier frame handler threw",{err:String(l)}))}};function Fh(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Uh=2e3;function cS(t){return t.length<=Uh?t:`${t.slice(0,Uh)}...<truncated, total ${t.length} chars>`}function lS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function dS(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}}je();ne();var zl=H("skill-publish"),uS="/api/marketplace/product/skill/publish_with_assets",fS=15e4;async function Gh(t,e={}){let i=`${Rr(Cr(e.handshakeBase))}${uS}`,o=e.timeoutMs??fS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let l={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...En(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,x=setTimeout(()=>u.abort(),o);zl.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...l,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let h=await fetch(i,{method:"POST",headers:l,body:c,signal:u.signal}),m=h.headers.get("x-tt-logid")??"";if(!h.ok){let _=await h.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${h.status} logid=${m}: ${_.slice(0,200)}`)}let w=await h.json();if(zl.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 k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${m}`);let S={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(S.skillId=String(w.data.skill_id)),w.data?.version&&(S.version=w.data.version),zl.info("skill publish ok",{logid:m,skillId:S.skillId??"",version:S.version??""}),S}catch(h){throw h instanceof k?h:h.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(h),{cause:h})}finally{clearTimeout(x)}}ne();var Fl=H("upstream.switchable"),Qo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Fl.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 Fl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Fl.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var Ul=H("upstream"),Kr=class{handler=null;async start(){Ul.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Ul.info("NoopUpstream stopped",{reason:e})}async send(e){Ul.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)}};je();ne();an();ne();Le();import{promises as xS}from"node:fs";var Hh=H("pat-token-store");async function ea(t=Q()){try{let r=(await xS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(Hh.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"&&Hh.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function as(t,e=Q()){if(!t)throw new Error("writePatToken: empty patToken");await on(e.patTokenFile,t,{mode:384})}Le();Le();import{promises as ta}from"node:fs";import{join as hS}from"node:path";function pS(t,e){return`#!/bin/sh
105
105
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
106
- `}function p1(t,e){return`@echo off\r
106
+ `}function gS(t,e){return`@echo off\r
107
107
  "${e}" "${t}" %*\r
108
- `}async function Ux(t,e=Q()){let r=e.binDir;await Jo.mkdir(r,{recursive:!0});let i=h1(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?p1(t,o):x1(t,o);return await Jo.readFile(i,"utf8").catch(()=>null)===c||(await Jo.writeFile(i,c,"utf8"),process.platform!=="win32"&&await Jo.chmod(i,493)),r}te();Oe();import{execSync as Gx}from"node:child_process";import{readFileSync as Hx,unlinkSync as g1}from"node:fs";import{mkdir as m1,open as w1,readFile as qx,unlink as Bl,writeFile as _1}from"node:fs/promises";import{dirname as y1}from"node:path";var E1=H("single-instance"),b1=t=>new Promise(e=>setTimeout(e,t)),Zo=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Q().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ui(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&E1.warn("removing stale pid file",{stalePid:i}),await _1(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 qx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Bl(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 qx(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 m1(y1(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await w1(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 b1(this.claimLockIntervalMs);continue}await Bl(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Bl(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=Hx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Lr)||r.includes("lib/index.js"))}catch{}try{let r=Gx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Lr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Gx(`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{Hx(this.pidFile,"utf8").trim()===String(this.selfPid)&&g1(this.pidFile)}catch{}})}};Yo();te();var Qn=H("daemon.upstream-watchdog"),R1=12e4,P1=9e5,D1=3e4;function zl(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var Xo=class{constructor(e){this.opts=e;this.softMs=e.softMs??zl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",R1),this.hardMs=e.hardMs??zl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",P1),this.intervalMs=e.intervalMs??zl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",D1),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),Qn.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&&Qn.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&&Qn.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,Qn.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){Qn.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,Qn.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>Qn.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=H("daemon");async function Kx(){let t=Q();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){wd({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Ve(P,t).logs,listAgentIds:()=>fs(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
108
+ `}async function qh(t,e=Q()){let r=e.binDir;await ta.mkdir(r,{recursive:!0});let i=hS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?gS(t,o):pS(t,o);return await ta.readFile(i,"utf8").catch(()=>null)===c||(await ta.writeFile(i,c,"utf8"),process.platform!=="win32"&&await ta.chmod(i,493)),r}ne();Le();import{execSync as jh}from"node:child_process";import{readFileSync as Wh,unlinkSync as mS}from"node:fs";import{mkdir as wS,open as _S,readFile as Kh,unlink as Gl,writeFile as yS}from"node:fs/promises";import{dirname as bS}from"node:path";var ES=H("single-instance"),vS=t=>new Promise(e=>setTimeout(e,t)),na=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Q().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Wi(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&&ES.warn("removing stale pid file",{stalePid:i}),await yS(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 Kh(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Gl(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 Kh(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 wS(bS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await _S(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(r);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await vS(this.claimLockIntervalMs);continue}await Gl(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Gl(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=Wh(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Nr)||r.includes("lib/index.js"))}catch{}try{let r=jh(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Nr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=jh(`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{Wh(this.pidFile,"utf8").trim()===String(this.selfPid)&&mS(this.pidFile)}catch{}})}};ra();ne();var Qn=H("daemon.upstream-watchdog"),DS=12e4,PS=9e5,LS=3e4;function ql(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ia=class{constructor(e){this.opts=e;this.softMs=e.softMs??ql("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",DS),this.hardMs=e.hardMs??ql("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",PS),this.intervalMs=e.intervalMs??ql("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",LS),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?.(),Qn.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&&Qn.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&&Qn.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,Qn.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){Qn.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,Qn.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>Qn.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 W=H("daemon");async function Jh(){let t=Q();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){bd({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:D=>Ve(D,t).logs,listAgentIds:()=>ws(t)});try{let{writeFileSync:D}=await import("node:fs");D(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
109
109
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
110
110
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
111
- `)}catch{}}let e=new Zo({processTitle:Lr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await vo(),o=i??{};ds({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let c=new $o(new Wr),d=null,u=new So({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,G,K,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,G,K,ee)}}),h=new yo({paths:t,config:o,registry:u});d=h;let p,m,_=null,v={},y,S=null,I=null,A=null,k=new An;function D(P,G){return k.enqueue(()=>R(P,G))}function E(){I||(I=new Xo({isConnected:()=>c.isConnected()&&!(S?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:P=>{if(process.env[rs]==="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)}})),I.start()}async function R(P,G){let K=P,ee=K?.privatecode;if(!ee)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Xe=Li(K.env),xe=K.handshake_url,pe=K.frontier_url,It=Wx(K.env,xe,pe);if(A=K,!G?.force&&p===ee&&m===It){let we=await O1(t);return u.agents.size===0&&we?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ea(t,h).catch(Ie=>q.warn("connect-noop auto-revive error (ignored)",{err:String(Ie)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let xt=!!p&&p!==ee,en=m!==void 0&&m!==It,zt=xt||en,tn=await zc({privatecode:ee,...xe?{endpoint:xe}:{},ppeOverride:Xe});if(zt){q.warn("connect config switched, resetting agents",{pcChanged:xt,envChanged:en,previousPc:p?Qo(p):"",nextPc:Qo(ee)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Wr,"connect switch").catch(()=>{})}_=tn.deviceId,ds({deviceId:_,pid:process.pid}),ll({patToken:ee,env:K.env}).catch(we=>q.warn("coze-cli setup error (ignored)",{err:String(we)}));let Zr=new ts({handshake:tn,privatecode:ee,...pe?{urlOverride:pe}:{},ppeOverride:Xe,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await c.swap(Zr,"connect"),p=ee,m=It,v=Xe,y=xe,K.mock_scenario!==void 0&&(u.setMockScenario(K.mock_scenario),q.info("mock scenario set",{scenario:K.mock_scenario})),S||(S=new Mi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(we=>q.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:J})),S.start(),E(),zt&&ea(t,h).catch(we=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),ns(ee,t).catch(we=>q.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),q.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>h.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let L={},B=new co({agents:u.agents,publishSkillToMarketplace:async P=>{let G=u.agents.get(P.agentId)?.patToken??p;if(!G)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Fx({patToken:G,zip:P.zip,...P.skillId?{skillId:P.skillId}:{},skillName:P.skillName,...P.description?{description:P.description}:{},agentId:P.agentId,...P.accountId?{accountId:P.accountId}:{}},{handshakeBase:y,ppeOverride:v})},disposeAndMarkDisconnected:async(P,G)=>{let K=u.agents.get(P);if(K){await h.cleanupOpenclawSessionProviders(K).catch(Xe=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Xe)}));let ee=!0;try{await K.dispose(`disconnect: ${G}`)}catch(Xe){ee=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Xe)}),K.status="error"}ee&&(K.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,G)=>{let K=u.agents.get(P);K&&(await h.cleanupOpenclawSessionProviders(K).catch(ee=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(ee)})),await K.dispose(`delete: ${G}`).catch(ee=>q.warn("dispose during delete failed (ignored)",{agentId:P,err:String(ee)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!L.ref)throw new Error("agent-detail-sync not initialized yet");await L.ref.syncOne(P)},cleanupOpenclawProviders:async P=>{await h.cleanupOpenclawSessionProviders(P)},openclawRepair:async(P,G)=>{await h.openclawRepair(P,G)},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>B.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>B.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>B.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>B.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>B.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>B.getFileContent(P.params)),u.registerExtension("_agent/update",P=>B.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>B.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>B.switchModel(P.params)),u.registerExtension("_agent/reset",P=>B.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>B.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>B.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>B.upgradeBridge(P.params));let M=new ps({paths:t,handlers:B,agentManager:h,sendDetail:P=>u.sendRequest("_agent/detail",P)});L.ref=M;let J=async P=>{await Promise.allSettled(P.map(async G=>{try{await B.disconnectAgent({agentId:G.agentId,reason:`auth_failure: code=${G.code} ${G.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:G.agentId,code:G.code,message:G.message})}catch(K){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:G.agentId,err:String(K)})}}))};c.onConnect(({initial:P})=>{q.info("frontier upstream connected, triggering detail sync",{initial:P}),M.syncAll(P?"initial-connect":"reconnect").catch(G=>q.warn("detail sync top-level error (ignored)",{err:String(G)}))});let V=new Io({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let P=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[rs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let G=P,K=G?.privatecode,ee=G?.pairing_code;if(!K||!ee)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Xe=Li(G.env),xe=G.handshake_url,pe=G.frontier_url,It=Wx(G.env,xe,pe),xt=!!p&&p!==K,en=m!==void 0&&m!==It,zt=xt||en,tn=await zc({privatecode:K,...xe?{endpoint:xe}:{},ppeOverride:Xe});if(zt){q.warn("pair config switched, resetting agents",{pcChanged:xt,envChanged:en,previousPc:p?Qo(p):"",nextPc:Qo(K),previousEnvKey:m??"",nextEnvKey:It});for(let Ie of[...u.agents.values()])await Ie.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ie.agentId);u.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Wr,"pair switch").catch(()=>{})}_=tn.deviceId,ds({deviceId:_,pid:process.pid}),ll({patToken:K,env:G.env}).catch(Ie=>q.warn("coze-cli setup error (ignored)",{err:String(Ie)}));let Zr=new ts({handshake:tn,privatecode:K,...pe?{urlOverride:pe}:{},ppeOverride:Xe,getPatTokenForAgent:Ie=>u.agents.get(Ie)?.patToken});await c.swap(Zr,"pair");try{let Ie=new $n;o.frameworksCache=await Ie.detectAll(),await ji(o),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ie){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ie)})}let we=Object.keys(o.frameworksCache??{});try{let Ie=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:K,frameworks:we,_meta:{cozeDeviceId:_}});q.info("_agent/pair ok",{pairResult:Ie}),p=K,m=It,v=Xe,y=xe,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),q.info("mock scenario set",{scenario:G.mock_scenario})),ns(K,t).catch(De=>q.warn("writePatToken after /pair failed (ignored)",{err:String(De)})),S||(S=new Mi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(De=>q.warn("detailSync.retryPending failed (ignored)",{err:String(De)})),onAuthFailures:J})),S.start(),E(),zt&&ea(t,h).catch(De=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(De)}));let er;return G.agent_id&&(er=await N1(G.agent_id,t,h,De=>u.sendRequest("_agent/detail",De),K).catch(De=>(q.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(De)}),{ok:!1,agentId:G.agent_id??"",note:String(De)}))),{ok:!0,note:"paired with cloud",...er?{agent:er}:{}}}catch(Ie){return q.error("_agent/pair failed",{err:String(Ie)}),{ok:!1,note:`pair failed: ${String(Ie)}`}}}},{method:"POST",path:"/connect",handler:P=>D(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let G=P;return{ok:!0,result:await h.createAgent(G)}}},{method:"POST",path:"/agent/send",handler:async P=>{let G=P;if(!G?.agentId||!G?.sessionId||!G?.kind||!G?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!p)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let K=G;return await(K.groupFile?Q0:X0)(K,{core:u,patToken:p,handshakeBase:y,ppeOverride:v})}catch(K){if(K instanceof T)return{ok:!1,code:K.code,message:K.message};throw K}}},{method:"POST",path:"/reload",handler:async P=>{let G=P?.agent_id,K=await u.reloadAgents(G);return q.info("IPC /reload: recycled agent subprocesses",{agentId:G??"(all)",recycled:K}),{ok:!0,recycled:K}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{se.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ne,token:Y}=await V.start();try{await Ux(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(),M1({paths:t,core:u,agentManager:h,detectAll:async()=>(o.frameworksCache=await new $n().detectAll(),await ji(o),o.frameworksCache)}).catch(P=>q.warn("startup warmup error (ignored)",{err:String(P)})),kd().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(sn(),Ad));for(let G of["claude-code","codex"]){let K=await P(G);K&&q.info("acp wrapper version",{framework:G,version:K})}}).catch(P=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let ie=null,se={port:ne,token:Y,core:u,ipc:V,shutdown(P){return ie||(q.info("daemon shutdown",{reason:P}),ie=(async()=>{S?.stop(),I?.stop(),await u.stop(P),await V.stop(),await e.release()})(),ie)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{se.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>g0()),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}
112
- `)}catch{}process.exit(1)}),q.info("daemon ready",{port:ne,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),F1({cliSpawned:process.env[rs]==="1",readPatToken:()=>Vo(t),connect:D}).catch(P=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),se}async function O1(t){return fs(t).length>0}function Qo(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Wx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function L1(t,e){let r=fs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(cn(),xs));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 N1(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(cn(),xs)),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`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let m=$x(d),_={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(_),{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 T("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(h);let p=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:p?"cloud agent acknowledged":"created from cloud detail"}}async function M1(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 L1(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ea(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await B1(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ea(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(()=>(cn(),xs));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(p){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(p)}),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 p=$x(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...p?{_meta:p}:{}},{revive:!0}),c+=1}catch(p){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(p)}),d+=1}}return q.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function B1(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 r0(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 F1(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 $x(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Yo();Oe();import{readFile as Vx}from"node:fs/promises";var Qt=class{paths;constructor(e){this.paths=e??Q()}async probe(e=1e3){let r=await ta(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}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:U1(i)}}}async request(e){let r=await ta(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:z1(h)}}finally{clearTimeout(d)}}};async function ta(t){try{let[e,r]=await Promise.all([Vx(t.portFile,"utf8"),Vx(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=r.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function z1(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function U1(t){return t instanceof Error?t.message:String(t)}$t();te();ir();import{spawn as G1}from"node:child_process";import{userInfo as Zx}from"node:os";var Ul="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",H1=new Set(["bash","zsh","sh","dash","ksh"]),Jx=$e("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),q1=2e3;function j1(t,e=Ul){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let d of o.split(`
113
- `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function W1(){let t=(process.env.SHELL??"").trim()||(Zx().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return H1.has(e)?t:null}function K1(t){return new Promise(e=>{let r=`printf '%s' '${Ul}'; env; printf '%s' '${Ul}'`,i;try{i=G1(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Zx().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(p),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"),Jx),p=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},Jx+q1)})}async function Gl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=W1();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??K1)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=j1(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Oe();function Cn(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}}sn();import{chmod as $1,copyFile as Yx,mkdir as Qx,readFile as na,rename as Xx,rm as Hl,stat as ep,writeFile as V1}from"node:fs/promises";import{homedir as iD}from"node:os";import{dirname as J1,join as Kr,resolve as ql,sep as is}from"node:path";import{fileURLToPath as Z1}from"node:url";$t();te();Oe();var jl=H("dist-install");function Y1(t){let e=Z1(t),r=J1(e),i=`${is}src${is}`;if(r.includes(i)||r.endsWith(`${is}src${is}cli`))return null;let o=ql(r,"index.js"),c=ql(r,"..","package.json");return{dist:o,pkgJson:c}}async function Kl(t={}){let e=t.paths??Q(),r=Y1(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let v=JSON.parse(await na(o,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){return jl.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=ti.map(v=>`${v}@${d[v]??"latest"}`),h=await vo(e.configFile)??{},p=h.libVersion,m=await na(e.libEntry).then(()=>!0).catch(()=>!1),_=p===c;if(_&&m&&await Wl(e))return{kind:"already-current",libVersion:c};if(!_||!m){await Qx(e.libDir,{recursive:!0}),await Yx(i,e.libEntry),await Yx(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=ql(e.libDir,"package.json"),y=`${JSON.stringify({type:"module"},null,2)}
114
- `;await na(v,"utf8").catch(()=>null)!==y&&await V1(v,y)}return(!_||!await Wl(e))&&await(t.installWrappers??X1)(e,u),h.libVersion=c,await ji(h,e.configFile),jl.info("dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:c}),_&&m?{kind:"already-current",libVersion:c}:p?{kind:"version-changed",fromVersion:p,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Wl(t){for(let e of ti){let r=Kr(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await ep(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function X1(t,e){await tS(t.installLock,async()=>{if(await Wl(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${is}.staging-${process.pid}-${r}`,o=Kr(i,"node_modules"),c=Kr(t.libDir,"node_modules");try{await Qx(i,{recursive:!0}),await Q1(e,i),await eS(o);let d=`${c}.trash-${r}`;await Xx(c,d).catch(()=>{}),await Xx(o,c),await Hl(d,{recursive:!0,force:!0}).catch(()=>{}),jl.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await Hl(i,{recursive:!0,force:!0}).catch(()=>{})}})}function Q1(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=nt("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 eS(t){for(let e of ti){let r=Kr(t,...e.split("/")),i=JSON.parse(await na(Kr(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=Kr(t,".bin",o),d=await ep(c);process.platform!=="win32"&&!(d.mode&73)&&await $1(c,d.mode|73).catch(()=>{})}}async function tS(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 Hl(t,{force:!0}).catch(()=>{})}}Sa();te();Oe();import{closeSync as np,fstatSync as rp,openSync as ip,readFileSync as nS,readSync as rS,readdirSync as iS,statSync as sS}from"node:fs";import{join as ra}from"node:path";var oS=new Set(["debug","info","warn","error"]);function sp(t){let e=t,r=Cn(e,"--agent-id");e=r.rest;let i=Cn(e,"--date");e=i.rest;let o=Cn(e,"-n","--lines");e=o.rest;let c=Cn(e,"--level");e=c.rest;let d=Cn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),h=Number.isInteger(u)&&u>=0?u:200,p=c.value&&oS.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),p&&(m.level=p),d.value&&(m.grep=d.value),m}function aS(t,e){return t.agentId?ra(Ve(t.agentId,e).logs,sr("agent",t.date)):ra(e.bridgeLogsDir,sr("bridge",t.date))}function cS(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function lS(t,e){let r;try{r=iS(t)}catch{return[]}let i=[];for(let o of r){let c=va(o,e);if(!c)continue;let d=0;try{d=sS(ra(t,o)).size}catch{}i.push({file:ra(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"&&!Ed(r,e.level))return!1}return!0}var tp={debug:"90",info:"36",warn:"33",error:"31"},dS=new Set(["ts","level","module","msg"]);function uS(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function ap(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=uS(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:"",h=Object.entries(r).filter(([p])=>!dS.has(p)).map(([p,m])=>` ${p}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${d} ${u}${h}`}function fS(t,e,r){let c=nS(t,"utf8").split(`
115
- `).filter(d=>d.length>0).filter(d=>op(d,{level:e.level,grep:e.grep}));for(let d of cS(c,e.lines))process.stdout.write(`${ap(d,{raw:e.raw,color:r})}
116
- `)}async function cp(t,e){let r=e.paths??Q(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ve(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=lS(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
117
- `),1;for(let p of h)process.stdout.write(`${p.date} ${(p.size/1024).toFixed(1)}KB ${p.file}
118
- `);return 0}let o=t.date??Pn(new Date),c=aS({agentId:t.agentId,date:o},r);try{fS(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
111
+ `)}catch{}}let e=new na({processTitle:Nr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await Ro(),o=i??{};gs({pid:process.pid}),W.info(i?"loaded bridge config":"initialized bridge config");let c=new Qo(new Kr),l=null,u=new Co({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(D,G,K,ee)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(D,G,K,ee)}}),x=new Ao({paths:t,config:o,registry:u});l=x;let h,m,w=null,S={},_,v=null,I=null,T=null,R=new An;function P(D,G){return R.enqueue(()=>C(D,G))}function b(){I||(I=new ia({isConnected:()=>c.isConnected()&&!(v?.isLivenessLost()??!1),forceReconnect:()=>T?P(T,{force:!0}):void 0,onFatal:D=>{if(process.env[cs]==="1"){W.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:D});return}W.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:D}),process.exit(1)}})),I.start()}async function C(D,G){let K=D,ee=K?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Qe=Fi(K.env),pe=K.handshake_url,ge=K.frontier_url,It=Vh(K.env,pe,ge);if(T=K,!G?.force&&h===ee&&m===It){let _e=await OS(t);return u.agents.size===0&&_e?(W.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),oa(t,x).catch(Ae=>W.warn("connect-noop auto-revive error (ignored)",{err:String(Ae)}))):W.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let pt=!!h&&h!==ee,en=m!==void 0&&m!==It,Ft=pt||en,tn=await qc({privatecode:ee,...pe?{endpoint:pe}:{},ppeOverride:Qe});if(Ft){W.warn("connect config switched, resetting agents",{pcChanged:pt,envChanged:en,previousPc:h?sa(h):"",nextPc:sa(ee)});for(let _e of[...u.agents.values()])await _e.dispose("connect config switch").catch(()=>{}),u.agents.delete(_e.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"connect switch").catch(()=>{})}w=tn.deviceId,gs({deviceId:w,pid:process.pid}),xl({patToken:ee,env:K.env}).catch(_e=>W.warn("coze-cli setup error (ignored)",{err:String(_e)}));let Zr=new os({handshake:tn,privatecode:ee,...ge?{urlOverride:ge}:{},ppeOverride:Qe,getPatTokenForAgent:_e=>u.agents.get(_e)?.patToken});return await c.swap(Zr,"connect"),h=ee,m=It,S=Qe,_=pe,K.mock_scenario!==void 0&&(u.setMockScenario(K.mock_scenario),W.info("mock scenario set",{scenario:K.mock_scenario})),v||(v=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(_e=>W.warn("detailSync.retryPending failed (ignored)",{err:String(_e)})),onAuthFailures:J})),v.start(),b(),Ft&&oa(t,x).catch(_e=>W.warn("post-connect-switch auto-revive error (ignored)",{err:String(_e)})),as(ee,t).catch(_e=>W.warn("writePatToken after /connect failed (ignored)",{err:String(_e)})),W.info("/connect: WS established",{deviceId:w}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async D=>x.createAgent(D.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let L={},z=new po({agents:u.agents,publishSkillToMarketplace:async D=>{let G=u.agents.get(D.agentId)?.patToken??h;if(!G)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Gh({patToken:G,zip:D.zip,...D.skillId?{skillId:D.skillId}:{},skillName:D.skillName,...D.description?{description:D.description}:{},agentId:D.agentId,...D.accountId?{accountId:D.accountId}:{}},{handshakeBase:_,ppeOverride:S})},disposeAndMarkDisconnected:async(D,G)=>{let K=u.agents.get(D);if(K){await x.cleanupOpenclawSessionProviders(K).catch(Qe=>W.warn("cleanup openclaw providers failed (ignored)",{agentId:D,err:String(Qe)}));let ee=!0;try{await K.dispose(`disconnect: ${G}`)}catch(Qe){ee=!1,W.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:D,err:String(Qe)}),K.status="error"}ee&&(K.status="disconnected",u.unregister(D),u.disconnectedAgents.add(D))}else u.disconnectedAgents.add(D)},disposeForDelete:async(D,G)=>{let K=u.agents.get(D);K&&(await x.cleanupOpenclawSessionProviders(K).catch(ee=>W.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:D,err:String(ee)})),await K.dispose(`delete: ${G}`).catch(ee=>W.warn("dispose during delete failed (ignored)",{agentId:D,err:String(ee)})),u.unregister(D)),u.disconnectedAgents.delete(D)},detailSyncer:async D=>{if(!L.ref)throw new Error("agent-detail-sync not initialized yet");await L.ref.syncOne(D)},cleanupOpenclawProviders:async D=>{await x.cleanupOpenclawSessionProviders(D)},openclawRepair:async(D,G)=>{await x.openclawRepair(D,G)},isRuntimePendingPermission:D=>u.hasPendingPermissionFor(D)});u.registerExtension("_agent/listSkills",D=>z.listSkills(D.params)),u.registerExtension("_agent/addSkills",D=>z.addSkills(D.params)),u.registerExtension("_agent/removeSkills",D=>z.removeSkills(D.params)),u.registerExtension("_agent/publishSkill",D=>z.publishSkill(D.params)),u.registerExtension("_agent/getFileTree",D=>z.getFileTree(D.params)),u.registerExtension("_agent/getFileContent",D=>z.getFileContent(D.params)),u.registerExtension("_agent/update",D=>z.updateAgent(D.params)),u.registerExtension("_agent/disconnect",D=>z.disconnectAgent(D.params)),u.registerExtension("_agent/switchModel",D=>z.switchModel(D.params)),u.registerExtension("_agent/reset",D=>z.resetAgent(D.params)),u.registerExtension("_agent/repair",D=>z.repairAgent(D.params)),u.registerExtension("_agent/delete",D=>z.deleteAgent(D.params)),u.registerExtension("_agent/upgrade",D=>z.upgradeBridge(D.params));let B=new bs({paths:t,handlers:z,agentManager:x,sendDetail:D=>u.sendRequest("_agent/detail",D)});L.ref=B;let J=async D=>{await Promise.allSettled(D.map(async G=>{try{await z.disconnectAgent({agentId:G.agentId,reason:`auth_failure: code=${G.code} ${G.message}`}),W.info("agent disconnected due to auth failure from heartbeat response",{agentId:G.agentId,code:G.code,message:G.message})}catch(K){W.warn("disconnect during authFailure handling failed (ignored)",{agentId:G.agentId,err:String(K)})}}))};c.onConnect(({initial:D})=>{W.info("frontier upstream connected, triggering detail sync",{initial:D}),B.syncAll(D?"initial-connect":"reconnect").catch(G=>W.warn("detail sync top-level error (ignored)",{err:String(G)}))});let V=new Do({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let D=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[cs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:w??"",frameworksCache:o.frameworksCache??{},...D?{mockScenario:D}:{}}}},{method:"POST",path:"/pair",handler:async D=>{let G=D,K=G?.privatecode,ee=G?.pairing_code;if(!K||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Qe=Fi(G.env),pe=G.handshake_url,ge=G.frontier_url,It=Vh(G.env,pe,ge),pt=!!h&&h!==K,en=m!==void 0&&m!==It,Ft=pt||en,tn=await qc({privatecode:K,...pe?{endpoint:pe}:{},ppeOverride:Qe});if(Ft){W.warn("pair config switched, resetting agents",{pcChanged:pt,envChanged:en,previousPc:h?sa(h):"",nextPc:sa(K),previousEnvKey:m??"",nextEnvKey:It});for(let Ae of[...u.agents.values()])await Ae.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ae.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Kr,"pair switch").catch(()=>{})}w=tn.deviceId,gs({deviceId:w,pid:process.pid}),xl({patToken:K,env:G.env}).catch(Ae=>W.warn("coze-cli setup error (ignored)",{err:String(Ae)}));let Zr=new os({handshake:tn,privatecode:K,...ge?{urlOverride:ge}:{},ppeOverride:Qe,getPatTokenForAgent:Ae=>u.agents.get(Ae)?.patToken});await c.swap(Zr,"pair");try{let Ae=new $n;o.frameworksCache=await Ae.detectAll(),await Ji(o),W.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ae){W.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ae)})}let _e=Object.keys(o.frameworksCache??{});try{let Ae=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:K,frameworks:_e,_meta:{cozeDeviceId:w}});W.info("_agent/pair ok",{pairResult:Ae}),h=K,m=It,S=Qe,_=pe,G.mock_scenario!==void 0&&(u.setMockScenario(G.mock_scenario),W.info("mock scenario set",{scenario:G.mock_scenario})),as(K,t).catch(Pe=>W.warn("writePatToken after /pair failed (ignored)",{err:String(Pe)})),v||(v=new Gi({core:u,getDeviceId:()=>w??"",onTickEnd:()=>B.retryPending().catch(Pe=>W.warn("detailSync.retryPending failed (ignored)",{err:String(Pe)})),onAuthFailures:J})),v.start(),b(),Ft&&oa(t,x).catch(Pe=>W.warn("post-pair-switch auto-revive error (ignored)",{err:String(Pe)}));let er;return G.agent_id&&(er=await MS(G.agent_id,t,x,Pe=>u.sendRequest("_agent/detail",Pe),K).catch(Pe=>(W.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(Pe)}),{ok:!1,agentId:G.agent_id??"",note:String(Pe)}))),{ok:!0,note:"paired with cloud",...er?{agent:er}:{}}}catch(Ae){return W.error("_agent/pair failed",{err:String(Ae)}),{ok:!1,note:`pair failed: ${String(Ae)}`}}}},{method:"POST",path:"/connect",handler:D=>P(D)},{method:"POST",path:"/_agent/create",handler:async D=>{let G=D;return{ok:!0,result:await x.createAgent(G)}}},{method:"POST",path:"/agent/send",handler:async D=>{let G=D;if(!G?.agentId||!G?.sessionId||!G?.kind||!G?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!h)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let K=G;return await(K.groupFile?nx:tx)(K,{core:u,patToken:h,handshakeBase:_,ppeOverride:S})}catch(K){if(K instanceof k)return{ok:!1,code:K.code,message:K.message};throw K}}},{method:"POST",path:"/reload",handler:async D=>{let G=D?.agent_id,K=await u.reloadAgents(G);return W.info("IPC /reload: recycled agent subprocesses",{agentId:G??"(all)",recycled:K}),{ok:!0,recycled:K}}},{method:"POST",path:"/shutdown",handler:async()=>(W.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:re,token:Z}=await V.start();try{await qh(t.libEntry,t)}catch(D){W.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(D)})}await u.start(),BS({paths:t,core:u,agentManager:x,detectAll:async()=>(o.frameworksCache=await new $n().detectAll(),await Ji(o),o.frameworksCache)}).catch(D=>W.warn("startup warmup error (ignored)",{err:String(D)})),Dd().then(async()=>{let{probeAcpVersion:D}=await Promise.resolve().then(()=>(sn(),Rd));for(let G of["claude-code","codex"]){let K=await D(G);K&&W.info("acp wrapper version",{framework:G,version:K})}}).catch(D=>W.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(D)}));let se=null,oe={port:re,token:Z,core:u,ipc:V,shutdown(D){return se||(W.info("daemon shutdown",{reason:D}),se=(async()=>{v?.stop(),I?.stop(),await u.stop(D),await V.stop(),await e.release()})(),se)}};for(let D of["SIGTERM","SIGINT"])process.on(D,()=>{oe.shutdown(D).then(()=>process.exit(0))});return process.on("exit",()=>_0()),process.on("unhandledRejection",D=>{W.error("unhandledRejection",{reason:D instanceof Error?D.message:String(D),stack:D instanceof Error?D.stack:void 0})}),process.on("uncaughtException",D=>{W.error("uncaughtException (will exit, supervisor will restart)",{message:D.message,stack:D.stack,name:D.name});try{process.stderr.write(`FATAL uncaughtException: ${D.stack??D.message}
112
+ `)}catch{}process.exit(1)}),W.info("daemon ready",{port:re,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),FS({cliSpawned:process.env[cs]==="1",readPatToken:()=>ea(t),connect:P}).catch(D=>W.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(D)})),oe}async function OS(t){return ws(t).length>0}function sa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Vh(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function NS(t,e){let r=ws(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(cn(),ys));for(let c of r){await o(c,t).catch(l=>W.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.deletedAt?(e.disconnectedAgents.add(c),W.info("agent marked deleted on startup",{agentId:c,deletedAt:l.deletedAt,reason:l.deleteReason??""})):l?.disconnectedAt&&(e.disconnectedAgents.add(c),W.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){W.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function MS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(cn(),ys)),l=await c(t,e);if(l){if(l.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${l.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);W.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let m=Yh(l),w={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...o?{patToken:o}:{},...m?{_meta:m}:{}};return await r.createAgent(w),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}W.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let 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 BS(t){let e=t.logger??W;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 NS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await oa(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await zS(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function oa(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(()=>(cn(),ys));W.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let x;try{x=await o(u,t)}catch(h){W.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(h)}),l+=1;continue}if(!x){l+=1;continue}if(x.deletedAt){W.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:x.deletedAt}),l+=1;continue}if(x.disconnectedAt){W.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:x.disconnectedAt}),l+=1;continue}try{W.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:x.framework});let h=Yh(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){W.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:x.framework,err:String(h)}),l+=1}}return W.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function zS(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 o0(o,t)).status==="refreshed"&&(i+=1)}catch(c){W.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&W.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function FS(t){let e=t.logger??W;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 Yh(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}ra();Le();import{readFile as Zh}from"node:fs/promises";var Qt=class{paths;constructor(e){this.paths=e??Q()}async probe(e=1e3){let r=await aa(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}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:GS(i)}}}async request(e){let r=await aa(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,l=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),x=await u.text();return{status:u.status,body:US(x)}}finally{clearTimeout(l)}}};async function aa(t){try{let[e,r]=await Promise.all([Zh(t.portFile,"utf8"),Zh(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 US(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function GS(t){return t instanceof Error?t.message:String(t)}$t();ne();sr();import{spawn as HS}from"node:child_process";import{userInfo as Qh}from"node:os";var jl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",qS=new Set(["bash","zsh","sh","dash","ksh"]),Xh=$e("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),jS=2e3;function WS(t,e=jl){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let l of o.split(`
113
+ `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function KS(){let t=(process.env.SHELL??"").trim()||(Qh().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return qS.has(e)?t:null}function $S(t){return new Promise(e=>{let r=`printf '%s' '${jl}'; env; printf '%s' '${jl}'`,i;try{i=HS(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Qh().homedir}})}catch{e(null);return}let o="",c=!1,l=m=>{try{i.pid&&process.kill(-i.pid,m)}catch{}},u=m=>{c||(c=!0,clearTimeout(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(()=>l("SIGTERM"),Xh),h=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},Xh+jS)})}async function Wl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=KS();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??$S)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=WS(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Le();function Rn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],l=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||r.push(c)}return{value:i,rest:r}}sn();import{chmod as VS,copyFile as ep,mkdir as np,readFile as ca,rename as tp,rm as Kl,stat as rp,writeFile as JS}from"node:fs/promises";import{homedir as sP}from"node:os";import{dirname as YS,join as $r,resolve as $l,sep as ls}from"node:path";import{fileURLToPath as ZS}from"node:url";$t();ne();Le();var Vl=H("dist-install");function XS(t){let e=ZS(t),r=YS(e),i=`${ls}src${ls}`;if(r.includes(i)||r.endsWith(`${ls}src${ls}cli`))return null;let o=$l(r,"index.js"),c=$l(r,"..","package.json");return{dist:o,pkgJson:c}}async function Yl(t={}){let e=t.paths??Q(),r=XS(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,l;try{let S=JSON.parse(await ca(o,"utf8"));c=S.version??"unknown",l=S.dependencies??{}}catch(S){return Vl.warn("cannot read source package.json,skip dist install",{err:String(S)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(S)}`}}let u=oi.map(S=>`${S}@${l[S]??"latest"}`),x=await Ro(e.configFile)??{},h=x.libVersion,m=await ca(e.libEntry).then(()=>!0).catch(()=>!1),w=h===c;if(w&&m&&await Jl(e))return{kind:"already-current",libVersion:c};if(!w||!m){await np(e.libDir,{recursive:!0}),await ep(i,e.libEntry),await ep(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let S=$l(e.libDir,"package.json"),_=`${JSON.stringify({type:"module"},null,2)}
114
+ `;await ca(S,"utf8").catch(()=>null)!==_&&await JS(S,_)}return(!w||!await Jl(e))&&await(t.installWrappers??QS)(e,u),x.libVersion=c,await Ji(x,e.configFile),Vl.info("dist installed",{libEntry:e.libEntry,fromVersion:h,toVersion:c}),w&&m?{kind:"already-current",libVersion:c}:h?{kind:"version-changed",fromVersion:h,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Jl(t){for(let e of oi){let r=$r(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await rp(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function QS(t,e){await n1(t.installLock,async()=>{if(await Jl(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${ls}.staging-${process.pid}-${r}`,o=$r(i,"node_modules"),c=$r(t.libDir,"node_modules");try{await np(i,{recursive:!0}),await e1(e,i),await t1(o);let l=`${c}.trash-${r}`;await tp(c,l).catch(()=>{}),await tp(o,c),await Kl(l,{recursive:!0,force:!0}).catch(()=>{}),Vl.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await Kl(i,{recursive:!0,force:!0}).catch(()=>{})}})}function e1(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=rt("npm",r,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",x=>{l.length<8192&&(l+=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}: ${l.trim().slice(0,2e3)}`))})})}async function t1(t){for(let e of oi){let r=$r(t,...e.split("/")),i=JSON.parse(await ca($r(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=$r(t,".bin",o),l=await rp(c);process.platform!=="win32"&&!(l.mode&73)&&await VS(c,l.mode|73).catch(()=>{})}}async function n1(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await Kl(t,{force:!0}).catch(()=>{})}}ka();ne();Le();import{closeSync as sp,fstatSync as op,openSync as ap,readFileSync as r1,readSync as i1,readdirSync as s1,statSync as o1}from"node:fs";import{join as la}from"node:path";var a1=new Set(["debug","info","warn","error"]);function cp(t){let e=t,r=Rn(e,"--agent-id");e=r.rest;let i=Rn(e,"--date");e=i.rest;let o=Rn(e,"-n","--lines");e=o.rest;let c=Rn(e,"--level");e=c.rest;let l=Rn(e,"--grep");e=l.rest;let u=o.value===void 0?200:Number(o.value),x=Number.isInteger(u)&&u>=0?u:200,h=c.value&&a1.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),l.value&&(m.grep=l.value),m}function c1(t,e){return t.agentId?la(Ve(t.agentId,e).logs,or("agent",t.date)):la(e.bridgeLogsDir,or("bridge",t.date))}function l1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function d1(t,e){let r;try{r=s1(t)}catch{return[]}let i=[];for(let o of r){let c=Ta(o,e);if(!c)continue;let l=0;try{l=o1(la(t,o)).size}catch{}i.push({file:la(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function lp(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"&&!Sd(r,e.level))return!1}return!0}var ip={debug:"90",info:"36",warn:"33",error:"31"},u1=new Set(["ts","level","module","msg"]);function f1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function dp(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=f1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&ip[o]&&(c=`\x1B[${ip[o]}m${c}\x1B[0m`);let l=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",x=Object.entries(r).filter(([h])=>!u1.has(h)).map(([h,m])=>` ${h}=${typeof m=="string"?m:JSON.stringify(m)}`).join("");return`${i} ${c} ${l} ${u}${x}`}function x1(t,e,r){let c=r1(t,"utf8").split(`
115
+ `).filter(l=>l.length>0).filter(l=>lp(l,{level:e.level,grep:e.grep}));for(let l of l1(c,e.lines))process.stdout.write(`${dp(l,{raw:e.raw,color:r})}
116
+ `)}async function up(t,e){let r=e.paths??Q(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Ve(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",x=d1(l,u);if(x.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
117
+ `),1;for(let h of x)process.stdout.write(`${h.date} ${(h.size/1024).toFixed(1)}KB ${h.file}
118
+ `);return 0}let o=t.date??Dn(new Date),c=c1({agentId:t.agentId,date:o},r);try{x1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
119
119
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
120
120
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
121
- `),1}return t.follow&&await pS(c,t,i),0}var hS=500;function xS(t){try{let e=ip(t,"r");try{return rp(e).size}finally{np(e)}}catch{return 0}}async function pS(t,e,r){let i=xS(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let h=ip(t,"r");try{let p=rp(h).size;if(p>i){let m=Buffer.allocUnsafe(p-i),_=rS(h,m,0,m.length,i);u=m.subarray(0,_).toString("utf8"),i+=_}}finally{np(h)}}catch{}if(u){let h=(o+u).split(`
122
- `);o=h.pop()??"";for(let p of h)p.length>0&&op(p,{level:e.level,grep:e.grep})&&process.stdout.write(`${ap(p,{raw:e.raw,color:r})}
123
- `)}await new Promise(h=>setTimeout(h,hS))}}finally{process.off("SIGINT",d)}}import{basename as gS,resolve as mS}from"node:path";Oe();var wS=9e4,_S={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 yS(t){return _S[t]??1}async function lp(t,e={}){let r=e.paths??Q();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
121
+ `),1}return t.follow&&await g1(c,t,i),0}var h1=500;function p1(t){try{let e=ap(t,"r");try{return op(e).size}finally{sp(e)}}catch{return 0}}async function g1(t,e,r){let i=p1(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let x=ap(t,"r");try{let h=op(x).size;if(h>i){let m=Buffer.allocUnsafe(h-i),w=i1(x,m,0,m.length,i);u=m.subarray(0,w).toString("utf8"),i+=w}}finally{sp(x)}}catch{}if(u){let x=(o+u).split(`
122
+ `);o=x.pop()??"";for(let h of x)h.length>0&&lp(h,{level:e.level,grep:e.grep})&&process.stdout.write(`${dp(h,{raw:e.raw,color:r})}
123
+ `)}await new Promise(x=>setTimeout(x,h1))}}finally{process.off("SIGINT",l)}}import{basename as m1,resolve as w1}from"node:path";Le();var _1=9e4,y1={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 b1(t){return y1[t]??1}async function fp(t,e={}){let r=e.paths??Q();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
124
124
  `),4;if(t.groupFile&&!t.mimeType)return process.stderr.write(`Error: --group-file requires --mime <mimeType> (e.g. application/pdf, image/png). No local file is read in group-file mode, mime cannot be auto-detected.
125
- `),3;let i=await ta(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
126
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:mS(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 ES(i,"/agent/send",o,wS)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
125
+ `),3;let i=await aa(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
126
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:w1(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 E1(i,"/agent/send",o,_1)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
127
127
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
128
- `),yS(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
- `);else{let d=t.name??gS(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
130
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${bS(c.bytes)})
131
- `)}return 0}async function ES(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 bS(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var wp=H("cli");function He(t,e){let{value:r,rest:i}=Cn(t,e);return{value:r,rest:i}}function la(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
- `)}function KS(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:D}=He(e.slice(1),"--agent-id");return D?{mode:"reload",agentId:D}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return $S(e.slice(1));if(e[0]==="log")return{mode:"log",...sp(e.slice(1))};if(e[0]==="connect")return VS(e.slice(1));if(e.includes("--status"))return la("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return la("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return la("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return la("--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}=He(r,"--pat-token");r=o;let{value:c,rest:d}=He(r,"--pair-code");r=d;let{value:u,rest:h}=He(r,"--env");r=h;let{value:p,rest:m}=He(r,"--handshake-url");r=m;let{value:_,rest:v}=He(r,"--frontier-url");r=v;let{value:y,rest:S}=He(r,"--mock-scenario");r=S;let{value:I}=He(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let k={mode:"pair",privatecode:i,pairingCode:c};return u&&(k.env=u),p&&(k.handshakeUrl=p),_&&(k.frontierUrl=_),y&&(k.mockScenario=y),I&&(k.agentId=I),A&&(k.skipRebuildEnv=!0),k}function $S(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}=He(i,"--caption");i=c;let{value:d,rest:u}=He(i,"--name");i=u;let{value:h,rest:p}=He(i,"--agent-id");i=p;let{value:m,rest:_}=He(i,"--session-id");i=_;let{value:v,rest:y}=He(i,"--mime");i=y;let S=i.includes("--group-file");i=i.filter(k=>k!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),d&&(A.name=d),h&&(A.agentId=h),m&&(A.sessionId=m),S&&(A.groupFile=!0),v&&(A.mimeType=v),A}function VS(t){let e=t,{value:r,rest:i}=He(e,"--pat-token");e=i;let{value:o,rest:c}=He(e,"--env");e=c;let{value:d,rest:u}=He(e,"--handshake-url");e=u;let{value:h,rest:p}=He(e,"--frontier-url");e=p;let{value:m,rest:_}=He(e,"--mock-scenario");e=_;let v=e.includes("--skip-rebuild-env"),y={mode:"connect"};return r&&(y.privatecode=r),o&&(y.env=o),d&&(y.handshakeUrl=d),h&&(y.frontierUrl=h),m&&(y.mockScenario=m),v&&(y.skipRebuildEnv=!0),y}var JS=`
128
+ `),b1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
+ `);else{let l=t.name??m1(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
130
+ `)}else process.stdout.write(`Sent ${t.kind} ${l} (${v1(c.bytes)})
131
+ `)}return 0}async function E1(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await l.text(),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=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function v1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var bp=H("cli");function qe(t,e){let{value:r,rest:i}=Rn(t,e);return{value:r,rest:i}}function pa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
+ `)}function $1(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:P}=qe(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return V1(e.slice(1));if(e[0]==="log")return{mode:"log",...cp(e.slice(1))};if(e[0]==="connect")return J1(e.slice(1));if(e.includes("--status"))return pa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return pa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return pa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return pa("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=qe(r,"--pat-token");r=o;let{value:c,rest:l}=qe(r,"--pair-code");r=l;let{value:u,rest:x}=qe(r,"--env");r=x;let{value:h,rest:m}=qe(r,"--handshake-url");r=m;let{value:w,rest:S}=qe(r,"--frontier-url");r=S;let{value:_,rest:v}=qe(r,"--mock-scenario");r=v;let{value:I}=qe(r,"--agent-id"),T=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let R={mode:"pair",privatecode:i,pairingCode:c};return u&&(R.env=u),h&&(R.handshakeUrl=h),w&&(R.frontierUrl=w),_&&(R.mockScenario=_),I&&(R.agentId=I),T&&(R.skipRebuildEnv=!0),R}function V1(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=qe(i,"--caption");i=c;let{value:l,rest:u}=qe(i,"--name");i=u;let{value:x,rest:h}=qe(i,"--agent-id");i=h;let{value:m,rest:w}=qe(i,"--session-id");i=w;let{value:S,rest:_}=qe(i,"--mime");i=_;let v=i.includes("--group-file");i=i.filter(R=>R!=="--group-file");let I=i.includes("--json"),T={mode:"send",kind:e,path:r,json:I};return o&&(T.caption=o),l&&(T.name=l),x&&(T.agentId=x),m&&(T.sessionId=m),v&&(T.groupFile=!0),S&&(T.mimeType=S),T}function J1(t){let e=t,{value:r,rest:i}=qe(e,"--pat-token");e=i;let{value:o,rest:c}=qe(e,"--env");e=c;let{value:l,rest:u}=qe(e,"--handshake-url");e=u;let{value:x,rest:h}=qe(e,"--frontier-url");e=h;let{value:m,rest:w}=qe(e,"--mock-scenario");e=w;let S=e.includes("--skip-rebuild-env"),_={mode:"connect"};return r&&(_.privatecode=r),o&&(_.env=o),l&&(_.handshakeUrl=l),x&&(_.frontierUrl=x),m&&(_.mockScenario=m),S&&(_.skipRebuildEnv=!0),_}var Y1=`
133
133
  coze-bridge - local bridge daemon for cloud Agent Service
134
134
 
135
135
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -210,57 +210,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
210
210
 
211
211
  Internal:
212
212
  <node> <entry> --daemon daemon mode (OS supervisor only)
213
- `.trimStart();async function _p(t=process.argv,e={}){let r=KS(t);switch(r.mode){case"help":return process.stdout.write(JS),0;case"version":return process.stdout.write(`${Ot}
214
- `),0;case"daemon":{try{await Kx()}catch(i){return wp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return ZS(e);case"stop":return Ep(e);case"reload":return QS(r.agentId,e);case"log":return cp(r,e);case"update":return YS(e);case"purge":return e2(e);case"service-install":return t2(e);case"service-uninstall":return n2(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),r2(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),i2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return lp({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function yp(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 ZS(t){let e=t.paths??Q(),r=new Qt(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
- `),1;if(i.kind==="stale")return await yp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
213
+ `.trimStart();async function Ep(t=process.argv,e={}){let r=$1(t);switch(r.mode){case"help":return process.stdout.write(Y1),0;case"version":return process.stdout.write(`${Lt}
214
+ `),0;case"daemon":{try{await Jh()}catch(i){return bp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return Z1(e);case"stop":return Sp(e);case"reload":return e2(r.agentId,e);case"log":return up(r,e);case"update":return X1(e);case"purge":return t2(e);case"service-install":return n2(e);case"service-uninstall":return r2(e);case"pair":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),i2(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),s2(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 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 Z1(t){let e=t.paths??Q(),r=new Qt(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
+ `),1;if(i.kind==="stale")return await vp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
216
216
  `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
217
217
  ${JSON.stringify(o.body,null,2)}
218
- `),0}async function Ep(t){let e=t.paths??Q(),r=new Qt(e),i=t.daemonSweep??(async()=>{let h=m0();return await w0(h),h}),o=async()=>{t.skipProcessKill||await i(e)},c=await os(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
219
- `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
218
+ `),0}async function Sp(t){let e=t.paths??Q(),r=new Qt(e),i=t.daemonSweep??(async()=>{let x=y0();return await b0(x),x}),o=async()=>{t.skipProcessKill||await i(e)},c=await us(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(x){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(x)}
219
+ `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
220
220
  `:`coze-bridge: not running
221
- `),0;if(u.kind==="stale")return await yp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
221
+ `),0;if(u.kind==="stale")return await vp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
222
222
  `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
223
- `),0}catch(h){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
224
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
225
- `),1)}}async function YS(t){return await Ep(t),(t.spawnNpx??XS)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function XS(t){return new Promise(e=>{let r=nt("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
226
- `),e(1)})})}async function QS(t,e){let r=new Qt(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
223
+ `),0}catch(x){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
224
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(x)}
225
+ `),1)}}async function X1(t){return await Sp(t),(t.spawnNpx??Q1)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function Q1(t){return new Promise(e=>{let r=rt("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
226
+ `),e(1)})})}async function e2(t,e){let r=new Qt(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
227
227
  `),1;try{let o=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
228
228
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
229
229
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
230
230
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
231
- `),1}}async function os(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(gp(),pp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function bp(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??jx,o=t.waitTimeoutMs??15e3,c=t.sleep??o2,d=t.paths??Q(),u=await os(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await mp(e,o,c);if(h.kind==="connected")return h;At(d.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:o})}catch(h){At(d.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}At(d.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 s2(d.pidFile,c)}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)}
231
+ `),1}}async function us(t){if(t.supervisor){let c=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(l,u),uninstall:()=>c.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(_p(),wp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Ip(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??$h,o=t.waitTimeoutMs??15e3,c=t.sleep??a2,l=t.paths??Q(),u=await us(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let x=await yp(e,o,c);if(x.kind==="connected")return x;At(l.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:o})}catch(x){At(l.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(x)})}At(l.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 o2(l.pidFile,c)}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)}
232
232
  `));return process.stdout.write(`coze-bridge: starting daemon...
233
- `),await i({paths:t.paths}),mp(e,o,c)}async function e2(t){let e=new Qt(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
234
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
235
- `)}await new Promise(d=>setTimeout(d,500))}let i=await os(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
236
- `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
233
+ `),await i({paths:t.paths}),yp(e,o,c)}async function t2(t){let e=new Qt(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
234
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
235
+ `)}await new Promise(l=>setTimeout(l,500))}let i=await us(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
236
+ `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
237
237
  `)}let o=t.paths??Q(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
238
- `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
238
+ `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
239
239
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
240
- `),0}async function t2(t){let e=await os(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
240
+ `),0}async function n2(t){let e=await us(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
241
241
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
242
242
  `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
243
- `),1}}async function n2(t){let e=await os(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
243
+ `),1}}async function r2(t){let e=await us(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
244
244
  `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
245
- `),1}}async function vp(t,e,r){if(e)return At(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(At(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(At(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
246
- `),At(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function r2(t,e,r,i={},o,c){let d=new Qt(r.paths),u=r.paths??Q(),h=await vp(u,c,r.reconstructEnv??Gl);if(await Qc(u,h).catch(_=>At(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!r.skipDistInstall){let _=await Kl({paths:r.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
247
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
248
- `)}let p=await bp(r,d);if(p.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${p.kind}
249
- `),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 _=await d.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let v=_.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
245
+ `),1}}async function Ap(t,e,r){if(e)return At(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(At(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(At(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
246
+ `),At(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function i2(t,e,r,i={},o,c){let l=new Qt(r.paths),u=r.paths??Q(),x=await Ap(u,c,r.reconstructEnv??Wl);if(await rl(u,x).catch(w=>At(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!r.skipDistInstall){let w=await Yl({paths:r.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
247
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
248
+ `)}let h=await Ip(r,l);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
249
+ `),1;let m={privatecode:t,pairing_code:e};i.env&&(m.env=i.env),i.handshakeUrl&&(m.handshake_url=i.handshakeUrl),i.frontierUrl&&(m.frontier_url=i.frontierUrl),i.mockScenario&&(m.mock_scenario=i.mockScenario),o&&(m.agent_id=o);try{let w=await l.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let S=w.body.agent;return S&&!S.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${S.agentId}): ${S.note}
250
250
  `),1):(process.stdout.write(`\u5DF2\u914D\u5BF9\u8FDE\u63A5\u5B8C\u6210\uFF0C\u8BF7\u8FD4\u56DE\u5230 coze \u5E73\u53F0\u4E0A\u70B9\u51FB "\u6211\u5DF2\u6267\u884C"
251
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(_.body)}
252
- `),1}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
253
- `),1}}async function i2(t,e,r={},i){let o=e.paths??Q(),c=t??await Vo(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 Qt(e.paths),u=await vp(o,i,e.reconstructEnv??Gl);if(await Qc(o,u).catch(m=>At(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await Kl({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
254
- `),(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}
255
- `)}let h=await bp(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
256
- `),1;let p={privatecode:c};r.env&&(p.env=r.env),r.handshakeUrl&&(p.handshake_url=r.handshakeUrl),r.frontierUrl&&(p.frontier_url=r.frontierUrl),r.mockScenario&&(p.mock_scenario=r.mockScenario);try{let m=await d.request({method:"POST",path:"/connect",body:p,timeoutMs:35e3});return m.status===200&&m.body?.ok?(process.stdout.write(`coze-bridge: connected (${m.body.note??"ok"})
257
- `),t!==void 0&&await ns(c,o).catch(_=>wp.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
251
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
252
+ `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
253
+ `),1}}async function s2(t,e,r={},i){let o=e.paths??Q(),c=t??await ea(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new Qt(e.paths),u=await Ap(o,i,e.reconstructEnv??Wl);if(await rl(o,u).catch(m=>At(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!e.skipDistInstall){let m=await Yl({paths:e.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
254
+ `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(S=>setTimeout(S,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
255
+ `)}let x=await Ip(e,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
256
+ `),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 l.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"})
257
+ `),t!==void 0&&await as(c,o).catch(w=>bp.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(m.body)}
258
258
  `),1)}catch(m){return process.stderr.write(`coze-bridge: connect failed: ${String(m)}
259
- `),1}}async function mp(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await r(200)}return t.probe(500)}async function s2(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Ui(u))return;await e(i)}}function o2(t){return new Promise(e=>setTimeout(e,t))}te();function a2(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 Sp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=a2(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
259
+ `),1}}async function yp(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 o2(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Wi(u))return;await e(i)}}function a2(t){return new Promise(e=>setTimeout(e,t))}ne();function c2(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 Tp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=c2(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
260
260
  `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
261
261
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
262
262
  npx -y coze-bridge@latest stop
263
263
  npx -y coze-bridge@latest connect
264
264
 
265
- `)}Sp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&_d("warn");_p(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
265
+ `)}Tp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Ed("warn");Ep(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
266
266
  `),process.exit(1)});