coze-bridge 0.3.2-alpha.1 → 0.3.2-alpha.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +97 -98
  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 am=Object.create;var Ga=Object.defineProperty;var cm=Object.getOwnPropertyDescriptor;var dm=Object.getOwnPropertyNames;var lm=Object.getPrototypeOf,um=Object.prototype.hasOwnProperty;var pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var it=(t,e)=>()=>(t&&(e=t(t=0)),e);var de=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),qa=(t,e)=>{for(var n in e)Ga(t,n,{get:e[n],enumerable:!0})},fm=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dm(e))!um.call(t,o)&&o!==n&&Ga(t,o,{get:()=>e[o],enumerable:!(i=cm(e,o))||i.enumerable});return t};var Wt=(t,e,n)=>(n=t!=null?am(lm(t)):{},fm(e||!t||!t.__esModule?Ga(n,"default",{value:t,enumerable:!0}):n,t));function Xe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var fr=it(()=>{"use strict"});import{createWriteStream as hm,mkdirSync as xm,readdirSync as pm,unlinkSync as gm}from"node:fs";import{join as Hl}from"node:path";function Nn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function hr(t,e){return`${t}-${e}.log`}function ja(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function mm(t,e,n){let i=a=>{let[d,u,f]=a.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>n}function ys(t,e,n,i){let o;try{o=pm(t)}catch{return}for(let a of o){let d=ja(a,e);if(d&&mm(d,n,i))try{gm(Hl(t,a))}catch{}}}var li,Wa=it(()=>{"use strict";li=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Nn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let n=this.clock();n!==this.currentDate&&this.rotate(n),this.stream?.write(e)}rotate(e){this.stream?.end();try{xm(this.dir,{recursive:!0});let n=hm(Hl(this.dir,hr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var Dm=Object.create;var Za=Object.defineProperty;var Om=Object.getOwnPropertyDescriptor;var Lm=Object.getOwnPropertyNames;var Nm=Object.getPrototypeOf,Mm=Object.prototype.hasOwnProperty;var ge=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var st=(t,e)=>()=>(t&&(e=t(t=0)),e);var le=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ja=(t,e)=>{for(var n in e)Za(t,n,{get:e[n],enumerable:!0})},Bm=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lm(e))!Mm.call(t,s)&&s!==n&&Za(t,s,{get:()=>e[s],enumerable:!(i=Om(e,s))||i.enumerable});return t};var Xt=(t,e,n)=>(n=t!=null?Dm(Nm(t)):{},Bm(e||!t||!t.__esModule?Za(n,"default",{value:t,enumerable:!0}):n,t));function Ze(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var _r=st(()=>{"use strict"});import{createWriteStream as Fm,mkdirSync as zm,readdirSync as Um,unlinkSync as Hm}from"node:fs";import{join as Jl}from"node:path";function Hn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function br(t,e){return`${t}-${e}.log`}function Ya(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Gm(t,e,n){let i=a=>{let[d,u,f]=a.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>n}function ks(t,e,n,i){let s;try{s=Um(t)}catch{return}for(let a of s){let d=Ya(a,e);if(d&&Gm(d,n,i))try{Hm(Jl(t,a))}catch{}}}var wi,Xa=st(()=>{"use strict";wi=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Hn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let n=this.clock();n!==this.currentDate&&this.rotate(n),this.stream?.write(e)}rotate(e){this.stream?.end();try{zm(this.dir,{recursive:!0});let n=Fm(Jl(this.dir,br(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
9
  `)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&ys(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 wm,mkdirSync as _m}from"node:fs";import{join as ym}from"node:path";function ql(t){let e=t.retentionDays??vm,n=t.clock??(()=>Nn(new Date));Es={bridgeSink:new li(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new li(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();ys(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])ys(t.agentLogsDir(o),"agent",i,e)}function Sm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function jl(t){Ka=t}function Wl(t){return xr[Ka]<=xr[t]}function Kl(t,e){let n=xr[t];return n===void 0?!0:n>=xr[e]}function vs(t){Gl={...t}}function $l(t){let e=(u,f=2)=>String(u).padStart(f,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",o=Math.abs(n),a=e(Math.floor(o/60)),d=e(o%60);return`${Nn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function st(t,e,n,i,o){try{let a=`${JSON.stringify({ts:$l(new Date),level:e,module:n,msg:i,...o})}
11
- `;_m(t,{recursive:!0}),wm(ym(t,hr("bridge",Nn(new Date))),a)}catch{}}function Im(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function bs(t,e,n,i,o){if(xr[t]<xr[Ka])return;let a=`${JSON.stringify({ts:$l(new Date),level:t,module:e,msg:n,...Gl,...i})}
12
- `;if(Es){let d=Im(o,i),u=d?Sm(Es,d):Es.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?Em.write(a):bm.write(a)}function G(t,e){return{debug:(n,i)=>bs("debug",t,n,i,e),info:(n,i)=>bs("info",t,n,i,e),warn:(n,i)=>bs("warn",t,n,i,e),error:(n,i)=>bs("error",t,n,i,e),child:n=>G(`${t}.${n}`,e),forAgent:n=>G(t,n)}}var xr,Ka,bm,Em,Gl,vm,Es,te=it(()=>{"use strict";fr();Wa();xr={debug:10,info:20,warn:30,error:40},Ka=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),bm=process.stdout,Em=process.stderr,Gl={},vm=Xe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Es=null});var A,Je=it(()=>{"use strict";A=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Yl={};qa(Yl,{ACP_WRAPPER_NPM_PACKAGES:()=>Is,_resetAcpInstallerForTests:()=>Pm,_setBinaryPathCacheForTests:()=>Dm,buildAcpSpawn:()=>ui,ensureAcpInstalled:()=>gr,getAcpBinaryPath:()=>As,pickWhichLine:()=>Za,probeAcpVersion:()=>Rm,resolveAcpCommand:()=>Jl});import{readFileSync as Vl}from"node:fs";import{createRequire as Am}from"node:module";import{dirname as km,resolve as Tm}from"node:path";function Va(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Za(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(o=>o.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function Cm(t){let e=Zl.resolve(`${t.npmPackage}/package.json`),n=km(e),i=JSON.parse(Vl(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 Tm(n,o)}async function gr(t,e){let n=$a[t];if(!n)throw new A("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=pr.get(t);if(i)return i;let o=Va(t);if(o)return pr.set(t,o),Ss.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let a=Cm(n);return pr.set(t,a),Ss.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw Ss.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(a)}),new A("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${n.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
- `),{cause:a})}}async function Rm(t){let e=$a[t];if(e)try{let n=Zl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Vl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Ss.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function As(t){return pr.get(t)}function Jl(t,e){if(e)return e;let n=Va(t);if(n)return n;let i=As(t);if(!i)throw new A("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function ui(t,e,n){if(e)return{command:e,args:[...n]};let i=Va(t);if(i)return{command:i,args:[...n]};let o=Jl(t);return{command:process.execPath,args:[o,...n]}}function Pm(){pr.clear()}function Dm(t,e){pr.set(t,e)}var Ss,$a,Is,Zl,pr,fn=it(()=>{"use strict";Je();te();Ss=G("agents.acp-installer"),$a={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Is=Object.values($a).filter(t=>t!==void 0).map(t=>t.npmPackage),Zl=Am(import.meta.url),pr=new Map});import{chmod as Lm,mkdir as Nm,readFile as Mm,rename as Bm,rm as Fm,writeFile as zm}from"node:fs/promises";import{dirname as Um}from"node:path";async function hn(t){try{let e=await Mm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ct(t,e,n){await Nm(Um(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await zm(i,e,{encoding:"utf8",mode:n?.mode}),await Bm(i,t),n?.mode!==void 0&&await Lm(t,n.mode)}catch(o){throw await Fm(i,{force:!0}).catch(()=>{}),o}}async function xn(t,e,n){await ct(t,`${JSON.stringify(e,null,2)}
14
- `,n)}var Kt=it(()=>{"use strict"});import{promises as eu,readdirSync as Hm}from"node:fs";import{homedir as Gm}from"node:os";import{sep as qm,join as Le,resolve as tu}from"node:path";function Z(t){let e=t??Gm(),n=Le(e,".coze"),i=Le(n,"bridge"),o=Le(i,"lib"),a=Le(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Le(o,"index.js"),binDir:Le(i,"bin"),pidFile:Le(i,"bridge.pid"),portFile:Le(i,"bridge.port"),tokenFile:Le(i,"bridge.token"),patTokenFile:Le(i,"pat-token"),agentEnvFile:Le(i,"agent-env.json"),logFile:Le(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Le(a,"daemon-stdio.log"),installLock:Le(i,"install.lock"),configFile:Le(i,"config.json"),agentsRoot:Le(n,"agents")}}function Re(t,e=Z()){let n=Le(e.agentsRoot,t);return{root:n,config:Le(n,"config.json"),workspace:Le(n,"workspace"),logs:Le(n,"logs")}}function ks(t=Z()){try{return Hm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function fi(t,e){let n=await eu.realpath(tu(t)).catch(()=>null);if(!n)return!1;let i=await eu.realpath(tu(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?n.toLowerCase():n,a=process.platform==="win32"?i.toLowerCase():i;return o===a||o.startsWith(a+qm)}var Pe=it(()=>{"use strict"});var Cs={};qa(Cs,{AGENT_CONFIG_FILE_MODE:()=>Ts,enforceAgentConfigMode:()=>Km,loadAgentConfig:()=>Ie,persistAgentSessions:()=>hi,persistAgentSkills:()=>xi,saveAgentConfig:()=>qe});import{chmod as jm,stat as Wm}from"node:fs/promises";function Ie(t,e){return hn(Re(t,e).config)}function qe(t,e){return xn(Re(t.agentId,e).config,t,{mode:Ts})}async function Km(t,e){if(process.platform==="win32")return;let n=Re(t,e).config;try{let i=await Wm(n);if(!i.isFile())return;let o=i.mode&511;o!==Ts&&(await jm(n,Ts),nu.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;nu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function hi(t,e,n){let i=await Ie(t,n);i&&(i.sessions=Object.fromEntries(e),await qe(i,n))}async function xi(t,e,n){let i=await Ie(t,n);i&&(i.skills=e,await qe(i,n))}var nu,Ts,$t=it(()=>{"use strict";Kt();te();Pe();nu=G("agent-config"),Ts=384});var Xa=de((v2,su)=>{su.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 Ps=de(au=>{var ou={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 Xm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(ou))au[t]=Xm(ou[t])});var fu=de((I2,uu)=>{var Qm=pe("fs"),ze=pe("path"),cu=Xa(),ew=Ps(),tw=typeof process=="object"&&process.platform==="win32",du=t=>typeof t=="object"&&t!==null,lu=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ae(t){this.sep=ze.sep,this.fs=Qm,du(t)&&du(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}uu.exports=Ae;Ae.prototype.makeDir=function(t){let e=this;function n(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){o+=e.sep+a;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw ew.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};Ae.prototype.writeFileTo=function(t,e,n,i){let o=this;if(o.fs.existsSync(t)){if(!n)return!1;var a=o.fs.statSync(t);if(a.isDirectory())return!1}var d=ze.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ae.prototype.writeFileToAsync=function(t,e,n,i,o){typeof i=="function"&&(o=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!n)return o(!1);a.fs.stat(t,function(u,f){if(d&&f.isDirectory())return o(!1);var x=ze.dirname(t);a.fs.exists(x,function(p){p||a.makeDir(x),a.fs.open(t,"w",438,function(m,v){m?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(_,b){a.fs.write(b,e,0,e.length,0,function(){a.fs.close(b,function(){a.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){o(!0)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ae.prototype.findFiles=function(t){let e=this;function n(i,o,a){typeof o=="boolean"&&(a=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let f=ze.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&d.push(ze.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(f,o,a)))}),d}return n(t,void 0,!0)};Ae.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(o,a){if(o)return e(o);let d=a.length;if(!d)return e(null,i);a.forEach(function(u){u=ze.join(t,u),n.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(ze.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(p,m){if(p)return e(p);i=i.concat(m),--d||e(null,i)}):--d||e(null,i))})})})};Ae.prototype.getAttributes=function(){};Ae.prototype.setAttributes=function(){};Ae.crc32update=function(t,e){return lu[(t^e)&255]^t>>>8};Ae.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ae.crc32update(n,t[i++]);return~n>>>0};Ae.methodToString=function(t){switch(t){case cu.STORED:return"STORED ("+t+")";case cu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ae.canonical=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.join(".",e)};Ae.zipnamefix=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.posix.join(".",e)};Ae.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ae.sanitize=function(t,e){t=ze.resolve(ze.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var a=ze.normalize(ze.join(t,n.slice(i,o).join(ze.sep)));if(a.indexOf(t)===0)return a}return ze.normalize(ze.join(t,ze.basename(e)))};Ae.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ae.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Ae.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ae.fromDate2DOS=function(t){let e=0,n=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),n=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|n};Ae.isWin=tw;Ae.crcTable=lu});var xu=de((A2,hu)=>{var nw=pe("path");hu.exports=function(t,{fs:e}){var n=t||"",i=a(),o=null;function a(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(o=e.statSync(n),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=nw.basename(n)[0]==="."):console.warn("Invalid path: "+n),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:n,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var gu=de((k2,pu)=>{pu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var _r=de((T2,wr)=>{wr.exports=fu();wr.exports.Constants=Xa();wr.exports.Errors=Ps();wr.exports.FileAttr=xu();wr.exports.decoder=gu()});var wu=de((C2,mu)=>{var pn=_r(),U=pn.Constants;mu.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,u=0,f=0,x=0,p=0,m=0,v=0,_=0,b=0;t|=pn.isWin?2560:768,n|=U.FLG_EFS;let S={extraLen:0},I=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,R=E=>Math.max(0,E)&255;return o=pn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&U.FLG_EFS)>0},set flags_efs(E){E?n|=U.FLG_EFS:n&=~U.FLG_EFS},get flags_desc(){return(n&U.FLG_DESC)>0},set flags_desc(E){E?n|=U.FLG_DESC:n&=~U.FLG_DESC},get method(){return i},set method(E){switch(E){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=E},get time(){return pn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=pn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=I(E)},get timeHighByte(){return R(o>>>8)},get crc(){return a},set crc(E){a=I(E)},get compressedSize(){return d},set compressedSize(E){d=I(E)},get size(){return u},set size(E){u=I(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return S.extraLen},set extraLocalLength(E){S.extraLen=E},get commentLength(){return p},set commentLength(E){p=E},get diskNumStart(){return m},set diskNumStart(E){m=I(E)},get inAttr(){return v},set inAttr(E){v=I(E)},get attr(){return _},set attr(E){_=I(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return b},set offset(E){b=I(E)},get encrypted(){return(n&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+x+p},get realDataOffset(){return b+U.LOCHDR+S.fnameLen+S.extraLen},get localHeader(){return S},loadLocalHeaderFromBinary:function(E){var P=E.slice(b,b+U.LOCHDR);if(P.readUInt32LE(0)!==U.LOCSIG)throw pn.Errors.INVALID_LOC();S.version=P.readUInt16LE(U.LOCVER),S.flags=P.readUInt16LE(U.LOCFLG),S.flags_desc=(S.flags&U.FLG_DESC)>0,S.method=P.readUInt16LE(U.LOCHOW),S.time=P.readUInt32LE(U.LOCTIM),S.crc=P.readUInt32LE(U.LOCCRC),S.compressedSize=P.readUInt32LE(U.LOCSIZ),S.size=P.readUInt32LE(U.LOCLEN),S.fnameLen=P.readUInt16LE(U.LOCNAM),S.extraLen=P.readUInt16LE(U.LOCEXT);let D=b+U.LOCHDR+S.fnameLen,M=D+S.extraLen;return E.slice(D,M)},loadFromBinary:function(E){if(E.length!==U.CENHDR||E.readUInt32LE(0)!==U.CENSIG)throw pn.Errors.INVALID_CEN();t=E.readUInt16LE(U.CENVEM),e=E.readUInt16LE(U.CENVER),n=E.readUInt16LE(U.CENFLG),i=E.readUInt16LE(U.CENHOW),o=E.readUInt32LE(U.CENTIM),a=E.readUInt32LE(U.CENCRC),d=E.readUInt32LE(U.CENSIZ),u=E.readUInt32LE(U.CENLEN),f=E.readUInt16LE(U.CENNAM),x=E.readUInt16LE(U.CENEXT),p=E.readUInt16LE(U.CENCOM),m=E.readUInt16LE(U.CENDSK),v=E.readUInt16LE(U.CENATT),_=E.readUInt32LE(U.CENATX),b=E.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(U.LOCHDR);return E.writeUInt32LE(U.LOCSIG,0),E.writeUInt16LE(e,U.LOCVER),E.writeUInt16LE(n,U.LOCFLG),E.writeUInt16LE(i,U.LOCHOW),E.writeUInt32LE(o,U.LOCTIM),E.writeUInt32LE(a,U.LOCCRC),E.writeUInt32LE(d,U.LOCSIZ),E.writeUInt32LE(u,U.LOCLEN),E.writeUInt16LE(f,U.LOCNAM),E.writeUInt16LE(S.extraLen,U.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(U.CENHDR+f+x+p);return E.writeUInt32LE(U.CENSIG,0),E.writeUInt16LE(t,U.CENVEM),E.writeUInt16LE(e,U.CENVER),E.writeUInt16LE(n,U.CENFLG),E.writeUInt16LE(i,U.CENHOW),E.writeUInt32LE(o,U.CENTIM),E.writeUInt32LE(a,U.CENCRC),E.writeUInt32LE(d,U.CENSIZ),E.writeUInt32LE(u,U.CENLEN),E.writeUInt16LE(f,U.CENNAM),E.writeUInt16LE(x,U.CENEXT),E.writeUInt16LE(p,U.CENCOM),E.writeUInt16LE(m,U.CENDSK),E.writeUInt16LE(v,U.CENATT),E.writeUInt32LE(_,U.CENATX),E.writeUInt32LE(b,U.CENOFF),E},toJSON:function(){let E=function(P){return P+" bytes"};return{made:t,version:e,flags:n,method:pn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(p),diskNumStart:m,inAttr:v,attr:_,offset:b,centralHeaderSize:E(U.CENHDR+f+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var yu=de((R2,_u)=>{var yr=_r(),Ee=yr.Constants;_u.exports=function(){var t=0,e=0,n=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return n},set size(a){n=a},get offset(){return i},set offset(a){i=a},get commentLength(){return o},set commentLength(a){o=a},get mainHeaderSize(){return Ee.ENDHDR+o},loadFromBinary:function(a){if((a.length!==Ee.ENDHDR||a.readUInt32LE(0)!==Ee.ENDSIG)&&(a.length<Ee.ZIP64HDR||a.readUInt32LE(0)!==Ee.ZIP64SIG))throw yr.Errors.INVALID_END();a.readUInt32LE(0)===Ee.ENDSIG?(t=a.readUInt16LE(Ee.ENDSUB),e=a.readUInt16LE(Ee.ENDTOT),n=a.readUInt32LE(Ee.ENDSIZ),i=a.readUInt32LE(Ee.ENDOFF),o=a.readUInt16LE(Ee.ENDCOM)):(t=yr.readBigUInt64LE(a,Ee.ZIP64SUB),e=yr.readBigUInt64LE(a,Ee.ZIP64TOT),n=yr.readBigUInt64LE(a,Ee.ZIP64SIZE),i=yr.readBigUInt64LE(a,Ee.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(Ee.ENDHDR+o);return a.writeUInt32LE(Ee.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,Ee.ENDSUB),a.writeUInt16LE(e,Ee.ENDTOT),a.writeUInt32LE(n,Ee.ENDSIZ),a.writeUInt32LE(i,Ee.ENDOFF),a.writeUInt16LE(o,Ee.ENDCOM),a.fill(" ",Ee.ENDHDR),a},toJSON:function(){let a=function(d,u){let f=d.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:a(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ec=de(Qa=>{Qa.EntryHeader=wu();Qa.MainHeader=yu()});var Eu=de((D2,bu)=>{bu.exports=function(t){var e=pe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),a=[],d=0;o.on("data",function(u){a.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var x=0;x<a.length;x++){var p=a[x];p.copy(u,f),f+=p.length}i&&i(u)}),o.end(t)}}}});var Su=de((O2,vu)=>{var rw=+(process.versions?process.versions.node:"").split(".")[0]||0;vu.exports=function(t,e){var n=pe("zlib");let i=rw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var a=n.createInflateRaw(i),d=[],u=0;a.on("data",function(f){d.push(f),u+=f.length}),a.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var p=0;p<d.length;p++){var m=d[p];m.copy(f,x),x+=m.length}o&&o(f)}),a.end(t)}}}});var Cu=de((L2,Tu)=>{"use strict";var{randomFillSync:Iu}=pe("crypto"),iw=Ps(),sw=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),ku=(t,e)=>Math.imul(t,e)>>>0,Au=(t,e)=>sw[(t^e)&255]^t>>>8,pi=()=>typeof Iu=="function"?Iu(Buffer.alloc(12)):pi.node();pi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let n=0;n<e;n++)t[n]=Math.random()*256&255;return t};var Ds={genSalt:pi};function Os(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let n=0;n<e.length;n++)this.updateKeys(e[n])}Os.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Au(e[0],t),e[1]+=e[0]&255,e[1]=ku(e[1],134775813)+1,e[2]=Au(e[2],e[1]>>>24),t};Os.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return ku(t,t^1)>>8&255};function ow(t){let e=new Os(t);return function(n){let i=Buffer.alloc(n.length),o=0;for(let a of n)i[o++]=e.updateKeys(a^e.next());return i}}function aw(t){let e=new Os(t);return function(n,i,o=0){i||(i=Buffer.alloc(n.length));for(let a of n){let d=e.next();i[o++]=a^d,e.updateKeys(a)}return i}}function cw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=ow(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw iw.WRONG_PASSWORD();return i(t.slice(12))}function dw(t){Buffer.isBuffer(t)&&t.length>=12?Ds.genSalt=function(){return t.slice(0,12)}:t==="node"?Ds.genSalt=pi.node:Ds.genSalt=pi}function lw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=aw(n),a=Ds.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(a,d),o(t,d,12)}Tu.exports={decrypt:cw,encrypt:lw,_salter:dw}});var Ru=de(Ls=>{Ls.Deflater=Eu();Ls.Inflater=Su();Ls.ZipCrypto=Cu()});var nc=de((M2,Pu)=>{var le=_r(),uw=ec(),ke=le.Constants,tc=Ru();Pu.exports=function(t,e){var n=new uw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let p=t,m=typeof p.decoder=="object"?p.decoder:le.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(le.crc32(E)!==n.localHeader.crc)return!1}else{let P={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==ke.LOCSIG||e.readUInt32LE(D)==ke.CENSIG)throw le.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==ke.EXTSIG)P.crc=e.readUInt32LE(D+ke.EXTCRC),P.compressedSize=e.readUInt32LE(D+ke.EXTSIZ),P.size=e.readUInt32LE(D+ke.EXTLEN);else if(e.readUInt16LE(D+12)===19280)P.crc=e.readUInt32LE(D+ke.EXTCRC-4),P.compressedSize=e.readUInt32LE(D+ke.EXTSIZ-4),P.size=e.readUInt32LE(D+ke.EXTLEN-4);else throw le.Errors.DESCRIPTOR_UNKNOWN();if(P.compressedSize!==n.compressedSize||P.size!==n.size||P.crc!==n.crc)throw le.Errors.DESCRIPTOR_FAULTY();if(le.crc32(E)!==P.crc)return!1}return!0}function b(E,P,D){if(typeof P>"u"&&typeof E=="string"&&(D=E,E=void 0),a)return E&&P&&P(Buffer.alloc(0),le.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var M=v();if(M.length===0)return E&&P&&P(M),M;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw le.Errors.INVALID_PASS_PARAM();M=tc.ZipCrypto.decrypt(M,n,D)}var N=Buffer.alloc(n.size);switch(n.method){case le.Constants.STORED:if(M.copy(N),_(N))return E&&P&&P(N),N;throw E&&P&&P(N,le.Errors.BAD_CRC()),le.Errors.BAD_CRC();case le.Constants.DEFLATED:var J=new tc.Inflater(M,n.size);if(E)J.inflateAsync(function(V){V.copy(V,0),P&&(_(V)?P(V):P(V,le.Errors.BAD_CRC()))});else{if(J.inflate(N).copy(N,0),!_(N))throw le.Errors.BAD_CRC(`"${m.decode(i)}"`);return N}break;default:throw E&&P&&P(Buffer.alloc(0),le.Errors.UNKNOWN_METHOD()),le.Errors.UNKNOWN_METHOD()}}function S(E,P){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&P&&P(v()),v();if(d.length&&!a){var D;switch(n.method){case le.Constants.STORED:return n.compressedSize=n.size,D=Buffer.alloc(d.length),d.copy(D),E&&P&&P(D),D;default:case le.Constants.DEFLATED:var M=new tc.Deflater(d);if(E)M.deflateAsync(function(J){D=Buffer.alloc(J.length),n.compressedSize=J.length,J.copy(D),P&&P(D)});else{var N=M.deflate();return n.compressedSize=N.length,N}M=null;break}}else if(E&&P)P(Buffer.alloc(0));else return Buffer.alloc(0)}function I(E,P){return le.readBigUInt64LE(E,P)}function T(E){try{for(var P=0,D,M,N;P+4<E.length;)D=E.readUInt16LE(P),P+=2,M=E.readUInt16LE(P),P+=2,N=E.slice(P,P+M),P+=M,ke.ID_ZIP64===D&&R(N)}catch{throw le.Errors.EXTRA_FIELD_PARSE_ERROR()}}function R(E){var P,D,M,N;E.length>=ke.EF_ZIP64_SCOMP&&(P=I(E,ke.EF_ZIP64_SUNCOMP),n.size===ke.EF_ZIP64_OR_32&&(n.size=P)),E.length>=ke.EF_ZIP64_RHO&&(D=I(E,ke.EF_ZIP64_SCOMP),n.compressedSize===ke.EF_ZIP64_OR_32&&(n.compressedSize=D)),E.length>=ke.EF_ZIP64_DSN&&(M=I(E,ke.EF_ZIP64_RHO),n.offset===ke.EF_ZIP64_OR_32&&(n.offset=M)),E.length>=ke.EF_ZIP64_DSN+4&&(N=E.readUInt32LE(ke.EF_ZIP64_DSN),n.diskNumStart===ke.EF_ZIP64_OR_16&&(n.diskNumStart=N))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(E){i=le.toBuffer(E,m.encode);var P=i[i.length-1];a=P===47||P===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,T(E)},get comment(){return m.decode(o)},set comment(E){if(o=le.toBuffer(E,m.encode),n.commentLength=o.length,o.length>65535)throw le.Errors.COMMENT_TOO_LONG()},get name(){var E=m.decode(i);return a?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return S(!1,null)},getCompressedDataAsync:function(E){S(!0,E)},setData:function(E){d=le.toBuffer(E,le.decoder.encode),!a&&d.length?(n.size=d.length,n.method=le.Constants.DEFLATED,n.crc=le.crc32(E),n.changed=!0):n.method=le.Constants.STORED},getData:function(E){return n.changed?d:b(!1,null,E)},getDataAsync:function(E,P){n.changed?E(d):b(!0,E,P)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),P=le.Constants.CENHDR;return i.copy(E,P),P+=i.length,u.copy(E,P),P+=n.extraLength,o.copy(E,P),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let P=n.localHeaderToBinary(),D=Buffer.alloc(P.length+i.length+n.extraLocalLength);return P.copy(D,E),E+=P.length,i.copy(D,E),E+=i.length,f.copy(D,E),E+=f.length,D},toJSON:function(){let E=function(P){return"<"+(P&&P.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Lu=de((B2,Ou)=>{var Du=nc(),fw=ec(),Ye=_r();Ou.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new fw.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:p,decoder:m}=x;t?b(x.readEntries):d=!0;function v(){let I=new Set;for(let T of Object.keys(i)){let R=T.split("/");if(R.pop(),!!R.length)for(let E=0;E<R.length;E++){let P=R.slice(0,E+1).join("/")+"/";I.add(P)}}for(let T of I)if(!(T in i)){let R=new Du(x);R.entryName=T,R.attr=16,R.temporary=!0,n.push(R),i[R.entryName]=R,f.add(R)}}function _(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Ye.Constants.CENHDR)throw Ye.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var I=a.offset,T=0;T<n.length;T++){var R=I,E=new Du(x,t);E.header=t.slice(R,R+=Ye.Constants.CENHDR),E.entryName=t.slice(R,R+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(R,R+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(R,R+E.header.commentLength)),I+=E.header.centralHeaderSize,n[T]=E,i[E.entryName]=E}f.clear(),v()}function b(I){var T=t.length-Ye.Constants.ENDHDR,R=Math.max(0,T-65535),E=R,P=t.length,D=-1,M=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(R=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ye.Constants.ENDSIG){D=T,M=T,P=T+Ye.Constants.ENDHDR,E=T-Ye.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ye.Constants.END64SIG){E=R;continue}if(t.readUInt32LE(T)===Ye.Constants.ZIP64SIG){D=T,P=T+Ye.readBigUInt64LE(t,T+Ye.Constants.ZIP64SIZE)+Ye.Constants.ZIP64LEAD;break}}if(D==-1)throw Ye.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,P)),a.commentLength&&(o=t.slice(M+Ye.Constants.ENDHDR)),I&&_()}function S(){n.length>1&&!p&&n.sort((I,T)=>I.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(I=>!f.has(I))},get comment(){return m.decode(o)},set comment(I){o=Ye.toBuffer(I,m.encode),a.commentLength=o.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(I){this.entries.forEach(I)},getEntry:function(I){return d||_(),i[I]||null},setEntry:function(I){d||_(),n.push(I),i[I.entryName]=I,a.totalEntries=n.length},deleteFile:function(I,T=!0){d||_();let R=i[I];this.getEntryChildren(R,T).map(P=>P.entryName).forEach(this.deleteEntry)},deleteEntry:function(I){d||_();let T=i[I],R=n.indexOf(T);R>=0&&(n.splice(R,1),delete i[I],a.totalEntries=n.length)},getEntryChildren:function(I,T=!0){if(d||_(),typeof I=="object")if(I.isDirectory&&T){let R=[],E=I.entryName;for(let P of n)P.entryName.startsWith(E)&&R.push(P);return R}else return[I];return[]},getChildCount:function(I){if(I&&I.isDirectory){let T=this.getEntryChildren(I);return T.includes(I)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),S();let I=[],T=[],R=0,E=0;a.size=0,a.offset=0;let P=0;for(let N of this.entries){let J=N.getCompressedData();N.header.offset=E;let V=N.packLocalHeader(),se=V.length+J.length;E+=se,I.push(V),I.push(J);let X=N.packCentralHeader();T.push(X),a.size+=X.length,R+=se+X.length,P++}R+=a.mainHeaderSize,a.offset=E,a.totalEntries=P,E=0;let D=Buffer.alloc(R);for(let N of I)N.copy(D,E),E+=N.length;for(let N of T)N.copy(D,E),E+=N.length;let M=a.toBinary();return o&&o.copy(M,Ye.Constants.ENDHDR),M.copy(D,E),t=D,d=!1,D},toAsyncBuffer:function(I,T,R,E){try{d||_(),S();let P=[],D=[],M=0,N=0,J=0;a.size=0,a.offset=0;let V=function(se){if(se.length>0){let X=se.shift(),re=X.entryName+X.extra.toString();R&&R(re),X.getCompressedDataAsync(function(ae){E&&E(re),X.header.offset=N;let C=X.packLocalHeader(),z=C.length+ae.length;N+=z,P.push(C),P.push(ae);let q=X.packCentralHeader();D.push(q),a.size+=q.length,M+=z+q.length,J++,V(se)})}else{M+=a.mainHeaderSize,a.offset=N,a.totalEntries=J,N=0;let X=Buffer.alloc(M);P.forEach(function(ae){ae.copy(X,N),N+=ae.length}),D.forEach(function(ae){ae.copy(X,N),N+=ae.length});let re=a.toBinary();o&&o.copy(re,Ye.Constants.ENDHDR),re.copy(X,N),t=X,d=!1,I(X)}};V(Array.from(this.entries))}catch(P){T(P)}}}}});var Bu=de((F2,Mu)=>{var Se=_r(),ve=pe("path"),hw=nc(),xw=Lu(),Mn=(...t)=>Se.findLast(t,e=>typeof e=="boolean"),Nu=(...t)=>Se.findLast(t,e=>typeof e=="string"),pw=(...t)=>Se.findLast(t,e=>typeof e=="function"),gw={noSort:!1,readEntries:!1,method:Se.Constants.NONE,fs:null};Mu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),gw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=Se.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Se(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Se.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Se.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw Se.Errors.INVALID_FILENAME();let a=new xw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=Se;function x(_){if(_&&a){var b;if(typeof _=="string"&&(b=a.getEntry(ve.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(b=a.getEntry(_.entryName)),b)return b}return null}function p(_){let{join:b,normalize:S,sep:I}=ve.posix;return b(ve.isAbsolute(_)?"/":".",S(I+_.split("\\").join(I)+I))}function m(_){return _ instanceof RegExp?(function(b){return function(S){return b.test(S)}})(_):typeof _!="function"?()=>!0:_}let v=(_,b)=>{let S=b.slice(-1);return S=S===o.sep?o.sep:"",ve.relative(_,b)+S};return{readFile:function(_,b){var S=x(_);return S&&S.getData(b)||null},childCount:function(_){let b=x(_);if(b)return a.getChildCount(b)},readFileAsync:function(_,b){var S=x(_);S?S.getDataAsync(b):b(null,"getEntry failed for:"+_)},readAsText:function(_,b){var S=x(_);if(S){var I=S.getData();if(I&&I.length)return I.toString(b||"utf8")}return""},readAsTextAsync:function(_,b,S){var I=x(_);I?I.getDataAsync(function(T,R){if(R){b(T,R);return}T&&T.length?b(T.toString(S||"utf8")):b("")}):b("")},deleteFile:function(_,b=!0){var S=x(_);S&&a.deleteFile(S.entryName,b)},deleteEntry:function(_){var b=x(_);b&&a.deleteEntry(b.entryName)},addZipComment:function(_){a.comment=_},getZipComment:function(){return a.comment||""},addZipEntryComment:function(_,b){var S=x(_);S&&(S.comment=b)},getZipEntryComment:function(_){var b=x(_);return b&&b.comment||""},updateFile:function(_,b){var S=x(_);S&&S.setData(b)},addLocalFile:function(_,b,S,I){if(o.fs.existsSync(_)){b=b?p(b):"";let T=ve.win32.basename(ve.win32.normalize(_));b+=S||T;let R=o.fs.statSync(_),E=R.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);R.isDirectory()&&(b+=o.sep),this.addFile(b,E,I,R)}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,b){_=typeof _=="object"?_:{localPath:_};let S=ve.resolve(_.localPath),{comment:I}=_,{zipPath:T,zipName:R}=_,E=this;o.fs.stat(S,function(P,D){if(P)return b(P,!1);T=T?p(T):"";let M=ve.win32.basename(ve.win32.normalize(S));if(T+=R||M,D.isFile())o.fs.readFile(S,function(N,J){return N?b(N,!1):(E.addFile(T,J,I,D),setImmediate(b,void 0,!0))});else if(D.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),I,D),setImmediate(b,void 0,!0)})},addLocalFolder:function(_,b,S){if(S=m(S),b=b?p(b):"",_=ve.normalize(_),o.fs.existsSync(_)){let I=o.findFiles(_),T=this;if(I.length)for(let R of I){let E=ve.join(b,v(_,R));S(E)&&T.addLocalFile(R,ve.dirname(E))}}else throw Se.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,b,S,I){I=m(I),S=S?p(S):"",_=ve.normalize(_);var T=this;o.fs.open(_,"r",function(R){if(R&&R.code==="ENOENT")b(void 0,Se.Errors.FILE_NOT_FOUND(_));else if(R)b(void 0,R);else{var E=o.findFiles(_),P=-1,D=function(){if(P+=1,P<E.length){var M=E[P],N=v(_,M).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),I(N)?o.fs.stat(M,function(J,V){J&&b(void 0,J),V.isFile()?o.fs.readFile(M,function(se,X){se?b(void 0,se):(T.addFile(S+N,X,"",V),D())}):(T.addFile(S+N+"/",Buffer.alloc(0),"",V),D())}):process.nextTick(()=>{D()})}else b(!0,void 0)};D()}})},addLocalFolderAsync2:function(_,b){let S=this;_=typeof _=="object"?_:{localPath:_},localPath=ve.resolve(p(_.localPath));let{zipPath:I,filter:T,namefix:R}=_;T instanceof RegExp?T=(function(D){return function(M){return D.test(M)}})(T):typeof T!="function"&&(T=function(){return!0}),I=I?p(I):"",R=="latin1"&&(R=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof R!="function"&&(R=D=>D);let E=D=>ve.join(I,R(v(localPath,D))),P=D=>ve.win32.basename(ve.win32.normalize(R(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?b(void 0,Se.Errors.FILE_NOT_FOUND(localPath)):D?b(void 0,D):o.findFilesAsync(localPath,function(M,N){if(M)return b(M);N=N.filter(J=>T(E(J))),N.length||b(void 0,!1),setImmediate(N.reverse().reduce(function(J,V){return function(se,X){if(se||X===!1)return setImmediate(J,se,!1);S.addLocalFileAsync({localPath:V,zipPath:ve.dirname(E(V)),zipName:P(V)},J)}},b))})})},addLocalFolderPromise:function(_,b){return new Promise((S,I)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},b),(T,R)=>{T&&I(T),R&&S(this)})})},addFile:function(_,b,S,I){_=f(_);let T=x(_),R=T!=null;R||(T=new hw(i),T.entryName=_),T.comment=S||"";let E=typeof I=="object"&&I instanceof o.fs.Stats;E&&(T.header.time=I.mtime);var P=T.isDirectory?16:0;let D=T.isDirectory?16384:32768;return E?D|=4095&I.mode:typeof I=="number"?D|=4095&I:D|=T.isDirectory?493:420,P=(P|D<<16)>>>0,T.attr=P,T.setData(b),R||a.setEntry(T),T},getEntries:function(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,b,S,I,T,R){I=Mn(!1,I),T=Mn(!1,T),S=Mn(!0,S),R=Nu(T,R);var E=x(_);if(!E)throw Se.Errors.NO_ENTRY();var P=d(E.entryName),D=u(b,R&&!E.isDirectory?R:S?P:ve.basename(P));if(E.isDirectory){var M=a.getEntryChildren(E);return M.forEach(function(V){if(V.isDirectory)return;var se=V.getData();if(!se)throw Se.Errors.CANT_EXTRACT_FILE();var X=d(V.entryName),re=u(b,S?X:ve.basename(X));let ae=T?V.header.fileAttr:void 0;o.writeFileTo(re,se,I,ae)}),!0}var N=E.getData(a.password);if(!N)throw Se.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!I)throw Se.Errors.CANT_OVERRIDE();let J=T?_.header.fileAttr:void 0;return o.writeFileTo(D,N,I,J),!0},test:function(_){if(!a)return!1;for(var b in a.entries)try{if(b.isDirectory)continue;var S=a.entries[b].getData(_);if(!S)return!1}catch{return!1}return!0},extractAllTo:function(_,b,S,I){if(S=Mn(!1,S),I=Nu(S,I),b=Mn(!1,b),!a)throw Se.Errors.NO_ZIP();a.entries.forEach(function(T){var R=u(_,d(T.entryName));if(T.isDirectory){o.makeDir(R);return}var E=T.getData(I);if(!E)throw Se.Errors.CANT_EXTRACT_FILE();let P=S?T.header.fileAttr:void 0;o.writeFileTo(R,E,b,P);try{o.fs.utimesSync(R,T.header.time,T.header.time)}catch{throw Se.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,b,S,I){if(I=pw(b,S,I),S=Mn(!1,S),b=Mn(!1,b),!I)return new Promise((D,M)=>{this.extractAllToAsync(_,b,S,function(N){N?M(N):D(this)})});if(!a){I(Se.Errors.NO_ZIP());return}_=ve.resolve(_);let T=D=>u(_,ve.normalize(d(D.entryName))),R=(D,M)=>new Error(D+': "'+M+'"'),E=[],P=[];a.entries.forEach(D=>{D.isDirectory?E.push(D):P.push(D)});for(let D of E){let M=T(D),N=S?D.header.fileAttr:void 0;try{o.makeDir(M),N&&o.fs.chmodSync(M,N),o.fs.utimesSync(M,D.header.time,D.header.time)}catch{I(R("Unable to create folder",M))}}P.reverse().reduce(function(D,M){return function(N){if(N)D(N);else{let J=ve.normalize(d(M.entryName)),V=u(_,J);M.getDataAsync(function(se,X){if(X)D(X);else if(!se)D(Se.Errors.CANT_EXTRACT_FILE());else{let re=S?M.header.fileAttr:void 0;o.writeFileToAsync(V,se,b,re,function(ae){ae||D(R("Unable to write file",V)),o.fs.utimes(V,M.header.time,M.header.time,function(C){C?D(R("Unable to set times",V)):D()})})}})}}},I)()},writeZip:function(_,b){if(arguments.length===1&&typeof _=="function"&&(b=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var S=a.compressToBuffer();if(S){var I=o.writeFileTo(_,S,!0);typeof b=="function"&&b(I?null:new Error("failed"),"")}}},writeZipPromise:function(_,b){let{overwrite:S,perm:I}=Object.assign({overwrite:!0},b);return new Promise((T,R)=>{!_&&i.filename&&(_=i.filename),_||R("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let P=D=>D?T(D):R("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(_,E,S,I,P)},R)})},toBufferPromise:function(){return new Promise((_,b)=>{a.toAsyncBuffer(_,b)})},toBuffer:function(_,b,S,I){return typeof _=="function"?(a.toAsyncBuffer(_,b,S,I),null):a.compressToBuffer()}}}});import{execFile as Sy,spawn as Iy,spawnSync as nT}from"node:child_process";import{promisify as Ay}from"node:util";function Ty(t){if(process.platform!=="win32")return!1;if(s0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(s0,"").toLowerCase();return ky.has(n)}function o0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return Ty(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function at(t,e=[],n={}){return Iy(t,e,o0(t,n))}function a0(t,e=[],n={}){return Cy(t,e,o0(t,n))}var ky,s0,Cy,en=it(()=>{"use strict";ky=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),s0=/\.(cmd|bat|ps1)$/i;Cy=Ay(Sy)});var nn=de((hD,ix)=>{"use strict";var nx=["nodebuffer","arraybuffer","fragments"],rx=typeof Blob<"u";rx&&nx.push("blob");ix.exports={BINARY_TYPES:nx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:rx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var is=de((xD,Vo)=>{"use strict";var{EMPTY_BUFFER:Wv}=nn(),Bd=Buffer[Symbol.species];function Kv(t,e){if(t.length===0)return Wv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let a=t[o];n.set(a,i),i+=a.length}return i<e?new Bd(n.buffer,n.byteOffset,i):n}function sx(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function ox(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function $v(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Fd(t){if(Fd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Bd(t):ArrayBuffer.isView(t)?e=new Bd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Fd.readOnly=!1),e}Vo.exports={concat:Kv,mask:sx,toArrayBuffer:$v,toBuffer:Fd,unmask:ox};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=pe("bufferutil");Vo.exports.mask=function(e,n,i,o,a){a<48?sx(e,n,i,o,a):t.mask(e,n,i,o,a)},Vo.exports.unmask=function(e,n){e.length<32?ox(e,n):t.unmask(e,n)}}catch{}});var dx=de((pD,cx)=>{"use strict";var ax=Symbol("kDone"),zd=Symbol("kRun"),Ud=class{constructor(e){this[ax]=()=>{this.pending--,this[zd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[zd]()}[zd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ax])}}};cx.exports=Ud});var Jr=de((gD,hx)=>{"use strict";var ss=pe("zlib"),lx=is(),Vv=dx(),{kStatusCode:ux}=nn(),Zv=Buffer[Symbol.species],Jv=Buffer.from([0,0,255,255]),Jo=Symbol("permessage-deflate"),rn=Symbol("total-length"),Vr=Symbol("callback"),Pn=Symbol("buffers"),Zr=Symbol("error"),Zo,Hd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Zo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zo=new Vv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Vr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let o=n[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=o})}),e}decompress(e,n,i){Zo.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){Zo.add(o=>{this._compress(e,n,(a,d)=>{o(),i(a,d)})})}_decompress(e,n,i){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?ss.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=ss.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Jo]=this,this._inflate[rn]=0,this._inflate[Pn]=[],this._inflate.on("error",Xv),this._inflate.on("data",fx)}this._inflate[Vr]=i,this._inflate.write(e),n&&this._inflate.write(Jv),this._inflate.flush(()=>{let a=this._inflate[Zr];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=lx.concat(this._inflate[Pn],this._inflate[rn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rn]=0,this._inflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,d=typeof this.params[a]!="number"?ss.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=ss.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[rn]=0,this._deflate[Pn]=[],this._deflate.on("data",Yv)}this._deflate[Vr]=i,this._deflate.write(e),this._deflate.flush(ss.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=lx.concat(this._deflate[Pn],this._deflate[rn]);n&&(a=new Zv(a.buffer,a.byteOffset,a.length-4)),this._deflate[Vr]=null,this._deflate[rn]=0,this._deflate[Pn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};hx.exports=Hd;function Yv(t){this[Pn].push(t),this[rn]+=t.length}function fx(t){if(this[rn]+=t.length,this[Jo]._maxPayload<1||this[rn]<=this[Jo]._maxPayload){this[Pn].push(t);return}this[Zr]=new RangeError("Max payload size exceeded"),this[Zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zr][ux]=1009,this.removeListener("data",fx),this.reset()}function Xv(t){if(this[Jo]._inflate=null,this[Zr]){this[Vr](this[Zr]);return}t[ux]=1007,this[Vr](t)}});var Yr=de((mD,Yo)=>{"use strict";var{isUtf8:xx}=pe("buffer"),{hasBlob:Qv}=nn(),eS=[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 tS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Gd(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function nS(t){return Qv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Yo.exports={isBlob:nS,isValidStatusCode:tS,isValidUTF8:Gd,tokenChars:eS};if(xx)Yo.exports.isValidUTF8=function(t){return t.length<24?Gd(t):xx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=pe("utf-8-validate");Yo.exports.isValidUTF8=function(e){return e.length<32?Gd(e):t(e)}}catch{}});var $d=de((wD,Ex)=>{"use strict";var{Writable:rS}=pe("stream"),px=Jr(),{BINARY_TYPES:iS,EMPTY_BUFFER:gx,kStatusCode:sS,kWebSocket:oS}=nn(),{concat:qd,toArrayBuffer:aS,unmask:cS}=is(),{isValidStatusCode:dS,isValidUTF8:mx}=Yr(),Xo=Buffer[Symbol.species],wt=0,_x=1,yx=2,bx=3,jd=4,Wd=5,Qo=6,Kd=class extends rS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||iS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[oS]=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=wt}_write(e,n,i){if(this._opcode===8&&this._state==wt)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Xo(i.buffer,i.byteOffset+e,i.length-e),new Xo(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=n.length-e;e>=i.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new Xo(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case wt:this.getInfo(e);break;case _x:this.getPayloadLength16(e);break;case yx:this.getPayloadLength64(e);break;case bx:this.getMask();break;case jd:this.getData(e);break;case Wd:case Qo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(n[0]&64)===64;if(i&&!this._extensions[px.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=_x:this._payloadLength===127?this._state=yx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=bx:this._state=jd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jd}getData(e){let n=gx;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&cS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Wd,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[px.extensionName].decompress(e,this._fin,(o,a)=>{if(o)return n(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}this._fragments.push(a)}this.dataMessage(n),this._state===wt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=wt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=qd(i,n):this._binaryType==="arraybuffer"?o=aS(qd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=wt):(this._state=Qo,setImmediate(()=>{this.emit("message",o,!0),this._state=wt,this.startLoop(e)}))}else{let o=qd(i,n);if(!this._skipUTF8Validation&&!mx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===Wd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=wt):(this._state=Qo,setImmediate(()=>{this.emit("message",o,!1),this._state=wt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,gx),this.end();else{let i=e.readUInt16BE(0);if(!dS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new Xo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!mx(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(a);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=wt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=wt):(this._state=Qo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=wt,this.startLoop(n)}))}createError(e,n,i,o,a){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=a,d[sS]=o,d}};Ex.exports=Kd});var Jd=de((yD,Ix)=>{"use strict";var{Duplex:_D}=pe("stream"),{randomFillSync:lS}=pe("crypto"),vx=Jr(),{EMPTY_BUFFER:uS,kWebSocket:fS,NOOP:hS}=nn(),{isBlob:Xr,isValidStatusCode:xS}=Yr(),{mask:Sx,toBuffer:nr}=is(),_t=Symbol("kByteLength"),pS=Buffer.alloc(4),ea=8*1024,rr,Qr=ea,Tt=0,gS=1,mS=2,Vd=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Tt,this.onerror=hS,this[fS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||pS,n.generateMask?n.generateMask(i):(Qr===ea&&(rr===void 0&&(rr=Buffer.alloc(ea)),lS(rr,0,ea),Qr=0),i[0]=rr[Qr++],i[1]=rr[Qr++],i[2]=rr[Qr++],i[3]=rr[Qr++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[_t]!==void 0?u=n[_t]:(e=Buffer.from(e),u=e.length):(u=e.length,o=n.mask&&n.readOnly&&!d);let f=u;u>=65536?(a+=8,f=127):u>125&&(a+=2,f=126);let x=Buffer.allocUnsafe(o?u+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:o?(Sx(e,i,x,a,u),[x]):(Sx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,o){let a;if(e===void 0)a=uS;else{if(typeof e!="number"||!xS(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+u),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let d={[_t]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Tt?this.enqueue([this.dispatch,a,!1,d,o]):this.sendFrame(t.frame(a,d),o)}ping(e,n,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Xr(e)?(o=e.size,a=!1):(e=nr(e),o=e.length,a=nr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};Xr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):Xr(e)?(o=e.size,a=!1):(e=nr(e),o=e.length,a=nr.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[_t]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};Xr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Tt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[vx.extensionName],a=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Xr(e)?(u=e.size,f=!1):(e=nr(e),u=e.length,f=nr.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[_t]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:d};Xr(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Tt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[_t],this._state=mS,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(Zd,this,u,o);return}this._bufferedBytes-=i[_t];let d=nr(a);n?this.dispatch(d,n,i,o):(this._state=Tt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(wS,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[vx.extensionName];this._bufferedBytes+=i[_t],this._state=gS,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");Zd(this,f,o);return}this._bufferedBytes-=i[_t],this._state=Tt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_t],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_t],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Ix.exports=Vd;function Zd(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],a=o[o.length-1];typeof a=="function"&&a(e)}}function wS(t,e,n){Zd(t,e,n),t.onerror(e)}});var Lx=de((bD,Ox)=>{"use strict";var{kForOnEventAttribute:os,kListener:Yd}=nn(),Ax=Symbol("kCode"),kx=Symbol("kData"),Tx=Symbol("kError"),Cx=Symbol("kMessage"),Rx=Symbol("kReason"),ei=Symbol("kTarget"),Px=Symbol("kType"),Dx=Symbol("kWasClean"),sn=class{constructor(e){this[ei]=null,this[Px]=e}get target(){return this[ei]}get type(){return this[Px]}};Object.defineProperty(sn.prototype,"target",{enumerable:!0});Object.defineProperty(sn.prototype,"type",{enumerable:!0});var ir=class extends sn{constructor(e,n={}){super(e),this[Ax]=n.code===void 0?0:n.code,this[Rx]=n.reason===void 0?"":n.reason,this[Dx]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Ax]}get reason(){return this[Rx]}get wasClean(){return this[Dx]}};Object.defineProperty(ir.prototype,"code",{enumerable:!0});Object.defineProperty(ir.prototype,"reason",{enumerable:!0});Object.defineProperty(ir.prototype,"wasClean",{enumerable:!0});var ti=class extends sn{constructor(e,n={}){super(e),this[Tx]=n.error===void 0?null:n.error,this[Cx]=n.message===void 0?"":n.message}get error(){return this[Tx]}get message(){return this[Cx]}};Object.defineProperty(ti.prototype,"error",{enumerable:!0});Object.defineProperty(ti.prototype,"message",{enumerable:!0});var as=class extends sn{constructor(e,n={}){super(e),this[kx]=n.data===void 0?null:n.data}get data(){return this[kx]}};Object.defineProperty(as.prototype,"data",{enumerable:!0});var _S={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[os]&&o[Yd]===e&&!o[os])return;let i;if(t==="message")i=function(a,d){let u=new as("message",{data:d?a:a.toString()});u[ei]=this,ta(e,this,u)};else if(t==="close")i=function(a,d){let u=new ir("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[ei]=this,ta(e,this,u)};else if(t==="error")i=function(a){let d=new ti("error",{error:a,message:a.message});d[ei]=this,ta(e,this,d)};else if(t==="open")i=function(){let a=new sn("open");a[ei]=this,ta(e,this,a)};else return;i[os]=!!n[os],i[Yd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Yd]===e&&!n[os]){this.removeListener(t,n);break}}};Ox.exports={CloseEvent:ir,ErrorEvent:ti,Event:sn,EventTarget:_S,MessageEvent:as};function ta(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var na=de((ED,Nx)=>{"use strict";var{tokenChars:cs}=Yr();function Ht(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function yS(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,u,f=-1,x=-1,p=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),d===void 0)if(p===-1&&cs[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);x===44?(Ht(e,_,n),n=Object.create(null)):d=_,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(p===-1&&cs[x]===1)f===-1&&(f=m);else if(x===32||x===9)p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),Ht(n,t.slice(f,p),!0),x===44&&(Ht(e,d,n),n=Object.create(null),d=void 0),f=p=-1}else if(x===61&&f!==-1&&p===-1)u=t.slice(f,m),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){if(cs[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),o=!1}else if(a)if(cs[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)a=!1,p=m;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)a=!0;else if(p===-1&&cs[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))p===-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let _=t.slice(f,p);i&&(_=_.replace(/\\/g,""),i=!1),Ht(n,u,_),x===44&&(Ht(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(f===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let v=t.slice(f,p);return d===void 0?Ht(e,v,n):(u===void 0?Ht(n,v,!0):i?Ht(n,u,v.replace(/\\/g,"")):Ht(n,u,v),Ht(e,d,n)),e}function bS(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(o=>{let a=i[o];return Array.isArray(a)||(a=[a]),a.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Nx.exports={format:bS,parse:yS}});var oa=de((ID,$x)=>{"use strict";var ES=pe("events"),vS=pe("https"),SS=pe("http"),Fx=pe("net"),IS=pe("tls"),{randomBytes:AS,createHash:kS}=pe("crypto"),{Duplex:vD,Readable:SD}=pe("stream"),{URL:Xd}=pe("url"),Dn=Jr(),TS=$d(),CS=Jd(),{isBlob:RS}=Yr(),{BINARY_TYPES:Mx,CLOSE_TIMEOUT:PS,EMPTY_BUFFER:ra,GUID:DS,kForOnEventAttribute:Qd,kListener:OS,kStatusCode:LS,kWebSocket:Ve,NOOP:zx}=nn(),{EventTarget:{addEventListener:NS,removeEventListener:MS}}=Lx(),{format:BS,parse:FS}=na(),{toBuffer:zS}=is(),Ux=Symbol("kAborted"),el=[8,13],on=["CONNECTING","OPEN","CLOSING","CLOSED"],US=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends ES{constructor(e,n,i){super(),this._binaryType=Mx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ra,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),Hx(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Mx.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let o=new TS({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new CS(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[Ve]=this,a[Ve]=this,e[Ve]=this,o.on("conclude",qS),o.on("drain",jS),o.on("error",WS),o.on("message",KS),o.on("ping",$S),o.on("pong",VS),a.onerror=ZS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",jx),e.on("data",sa),e.on("end",Wx),e.on("error",Kx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Dn.extensionName]&&this._extensions[Dn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ft(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),qx(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){tl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ra,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){tl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ra,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){tl(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Dn.extensionName]||(o.compress=!1),this._sender.send(e||ra,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ft(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_e,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Qd])return e[OS];return null},set(e){for(let n of this.listeners(t))if(n[Qd]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Qd]:!0})}})});_e.prototype.addEventListener=NS;_e.prototype.removeEventListener=MS;$x.exports=_e;function Hx(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:PS,protocolVersion:el[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!el.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${el.join(", ")})`);let a;if(e instanceof Xd)a=e;else try{a=new Xd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),t._url=a.href;let d=a.protocol==="wss:",u=a.protocol==="ws+unix:",f;if(a.protocol!=="ws:"&&!d&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?f="The URL's pathname is empty":a.hash&&(f="The URL contains a fragment identifier"),f){let S=new SyntaxError(f);if(t._redirects===0)throw S;ia(t,S);return}let x=d?443:80,p=AS(16).toString("base64"),m=d?vS.request:SS.request,v=new Set,_;if(o.createConnection=o.createConnection||(d?GS:HS),o.defaultPort=o.defaultPort||x,o.port=a.port||x,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(_=new Dn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=BS({[Dn.extensionName]:_.offer()})),n.length){for(let S of n){if(typeof S!="string"||!US.test(S)||v.has(S))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(S)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),u){let S=o.path.split(":");o.socketPath=S[0],o.path=S[1]}let b;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:a.host;let S=i&&i.headers;if(i={...i,headers:{}},S)for(let[I,T]of Object.entries(S))i.headers[I.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let S=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!S||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,S||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),b=t._req=m(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=m(o);o.timeout&&b.on("timeout",()=>{ft(t,b,"Opening handshake has timed out")}),b.on("error",S=>{b===null||b[Ux]||(b=t._req=null,ia(t,S))}),b.on("response",S=>{let I=S.headers.location,T=S.statusCode;if(I&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ft(t,b,"Maximum redirects exceeded");return}b.abort();let R;try{R=new Xd(I,e)}catch{let P=new SyntaxError(`Invalid URL: ${I}`);ia(t,P);return}Hx(t,R,n,i)}else t.emit("unexpected-response",b,S)||ft(t,b,`Unexpected server response: ${S.statusCode}`)}),b.on("upgrade",(S,I,T)=>{if(t.emit("upgrade",S),t.readyState!==_e.CONNECTING)return;b=t._req=null;let R=S.headers.upgrade;if(R===void 0||R.toLowerCase()!=="websocket"){ft(t,I,"Invalid Upgrade header");return}let E=kS("sha1").update(p+DS).digest("base64");if(S.headers["sec-websocket-accept"]!==E){ft(t,I,"Invalid Sec-WebSocket-Accept header");return}let P=S.headers["sec-websocket-protocol"],D;if(P!==void 0?v.size?v.has(P)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":v.size&&(D="Server sent no subprotocol"),D){ft(t,I,D);return}P&&(t._protocol=P);let M=S.headers["sec-websocket-extensions"];if(M!==void 0){if(!_){ft(t,I,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=FS(M)}catch{ft(t,I,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(N);if(J.length!==1||J[0]!==Dn.extensionName){ft(t,I,"Server indicated an extension that was not requested");return}try{_.accept(N[Dn.extensionName])}catch{ft(t,I,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=_}t.setSocket(I,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(b,t):b.end()}function ia(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function HS(t){return t.path=t.socketPath,Fx.connect(t)}function GS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Fx.isIP(t.host)?"":t.host),IS.connect(t)}function ft(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ft),e.setHeader?(e[Ux]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ia,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function tl(t,e,n){if(e){let i=RS(e)?e.size:zS(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${on[t.readyState]})`);process.nextTick(n,i)}}function qS(t,e){let n=this[Ve];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Ve]!==void 0&&(n._socket.removeListener("data",sa),process.nextTick(Gx,n._socket),t===1005?n.close():n.close(t,e))}function jS(){let t=this[Ve];t.isPaused||t._socket.resume()}function WS(t){let e=this[Ve];e._socket[Ve]!==void 0&&(e._socket.removeListener("data",sa),process.nextTick(Gx,e._socket),e.close(t[LS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Bx(){this[Ve].emitClose()}function KS(t,e){this[Ve].emit("message",t,e)}function $S(t){let e=this[Ve];e._autoPong&&e.pong(t,!this._isServer,zx),e.emit("ping",t)}function VS(t){this[Ve].emit("pong",t)}function Gx(t){t.resume()}function ZS(t){let e=this[Ve];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,qx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function qx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function jx(){let t=this[Ve];if(this.removeListener("close",jx),this.removeListener("data",sa),this.removeListener("end",Wx),t._readyState=_e.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[Ve]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Bx),t._receiver.on("finish",Bx))}function sa(t){this[Ve]._receiver.write(t)||this.pause()}function Wx(){let t=this[Ve];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function Kx(){let t=this[Ve];this.removeListener("error",Kx),this.on("error",zx),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Yx=de((kD,Jx)=>{"use strict";var AD=oa(),{Duplex:JS}=pe("stream");function Vx(t){t.emit("close")}function YS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Zx(t){this.removeListener("error",Zx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function XS(t,e){let n=!0,i=new JS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let u=!d&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(n=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,a){if(t.readyState===t.CLOSED){a(o),process.nextTick(Vx,i);return}let d=!1;t.once("error",function(f){d=!0,a(f)}),t.once("close",function(){d||a(o),process.nextTick(Vx,i)}),n&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,a,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,a,d)});return}t.send(o,d)},i.on("end",YS),i.on("error",Zx),i}Jx.exports=XS});var nl=de((TD,Xx)=>{"use strict";var{tokenChars:QS}=Yr();function e1(t){let e=new Set,n=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&QS[d]===1)n===-1&&(n=o);else if(o!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=o);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let a=t.slice(n,o);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}Xx.exports={parse:e1}});var sp=de((RD,ip)=>{"use strict";var t1=pe("events"),aa=pe("http"),{Duplex:CD}=pe("stream"),{createHash:n1}=pe("crypto"),Qx=na(),sr=Jr(),r1=nl(),i1=oa(),{CLOSE_TIMEOUT:s1,GUID:o1,kWebSocket:a1}=nn(),c1=/^[+/0-9A-Za-z]{22}==$/,ep=0,tp=1,rp=2,rl=class extends t1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:s1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:i1,...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=aa.createServer((i,o)=>{let a=aa.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=d1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,a,d)=>{this.handleUpgrade(o,a,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ep}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===rp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ds,this);return}if(e&&this.once("close",e),this._state!==tp)if(this._state=tp,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(ds,this):process.nextTick(ds,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ds(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,o){n.on("error",np);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){or(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){or(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!c1.test(a)){or(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){or(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ls(n,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=r1.parse(f)}catch{or(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let v=new sr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Qx.parse(p);_[sr.extensionName]&&(v.accept(_[sr.extensionName]),m[sr.extensionName]=v)}catch{or(this,e,n,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,(_,b,S,I)=>{if(!_)return ls(n,b||401,S,I);this.completeUpgrade(m,a,x,e,n,i,o)});return}if(!this.options.verifyClient(v))return ls(n,401)}this.completeUpgrade(m,a,x,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[a1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ep)return ls(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${n1("sha1").update(n+o1).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[sr.extensionName]){let m=e[sr.extensionName].params,v=Qx.format({[sr.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${v}`),p._extensions=e}this.emit("headers",x,o),a.write(x.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&ks(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 qm,mkdirSync as jm}from"node:fs";import{join as Km}from"node:path";function Xl(t){let e=t.retentionDays??Vm,n=t.clock??(()=>Hn(new Date));Cs={bridgeSink:new wi(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:s=>new wi(t.agentLogsDir(s),"agent",{retentionDays:e,clock:n})};let i=n();ks(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])ks(t.agentLogsDir(s),"agent",i,e)}function Zm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Ql(t){Qa=t}function eu(t){return Er[Qa]<=Er[t]}function tu(t,e){let n=Er[t];return n===void 0?!0:n>=Er[e]}function Ps(t){Yl={...t}}function nu(t){let e=(u,f=2)=>String(u).padStart(f,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",s=Math.abs(n),a=e(Math.floor(s/60)),d=e(s%60);return`${Hn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function ot(t,e,n,i,s){try{let a=`${JSON.stringify({ts:nu(new Date),level:e,module:n,msg:i,...s})}
11
+ `;jm(t,{recursive:!0}),qm(Km(t,br("bridge",Hn(new Date))),a)}catch{}}function Jm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function Ts(t,e,n,i,s){if(Er[t]<Er[Qa])return;let a=`${JSON.stringify({ts:nu(new Date),level:t,module:e,msg:n,...Yl,...i})}
12
+ `;if(Cs){let d=Jm(s,i),u=d?Zm(Cs,d):Cs.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?$m.write(a):Wm.write(a)}function H(t,e){return{debug:(n,i)=>Ts("debug",t,n,i,e),info:(n,i)=>Ts("info",t,n,i,e),warn:(n,i)=>Ts("warn",t,n,i,e),error:(n,i)=>Ts("error",t,n,i,e),child:n=>H(`${t}.${n}`,e),forAgent:n=>H(t,n)}}var Er,Qa,Wm,$m,Yl,Vm,Cs,re=st(()=>{"use strict";_r();Xa();Er={debug:10,info:20,warn:30,error:40},Qa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Wm=process.stdout,$m=process.stderr,Yl={},Vm=Ze("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Cs=null});var k,Je=st(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var ou={};Ja(ou,{ACP_WRAPPER_NPM_PACKAGES:()=>Ds,_resetAcpInstallerForTests:()=>nw,_setBinaryPathCacheForTests:()=>rw,buildAcpSpawn:()=>yi,ensureAcpInstalled:()=>Sr,getAcpBinaryPath:()=>Os,pickWhichLine:()=>nc,probeAcpVersion:()=>tw,resolveAcpCommand:()=>su});import{readFileSync as ru}from"node:fs";import{createRequire as Ym}from"node:module";import{dirname as Xm,resolve as Qm}from"node:path";function tc(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function nc(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(s=>s.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function ew(t){let e=iu.resolve(`${t.npmPackage}/package.json`),n=Xm(e),i=JSON.parse(ru(e,"utf8")),s=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!s)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return Qm(n,s)}async function Sr(t,e){let n=ec[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=vr.get(t);if(i)return i;let s=tc(t);if(s)return vr.set(t,s),Rs.info("acp wrapper overridden by env",{framework:t,path:s}),s;try{let a=ew(n);return vr.set(t,a),Rs.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw Rs.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(a)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${n.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:a})}}async function tw(t){let e=ec[t];if(e)try{let n=iu.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(ru(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Rs.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Os(t){return vr.get(t)}function su(t,e){if(e)return e;let n=tc(t);if(n)return n;let i=Os(t);if(!i)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return i}function yi(t,e,n){if(e)return{command:e,args:[...n]};let i=tc(t);if(i)return{command:i,args:[...n]};let s=su(t);return{command:process.execPath,args:[s,...n]}}function nw(){vr.clear()}function rw(t,e){vr.set(t,e)}var Rs,ec,Ds,iu,vr,_n=st(()=>{"use strict";Je();re();Rs=H("agents.acp-installer"),ec={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Ds=Object.values(ec).filter(t=>t!==void 0).map(t=>t.npmPackage),iu=Ym(import.meta.url),vr=new Map});import{chmod as sw,mkdir as ow,readFile as aw,rename as cw,rm as dw,writeFile as lw}from"node:fs/promises";import{dirname as uw}from"node:path";async function gt(t){try{let e=await aw(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function mt(t,e,n){await ow(uw(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await lw(i,e,{encoding:"utf8",mode:n?.mode}),await cw(i,t),n?.mode!==void 0&&await sw(t,n.mode)}catch(s){throw await dw(i,{force:!0}).catch(()=>{}),s}}async function Ot(t,e,n){await mt(t,`${JSON.stringify(e,null,2)}
14
+ `,n)}var Lt=st(()=>{"use strict"});import{promises as du,readdirSync as fw}from"node:fs";import{homedir as hw}from"node:os";import{sep as xw,join as Oe,resolve as lu}from"node:path";function Z(t){let e=t??hw(),n=Oe(e,".coze"),i=Oe(n,"bridge"),s=Oe(i,"lib"),a=Oe(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:s,libEntry:Oe(s,"index.js"),binDir:Oe(i,"bin"),pidFile:Oe(i,"bridge.pid"),portFile:Oe(i,"bridge.port"),tokenFile:Oe(i,"bridge.token"),patTokenFile:Oe(i,"pat-token"),agentEnvFile:Oe(i,"agent-env.json"),logFile:Oe(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Oe(a,"daemon-stdio.log"),installLock:Oe(i,"install.lock"),configFile:Oe(i,"config.json"),agentsRoot:Oe(n,"agents")}}function Le(t,e=Z()){let n=Oe(e.agentsRoot,t);return{root:n,config:Oe(n,"config.json"),workspace:Oe(n,"workspace"),logs:Oe(n,"logs")}}function Ls(t=Z()){try{return fw(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function _i(t,e){let n=await du.realpath(lu(t)).catch(()=>null);if(!n)return!1;let i=await du.realpath(lu(e)).catch(()=>null);if(!i)return!1;let s=process.platform==="win32"?n.toLowerCase():n,a=process.platform==="win32"?i.toLowerCase():i;return s===a||s.startsWith(a+xw)}var Pe=st(()=>{"use strict"});var Ms={};Ja(Ms,{AGENT_CONFIG_FILE_MODE:()=>Ns,enforceAgentConfigMode:()=>mw,loadAgentConfig:()=>me,persistAgentSessions:()=>bi,persistAgentSkills:()=>Ei,saveAgentConfig:()=>Ne});import{chmod as pw,stat as gw}from"node:fs/promises";function me(t,e){return gt(Le(t,e).config)}function Ne(t,e){return Ot(Le(t.agentId,e).config,t,{mode:Ns})}async function mw(t,e){if(process.platform==="win32")return;let n=Le(t,e).config;try{let i=await gw(n);if(!i.isFile())return;let s=i.mode&511;s!==Ns&&(await pw(n,Ns),uu.warn("agent config mode auto-corrected to 0600",{path:n,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;uu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function bi(t,e,n){let i=await me(t,n);i&&(i.sessions=Object.fromEntries(e),await Ne(i,n))}async function Ei(t,e,n){let i=await me(t,n);i&&(i.skills=e,await Ne(i,n))}var uu,Ns,Qt=st(()=>{"use strict";Lt();re();Pe();uu=H("agent-config"),Ns=384});var sc=le((a2,xu)=>{xu.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 Fs=le(gu=>{var pu={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 vw(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(pu))gu[t]=vw(pu[t])});var bu=le((d2,_u)=>{var Sw=ge("fs"),Ue=ge("path"),mu=sc(),Iw=Fs(),Aw=typeof process=="object"&&process.platform==="win32",wu=t=>typeof t=="object"&&t!==null,yu=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ae(t){this.sep=Ue.sep,this.fs=Sw,wu(t)&&wu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}_u.exports=Ae;Ae.prototype.makeDir=function(t){let e=this;function n(i){let s=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){s+=e.sep+a;var d;try{d=e.fs.statSync(s)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw u}if(d&&d.isFile())throw Iw.FILE_IN_THE_WAY(`"${s}"`)}})}n(t)};Ae.prototype.writeFileTo=function(t,e,n,i){let s=this;if(s.fs.existsSync(t)){if(!n)return!1;var a=s.fs.statSync(t);if(a.isDirectory())return!1}var d=Ue.dirname(t);s.fs.existsSync(d)||s.makeDir(d);var u;try{u=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),u=s.fs.openSync(t,"w",438)}if(u)try{s.fs.writeSync(u,e,0,e.length,0)}finally{s.fs.closeSync(u)}return s.fs.chmodSync(t,i||438),!0};Ae.prototype.writeFileToAsync=function(t,e,n,i,s){typeof i=="function"&&(s=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!n)return s(!1);a.fs.stat(t,function(u,f){if(d&&f.isDirectory())return s(!1);var x=Ue.dirname(t);a.fs.exists(x,function(p){p||a.makeDir(x),a.fs.open(t,"w",438,function(m,b){m?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(y,v){a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){s(!0)})})})})}):b?a.fs.write(b,e,0,e.length,0,function(){a.fs.close(b,function(){a.fs.chmod(t,i||438,function(){s(!0)})})}):a.fs.chmod(t,i||438,function(){s(!0)})})})})})};Ae.prototype.findFiles=function(t){let e=this;function n(i,s,a){typeof s=="boolean"&&(a=s,s=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let f=Ue.join(i,u),x=e.fs.statSync(f);(!s||s.test(f))&&d.push(Ue.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(f,s,a)))}),d}return n(t,void 0,!0)};Ae.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(s,a){if(s)return e(s);let d=a.length;if(!d)return e(null,i);a.forEach(function(u){u=Ue.join(t,u),n.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Ue.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(p,m){if(p)return e(p);i=i.concat(m),--d||e(null,i)}):--d||e(null,i))})})})};Ae.prototype.getAttributes=function(){};Ae.prototype.setAttributes=function(){};Ae.crc32update=function(t,e){return yu[(t^e)&255]^t>>>8};Ae.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Ae.crc32update(n,t[i++]);return~n>>>0};Ae.methodToString=function(t){switch(t){case mu.STORED:return"STORED ("+t+")";case mu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ae.canonical=function(t){if(!t)return"";let e=Ue.posix.normalize("/"+t.split("\\").join("/"));return Ue.join(".",e)};Ae.zipnamefix=function(t){if(!t)return"";let e=Ue.posix.normalize("/"+t.split("\\").join("/"));return Ue.posix.join(".",e)};Ae.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let i=n-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ae.sanitize=function(t,e){t=Ue.resolve(Ue.normalize(t));for(var n=e.split("/"),i=0,s=n.length;i<s;i++){var a=Ue.normalize(Ue.join(t,n.slice(i,s).join(Ue.sep)));if(a.indexOf(t)===0)return a}return Ue.normalize(Ue.join(t,Ue.basename(e)))};Ae.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Ae.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Ae.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ae.fromDate2DOS=function(t){let e=0,n=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),n=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|n};Ae.isWin=Aw;Ae.crcTable=yu});var vu=le((l2,Eu)=>{var kw=ge("path");Eu.exports=function(t,{fs:e}){var n=t||"",i=a(),s=null;function a(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(s=e.statSync(n),i.directory=s.isDirectory(),i.mtime=s.mtime,i.atime=s.atime,i.executable=(73&s.mode)!==0,i.readonly=(128&s.mode)===0,i.hidden=kw.basename(n)[0]==="."):console.warn("Invalid path: "+n),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:n,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Iu=le((u2,Su)=>{Su.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var kr=le((f2,Ar)=>{Ar.exports=bu();Ar.exports.Constants=sc();Ar.exports.Errors=Fs();Ar.exports.FileAttr=vu();Ar.exports.decoder=Iu()});var ku=le((h2,Au)=>{var bn=kr(),U=bn.Constants;Au.exports=function(){var t=20,e=10,n=0,i=0,s=0,a=0,d=0,u=0,f=0,x=0,p=0,m=0,b=0,y=0,v=0;t|=bn.isWin?2560:768,n|=U.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,R=E=>Math.max(0,E)&255;return s=bn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&U.FLG_EFS)>0},set flags_efs(E){E?n|=U.FLG_EFS:n&=~U.FLG_EFS},get flags_desc(){return(n&U.FLG_DESC)>0},set flags_desc(E){E?n|=U.FLG_DESC:n&=~U.FLG_DESC},get method(){return i},set method(E){switch(E){case U.STORED:this.version=10;case U.DEFLATED:default:this.version=20}i=E},get time(){return bn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=bn.fromDate2DOS(E)},get timeval(){return s},set timeval(E){s=A(E)},get timeHighByte(){return R(s>>>8)},get crc(){return a},set crc(E){a=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return f},set fileNameLength(E){f=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return p},set commentLength(E){p=E},get diskNumStart(){return m},set diskNumStart(E){m=A(E)},get inAttr(){return b},set inAttr(E){b=A(E)},get attr(){return y},set attr(E){y=A(E)},get fileAttr(){return(y||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(n&U.FLG_ENC)===U.FLG_ENC},get centralHeaderSize(){return U.CENHDR+f+x+p},get realDataOffset(){return v+U.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var P=E.slice(v,v+U.LOCHDR);if(P.readUInt32LE(0)!==U.LOCSIG)throw bn.Errors.INVALID_LOC();I.version=P.readUInt16LE(U.LOCVER),I.flags=P.readUInt16LE(U.LOCFLG),I.flags_desc=(I.flags&U.FLG_DESC)>0,I.method=P.readUInt16LE(U.LOCHOW),I.time=P.readUInt32LE(U.LOCTIM),I.crc=P.readUInt32LE(U.LOCCRC),I.compressedSize=P.readUInt32LE(U.LOCSIZ),I.size=P.readUInt32LE(U.LOCLEN),I.fnameLen=P.readUInt16LE(U.LOCNAM),I.extraLen=P.readUInt16LE(U.LOCEXT);let D=v+U.LOCHDR+I.fnameLen,z=D+I.extraLen;return E.slice(D,z)},loadFromBinary:function(E){if(E.length!==U.CENHDR||E.readUInt32LE(0)!==U.CENSIG)throw bn.Errors.INVALID_CEN();t=E.readUInt16LE(U.CENVEM),e=E.readUInt16LE(U.CENVER),n=E.readUInt16LE(U.CENFLG),i=E.readUInt16LE(U.CENHOW),s=E.readUInt32LE(U.CENTIM),a=E.readUInt32LE(U.CENCRC),d=E.readUInt32LE(U.CENSIZ),u=E.readUInt32LE(U.CENLEN),f=E.readUInt16LE(U.CENNAM),x=E.readUInt16LE(U.CENEXT),p=E.readUInt16LE(U.CENCOM),m=E.readUInt16LE(U.CENDSK),b=E.readUInt16LE(U.CENATT),y=E.readUInt32LE(U.CENATX),v=E.readUInt32LE(U.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(U.LOCHDR);return E.writeUInt32LE(U.LOCSIG,0),E.writeUInt16LE(e,U.LOCVER),E.writeUInt16LE(n,U.LOCFLG),E.writeUInt16LE(i,U.LOCHOW),E.writeUInt32LE(s,U.LOCTIM),E.writeUInt32LE(a,U.LOCCRC),E.writeUInt32LE(d,U.LOCSIZ),E.writeUInt32LE(u,U.LOCLEN),E.writeUInt16LE(f,U.LOCNAM),E.writeUInt16LE(I.extraLen,U.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(U.CENHDR+f+x+p);return E.writeUInt32LE(U.CENSIG,0),E.writeUInt16LE(t,U.CENVEM),E.writeUInt16LE(e,U.CENVER),E.writeUInt16LE(n,U.CENFLG),E.writeUInt16LE(i,U.CENHOW),E.writeUInt32LE(s,U.CENTIM),E.writeUInt32LE(a,U.CENCRC),E.writeUInt32LE(d,U.CENSIZ),E.writeUInt32LE(u,U.CENLEN),E.writeUInt16LE(f,U.CENNAM),E.writeUInt16LE(x,U.CENEXT),E.writeUInt16LE(p,U.CENCOM),E.writeUInt16LE(m,U.CENDSK),E.writeUInt16LE(b,U.CENATT),E.writeUInt32LE(y,U.CENATX),E.writeUInt32LE(v,U.CENOFF),E},toJSON:function(){let E=function(P){return P+" bytes"};return{made:t,version:e,flags:n,method:bn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(f),extraLength:E(x),commentLength:E(p),diskNumStart:m,inAttr:b,attr:y,offset:v,centralHeaderSize:E(U.CENHDR+f+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Cu=le((x2,Tu)=>{var Tr=kr(),be=Tr.Constants;Tu.exports=function(){var t=0,e=0,n=0,i=0,s=0;return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return n},set size(a){n=a},get offset(){return i},set offset(a){i=a},get commentLength(){return s},set commentLength(a){s=a},get mainHeaderSize(){return be.ENDHDR+s},loadFromBinary:function(a){if((a.length!==be.ENDHDR||a.readUInt32LE(0)!==be.ENDSIG)&&(a.length<be.ZIP64HDR||a.readUInt32LE(0)!==be.ZIP64SIG))throw Tr.Errors.INVALID_END();a.readUInt32LE(0)===be.ENDSIG?(t=a.readUInt16LE(be.ENDSUB),e=a.readUInt16LE(be.ENDTOT),n=a.readUInt32LE(be.ENDSIZ),i=a.readUInt32LE(be.ENDOFF),s=a.readUInt16LE(be.ENDCOM)):(t=Tr.readBigUInt64LE(a,be.ZIP64SUB),e=Tr.readBigUInt64LE(a,be.ZIP64TOT),n=Tr.readBigUInt64LE(a,be.ZIP64SIZE),i=Tr.readBigUInt64LE(a,be.ZIP64OFF),s=0)},toBinary:function(){var a=Buffer.alloc(be.ENDHDR+s);return a.writeUInt32LE(be.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,be.ENDSUB),a.writeUInt16LE(e,be.ENDTOT),a.writeUInt32LE(n,be.ENDSIZ),a.writeUInt32LE(i,be.ENDOFF),a.writeUInt16LE(s,be.ENDCOM),a.fill(" ",be.ENDHDR),a},toJSON:function(){let a=function(d,u){let f=d.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:a(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ac=le(oc=>{oc.EntryHeader=ku();oc.MainHeader=Cu()});var Ru=le((g2,Pu)=>{Pu.exports=function(t){var e=ge("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var s=e.createDeflateRaw(n),a=[],d=0;s.on("data",function(u){a.push(u),d+=u.length}),s.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var x=0;x<a.length;x++){var p=a[x];p.copy(u,f),f+=p.length}i&&i(u)}),s.end(t)}}}});var Ou=le((m2,Du)=>{var Tw=+(process.versions?process.versions.node:"").split(".")[0]||0;Du.exports=function(t,e){var n=ge("zlib");let i=Tw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(s){var a=n.createInflateRaw(i),d=[],u=0;a.on("data",function(f){d.push(f),u+=f.length}),a.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var p=0;p<d.length;p++){var m=d[p];m.copy(f,x),x+=m.length}s&&s(f)}),a.end(t)}}}});var Fu=le((w2,Bu)=>{"use strict";var{randomFillSync:Lu}=ge("crypto"),Cw=Fs(),Pw=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Mu=(t,e)=>Math.imul(t,e)>>>0,Nu=(t,e)=>Pw[(t^e)&255]^t>>>8,vi=()=>typeof Lu=="function"?Lu(Buffer.alloc(12)):vi.node();vi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let n=0;n<e;n++)t[n]=Math.random()*256&255;return t};var zs={genSalt:vi};function Us(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let n=0;n<e.length;n++)this.updateKeys(e[n])}Us.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Nu(e[0],t),e[1]+=e[0]&255,e[1]=Mu(e[1],134775813)+1,e[2]=Nu(e[2],e[1]>>>24),t};Us.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Mu(t,t^1)>>8&255};function Rw(t){let e=new Us(t);return function(n){let i=Buffer.alloc(n.length),s=0;for(let a of n)i[s++]=e.updateKeys(a^e.next());return i}}function Dw(t){let e=new Us(t);return function(n,i,s=0){i||(i=Buffer.alloc(n.length));for(let a of n){let d=e.next();i[s++]=a^d,e.updateKeys(a)}return i}}function Ow(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Rw(n),s=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==a)throw Cw.WRONG_PASSWORD();return i(t.slice(12))}function Lw(t){Buffer.isBuffer(t)&&t.length>=12?zs.genSalt=function(){return t.slice(0,12)}:t==="node"?zs.genSalt=vi.node:zs.genSalt=vi}function Nw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=Dw(n),a=zs.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return s(a,d),s(t,d,12)}Bu.exports={decrypt:Ow,encrypt:Nw,_salter:Lw}});var zu=le(Hs=>{Hs.Deflater=Ru();Hs.Inflater=Ou();Hs.ZipCrypto=Fu()});var dc=le((_2,Uu)=>{var ue=kr(),Mw=ac(),ke=ue.Constants,cc=zu();Uu.exports=function(t,e){var n=new Mw.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let p=t,m=typeof p.decoder=="object"?p.decoder:ue.decoder;x=m.hasOwnProperty("efs")?m.efs:!1;function b(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function y(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ue.crc32(E)!==n.localHeader.crc)return!1}else{let P={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==ke.LOCSIG||e.readUInt32LE(D)==ke.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==ke.EXTSIG)P.crc=e.readUInt32LE(D+ke.EXTCRC),P.compressedSize=e.readUInt32LE(D+ke.EXTSIZ),P.size=e.readUInt32LE(D+ke.EXTLEN);else if(e.readUInt16LE(D+12)===19280)P.crc=e.readUInt32LE(D+ke.EXTCRC-4),P.compressedSize=e.readUInt32LE(D+ke.EXTSIZ-4),P.size=e.readUInt32LE(D+ke.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(P.compressedSize!==n.compressedSize||P.size!==n.size||P.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(E)!==P.crc)return!1}return!0}function v(E,P,D){if(typeof P>"u"&&typeof E=="string"&&(D=E,E=void 0),a)return E&&P&&P(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=b();if(z.length===0)return E&&P&&P(z),z;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw ue.Errors.INVALID_PASS_PARAM();z=cc.ZipCrypto.decrypt(z,n,D)}var N=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(z.copy(N),y(N))return E&&P&&P(N),N;throw E&&P&&P(N,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var V=new cc.Inflater(z,n.size);if(E)V.inflateAsync(function($){$.copy($,0),P&&(y($)?P($):P($,ue.Errors.BAD_CRC()))});else{if(V.inflate(N).copy(N,0),!y(N))throw ue.Errors.BAD_CRC(`"${m.decode(i)}"`);return N}break;default:throw E&&P&&P(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(E,P){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&P&&P(b()),b();if(d.length&&!a){var D;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,D=Buffer.alloc(d.length),d.copy(D),E&&P&&P(D),D;default:case ue.Constants.DEFLATED:var z=new cc.Deflater(d);if(E)z.deflateAsync(function(V){D=Buffer.alloc(V.length),n.compressedSize=V.length,V.copy(D),P&&P(D)});else{var N=z.deflate();return n.compressedSize=N.length,N}z=null;break}}else if(E&&P)P(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,P){return ue.readBigUInt64LE(E,P)}function T(E){try{for(var P=0,D,z,N;P+4<E.length;)D=E.readUInt16LE(P),P+=2,z=E.readUInt16LE(P),P+=2,N=E.slice(P,P+z),P+=z,ke.ID_ZIP64===D&&R(N)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function R(E){var P,D,z,N;E.length>=ke.EF_ZIP64_SCOMP&&(P=A(E,ke.EF_ZIP64_SUNCOMP),n.size===ke.EF_ZIP64_OR_32&&(n.size=P)),E.length>=ke.EF_ZIP64_RHO&&(D=A(E,ke.EF_ZIP64_SCOMP),n.compressedSize===ke.EF_ZIP64_OR_32&&(n.compressedSize=D)),E.length>=ke.EF_ZIP64_DSN&&(z=A(E,ke.EF_ZIP64_RHO),n.offset===ke.EF_ZIP64_OR_32&&(n.offset=z)),E.length>=ke.EF_ZIP64_DSN+4&&(N=E.readUInt32LE(ke.EF_ZIP64_DSN),n.diskNumStart===ke.EF_ZIP64_OR_16&&(n.diskNumStart=N))}return{get entryName(){return m.decode(i)},get rawEntryName(){return i},set entryName(E){i=ue.toBuffer(E,m.encode);var P=i[i.length-1];a=P===47||P===92,n.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(E){u=E,n.extraLength=E.length,T(E)},get comment(){return m.decode(s)},set comment(E){if(s=ue.toBuffer(E,m.encode),n.commentLength=s.length,s.length>65535)throw ue.Errors.COMMENT_TOO_LONG()},get name(){var E=m.decode(i);return a?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=ue.toBuffer(E,ue.decoder.encode),!a&&d.length?(n.size=d.length,n.method=ue.Constants.DEFLATED,n.crc=ue.crc32(E),n.changed=!0):n.method=ue.Constants.STORED},getData:function(E){return n.changed?d:v(!1,null,E)},getDataAsync:function(E,P){n.changed?E(d):v(!0,E,P)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var E=n.centralHeaderToBinary(),P=ue.Constants.CENHDR;return i.copy(E,P),P+=i.length,u.copy(E,P),P+=n.extraLength,s.copy(E,P),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let P=n.localHeaderToBinary(),D=Buffer.alloc(P.length+i.length+n.extraLocalLength);return P.copy(D,E),E+=P.length,i.copy(D,E),E+=i.length,f.copy(D,E),E+=f.length,D},toJSON:function(){let E=function(P){return"<"+(P&&P.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var qu=le((b2,Gu)=>{var Hu=dc(),Bw=ac(),Ye=kr();Gu.exports=function(t,e){var n=[],i={},s=Buffer.alloc(0),a=new Bw.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:p,decoder:m}=x;t?v(x.readEntries):d=!0;function b(){let A=new Set;for(let T of Object.keys(i)){let R=T.split("/");if(R.pop(),!!R.length)for(let E=0;E<R.length;E++){let P=R.slice(0,E+1).join("/")+"/";A.add(P)}}for(let T of A)if(!(T in i)){let R=new Hu(x);R.entryName=T,R.attr=16,R.temporary=!0,n.push(R),i[R.entryName]=R,f.add(R)}}function y(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Ye.Constants.CENHDR)throw Ye.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,T=0;T<n.length;T++){var R=A,E=new Hu(x,t);E.header=t.slice(R,R+=Ye.Constants.CENHDR),E.entryName=t.slice(R,R+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(R,R+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(R,R+E.header.commentLength)),A+=E.header.centralHeaderSize,n[T]=E,i[E.entryName]=E}f.clear(),b()}function v(A){var T=t.length-Ye.Constants.ENDHDR,R=Math.max(0,T-65535),E=R,P=t.length,D=-1,z=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(R=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Ye.Constants.ENDSIG){D=T,z=T,P=T+Ye.Constants.ENDHDR,E=T-Ye.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Ye.Constants.END64SIG){E=R;continue}if(t.readUInt32LE(T)===Ye.Constants.ZIP64SIG){D=T,P=T+Ye.readBigUInt64LE(t,T+Ye.Constants.ZIP64SIZE)+Ye.Constants.ZIP64LEAD;break}}if(D==-1)throw Ye.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,P)),a.commentLength&&(s=t.slice(z+Ye.Constants.ENDHDR)),A&&y()}function I(){n.length>1&&!p&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||y(),n.filter(A=>!f.has(A))},get comment(){return m.decode(s)},set comment(A){s=Ye.toBuffer(A,m.encode),a.commentLength=s.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),n.push(A),i[A.entryName]=A,a.totalEntries=n.length},deleteFile:function(A,T=!0){d||y();let R=i[A];this.getEntryChildren(R,T).map(P=>P.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let T=i[A],R=n.indexOf(T);R>=0&&(n.splice(R,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&T){let R=[],E=A.entryName;for(let P of n)P.entryName.startsWith(E)&&R.push(P);return R}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],T=[],R=0,E=0;a.size=0,a.offset=0;let P=0;for(let N of this.entries){let V=N.getCompressedData();N.header.offset=E;let $=N.packLocalHeader(),se=$.length+V.length;E+=se,A.push($),A.push(V);let Q=N.packCentralHeader();T.push(Q),a.size+=Q.length,R+=se+Q.length,P++}R+=a.mainHeaderSize,a.offset=E,a.totalEntries=P,E=0;let D=Buffer.alloc(R);for(let N of A)N.copy(D,E),E+=N.length;for(let N of T)N.copy(D,E),E+=N.length;let z=a.toBinary();return s&&s.copy(z,Ye.Constants.ENDHDR),z.copy(D,E),t=D,d=!1,D},toAsyncBuffer:function(A,T,R,E){try{d||y(),I();let P=[],D=[],z=0,N=0,V=0;a.size=0,a.offset=0;let $=function(se){if(se.length>0){let Q=se.shift(),ce=Q.entryName+Q.extra.toString();R&&R(ce),Q.getCompressedDataAsync(function(ae){E&&E(ce),Q.header.offset=N;let Se=Q.packLocalHeader(),C=Se.length+ae.length;N+=C,P.push(Se),P.push(ae);let q=Q.packCentralHeader();D.push(q),a.size+=q.length,z+=C+q.length,V++,$(se)})}else{z+=a.mainHeaderSize,a.offset=N,a.totalEntries=V,N=0;let Q=Buffer.alloc(z);P.forEach(function(ae){ae.copy(Q,N),N+=ae.length}),D.forEach(function(ae){ae.copy(Q,N),N+=ae.length});let ce=a.toBinary();s&&s.copy(ce,Ye.Constants.ENDHDR),ce.copy(Q,N),t=Q,d=!1,A(Q)}};$(Array.from(this.entries))}catch(P){T(P)}}}}});var Wu=le((E2,Ku)=>{var ve=kr(),Ee=ge("path"),Fw=dc(),zw=qu(),Gn=(...t)=>ve.findLast(t,e=>typeof e=="boolean"),ju=(...t)=>ve.findLast(t,e=>typeof e=="string"),Uw=(...t)=>ve.findLast(t,e=>typeof e=="function"),Hw={noSort:!1,readEntries:!1,method:ve.Constants.NONE,fs:null};Ku.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Hw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=ve.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new ve(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ve.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=ve.Constants.FILE,i.filename=t,n=s.fs.readFileSync(t);else throw ve.Errors.INVALID_FILENAME();let a=new zw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=ve;function x(y){if(y&&a){var v;if(typeof y=="string"&&(v=a.getEntry(Ee.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(v=a.getEntry(y.entryName)),v)return v}return null}function p(y){let{join:v,normalize:I,sep:A}=Ee.posix;return v(Ee.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function m(y){return y instanceof RegExp?(function(v){return function(I){return v.test(I)}})(y):typeof y!="function"?()=>!0:y}let b=(y,v)=>{let I=v.slice(-1);return I=I===s.sep?s.sep:"",Ee.relative(y,v)+I};return{readFile:function(y,v){var I=x(y);return I&&I.getData(v)||null},childCount:function(y){let v=x(y);if(v)return a.getChildCount(v)},readFileAsync:function(y,v){var I=x(y);I?I.getDataAsync(v):v(null,"getEntry failed for:"+y)},readAsText:function(y,v){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(y,v,I){var A=x(y);A?A.getDataAsync(function(T,R){if(R){v(T,R);return}T&&T.length?v(T.toString(I||"utf8")):v("")}):v("")},deleteFile:function(y,v=!0){var I=x(y);I&&a.deleteFile(I.entryName,v)},deleteEntry:function(y){var v=x(y);v&&a.deleteEntry(v.entryName)},addZipComment:function(y){a.comment=y},getZipComment:function(){return a.comment||""},addZipEntryComment:function(y,v){var I=x(y);I&&(I.comment=v)},getZipEntryComment:function(y){var v=x(y);return v&&v.comment||""},updateFile:function(y,v){var I=x(y);I&&I.setData(v)},addLocalFile:function(y,v,I,A){if(s.fs.existsSync(y)){v=v?p(v):"";let T=Ee.win32.basename(Ee.win32.normalize(y));v+=I||T;let R=s.fs.statSync(y),E=R.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);R.isDirectory()&&(v+=s.sep),this.addFile(v,E,A,R)}else throw ve.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,v){y=typeof y=="object"?y:{localPath:y};let I=Ee.resolve(y.localPath),{comment:A}=y,{zipPath:T,zipName:R}=y,E=this;s.fs.stat(I,function(P,D){if(P)return v(P,!1);T=T?p(T):"";let z=Ee.win32.basename(Ee.win32.normalize(I));if(T+=R||z,D.isFile())s.fs.readFile(I,function(N,V){return N?v(N,!1):(E.addFile(T,V,A,D),setImmediate(v,void 0,!0))});else if(D.isDirectory())return T+=s.sep,E.addFile(T,Buffer.alloc(0),A,D),setImmediate(v,void 0,!0)})},addLocalFolder:function(y,v,I){if(I=m(I),v=v?p(v):"",y=Ee.normalize(y),s.fs.existsSync(y)){let A=s.findFiles(y),T=this;if(A.length)for(let R of A){let E=Ee.join(v,b(y,R));I(E)&&T.addLocalFile(R,Ee.dirname(E))}}else throw ve.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,v,I,A){A=m(A),I=I?p(I):"",y=Ee.normalize(y);var T=this;s.fs.open(y,"r",function(R){if(R&&R.code==="ENOENT")v(void 0,ve.Errors.FILE_NOT_FOUND(y));else if(R)v(void 0,R);else{var E=s.findFiles(y),P=-1,D=function(){if(P+=1,P<E.length){var z=E[P],N=b(y,z).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(N)?s.fs.stat(z,function(V,$){V&&v(void 0,V),$.isFile()?s.fs.readFile(z,function(se,Q){se?v(void 0,se):(T.addFile(I+N,Q,"",$),D())}):(T.addFile(I+N+"/",Buffer.alloc(0),"",$),D())}):process.nextTick(()=>{D()})}else v(!0,void 0)};D()}})},addLocalFolderAsync2:function(y,v){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=Ee.resolve(p(y.localPath));let{zipPath:A,filter:T,namefix:R}=y;T instanceof RegExp?T=(function(D){return function(z){return D.test(z)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?p(A):"",R=="latin1"&&(R=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof R!="function"&&(R=D=>D);let E=D=>Ee.join(A,R(b(localPath,D))),P=D=>Ee.win32.basename(Ee.win32.normalize(R(D)));s.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?v(void 0,ve.Errors.FILE_NOT_FOUND(localPath)):D?v(void 0,D):s.findFilesAsync(localPath,function(z,N){if(z)return v(z);N=N.filter(V=>T(E(V))),N.length||v(void 0,!1),setImmediate(N.reverse().reduce(function(V,$){return function(se,Q){if(se||Q===!1)return setImmediate(V,se,!1);I.addLocalFileAsync({localPath:$,zipPath:Ee.dirname(E($)),zipName:P($)},V)}},v))})})},addLocalFolderPromise:function(y,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},v),(T,R)=>{T&&A(T),R&&I(this)})})},addFile:function(y,v,I,A){y=f(y);let T=x(y),R=T!=null;R||(T=new Fw(i),T.entryName=y),T.comment=I||"";let E=typeof A=="object"&&A instanceof s.fs.Stats;E&&(T.header.time=A.mtime);var P=T.isDirectory?16:0;let D=T.isDirectory?16384:32768;return E?D|=4095&A.mode:typeof A=="number"?D|=4095&A:D|=T.isDirectory?493:420,P=(P|D<<16)>>>0,T.attr=P,T.setData(v),R||a.setEntry(T),T},getEntries:function(y){return a.password=y,a?a.entries:[]},getEntry:function(y){return x(y)},getEntryCount:function(){return a.getEntryCount()},forEach:function(y){return a.forEach(y)},extractEntryTo:function(y,v,I,A,T,R){A=Gn(!1,A),T=Gn(!1,T),I=Gn(!0,I),R=ju(T,R);var E=x(y);if(!E)throw ve.Errors.NO_ENTRY();var P=d(E.entryName),D=u(v,R&&!E.isDirectory?R:I?P:Ee.basename(P));if(E.isDirectory){var z=a.getEntryChildren(E);return z.forEach(function($){if($.isDirectory)return;var se=$.getData();if(!se)throw ve.Errors.CANT_EXTRACT_FILE();var Q=d($.entryName),ce=u(v,I?Q:Ee.basename(Q));let ae=T?$.header.fileAttr:void 0;s.writeFileTo(ce,se,A,ae)}),!0}var N=E.getData(a.password);if(!N)throw ve.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(D)&&!A)throw ve.Errors.CANT_OVERRIDE();let V=T?y.header.fileAttr:void 0;return s.writeFileTo(D,N,A,V),!0},test:function(y){if(!a)return!1;for(var v in a.entries)try{if(v.isDirectory)continue;var I=a.entries[v].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,v,I,A){if(I=Gn(!1,I),A=ju(I,A),v=Gn(!1,v),!a)throw ve.Errors.NO_ZIP();a.entries.forEach(function(T){var R=u(y,d(T.entryName));if(T.isDirectory){s.makeDir(R);return}var E=T.getData(A);if(!E)throw ve.Errors.CANT_EXTRACT_FILE();let P=I?T.header.fileAttr:void 0;s.writeFileTo(R,E,v,P);try{s.fs.utimesSync(R,T.header.time,T.header.time)}catch{throw ve.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,v,I,A){if(A=Uw(v,I,A),I=Gn(!1,I),v=Gn(!1,v),!A)return new Promise((D,z)=>{this.extractAllToAsync(y,v,I,function(N){N?z(N):D(this)})});if(!a){A(ve.Errors.NO_ZIP());return}y=Ee.resolve(y);let T=D=>u(y,Ee.normalize(d(D.entryName))),R=(D,z)=>new Error(D+': "'+z+'"'),E=[],P=[];a.entries.forEach(D=>{D.isDirectory?E.push(D):P.push(D)});for(let D of E){let z=T(D),N=I?D.header.fileAttr:void 0;try{s.makeDir(z),N&&s.fs.chmodSync(z,N),s.fs.utimesSync(z,D.header.time,D.header.time)}catch{A(R("Unable to create folder",z))}}P.reverse().reduce(function(D,z){return function(N){if(N)D(N);else{let V=Ee.normalize(d(z.entryName)),$=u(y,V);z.getDataAsync(function(se,Q){if(Q)D(Q);else if(!se)D(ve.Errors.CANT_EXTRACT_FILE());else{let ce=I?z.header.fileAttr:void 0;s.writeFileToAsync($,se,v,ce,function(ae){ae||D(R("Unable to write file",$)),s.fs.utimes($,z.header.time,z.header.time,function(Se){Se?D(R("Unable to set times",$)):D()})})}})}}},A)()},writeZip:function(y,v){if(arguments.length===1&&typeof y=="function"&&(v=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=a.compressToBuffer();if(I){var A=s.writeFileTo(y,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((T,R)=>{!y&&i.filename&&(y=i.filename),y||R("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let P=D=>D?T(D):R("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(y,E,I,A,P)},R)})},toBufferPromise:function(){return new Promise((y,v)=>{a.toAsyncBuffer(y,v)})},toBuffer:function(y,v,I,A){return typeof y=="function"?(a.toAsyncBuffer(y,v,I,A),null):a.compressToBuffer()}}}});import{execFile as J_,spawn as Y_,spawnSync as jT}from"node:child_process";import{promisify as X_}from"node:util";function eb(t){if(process.platform!=="win32")return!1;if(b0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(b0,"").toLowerCase();return Q_.has(n)}function E0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return eb(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function ct(t,e=[],n={}){return Y_(t,e,E0(t,n))}function v0(t,e=[],n={}){return tb(t,e,E0(t,n))}var Q_,b0,tb,an=st(()=>{"use strict";Q_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),b0=/\.(cmd|bat|ps1)$/i;tb=X_(J_)});var un=le((mO,Px)=>{"use strict";var Tx=["nodebuffer","arraybuffer","fragments"],Cx=typeof Blob<"u";Cx&&Tx.push("blob");Px.exports={BINARY_TYPES:Tx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Cx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var fs=le((wO,ta)=>{"use strict";var{EMPTY_BUFFER:CS}=un(),Wd=Buffer[Symbol.species];function PS(t,e){if(t.length===0)return CS;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let s=0;s<t.length;s++){let a=t[s];n.set(a,i),i+=a.length}return i<e?new Wd(n.buffer,n.byteOffset,i):n}function Rx(t,e,n,i,s){for(let a=0;a<s;a++)n[i+a]=t[a]^e[a&3]}function Dx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function RS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function $d(t){if($d.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Wd(t):ArrayBuffer.isView(t)?e=new Wd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),$d.readOnly=!1),e}ta.exports={concat:PS,mask:Rx,toArrayBuffer:RS,toBuffer:$d,unmask:Dx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ge("bufferutil");ta.exports.mask=function(e,n,i,s,a){a<48?Rx(e,n,i,s,a):t.mask(e,n,i,s,a)},ta.exports.unmask=function(e,n){e.length<32?Dx(e,n):t.unmask(e,n)}}catch{}});var Nx=le((yO,Lx)=>{"use strict";var Ox=Symbol("kDone"),Vd=Symbol("kRun"),Zd=class{constructor(e){this[Ox]=()=>{this.pending--,this[Vd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Vd]()}[Vd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ox])}}};Lx.exports=Zd});var ii=le((_O,zx)=>{"use strict";var hs=ge("zlib"),Mx=fs(),DS=Nx(),{kStatusCode:Bx}=un(),OS=Buffer[Symbol.species],LS=Buffer.from([0,0,255,255]),ra=Symbol("permessage-deflate"),fn=Symbol("total-length"),ni=Symbol("callback"),Mn=Symbol("buffers"),ri=Symbol("error"),na,Jd=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,!na){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;na=new DS(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ni];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let s=n[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=s})}),e}decompress(e,n,i){na.add(s=>{this._decompress(e,n,(a,d)=>{s(),i(a,d)})})}compress(e,n,i){na.add(s=>{this._compress(e,n,(a,d)=>{s(),i(a,d)})})}_decompress(e,n,i){let s=this._isServer?"client":"server";if(!this._inflate){let a=`${s}_max_window_bits`,d=typeof this.params[a]!="number"?hs.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=hs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[ra]=this,this._inflate[fn]=0,this._inflate[Mn]=[],this._inflate.on("error",MS),this._inflate.on("data",Fx)}this._inflate[ni]=i,this._inflate.write(e),n&&this._inflate.write(LS),this._inflate.flush(()=>{let a=this._inflate[ri];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Mx.concat(this._inflate[Mn],this._inflate[fn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fn]=0,this._inflate[Mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let s=this._isServer?"server":"client";if(!this._deflate){let a=`${s}_max_window_bits`,d=typeof this.params[a]!="number"?hs.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=hs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[fn]=0,this._deflate[Mn]=[],this._deflate.on("data",NS)}this._deflate[ni]=i,this._deflate.write(e),this._deflate.flush(hs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Mx.concat(this._deflate[Mn],this._deflate[fn]);n&&(a=new OS(a.buffer,a.byteOffset,a.length-4)),this._deflate[ni]=null,this._deflate[fn]=0,this._deflate[Mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};zx.exports=Jd;function NS(t){this[Mn].push(t),this[fn]+=t.length}function Fx(t){if(this[fn]+=t.length,this[ra]._maxPayload<1||this[fn]<=this[ra]._maxPayload){this[Mn].push(t);return}this[ri]=new RangeError("Max payload size exceeded"),this[ri].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ri][Bx]=1009,this.removeListener("data",Fx),this.reset()}function MS(t){if(this[ra]._inflate=null,this[ri]){this[ni](this[ri]);return}t[Bx]=1007,this[ni](t)}});var si=le((bO,ia)=>{"use strict";var{isUtf8:Ux}=ge("buffer"),{hasBlob:BS}=un(),FS=[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 zS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Yd(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function US(t){return BS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ia.exports={isBlob:US,isValidStatusCode:zS,isValidUTF8:Yd,tokenChars:FS};if(Ux)ia.exports.isValidUTF8=function(t){return t.length<24?Yd(t):Ux(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ge("utf-8-validate");ia.exports.isValidUTF8=function(e){return e.length<32?Yd(e):t(e)}}catch{}});var nl=le((EO,$x)=>{"use strict";var{Writable:HS}=ge("stream"),Hx=ii(),{BINARY_TYPES:GS,EMPTY_BUFFER:Gx,kStatusCode:qS,kWebSocket:jS}=un(),{concat:Xd,toArrayBuffer:KS,unmask:WS}=fs(),{isValidStatusCode:$S,isValidUTF8:qx}=si(),sa=Buffer[Symbol.species],bt=0,jx=1,Kx=2,Wx=3,Qd=4,el=5,oa=6,tl=class extends HS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||GS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[jS]=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=bt}_write(e,n,i){if(this._opcode===8&&this._state==bt)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new sa(i.buffer,i.byteOffset+e,i.length-e),new sa(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=n.length-e;e>=i.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new sa(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case bt:this.getInfo(e);break;case jx:this.getPayloadLength16(e);break;case Kx:this.getPayloadLength64(e);break;case Wx:this.getMask();break;case Qd:this.getData(e);break;case el:case oa:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let i=(n[0]&64)===64;if(i&&!this._extensions[Hx.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=jx:this._payloadLength===127?this._state=Kx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Wx:this._state=Qd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Qd}getData(e){let n=Gx;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&WS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=el,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hx.extensionName].decompress(e,this._fin,(s,a)=>{if(s)return n(s);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}this._fragments.push(a)}this.dataMessage(n),this._state===bt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=bt;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Xd(i,n):this._binaryType==="arraybuffer"?s=KS(Xd(i,n)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=bt):(this._state=oa,setImmediate(()=>{this.emit("message",s,!0),this._state=bt,this.startLoop(e)}))}else{let s=Xd(i,n);if(!this._skipUTF8Validation&&!qx(s)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===el||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=bt):(this._state=oa,setImmediate(()=>{this.emit("message",s,!1),this._state=bt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gx),this.end();else{let i=e.readUInt16BE(0);if(!$S(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let s=new sa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!qx(s)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(a);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=bt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=bt):(this._state=oa,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=bt,this.startLoop(n)}))}createError(e,n,i,s,a){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=a,d[qS]=s,d}};$x.exports=tl});var sl=le((SO,Jx)=>{"use strict";var{Duplex:vO}=ge("stream"),{randomFillSync:VS}=ge("crypto"),Vx=ii(),{EMPTY_BUFFER:ZS,kWebSocket:JS,NOOP:YS}=un(),{isBlob:oi,isValidStatusCode:XS}=si(),{mask:Zx,toBuffer:ur}=fs(),Et=Symbol("kByteLength"),QS=Buffer.alloc(4),aa=8*1024,fr,ai=aa,Pt=0,e1=1,t1=2,rl=class t{constructor(e,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Pt,this.onerror=YS,this[JS]=void 0}static frame(e,n){let i,s=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||QS,n.generateMask?n.generateMask(i):(ai===aa&&(fr===void 0&&(fr=Buffer.alloc(aa)),VS(fr,0,aa),ai=0),i[0]=fr[ai++],i[1]=fr[ai++],i[2]=fr[ai++],i[3]=fr[ai++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[Et]!==void 0?u=n[Et]:(e=Buffer.from(e),u=e.length):(u=e.length,s=n.mask&&n.readOnly&&!d);let f=u;u>=65536?(a+=8,f=127):u>125&&(a+=2,f=126);let x=Buffer.allocUnsafe(s?u+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:s?(Zx(e,i,x,a,u),[x]):(Zx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,s){let a;if(e===void 0)a=ZS;else{if(typeof e!="number"||!XS(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(e,0);else{let u=Buffer.byteLength(n);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+u),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let d={[Et]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Pt?this.enqueue([this.dispatch,a,!1,d,s]):this.sendFrame(t.frame(a,d),s)}ping(e,n,i){let s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):oi(e)?(s=e.size,a=!1):(e=ur(e),s=e.length,a=ur.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[Et]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};oi(e)?this._state!==Pt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Pt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):oi(e)?(s=e.size,a=!1):(e=ur(e),s=e.length,a=ur.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[Et]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};oi(e)?this._state!==Pt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Pt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let s=this._extensions[Vx.extensionName],a=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):oi(e)?(u=e.size,f=!1):(e=ur(e),u=e.length,f=ur.readOnly),this._firstFragment?(this._firstFragment=!1,d&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=s._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[Et]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:d};oi(e)?this._state!==Pt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Pt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,s){this._bufferedBytes+=i[Et],this._state=t1,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(il,this,u,s);return}this._bufferedBytes-=i[Et];let d=ur(a);n?this.dispatch(d,n,i,s):(this._state=Pt,this.sendFrame(t.frame(d,i),s),this.dequeue())}).catch(a=>{process.nextTick(n1,this,a,s)})}dispatch(e,n,i,s){if(!n){this.sendFrame(t.frame(e,i),s);return}let a=this._extensions[Vx.extensionName];this._bufferedBytes+=i[Et],this._state=e1,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");il(this,f,s);return}this._bufferedBytes-=i[Et],this._state=Pt,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===Pt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Et],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Et],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Jx.exports=rl;function il(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let s=t._queue[i],a=s[s.length-1];typeof a=="function"&&a(e)}}function n1(t,e,n){il(t,e,n),t.onerror(e)}});var sp=le((IO,ip)=>{"use strict";var{kForOnEventAttribute:xs,kListener:ol}=un(),Yx=Symbol("kCode"),Xx=Symbol("kData"),Qx=Symbol("kError"),ep=Symbol("kMessage"),tp=Symbol("kReason"),ci=Symbol("kTarget"),np=Symbol("kType"),rp=Symbol("kWasClean"),hn=class{constructor(e){this[ci]=null,this[np]=e}get target(){return this[ci]}get type(){return this[np]}};Object.defineProperty(hn.prototype,"target",{enumerable:!0});Object.defineProperty(hn.prototype,"type",{enumerable:!0});var hr=class extends hn{constructor(e,n={}){super(e),this[Yx]=n.code===void 0?0:n.code,this[tp]=n.reason===void 0?"":n.reason,this[rp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Yx]}get reason(){return this[tp]}get wasClean(){return this[rp]}};Object.defineProperty(hr.prototype,"code",{enumerable:!0});Object.defineProperty(hr.prototype,"reason",{enumerable:!0});Object.defineProperty(hr.prototype,"wasClean",{enumerable:!0});var di=class extends hn{constructor(e,n={}){super(e),this[Qx]=n.error===void 0?null:n.error,this[ep]=n.message===void 0?"":n.message}get error(){return this[Qx]}get message(){return this[ep]}};Object.defineProperty(di.prototype,"error",{enumerable:!0});Object.defineProperty(di.prototype,"message",{enumerable:!0});var ps=class extends hn{constructor(e,n={}){super(e),this[Xx]=n.data===void 0?null:n.data}get data(){return this[Xx]}};Object.defineProperty(ps.prototype,"data",{enumerable:!0});var r1={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[xs]&&s[ol]===e&&!s[xs])return;let i;if(t==="message")i=function(a,d){let u=new ps("message",{data:d?a:a.toString()});u[ci]=this,ca(e,this,u)};else if(t==="close")i=function(a,d){let u=new hr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[ci]=this,ca(e,this,u)};else if(t==="error")i=function(a){let d=new di("error",{error:a,message:a.message});d[ci]=this,ca(e,this,d)};else if(t==="open")i=function(){let a=new hn("open");a[ci]=this,ca(e,this,a)};else return;i[xs]=!!n[xs],i[ol]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ol]===e&&!n[xs]){this.removeListener(t,n);break}}};ip.exports={CloseEvent:hr,ErrorEvent:di,Event:hn,EventTarget:r1,MessageEvent:ps};function ca(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var da=le((AO,op)=>{"use strict";var{tokenChars:gs}=si();function Vt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function i1(t){let e=Object.create(null),n=Object.create(null),i=!1,s=!1,a=!1,d,u,f=-1,x=-1,p=-1,m=0;for(;m<t.length;m++)if(x=t.charCodeAt(m),d===void 0)if(p===-1&&gs[x]===1)f===-1&&(f=m);else if(m!==0&&(x===32||x===9))p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let y=t.slice(f,p);x===44?(Vt(e,y,n),n=Object.create(null)):d=y,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(u===void 0)if(p===-1&&gs[x]===1)f===-1&&(f=m);else if(x===32||x===9)p===-1&&f!==-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),Vt(n,t.slice(f,p),!0),x===44&&(Vt(e,d,n),n=Object.create(null),d=void 0),f=p=-1}else if(x===61&&f!==-1&&p===-1)u=t.slice(f,m),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(s){if(gs[x]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);f===-1?f=m:i||(i=!0),s=!1}else if(a)if(gs[x]===1)f===-1&&(f=m);else if(x===34&&f!==-1)a=!1,p=m;else if(x===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(x===34&&t.charCodeAt(m-1)===61)a=!0;else if(p===-1&&gs[x]===1)f===-1&&(f=m);else if(f!==-1&&(x===32||x===9))p===-1&&(p=m);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let y=t.slice(f,p);i&&(y=y.replace(/\\/g,""),i=!1),Vt(n,u,y),x===44&&(Vt(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(f===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let b=t.slice(f,p);return d===void 0?Vt(e,b,n):(u===void 0?Vt(n,b,!0):i?Vt(n,u,b.replace(/\\/g,"")):Vt(n,u,b),Vt(e,d,n)),e}function s1(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(s=>{let a=i[s];return Array.isArray(a)||(a=[a]),a.map(d=>d===!0?s:`${s}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}op.exports={format:s1,parse:i1}});var ha=le((CO,wp)=>{"use strict";var o1=ge("events"),a1=ge("https"),c1=ge("http"),dp=ge("net"),d1=ge("tls"),{randomBytes:l1,createHash:u1}=ge("crypto"),{Duplex:kO,Readable:TO}=ge("stream"),{URL:al}=ge("url"),Bn=ii(),f1=nl(),h1=sl(),{isBlob:x1}=si(),{BINARY_TYPES:ap,CLOSE_TIMEOUT:p1,EMPTY_BUFFER:la,GUID:g1,kForOnEventAttribute:cl,kListener:m1,kStatusCode:w1,kWebSocket:$e,NOOP:lp}=un(),{EventTarget:{addEventListener:y1,removeEventListener:_1}}=sp(),{format:b1,parse:E1}=da(),{toBuffer:v1}=fs(),up=Symbol("kAborted"),dl=[8,13],xn=["CONNECTING","OPEN","CLOSING","CLOSED"],S1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends o1{constructor(e,n,i){super(),this._binaryType=ap[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=la,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),fp(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ap.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let s=new f1({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new h1(e,this._extensions,i.generateMask);this._receiver=s,this._sender=a,this._socket=e,s[$e]=this,a[$e]=this,e[$e]=this,s.on("conclude",k1),s.on("drain",T1),s.on("error",C1),s.on("message",P1),s.on("ping",R1),s.on("pong",D1),a.onerror=O1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",pp),e.on("data",fa),e.on("end",gp),e.on("error",mp),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[Bn.extensionName]&&this._extensions[Bn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ht(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),xp(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ll(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||la,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ll(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||la,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ll(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Bn.extensionName]||(s.compress=!1),this._sender.send(e||la,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ht(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_e,"CONNECTING",{enumerable:!0,value:xn.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:xn.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:xn.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:xn.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:xn.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:xn.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:xn.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:xn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[cl])return e[m1];return null},set(e){for(let n of this.listeners(t))if(n[cl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[cl]:!0})}})});_e.prototype.addEventListener=y1;_e.prototype.removeEventListener=_1;wp.exports=_e;function fp(t,e,n,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:p1,protocolVersion:dl[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!dl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${dl.join(", ")})`);let a;if(e instanceof al)a=e;else try{a=new al(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),t._url=a.href;let d=a.protocol==="wss:",u=a.protocol==="ws+unix:",f;if(a.protocol!=="ws:"&&!d&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?f="The URL's pathname is empty":a.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;ua(t,I);return}let x=d?443:80,p=l1(16).toString("base64"),m=d?a1.request:c1.request,b=new Set,y;if(s.createConnection=s.createConnection||(d?A1:I1),s.defaultPort=s.defaultPort||x,s.port=a.port||x,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(y=new Bn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=b1({[Bn.extensionName]:y.offer()})),n.length){for(let I of n){if(typeof I!="string"||!S1.test(I)||b.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(I)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),u){let I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let v;if(s.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?s.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),v=t._req=m(s),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=m(s);s.timeout&&v.on("timeout",()=>{ht(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[up]||(v=t._req=null,ua(t,I))}),v.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&s.followRedirects&&T>=300&&T<400){if(++t._redirects>s.maxRedirects){ht(t,v,"Maximum redirects exceeded");return}v.abort();let R;try{R=new al(A,e)}catch{let P=new SyntaxError(`Invalid URL: ${A}`);ua(t,P);return}fp(t,R,n,i)}else t.emit("unexpected-response",v,I)||ht(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==_e.CONNECTING)return;v=t._req=null;let R=I.headers.upgrade;if(R===void 0||R.toLowerCase()!=="websocket"){ht(t,A,"Invalid Upgrade header");return}let E=u1("sha1").update(p+g1).digest("base64");if(I.headers["sec-websocket-accept"]!==E){ht(t,A,"Invalid Sec-WebSocket-Accept header");return}let P=I.headers["sec-websocket-protocol"],D;if(P!==void 0?b.size?b.has(P)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":b.size&&(D="Server sent no subprotocol"),D){ht(t,A,D);return}P&&(t._protocol=P);let z=I.headers["sec-websocket-extensions"];if(z!==void 0){if(!y){ht(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=E1(z)}catch{ht(t,A,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(N);if(V.length!==1||V[0]!==Bn.extensionName){ht(t,A,"Server indicated an extension that was not requested");return}try{y.accept(N[Bn.extensionName])}catch{ht(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Bn.extensionName]=y}t.setSocket(A,T,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(v,t):v.end()}function ua(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function I1(t){return t.path=t.socketPath,dp.connect(t)}function A1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=dp.isIP(t.host)?"":t.host),d1.connect(t)}function ht(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,ht),e.setHeader?(e[up]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ua,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ll(t,e,n){if(e){let i=x1(e)?e.size:v1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${xn[t.readyState]})`);process.nextTick(n,i)}}function k1(t,e){let n=this[$e];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[$e]!==void 0&&(n._socket.removeListener("data",fa),process.nextTick(hp,n._socket),t===1005?n.close():n.close(t,e))}function T1(){let t=this[$e];t.isPaused||t._socket.resume()}function C1(t){let e=this[$e];e._socket[$e]!==void 0&&(e._socket.removeListener("data",fa),process.nextTick(hp,e._socket),e.close(t[w1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function cp(){this[$e].emitClose()}function P1(t,e){this[$e].emit("message",t,e)}function R1(t){let e=this[$e];e._autoPong&&e.pong(t,!this._isServer,lp),e.emit("ping",t)}function D1(t){this[$e].emit("pong",t)}function hp(t){t.resume()}function O1(t){let e=this[$e];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,xp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function pp(){let t=this[$e];if(this.removeListener("close",pp),this.removeListener("data",fa),this.removeListener("end",gp),t._readyState=_e.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[$e]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",cp),t._receiver.on("finish",cp))}function fa(t){this[$e]._receiver.write(t)||this.pause()}function gp(){let t=this[$e];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function mp(){let t=this[$e];this.removeListener("error",mp),this.on("error",lp),t&&(t._readyState=_e.CLOSING,this.destroy())}});var Ep=le((RO,bp)=>{"use strict";var PO=ha(),{Duplex:L1}=ge("stream");function yp(t){t.emit("close")}function N1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function _p(t){this.removeListener("error",_p),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function M1(t,e){let n=!0,i=new L1({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let u=!d&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(n=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,a){if(t.readyState===t.CLOSED){a(s),process.nextTick(yp,i);return}let d=!1;t.once("error",function(f){d=!0,a(f)}),t.once("close",function(){d||a(s),process.nextTick(yp,i)}),n&&t.terminate()},i._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(s,a,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(s,a,d)});return}t.send(s,d)},i.on("end",N1),i.on("error",_p),i}bp.exports=M1});var ul=le((DO,vp)=>{"use strict";var{tokenChars:B1}=si();function F1(t){let e=new Set,n=-1,i=-1,s=0;for(s;s<t.length;s++){let d=t.charCodeAt(s);if(i===-1&&B1[d]===1)n===-1&&(n=s);else if(s!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=s);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}vp.exports={parse:F1}});var Pp=le((LO,Cp)=>{"use strict";var z1=ge("events"),xa=ge("http"),{Duplex:OO}=ge("stream"),{createHash:U1}=ge("crypto"),Sp=da(),xr=ii(),H1=ul(),G1=ha(),{CLOSE_TIMEOUT:q1,GUID:j1,kWebSocket:K1}=un(),W1=/^[+/0-9A-Za-z]{22}==$/,Ip=0,Ap=1,Tp=2,fl=class extends z1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:q1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:G1,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=xa.createServer((i,s)=>{let a=xa.STATUS_CODES[426];s.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),s.end(a)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=$1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,a,d)=>{this.handleUpgrade(s,a,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ip}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===Tp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ms,this);return}if(e&&this.once("close",e),this._state!==Ap)if(this._state=Ap,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(ms,this):process.nextTick(ms,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ms(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,s){n.on("error",kp);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){pr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){pr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!W1.test(a)){pr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){pr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ws(n,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=H1.parse(f)}catch{pr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let b=new xr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Sp.parse(p);y[xr.extensionName]&&(b.accept(y[xr.extensionName]),m[xr.extensionName]=b)}catch{pr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={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(b,(y,v,I,A)=>{if(!y)return ws(n,v||401,I,A);this.completeUpgrade(m,a,x,e,n,i,s)});return}if(!this.options.verifyClient(b))return ws(n,401)}this.completeUpgrade(m,a,x,e,n,i,s)}completeUpgrade(e,n,i,s,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[K1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ip)return ws(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${U1("sha1").update(n+j1).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;m&&(x.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[xr.extensionName]){let m=e[xr.extensionName].params,b=Sp.format({[xr.extensionName]:[m]});x.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",x,s),a.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),a.removeListener("error",np),p.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ds,this)})),u(p,o)}};ip.exports=rl;function d1(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function ds(t){t._state=rp,t.emit("close")}function np(){this.destroy()}function ls(t,e,n,i){n=n||aa.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${aa.STATUS_CODES[e]}\r
17
- `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
16
+ `)),a.removeListener("error",kp),p.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ms,this)})),u(p,s)}};Cp.exports=fl;function $1(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function ms(t){t._state=Tp,t.emit("close")}function kp(){this.destroy()}function ws(t,e,n,i){n=n||xa.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${xa.STATUS_CODES[e]}\r
17
+ `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+n)}function or(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,or),t.emit("wsClientError",d,n,e)}else ls(n,i,o,a)}});var wp=de(Ce=>{"use strict";var L=B;(function(t,e){let n=B,i=t();for(;;)try{if(-parseInt(n(725))/1*(-parseInt(n(1743))/2)+parseInt(n(1641))/3*(parseInt(n(409))/4)+parseInt(n(1854))/5*(parseInt(n(1582))/6)+parseInt(n(1596))/7+parseInt(n(1726))/8+parseInt(n(1519))/9*(parseInt(n(476))/10)+-parseInt(n(1528))/11===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(xa,238802);var m1=Object["definePr"+L(933)],w1=Object[L(952)+L(939)+L(1287)],hp=(t,e)=>function(){return t&&(e=(0,t[w1(t)[0]])(t=0)),e},_1=(t,e)=>{let n={hrSON:function(o,a,d,u){return o(a,d,u)}};for(var i in e)n.hrSON(m1,t,i,{get:e[i],enumerable:!0})};function y1(){return cp||(cp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function b1(){let t=L;return dp||(dp=[IDBCursor.prototype[t(972)],IDBCursor[t(875)+"e"].continue,IDBCursor.prototype["continue"+t(720)+"ey"]])}function E1(t){let e=L,n={yadPC:e(443),ICJac:"error",jMGRr:function(o,a){return o!==a},bWQNO:e(1193),jmbTo:function(o,a){return o(a)},JMDCn:function(o){return o()},MJVyJ:function(o,a){return o|a},YOZis:function(o,a){return o&a},guqRf:function(o,a){return o>>a},QjEMe:function(o,a){return o(a)},aZdTx:function(o,a){return o===a},hJdjm:e(1553),miTWF:function(o,a){return o instanceof a}},i=new Promise((o,a)=>{let d=e,u={fFOct:function(m,v){return n[B(1749)](m,v)},HRRiW:function(m,v){return m&v},lDZnW:function(m,v){return n[B(1749)](m,v)},BjCdV:function(m,v){return n[B(1428)](m,v)},scFpB:function(m,v){return n[B(496)](m,v)},WgIAi:function(m,v){return n[B(1428)](m,v)},VuDmZ:function(m,v){return m+v},StUcu:function(m,v){return m+v},kgfcb:function(m,v){return m<<v},nkXjn:function(m,v){return n.QjEMe(m,v)},NYVtv:function(m){return n.JMDCn(m)}},f=()=>{let m=B;t[m(1550)+m(1436)+"ner"](n[m(1138)],x),t[m(1550)+m(1436)+"ner"](n[m(1458)],p)},x=()=>{let m=B;if(n.jMGRr("sRGpJ",n[m(1844)])){let v=(m(736)+"3|0").split("|"),_=0;for(;;){switch(v[_++]){case"0":_0x268e70[_0x54ae72++]=u[m(400)](u[m(970)](63,_0x2160a6),128);continue;case"1":_0x1024c1[_0x21badc++]=u.lDZnW(u[m(1518)](u[m(499)](_0x36b4d0,12),63),128);continue;case"2":++_0x502a47;continue;case"3":_0x237382[_0x10ee95++]=u[m(400)](u[m(1565)](_0x5295ac>>6,63),128);continue;case"4":_0x14fea1[_0x46049c++]=u[m(1150)](u.scFpB(_0x23dfa0,18),240);continue;case"5":_0x361025=u[m(1488)](u[m(1744)](65536,u.kgfcb(u.WgIAi(1023,_0x46fec6),10)),1023&_0x43e320);continue}break}}else n[m(1705)](o,n.jmbTo(qt,t[m(762)])),n[m(734)](f)},p=()=>{let m=B;u[m(1007)](a,t[m(749)]),u.NYVtv(f)};t["addEvent"+d(1810)](n[d(1138)],x),t[d(1323)+d(1810)](n[d(1458)],p)});return i[e(1663)](o=>{let a=e;if(n[a(907)](n[a(501)],a(1827)))return!!_0x478832?.[a(1457)](d=>d[a(1484)]===_0x598226&&d.value===_0x398c70);n[a(1487)](o,IDBCursor)&&sl[a(598)](o,t)})[e(660)](()=>{}),fa[e(598)](i,t),i}function v1(t){let e=L,n={ciUQJ:e(749),EhvXc:e(1575),CsKHN:function(o){return o()},rcYFz:"complete"};if(ua[e(1106)](t))return;let i=new Promise((o,a)=>{let d=e,u={yOiKV:function(m,v){return m(v)},iTuZU:d(613)+"or"},f=()=>{let m=d;t[m(1550)+m(1436)+"ner"](m(508),x),t[m(1550)+m(1436)+m(871)](n[m(1736)],p),t[m(1550)+m(1436)+m(871)](n.EhvXc,p)},x=()=>{let m=d;o(),n[m(1580)](f)},p=()=>{let m=d;u[m(865)](a,t[m(749)]||new DOMException(m(613)+"or",u[m(850)])),f()};t[d(1323)+d(1810)](n[d(1097)],x),t.addEventListener(n[d(1736)],p),t[d(1323)+d(1810)]("abort",p)});ua[e(598)](t,i)}function S1(t){ha={DTVYR:function(i,o){return i(o)}}[L(500)](t,ha)}function I1(t){let e=L,n={ZkrLB:function(i,o){return i(o)},SiNoC:function(i,o){return i(o)},jcvBP:function(i,o){return i(o)},FVTRl:function(i,o){return i(o)},TGhXo:function(i,o){return i===o},oIedZ:function(i,o){return i in o},aIxem:function(i,o){return i===o},gekGa:e(1128),noqEq:"ywEyB",nISkQ:function(i){return i()}};return n.TGhXo(t,IDBDatabase[e(875)+"e"]["transact"+e(1729)])&&!n[e(539)](e(1218)+e(815),IDBTransaction[e(875)+"e"])?n[e(713)](n[e(1203)],n[e(1717)])?_0xe7dc9a["objectSt"+e(815)]||_0x13bbb4[e(493)](_0x19118b):function(i,...o){let a=e,d=t[a(444)](n[a(1185)](us,this),i,...o);return il.set(d,i[a(874)]?i[a(874)]():[i]),n[a(790)](qt,d)}:n[e(1475)](b1).includes(t)?function(...i){let o=e;return t[o(662)](n[o(732)](us,this),i),n[o(732)](qt,sl[o(493)](this))}:function(...i){let o=e;return qt(t[o(662)](n[o(1209)](us,this),i))}}function A1(t){let e=L,n={Uitqb:function(i,o){return i===o},afDPP:function(i,o){return i(o)},QflQX:function(i,o,a){return i(o,a)}};return n.Uitqb(typeof t,e(1115))?n[e(1024)](I1,t):(t instanceof IDBTransaction&&n[e(1024)](v1,t),n[e(1186)](xp,t,y1())?new Proxy(t,ha):t)}function qt(t){let e=L,n={ScWOz:function(o,a){return o instanceof a},qJkxo:function(o,a){return o(a)}};if(n[e(668)](t,IDBRequest))return n.qJkxo(E1,t);if(da.has(t))return da[e(493)](t);let i=n.qJkxo(A1,t);return i!==t&&(da.set(t,i),fa[e(598)](i,t)),i}var xp,cp,dp,sl,ua,il,da,fa,ha,us,lp=hp({"node_modules/idb/build/wrap-idb-value.js"(){let t=L,e={rgxYu:t(443),DVaDX:t(948)+t(557)+"s",ArGIA:t(948)+t(1304)+"t",AuGZK:function(n,i){return n===i},vntll:t(1472),UYnYV:function(n,i){return n instanceof i},wycrl:function(n,i){return n===i},MYpXm:t(1094),tEFHr:function(n,i){return n===i},ycSEd:t(1218)+t(815),VxLSY:t(532),fdUFn:function(n,i){return n(i)},FvcLx:function(n,i){return n>i},KiYBI:function(n,i){return n!==i},qBxmT:t(583)};xp=(n,i)=>i[t(1507)](o=>n instanceof o),sl=new WeakMap,ua=new WeakMap,il=new WeakMap,da=new WeakMap,fa=new WeakMap,ha={get(n,i,o){let a=t,d={aVPiy:e[a(1297)],VVksm:e.ArGIA};if(e.AuGZK(e[a(688)],a(849))){let u={WyRKk:e[a(505)],Irhcn:e[a(1297)]};return new _0x34cf4a((f,x)=>{let p=a,m={JdJJv:function(b,S){return b(S)},cBDWM:d.aVPiy,HevVO:d[p(1720)]};this[p(1846)+"ngTimer"](),this[p(944)+p(1801)+"Id"]=_0x1ef742(this[p(1264)][p(1072)](this),this[p(979)]["pingInte"+p(419)]);let v=()=>{let b=p;f(u.WyRKk),this.off(u.Irhcn,v),this[b(1397)](b(948)+b(1304)+"t",_)},_=()=>{let b=p;m[b(696)](x,b(1692)),this[b(1397)](m.cBDWM,v),this[b(1397)](m.HevVO,_)};this.on(d[p(1019)],v),this.on(d[p(1720)],_),this[p(1264)]()})}else{if(e[a(1053)](n,IDBTransaction)){if(e[a(1192)](i,e.MYpXm))return ua[a(493)](n);if(e[a(942)](i,e[a(710)]))return n[a(1218)+a(815)]||il[a(493)](n);if(e.AuGZK(i,e.VxLSY))return o[a(1218)+a(815)][1]?void 0:o.objectStore(o[a(1218)+"oreNames"][0])}return e[a(898)](qt,n[i])}},set(n,i,o){return n[i]=o,!0},has(n,i){let o=t,a={dLvbH:function(d,u){return d*u},buzvd:function(d,u){return e[B(1833)](d,u)}};if(e[o(510)](e[o(1110)],e[o(1110)])){let{initReconnectInterval:d,maxReconnectInterval:u,reconnectIntervalGrowFactor:f}=this._options,x=a.dLvbH(d,_0x33bbab.pow(f,_0x1f4f1b-1));return a.buzvd(x,u)?u:x}else return n instanceof IDBTransaction&&(e[o(1192)](i,e.MYpXm)||i===e[o(1336)])?!0:i in n}},us=n=>fa.get(n)}}),pp={};_1(pp,{deleteDB:()=>T1,openDB:()=>k1,unwrap:()=>us,wrap:()=>qt});function k1(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=L,u={aiPvn:function(p,m,v,_,b){return p(m,v,_,b)},QOdCC:function(p,m){return p(m)},eKeLL:function(p,m){return p(m)},pLhAP:d(438),OnFmC:d(1234),mBlZv:d(1144)+d(1165),FmFSV:d(1109)},f=indexedDB[d(1430)](t,e),x=qt(f);return i&&(u[d(1411)]!=="WrzYh"?f[d(1323)+d(1810)](u[d(929)],p=>{let m=d;u[m(1427)](i,u[m(506)](qt,f.result),p[m(1462)+"on"],p[m(1511)+"on"],u[m(454)](qt,f["transact"+m(1729)]))}):this[d(1179)+d(1025)]()),n&&f[d(1323)+d(1810)](u.FmFSV,()=>n()),x[d(1663)](p=>{let m=d;a&&p[m(1323)+"Listener"](u.pLhAP,()=>a()),o&&p["addEvent"+m(1810)](m(877)+m(1769),()=>o())})[d(660)](()=>{}),x}function T1(t,{blocked:e}={}){let n=L,i={piJWJ:n(1109),zwjqK:function(a,d){return a(d)}},o=indexedDB[n(1622)+n(1056)](t);return e&&o[n(1323)+n(1810)](i.piJWJ,()=>e()),i.zwjqK(qt,o)[n(1663)](()=>{})}function up(t,e){let n=L,i={TBbLK:function(f,x,p){return f(x,p)},zVjDI:n(438),PUFBl:function(f,x){return f>x},rAllV:function(f,x){return f+x},zBDjt:n(811)+n(864),URdRm:n(1545)+"e",geUUI:n(642),bJvZo:function(f,x){return f instanceof x},qnmvK:function(f,x){return f in x},sKXvk:function(f,x){return f===x},hOCmJ:function(f,x){return f!==x},dkOoc:n(1758),efKpo:function(f,x){return f!==x},pewvb:"QeUsh"};if(!(i[n(1529)](t,IDBDatabase)&&!i[n(1279)](e,t)&&i.sKXvk(typeof e,"string")))if(i.hOCmJ(i[n(1295)],i[n(1295)])){let f=this[n(979)]["reconnec"+n(873)+n(669)](_0x3bdc43,_0x59c66e);this[n(1255)+"hCloseEv"+n(741)](i[n(758)](_0x504f16,i.zVjDI,{code:_0x85c859,reason:_0x5985cf,wasClean:!0,willReconnect:f})),f&&this[n(892)]()}else return;if(la[n(493)](e))return la[n(493)](e);let o=e[n(893)](/FromIndex$/,""),a=i[n(1291)](e,o),d=mp.includes(o);if(!i[n(1279)](o,(a?IDBIndex:IDBObjectStore).prototype)||!(d||gp.includes(o))){if(i[n(797)]===i[n(797)])return;{let f=_0x16b17d[n(1344)];if(i[n(1767)](i[n(588)](f,_0x247daf),_0x1b2528.limit))throw new _0x3a0fb9(i[n(971)]);return _0x2612b3.offset+=_0x561c0f,f}}let u=async function(f,...x){let p=n,m=this[p(483)+p(1729)](f,d?i.URdRm:i[p(1821)]),v=m[p(532)];return a&&(v=v.index(x[p(674)]())),(await Promise[p(1180)]([v[o](...x),d&&m[p(1094)]]))[0]};return la[n(598)](e,u),u}function xa(){let t=["DMfS","q291BNq","CgXLyxnLiha","CMvHC29U","y2HLy2Tszwe","x2vUzhbVAw4","Dg9oDw1Izxi","uwTzywG","CNn1wxa","wMHOqNK","qLLSvMy","yNzqDvq","DuTVzNi","DgHLBG","DgXttLu","wfHjt2S","wxP0wuq","ihzHBgLKigq","Bg93","ihjLy29UBMu","CwrrDMG","zxj2AwnL","t0vrr2y","EgvqsMq","zgvIDwC","rw5hwM4","uKHyEg4","q3vZDg9Tq2W","Eu5It00","DfvTqM0","CNDpvK0","qxvQtMq","q3PMqvG","twvZC2fNzuu","zwX0tw8","suTUrfm","Bg9Nsurhzw4","AwXLx25HBwu","C2v0sxrLBq","uwzHEfi","y2vZC0HHBMq","ihrPBwvVDxq","DgLTzw91Da","yxnL","C2v0u3rVCMe","rwXXt2W","y29UC3rYDwm","vw5Oyw5KBgu","AxnmB25N","AevYCM9Yrxy","zw1PDa","t01LzwO","rgDyDLu","rvvMu1i","BMrWB2LUDfq","AM1Ivg8","Dxrjza","EfrVruC","A2HvELO","ugjlAhK","tM1syKm","x3bHDgHlzxK","D0fIDxm","qxz1C0K","C2nNzvG","CwTSu28","y3vYC29Yx2y","BM9Xrxe","x19LC01Vzhu","x2n1CNnVCK0","vLzRC20","BgLZDgvUtMu","m3WWFdf8mNW","uKTXEK0","tfDdqM8","B3v0sw50zxi","mZuZmdyYne1gzwHWCG","AgLMyNC","z2v0u3rVCMe","Aw9U","y3ndwe8","C3vIyxjYyxK","ugvpyLi","v2vPEgLUsLm","C0DACxG","vxLbz2C","y2LvuuO","x3jLBw92zvC","q29Kzq","vLPNEuq","DeDVBui","y2XLyxjtDg8","zxzTC3O","neLMD2LAqW","u3rvy3u","B3n6CM0","qLH2rwW","Dgzfy1G","tMfTzq","tuPwEuO","rurKzw4","DerhDKO","CM92AwrLige","yM9KEq","vgfN","DgHLs28","BwHSzMW","EMTlBhG","yu5lzwO","rNjVBNrPzxi","qu5oqve","BNHOEgK","nxW3Fdn8nhW","DMvUDa","Dw5RBM93BIa","C1L2z3C","C2v0zgi","ufvgqMW","C2vUzf9Hy2S","AgfUz2u","C0nVDw50zxi","uMzovfK","AwXK","rhHwtKe","AvHIthK","EwrvCM4","DxP1CMi","uLvZrwq","zvvYBa","zMXVB3i","uKvZvM0","DcbVzIbYyw4","z2vtEw5J","BwfW","teXLqLC","CwHqC2C","rLb4v2i","Aw5L","B3LItLq","qKrABve","ywnRtxnNswq","igzHAwWSig0","q1nhCLi","svzyBxq","Ag1cCgO","BwvY","x29UtwvZC2e","qMDivhu","ywjetey","Ae1LC3nHz2u","D2LSBfjLy28","z1rPBwvVDxq","Bu56uvG","twLZC2LUzYa","id4G","CMvJzwL2zwq","x2XPC3rLBMu","t3nYsui","CMvTB3zLq2G","zfDVCMTLCKC","tgLZDgvUzxi","Aw5KzxGGB3u","q0Xpu0ve","BwvZC2fNzq","s01iCxe","z0zoufC","tMH4y1a","sg9sCwe","B25JBg9Zzq","CMvZB2X2zq","AeTnsKi","z2vvvuK","rNznz04","BhPhEeq","y29UBMvJDca","DhjPzxmGCMu","te5wAge","BMPPy0e","Ehfywfu","DgLUzYbZzxi","yKHiAwK","C3rLBMvYCW","BwHssMC","rNzJthG","ywXty29Wzq","z1DHyuy","uMD4tfq","zw50zwqGDhK","zgf0yq","DvvgwuS","BgLTAxq","v2fqv1q","uxrIze0","zNjVBuHHC2G","yLDrtK8","DgnWs1u","x2nSzwfYugK","A0fRAeK","tg5iAKW","z3fHz3O","wfrOAMG","yNL0zu9MzNm","B25szwnLAxy","ANzKEhK","mtG2nJu4mgvqAMfRzq","wKLOzKi","yxGGCMv0CMK","ChvUtxi","wgjhy2W","yvf2yKe","CNnVCL92ywW","Bwv0Ag9K","AgXyqLa","vvfkuMG","AMH3uhi","ywnRx2nVzgu","Bhbquxy","sxH3swG","vhjXD28","B3jRzxjhBg8","vw9hrvu","yM9L","ywrKq291BNq","uxDozgq","sLbAtg8","z3PTuM0","t0PrDxq","t1bftL9fuLi","uMTvvuK","r1PQyNu","D2rNq00","yxrHlcbKyxq","t0rvB0q","m3W0Fdv8mxW","y29UDgLUDwu","rwL1Bvm","DgrRqMu","y2HLy2TdDxi","ug96svq","ChbL","BuLtAhi","Ce5wz0y","uu1VDem","CMfTzq","Dg9cExrLC0i","zKzpy3q","suvtx0vsuK8","rhHuqKm","wwLSEe8","Aw50zwDLCIa","zNLUAKq","y3P4q1C","yw5Hz2vY","sfHHyK0","mJbxy0roqvi","DKXcDwK","sLzuA2e","DK1HvMi","uwj0CMq","CgLUz1rPBwu","u2HHCMvKv28","AxnAzxjV","DMLJzuLeig8","q3vZDg9Trxi","CNzHBa","rfb4Bw0","qvbTBw4","sgvUre4","yNvMzMvYzwq","wufICg4","B25LCNjVCG","AvLTtK0","BM93","uMvJB25Uzwm","yMfSu2nVCgu","B3jpBMXPBMu","BezSDxnO","C011r1i","BIWGAg9ZDg4","EhHtzw4","BKngAhi","A1jlwMG","BKHZy3y","y2XVC2u","sKXhDgy","u1ncqNK","rKLmrv9ot1q","wKT5tg4","C3vJy2vZCW","y2fSBa","Cgvquey","z2v0qwXS","CgfNzxnOB3C","lcbOB3n0BMe","De1rBfO","tMHYCg0","t1vrD28","qxvZtKy","v0LVvMC","zuTLteW","tunqC1e","r1jIEwS","yKTuExi","CMvZzxrfBMq","rvjst1i","CNnVCL9Uyw0","zu9ACvG","qvjpEvO","CMvZzxrdB3u","y3vYC29Yx24","mdaWma","BwDjCK0","BxnNsuq","CMj5CuG","q29UzMLN","yMfSrxzLBNq","zNjVBNrPzxi","s1nHrgW","ExbL","sufsqNy","uxvLDwu","ntG5ntbLtKrgqxq","CgfYC2u","z3HHt00","rLfQvM4","Cgf5Bg9Hzfq","Axnby2TdBgu","tw5wv08","DhjHBNnHy3q","Dwvytgu","wNv5ueK","B25dBg9Zzq","D24GCMvHC28","sKHZwMe","ChvZAa","qw1VDw50","x2HHBMrSzva","zgv2AwnLx2K","z2v0","y3jLyxrLt3a","EuHfy2G","z3vXuMy","BgvY","wwXeBfu","C2ngCei","rfrwwvi","AePKAM0","BgLUzq","Aw5N","yvjku0S","CMD4wxu","uu9Kq0m","B25VCgvU","y29TCgXLDgu","yxbWzw5Kq2G","s2LzqKK","shL0wNe","wfv5Egy","q1PSsfe","y3vYC29Y","ywrK","q1zpvwq","zxjHDg9Y","x3nLBMrby2S","s1rTCNu","t2jQzwn0","AgX4t3a","x2LZsw5PDa","zNjVBujPDhm","tfDvyK4","yxbWBgLJyxq","shnnBwK","CfvSAhK","wwr6ANe","Bg9IywXty28","BgDtzKm","rNPHCuO","C3rVCMu","qM1YzLO","zg1XD1G","CNzHBfzHBhu","x2TLEvbHDgG","rw5AreW","rvzkAuq","B0LLzfO","z0P1tMS","BwvKAwf0zwW","v0XLwvO","B2nRzxrtDwm","EKD5C2K","Ef9MCM9UDgK","uwHLrKW","sxn2CM8","Bg9N","EfDWwwS","z2u6ia","s2v2Au8","D2fZq2XLyw4","x2fKzfDZtgK","C2vUDa","BLDvwfy","uK1ADKG","zv9ZDwnJzxm","wM5vDhG","BwvZC2fNztO","yLfJqvu","AK52vfa","u2rjzwe","qLfJsNm","u2vYDMLJzvC","BwXrqxO","Ec1TC2CTCw8","qvjHr28","swzXreK","AwXSihvZzsa","y29UBMvJDa","q05JEe8","CIb0DhDjra","DhLWzq","DNz2D0K","Au9JC0S","BgLUzw5V","DLnYDwK","sw9wB1O","s2vWtMi","Dgv4Dc9WBge","ChjVy2vZCW","C3vIC3rYAw4","vgf2yKG","ugD0wKm","x2LZv29YA2u","z1r0Axa","qKfwsKu","CKfSBfy","zKXruNi","vxfQt00","ANndz2y","CgLUz09Uy2u","Cw9Iug4","BfHyrK8","zw5JB2rLrNi","DeLK","vKzhwLm","C2v0","zwjfqNa","wKnfAM8","yxnjtfa","yvP4Bey","AxnszwfKEq","zKz3rg4","nxWWFdH8m3W","yNL0zxm","yw10thy","DxP6BNa","DgvyCui","DxDiwfK","x2rItMfTzq","tK1MCwO","qwjVCNrfCNi","BeDRzwm","zw5HyMXLqxu","zNjHBwvuExa","sgznD2O","x2LUAxq","u2DIugK","z2L2Eg4","Ae5wr1K","yNj1uwC","tvHzD3G","pxv0zI04","uNrSDg0","y2HADMS","z29PBMCGyxC","BfDQBha","BMvLzf9Hy2S","yNLL","y2nTDMm","sgDSrfy","qM5KEfO","EhLuzfC","sMfxAuG","uunJuLy","Dgv4DfbHEwW","CgfNzwHPzgu","ueniyvC","BK9oA04","AhbhuuS","CMvHzg9UBhK","rKrOv1K","x29UvgLTzw8","DxjS","C0jf","y3ruAw1LB3u","zefwr2G","A3LhAhu","sKXowfq","ihzHBgLKihm","zfz6vfO","Cg9PBNrdB24","BxbXwM0","y29Kzq","Ae9Wzw5fDMu","x29UrxjYB3i","r2rQwLy","B2zMBgLUzq","y2f0y2G","BMrWB2LUDca","yxbWBhK","DgfcD2G","zgjqD1q","CMLLC0nVDw4","y05pu00","C2v0q3vYC28","u2nxt3O","ChrVCG","y3ntz1m","B3jcy28","Bu11yxq","wKTjA04","C2HPzNq","sNvmsgu","ig1LC3nHz2u","u2vXsuq","vMLHD3u","z3Poyui","rw1kBvm","y1H0Ew4","ywHVBfm","runArui","yMrJuLu","ENnJreS","B3nLza","qMjyr0S","DM50BgW","mdaWmdaWmda","Dw5ZAwDUzwq","q2TxtwW","y2D1v2K","EevyuM0","CgTisM0","uwzYB3e","sMrksNy","vvvpthK","yxrLq291BNq","Cu5HAha","Cgf5Bg9Hzeu","EhLgv3C","yKLQD0S","BMv4DcGPigm","x2rYB3bhBg8","y3jLyxrLq2W","EePcvw4","su5Nruy","zMzmAw5L","B3bLBKrc","Ewntrwq","Dhj1y3rVCIa","BNfYwNG","yuL4zw0","DNzbrvG","DMfSDwu","x3jLy29UBMu","zgrjrcWGzgu","vhbTA1m","B0fKwgO","uhjPBwfYEuS","sLLWs2i","EfDUBvm","Aw5KzxHpzG","B3nLrxzLBNq","mtG2mZmXEwPUEMDd","DhDVCMTdAge","vLrztKm","Dg9tDhjPBMC","svP0yxm","yxnZAwDU","Cfzxzfi","AMn2qLa","EMHQsK4","sK1eq24","sufQt1i","nxWYFdr8mxW","DgvZDa","vvnKCxK","C0XPC3rLBMu","x3bYB3rVy28","zw50","vhbdB2O","CMvHzhLtDge","qKnHtLq","tKj5C0u","zwDhz20","EMnJAvC","rMLPA1q","zxjYB3i","vvrQu0S","Ew1WENG","q09oveLovuu","A1n0yxr1C0m","q3HLzvi","BwLUAvbYB2C","l3DZl3yY","BfDOywK","vejIteS","zw5HyMXLuw8","ALLKDLe","wfv5AfC","CMvZDwX0","yMLUyxj5vhK","Ee1mvMm","C3rYAw5N","y0fgt0y","BMnVzgLUzW","ANnfA2W","Dw50","ywnRx2LK","tKrqrK4","B2HMsvi","qNvHDgS","zxjFDhrS","x2LUAxrhBg8","r3L6sMG","uu9qvwO","thHPBNC","ExHYrvi","Aw9tCLy","qxvqsfm","DhbizwfKzxi","ywnR","ywXSzwqGBxu","B25mAw5L","ywDLu2HVDW","v21XAwq","x2HHBMrSzvi","uMjeqvO","u2LoB0m","z2v0q3vYCMu","CM92AwrLihy","q0Xpu0LorW","qLbkqxO","y2uGBM90igK","vKnPEvu","Cgv3DMi","Dg9cExrLCW","r1P5rNC","yxv0B21HDgK","uLjpuG","zxLduuW","y29Uy2f0","Bgf2uxK","BwLUzW","svLXqw0","wfbLB2e","r1zoz1y","B25ozxr3B3i","x2rLyNvN","uMvHzcbWyxm","wKjzs0W","rwrjsMe","zw5fDMvUDa","B3jLtMfTzxm","x0rctMfTzq","C2DPza","AfLjD1O","vMfyA1y","uNrLyxC","BwfUDwfSihi","DvbnuLO","Dev2zw50","tK1TrNe","DvPmBey","sfbjz3i","ugP2s0m","rfzmChy","y2TcA2O","yw1L","y2XLyxi","C2vYDMvYvgK","BNruCMLLC0m","yNvMzMvY","ywrKt25L","tg9JAW","uMn1wNa","rePpwfC","tg9Nsuq","CKDuqLG","t3bLBKv2zw4","x3bYzwzPEa","BNrbBMrvCgq","CMvQzwn0","yw5Nzq","D3m6lY8","zgLZCgf0y2G","CMTLCKDSB2i","sxzjy2W","Avr1wLu","rejpBve","CKHzyKK","C2f0D2G","zw1LBNq","renqwhG","AenSB3nLrxy","zcWGDw5RBM8","zvjLu2G","BMCGzMfPBgu","Ahr0Ca","AwXLtMfTzq","rhLOsvG","rw9UtMu","DcbSAw1PDa","Eu9Ps1y","AgXRCMy","seL1CMi","weLwuwW","B2fK","BMnLq2XVC2u","BMvY","ywX3yxLZ","DeLUDgvYy2u","C29YDa","ChjVDg90Exa","zxjFCw9Zx2e","DMvYC2LVBMm","ufnqyve","tevfsvm","Dg9hzw5LCMe","x29Uq2XVC2u","y0DurLa","EvndD1q","Cw9pBfK","BxPWvui","BML0AwfSAxO","x2HHBMrSzu8","Aw47y2HHCNm","sMjqsw4","yxvwDeq","B25pCgvU","x2nVBM5Ly3q","CMvWBgfJzq","sxztDe4","Bxnotgq","DMTYzeG","x2nYzwf0zvm","zMrvrM4","x2n1CNnVCKy","AMP6zKi","ve5cr2K","A2T2ueu","AwTXrgW","z1bAq2y","CePwzhm","AgfZt3DUuhi","yvPKvhG","uMn3Cee","zxH0zw5ZAw8","zxjFywnRx20","rxjYB3jdB2q","BuTMwem","qNjQsKG","B1zmqKO","CwvJAfG","zerJt04","u2Xmzgi","tenABMi","rgXLy04","zM9YrwfJAa","vgLTzw91Da","yw51Ce1LC3m","qvHfvum","A2vhEui","AhrVrg4","zw5HyMXLvhi","yMvkANy","D3DZqxe","BujSwNy","z3vWwxG","CKLSzg4","y29UBMvJDfm","B3bLCNr5","x21PBMLoyxy","C2vYDMLJzq","uwP6z3e","EuXJyxK","BfbusLG","B3bLCNr5tMe","zNjVBunOyxi","tfroB2m","Devgshi","yvbcyNK","x3bPBMDqB24","D3nZoI8V","r2jTv3O","m3WXFdb8nhW","CgLUz19VBMm","qwX4Exe","z2vY","tffVve8","z2v0t3DUuhi","Ec1TC2CTy3u","D0LnAxe","x2LZtwLUAvC","CMfUzg9T","CMfNzvn5BMm","DgHHBIbSB2m","yw1Lu3bHy2u","igzPzwXKoIa","rxnetKG","DxfnAMi","q1bRzwe","BM5Ly3q","DxrMofDYAxq","yMPRA0u","AgvHzgvYCW","tuvtu0fhrv8","DLHYC0q","sfjsAvC","EKjeANq","ywr2yw5Jzq","ug9KyMi","Dg9mB3DLCKm","vxfAq1O","sxz6Bue","BLH2ueG","sgPWDM4","x29WDgLVBNm","vw9iqKK","rvvVAwC","yvzIswi","Dg9iyxnO","zMDRuxq","Cg15zuS","CYbWyxjHBxm","x25HDMLNyxq","ihrPBwvZ","A2fmrgC","BMrLEa","A2v5CW","s2ngA2K","y29SBM8","se96zLC","DMvY","BuzRCwy","vMvds1y","C3nHz2vfDMu","Cw9nzfK","tufgEwW","uvHjCeO","CYbHBhjLywq","BLfhz0i","CvDjzhy","rNLTDfC","BejetKO","BMTyAM4","suzLvxi","tKHozMq","AMvJDfn0B3i","x1fVu01HBMe","EfnYvxa","qwrpCLC","sw10r2m","q3DYAwO","Cw9Zx18","x3DHAxq","tufyx1jfvfi","yvzqAxK","mNWW","zuXxsLO","A2v0ignVBNm","CgLUz0XVC3m","ywzeufa","AxjLza","qwLwz00","zgDQyLK","u2TPCcbWyxm","ufrPCfe","vvb3svO","CYbPBNn0yw4","tg9NsurozxC","B3zwvhy","DgLTzw91DcW","yLPpr2C","AwjUwNK","C0r6C3u","v25pD1u","vK16y3m","vwXWCva","ywXPzcb1CMW","rMLkBwq","A25ODfy","zw5KCg9PBNq","DNHJBem","sLLWzxC","s3L4C2q","v2LUzg93","rNbLEfC","CMffrvq","Aw5Lza","B2nRzxq","vvLUwvy","D0TQEuy","Au5Mt1O","DgfIyxnL","DLzrq2m","z2rOCxi","zxHqruC","BxnN","ywzL","z0LOsuC","uNP2t3C","wenfEw0","DhrzD2e","D09rwxm","tMrRzLi","Cg9PBNrbBMq","y3jLyxrLuMu","ywfzuvi","B0XVA2K","yMLUza","y29UDgv4Da","ihn1y2nLC3m","q09otKvdveK","r2DIEKi","y3vYCMvUDeK","vuLqqKC","CxvYwxK","y1rJvMe","yMLUyxj5","zLjvsvG","AMv5uvK","Dg9Y","BwLZzq","yLLUrwm","EeTvy0S","Curbz1G","AM9PBG","EfDrvgy","x2LUDgvYDMe","EgzcC0e","uhnZEeC","zg9Uzq","r21fAuG","sgXAD1m","CMnzrNO","C2nYAxb0","Dgv4Dc9Qyxy","Aw9Ul2PZB24","Aw5cwMe","AMDPA1q","D3jPDgvvAw4","zw5XDwv1zq","D0XtEKW","AgfZ","AMntqNa","BM5HCeu","yMXVy2TLza","Cuj4Bvq","vuThzMG","zxjFCw9Z","rLDt","D3jPDgu","zNvUy3rPB24","C2XPy2u","AvHOtMG","x2jPBMfYEvq","uNvIEe0","EKT5uLm","zxjYtxnN","t1bftG","wuLbqNK","EM92y3O","zgLZywjSzue","C0Xf","u1rHB0y","EKjQvwe","s0nbDhy","EvjLy29UBMu","zvHfwNq","AxnFywnR","zxmGCMvHy2G","BhPVtNu","s1H1Chu","q3rHqLK","BwvZC2fNzv8","EwfKuem","DNreA3i","t0retg8","zxHWB3j0CW","nNWYFdf8ma","y2PHs1q","DxbNCMfKzw4","o2nOyxjZzxq","uwPgy2u","u3rYyxrLz3K","icSG","ENbcuLa","BerABLC","tKfusvzfx0u","B3vUDa","z01hvfa","vLzSrhi","ywDLsgLKzq","lcbTyxGGCMu","r3PRyuy","CM9YrxzLBNq","CwrQqLe","tuX1B3i","zwrPyxrLBhK","svPVCg4","vwr4wLG","tujIwNG","zwvKzwq","y1j0DNe","B2jJALq","x3nVy2TLDa","B3LYEM0","vKfgrLu","whPbzgW","ze94CNe","tK9vwfu","CM92AwrLihC","Bg9xqMi","ywnOzwqSihC","yNPrCuG","x3jLywr5q2W","zMX1C2HfEha","ywXS","B0nSzuS","A0rsvfq","uxHqEey","yxrNqwS","wMTYtei","uwzSuvG","wvnZtvm","BM9Uzv9UB24","r3L6zxO","DgLLCKPtt04","BeHHBMrSzxi","D3LJCMW","C1jhCeO","y1n2sNi","AgvHzgvY","BfrPBwvVDxq","vwXdtKG","tKDFrvjst1i","zcbLCNjVCI4","zwn6wvm","y2HnyxHuCMK","tvj4rNC","z2vRr2e","vKTYyKq","wvHMwwm","CgjRzgG","y3jLyxrLrxi","vwvZvKK","rLzuuMW","r1jwCe0","rgvKAwnHDgu","whLxugS","t1Hjthm","v2XVBwG","B0nduK8","zgvSzxrL","suDnwNi","B2jQzwn0u3q","qwvIDMC","rxjxyxa","AwrI","sgTjA2C","zNjVBu51Bwi","EwzJEhK","De1HBMfNzxi","uxnzv20","ANnerMK","rfnwDMy","y2HnyxHdB3u","ywnRDxbfBMq","wfjABuS","Ee1Rse4","CgvYC2LZDgu","Bfv3qw4","Aw9UvgLTzw8","yxKSihrYEsa","ENPnCuS","zM9Yy2u","qxHfEfK","nxWZFdb8mxW","u1LjwwS","BvPfugm","swTOuwy","DvrRsfm","y3vYCMvUDeu","AfDqtNK","AwDHDg9Yt24","u0jpy3G","ENrStuK","ufb3uKy","BMCGB3iGyw4","x3nLCuLK","rvHrs1m","z2v0sxrLBq","x2rPC3bHDgm","AgLNAa","z1DyBgy","CNjVCK1LC3m","ExPgBKi","ALD2B2i","D2vI","r0HfqNa","vLHpr1i","x3bPBMC","vuv2Bhy","sMLmrNe","z1L3AKG","AenVv3C","DerZt3C","wu5SqKC","EMXPyKG","z2v0s2v5","y3vlwNO","BuXbCfu","zxzPu0O","t2vlzxq","mxW0Fdb8mNW","Dwz0AgW","Cw5TDKS","vhfABwi","EK5MBvm","EhfAqNK","r3L4rNm","ze1Js3C","B2nRzxrgywK","rvD6Afq","BwvZ","ywDLrxzLBNq","EhDVr2u","D1fSBKy","zwzlCg8","ENzyDe0","z29MsfC","CMfTugfYyw0","zgTpB2m","DhjPzxm","rfzHrfG","y3jLyxrLt2i","yNrIr2m","y3jLyxrLtwu","sezjB20","B01nC2K","B1DTCKW","zv90Aw1LB3u","zMLSDgvY","EwHqrei","qMjMr2i","q3bqy28","AefJA01LC3m","C0n0s1C","BKfLswu","r1LZwhO","t01PwgG","C21OAxa","AgvKtwf4uMu","Aw1LCYbPBIa","x194x21Zz18","x2nSzwfYvgK","zxrxB3jRq2G","mxWZFdj8nhW","x3vYBa","DhHKDKu","ywrKrxzLBNq","txPHAMO","DuLPs0S","DKLmBuC","vw5PBxbSzw0","zLPqthi","Ahr0Chm6","twX0DNC","Au5HDMe","BMDLza","z2v0q3vYC28","lcbxzwjtB2m","DM5Ly2y","vNHmu1K","su5hsxa","DwHXvgS","B2neALK","wvHjrKC","AMP3Eee","x29Ut3bLBG","tuD3sgS","B2zMC2v0","BKXPBMu","sfzcDw0","EMP0q2u","y2XVC2uSihC","mNW0Fdb8m3W","CNjpBMy","x2zVCM1HDeu","CMf2B1q","AvfvzeK","ihbYB3rVy28","D0HYCgu","zhPVweK","yMrFzgLK","DeXzvxO","x2LZtM9Kzq","z05cvuy","z1jJA2m","DhjPBq","rxjyyKu","ugPxDKi","rfL6vLO","yNL0zuXLBMC","rxzLBNq","ywnOzwq","ENbzqLi","Bwf4uMv0CMK","AwrSzwW","AfngsKy","DejKENO","BgHXD0q","vxbKyxrLq28","vu9MDvq","uen5u20","zufJAW","nhWY","CvzArNi","twXxr1y","CufHB1K","C2vUza","zgvJB2rLzey","z2DKCMm","x2n1CNnVCK4","BNHty20","zMvY","nhWXmhW2","t2fOsNa","tKzYC3m","zMLSzw5HBwu","wunbrLy","CMv0CNLdB3u","AvH5De0","rxHlDvy","B2zM","x2DLDeLUDgu","EfvZzuvUDG","ALffEvm","Aev0whi","C3fVzwO","C2vYDMLJzs0","CuP0zgq","AvPwwNe","AK9zA2K","BgvUz3rO","zsbHihn0CMK","wNzzzg0","qxPbwxq","t25gBum","AxnrB1nby2S","B25SAw5L","rLbzuwy","t0Xiyxu","DxbKyxrLq3u","yw1LoIa","CgLUz0LUDgu","ChP0uuW","mNWZFdf8mhW","DLb1AuW","qvDgz1O","A0LLExe","CMvWBgfJzui","zgvS","A0LkuM4","ywLqDM4","wu9AAxm","rerZCKm","B3bLBG","y2HHCKnVzgu","C3bSAxq","tePLEwO","Dw5KzwzPBMu","CMvXDwLYzwq","zw50tgLZDgu","zNjVBuj5Dgu","CLb6veO","rMjfDMq","Bg9NsurozxC","zxjYtM8","zw5JB2rPBMC","Bwf4twvZC2e","y3jLyxrLrwW","y1bsv3i","A01uzKO","txr0r3y","r25TzLy","CMvKDwnL","y291BNq","CNnVCKzPBgu","z2v0qwXSs2u","x2rPC2nVBM4","uwTJDMy","txbgBhG","AM1rwMu","zMLUza","sunkywm","zwnVBM5Ly3q","CMvUDevUzha","zujfAhy","B2XKvMvYC2K","y3bWAu4","rfvnBhK","tNPpzwG","AunbrfO","x2rLC3rYB3K","ExHduuS","t0D1Ewi","sLDRC1K","veTkywK","zer1EfK","DxrVuMvJB24","mhWYFdf8nhW","BKLtA1e","AM5htui","EefUsMu","x21LC3nHz2u","BMLst2e","y29UBMvJDeu","AgPoANO","B25tDg9Wsw0","x2DLBMvYyxq","A2v5","t21AsNu","CMvHzfvjBNq","BwLuv0y","vNveBvO","z2vjBMzVu3K","DMfSDwvZ","B25Uzwn0Aw4","AxnrB1nnzxm","EMDrt2S","s2fhqxG","Dg9cExrLC0W","EML2z3y","yxjYyxLIDwy","BNrfBMrWB2K","C3rYAw5NAwy","zvD6y2W","y2XVC2veqG","AKzxEfO","wM9PCK8","r0Hxs2O","A1bnEMG","AKTUyLy","C29Tzq","rvfntxa","C2fNzq","B2XRD1y","BMv3vMvYC2K","zgvMAw5Luhi","q0DQvva","sLnptLa","BKXPs1e","rxjKC2K","ELfUyvm","qMPdzfy","mtCXCg9qre1d","t1zZv3C","B2DvDMy","qunnBwS","EMzwthO","wMvUwM0","Bxz4veW","zxjFBxnNAwq","ywDL","mtuZnZGYmJbYwhPNvNC","yKP2wM8","x2LUAxrqCM8","x3fVC0rc","v2vIu29JA2u","Dhr3Awq","Cfb1ywW","B3jRig9MzMW","x3DZsw5ZDge","Cw9Z","y29UBMvJDgK","yKrYANy","u1jNtg4","CwDcy2u","vKrbDNC","Durqrvi","y3vYC29YlNm","CMvHzhDYAxq","Bwu6ia","BMDuAw1LCG","swD2Chy","AKHLrMO","CMvTB3zLrxy","uxrHBLm","t3zYuuu","zeXJuNm","rMr3v0q","zvrRDLa","DuznzMq","CLzHBhvLCW","BMvJDa","zxq9DxrMltG","zMLN","sMvXr0O","tgzpzeS","tu9Pt3K","yxKSig5LDhC","v2DjqwK","CfLOweS","A3LeAum","r1DZAhi","CuPiEfi","A3f0u1C","rMnNswS","zwn0","BejXAMG","wxDkBg8","ywjVCNq","x2LZqNjVD3m","igXHCMDLCIa","Ce5Zr3m","wMrKAMC","q3nlse4","wefZue0","nNvir1v3zG","y09Wzw4","CgPfyNK","D292z3m","sLvTv0e","uNvyufy","BMfTzq","y3vYDMfSDwu","C3bSAwnL","uLrfB0y","BuDMq1q","BNrLCG","x3DZ","reDOwvy","mtuXnZe1mKDsuKrYEG","zxjFAxnFywm","sxf3wuy","sfzZAuW","Be5Xr0C","BvrOCMi","yvbZAuu","qw9dqxq","Chfzwue","AeDxDuO","y0DtDKK","ign1CNnVCIa","BNz4tw8","qvfiCLe","B3bLBIa","uxPhy0C","ChjVDg9JB2W","AxnbCNjHEq","ALrqu2K","rwTSC0O","v1rPz04","qLHMwLm","v3n6the","uND2rg4","yw5tDgC","sfj3wfu","zgvSzxrLrge","yuf6Che","CMvJB25Uzwm","rvD0y3u","DxnLCKLW","Cgf5Bg9Hza","vLvsswu","B25TzxnZywC","yw1rz3q","t1btwMC","B1jxsgS","q2TWEwW","AwrZweq","zxf1ywXZ","x2LZtwLUAvq","Cg9Uuxu","x3bPBMDmB3m","Bwf4tg9ZC0m","y0XTBwO","nZi0nJvVtxfWs2y","igfYCMf5yNu","CxvXseq","CMLoyui","Aw5JBhvKzxm","ALHwv1y","B1rAuKq","rNLjzuu","rLjptLrjrvi"];return xa=function(){return t},xa()}var gp,mp,la,C1=hp({"node_modules/idb/build/index.js"(){let t=L,e={gupYx:function(n){return n()},ympzx:"getAll",VKrbD:t(1452)+"ys",bBrDQ:t(1450),VFGZS:"put",LWCBo:t(515),GYsXz:t(1216)};e[t(930)](lp),lp(),gp=[t(493),t(1272),e[t(751)],e[t(1204)],e.bBrDQ],mp=[e[t(597)],e[t(1724)],e[t(1312)],"clear"],la=new Map,S1(n=>({...n,get:(i,o,a)=>up(i,o)||n.get(i,o,a),has:(i,o)=>!!up(i,o)||n.has(i,o)}))}}),R1={idb:function(t){let e=L;t[e(1141)]=Promise[e(1819)]()[e(1663)](()=>(C1(),pp))[e(1663)](function(n){return n})}},fp={};function Gt(t){let e=L,n={oyrzm:e(1420)+"4"},i=n[e(1169)][e(1432)]("|"),o=0;for(;;){switch(i[o++]){case"0":R1[t](a,a[e(1141)],Gt);continue;case"1":var a=fp[t]={exports:{}};continue;case"2":var d=fp[t];continue;case"3":if(d!==void 0)return d[e(1141)];continue;case"4":return a[e(1141)]}break}}Gt.d=(t,e)=>{let n=B;for(var i in e)Gt.o(e,i)&&!Gt.o(t,i)&&Object[n(1512)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=L;Gt.o=(e,n)=>Object[t(875)+"e"][t(906)+"operty"][t(444)](e,n)})(),(()=>{let t=L,e={anStg:function(n,i){return n!=i},Ckpyl:t(1434)+"d",PjvKC:"Module"};Gt.r=n=>{let i=t;e[i(1620)](e[i(1633)],typeof Symbol)&&Symbol[i(728)+i(1754)]&&Object[i(1512)+i(933)](n,Symbol[i(728)+i(1754)],{value:e[i(827)]}),Object[i(1512)+i(933)](n,i(1718)+"le",{value:!0})}})();var Ne={};function B(t,e){t=t-393;let n=xa(),i=n[t];if(B.XCdFIF===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",m="";for(let v=0,_,b,S=0;b=f.charAt(S++);~b&&(_=v%4?_*64+b:b,v++%4)?p+=String.fromCharCode(255&_>>(-2*v&6)):0)b=x.indexOf(b);for(let v=0,_=p.length;v<_;v++)m+="%"+("00"+p.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(m)};B.DhGvGK=o,B.RnZVmx={},B.XCdFIF=!0}let a=n[0],d=t+a,u=B.RnZVmx[d];return u?i=u:(i=B.DhGvGK(i),B.RnZVmx[d]=i),i}(()=>{let t=L,e={zpYBR:function(c,r){return c(r)},ZnUtx:function(c,r){return c+r},zzMqK:function(c,r){return c+r},wYoCi:function(c,r){return c*r},OMeej:function(c,r){return c*r},bruQg:function(c,r){return c+r},SYIYk:function(c,r,s){return c(r,s)},Podbb:function(c,r){return c+r},EDden:function(c,r,s){return c(r,s)},hNVGY:function(c,r){return c(r)},EUoig:t(465),UqZCZ:"ffff",oVLBJ:function(c,r){return c|r},ztlMI:function(c,r){return c<<r},LQoTO:function(c,r){return c&r},lzoNu:function(c,r){return c<r},AoCAt:function(c,r){return c<=r},SBOcx:function(c,r){return c(r)},hEtXr:function(c,r){return c>r},uhqTk:function(c,r){return c===r},vILmG:t(778),xWnmS:t(1078),nvxMo:function(c,r){return c!==r},hlXBP:function(c,r){return c-r},gofHW:function(c,r){return c-r},punMr:function(c,r){return c<r},zpBRP:function(c,r){return c===r},hYIwZ:t(488),HlNqE:function(c,r){return c<r},Mzajj:function(c,r){return c-r},pjEby:function(c,r){return c!==r},xJBUn:t(1290),Buatk:"zWkdd",AzAYt:t(1008),hGWuJ:function(c,r,s){return c(r,s)},eLWJZ:function(c,r){return c+r},vvAEX:function(c,r){return c+r},OUQwo:function(c,r){return c<<r},oCCRO:function(c,r){return c|r},qdjBQ:function(c,r){return c+r},BCaNT:function(c,r){return c+r},pUlhy:"uVlkO",hVOJI:"Ftdcp",jKnbV:function(c,r){return c(r)},BndxZ:function(c,r){return c>>>r},ANNAQ:function(c,r,s){return c(r,s)},aaYQR:function(c,r,s){return c(r,s)},ikqDl:"Missing required"+t(960)+t(1484),zlibH:function(c,r){return c===r},xxSen:t(1803)+t(1435)+" field: "+t(715),Erdsi:function(c){return c()},fynjD:function(c,r){return c===r},pNsGs:function(c,r){return c<r},NmRbC:function(c,r,s){return c(r,s)},WaPWT:function(c,r){return c!==r},GDKnX:t(787),qdxKN:function(c,r,s){return c(r,s)},guCbo:function(c,r,s){return c(r,s)},ZIhfB:function(c,r){return c(r)},TpCoj:function(c,r){return c!==r},LIDwa:function(c,r){return c!==r},CzfAX:function(c){return c()},xWQTf:function(c,r,s){return c(r,s)},wdgCM:function(c,r,s){return c(r,s)},UQJRh:function(c,r,s){return c(r,s)},EVJiD:function(c,r){return c!==r},tBdzz:function(c,r,s){return c(r,s)},ovVTv:function(c,r,s){return c(r,s)},oCleK:function(c,r,s){return c(r,s)},mKfXC:function(c,r,s){return c(r,s)},ogUvf:function(c,r){return c!==r},rTGvF:function(c,r,s){return c(r,s)},ioSrV:function(c,r){return c!==r},qAaoY:function(c,r,s){return c(r,s)},ZBYKL:function(c,r){return c(r)},CGjUP:function(c,r,s){return c(r,s)},bzQqH:function(c,r){return c(r)},fFwDn:function(c,r){return c>>>r},nHscv:function(c,r,s){return c(r,s)},uKofr:function(c,r,s){return c(r,s)},EXQKS:function(c,r){return c(r)},jjwxA:function(c,r,s){return c(r,s)},kDRTT:function(c,r,s){return c(r,s)},iZVZq:function(c,r){return c(r)},oybNT:function(c,r){return c===r},VMzcs:t(1803)+t(1435)+" field: "+t(677),pkHJm:function(c,r){return c===r},DYzVZ:t(1803)+t(1435)+t(960)+t(839),QVwxo:t(1803)+t(1435)+" field: service",AujNd:function(c,r){return c===r},UqjOM:t(1803)+"required field: method",msNLd:function(c,r){return c(r)},NFrss:function(c,r){return c+r},nxScm:function(c,r){return c&r},qJHxR:function(c,r,s){return c(r,s)},jmBcI:t(1327)+t(1837)+"pe: ",mlQAz:function(c,r){return c>>r},VZgyD:function(c,r){return c>=r},YlDlU:function(c,r){return c!==r},INgEF:"koTtc",SlLdb:function(c,r){return c===r},IKnDS:function(c,r){return c>r},AXEUC:t(1028)+t(864),UPwIZ:function(c,r){return c|r},NMfqj:function(c,r){return c<<r},QzGcG:function(c,r){return c<<r},pmyeK:function(c,r){return c|r},eBEhv:function(c,r){return c!==r},MRxFw:function(c,r){return c+r},aVbIb:t(811)+t(864),LTNoc:function(c,r,s){return c(r,s)},loWBb:function(c,r){return c+r},gMGTP:function(c,r){return c+r},zovcz:function(c,r){return c&r},evmsz:function(c,r){return c===r},tDGvJ:function(c,r){return c&r},PCySm:function(c,r){return c>=r},teXqB:function(c,r){return c+r},cguWi:function(c,r){return c+r},beJjv:function(c,r){return c&r},zQnaS:function(c,r){return c|r},gTtip:function(c,r){return c&r},ZKIkN:t(1470),tbSZo:t(902),FdwWD:function(c,r){return c(r)},AWFgZ:function(c,r){return c==r},vPuiL:function(c,r){return c+r},gdhqr:function(c,r){return c!==r},Rteaw:function(c,r){return c&r},yhPDB:function(c,r){return c<<r},xfBsA:function(c,r){return c<<r},sGZqx:function(c,r){return c&r},CZlHQ:function(c,r){return c&r},hjNjz:function(c,r){return c>=r},jFWxZ:function(c,r){return c===r},EiumS:"FztXe",GZyFw:function(c,r){return c(r)},OXILs:function(c,r){return c==r},hSFJF:function(c,r){return c+r},DyhIX:function(c,r){return c+r},pRLAj:function(c,r){return c+r},NJheo:function(c,r){return c+r},lavQy:function(c,r){return c+r},uZLlF:function(c,r){return c&r},SRgLn:function(c,r){return c|r},zgQOk:function(c,r){return c|r},sZukz:function(c,r){return c<<r},fLQRr:function(c,r){return c+r},IAjOR:t(1649)+">",Isvro:function(c,r){return c<r},cjaKT:function(c,r){return c<r},xWpYk:function(c,r){return c<r},ACMmk:function(c,r,s){return c(r,s)},JiRwr:function(c,r){return c<r},vXrsD:function(c,r){return c===r},LnHjL:"THugn",Gyzez:function(c,r){return c>=r},qJtdd:function(c,r){return c+r},KSaDl:function(c,r){return c<r},KXupu:function(c,r){return c<r},CPkea:function(c,r){return c|r},DUMly:function(c,r){return c&r},sCtKW:function(c,r){return c|r},oszrm:function(c,r){return c&r},dmqwX:function(c,r){return c>>r},IYqAm:function(c,r){return c&r},TKJai:function(c,r){return c>>r},OEQGf:function(c,r){return c&r},DVLpv:function(c,r){return c&r},wLSzL:function(c,r){return c|r},cSvJr:function(c,r){return c>=r},yfcxy:function(c,r){return c<=r},MOiOy:function(c,r){return c>=r},orIGV:function(c,r){return c|r},pYhXK:function(c,r){return c/r},bIjwK:t(813),GgbzB:function(c,r){return c&r},NMmFq:function(c,r){return c&r},JeqGJ:function(c,r,s){return c(r,s)},HenDN:function(c,r,s){return c(r,s)},givxn:function(c,r,s){return c(r,s)},EQMMp:function(c,r){return c(r)},FyIeE:function(c,r){return c&r},auVtD:function(c,r){return c<<r},RcwpA:function(c,r){return c<<r},pVWdR:function(c,r){return c&r},rwOVM:function(c,r){return c&r},DCPXx:function(c,r){return c<<r},pqYYA:function(c,r){return c&r},cPRWr:t(619),scgeX:function(c,r){return c(r)},ODDLo:function(c,r){return c&r},dzoXI:function(c,r){return c!==r},BJWVA:"qDoki",JbPIn:t(1876),IVXmt:function(c,r){return c&r},gPZCf:function(c,r){return c&r},lXXFO:function(c,r){return c<<r},uDPER:function(c,r){return c|r},CNcxO:function(c,r){return c<<r},hifbw:function(c,r){return c|r},QxPxF:function(c,r){return c===r},IvStN:function(c,r){return c<r},wovgs:function(c,r){return c<r},GyzJh:function(c,r){return c<r},sqoej:function(c,r){return c<r},RTEoF:function(c,r){return c+r},lBDNJ:function(c,r){return c+r},VCiyU:function(c,r){return c>>>r},BmrfZ:function(c,r){return c>>>r},PbKhy:function(c,r){return c+r},PozIT:function(c,r){return c!==r},nCFhr:function(c,r){return c|r},IZtas:function(c,r){return c>>>r},ccmvc:function(c,r){return c!==r},JkWwp:function(c,r){return c|r},UdxZX:function(c,r){return c>>>r},IZopn:function(c,r){return c!==r},qhyCp:function(c,r){return c|r},nAeIe:function(c,r){return c>>>r},rHYbI:function(c,r){return c&r},VXOGR:function(c,r){return c+r},ARaGo:function(c,r){return c>>>r},QXIpJ:function(c,r){return c<r},xToEG:function(c,r){return c|r},xePJd:function(c,r){return c>>r},VaXkV:t(1775),mZEPc:function(c,r){return c|r},UEvlv:function(c,r){return c|r},qklSo:function(c,r){return c|r},GZjbu:function(c,r){return c<<r},nxhxi:function(c,r){return c<<r},bYnEc:function(c,r){return c|r},mvxTL:function(c,r){return c|r},YztYD:function(c,r){return c<<r},jjzfB:function(c,r){return c|r},QheFL:function(c,r){return c|r},LNVha:function(c,r){return c<<r},jQEyS:function(c,r){return c|r},idlel:function(c,r){return c<<r},xSrUp:function(c,r){return c<<r},tfEcX:function(c,r){return c===r},jArVb:function(c,r){return c|r},tlSNU:function(c,r){return c<<r},VTYNC:function(c,r){return c|r},nWUXV:function(c,r){return c<<r},iXytM:function(c,r){return c<<r},eXEZt:function(c,r){return c&r},bmood:function(c,r){return c>>>r},MJkpx:function(c,r){return c!==r},gxaOM:t(1246),sDzsu:function(c,r){return c<=r},tdnzI:function(c,r){return c|r},JJLdq:function(c,r){return c===r},yHEch:function(c,r){return c===r},ZuyPI:function(c,r){return c&r},tUmBm:function(c,r){return c+r},jsCgf:function(c,r){return c>>>r},OXCSz:function(c,r){return c>>>r},CxeeR:function(c,r){return c>>>r},jFseD:function(c,r){return c<<r},NOUXU:function(c,r){return c|r},IqwYF:function(c,r){return c!==r},uPBaV:t(1814),aPsiE:function(c,r){return c!==r},Qbtrd:function(c,r){return c===r},jmQZe:function(c,r){return c<r},InwrJ:"aPhRM",ZKIIe:function(c,r){return c&r},wIMiq:t(1009),LfaNy:t(1849),IkhQf:function(c,r){return c>>>r},Furgk:function(c,r){return c&r},FPYQf:function(c,r){return c>>>r},JaWiH:function(c,r){return c>>>r},ZWdvu:function(c,r){return c>>>r},xCANA:function(c,r){return c&r},PssxG:function(c,r){return c>>>r},wKjyF:t(1883)+t(1020),YIABy:t(1877)+"OR",zkKlx:t(1151)+t(801),nLiKQ:"CONNECTI"+t(1198),xtTxr:t(1018)+t(401)+"R",GHEBp:function(c,r){return c===r},TUGwA:t(1600),xKUcK:t(607),FEVCf:t(1581),kIJRn:function(c,r){return c||r},NCaMf:function(c,r){return c!==r},MGwHk:t(1637),gzNaB:function(c,r){return c>=r},Zddjg:t(749),wHrpe:function(c,r){return c instanceof r},HytZq:function(c,r){return c+r},jWvob:t(1697)+t(1199),xqXXU:function(c,r){return c===r},nQGgB:t(1716)+t(1687),ImtGc:t(441)+"_EXIST",fZaKL:function(c,r){return c!==r},qVZFr:t(1539),HgBVq:function(c,r,s){return c(r,s)},oLoki:t(1430),mLApU:t(438),QMotC:function(c,r,s){return c(r,s)},JYpKb:t(1813),qNahp:function(c,r,s){return c(r,s)},GmEiH:function(c,r){return c||r},RcuZp:function(c,r){return c!=r},ErXbE:"undefined",obcjT:function(c,r,s,l){return c(r,s,l)},HGAQl:t(1618),Rtltm:function(c,r){return c||r},lPTJX:t(703)+t(784)+"ltiple t"+t(1316)+t(581),jhwPr:function(c,r){return c|r},hgdFX:function(c,r){return c<<r},vSrui:function(c,r){return c&r},qdQvh:function(c,r){return c<<r},UlpqP:function(c,r){return c&r},dbPwT:t(947)+"2",czxCW:function(c,r){return c+r},bQcAU:function(c,r){return c+r},oRWHk:t(608),MCPsQ:t(853),hmBpj:function(c,r){return c<r},DLdgm:t(701),kPMzh:function(c,r){return c<r},LLeBW:function(c,r){return c&r},HglDV:function(c,r){return c===r},NhxcP:function(c,r){return c&r},kNkKk:function(c,r){return c<r},gYacW:function(c,r){return c<=r},ECZEB:function(c,r){return c|r},XPeoa:function(c,r){return c<<r},fRUIX:function(c,r){return c&r},ibnZy:function(c,r){return c&r},BAVJE:function(c,r){return c&r},mNzQX:function(c,r){return c>=r},mWcQm:function(c,r){return c&r},Hjpvn:function(c,r){return c&r},yxCQK:function(c,r){return c<r},uUFYK:function(c,r){return c<r},cjsFB:t(1571),nAqAo:t(764),DGhYV:function(c,r){return c|r},raEET:function(c,r){return c|r},twYlI:function(c,r){return c===r},bHHii:function(c,r){return c+r},Viawu:t(1240)+t(1379),theKo:function(c,r){return c|r},EnZDL:function(c,r){return c+r},kIeyq:function(c,r){return c>>r},taBwh:function(c,r){return c>>r},MBbZx:function(c,r){return c|r},EJYqL:function(c,r){return c-r},XbGcl:"sioLh",lACtz:function(c,r){return c==r},NzOeh:t(765),VJYKv:"AaWVM",HFIom:function(c,r,s,l){return c(r,s,l)},AvusI:function(c,r){return c!=r},DDsrC:t(781),eReSh:"hUZxs",cDYQe:"text/pla"+t(888)+t(1559),NDPFN:function(c,r){return c!==r},xqZBy:t(1005),JXPag:t(1871),jvdxy:t(394),JxZoK:function(c,r){return c||r},Mltvw:"OIgLB",ZZsAo:t(531),DSVvf:function(c,r){return c>=r},OsrIB:t(1764)+t(1653),EmJmS:t(1098),KeviO:t(1099)+"ascript",gJuNk:function(c,r){return c+r},OahJp:t(860),VVlDr:"&jscallback=fron"+t(1190)+"P",zfVLz:t(1047),hKMJB:function(c,r){return c(r)},MttGv:function(c,r){return c(r)},GCstk:t(1221),csSgS:t(689)+t(689)+t(689)+t(689),QCcRV:function(c,r,s,l){return c(r,s,l)},knhtV:t(1785),qechX:t(1455),orBco:function(c,r){return c!==r},PsdSO:t(601),VAFFU:t(1562),GWshr:t(1393),vkrdH:t(1606),yzFnB:t(1616),niROa:function(c,r){return c||r},vxclC:t(1026),Cwrij:function(c,r){return c||r},CtaBY:function(c,r){return c===r},DgXvU:"CULiI",cNOSM:function(c,r){return c||r},pNVgF:t(578),rPzTJ:function(c,r){return c||r},OGuyb:"init QoSDB failed",ZenZm:t(1631),bZOGg:t(1537),ttYwa:t(1137)+"id",CMHPA:t(579),jYdvQ:t(1353),hlkrf:function(c,r){return c>=r},khUzZ:function(c,r){return c<=r},jgikT:function(c,r){return c-r},MAFyl:function(c,r){return c+r},EWzhT:function(c,r){return c<r},rbyqH:t(563),Qkcvf:t(545)+t(876)+"ck",zivgv:t(545)+t(1597)+"k",ZKyLn:t(545)+t(910)+t(817),egGgm:t(1132),BHJok:t(770),tcpKU:function(c,r){return c||r},nXvPH:t(1865),aholS:function(c){return c()},riNaB:function(c,r){return c!==r},QjFce:t(681),mThrb:t(1805),TABTV:function(c){return c()},RwvDn:function(c,r){return c instanceof r},UyAgg:t(525)+t(1100),vMaVb:t(525)+t(1100)+t(1145)+t(624),BgHTu:t(1188)+"e",gWaaF:function(c){return c()},PjWvB:function(c,r){return c(r)},dOxrq:function(c,r){return c&r},RubxM:function(c,r){return c+r},eDOft:function(c,r){return c(r)},CcKGP:function(c,r){return c&r},RfNTY:function(c,r){return c!==r},xiKAG:"XzAdl",PsykK:function(c,r){return c||r},BkHJe:function(c,r){return c>>>r},EsDNH:function(c,r){return c===r},OVsWw:t(1786),VURIe:function(c,r){return c(r)},DBOmQ:function(c,r){return c+r},DJAhk:function(c,r){return c+r},sYvgw:t(1811)+t(1781)+"ge: ",eOZqX:t(1148),HkIkg:t(1804),RgxLT:function(c,r){return c>r},WIoVg:t(404)+"too large",gYwjH:function(c,r){return c>=r},atgAk:function(c,r,s,l){return c(r,s,l)},amQgt:function(c,r,s){return c(r,s)},QtanS:function(c,r){return c<<r},tRPVW:"1|4|3|2|0",lJUVe:function(c,r){return c+r},txdvE:function(c,r){return c<r},hyYdv:function(c,r){return c+r},AdOrW:function(c,r){return c>>>r},gFNPW:t(640),RbDAZ:function(c,r){return c|r},GRbyk:function(c,r){return c|r},btbGc:function(c,r){return c|r},iOcsK:function(c,r){return c<<r},eltMo:function(c,r){return c+r},BbfGb:function(c,r){return c|r},IvzmA:function(c,r){return c<<r},Wlomh:function(c,r){return c+r},UoHBI:function(c,r){return c(r)},AROyZ:t(443),ueXLe:t(948)+t(557)+"s",kyGhu:t(948)+t(1304)+"t",EklsJ:"wLYpb",wGFXx:function(c,r){return c&r},dsExu:function(c,r){return c>>>r},rTVJl:function(c,r){return c&r},ywFIM:function(c,r){return c+r},eyCQL:function(c,r){return c+r},wfEzj:function(c,r){return c&r},emrgh:function(c,r){return c+r},zvXtM:function(c,r){return c&r},YAbpn:function(c,r){return c-r},JuLHe:function(c,r){return c|r},ocDjY:function(c,r){return c<<r},dAVGh:function(c,r){return c&r},YSsMS:function(c,r){return c&r},wwsAq:function(c,r){return c+r},qoMdY:function(c,r,s){return c(r,s)},vQEMW:function(c,r,s){return c(r,s)},bKTyr:function(c,r,s){return c(r,s)},hCoWw:function(c,r,s){return c(r,s)},jHeFj:t(1592),UUOLy:function(c,r){return c+r},YNlBG:function(c,r){return c>>>r},pJVds:function(c,r){return c>>>r},xmNwi:function(c,r){return c>>>r},ExKuV:function(c,r){return c<r},HlZwS:function(c,r){return c|r},wopcm:function(c,r,s,l){return c(r,s,l)},jsDFi:t(1544)+t(1671),YXfYc:function(c,r,s,l){return c(r,s,l)},FvMgN:function(c,r,s,l){return c(r,s,l)},HVsiL:t(935),PSPaQ:function(c,r,s,l){return c(r,s,l)},GzkaF:function(c,r,s,l){return c(r,s,l)},vtDkr:t(1589),RKqzM:function(c,r,s){return c(r,s)},qobPn:t(1624)+"t",DPxmm:"stop imm"+t(1161)+t(1669)+"ct",WLeYZ:function(c,r){return c===r},HXabM:"LdZgc",PPwRF:function(c,r,s){return c(r,s)},pKcSO:"ALL",bvPuT:function(c,r,s,l){return c(r,s,l)},cppiN:t(752),ElqOl:function(c,r,s,l){return c(r,s,l)},dQvBu:t(1766),ErWap:function(c,r){return c(r)},CrBNH:"setcursor",tMQlZ:function(c,r){return c===r},xyTdW:t(750),CdIya:"avaeP",jXVWV:t(1269),eWzcl:t(883),zKyRS:function(c,r){return c||r},fgkQt:"timeout",aPBby:function(c,r){return c(r)},mFkqf:t(545)+t(1526),ZoirO:function(c,r){return c(r)},qFRzS:t(545)+t(774),XXIOk:function(c,r,s,l){return c(r,s,l)},JLNXT:t(566)+"s",ZjuIe:function(c,r,s){return c(r,s)},tdkBe:function(c,r,s){return c(r,s)},XThjh:function(c,r){return c>r},IGMZr:function(c,r){return c>r},iNava:t(474),nnapE:function(c,r){return c+r},FQjVn:function(c){return c()},EUfSR:function(c){return c()},oWmrL:function(c){return c()},ufthl:function(c){return c()},kRKZh:function(c,r){return c===r},uzurb:function(c){return c()},UoGEU:function(c){return c()},kqtSW:t(638),FDhWY:function(c,r){return c===r},mMuat:t(1080),vnecf:function(c,r){return c===r},xAnJe:function(c,r){return c!==r},uTkHS:function(c,r,s){return c(r,s)},chZvk:function(c){return c()},XUyxf:function(c,r,s){return c(r,s)},bENXa:function(c,r){return c===r},BYlVf:function(c,r,s){return c(r,s)},XCEym:"blocked",GVNgV:t(1574),TzZed:function(c,r){return c===r},DWErH:t(872),oMMsi:"auto",INGIp:function(c,r){return c+r},czlad:function(c,r){return c!==r},WnOwU:function(c,r,s){return c(r,s)},kyDiC:"bye",VeCKV:function(c,r){return c(r)},DRmLz:t(1107),fFWNW:t(1647),ggdrc:t(1497)+t(1388),EJUeP:"pbbp2",qurYy:function(c,r){return c===r},exPEG:function(c,r){return c(r)},syOCI:t(1652)+t(1174)+t(986)+t(1334)+t(1022)+t(711)+"is undef"+t(1051),bFlAN:function(c,r,s){return c(r,s)},KTmru:function(c,r,s){return c(r,s)},FpexW:function(c,r,s){return c(r,s)},PeObR:t(627)+t(1564)+t(1535)+t(1787),BDZmQ:t(1746),uwHXY:t(1413),ravoT:t(659),EnGZn:"pageshow",QwNdd:t(949),FiJmd:function(c,r){return c!==r},lGkec:function(c,r){return c!==r},xwoGe:t(1329),UlwdF:t(945),zGPVt:t(1357),OvrQE:t(492)+"d",iYmNM:"please provide b"+t(717)+t(417)+t(572),uIiKK:function(c,r){return c==r},jOYki:function(c){return c()},aRJSK:"fws_1.0.0",lWJEl:function(c,r){return c||r},GHWKj:function(c,r,s){return c(r,s)},mhlfl:"start",EwMTo:function(c,r){return c>r},qDAgX:function(c,r,s){return c(r,s)},pPual:function(c,r){return c!==r},rGTBX:t(1029),xEXRm:function(c,r){return c!==r},JPZLo:t(1308),CSGrR:function(c,r){return c*r},BXfZS:function(c,r,s){return c(r,s)},Nhrpm:function(c,r,s){return c(r,s)},tJUZA:t(627)+t(1236)+t(1624)+t(1829)+t(995),pztQL:t(901),lWhai:t(1034)+" try rec"+t(1491)+"g",RkUUI:function(c,r){return c===r},UzHlg:t(1768),STaoF:t(1722)+"4",rykxa:"0|2|4|3|1",YilxO:function(c,r,s){return c(r,s)},Ydzjq:function(c,r,s){return c(r,s)},kaLDg:function(c,r,s){return c(r,s)},MnVWO:function(c,r,s){return c(r,s)},gNBUF:t(1328),wAbus:function(c,r){return c!==r},kracM:t(1823),cRtvq:t(1257),nqrZx:function(c,r){return c===r},OzVQB:t(1348)+t(1002)+"y closed",QVauF:t(1348)+t(1031)+t(795)+t(886)+"ed",LWUbN:function(c,r){return c&r},tGomB:function(c,r){return c!==r},NdkfR:t(1556),zNfmS:function(c,r){return c==r},Qjzgq:t(1652)+t(1752)+t(1667)+t(1881)+"a must b"+t(1408)+t(1251)+t(1642)+"ffer",qoOlY:function(c,r){return c==r},OksLq:function(c,r){return c(r)},HfMwj:function(c,r){return c||r},Aebvg:function(c,r){return c===r},JYpew:function(c,r){return c<r},EWtcu:t(1104),KcFki:function(c,r){return c!==r},iCADZ:function(c,r){return c==r},NBysE:t(821)+"econnect"+t(503),uPMRZ:t(1621),XDrzg:"9|7|1|2|"+t(605)+t(1389),keGyB:function(c,r,s,l){return c(r,s,l)},htoDn:t(1195),cGTFP:function(c,r,s,l){return c(r,s,l)},GdjZV:t(1588),HOzfW:"service-"+t(1588),cAFOF:function(c,r,s,l){return c(r,s,l)},rrOnf:t(1476),grhwC:t(794),ebEBp:function(c,r){return c===r},csCXO:t(1817),QkYah:t(544),quqHD:function(c,r,s){return c(r,s)},TJCDe:t(602),gIhIG:t(1847),aAzpq:"\0\0\0\0\0\0\0\0",DlecN:function(c,r){return c*r},PCHaW:function(c,r){return c/r},noBLq:t(1048),RUsEd:function(c,r){return c===r},XyWPk:function(c,r){return c===r},tLYUz:function(c,r){return c===r},DxTBC:t(1211)+t(1809)+t(529)+"pe",TMMNx:function(c,r){return c===r},zhjJN:t(520),inBZa:function(c,r){return c!=r},VDAvw:t(415)+t(848)+t(1834),KaGAx:t(564)+t(1869)+t(429),mpqZm:function(c,r){return c!=r},LJeyj:function(c,r){return c===r},ijupe:t(1317)+t(1016)};Gt.r(Ne),Gt.d(Ne,{FWS:()=>rm,CustomErrorEvent:()=>Il,createCloseEvent:()=>bt,ReconnectEvent:()=>Sl,createErrorEvent:()=>ht,decodedFrame:()=>cn,createOpenEvent:()=>Pl,CustomCloseEvent:()=>Al,createReconnectEvent:()=>Pa,FrontierMessageEvent:()=>Tl,encodeFrame:()=>jt,createMessageEvent:()=>Rl,OpenEvent:()=>Cl,ErrorCode:()=>ln,Event:()=>dr,MessageEvent:()=>kl});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(427)](),h=n||(n=e[r(1369)](f,c)),g=Math[r(956)]()[r(728)](16)[r(1116)](-6);return e.ZnUtx(e[r(558)](e.zzMqK(s,l),h),g)}function o(){let c=t;return e.wYoCi(1e4,Date[c(427)]())+Math[c(1779)](e[c(1701)](1e4,Math[c(956)]()))}function a(c){let r=t;return e.bruQg(Array(8)[r(1089)]("0"),e.SYIYk(parseInt,c,10).toString(2))[r(1116)](-8)}function d(c){let r=t;return e[r(973)](e.zpYBR(Array,4)[r(1089)]("0"),e[r(1750)](parseInt,c,2)[r(728)](16)).slice(-4)}function u(c){let r=t,s=c[r(1432)](/\./)[r(1783)](g=>a(g)),l=[];return l[0]=e[r(621)](d,s[0]+s[1]),l[1]=e[r(1369)](d,s[2]+s[3]),[e.EUoig,e[r(981)],e[r(981)],e[r(981)],e[r(981)],e[r(975)],l[0],l[1]][r(1089)]("")}function f(c){let r=t,s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(737)](c),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(737)](c);return s?e[r(1369)](u,c):l?x(c):r(689)+"00000000"+r(689)+r(689)}function x(c){let r=t,s="",l=[],h=0,g=0,y=!0,k=e[r(981)];if(e[r(1401)](c[r(723)]("::"),-1)){let w=c[r(1432)]("::");for(let H=0;H<w.length;H++)if(e.uhqTk(e[r(1326)],e[r(722)]))_0x216265=e[r(914)](e[r(1249)](e.LQoTO(15,_0x511335),12)|e[r(951)](63,_0x21c7bb)<<6,e[r(951)](63,_0x491cee)),e.lzoNu(_0x5252cd,2048)||_0x2f2fe3>=55296&&e[r(1603)](_0x39ac55,57343)?_0x17fe2c+=_0x488ddf:(_0x1e0006+=e[r(1248)](_0x276d99,_0x19ff92),_0x31eb48+=2);else{let F=w[H];if(e.hEtXr(F[r(723)](":"),0)){let W=F[r(1432)](":");y&&(h=W[r(1407)]),g+=W[r(1407)];for(let K=0;K<W.length;K++)if(e[r(1608)](4,W[K].length)){let ce=k[r(582)+"g"](0,4-W[K][r(1407)]),be=ce[r(803)](W[K]);l.push(be)}else l.push(W[K]);y=!1}else{if(e.nvxMo(4,F[r(1407)])){let W=k[r(582)+"g"](0,e[r(1862)](4,F[r(1407)])),K=W[r(803)](F);l[r(489)](K)}else l.push(F);y&&(h+=1),g+=1,y=!1}}let O="";for(let H=0;e[r(1134)](H,e[r(1293)](8,g));H++)O=O[r(803)](k);for(let H=0;e[r(1857)](H,l[r(1407)]);H++)if(e.zpBRP(H,h)){if(e[r(1608)](e.hYIwZ,e[r(818)]))return new _0x374173(_0x404df7,{code:_0x14fa1e,reason:_0x5f3916,wasClean:_0x2149ab,willReconnect:_0x54d380});s=s[r(803)](O),s=s[r(803)](l[H])}else s=s.concat(l[H]);return s}{let w=c[r(1432)](":");for(let O=0;e.HlNqE(O,w[r(1407)]);O++){let H=w[O];if(e.nvxMo(4,w[O][r(1407)])){let F=k[r(582)+"g"](0,e[r(1324)](4,w[O].length)),W=F.concat(H);s=s[r(803)](W)}else s=s[r(803)](H)}return s}}function p(c,r){let s=t,l={MLuor:function(h,g,y){return e.EDden(h,g,y)},UOfuT:function(h,g){return h+g}};if(e[s(1584)](e[s(706)],e[s(773)])){let h=c[s(1484)];if(h!==void 0)if(e.pjEby(e[s(1410)],s(1689)))me(r,10),e.hGWuJ(z,r,h);else{let{offset:y}=_0x376a76(_0x5064fd,_0x47fc2a);_0xd9eea6=y;let k={cursor_name:"",cursor:0,service:0},{value:w,offset:O}=l[s(1160)](_0x13390b,_0x3c3a81,_0x4ed646);k[s(935)]=w,_0x1bd2f6=O;let{value:H,offset:F}=l[s(1160)](_0x3ddbf6,_0x4c180d,_0x4661ca);_0x4672da=F,k[s(464)+s(830)]=_0x152c5f(_0xc03002,_0x423064,l[s(1376)](_0x29b3fd,H)),_0x402e23+=H;let{value:W,offset:K}=_0x39bda6(_0x318464,_0x64e29);k.cursor=W[s(1656)](),_0x3052d4=K,_0x3b717a.push(k)}let g=c[s(715)];e[s(1584)](void 0,g)&&(me(r,18),e[s(1605)](z,r,g))}else return this._socket.protocol}function m(c){let r=t,s={YXIFG:function(l,h){return e[B(914)](l,h)},ohfIR:function(l,h){return l<<h},pePPF:function(l,h){return e[B(1021)](l,h)},TqZmb:function(l,h){return e[B(714)](l,h)},PgtZC:function(l,h){return e.OUQwo(l,h)},eczYS:function(l,h){return l|h},aQvbA:function(l,h){return e[B(1215)](l,h)},AQHrQ:function(l,h){return e[B(1159)](l,h)},jsEkl:function(l,h){return e[B(744)](l,h)}};if(e.nvxMo(e[r(527)],e.hVOJI)){let l={};e:for(;!e[r(1369)](V,c);){let h=e[r(1506)](he,c);switch(e.BndxZ(h,3)){case 0:break e;case 1:l.key=C(c,he(c));break;case 2:l[r(715)]=e[r(1760)](C,c,e[r(621)](he,c));break;default:e[r(1070)](T,c,7&h)}}if(e[r(1338)](void 0,l[r(1484)]))throw new Error(e[r(903)]);if(e[r(1271)](void 0,l.value))throw new Error(e[r(434)]);return l}else{let l=new _0x118435(s[r(1340)](s[r(1340)](s.YXIFG(s.ohfIR(_0x4ee840[s[r(445)](_0x2cd13e,4)],24),s[r(772)](_0x4cd135[s[r(1280)](_0x22b02f,5)],16)),s[r(584)](_0x3838f1[_0x275428+6],8)),_0x5b6c0f[_0x54ee3f+7]),s[r(1200)](s[r(1340)](s[r(1859)](s[r(584)](_0x66de74[_0x228c18+0],24),_0x50f557[s[r(1609)](_0x4020a0,1)]<<16),s[r(584)](_0x25a5c[s.TqZmb(_0x4720dc,2)],8)),_0x9abfa8[s[r(768)](_0x4c6636,3)]),!0);return _0x3fd716+=8,{value:l,offset:s[r(445)](_0x59c8ad,8)}}}function v(c){let r=t;if(e[r(1584)](r(1867),r(1448))){let s=e[r(1516)](P);return _(c,s),e.zpYBR(N,s)}else _0x4d9545.set(_0x592938,_0x5a361a),_0x1bc6ce[r(598)](_0x1112e2,_0x41ad0d)}function _(c,r){let s=t,l={QOPUj:function(ge,Ge){return e[B(405)](ge,Ge)},mgIrM:function(ge,Ge){return e.pNsGs(ge,Ge)}},h=c[s(677)];e[s(1608)](void 0,h)&&(e[s(1750)](me,r,8),e[s(1710)](yt,r,h));let g=c.LogID;e[s(1584)](void 0,g)&&(e[s(1605)](me,r,16),yt(r,g));let y=c[s(935)];if(e[s(1841)](void 0,y))if(s(1832)===e.GDKnX){if(l.QOPUj(void 0,_0x5c8063))this[s(1806)+"rs"]={};else if(_0x230250===void 0)this[s(1806)+"rs"][_0x1124d3]=null;else{let ge=this[s(1806)+"rs"][_0x502d44];if(ge)for(let Ge=0;l[s(466)](Ge,ge[s(1407)]);)l[s(777)](ge[Ge].fn,_0x52bd83)?ge[s(1590)](Ge,1):++Ge}return this}else e.qdxKN(me,r,24),e.guCbo(yt,r,e[s(1855)](R,y));let k=c.method;e[s(742)](void 0,k)&&(me(r,32),e[s(1070)](yt,r,e[s(1248)](R,k)));let w=c[s(967)];if(e.LIDwa(void 0,w))for(let ge of w){e[s(1760)](me,r,42);let Ge=e[s(1682)](P);p(ge,Ge),e.xWQTf(me,r,Ge[s(1840)]),e[s(1880)](q,r,Ge),e[s(1369)](D,Ge)}let O=c[s(700)+s(767)];O!==void 0&&(e[s(1070)](me,r,50),e[s(1863)](z,r,O));let H=c[s(480)+s(473)];e[s(538)](void 0,H)&&(e[s(1241)](me,r,58),z(r,H));let F=c[s(1627)];F!==void 0&&(e[s(1373)](me,r,66),e[s(1033)](me,r,F[s(1407)]),e[s(1181)](ae,r,F));let W=c.LogIDNew;W!==void 0&&(e[s(912)](me,r,74),z(r,W));let K=c[s(832)+"ming"];e[s(1521)](void 0,K)&&(e.rTGvF(me,r,82),z(r,K));let ce=c[s(467)];e[s(780)](void 0,ce)&&(e[s(1750)](me,r,90),e[s(1382)](z,r,ce));let be=c[s(616)+"e"];e[s(1521)](void 0,be)&&(me(r,96),e[s(1033)](yt,r,e[s(812)](R,be)))}function b(c){return e[t(1855)](S,M(c))}function S(c){let r=t,s={LZDQM:function(h,g,y){return e[B(1513)](h,g,y)},UlCNH:function(h,g){return h|g},eyJJt:function(h,g){return e[B(951)](h,g)}},l={};e:for(;!e.bzQqH(V,c);)if(e.uhqTk(r(913),r(913))){let h=e[r(1506)](he,c);switch(e[r(604)](h,3)){case 0:break e;case 1:l[r(677)]=e[r(437)](Ct,c,!0);break;case 2:l.LogID=e[r(1662)](Ct,c,!0);break;case 3:l[r(935)]=e.bzQqH(he,c);break;case 4:l[r(1861)]=e[r(812)](he,c);break;case 5:{let g=e[r(1369)](I,c);(l[r(967)]||(l[r(967)]=[]))[r(489)](e[r(1253)](m,c)),c.limit=g;break}case 6:l[r(700)+r(767)]=e[r(1341)](C,c,he(c));break;case 7:l[r(480)+r(473)]=C(c,he(c));break;case 8:l[r(1627)]=e[r(1182)](re,c,e[r(621)](he,c));break;case 9:l[r(1032)]=e[r(1760)](C,c,he(c));break;case 10:l[r(832)+r(805)]=C(c,e.bzQqH(he,c));break;case 11:l[r(467)]=C(c,e[r(1405)](he,c));break;case 12:l[r(616)+"e"]=e.iZVZq(he,c);break;default:T(c,7&h)}}else s.LZDQM(_0x39f76d,_0xfb2312,s[r(1197)](s.eyJJt(127,_0x15f062),128)),_0x1f3aa3>>>=7;if(e[r(1788)](void 0,l[r(677)]))throw new Error(e[r(1039)]);if(e[r(694)](void 0,l[r(839)]))throw new Error(e[r(1365)]);if(e[r(1149)](void 0,l[r(935)]))throw new Error(e.QVwxo);if(e[r(1681)](void 0,l[r(1861)]))throw new Error(e[r(590)]);return l}function I(c){let r=t,s=e[r(895)](he,c),l=c[r(1840)];return c[r(1840)]=e[r(1391)](c[r(1344)],s),l}function T(c,r){let s=t;switch(r){case 0:for(;e.nxScm(128,e[s(1369)](ee,c)););break;case 2:e.oCleK(J,c,he(c));break;case 5:J(c,4);break;case 1:e[s(1569)](J,c,8);break;default:throw new Error(e[s(1391)](e.jmBcI,r))}}function R(c){let r=t;return c|=0,{low:c,high:e[r(565)](c,31),unsigned:e[r(1739)](c,0)}}let E=[];function P(){let c=t,r=E.pop();return r?(r[c(1344)]=r[c(1840)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(c){let r=t;if(e.YlDlU(e[r(707)],e[r(707)]))return _0x4b2217||(_0x447f8=[_0x1b8067[r(875)+"e"].advance,_0x320e69[r(875)+"e"].continue,_0x5a0562[r(875)+"e"][r(1884)+r(720)+"ey"]]);E[r(489)](c)}function M(c){return{bytes:c,offset:0,limit:c.length}}function N(c){let r=t,s=c.bytes,l=c.limit;return e[r(917)](s[r(1407)],l)?s:s[r(1731)](0,l)}function J(c,r){let s=t;if(e.IKnDS(c[s(1344)]+r,c.limit))throw new Error(e[s(923)]);c[s(1344)]+=r}function V(c){let r=t;return c[r(1344)]>=c[r(1840)]}function se(c,r){let s=t,l={RzvOw:function(h,g){return e[B(914)](h,g)},bFxaz:function(h,g){return e[B(1030)](h,g)},bVzLc:function(h,g){return e[B(1030)](h,g)},XIVQl:function(h,g){return e[B(612)](h,g)},FWGnF:function(h,g){return e[B(1611)](h,g)},eTkvP:function(h,g){return e[B(985)](h,g)},SdIea:function(h,g){return e[B(1030)](h,g)},pgXKM:function(h,g){return e[B(612)](h,g)}};if(e[s(1461)](s(966),s(779))){let h=c[s(606)],g=c[s(1344)],y=c.limit,k=e.MRxFw(g,r);if(k>h[s(1407)]){let w=new Uint8Array(e[s(1701)](2,k));w[s(598)](h),c[s(606)]=w}return c[s(1344)]=k,k>y&&(c[s(1840)]=k),g}else return new _0x4f857d(l[s(1063)](l.bFxaz(l.bVzLc(_0x322baa[4]<<24,l[s(868)](_0x7aaddf[5],16)),l.FWGnF(_0x40ad7a[6],8)),_0x1316cf[7]),l[s(1555)](l[s(562)](l.XIVQl(_0x131fcd[0],24)|l.pgXKM(_0x26b74a[1],16),l[s(868)](_0x4c7abe[2],8)),_0xc321c7[3]),_0x4e20f0)}function X(c,r){let s=t,l=c[s(1344)];if(e[s(1685)](e.eLWJZ(l,r),c[s(1840)]))throw new Error(e[s(982)]);return c.offset+=r,l}function re(c,r){let s=t,l=e.LTNoc(X,c,r);return c[s(606)][s(1731)](l,e[s(1175)](l,r))}function ae(c,r){let s=t,l=e.NmRbC(se,c,r.length);c[s(606)].set(r,l)}function C(c,r){let s=t,l=e[s(1181)](X,c,r),h=String[s(940)+s(1738)],g=c[s(606)],y="\uFFFD",k="";for(let w=0;e[s(1578)](w,r);w++){let O=g[e[s(1153)](w,l)],H,F,W,K;e[s(1338)](e[s(1124)](128,O),0)?k+=e[s(1405)](h,O):e.evmsz(e.tDGvJ(224,O),192)?e[s(1377)](e.vvAEX(w,1),r)?k+=y:(H=g[e[s(609)](e[s(692)](w,l),1)],e[s(927)](192,H)!==128?k+=y:(K=e.zQnaS(e.NMfqj(e[s(586)](31,O),6),63&H),e.HlNqE(K,128)?k+=y:e[s(742)](e[s(673)],e.tbSZo)?(k+=e[s(1554)](h,K),w++):_0x41fb50[s(548)](_0x2a2c88))):e[s(1422)](240&O,224)?w+2>=r?k+=y:(H=g[e.vPuiL(e[s(1021)](w,l),1)],F=g[e[s(1202)](e[s(622)](w,l),2)],e[s(1058)](e[s(820)](e[s(985)](H,e[s(1306)](F,8)),49344),32896)?k+=y:(K=e[s(1215)](e.xfBsA(e[s(1734)](15,O),12),e[s(513)](63,H)<<6)|63&F,K<2048||e.hjNjz(K,55296)&&e[s(1603)](K,57343)?k+=y:e[s(1502)](e.EiumS,e[s(1885)])?(k+=e[s(799)](h,K),w+=2):(_0x1b93f0+=e.SBOcx(_0x44628f,_0x21bfca),_0x2315fb++))):e[s(1213)](e[s(1124)](248,O),240)?e[s(1481)](e[s(1421)](w,3),r)?k+=y:(H=g[e[s(1372)](e[s(862)](w,l),1)],F=g[e.pRLAj(w+l,2)],W=g[e.NJheo(e[s(804)](w,l),3)],e[s(1521)](e.uZLlF(e[s(1540)](e[s(914)](H,e.ztlMI(F,8)),e.xfBsA(W,16)),12632256),8421504)?k+=y:(K=e[s(1493)](e[s(451)](e[s(825)](7,O),18),e.sZukz(e[s(1734)](63,H),12))|e[s(1092)](63&F,6)|63&W,K<65536||K>1114111?k+=y:(K-=65536,k+=h(e[s(1021)](K>>10,55296),e.fLQRr(e[s(586)](1023,K),56320)),w+=3))):k+=y}return k}function z(c,r){let s=t,l=r[s(1407)],h=0;for(let k=0;e.Isvro(k,l);k++){let w=r[s(1431)+"At"](k);w>=55296&&e.AoCAt(w,56319)&&e[s(547)](k+1,l)&&(w=e[s(1237)](e[s(1611)](w,10),r[s(1431)+"At"](++k))-56613888),h+=e[s(1134)](w,128)?1:e.cjaKT(w,2048)?2:e[s(549)](w,65536)?3:4}e[s(1522)](me,c,h);let g=se(c,h),y=c[s(606)];for(let k=0;e.JiRwr(k,l);k++)if(e[s(969)](s(1284),e[s(1848)]))this[s(979)][s(1674)]&&_0x2630d6.log[s(662)](_0x1eb31e,[e[s(735)],..._0x30e230]);else{let w=r[s(1431)+"At"](k);e[s(1189)](w,55296)&&w<=56319&&e[s(1404)](k,1)<l&&(w=e[s(1237)](e[s(1306)](w,10),r[s(1431)+"At"](++k))-56613888),e[s(472)](w,128)?y[g++]=w:(e[s(1135)](w,2048)?y[g++]=e[s(963)](e[s(1464)](e.mlQAz(w,6),31),192):(w<65536?y[g++]=e[s(1310)](e.oszrm(e[s(534)](w,12),15),224):(y[g++]=e[s(806)](e[s(1471)](w,18),7)|240,y[g++]=e[s(1672)](e[s(534)](w,12),63)|128),y[g++]=e[s(828)](w>>6,63)|128),y[g++]=e[s(1105)](e[s(586)](63,w),128))}}function q(c,r){let s=t,l=e[s(1382)](se,c,r.limit),h=c[s(606)],g=r[s(606)];for(let y=0,k=r[s(1840)];y<k;y++)h[y+l]=g[y]}function ee(c){let r=t;return c.bytes[e[r(1241)](X,c,1)]}function He(c,r){let s=t;if(e.pjEby(e[s(702)],s(526))){let l=e[s(1341)](se,c,1);c[s(606)][l]=r}else{if(e.hNVGY(_0x344ff1,_0x38a9b3))return _0x1bf3b2?_0x4050f8:_0x5bf51b;if(_0x471fd5){if(e[s(1194)](_0x2c3fe9,_0x24310f))return _0x35f3f7}else{if(e[s(1224)](_0x1d32ee,-_0x2f2158))return _0x15af41;if(e[s(1563)](_0x20b1ba+1,_0x2745d9))return _0x245250}return _0x522eff[s(523)](e.UPwIZ(_0x3d09af%_0x13046f,0),e.orIGV(e[s(1566)](_0x1dab81,_0x4896d8),0),_0x280060)}}function he(c){let r=t,s=0,l=0,h;do h=ee(c),s<32&&(l|=e[r(1076)](127,h)<<s),s+=7;while(e[r(824)](128,h));return l}function me(c,r){let s=t;for(r>>>=0;r>=128;)e[s(1561)](He,c,e.Rteaw(127,r)|128),r>>>=7;e[s(422)](He,c,r)}function Ct(c,r){let s=t,l=0,h=0,g=0,y;if(y=e.EQMMp(ee,c),l=e[s(1648)](127,y),128&y&&(y=ee(c),l|=e[s(890)](127&y,7),128&y&&(y=e[s(1253)](ee,c),l|=e[s(908)](e[s(731)](127,y),14),e[s(1680)](128,y)&&(y=e[s(1248)](ee,c),l|=e[s(855)](e.nxScm(127,y),21),e[s(1464)](128,y)&&(y=ee(c),h=e[s(1604)](127,y),e.pqYYA(128,y))))))if(e[s(405)](e[s(1445)],s(619))){if(y=e[s(1714)](ee,c),h|=e[s(1140)](127,y)<<7,128&y)if(e.dzoXI(e.BJWVA,e[s(889)]))y=e[s(1177)](ee,c),h|=e[s(908)](e[s(1793)](127,y),14),e[s(904)](128,y)&&(y=e.hNVGY(ee,c),h|=e.lXXFO(127&y,21),e.gPZCf(128,y)&&(y=ee(c),g=127&y,128&y&&(y=ee(c),g|=e.RcwpA(e.oszrm(127,y),7))));else return this._ws?this._ws[s(909)+"ns"]:""}else return e[s(558)](_0x3b3a8a(4)[s(1089)]("0"),e[s(620)](_0x3eca75,_0x4a41ce,2)[s(728)](16))[s(1116)](-4);return{low:e[s(1543)](l,e[s(571)](h,28)),high:e[s(604)](h,4)|g<<24,unsigned:r}}function yt(c,r){let s=t,l=e[s(633)](r[s(1668)],0),h=e[s(1727)](e[s(604)](r.low,28),e[s(1249)](r.high,4))>>>0,g=e[s(633)](r[s(1256)],24),y=g===0?e.QxPxF(0,h)?l<16384?e[s(1143)](l,128)?1:2:e[s(894)](l,2097152)?3:4:e[s(1585)](h,16384)?e[s(1578)](h,128)?5:6:e[s(776)](h,2097152)?7:8:e[s(1402)](g,128)?9:10,k=se(c,y),w=c[s(606)];switch(y){case 10:w[e[s(1591)](k,9)]=e[s(1464)](e.fFwDn(g,7),1);case 9:w[e.loWBb(k,8)]=e.ogUvf(9,y)?e[s(1540)](128,g):e[s(1140)](127,g);case 8:w[e[s(1006)](k,7)]=e[s(1356)](8,y)?e[s(796)](h,21)|128:e.BmrfZ(h,21)&127;case 7:w[e[s(1709)](k,6)]=e[s(393)](7,y)?e[s(435)](e.IZtas(h,14),128):e[s(796)](h,14)&127;case 6:w[e[s(1237)](k,5)]=e[s(631)](6,y)?e.JkWwp(h>>>7,128):e.tDGvJ(h>>>7,127);case 5:w[k+4]=e.EVJiD(5,y)?e[s(963)](128,h):e[s(1745)](127,h);case 4:w[e[s(973)](k,3)]=e[s(393)](4,y)?e[s(963)](e[s(1163)](l,21),128):e.CZlHQ(e[s(796)](l,21),127);case 3:w[k+2]=e[s(1162)](3,y)?e.qhyCp(e[s(1311)](l,14),128):e[s(852)](e[s(604)](l,14),127);case 2:w[e[s(1263)](k,1)]=e.pjEby(2,y)?e[s(985)](l>>>7,128):e.CZlHQ(e[s(567)](l,7),127);case 1:w[k]=e[s(1461)](1,y)?e[s(963)](128,l):e[s(824)](127,l)}}function cn(c){return e.zpYBR(b,c)}function jt(c){return e[t(1508)](v,c)}let dn=65536,ai=e[t(1623)],ye=e[t(1792)](dn,dn),Oe=e[t(919)](ye,ye),cr=e[t(639)](Oe,2),Fe=String[t(875)+"e"][t(1431)+"At"];class xe{constructor(r,s,l){let h=t;e[h(538)](e[h(819)],e[h(819)])?(e[h(1001)](_0x43d48c,65536)?_0x18c3ca[_0x5a50e4++]=e[h(927)](e[h(1471)](_0x525bff,12),15)|224:(_0x314178[_0xeda403++]=e[h(1793)](e[h(565)](_0x4e1fdc,18),7)|240,_0x6a9fa5[_0x4fdbf2++]=e[h(1707)](e[h(1604)](e.dmqwX(_0x54cbfb,12),63),128)),_0x4c7e47[_0x279eb2++]=e[h(963)](e[h(1673)](_0x1fefa4,6)&63,128)):(this[h(1698)]=!0,this[h(1668)]=0|r,this.high=e[h(1242)](0,s),this.unsigned=!!l)}static[t(1698)](r){return r&&e.pkHJm(!0,r.isLong)}static[t(523)](r,s,l){return new xe(r,s,l)}static fromBytes(r,s,l){let h=t;return l?xe[h(1437)+h(1126)](r,s):xe[h(1437)+h(646)](r,s)}static[t(1437)+t(1126)](r,s){let l=t;return new xe(e[l(1265)](e.pmyeK(e[l(1715)](r[0],e[l(1879)](r[1],8)),e[l(594)](r[2],16)),e[l(1761)](r[3],24)),e[l(1086)](e[l(1525)](r[4],e.YztYD(r[5],8)),r[6]<<16)|r[7]<<24,s)}static[t(1437)+t(646)](r,s){let l=t;return new xe(e[l(963)](e[l(900)](e.QheFL(e[l(1306)](r[4],24),r[5]<<16),e.LNVha(r[6],8)),r[7]),e[l(1707)](e[l(1400)](e[l(546)](e[l(1371)](r[0],24),e[l(1012)](r[1],16)),r[2]<<8),r[3]),s)}static[t(1843)](r){let s=t;return e[s(1747)](r,ai)?vl:new xe(e[s(1163)](e.jArVb(e.xToEG(e[s(1517)](Fe[s(444)](r,0),e[s(1666)](Fe[s(444)](r,1),8)),Fe.call(r,2)<<16),e[s(1664)](Fe[s(444)](r,3),24)),0),e[s(1163)](e.zQnaS(e[s(727)](Fe[s(444)](r,4),e.nWUXV(Fe.call(r,5),8))|e[s(1666)](Fe[s(444)](r,6),16),e[s(1395)](Fe[s(444)](r,7),24)),0),!0)}[t(983)](){let r=t;return String[r(940)+r(1738)](e[r(828)](255,this[r(1668)]),e[r(1131)](e[r(729)](this[r(1668)],8),255),e[r(1311)](this[r(1668)],16)&255,this[r(1668)]>>>24,e[r(1751)](255,this[r(1256)]),e.beJjv(e[r(1163)](this[r(1256)],8),255),e.bmood(this[r(1256)],16)&255,e[r(1163)](this[r(1256)],24))}static[t(1223)+"er"](r,s=!0){let l=t;if(isNaN(r))return s?pg:vl;if(s){if(r>=Oe)return mg}else if(e.MJkpx(e.gxaOM,e[l(478)]))++_0x2bbb6d,_0x171b27+=4;else{if(e[l(1037)](r,-cr))return wg;if(e.MRxFw(r,1)>=cr)return gg}return xe[l(523)](r%ye|0,e.tdnzI(e.pYhXK(r,ye),0),s)}toNumber(){let r=t;return this[r(690)]?(this[r(1256)]>>>0)*ye+e[r(796)](this[r(1668)],0):e[r(1175)](this[r(1256)]*ye,e[r(1311)](this[r(1668)],0))}[t(416)](){return e.JJLdq(0,this.high)&&e.yHEch(0,this.low)}[t(515)](r){let s=t;xe[s(1698)](r)||(r=xe[s(1223)+"er"](r));let l=this[s(1256)]>>>16,h=e[s(485)](65535,this[s(1256)]),g=e[s(633)](this[s(1668)],16),y=65535&this.low,k=r[s(1256)]>>>16,w=65535&r[s(1256)],O=e[s(633)](r[s(1668)],16),H=e[s(1124)](65535,r[s(1668)]),F=0,W=0,K=0,ce=0;return ce+=e[s(1679)](y,H),K+=e[s(591)](ce,16),ce&=65535,K+=g+O,W+=e.OXCSz(K,16),K&=65535,W+=e[s(804)](h,w),F+=e[s(754)](W,16),W&=65535,F+=e.pRLAj(l,k),F&=65535,xe[s(523)](e[s(1517)](e.jFseD(K,16),ce),e[s(1173)](e[s(1826)](F,16),W),this[s(690)])}[t(1635)](r){let s=t,l={OxhuE:function(h,g){return e[B(1739)](h,g)}};return e[s(1598)](e.uPBaV,e.uPBaV)?l.OxhuE(this[s(1450)],this[s(1639)+"ount"]):(xe[s(1698)](r)||(r=xe[s(1223)+"er"](r)),e[s(1602)](this[s(690)],r[s(690)])&&e[s(1742)](this[s(1256)]>>>31,1)&&e.fynjD(e[s(567)](r.high,31),1)?!1:e[s(413)](this[s(1256)],r.high)&&this[s(1668)]===r[s(1668)])}[t(835)](){let r=t;return e[r(969)](-1,this.low)&&e.evmsz(-1,this[r(1256)])?xe[r(523)](0,0,this[r(690)]):this[r(1668)]===-1?xe[r(523)](0,this[r(1256)]+1,this[r(690)]):xe[r(523)](this[r(1668)]+1,this[r(1256)],this[r(690)])}[t(798)](r){let s=t,l={nyTLa:function(h,g){return e[B(1456)](h,g)},JUmWA:function(h,g){return e[B(1714)](h,g)}};if(e.InwrJ===e.InwrJ)return r?this[s(1495)+"E"]():this[s(399)+"E"]();{let h=0,g={};for(let y=0;l.nyTLa(y,_0x570fa3[s(1407)]);y++)g[_0x49ec1c[y][s(464)+"ame"]]=l[s(1586)](_0x5d31d7,_0x3eaddf[y][s(464)+s(830)]),h+=14+g[_0x3d21a0[y][s(464)+s(830)]];return[h,g]}}[t(1495)+"E"](){let r=t,s=this[r(1256)],l=this[r(1668)];return[255&l,e[r(1140)](l>>>8,255),e.pqYYA(l>>>16,255),l>>>24,e[r(1140)](255,s),e.uZLlF(s>>>8,255),e.ZKIIe(e[r(604)](s,16),255),e[r(533)](s,24)]}[t(399)+"E"](){let r=t;if(e[r(954)]===e.LfaNy){let h=(r(1277)+"3")[r(1432)]("|"),g=0;for(;;){switch(h[g++]){case"0":var s=_0x1aeb60[_0x42b29e]={exports:{}};continue;case"1":var l=_0x32f387[_0x53add9];continue;case"2":_0x3d4980[_0x2ca206](s,s[r(1141)],_0x408068);continue;case"3":return s[r(1141)];case"4":if(UtxsnM[r(1602)](void 0,l))return l[r(1141)];continue}break}}else{let h=this[r(1256)],g=this[r(1668)];return[e[r(1243)](h,24),e.Furgk(e[r(1414)](h,16),255),e[r(806)](e[r(635)](h,8),255),255&h,e.ZWdvu(g,24),e.xCANA(e[r(1163)](g,16),255),e[r(806)](e[r(1093)](g,8),255),e[r(1672)](255,g)]}}}let vl=new xe(0,0,!1),pg=new xe(0,0,!0),gg=xe[t(523)](-1,2147483647,!1),mg=xe[t(523)](-1,-1,!0),wg=xe[t(523)](0,-2147483648,!1);var ln=(function(c){let r=t,s=e[r(1054)][r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":return c;case"1":c[c[r(968)+r(459)]=5004]=r(968)+r(459);continue;case"2":c[c[e.YIABy]=5005]=e[r(1123)];continue;case"3":c[c[e[r(1757)]]=5001]=e[r(1757)];continue;case"4":c[c[e[r(1515)]]=5002]=e[r(1515)];continue;case"5":c[c[e.xtTxr]=5003]=r(1018)+r(401)+"R";continue}break}})({});class dr{constructor(r){this.type=r,this.target=null}}class Sl extends dr{constructor(r,s){let l=t;super(r),this[l(1813)]=s&&s[l(1813)]||null}}class Il extends dr{constructor(r,s){let l=t,h={dJPRM:function(g,y){return g(y)}};if(e[l(1262)](e.TUGwA,l(1541)))return function(...g){let y=l;return _0x36f6f8[y(662)](SnkRfP.dJPRM(_0x4b736b,this),g),_0x27fc06(_0x44be9d[y(493)](this))};super(r),this[l(749)]=s&&s[l(749)]||null,this[l(993)]=s&&s[l(993)]||0,this[l(1392)]=s&&s[l(1392)]||"",this[l(576)]=s&&s.lineno||0,this.message=s&&s[l(1813)]||"",this.code=s&&s[l(655)]||5001}}class Al extends dr{constructor(r,s){let l=t,h=(l(1320)+"0")[l(1432)]("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(1800)+l(964)]=s&&s["willReco"+l(964)]||!1;continue;case"1":super(r);continue;case"2":this[l(1653)]=s&&s[l(1653)]||"";continue;case"3":this[l(655)]=s&&s[l(655)]||0;continue;case"4":this.wasClean=s&&s[l(552)]||!1;continue}break}}}class kl extends dr{constructor(r,s){let l=t;super(r),this.data=s&&s[l(1838)]||null}}class Tl extends kl{constructor(r,s){let l=t;super(r),this[l(1838)]=s&&s.data||null,this.message=s&&s[l(1813)]||null}}class Cl extends dr{constructor(r,s){let l=t;super(r),this[l(1838)]=s&&s[l(1838)]||null}}function ht(c,{message:r,code:s,error:l}){return new Il(c,{message:r,code:s,error:l})}function bt(c,{code:r,reason:s,wasClean:l,willReconnect:h}){return new Al(c,{code:r,reason:s,wasClean:l,willReconnect:h})}function Rl(c,{data:r,message:s}){return new Tl(c,{data:r,message:s})}function Pl(c,{data:r}){let s=t;if(e.IqwYF(e[s(1087)],"zGqDx"))return new Cl(c,{data:r});for(var l in _0x55b8b8)_0x12d8b8.o(_0x4de335,l)&&!_0x4175c1.o(_0xe1f9d,l)&&_0x5b8c4e[s(1512)+s(933)](_0x505a67,l,{enumerable:!0,get:_0x572e48[l]})}function Pa(c,{message:r}){return new Sl(c,{message:r})}class Dl{constructor(r,s){let l=t;this.endpoints=r,this[l(1370)+"es"]=s,this.currentIndex=0,this[l(1245)+"ndpointT"+l(665)+"t"]=0}[t(458)+"pointConfig"](){let r=t;if(e.Qbtrd(e.FEVCf,"XAsPM"))this["currentI"+r(990)]=0,this[r(1245)+r(1704)+r(665)+"t"]=0;else{let s={XUdjV:function(l,h,g){return e[r(1382)](l,h,g)}};return new _0x43db50(l=>{let h=r;s.XUdjV(_0x3d62ea,l,this[h(1398)+"rvalValue"](_0x41854c))})}}resetTries(){let r=t;this[r(1245)+r(1704)+"riesCount"]=0}[t(791)+t(1498)+"nt"](){let r=t,s={BbXGK:function(l,h){return e[B(1426)](l,h)}};if(e.NCaMf("XzBTN",e[r(1343)]))return this.endpoints[this[r(1077)+r(990)]];{let l=this[r(1531)][r(1728)+r(1782)](this[r(842)]),h=_0x1c541b[r(477)](s[r(687)](l,"{}"));return h[_0x49908e||_0x213111[this[r(1711)]]]=_0x449ce7,this._qosDB[r(1694)+r(1782)](this._prefix,_0x3cce83[r(1499)+"y"](h)),_0x5be200||_0x1a1db5[this[r(1711)]]}}[t(791)+"ntEndpointTriesC"+t(1152)](){let r=t;return this[r(1245)+"ndpointT"+r(665)+"t"]}checkReachMaxTries(){let r=t;return!!(e[r(679)](this[r(1077)+"ndex"],this[r(1044)+"s"][r(1407)])||e[r(969)](this[r(1077)+"ndex"],e[r(1324)](this[r(1044)+"s"].length,1))&&e[r(1271)](this[r(1245)+r(1704)+"riesCount"],this[r(1370)+"es"]))}[t(1887)+t(1460)+"ointReac"+t(1315)+t(1296)](){let r=t;return e[r(1213)](this["currentI"+r(990)],this.endpoints[r(1407)])?!0:this[r(1245)+"ndpointT"+r(665)+"t"]>this[r(1370)+"es"]}[t(1424)+t(1230)+t(1068)+t(1375)+"unt"](){let r=t;return this[r(1245)+r(1704)+r(665)+"t"]=1,this[r(1077)+r(990)]++,this[r(1044)+"s"][this["currentI"+r(990)]]}[t(791)+t(1498)+t(843)+"ateCount"](){let r=t;return this[r(1245)+r(1704)+"riesCount"]++,this[r(791)+r(1498)+"nt"]()}}let lr=(e[t(1713)](e[t(1363)],typeof globalThis)&&e.noBLq===globalThis[t(1696)+"tor"][t(1588)]||e[t(1363)]!=typeof window&&e[t(1777)]("Window",window.constructor.name))&&e[t(1713)](e[t(1363)],typeof document),Ln=e[t(1713)](e[t(1363)],typeof globalThis)&&(e[t(1212)](t(520),globalThis[t(1696)+t(1084)][t(1588)])||e[t(1358)](e[t(402)],globalThis[t(1696)+t(1084)][t(1588)]))&&e[t(837)](e[t(1363)],typeof tt),ci=(e[t(837)](t(1434)+"d",typeof globalThis)&&e.TMMNx(e[t(733)],globalThis[t(1696)+t(1084)][t(1588)])||e[t(884)](e.ErXbE,typeof globalThis)||e[t(1713)](e[t(1363)],typeof globalThis)&&!!globalThis[t(1733)+"Bridge"])&&e[t(1101)](e[t(1363)],typeof wx),di=e[t(1363)]!=typeof globalThis&&(e[t(402)]===globalThis[t(1696)+t(1084)][t(1588)]||e.SlLdb(e[t(1542)],globalThis["construc"+t(1084)].name)||e[t(712)](e[t(1494)],globalThis[t(1696)+t(1084)][t(1588)]))&&e.ErXbE!=typeof self,_g=e[t(654)](e[t(1363)],typeof globalThis)&&e[t(1433)](e[t(733)],globalThis[t(1696)+t(1084)].name)&&e[t(1363)]!=typeof global&&e[t(1219)](e.zhjJN,global["construc"+t(1084)][t(1588)])&&e[t(1713)](e[t(1363)],typeof process)&&!!process.version;class Da{constructor(){let r=t;this[r(1806)+"rs"]={}}[t(1700)](r,...s){let l=t,h=this[l(1806)+"rs"][r];if(h)h[l(1116)]()[l(920)](g=>g.fn.apply(g.ctx,s));else if(e.uhqTk(e[l(1579)],r)&&!this[l(425)]){let g=s.length&&s[0];if(e[l(1355)](g,Error))throw g;let y=new Error(e.HytZq(e[l(1260)],g?e.MRxFw(" ("+g[l(1813)],")"):""));throw y[l(1073)]=g,g}return this}[t(1397)](r,s){let l=t;if(e[l(1338)](void 0,r))this._listeners={};else if(e[l(1828)](void 0,s))this[l(1806)+"rs"][r]=null;else{let h=this._listeners[r];if(h)for(let g=0;g<h[l(1407)];)e[l(1742)](h[g].fn,s)?h[l(1590)](g,1):++g}return this}on(r,s,l){let h=t;return e.fZaKL(e[h(1380)],e[h(1380)])?{frameType:_0x42e49c,headers:[{key:e[h(1003)],value:e[h(1014)]}],payload:void 0}:((this[h(1806)+"rs"][r]||(this._listeners[r]=[]))[h(489)]({fn:s,ctx:l||this}),this)}}class yg extends Da{[t(1351)+t(1258)+t(1527)](r){let s=t;return r[s(1121)]||r[s(1441)]?(s(559)+" "+(r[s(1121)]||"")+" code: "+(r[s(1441)]||""))[s(1362)]():JSON[s(1499)+"y"](r)}constructor(r,s,l){let h=t;super(),this[h(1168)]=null,ci&&wx[h(932)+"ocket"]&&(this[h(1168)]=wx["connectS"+h(1052)]({url:r,protocols:s,header:l,fail:this["_createS"+h(1285)+h(1191)].bind(this),success:this[h(897)+"ocketSuc"+h(1690)+h(497)][h(1072)](this)})),Ln&&tt[h(932)+h(1052)]&&(this[h(1168)]=tt[h(932)+h(1052)]({url:r,protocols:s,header:l,fail:this[h(897)+h(1285)+h(1191)].bind(this),success:this[h(897)+h(543)+h(1690)+h(497)][h(1072)](this)}))}["_createS"+t(543)+t(1690)+t(497)](){let r=t;Promise[r(1819)]()[r(1663)](()=>{this["_addWsLi"+r(1831)]()})}[t(897)+t(1285)+t(1191)](r){let s=t,l={OMiXh:function(h,g,y){return e[B(1522)](h,g,y)},kDlzO:s(749),sMuGR:function(h,g,y){return e.HgBVq(h,g,y)},xMkHN:s(438)};Promise.resolve().then(()=>{let h=s,g=l[h(1313)](ht,h(749),{message:this[h(1351)+"rrorMess"+h(1527)](r)});this.emit(l.kDlzO,g);let y=l[h(432)](bt,l[h(1232)],{reason:this[h(1351)+h(1258)+h(1527)](r)});this[h(1700)](l[h(1232)],y)})}[t(553)+"steners"](){let r=t,s={EonNe:e[r(721)],dgjbY:function(l,h,g){return e[r(941)](l,h,g)}};this[r(1168)][r(891)](l=>{let h=r;this[h(1700)](h(1430),e[h(1090)](Pl,e[h(1071)],{...l,data:l.errMsg||""}))}),this._socket[r(486)](l=>{let h=r;this.emit(e[h(1274)],e[h(397)](bt,e[h(1274)],{...l}))}),this._socket.onMessage(l=>{let h=r;this.emit(s[h(863)],s[h(1027)](Rl,h(1813),{...l}))}),this[r(1168)].onError(l=>{let h=r;this[h(1700)](e[h(1579)],ht(h(749),{...l,message:l.errMsg||""}))})}[t(1383)](r){let s=t,l={zRPZN:e.Zddjg,PYdef:function(h,g,y){return e.qNahp(h,g,y)}};if(e.wHrpe(r,Uint8Array)){let h=r.buffer[s(1116)](r[s(1851)+"et"],e.teXqB(r.byteLength,r[s(1851)+"et"]));this._socket&&this._socket.send({data:h,fail:g=>{let y=s;this[y(1700)](e[y(1579)],e[y(1880)](ht,y(749),{message:this["_formatE"+y(1258)+y(1527)](g)}))}})}else this[s(1168)]&&this[s(1168)].send({data:r,fail:h=>{let g=s;this[g(1700)](l.zRPZN,l.PYdef(ht,l.zRPZN,{message:this[g(1351)+g(1258)+"age"](h)}))}})}[t(438)](r,s){let l=t;this[l(1168)]&&this[l(1168)][l(438)]({code:r,reason:s})}addEventListener(r,s){this.on(r,s)}[t(1550)+t(1436)+"ner"](r,s){this[t(1397)](r,s)}get[t(743)+"te"](){let r=t;return this._socket[r(743)+"te"]}get[t(763)+"pe"](){let r=t;return this[r(1168)][r(763)+"pe"]}set binaryType(r){}get[t(645)](){let r=t;return this[r(1168)][r(645)]}get[t(1612)](){return this[t(1168)].protocol}get[t(909)+"ns"](){let r=t;return this[r(1168)][r(909)+"ns"]}get[t(423)+t(490)](){return 0}}function bg(c,r){let s=t;if(r)return new r(c[s(645)],c[s(1612)]);if(e[s(1095)](ci,Ln))return new yg(c[s(645)],c[s(1612)],c.headers);if(e[s(1426)](lr,di)&&e[s(837)](e[s(1363)],typeof WebSocket)&&WebSocket)return new WebSocket(c[s(645)],c[s(1612)+"s"])}function Eg(c){let r=t;if(e.HGAQl===r(1618)){let s=(r(1474)+"3")[r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(c)return!0;continue;case"1":if(Ln&&tt.connectSocket)return!0;continue;case"2":if(ci&&wx[r(932)+r(1052)])return!0;continue;case"3":return!1;case"4":if(e[r(625)](lr,di)&&e[r(837)](e[r(1363)],typeof WebSocket)&&WebSocket)return!0;continue}break}}else e[r(1167)](_0xd2854d,this,_0x20f63e,[_0x437552,_0x57def6,_0x1444dc])}function Ol(c,r,s){let l=t,h={KCAtv:function(k,w){return e.yfcxy(k,w)},FiikT:e[l(938)],fEarO:function(k,w){return e[l(1742)](k,w)}},g=-1;async function y(k){let w=l;return h[w(1129)](k,g)?Promise[w(844)](new Error(h[w(748)])):(g=k,h.fEarO(k,s.length)?Promise[w(1819)]():s[k][w(1072)](c)(r,y.bind(null,k+1)))}e.GZyFw(y,0)}function Ll(c){let r=t;if(e.MJkpx(e[r(1632)],e[r(455)])){let s=0,l=0;for(let h=0;e[r(1794)](h,c[r(1407)]);++h)r(440)===e.DLdgm?(_0x425a00=e[r(1864)](e[r(571)](7&_0x219adf,18)|e.hgdFX(e[r(577)](63,_0x1171f7),12),e[r(1670)](63&_0x3bc31a,6))|e[r(824)](63,_0x29d6c9),_0x39105b<65536||_0x45f12f>1114111?_0x16df61+=_0x252e24:(_0x38b97c-=65536,_0x29d048+=_0x7cd82b(e[r(1391)](_0x4867aa>>10,55296),e[r(862)](e.UlpqP(1023,_0x15c798),56320)),_0x248c98+=3)):(l=c[r(1431)+"At"](h),e[r(549)](l,128)?s+=1:e[r(1505)](l,2048)?s+=2:e[r(405)](e[r(1784)](64512,l),55296)&&e[r(632)](e[r(1816)](64512,c[r(1431)+"At"](e.BCaNT(h,1))),56320)?(++h,s+=4):s+=3);return s}else{let s=e[r(664)].split("|"),l=0;for(;;){switch(s[l++]){case"0":if(_0x1bfa41.utf8Write)return _0x465c73.utf8Write(_0x250916,_0x38e4f9)+_0x450fc6;continue;case"1":if(e.xWpYk(_0x26a604[r(1407)],40))return e[r(406)](_0x47526e(_0x4b7cca,_0x2ddeb6,_0x494afb),_0x213f89);continue;case"2":return e[r(1202)](e[r(1167)](_0x196c71,_0x3e381c,_0xcce51,_0x518a57),_0x1cc203);case"3":if(!_0xc8f61a)return _0xb3dc06;continue;case"4":if(_0x158523[r(1114)])return e[r(560)](_0x33e1fa[r(1114)](_0x1763f1,_0x30c28a),_0x42dbf1);continue}break}}}function Nl(c,r,s){let l=t;if(e.wovgs(e[l(1862)](s,r),1))return"";let h="";for(let g=r;e.kNkKk(g,s);){let y=c[g++];if(e.gYacW(y,127))h+=String["fromChar"+l(1738)](y);else if(y>=192&&y<224)h+=String[l(940)+l(1738)](e[l(683)](e[l(807)](e.IYqAm(31,y),6),e[l(1082)](63,c[g++])));else if(e[l(1194)](y,224)&&e[l(472)](y,240))h+=String[l(940)+"Code"](e[l(435)](e[l(914)](e[l(1826)](e.ibnZy(15,y),12),e[l(1395)](e.Furgk(63,c[g++]),6)),e[l(587)](63,c[g++])));else if(e[l(1802)](y,240)){let k=e[l(1324)](e.SRgLn(e[l(1400)](e[l(1092)](e.mWcQm(7,y),18)|e[l(855)](e.uZLlF(63,c[g++]),12),e[l(555)](63&c[g++],6)),63&c[g++]),65536);h+=String[l(940)+l(1738)](e[l(1709)](55296,k>>10)),h+=String[l(940)+l(1738)](e[l(622)](56320,e[l(978)](1023,k)))}}return h}function Oa(c,r,s){let l=t,h=s,g,y;for(let k=0;k<c[l(1407)];++k)if(g=c[l(1431)+"At"](k),e[l(1468)](g,128))r[s++]=g;else if(e[l(1839)](g,2048))if(e.cjsFB!==e.nAqAo)r[s++]=e[l(1595)](g>>6,192),r[s++]=e[l(1050)](63&g,128);else return _0x1413b5[l(548)](_0x2c3a07),!1;else if(e.evmsz(e.FyIeE(64512,g),55296)&&e.twYlI(e[l(1036)](64512,y=c[l(1431)+"At"](e[l(1830)](k,1))),56320)){let w=e[l(678)][l(1432)]("|"),O=0;for(;;){switch(w[O++]){case"0":r[s++]=g>>18|240;continue;case"1":r[s++]=e[l(727)](e[l(534)](g,12)&63,128);continue;case"2":r[s++]=e[l(1755)](e[l(1040)](63,g),128);continue;case"3":++k;continue;case"4":r[s++]=e[l(731)](e[l(565)](g,6),63)|128;continue;case"5":g=e[l(692)](e[l(537)](65536,e[l(555)](e[l(1387)](1023,g),10)),e.Furgk(1023,y));continue}break}}else r[s++]=e[l(1423)](g,12)|224,r[s++]=e[l(663)](g,6)&63|128,r[s++]=e[l(1164)](e[l(825)](63,g),128);return e.EJYqL(s,h)}async function Ml(c){let r=t,s={ZNeme:function(l,h,g){return l(h,g)},RMZvH:function(l,h){return e[B(1727)](l,h)}};if(e[r(1858)]===e[r(1858)]){if(e.lACtz(e[r(1465)],typeof c))if(e[r(1183)](e.VJYKv,"cftGA")){for(_0x3fa474>>>=0;_0x24d25f>=128;)mLVwSw.ZNeme(_0x2514b8,_0x5ed0f9,mLVwSw[r(556)](127&_0x5310bb,128)),_0x112a87>>>=7;_0x1212b8(_0x2cd89e,_0x58e966)}else{let l=new Uint8Array(e[r(799)](Ll,c));return e[r(1301)](Oa,c,l,0),l}return e[r(1355)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[r(834)],c[r(1851)+"et"],c.byteLength)}else this[r(1530)+"mise"]=null}function vg(c){let r=t,s={JSjUu:function(l,h){return l===h},pbkdh:function(l,h){return l!==h},idsXD:function(l,h,g){return e[B(1605)](l,h,g)}};try{return e[r(837)]("string",typeof c)&&(c instanceof ArrayBuffer||c.buffer&&c.buffer instanceof ArrayBuffer)||e[r(1713)](e.NzOeh,typeof c)?"":(JSON.parse(c),r(525)+r(1100))}catch{if(e.pjEby(e[r(1429)],e[r(858)]))return e[r(1422)](e[r(1465)],typeof c)?e.cDYQe:"";if(this[r(1594)]&&s.JSjUu(this[r(1594)][r(743)+"te"],this.CONNECTING)){this[r(1846)+r(1547)](),this[r(944)+r(1801)+"Id"]=_0x413834(this[r(1264)][r(1072)](this),this[r(979)][r(1418)+r(419)]);return}if(!this[r(1594)]||s[r(1206)](this[r(1594)][r(743)+"te"],this.OPEN))return void this[r(788)+r(1459)]();this[r(1594)]&&this._ws[r(1383)]("hi"),this[r(716)+"ctTimeou"+r(596)]=s[r(1634)](_0x1d3b28,this[r(788)+r(1459)+r(921)][r(1072)](this),this[r(979)][r(414)+"outInter"+r(1650)])}}let Sg=(c,r)=>{let s=t;if(e[s(771)](e[s(1282)],e.xqZBy))Ce[s(1118)+s(473)]=_0x2b4a68,Ce._ws&&(Ce._ws[s(763)+"pe"]=_0x4cb719);else switch(c){case e.JXPag:case e[s(1853)]:return{["x-use-"+c]:1,"x-tt-env":r};default:return{}}};class Ig{constructor(r){let s=t;this["maxLossC"+s(1152)]=r,this[s(1450)]=0}[t(1872)](){this.count++}[t(1654)+t(1229)+"nt"](){let r=t;if(e[r(1183)](e[r(1330)],e.ZZsAo)){let s=this[r(1531)]["getStora"+r(1782)](this[r(842)]);return _0x321480[r(477)](e.JxZoK(s,"{}"))[_0x31317d]}else return e[r(1228)](this[r(1450)],this[r(1639)+r(1152)])}[t(463)+"nter"](r=0){let s=t;this[s(1639)+s(1152)]=r,this[s(1450)]=0}}async function Ag(c){let r={KDJsQ:function(s,l){return e[B(1447)](s,l)},GRVpM:function(s){return s()},SgyyV:function(s,l,h){return e[B(1569)](s,l,h)},AVAJh:function(s,l){return e[B(1248)](s,l)}};return new Promise(s=>{let l=B;if(!lr)return e[l(1714)](s,e[l(1807)]);try{let h=document[l(1444)+l(854)](e[l(680)]);window[l(471)+l(1514)]=g=>{let y=l;document[y(1753)][y(1808)+y(1772)](h),window[y(471)+y(1514)]=void 0,r.KDJsQ(s,g&&g[y(1060)]||"unknown "+y(1653))},h.type=e[l(551)],h.src=e[l(540)](c.replace(/^ws/,e[l(1390)]),e[l(1154)]);try{document[l(1753)][l(509)+l(1772)](h)}catch{if(l(1047)===e[l(1523)])document.body[l(1808)+l(1772)](h);else{let g=mscmMg[l(1210)](_0x31c4d3);return mscmMg.SgyyV(_0x4983af,_0x237087,g),mscmMg.AVAJh(_0x5a5573,g)}}}catch{window[l(471)+"JSONP"]=void 0,e[l(1820)](s,e[l(1807)])}})}function un(c,r,s){let l=t;return!!c?.[l(1457)](h=>h[l(1484)]===r&&h[l(715)]===s)}function ur(c,r){let s=t;return c?.[s(1457)](l=>l[s(1484)]===r)?.[s(715)]}let La=null;async function kg(){let c=t;return La||(La=Promise[c(1819)]()[c(1663)](Gt.bind(Gt,e.GCstk))),La}class Tg extends Da{constructor(r,s){let l=t;super(),this[l(611)]=r,this[l(536)]=s,this[l(1531)]=void 0,this._initPromise=null}async[t(709)](){await this._init()}async[t(618)](){let r=t,s={TwHgV:function(l){return l()},iXhNh:function(l,h,g,y){return e[B(636)](l,h,g,y)}};if(!this[r(1531)]){if(this[r(1530)+r(1085)])return this[r(1530)+r(1085)];try{let l=this[r(611)],h=this[r(536)];this[r(1530)+r(1085)]=(async()=>{let g=r,{openDB:y}=await s.TwHgV(kg);this[g(1531)]=await s[g(1117)](y,g(471)+"_"+l,1,{upgrade(k){let w=g;k[w(1298)+w(1010)+"e"](l,{keyPath:h})}})})(),await this["_initPro"+r(1085)]}catch(l){console[r(548)](l)}finally{if(e[r(498)](r(1785),e[r(1043)])){let l=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(737)](_0x3d1101),h=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(737)](_0x3d881d);return l?e.hNVGY(_0x55f71b,_0x4a78a9):h?e.msNLd(_0x10977d,_0x4bf4dd):e[r(670)]}else this[r(1530)+r(1085)]=null}}}async get(r){let s=t;if(e[s(915)]===s(1780))return this[s(1594)]?this._ws[s(645)]:this[s(1321)];try{return await this._init(),this[s(1531)]?.get(this[s(611)],r)}catch(l){console[s(548)](l)}}async[t(598)](r,s){let l=t;return await this._init(),this[l(1531)]?.put(this[l(611)],r)}async[t(1425)](r){let s=t;try{return await this[s(618)](),this[s(1531)]?.delete(this._dbName,r)}catch(l){console[s(548)](l)}}async[t(831)](){let r=t;if(e[r(671)](e.PsdSO,r(601)))this.emit(e.Zddjg,_0x333131(e[r(1579)],{message:this[r(1351)+r(1258)+"age"](_0x4c1327)}));else try{return e[r(1788)](e[r(1170)],e[r(1170)])?(await this[r(618)](),this._qosDB?.[r(831)](this[r(611)])):new _0x3ba308(_0x28ba59)}catch(s){console[r(548)](s)}}async keys(){let r=t;return e[r(1568)]!==e.GWshr?(_0xa0a847&&(_0x457e49=(0,_0x3733b9[_0x26dc45(_0x542b25)[0]])(_0x242876=0)),_0x18c22b):(await this[r(618)](),this[r(1531)]?.[r(1452)+"ys"](this._dbName))}async[t(446)](){let r=t;return await this._init(),this._qosDB?.getAll(this[r(611)])}async[t(1501)](){let r=t;try{this._qosDB?.close(),this[r(1531)]=void 0}catch(s){console[r(548)](s)}}get[t(603)](){let r=t;try{return!!this[r(1531)]}catch(s){return console[r(548)](s),!1}}}class Cg{constructor(r,s){let l=t;this[l(816)]=r,this[l(1711)]=s,this[l(1531)]=localStorage}async[t(709)](){}get[t(842)](){let r=t,s={JVTka:function(l,h){return l-h}};if(e[r(1841)](e[r(896)],e[r(896)])){let l=_0xf03b95.substring(0,OymWwD[r(411)](4,_0x32c57e[_0x388779][r(1407)])),h=l.concat(_0x18b7c1);_0x580992=_0x5c08cc[r(803)](h)}else return r(471)+"_"+this[r(816)]}async[t(493)](r){let s=t;if(e[s(1262)](s(1616),e[s(1259)])){let l=this[s(1531)][s(1254)](this[s(842)]);return JSON[s(477)](e.Rtltm(l,"{}"))[r]}else _0x50b8c4[s(548)](_0x33adb9)}async[t(598)](r,s){let l=t,h=this._qosDB[l(1254)](this[l(842)]),g=JSON[l(477)](e[l(1479)](h,"{}"));return g[s||r[this[l(1711)]]]=r,this[l(1531)][l(1688)](this[l(842)],JSON[l(1499)+"y"](g)),s||r[this[l(1711)]]}async[t(1425)](r){let s=t,l=this[s(1531)][s(1254)](this[s(842)]),h=JSON[s(477)](e[s(1479)](l,"{}"));return h[r]=void 0,this[s(1531)].setItem(this[s(842)],JSON[s(1499)+"y"](h))}async[t(831)](){let r=t,s={hpGQK:function(l,h,g,y){return l(h,g,y)},jNvTP:function(l,h,g){return e[B(699)](l,h,g)},zjtCe:e.Zddjg};if(e[r(1598)](r(1439),e[r(1045)]))return this._qosDB[r(831)]();try{s[r(641)](_0x48612e,this,_0x52438d,[_0x10c1c5,_0x4cdab2,_0x37e211])}catch(l){let h=s[r(561)](_0x596a88,s[r(1347)],{message:l.message,code:_0x143502[r(1877)+"OR"],error:l});this[r(1255)+"hErrorEv"+r(741)](h)}}async[t(991)](){let r=t,s=this._qosDB[r(1254)](this._prefix),l=JSON[r(477)](e.Rtltm(s,"{}"));return Object[r(991)](l)}async[t(446)](){let r=t,s=this[r(1531)].getItem(this._prefix),l=JSON.parse(e[r(625)](s,"{}"));return Object[r(1490)](l)}[t(1501)](){return Promise[t(1819)]()}get[t(603)](){return!!this[t(1531)]}}class Rg{constructor(r,s){let l=t;this._DBName=r,this._pathKey=s,this[l(1531)]=Ln?tt:ci?wx:null}async[t(709)](){}get[t(842)](){let r=t;return r(471)+"_"+this[r(816)]}async get(r){let s=t,l=this[s(1531)][s(1728)+s(1782)](this[s(842)]);return JSON[s(477)](l||"{}")[r]}async[t(598)](r,s){let l=t,h=this[l(1531)][l(1728)+l(1782)](this[l(842)]),g=JSON.parse(e.Cwrij(h,"{}"));return g[s||r[this[l(1711)]]]=r,this._qosDB[l(1694)+l(1782)](this[l(842)],JSON.stringify(g)),s||r[this._pathKey]}async del(r){let s=t;if(e[s(1136)](e[s(1702)],s(1587)))this._messageQueue.shift(),this[s(1478)+s(475)].push(_0x545067);else{let l=this[s(1531)].getStorageSync(this[s(842)]),h=JSON[s(477)](e[s(1015)](l,"{}"));return h[r]=void 0,this._qosDB[s(1694)+s(1782)](this._prefix,JSON.stringify(h))}}async[t(831)](){let r=t;return this[r(1531)][r(1741)+r(957)]()}async[t(991)](){let r=t,s=this._qosDB[r(1728)+r(1489)+"nc"](this[r(842)]),l=JSON[r(477)](e[r(666)](s,"{}"));return Object.keys(l)}async[t(446)](){let r=t;if(e[r(396)]===e[r(396)]){let s=this[r(1531)][r(1728)+r(1489)+"nc"](this[r(842)]),l=JSON.parse(s||"{}");return Object[r(1490)](l)}else _0x3d9e38[r(1753)][r(1808)+"ild"](_0x2b50db)}[t(1501)](){return Promise.resolve()}get[t(603)](){return!!this._qosDB}}function Bl(c,r){let s=t;if(Ln||Ln)return new Rg(c,r);if(e[s(1438)](lr,di)&&e[s(837)](e[s(1363)],typeof indexedDB))return new Tg(c,r);if(e[s(1479)](lr,di)&&e[s(837)](s(1434)+"d",typeof localStorage))return new Cg(c,r);throw new Error(e[s(1469)])}class Pg{constructor(){let r=t;if(e.nvxMo(e[r(1524)],"hEDYm"))this[r(1091)+r(1196)+"Id"]=null,this[r(1091)+"l"]=36e5,this._qosDB=e[r(1090)](Bl,e[r(1035)],e[r(1065)]);else return this[r(1531)][r(831)]()}async["_interva"+t(431)](){let r=t;e.scgeX(clearInterval,this["_interva"+r(1196)+"Id"]),this[r(1091)+"lTimeoutId"]=e[r(1382)](setInterval,()=>{this.flushExpired()},this[r(1091)+"l"])}async[t(709)](){let r=t;await this[r(1531)][r(709)]().then(()=>{this["_interva"+r(431)]()})}async["flushExp"+t(1025)](){let r=t;(await this[r(1531)]?.getAll()||[]).filter(({timestamp:h})=>h<Date[r(427)]())[r(920)](h=>{let g=r;this[g(1531)]?.[g(1425)](h[g(1137)+"id"])})}async[t(1425)](r){let s=t;return this[s(1531)]?.[s(1425)](r)}async set(r,s){return this[t(1531)]?.set({message_id:r,timestamp:s})}async[t(493)](r){let s=t;if(e.dzoXI(e.CMHPA,e[s(760)]))return this._qosDB?.[s(493)](r);try{this[s(1594)]&&this[s(1594)][s(438)](_0x23205d,_0x44ca3a)}catch{}}async[t(1501)](){let r=t;e.msNLd(clearInterval,this[r(1091)+r(1196)+"Id"]),await this[r(1531)]?.[r(1501)]()}get[t(603)](){let r=t;return this[r(1531)]?.[r(603)]}}function Na(c){let r=t;if(e[r(1841)]("EBsqa",e[r(468)])){let s=!!this[r(979)][r(759)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(1301)](un,c.message[r(967)],r(545)+r(1112),"2"),h=l&&e[r(1167)](un,c.message[r(967)],e[r(1454)],"1"),g=l&&e[r(1167)](un,c[r(1813)][r(967)],e[r(1496)],"1"),y=g?ur(c[r(1813)][r(967)],e[r(442)])?.split(",")[r(1305)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:g,ackMsgIds:y}}else{let s=_0x83b5d0[r(1431)+"At"](_0x545d84);e[r(866)](s,55296)&&e[r(1708)](s,56319)&&e.GyzJh(_0x3942e7+1,_0x1936ba)&&(s=e[r(1102)](e[r(1e3)](e[r(451)](s,10),_0x1c93b6[r(1431)+"At"](++_0x33c3ab)),56613888)),_0x2aad91+=e[r(1286)](s,128)?1:s<2048?2:e[r(547)](s,65536)?3:4}}async function Fl(){let c=t;return this[c(1011)+c(950)]||(this[c(1011)+c(950)]=new Pg),this[c(1011)+c(950)].isReady||await this[c(1011)+c(950)][c(709)](),this[c(1011)+c(950)]}async function Dg(c,r){let s=t,{enableAutoAck:l}=this[s(979)],h=e[s(636)](un,c.message[s(967)],s(629),"1"),g=e[s(1167)](un,c[s(1813)][s(967)],e[s(746)],"1"),y=Na.call(this,c);if(l&&h){let{SeqID:k,LogID:w,service:O,LogIDNew:H,method:F}=c[s(1813)];this[s(518)]({SeqID:k,LogID:w,LogIDNew:H,service:O,method:F,headers:[{key:e[s(746)],value:"1"},{key:e.BHJok,value:e[s(1845)](H,"")},{key:e[s(977)],value:"0"}]})}g&&!y.isQoSAck&&this[s(1255)+s(1309)+s(1288)](c),e[s(682)](r)}async function Og(c,r){let s=t,l={qIWyj:function(h,g){return h(g)},fkhoN:function(h,g,y){return e.rTGvF(h,g,y)}};if(e[s(1644)](e[s(1146)],"cXtyn"))return(hTSIjg.qIWyj(_0x53841d,8).join("0")+hTSIjg.fkhoN(_0x194576,_0x5e9683,10).toString(2))[s(1116)](-8);this._debug(e[s(1601)],c.message),e.TABTV(r)}async function Lg(c,r){let s=t,l=e.iZVZq(cn,await e[s(1253)](Ml,c[s(1838)]));try{if(e[s(1355)](l[s(1627)],Uint8Array)){let h=e[s(1355)](this[s(979)]["payloadE"+s(767)],Object)?{force:!!this[s(979)][s(700)+s(767)][s(1238)],encoding:this[s(979)][s(700)+s(767)].encoding?this[s(979)][s(700)+s(767)][s(1442)][s(893)](/\s/g,"")[s(974)+s(1693)]():""}:{force:!1,encoding:this._options[s(700)+s(767)]?this[s(979)]["payloadE"+s(767)].replace(/\s/g,"")["toLowerC"+s(1693)]():""},g=l[s(700)+s(767)]?l[s(700)+s(767)][s(893)](/\s/g,"")[s(974)+s(1693)]():"",y=e[s(1619)](this[s(979)][s(480)+"ype"],Object)?{force:!!this[s(979)]["payloadT"+s(473)][s(1238)],type:this._options[s(480)+"ype"][s(573)]?this._options[s(480)+"ype"][s(573)][s(893)](/\s/g,"").toLowerCase():""}:{force:!1,type:this[s(979)][s(480)+s(473)]?this[s(979)][s(480)+"ype"].replace(/\s/g,"")[s(974)+"ase"]():""},k=l[s(480)+"ype"]?l[s(480)+s(473)].replace(/\s/g,"")[s(974)+"ase"]():"",w=y[s(1238)]?y[s(573)]:k||y[s(573)],O=h[s(1238)]?h[s(1442)]:g||h[s(1442)],H=[s(580)+s(888)+"et=utf-8",e[s(1735)],e[s(412)],e[s(1465)]],F=[e[s(1797)],s(1081)];this._options[s(926)+"ansformTextPayload"]&&H.includes(w)&&(!O||F[s(1645)](O))?l["textPayl"+s(869)]=e.HFIom(Nl,l[s(1627)],0,l[s(1627)].byteLength):l[s(637)+s(869)]=""}else l[s(637)+"oad"]=""}catch(h){l["textPayl"+s(869)]="",console[s(548)](h)}c[s(1813)]=l,e[s(1835)](r)}function Ng(c,r,s){let l=t,h={lhqwD:function(g,y){return e.pNsGs(g,y)},wOQYs:function(g,y){return g>y},vVQCc:function(g,y){return e[B(1119)](g,y)},cwBmH:function(g,y){return e.eDOft(g,y)},GyxFs:function(g,y){return e.CcKGP(g,y)},oAdXj:function(g,y){return e[B(435)](g,y)}};if(e[l(1771)](l(1171),e.xiKAG))_0x4c86e7=e[l(1364)](_0x3559ec,_0x27859c),e.uUFYK(_0x2e9e0b,32)&&(_0x2c0658|=e[l(1172)](127,_0x5552b0)<<_0x2703e8),_0x2b610b+=7;else{let g=e.PsykK(s,8192),y=e.BkHJe(g,1),k=null,w=g;return function(O){let H=l;if(h[H(1374)](O,1)||h[H(1066)](O,y))return c(O);h[H(1066)](h[H(1057)](w,O),g)&&(k=h.cwBmH(c,g),w=0);let F=r[H(444)](k,w,w+=O);return h[H(1283)](7,w)&&(w=h[H(719)](7,w)+1),F}}}let Mg=4294967295;function Bg(c,r,s){let l=t;if(e[l(961)](e[l(1520)],l(1786)))return e[l(1628)](RangeError,e[l(851)](e[l(851)](e.DJAhk(e[l(622)](e[l(1765)],c)+e.eOZqX,r||1),e[l(1222)]),s));this[l(1397)](_0xf8acb3,_0x255f63)}function Fg(c,r,s){let l=t;if(e[l(1836)](s,Mg))throw new Error(e[l(453)]);let h=3;for(;e[l(1267)](h,0);){let g=255&s;e[l(1184)](Ba,g,c,r+h),s>>>=8,h--}return e[l(1709)](r,4)}function zg(c,r){let s=t,l=0,h=r,g=r+4;for(;h<g;){let{value:y,offset:k}=e[s(1630)](Ma,c,h);h=k,l=e.BndxZ(e[s(1551)](l,8),0),l+=y}return{value:l,offset:g}}function Ug(c,r,s){let l=t,h=e.tRPVW.split("|"),g=0;for(;;){switch(h[g++]){case"0":return e.lJUVe(Oa(c,r,s),s);case"1":if(!c)return s;continue;case"2":if(r[l(1114)])return e.fLQRr(r[l(1114)](c,s),s);continue;case"3":if(r[l(965)+"e"])return r.utf8Write(c,s)+s;continue;case"4":if(e[l(1322)](c[l(1407)],40))return e.hyYdv(Oa(c,r,s),s);continue}break}}function Hg(c,r){let s=t;if(e[s(1841)](e[s(1815)],e.gFNPW))return _0x487607[s(1698)](_0x1cdc7f)||(_0x1f1e4a=_0x364ec4[s(1223)+"er"](_0x4bd9cf)),this[s(690)]!==_0x176ea6[s(690)]&&e[s(1243)](this[s(1256)],31)===1&&e.CtaBY(e[s(1013)](_0x3c77f2.high,31),1)?!1:this[s(1256)]===_0x241357[s(1256)]&&this[s(1668)]===_0x30afc1[s(1668)];{let l=new xe(e[s(789)](e[s(456)](e[s(1299)](c[e.bQcAU(r,4)]<<24,e[s(807)](c[r+5],16)),e[s(575)](c[r+6],8)),c[e.eltMo(r,7)]),e[s(1307)](e[s(1666)](c[r+0],24)|e[s(890)](c[e[s(537)](r,1)],16)|e[s(976)](c[e[s(1214)](r,2)],8),c[r+3]),!0);return r+=8,{value:l,offset:e.gJuNk(r,8)}}}function Gg(c,r,s){let l=t;if(e[l(671)](e[l(1615)],e[l(1615)]))e[l(980)](_0x15bc00,e[l(462)]),this[l(1397)](e[l(484)],_0x36a9b7),this[l(1397)](e[l(649)],_0x1e8b1b);else{let h=c.low,g=c[l(1256)];return r[s]=e[l(1093)](g,24),r[e[l(511)](s,1)]=e.wGFXx(e.dsExu(g,16),255),r[e.DJAhk(s,2)]=e.rTVJl(g>>>8,255),r[e.ywFIM(s,3)]=255&g,r[e[l(802)](s,4)]=h>>>24,r[s+5]=h>>>16&255,r[e[l(558)](s,6)]=e.wfEzj(h>>>8,255),r[e.emrgh(s,7)]=e[l(1292)](255,h),s+=8,s}}function Ma(c,r){let s=t,l={lWjlp:function(h,g){return e[B(424)](h,g)},DLZsm:function(h,g){return e[B(675)](h,g)},Qfroq:function(h,g){return h|g},uqMjb:function(h,g){return e[B(1339)](h,g)},iNfOZ:function(h,g){return e[B(648)](h,g)},TpmkS:function(h,g){return e[B(1040)](h,g)},DJOXW:function(h,g){return e[B(1187)](h,g)},AusNF:function(h,g){return e[B(1372)](h,g)},MXYwx:function(h,g){return e[B(534)](h,g)},iXbLy:function(h,g){return e[B(1153)](h,g)},LCZnb:function(h,g){return e[B(927)](h,g)}};if(e[s(1681)](s(1083),s(1842))){let h=vArNIx[s(628)](vArNIx.DLZsm(vArNIx[s(695)](vArNIx[s(962)](vArNIx[s(1055)](7,_0x1fdd1f),18),(63&_0x580804[_0x47ae56++])<<12)|vArNIx.uqMjb(vArNIx[s(718)](63,_0x4243ab[_0x212bb6++]),6),vArNIx[s(838)](63,_0x561349[_0x4b68e0++])),65536);_0x252d91+=_0x375c14[s(940)+s(1738)](vArNIx[s(452)](55296,vArNIx[s(623)](h,10))),_0x5135a2+=_0x3c8b09[s(940)+"Code"](vArNIx[s(1774)](56320,vArNIx[s(918)](1023,h)))}else return c[s(1486)+"8"]?{value:c[s(1486)+"8"](r),offset:e[s(928)](r,1)}:{value:e[s(1604)](255,c[r]),offset:e.pRLAj(r,1)}}function Ba(c,r,s){let l=t;if(e[l(1549)]!==l(1592)){let h=_0x52040f[l(1484)];h!==void 0&&(e[l(999)](_0x3980bc,_0x601ba9,10),e.vQEMW(_0x3aaf02,_0x155e72,h));let g=_0x18f36d[l(715)];e[l(1162)](void 0,g)&&(e[l(457)](_0x410bf9,_0x179e07,18),e[l(1268)](_0x9ddace,_0x1002d9,g))}else return r[l(1103)+"t8"]?r[l(1103)+"t8"](c,s):r[s]=255&c,e[l(697)](s,1)}let qg=function(c){return new Uint8Array(c)},jg=e[t(1101)](e[t(1363)],typeof Buffer)?Buffer["allocUns"+t(1061)]:e[t(1617)](Ng,qg,Uint8Array[t(875)+"e"].subarray);(()=>{let c=t,r={cGDuz:function(l,h){return e[B(1153)](l,h)},Igvpv:function(l,h){return e[B(1270)](l,h)},jTPSi:function(l,h){return l&h},ZhhBy:function(l,h){return l<h},UesVI:function(l,h){return e[B(905)](l,h)},MlWGV:function(l,h){return l<<h},PbLbz:function(l,h){return l&h},lgSfC:function(l,h){return e[B(727)](l,h)},OeKet:function(l,h){return e.xmNwi(l,h)},zcciW:function(l,h){return e[B(1322)](l,h)},HVBum:function(l,h){return e[B(890)](l,h)},sdZgR:function(l,h){return e[B(1396)](l,h)},bpXGX:function(l,h){return l>>>h},HPIgr:function(l,h){return e[B(1096)](l,h)},NiYXD:function(l,h){return e[B(1307)](l,h)},GbmWz:function(l,h){return e[B(1401)](l,h)},mzpUB:c(1658),ZBYQr:function(l,h,g,y){return e.wopcm(l,h,g,y)}},s=4294967295;return function(l,h,g=!0){let y=c,k={cdvBY:function(w,O){return r.cGDuz(w,O)}};if(s=r[y(1548)](r.jTPSi(127,l[h]),0),r[y(1659)](l[h++],128))return{value:g?s:0|s,offset:h};if(s=r[y(1208)](s|r.MlWGV(r.PbLbz(127,l[h]),7),0),r.ZhhBy(l[h++],128))return{value:g?s:r.lgSfC(0,s),offset:h};if(s=r.OeKet(r.lgSfC(s,r[y(1381)](127&l[h],14)),0),r[y(747)](l[h++],128))return{value:g?s:0|s,offset:h};if(s=r[y(1276)](r[y(530)](s,r[y(1346)](r[y(1614)](127,l[h]),21)),0),r.sdZgR(l[h++],128))return{value:g?s:r[y(530)](0,s),offset:h};if(s=r.bpXGX(r[y(826)](s,r[y(1346)](15&l[h],28)),0),l[h++]<128)return{value:g?s:r.NiYXD(0,s),offset:h};if(r[y(946)](h+=5,l[y(1407)])){if(r[y(885)]==="rsuYp")throw h=l.length,r.ZBYQr(Bg,h,10,l[y(1407)]);return tJTEsJ.cdvBY(1e4*_0x434d2f.now(),_0xbeb0df[y(1779)](1e4*_0x1f52b0[y(956)]()))}return{value:g?s:0|s,offset:h}}})();let Wg=16,Fa=32;function Kg(c){let r=t,s=0,l={};for(let h=0;e[r(1585)](h,c[r(1407)]);h++)l[c[h][r(464)+r(830)]]=Ll(c[h]["cursor_n"+r(830)]),s+=14+l[c[h][r(464)+r(830)]];return[s,l]}function zl(c,r,s){let l=t,[h,g]=Kg(c),y=e[l(1855)](jg,h),k=0;return c[l(920)](w=>{let O=l;console.log(e[O(1227)],w,w[O(935)]),k=e[O(1205)](Ba,0,y,k),console.log("header",k),k=e[O(1822)](Fg,y,k,w[O(935)]||0),console[O(548)](e[O(1599)],k),k=e[O(878)](Ba,g[w[O(464)+O(830)]],y,k),console[O(548)](O(1403)+O(1588),k),k=Ug(w[O(464)+O(830)],y,k),console[O(548)](O(1588),k),k=e[O(1157)](Gg,xe[O(1223)+"er"](w[O(514)]||r),y,k),console.log(e[O(1139)],k)}),{frameType:Fa,headers:[{key:"cursor_f"+l(1687),value:s}],payload:y}}function $g(c){let r=t;if(e[r(542)](r(879),e[r(408)])){this[r(1467)+"WebSocket"]();let s=e[r(1723)](_0x1f3fac,e[r(593)],{message:e.DPxmm});this["onStopIm"+r(541)+r(1130)+"ct"]&&this[r(1482)+r(541)+r(1130)+"ct"](s)}else{let s=0,l=[];for(;e[r(472)](s,c[r(1366)+"th"]);){let{offset:h}=e[r(1181)](Ma,c,s);s=h;let g={cursor_name:"",cursor:0,service:0},{value:y,offset:k}=zg(c,s);g[r(935)]=y,s=k;let{value:w,offset:O}=Ma(c,s);s=O,g[r(464)+r(830)]=Nl(c,s,e[r(589)](s,w)),s+=w;let{value:H,offset:F}=e[r(1250)](Hg,c,s);g[r(514)]=H[r(1656)](),s=F,l[r(489)](g)}return l}}function Vg(){let c=t;return{frameType:Fa,headers:[{key:e.nQGgB,value:e[c(1014)]}],payload:void 0}}class Zg{constructor(r,s,l){let h=t;this["_cursorN"+h(959)]=r,this[h(899)+"ileName"]=s,this["_message"+h(1147)]=l,this[h(1531)]=e[h(1268)](Bl,this[h(1386)+h(959)],h(464)+h(830))}async openDB(){let r=t;await this[r(1531)][r(709)]()}async[t(1333)+"rs"](){let r=t;if(!this[r(1531)][r(603)])return;let s=this[r(1478)+"Strategy"],l=await this[r(1531)][r(446)]();switch(console[r(548)]("allCurso"+r(1557),l),s){case e.pKcSO:return l&&l[r(1407)]?e[r(1661)](zl,l,0,this["_cursorF"+r(861)]):void 0;case"INSTANT":return;case e[r(1463)]:return l&&l[r(1407)]?e[r(1695)](zl,l,0,this[r(899)+"ileName"]):e.TABTV(Vg)}}async[t(598)](r,s,l){let h=t;return console[h(548)](e.dQvBu,r,s,l),this[h(1531)][h(598)]({cursor_name:r,cursor:s,service:l})}async[t(667)+"rs"](r){let s=t,l=e[s(1220)]($g,r);for(let h of l)console[s(548)](e.CrBNH,l),await this._qosDB[s(598)](h)}async[t(493)](r){let s=t;return(await this._qosDB[s(493)](r))?.[s(514)]}async[t(1501)](){let r=t;await this._qosDB[r(1501)]()}[t(1416)+t(1451)+t(1748)](r){let s=t;e[s(449)](e[s(634)],e.CdIya)?(this._isInit=!0,this[s(892)]()):this[s(899)+s(861)]=r}get[t(603)](){return this._qosDB.isReady}}let Jg=e.ijupe;async function Ul(c){let r=t;if(e[r(413)](e[r(1646)],e[r(1500)]))this[r(934)+r(1247)+r(502)]=_0x4dae93,_0x252fa1?this[r(887)+r(1345)]():this["_handleO"+r(708)]();else{if(!this[r(979)].enableQoS)return null;let{aID:s,fpID:l,messageStrategy:h}=this[r(979)],g=e[r(1120)](c,Jg);try{return this[r(1719)+r(407)]?c&&this[r(1719)+"anager"][r(1416)+r(1451)+r(1748)](c):this[r(1719)+"anager"]=new Zg(l+"_"+s+"_"+g,g,h),this[r(1719)+"anager"][r(603)]||await this[r(1719)+r(407)][r(709)](),this["_cursorM"+r(407)]}catch{return null}}}async function Yg(c,r){let s=t,l={fszkh:e[s(984)],cLmmj:e[s(649)],ZCEjo:function(K,ce){return e[s(943)](K,ce)},kMTfJ:s(948)+s(557)+"s",snxfx:function(K,ce,be){return K(ce,be)}},h=e[s(1184)](un,c[s(1813)][s(967)],s(655),"-1"),g=e.QCcRV(un,c[s(1813)].headers,e[s(746)],"1"),y=ur(c[s(1813)][s(967)],e[s(996)]),k=e[s(1503)](Number,ur(c.message[s(967)],e.qFRzS))||0,w=Na[s(444)](this,c),O=e[s(1665)](un,c[s(1813)][s(967)],e[s(650)],"2"),H=e.ZjuIe(ur,c[s(1813)][s(967)],s(953)+s(460)+"e"),F=e.UoHBI(Number,e[s(1886)](ur,c.message[s(967)],s(953)+s(1860)+"ue"));if(w[s(1412)])return e[s(1516)](r);let W=w[s(1492)+s(1509)]?await Fl[s(444)](this):null;if(e[s(1850)](c.message[s(935)],0)&&g&&!h||e[s(1217)](c[s(1813)][s(935)],0)){if(y&&w[s(1492)+s(1509)]&&W){if(e[s(1331)]===e[s(1331)])return!!!await W[s(493)](y)&&(this[s(1255)+"hMessage"+s(1367)](c),await W[s(598)](y,e[s(1108)](Date[s(427)](),k))),e[s(479)](r);{let K={USdqy:function(ge,Ge){return l[s(600)](ge,Ge)},UKGfh:l[s(1446)],Zrfrc:s(948)+"e_timeout"};this._clearPingTimer(),this["_pingPon"+s(1801)+"Id"]=l.snxfx(_0x435589,this[s(1264)][s(1072)](this),this[s(979)][s(1418)+s(419)]);let ce=()=>{let ge=s;K[ge(738)](_0xa66bb3,ge(443)),this[ge(1397)](K[ge(1111)],ce),this[ge(1397)](K.Zrfrc,be)},be=()=>{let ge=s;_0x217c37(l.fszkh),this.off(ge(948)+ge(557)+"s",ce),this.off(l[ge(1640)],be)};this.on(l.kMTfJ,ce),this.on(l[s(1640)],be),this[s(1264)]()}}if(O){let K=await Ul[s(444)](this);if(!K)return this[s(1255)+s(1799)+s(1367)](c),e[s(1682)](r);let ce=await K.get(H)??-1;if(e[s(1001)](ce,F))this["_dispatc"+s(1799)+"Event"](c),K[s(598)](H,F,c[s(1813)][s(935)]);else throw new Error("recevied"+s(676)+s(1607)+F+(s(1577)+s(958)+"al cursor ")+ce);return r()}return this[s(1255)+s(1799)+s(1367)](c),e[s(1703)](r)}}async function Xg(c,r){let s=t,l=Na.call(this,c);if(!l[s(1492)+s(1509)])return e[s(1303)](r);let h=await Fl[s(444)](this);if(l[s(481)+s(922)+s(1527)]&&l[s(1790)+"s"].length)for(let g of l[s(1790)+"s"])await h[s(1425)](g);e[s(1278)](r)}async function Qg(c,r){let s=t,l=e[s(1136)](c.message.frameType,Wg),h=e[s(436)](c.message.frameType,Fa);if(!l&&!h)return e.TABTV(r);let g=ur(c[s(1813)][s(967)],e[s(1003)]);if(!g)return e[s(1776)](r);let y=await Ul[s(444)](this,g);if(!y)return e[s(1870)](r);if(l){let k=await y[s(1333)+"rs"](),w={frameType:k?.[s(616)+"e"],SeqID:xe.fromNumber(this[s(1252)]++),LogID:xe.fromNumber(this[s(979)][s(1686)+s(517)]()),service:9e3,method:5,headers:k?.[s(967)],payload:k?.[s(1627)]},O=e.ErWap(v,w);this[s(1594)]&&this[s(1594)][s(743)+"te"]&&this[s(1594)].send(O)}if(h){let k=c[s(1813)][s(1627)];k&&y.setCursors(k)}}let em=async function(c,r){let s=t;this._isInit=!1,e[s(1253)](clearTimeout,this["_connect"+s(1235)+s(1706)]),e.CzfAX(r)},tm=async function(c,r){let s=t,l={yNbOM:e[s(1570)]};if(!this[s(1594)]||e[s(671)](this[s(1594)][s(743)+"te"],this.OPEN))return r();let{pingInterval:h}=this._options;this._endpointManager?.["resetEnd"+s(653)+s(1560)]();for(let y=0;y<this["_message"+s(475)][s(1407)];y++)if(e[s(643)](s(1080),e[s(672)])){let k=this["_message"+s(475)][y];if(e[s(1335)](this._ws[s(743)+"te"],this[s(1122)])&&e[s(1477)](null,k))this[s(1594)]&&this[s(1594)].send(k),this[s(1478)+"Queue"][y]=null;else break}else!_0x45d8ec[s(1233)+"d"]&&(this[s(1576)+"er"]&&_0x17fb43[s(1550)+s(1436)+s(871)](l[s(1678)],this[s(491)+s(1155)]),this[s(1576)+"er"]&&_0x29bfcd["removeEv"+s(1436)+"ner"]("pageshow",this[s(491)+s(786)]),this[s(438)]()),this[s(1576)+"er"]&&_0x37d957[s(1550)+s(1436)+s(871)](s(1413),this[s(887)+s(1345)]),this._isBrowser&&_0x1e6d39[s(1550)+s(1436)+s(871)](s(659),this[s(887)+s(708)]);this["_message"+s(475)]=this[s(1478)+"Queue"][s(1305)](y=>!!y),this["_pingPon"+s(1801)+"Id"]=e[s(1244)](setTimeout,()=>this[s(1264)](),h),this[s(1255)+"hOpenEvent"](c),this._isBrowser&&this[s(1594)]&&(this[s(1594)].binaryType=this["_binaryT"+s(473)]);let g=this[s(1655)+"tManager"]?.[s(791)+s(1498)+"nt"]();this[s(810)](s(1610)+g+s(1074)),e[s(626)](r)},nm=async function(c,r){let s=t,l=this["_endpoin"+s(1225)]?.[s(791)+"ntEndpoint"]();this[s(810)](s(1610)+l),e[s(1835)](r)};class rm extends Da{constructor(r){let s=t,l={Trqwo:e[s(1064)],lpPQv:function(h,g){return e[s(495)](h,g)},TkYJf:e[s(808)],ckBkj:function(h,g,y){return h(g,y)},cuKZz:"error",CNnuv:function(h,g){return h===g},hlxOp:function(h,g){return e.TzZed(h,g)},QsYWm:e.DWErH,dYUtV:e[s(1302)],lBqjh:function(h,g){return e[s(1337)](h,g)},rIldn:e[s(461)],KUWLv:function(h,g){return e.rPzTJ(h,g)},JiLFq:function(h,g){return e.czlad(h,g)},reBXX:s(1798),ODUoD:s(691),dVzTZ:function(h,g,y){return e.WnOwU(h,g,y)},vvvwI:e.mLApU,qWIdv:e[s(1567)],mIShr:function(h,g){return h!==g},efwgO:function(h,g){return e[s(997)](h,g)},GXkqB:function(h,g,y){return e[s(397)](h,g,y)}};if(e[s(643)](e.DRmLz,e.fFWNW)){let h=_0x119e48.deleteDatabase(_0x47c97f);return _0x813b28&&h[s(1323)+s(1810)](hjOfrn[s(1868)],()=>_0x216b61()),_0x375144(h).then(()=>{})}else{super(),this[s(934)+s(1247)+"line"]=!0,this[s(1576)+"er"]=lr,this[s(1359)]=_g,this[s(1636)+"T"]=Ln,this._isMiniWX=ci,this[s(585)+"r"]=di,this[s(1478)+"Queue"]=[],this[s(1655)+s(1225)]=null,this[s(1178)+s(686)]=!1,this[s(1118)+s(473)]=e[s(1385)],this["_connect"+s(836)]=!1,this[s(892)+s(1235)+s(1706)]=null,this[s(716)+s(647)+"tId"]=null,this[s(944)+"gTimeoutId"]=null,this[s(1252)]=0,this[s(522)]=!1,this[s(1321)]="",this[s(1011)+s(950)]=null,this[s(1719)+"anager"]=null,this[s(1638)+s(1770)]=null,this[s(740)+"ls"]=e.EJUeP,this.CLOSED=3,this.CONNECTING=0,this[s(1122)]=1,this.CLOSING=2,this[s(1342)]=k=>{let w=s;try{if(l[w(1866)](l.TkYJf,l.TkYJf))Ol(this,k,[em,tm,nm]);else return{bytes:_0x4d3692,offset:0,limit:_0x2fdc7b[w(1407)]}}catch(O){let H=l[w(829)](ht,l[w(1273)],{message:O[w(1813)],code:ln.OPEN_ERROR,error:O});this[w(1255)+w(1699)+w(741)](H)}},this[s(1796)+"ge"]=async k=>{let w=s,{pingInterval:O,pingFrequency:H}=this[w(979)];if((l.CNnuv("hi",k.data)&&l[w(521)](l[w(1226)],H)||l.dYUtV===H)&&(this[w(1846)+w(1547)](),this[w(1700)](w(948)+w(557)+"s",w(443)),this[w(944)+w(1801)+"Id"]=l[w(829)](setTimeout,this[w(1264)].bind(this),O)),!l[w(521)]("hi",k.data))try{Ol(this,k,[Lg,Dg,Xg,Qg,Yg,Og])}catch(F){let W=ht(l.cuKZz,{message:F.message,code:ln[w(968)+w(459)],error:F});this[w(1255)+w(1699)+"ent"](W)}},this[s(657)]=k=>{let w=s,O=this[w(1655)+w(1225)]?.[w(1654)+w(1201)+"es"](),H=this[w(1655)+w(1225)]?.[w(791)+w(1498)+"nt"]();if(O&&!k[w(1813)]){let F=w(1824)+H+(w(1791)+w(1856)+w(1133)+"ed");this[w(1255)+w(1699)+w(741)](e[w(512)](ht,e[w(1579)],{message:F,code:ln[w(1018)+"IES_ERROR"],error:k}));return}this[w(1594)]&&e.bENXa(this[w(1594)][w(743)+"te"],this[w(1122)])&&this[w(1453)+w(1572)](),this[w(1255)+w(1699)+w(741)](e[w(1660)](ht,e[w(1579)],{message:k[w(1813)],code:ln[w(1151)+w(801)],error:k}))},this[s(881)]=async k=>{let w=s,O={zscDK:function(F,W){return F+W},RHXxn:function(F,W){return F+W},AxExY:function(F,W){return l[B(1573)](F,W)},gRckc:function(F,W){return l[B(1573)](F,W)},OLHau:l[w(931)],yLcay:function(F,W){return l.KUWLv(F,W)},IfqDI:w(1804)};this._clearTimer(),this[w(1846)+w(1547)](),this[w(1737)+w(739)+"rs"](),this._ws=null,this[w(892)+w(836)]=!1;let H=this[w(1655)+"tManager"]?.[w(1654)+w(1201)+"es"]();if(!H&&this[w(987)+w(430)]()&&!this["_readyCl"+w(686)])if(l.JiLFq(l.reBXX,l[w(1882)])){let F=this[w(1655)+w(1225)]?.[w(791)+"ntEndpoint"](),W=this[w(979)][w(1624)+w(873)+w(669)](k[w(655)],k.reason);this[w(1255)+w(856)+"ent"](l.dVzTZ(bt,l[w(574)],{code:1006,reason:k[w(1653)]||w(1538)+w(859)+w(857)+w(487)+w(433)+w(1417)+F,willReconnect:W})),W&&this[w(892)]();return}else return _0xf86b4f(Ogkwxi[w(685)](Ogkwxi[w(1676)](Ogkwxi[w(1239)](Ogkwxi[w(1361)]("index ou"+w(1781)+w(550),_0x4f74b2),Ogkwxi[w(1415)]),Ogkwxi[w(937)](_0x28001c,1))+Ogkwxi[w(568)],_0x45e454));if(l[w(1266)](1e3,k[w(655)])&&this[w(1178)+w(686)]){this[w(1255)+w(856)+"ent"](l.dVzTZ(bt,l.vvvwI,{code:1e3,reason:l[w(1004)]})),this[w(1655)+"tManager"]?.["resetEnd"+w(653)+w(1560)](),this._pingLossCounter?.[w(463)+"nter"]();return}if(l[w(395)](1e3,k.code)&&H){let F=this[w(1655)+"tManager"]?.[w(791)+w(1498)+"nt"](),W=k[w(1653)];W||(W=await l.efwgO(Ag,this[w(1321)])),W=w(1538)+w(859)+"d, "+W+(w(448)+w(1546))+F+(", max re"+w(1825)+w(1368)),this[w(1255)+w(856)+w(741)](bt(l.vvvwI,{code:k.code,reason:W}));let K=w(1824)+F+(w(1791)+w(1856)+"es reached");this[w(1255)+w(1699)+"ent"](l.GXkqB(ht,l[w(1273)],{message:K,code:ln[w(1018)+w(401)+"R"]})),this[w(1655)+w(1225)]?.[w(458)+w(653)+w(1560)](),this[w(1638)+"sCounter"]?.[w(463)+w(1593)]();return}if(l[w(1266)](1e3,k[w(655)])&&!k[w(1653)]){let F=this["_endpoin"+w(1225)]?.[w(791)+w(1498)+"nt"]();this["_dispatc"+w(856)+w(741)](l[w(652)](bt,l[w(574)],{code:k.code,reason:w(1538)+w(859)+w(857)+"wn reaso"+w(433)+w(1417)+F})),this[w(1655)+w(1225)]?.["resetEnd"+w(653)+w(1560)](),this[w(1638)+w(1770)]?.resetCounter();return}this[w(1255)+w(856)+w(741)](k),this._endpointManager?.[w(458)+w(653)+w(1560)](),this[w(1638)+w(1770)]?.[w(463)+w(1593)]()},this[s(1818)]=null,this[s(425)]=null,this[s(1629)+"e"]=null,this[s(507)]=null,this["onStartR"+s(1459)]=null,this[s(1852)+s(1378)]=null,this[s(1482)+s(541)+s(1130)+"ct"]=null,this[s(887)+"nLine"]=this[s(887)+s(1345)][s(1072)](this),this[s(887)+s(708)]=this["_handleO"+s(708)][s(1072)](this),this["_handleP"+s(1155)]=this[s(491)+s(1155)].bind(this),this[s(491)+s(786)]=this[s(491)+s(786)][s(1072)](this),this[s(979)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1566)](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.oMMsi,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1463)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:g}=r,y=Array[s(1613)](h)?h:e[s(1465)]==typeof h?[h]:[];if(!y||e[s(1079)](0,y[s(1407)]))throw new Error(s(1652)+s(792)+s(1041));if(!e[s(1059)](Eg,g))throw new Error(e.syOCI);Object.assign(this[s(979)],r),this[s(1655)+s(1225)]=new Dl(y,this[s(979)][s(1370)+"es"]),this[s(1638)+s(1770)]=new Ig(this._options[s(1023)+s(1651)]),this[s(979)].automaticOpen&&(this[s(522)]=!0,this[s(892)]()),this._options["listenNe"+s(726)+s(1332)]&&(this[s(1636)+"T"]||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this[s(775)+s(470)+"Listener"]())}}["_handleO"+t(1345)](){let r=t;if(e[r(1162)](e[r(1789)],e[r(1789)])){if(this[r(1846)+r(1547)](),this[r(1318)+r(1795)](),this._removeWsListeners(),this["_wsInsta"+r(870)](1e3,_0x4be65f),this[r(892)+r(836)]=!1,_0x375f4e&&this[r(987)+r(430)]()&&!this[r(1178)+r(686)]){if(this[r(1655)+r(1225)]?.[r(1654)+r(1201)+"es"]()){let l=this[r(1655)+r(1225)]?.[r(791)+r(1498)+"nt"]();this["_dispatc"+r(856)+r(741)](e.bFlAN(_0x5d2bd9,e[r(1274)],{code:1006,reason:r(1824)+l+(" timeout"+r(1156)+r(1825)+r(1368)),wasClean:!0}))}else{let l=this[r(979)]["reconnec"+r(873)+r(669)](_0x41c93a,_0xf347a3);this[r(1255)+r(856)+r(741)](e.uKofr(_0x1d7115,r(438),{code:_0x497149,reason:_0x1969d7,wasClean:!0,willReconnect:l})),l&&this[r(892)]()}return}this[r(987)+r(430)]()||this[r(1178)+r(686)]?this[r(1255)+r(856)+"ent"](e[r(519)](_0x5990bb,r(438),{code:_0x141b38,reason:r(630)})):this[r(1255)+r(856)+r(741)](e[r(1049)](_0x3b4067,e[r(1274)],{code:1006,reason:e[r(1732)]})),this[r(1594)]=null,this["_endpoin"+r(1225)]?.[r(458)+"pointCon"+r(1560)](),this[r(1638)+r(1770)]?.[r(463)+r(1593)]()}else{if(this[r(979)][r(1125)+r(1473)+r(1558)]||this[r(1178)+r(686)])return;this[r(788)+r(1459)]()}}[t(887)+t(708)](){let r=t;this[r(1467)+r(1532)+"t"]();let s=e[r(1038)](Pa,e[r(593)],{message:e[r(420)]});this[r(1482)+r(541)+"yReconnect"]&&this[r(1482)+"mediatel"+r(1130)+"ct"](s)}["_initGlo"+t(470)+t(1810)](){let r=t;this[r(1576)+"er"]&&window[r(1323)+"Listener"](e[r(610)],this["_handleO"+r(1345)]),this[r(1576)+"er"]&&window[r(1323)+r(1810)](e[r(1352)],this["_handleO"+r(708)]),this[r(1576)+"er"]&&window[r(1323)+r(1810)](e[r(1570)],this[r(491)+r(1155)]),this[r(1576)+"er"]&&window[r(1323)+r(1810)](e.EnGZn,this._handlePageShow)}[t(704)+"balEvent"+t(1810)](){let r=t;if(e[r(1873)]!==r(949)){let s=_0x3d74b2.pop();return s?(s[r(1344)]=s[r(1840)]=0,s):{bytes:new _0x17e3a2(64),offset:0,limit:0}}else this[r(1576)+"er"]&&window[r(1550)+r(1436)+r(871)](e[r(610)],this[r(887)+r(1345)]),this[r(1576)+"er"]&&window[r(1550)+r(1436)+r(871)](r(659),this[r(887)+r(708)]),this._isBrowser&&window["removeEv"+r(1436)+r(871)](e[r(1570)],this[r(491)+r(1155)]),this._isBrowser&&window[r(1550)+r(1436)+r(871)](r(447),this[r(491)+r(786)])}[t(491)+t(1155)](r){let s=t;!r[s(1233)+"d"]&&(this._isBrowser&&window["removeEv"+s(1436)+s(871)](e[s(1570)],this[s(491)+s(1155)]),this[s(1576)+"er"]&&window[s(1550)+"entListe"+s(871)](e[s(1675)],this[s(491)+"ageShow"]),this[s(438)]()),this._isBrowser&&window["removeEv"+s(1436)+"ner"](s(1413),this[s(887)+s(1345)]),this[s(1576)+"er"]&&window[s(1550)+s(1436)+s(871)](s(659),this[s(887)+s(708)])}[t(491)+t(786)](r){let s=t;r[s(1233)+"d"]&&(this[s(987)+s(430)]()&&(!this[s(1594)]||e[s(1042)](this[s(1594)][s(743)+"te"],this.OPEN)||e[s(614)](this[s(1594)][s(743)+"te"],this.CONNECTING))&&this[s(887)+s(1345)](),this[s(1576)+"er"]&&window[s(1323)+s(1810)]("online",this[s(887)+s(1345)]),this[s(1576)+"er"]&&window[s(1323)+"Listener"](s(659),this[s(887)+s(708)]))}async[t(1483)+t(1778)](r){let s=t,{fpID:l,deviceID:h,bddID:g,ttwID:y,accessKey:k,aID:w,customParams:O={},enableAutoAck:H,enableQoS:F,QoSLevel:W,env:K}=this[s(979)],ce,be,ge;this._isBrowser||this[s(955)+"X"]||this[s(1636)+"T"]?(ce=location&&e[s(1422)](e[s(1289)],location[s(1612)])?e.UlwdF:s(846),be=r[s(893)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ge=/^wss(.*:\/\/)/.test(r)?r:""+ce+be):(ce=e.UlwdF,be=r[s(893)](/(^http)((?:[s]*:\/\/))/,""),ge=/(^ws)((?:[s]*:\/\/))/[s(737)](be)?be:""+ce+be);let Ge=g?e.zGPVt:y?s(1533):e[s(1552)],_s=g||y||h;if(e[s(1095)](!_s,!Ge))throw new Error(e[s(426)]);let im=e[s(1325)](s(1115),typeof O)?await e[s(1406)](O):O,sm=K?Sg(K[s(1399)],K.xTTEnv):{},za=Object[s(730)]({device_platform:s(1261),version_code:e[s(504)],access_key:k,fpid:l,aid:w,[Ge]:_s,xsack:H?1:0,xaack:H?1:0,xsqos:F?1:0,qos_level:F?W:void 0,qos_sdk_version:2,...sm},im),om=Object[s(991)](za)[s(1449)]((Ua,Ha)=>za[Ha]!==void 0?""+Ua+(Ua?"&":"?")+Ha+"="+za[Ha]:Ua,"");return ge+s(756)+om}async _connect(){let r=t;if(!(this["_connect"+r(836)]||this._readyClosed)){this[r(892)+r(836)]=!0;try{let s=this._endpointManager?.[r(1887)+r(1460)+"ointReac"+r(1315)+r(1296)](),{timeoutInterval:l}=this._options;if(s){let g=this[r(1655)+r(1225)]?.[r(791)+r(1498)+"nt"](),y=this[r(1655)+r(1225)]?.[r(1424)+r(1230)+r(1068)+"UpdateCo"+r(769)](),k=this[r(1655)+"tManager"]?.[r(791)+"ntEndpointTriesC"+r(1152)]();if(y){let w=r(1824)+g+(r(1691)+r(1156)+"tries re"+r(1176)+r(569)+"backup e"+r(661))+y+" to retry",O=e.xWQTf(ht,e[r(1579)],{message:w,code:ln[r(1018)+"IES_ERROR"]});this[r(810)](w),this[r(1255)+"hErrorEv"+r(741)](O),this[r(1321)]=await this._generateUrl(y),this[r(810)]("connect "+y+" "+k+r(988)),this[r(1737)+r(739)+"rs"]()}else{let w="connect "+g+(r(1691)+r(1156)+r(1825)+r(1368));this[r(810)](w),this[r(1255)+r(1699)+"ent"](e[r(1561)](ht,r(749),{message:w,code:ln["MAX_RETR"+r(401)+"R"]}));return}}else{let g=this[r(1655)+r(1225)]?.[r(791)+r(1498)+r(843)+r(698)](),y=this[r(1655)+"tManager"]?.["getCurre"+r(1498)+r(833)+r(1152)]();this[r(1321)]=await this[r(1483)+r(1778)](e.lWJEl(g,"")),this._debug(r(1824)+g+" "+y+r(988)),this[r(1737)+"sListeners"]()}if(this[r(522)])this[r(522)]=!1;else{let g=e[r(1504)](Pa,e[r(593)],{message:e[r(1756)]});this.onStartReconnect&&this["onStartR"+r(1459)](g)}let h=this[r(1655)+"tManager"]?.["getCurrentEndpoi"+r(833)+r(1152)]()||0;e.EwMTo(h,1)&&await this[r(1017)](h-1),this._debug(r(1538)+"ng url: "+this[r(1321)]+(r(1354)+"ls: ")+this[r(740)+"ls"]),this[r(1594)]=e[r(1088)](bg,{url:this[r(1321)],protocols:[this[r(740)+"ls"]],headers:this[r(979)][r(755)+r(1294)+"s"]["customHt"+r(782)]},this[r(979)].ws),(this[r(1576)+"er"]||this[r(585)+"r"])&&this[r(1594)]&&(this[r(1594)].binaryType=this[r(1118)+r(473)]),this["_addWsLi"+r(1831)](),this["_connect"+r(1235)+"utId"]=setTimeout(this[r(644)+"ut"][r(1072)](this),l)}catch(s){if(e[r(1534)](e[r(840)],e[r(840)]))return this[r(1044)+"s"][this[r(1077)+r(990)]];throw this[r(892)+r(836)]=!1,s}}}[t(1318)+t(1795)](){let r=t;if(e[r(693)](e[r(1874)],r(867)))e[r(943)](clearTimeout,this["_connect"+r(1235)+r(1706)]),this[r(892)+r(1235)+"utId"]=null;else return _0xc197bd[_0x3496c4]=_0x47f5c1,!0}[t(1846)+t(1547)](){let r=t;clearTimeout(this._pingPongTimeoutId),e[r(1820)](clearTimeout,this[r(716)+r(647)+r(596)]),this[r(944)+r(1801)+"Id"]=null,this[r(716)+r(647)+r(596)]=null}_debug(...r){let s=t;this._options.debug&&console.log[s(662)](console,[e[s(735)],...r])}["_getInte"+t(535)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:g}=this[s(979)],y=e[s(1792)](l,Math.pow(g,e[s(424)](r,1)));return e.XThjh(y,h)?h:y}[t(1264)](){let r=t;if(this._ws&&this[r(1594)][r(743)+"te"]===this[r(1075)+"NG"]){this[r(1846)+r(1547)](),this[r(944)+"gTimeoutId"]=e.BXfZS(setTimeout,this._ping[r(1072)](this),this[r(979)][r(1418)+r(419)]);return}if(!this[r(1594)]||this[r(1594)].readyState!==this.OPEN)return void this[r(788)+"econnect"]();this[r(1594)]&&this[r(1594)][r(1383)]("hi"),this[r(716)+r(647)+r(596)]=e[r(450)](setTimeout,this[r(788)+r(1459)+r(921)][r(1072)](this),this[r(979)]["pingTime"+r(1725)+r(1650)])}[t(788)+"econnect"+t(921)](){let r=t;this[r(1638)+"sCounter"]?.addCount(),this[r(1700)](e[r(649)],r(1692)),this[r(1638)+r(1770)]?.["checkRea"+r(1229)+"nt"]()?this[r(788)+r(1459)]():this[r(1264)]()}[t(987)+t(430)](){let r=t;return this[r(1636)+"T"]||this[r(955)+"X"]?this[r(934)+r(1247)+r(502)]:(this[r(1576)+"er"]||this[r(585)+"r"])&&this._options[r(1721)+r(726)+r(1332)]?navigator[r(785)]:!0}[t(788)+t(1459)](){let r=t;!this[r(987)+r(430)]()||this[r(1178)+r(686)]||(this[r(1655)+r(1225)]?.[r(458)+r(653)+"fig"](),this._pingLossCounter?.[r(463)+r(1593)](),this[r(1594)]?this[r(1453)+r(1572)](1001,e.tJUZA,!0):this._connect())}["_onPageN"+t(1319)+t(845)](){let r=t;this[r(1636)+"T"]?tt["onNetwor"+r(753)+r(1769)](({isConnected:s})=>{let l=r;this[l(934)+l(1247)+l(502)]=s,s?this[l(887)+l(1345)]():this[l(887)+l(708)]()}):this[r(955)+"X"]&&wx[r(809)+"kStatusC"+r(1769)](({isConnected:s})=>{let l=r;this[l(934)+l(1247)+l(502)]=s,s?this[l(887)+l(1345)]():this[l(887)+l(708)]()})}[t(1017)](r){let s=t,l={lhYWs:function(h,g,y){return e.ZjuIe(h,g,y)}};if(e.LIDwa(s(1773),e[s(1419)]))return new Promise(h=>{let g=s;setTimeout(h,this[g(1398)+g(535)+"e"](r))});_0x5ecdb7(_0x103fcc,8),vrviNF.lhYWs(_0x29d623,_0xf76027,_0xdc9584)}["_disconn"+t(1572)](r=1e3,s="",l=!1){let h=t;this[h(1594)]&&this[h(1467)+h(1532)+"t"](r,s,l)}_onTimeout(){let r=t,s=this[r(1655)+r(1225)]?.[r(791)+"ntEndpoint"]();this._debug(r(1824)+s+r(1691)),this[r(1453)+r(1572)](1001,e[r(757)],!0)}_sendAck(r){let s=t,l=e[s(997)](jt,r);this[s(1594)]&&e[s(1878)](this[s(1594)][s(743)+"te"],this[s(1122)])&&(this._ws&&this[s(1594)][s(1383)](l),this._debug(e.UzHlg,r))}["_removeW"+t(739)+"rs"](){let r=t,s=e[r(1127)].split("|"),l=0;for(;;){switch(s[l++]){case"0":this._ws[r(1550)+"entListe"+r(871)](e[r(1071)],this[r(1342)]);continue;case"1":this[r(1594)][r(1550)+"entListe"+r(871)](e[r(1274)],this[r(881)]);continue;case"2":this._ws["removeEv"+r(1436)+r(871)](e[r(721)],this[r(1796)+"ge"]);continue;case"3":if(!this[r(1594)])return;continue;case"4":this[r(1594)][r(1550)+r(1436)+r(871)](r(749),this[r(657)]);continue}break}}["_addWsLi"+t(1831)](){let r=t,s=e.rykxa.split("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[r(1594)])return;continue;case"1":this[r(1594)][r(1323)+"Listener"](e[r(1579)],this[r(657)]);continue;case"2":this[r(1594)][r(1323)+r(1810)](e.oLoki,this._onOpen);continue;case"3":this[r(1594)][r(1323)+r(1810)](e.JYpKb,this[r(1796)+"ge"]);continue;case"4":this[r(1594)]["addEvent"+r(1810)](r(438),this[r(881)]);continue}break}}[t(1536)+t(870)](r=1e3,s=""){let l=t;try{this[l(1594)]&&this[l(1594)].close(r,s)}catch{}}[t(1467)+t(1532)+"t"](r=1e3,s="",l=!1){let h=t;if(this[h(1846)+"ngTimer"](),this["_clearTi"+h(1795)](),this[h(1737)+h(739)+"rs"](),this[h(1536)+"nceClose"](1e3,s),this[h(892)+"Lock"]=!1,l&&this[h(987)+"orOnline"]()&&!this[h(1178)+h(686)]){if(this[h(1655)+"tManager"]?.["checkRea"+h(1201)+"es"]()){let y=this["_endpoin"+h(1225)]?.[h(791)+h(1498)+"nt"]();this["_dispatc"+h(856)+h(741)](e[h(403)](bt,h(438),{code:1006,reason:h(1824)+y+(h(1691)+h(1156)+h(1825)+h(1368)),wasClean:!0}))}else{let y=this[h(979)][h(1624)+h(873)+"ptor"](r,s);this["_dispatc"+h(856)+h(741)](e[h(528)](bt,e[h(1274)],{code:r,reason:s,wasClean:!0,willReconnect:y})),y&&this[h(892)]()}return}this["_navigat"+h(430)]()||this[h(1178)+"osed"]?this[h(1255)+h(856)+h(741)](e[h(989)](bt,e[h(1274)],{code:r,reason:e.kyDiC})):this[h(1255)+h(856)+h(741)](e[h(482)](bt,e[h(1274)],{code:1006,reason:e.PeObR})),this[h(1594)]=null,this[h(1655)+h(1225)]?.["resetEnd"+h(653)+"fig"](),this[h(1638)+"sCounter"]?.["resetCou"+h(1593)]()}[t(1255)+t(656)+"nt"](r){let s=t;this.emit(e[s(1071)],r),this.onopen&&this.onopen(r)}["_dispatc"+t(1799)+t(1367)](r){let s=t;this[s(1700)](s(1813),r),this[s(1629)+"e"]&&this[s(1629)+"e"](r)}[t(1255)+t(1309)+t(1288)](r){let s=t;this.emit(s(783),r),this.onReceiveAck&&this["onReceiv"+s(1378)](r)}["_dispatc"+t(1699)+t(741)](r){let s=t;this[s(1700)](s(749),r),this[s(425)]&&this.onerror(r)}["_dispatc"+t(856)+t(741)](r){let s=t;this[s(1700)](e[s(1274)],r),this[s(1818)]&&this[s(1818)](r)}get[t(763)+"pe"](){let r=t;if(e[r(1608)](e.gNBUF,e[r(1360)])){let s=this[r(1531)].getStorageSync(this[r(842)]),l=_0x3c8d41[r(477)](s||"{}");return l[_0x5dbd84]=void 0,this[r(1531)]["setStora"+r(1782)](this[r(842)],_0x32cf51[r(1499)+"y"](l))}else return this[r(1594)]?this[r(1594)][r(763)+"pe"]:this["_binaryT"+r(473)]}set[t(763)+"pe"](r){let s=t;this[s(1118)+s(473)]=r,this._ws&&(this._ws.binaryType=r)}get[t(1394)+"nt"](){let r=t;return this[r(1655)+r(1225)]?.[r(791)+"ntEndpointTriesC"+r(1152)]()||0}get[t(423)+t(490)](){let r=t,s=this[r(1478)+"Queue"][r(1449)]((l,h)=>(l+=h&&h[r(1366)+"th"]||0,l),0);return e[r(1684)](s,this._ws?this._ws[r(423)+"Amount"]:0)}get[t(909)+"ns"](){let r=t,s={CVOUd:r(1813),ZvYdm:function(l,h,g){return e[r(422)](l,h,g)}};if(e[r(1712)](e.kracM,e[r(1166)]))return this[r(1594)]?this[r(1594)][r(909)+"ns"]:"";this[r(1700)](fTCCHT.CVOUd,fTCCHT[r(1409)](_0x300313,fTCCHT[r(516)],{..._0x3b7244}))}get[t(1612)](){let r=t;return this[r(1594)]?this[r(1594)][r(1612)]:""}get[t(743)+"te"](){let r=t;return this._ws?this._ws[r(743)+"te"]:this._options[r(800)+r(1583)]?this[r(1075)+"NG"]:this.CLOSED}get[t(645)](){let r=t;return this[r(1594)]?this[r(1594)][r(645)]:this[r(1321)]}close(r=1e3,s){let l=t,h=(l(1762)+l(1142)).split("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(1467)+l(1532)+"t"](r,s);continue;case"1":if(e.nqrZx(this[l(1594)].readyState,this[l(1812)])||e[l(643)](this[l(1594)][l(743)+"te"],this[l(793)]))return void this._debug(e.OzVQB);continue;case"2":if(!this[l(1594)])return void this._debug(e.QVauF);continue;case"3":this[l(1846)+"ngTimer"]();continue;case"4":this["_dropGlo"+l(470)+l(1810)]();continue;case"5":this[l(1178)+l(686)]=!0;continue;case"6":this[l(1011)+l(950)]?.[l(1501)]();continue;case"7":this[l(1318)+"mer"]();continue}break}}async[t(1383)](r,s){let l=t,h={AJXUM:function(g,y){return e[B(524)](g,y)},olkwV:function(g,y){return g<y}};if(e[l(1740)](e.NdkfR,e[l(1067)]))_0x22a647=qlVDlI.AJXUM(31,_0x5ece81)<<6|qlVDlI.AJXUM(63,_0x4b6318),qlVDlI[l(1510)](_0x533279,128)?_0x1375f9+=_0x1e8087:(_0x4f7988+=_0x2b7514(_0x119b63),_0x1f6200++);else{if(e[l(1281)](null,r))throw new Error(e[l(936)]);e[l(884)]("number",typeof r)&&(r=JSON[l(1499)+"y"](r)),e.AvusI(e[l(1465)],typeof r)&&!(r instanceof ArrayBuffer)&&!(r[l(834)]&&r[l(834)]instanceof ArrayBuffer)&&(r=JSON[l(1499)+"y"](r));let g=await e[l(1508)](Ml,r),y=e.GZyFw(vg,r),{method:k=0,service:w=this[l(979)][l(935)],logID:O=this[l(979)][l(1686)+"erator"](),headers:H=this[l(979)][l(967)],payloadEncoding:F=this._options[l(700)+l(767)],payloadType:W=this[l(979)]["payloadT"+l(473)],logIDNew:K=this[l(979)][l(1440)+l(469)][l(615)+l(880)+"teLogIDNew"]?e.OksLq(i,this[l(979)][l(1440)+l(469)][l(1626)]):""}=e[l(617)](s,{});if(!w)throw new Error(l(1652)+l(1752)+l(651)+"ervice");let ce={SeqID:xe.fromNumber(this[l(1252)]++),LogID:xe[l(1223)+"er"](O),service:w,method:k,headers:H,payloadEncoding:F instanceof Object?F.encoding?F[l(1442)]:"":F,payloadType:e[l(1619)](W,Object)?W.type?W.type:y:W||y,payload:g,LogIDNew:K},be=e.UoHBI(jt,ce);return this[l(1594)]&&e[l(1219)](this[l(1594)].readyState,this[l(1122)])?(this[l(1594)]&&this[l(1594)][l(1383)](be),this[l(810)](l(554),ce)):e[l(1046)](this["_message"+l(475)].length,this[l(979)][l(1443)+"geQueueLength"])?(this[l(1478)+l(475)][l(489)](be),this[l(810)](e[l(1625)],ce)):(this[l(1478)+l(475)].shift(),this["_message"+l(475)].push(be)),{seqID:this._seqId,logID:O,logIDNew:K}}}async[t(1624)+"t"](r){let s=t,l={XRZmK:function(y,k){return e[B(992)](y,k)},FkzeA:e[s(610)],awviC:e[s(1352)]},{url:h}=r||{},g=Array[s(1613)](h)?h:e[s(1466)](e[s(1465)],typeof h)?[h]:[];r&&Object[s(730)](this[s(979)],r),g&&g.length?this._endpointManager=new Dl(g,this._options.maxRetries):this["_endpoin"+s(1225)]?.["resetEnd"+s(653)+s(1560)](),this[s(1638)+"sCounter"]?.[s(463)+s(1593)](this._options["pingLoss"+s(1651)]),this[s(1178)+s(686)]=!1,this._ws&&this._ws[s(743)+"te"]!==this[s(1812)]?this[s(1453)+"ect"](1e3,e[s(745)],!0):e[s(1534)](e.uPMRZ,e[s(822)])?_0x431455[s(1233)+"d"]&&(this["_navigat"+s(430)]()&&(!this[s(1594)]||FjEtGj[s(1231)](this[s(1594)][s(743)+"te"],this[s(1122)])||this._ws[s(743)+"te"]!==this[s(1075)+"NG"])&&this["_handleO"+s(1345)](),this[s(1576)+"er"]&&_0x3295f[s(1323)+s(1810)](FjEtGj.FkzeA,this[s(887)+s(1345)]),this[s(1576)+"er"]&&_0x4d998f[s(1323)+"Listener"](FjEtGj.awviC,this[s(887)+"ffLine"])):(this[s(522)]=!0,this[s(892)]())}async[t(570)](){let r=t;if(!this[r(892)+r(836)])if(e[r(1350)]===e.grhwC){let s=e.XDrzg[r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":_0x484e24=e[r(924)](_0x30bd9e,_0x3b2f15[_0x58835b["cursor_n"+r(830)]],_0x438ba6,_0x3cf784);continue;case"1":_0x5e5f31[r(548)](e[r(925)],_0xe89570);continue;case"2":_0x42929f=e[r(882)](_0x59aa67,_0x22432d,_0x1c0337,_0x16642a[r(935)]||0);continue;case"3":_0x4f5155=_0xfb48fd(_0x3face8[r(464)+r(830)],_0x2b4f62,_0x308e61);continue;case"4":_0x19bdde[r(548)](e[r(658)],_0x5412c4);continue;case"5":_0x43050c[r(548)](e.HVsiL,_0xae951);continue;case"6":_0x1cc001[r(548)](e.vtDkr,_0x1d622d);continue;case"7":_0x557cd4=_0x3bd4a5(0,_0x1ddbc9,_0x323c72);continue;case"8":_0xb9d87c[r(548)](e[r(994)],_0x278dfe);continue;case"9":_0x11be48[r(548)](e.jsDFi,_0x4e784b,_0x3dc3a9[r(935)]);continue;case"10":_0x40bcb8=e[r(766)](_0x4e3ddb,_0x2099d9[r(1223)+"er"](_0x4ae779[r(514)]||_0x36c335),_0x42e34f,_0x2706b4);continue}break}}else{let s=(r(1349)+"1")[r(1432)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1178)+r(686)]=!1;continue;case"1":this[r(892)]();continue;case"2":this["_endpoin"+r(1225)]?.[r(458)+r(653)+r(1560)]();continue;case"3":this[r(522)]=!0;continue;case"4":this[r(1638)+r(1770)]?.resetCounter();continue}break}}}[t(1323)+t(1810)](r,s){this.on(r,s)}[t(847)+"Event"](r){let{type:s}=r;this.emit(s,r)}["removeEv"+t(1436)+t(871)](r,s){let l=t;e[l(599)](e[l(1730)],e[l(1657)])?e[l(1301)](_0x3063ac,this,_0x197c2b,[_0x1935c5,_0x5191e3,_0x3173a5,_0xa363d5,_0x7f815f,_0x556fdb]):this.off(r,s)}[t(592)](){let r=t,s={bdcRU:function(l,h){return e.OksLq(l,h)},eviSJ:function(l,h,g,y){return e[B(636)](l,h,g,y)},JLGtf:function(l,h){return e[B(1712)](l,h)},smhip:e.TJCDe,OmZJu:e[r(1062)],vLBui:r(1692),EMsMN:e[r(649)]};return new Promise((l,h)=>{let g=r,y={gzmRm:function(O,H){return O(H)},LvHEP:e[g(462)],APmmn:g(948)+g(557)+"s",dDcON:g(948)+"e_timeout"};this[g(1846)+g(1547)](),this[g(944)+g(1801)+"Id"]=e[g(1643)](setTimeout,this[g(1264)].bind(this),this[g(979)]["pingInte"+g(419)]);let k=()=>{let O=g;y[O(1875)](l,y.LvHEP),this[O(1397)](y[O(421)],k),this[O(1397)](y[O(916)],w)},w=()=>{let O=g,H={TFcAJ:function(F,W){return s[B(684)](F,W)},XUyhW:function(F,W,K,ce){return s[B(1275)](F,W,K,ce)}};if(s[O(439)](s[O(1314)],s[O(1485)]))s[O(684)](h,s[O(410)]),this[O(1397)](O(948)+O(557)+"s",k),this[O(1397)](s.EMsMN,w);else{let F=new _0x5c9ba5(cGbeAe.TFcAJ(_0x3217c8,_0x50ad5a));return cGbeAe[O(761)](_0x15d061,_0x5d8aaa,F,0),F}};this.on(e[g(484)],k),this.on(e[g(649)],w),this._ping()})}}})(),Ce[L(1677)+L(724)]=Ne[L(1677)+L(724)],Ce[L(418)+L(1158)]=Ne[L(418)+"rorEvent"],Ce.ErrorCode=Ne[L(911)+"e"],Ce[L(1367)]=Ne.Event,Ce[L(1113)]=Ne[L(1113)],Ce["Frontier"+L(1683)+L(1763)]=Ne[L(1759)+L(1683)+L(1763)],Ce["MessageE"+L(1763)]=Ne[L(1683)+L(1763)],Ce[L(841)+"t"]=Ne[L(841)+"t"],Ce[L(428)+L(823)]=Ne[L(428)+L(823)],Ce[L(705)+"oseEvent"]=Ne[L(705)+"oseEvent"],Ce[L(1207)+L(1158)]=Ne["createEr"+L(1158)],Ce[L(1300)+L(998)+"nt"]=Ne["createMe"+L(998)+"nt"],Ce[L(494)+"enEvent"]=Ne[L(494)+L(814)],Ce[L(1069)+"connectE"+L(1763)]=Ne[L(1069)+L(1480)+L(1763)],Ce[L(1384)+L(398)]=Ne[L(1384)+L(398)],Ce[L(595)+"ame"]=Ne[L(595)+"ame"];for(ca in Ne)[L(1677)+L(724),L(418)+L(1158),L(911)+"e","Event",L(1113),L(1759)+L(1683)+"vent","MessageE"+L(1763),L(841)+"t",L(428)+L(823),L(705)+"oseEvent",L(1207)+L(1158),"createMessageEvent",L(494)+L(814),"createRe"+L(1480)+"vent",L(1384)+L(398),L(595)+"ame"].indexOf(ca)===-1&&(Ce[ca]=Ne[ca]);var ca;Object[L(1512)+L(933)](Ce,L(1718)+"le",{value:!0})});import{existsSync as Y1,openSync as X1}from"node:fs";import{mkdir as Q1}from"node:fs/promises";import{dirname as eI}from"node:path";import{fileURLToPath as tI}from"node:url";function rI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function ll(t=Z()){return Y1(t.libEntry)?t.libEntry:tI(new URL("../index.ts",import.meta.url))}async function Rp(t={}){let e=t.paths??Z(),n=t.entryOverride??ll(e),i=rI(e,process.env.COZE_BRIDGE_LOG_MODE);await Q1(eI(i),{recursive:!0});let o=X1(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=at(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[xs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return nI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var nI,xs,_a=it(()=>{"use strict";en();te();Pe();nI=G("spawn-daemon"),xs="COZE_BRIDGE_DAEMON"});import{spawn as eA}from"node:child_process";import{mkdir as tA,unlink as nA,writeFile as rA}from"node:fs/promises";import{dirname as iA,join as sA}from"node:path";function si(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function oA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${si(n)}</key>
21
- <string>${si(i)}</string>`).join(`
20
+ `+n)}function pr(t,e,n,i,s,a){if(t.listenerCount("wsClientError")){let d=new Error(s);Error.captureStackTrace(d,pr),t.emit("wsClientError",d,n,e)}else ws(n,i,s,a)}});var qp=le(Ce=>{"use strict";var M=j;(function(t,e){let n=j,i=t();for(;;)try{if(-parseInt(n(380))/1+parseInt(n(1219))/2+-parseInt(n(821))/3*(parseInt(n(1704))/4)+parseInt(n(679))/5+parseInt(n(425))/6*(-parseInt(n(667))/7)+-parseInt(n(781))/8*(-parseInt(n(872))/9)+parseInt(n(662))/10===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(wa,606580);function j(t,e){t=t-246;let n=wa(),i=n[t];if(j.dGUdDL===void 0){var s=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",m="";for(let b=0,y,v,I=0;v=f.charAt(I++);~v&&(y=b%4?y*64+v:v,b++%4)?p+=String.fromCharCode(255&y>>(-2*b&6)):0)v=x.indexOf(v);for(let b=0,y=p.length;b<y;b++)m+="%"+("00"+p.charCodeAt(b).toString(16)).slice(-2);return decodeURIComponent(m)};j.wmgtvm=s,j.GPfQhj={},j.dGUdDL=!0}let a=n[0],d=t+a,u=j.GPfQhj[d];return u?i=u:(i=j.wmgtvm(i),j.GPfQhj[d]=i),i}var tI=Object[M(1092)+M(1245)],nI=Object["getOwnPr"+M(334)+"mes"],Fp=(t,e)=>function(){return t&&(e=(0,t[nI(t)[0]])(t=0)),e},rI=(t,e)=>{for(var n in e)tI(t,n,{get:e[n],enumerable:!0})};function iI(){return Op||(Op=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function sI(){let t=M;return Lp||(Lp=[IDBCursor.prototype.advance,IDBCursor[t(1431)+"e"].continue,IDBCursor.prototype[t(1568)+"PrimaryKey"]])}function oI(t){let e=M,n={fCcOV:e(796),dSwEm:e(1148),BoGVA:function(s,a){return s(a)},MUfSE:function(s,a){return s(a)},PljEa:function(s){return s()},spnun:function(s,a){return s instanceof a}},i=new Promise((s,a)=>{let d=e,u={DOQpL:function(m,b){return m(b)},GtPKW:function(m){return n[j(1270)](m)}},f=()=>{let m=j;t[m(1086)+"entListe"+m(468)](n[m(701)],x),t[m(1086)+"entListener"](n[m(786)],p)},x=()=>{let m=j;n[m(691)](s,n.MUfSE(Jt,t[m(748)])),f()},p=()=>{let m=j;u.DOQpL(a,t.error),u[m(516)](f)};t[d(356)+"Listener"](n[d(701)],x),t[d(356)+d(1545)](n[d(786)],p)});return i[e(1657)](s=>{let a=e;n.spnun(s,IDBCursor)&&xl[a(926)](s,t)})[e(340)](()=>{}),_a.set(i,t),i}function aI(t){let e=M,n={IaJsO:e(1655),StAbz:e(1148),BiYpS:function(s,a){return s+a},wxVni:e(418)+e(971)+e(1362),yuKzA:e(506),ptyrV:function(s,a){return s||a},lMULW:e(1023),aCuvd:function(s,a){return s!==a},hqHpm:e(905),Meogb:"YfduE",BeTCE:function(s){return s()},zLdAz:e(1604)+"or",FENvU:"abort"};if(ya[e(1668)](t))return;let i=new Promise((s,a)=>{let d=e,u={yoSLp:n[d(487)],XxfsZ:n[d(300)],hOCHR:d(1625),tYGzY:function(m,b){return m(b)},HhWWF:function(m,b){return n.BiYpS(m,b)},hnVDT:n[d(1154)],rNXmT:n[d(1280)],kDzGn:function(m,b){return n[d(862)](m,b)},LPJua:n[d(1644)],KSbiS:function(m,b){return n[d(537)](m,b)},YmEoO:n[d(1173)],GDXkx:n[d(882)],wbwKo:function(m){return n[d(507)](m)},DTNCv:n[d(1373)]},f=()=>{let m=d;t[m(1086)+m(1350)+m(468)](u[m(1342)],x),t[m(1086)+m(1350)+m(468)](u[m(1486)],p),t[m(1086)+m(1350)+m(468)](u[m(652)],p)},x=()=>{let m=d;if(u[m(1217)](u[m(1786)],u[m(1019)]))u[m(557)](s),f();else return u.tYGzY(_0x3b0a71,u[m(1674)](u.hnVDT,_0x45d212)+u[m(741)]+u[m(1591)](_0x48c17c,1)+u[m(1588)]+_0xebc6f9)},p=()=>{let m=d;a(t.error||new DOMException(u[m(502)],m(1604)+"or")),u[m(557)](f)};t[d(356)+d(1545)](n[d(487)],x),t[d(356)+"Listener"](n[d(300)],p),t[d(356)+d(1545)](n[d(391)],p)});ya.set(t,i)}function cI(t){ba={DefqL:function(i,s){return i(s)}}[M(864)](t,ba)}function wa(){let t=["v2rKv2C","C29YDa","BKLmtMS","tfvHqKm","qKf0ELe","ywjVCNq","DgLLCKPtt04","B25tDg9Wsw0","rLnMtNG","D0Xcrei","suvtx0vsuK8","B2PZtxe","zhzlzM4","mdaWma","A2v5","DxnLCKLW","B29sqLu","vMvSDeK","Bg9N","C3jJ","zxzAEwq","D2zcCe0","ue1RtM0","u0Dhtg4","Be1vtfC","qM9zvgm","x3vYBa","whzty2e","z29PBMCGyxC","DgfAy3C","DvbeC2C","vxbKyxrLq28","wuDtzxy","vNzUDMe","DgvZDa","y29TCgXLDgu","AeLAzM8","DgHLBG","C3vTAeu","Dg9Y","q3vZDg9Trxi","DLrhB2O","Bg93","r0fiD20","D2v3Eei","zw5Jv20","rLHutLy","wKjYuw0","AgfZ","surPDfu","tuL5ugS","CgfNzxnOB3C","tg1zwKe","C0zNAM0","sgHxv0y","B3bLBKrc","yuH4BNG","B25pCgvU","vw5Oyw5KBgu","tgvRqxa","o2nOyxjZzxq","tvPqBw8","BMv3vMvYC2K","BvHvDKG","ve9lB3G","C3rLBMvYCW","thDztfK","te55BhK","DxbNCMfKzw4","A3LKy1K","B3jL","tLv5rvO","ueLbyMi","zv90Aw1LB3u","u3HZq3K","wKvksM0","ALjAC1O","twLZC2LUzYa","zufJAW","ChjVy2vZCW","yNL0zuXLBMC","ruLdwKi","BMnLq2XVC2u","Bfn3reG","otuYndiWtLvgvfv5","r3jxwu8","zw5HyMXLuw8","shjxCw8","seHStuO","DezUz1O","DND5wMu","yM9L","y29UBMvJDeu","shPivxy","AwXLx25HBwu","yMzXDeq","BhrPCgXLihq","B0fJr2u","zw5HyMXLqxu","CMzquKC","D1L2swm","DuXhqMS","AwrI","tw9KDwXL","ExbL","zujjzhC","AvjOruK","uuDTyNa","u2HHCMvKv28","mxWW","rhDzsKG","x2nSzwfYugK","vKTXvK0","y01VCwS","C3vhr0O","ywWGy3vYC28","AgPSveO","vvr0BK4","CuPXyKi","s0TrCvO","veTtu1m","rxzLBNq","zxjFDhrS","thDQuvO","ruTlBeO","yNP1uNe","r1zKzuG","Dxrjza","t1vcree","uxbuB0u","C0jVuMG","tNjXA3C","BMfTzq","ugTtEvK","DfHTCeS","AxnFywnR","x3bPBMDmB3m","reTwuee","DgfIyxnL","vgfN","D2LSBfjLy28","u3novuO","DeLUDgvYy2u","s0T0CwG","x21PBMLoyxy","Bu5wuNy","B25VCgvU","x2DLDeLUDgu","ALv4v0u","ywnRx2LK","vMLIuva","BhPMrhy","zgvSzxrLrge","qwT2A2C","wMDIvNq","tLjfDe8","CxP6ruO","CuLeshi","tNLUz3a","EKPwt2G","jMPZy2fSBgi","BxDmrMq","zxf1ywXZ","reLAzue","AMLxEeK","yxHIAKi","ww1fB08","wMvpvfO","yNbmALm","zM9JBue","BerfEhq","wMndyvm","DeDUBgy","uLDYshC","Dg9hzw5LCMe","wwXxsNC","tufyx1jfvfi","rLblvfm","CMvHzg9UBhK","CYbHBhjLywq","q2z3CvC","BMH0Aw4","zw1PDa","y29Kzq","uMfHse4","t1bftL9fuLi","D2nTEgO","CNnVCL92ywW","DNHdy0u","De5iCNC","y3PyuK0","s1Lyvha","A1bMyw8","Durxz0O","z2vY","B3bLBG","CgLUz0XVC3m","swHPu0m","zgv2AwnLx2K","B3PNsgG","u05Os2i","zw5JB2rPBMC","AxjLza","rfP5Efi","txnJD20","CgzQvfi","CgXLyxnLiha","Dgv4Dc9Qyxy","yxbWBhK","qKXvzuu","yMLOBgG","qKDmuKq","x3jLywr5q2W","BhnLzem","y2jRt2O","B25tDgfYDfi","u2vXsuq","EuzvyMm","Dvr6yLG","CMvHzhDYAxq","CMvZzxrdB3u","B2zMBgLUzq","qwTnu3m","C2vUDa","zNvUy3rPB24","Bg9NsurozxC","ww93BwG","reiGzMfPBgu","BIWGAg9ZDg4","D2fZq2XLyw4","rwLmrhG","DeLK","zhf1BKy","u3rbyNO","x1fVu01HBMe","x29Uq2XVC2u","DxzKweC","AKTKrMy","y3jLyxrLt2i","uNLls0W","mNWXFdb8nhW","uK53uNC","DhjHBNnHy3q","s252Bhi","tg9JAW","t3DVsMC","ywrK","x2LZv29YA2u","Eu9ADfG","vfDPt2W","Bwv0Ag9K","wgrJyM4","zuHpvKu","q3Piwxa","BxnN","Axnby2TdBgu","sg1juLG","uLzivwy","D0P5sMy","quzsrM0","yNvMzMvY","Cgf5Bg9Hzfq","CLvKy2W","CKHOrxC","C2v0q3vYC28","tNrXyKW","ChfTr3O","B3bLCNr5tMe","yNvMzMvYzwq","vw5ACLe","Ee9mD0G","DhDVCMTdAge","vNPtBMe","y2f0y2G","vK5IBwy","zMv4yvK","uNjNvwS","z2XHBg8","y2XVC2veqG","x2LUAxrqCM8","BKz5CfG","y29UBMvJDa","CLzHBhvLCW","x2XPC3rLBMu","y2TvAfy","CfnXwLq","BMv4DcGPigm","y29UDgv4Da","CMvXDwLYzwq","ywrKrxzLBNq","txzysgC","C2vYDMLJzs0","BezSDxnO","C2HPzNq","CgvYC2LZDgu","sgLRsNa","B25mAw5L","x2LZtwLUAvq","ExHxC0u","teHzt3O","r2POzMS","vK9NvKC","CuTvu2e","zxjHDg9Y","zgrjrcWGzgu","yKHkEKG","qwriwvG","ANzcDLe","whHbzva","BgvY","y3vYCMvUDeK","EKXjz2y","C01iwvC","otuZmdKYAvnXEhjR","zK9TqMW","zML5q00","Ec1TC2CTCw8","seT5qLu","vgjnshu","A0HYzum","C29Tzq","vMfss2q","BMCGB3iGyw4","zcWG","rKvoDLu","uwTpt3y","yxPcCee","rKXwrvO","BMrQs1a","qNjPzgDL","EfziuuW","zM9YrwfJAa","Ag1UExy","CNnVCKzPBgu","zLLKs1C","te5vseS","yMfSu2nVCgu","vwftDha","DMrnrLa","Ahr0Ca","vvL3sgm","igzPzwXKoIa","yurkvu8","yw5Hz2vY","nhWXFdn8mNW","ysbTDxn0igi","DfzTr1i","BwfW","CMvZzxrfBMq","tKTNyvy","Be1NBKm","Aw5KzxGGB3u","vefODey","zw5HyMXLvhi","CNHhtgC","sfPorvC","wM1qvuK","CvLVALG","nJu0sMnivLLY","Cw9Zx18","DxrVuMvJB24","yxjgD24","ugrMr0K","x29UugfNzu4","BeXoENa","Eg1SsK4","DfPXBve","Bwu6ia","x3DZsw5ZDge","u3zktfG","zuL5shK","z1nRquK","yNL0zxm","DhnPCwW","yxv0B21HDgK","DKrTr1u","Agjtv0q","Dg5oAKq","DcbSAw1PDa","sLnrteC","AxnbCNjHEq","y29SBM8","ChbL","q29Kzq","Bvfrugm","q1feB0q","uvzHtgW","r0HgCNi","CMfUC1e","su5tvefova","yMfJA3vWigu","svDWrxm","Dhr3Awq","y3vXDuq","yxnL","CNnus1e","yNHutK4","yxKSihrYEsa","ywnOzwq","EKvkvgq","DxroB0q","BMvY","rLDt","x2nVBM5Ly3q","t1zUvvG","B3vUDa","Dgv4DfbHEwW","qwzJA0S","y2HnyxHdB3u","C2nYAxb0","DhjPzxm","uNbis3y","tu9ItvC","CuTAChG","yuT3tKW","twvnsxu","zvjlqNy","tLPcALO","C1HND1G","ENLvA0y","swfkC08","tuvtu0fhrv8","sMXgu2i","AxnszwfKEq","CMvHzfvjBNq","CvPfyM8","D2vI","DxjS","B2nRzxrtDwm","sKzyq24","zw5KCg9PBNq","vLjxr0u","q3zcsgW","igfYCMf5yNu","x3jLBw92zvC","rfroq3y","ufzNs04","x2n1CNnVCKy","sLDvzg0","icSG","qMvuq0u","Bhm6ia","rgTXDvK","sKvcrLq","wMrOBMe","zgvJB2rLzey","vurUreO","y3vYDMfSDwu","sgfZyLC","r3rqs1C","rfzqveC","q3jPCwq","vNfNsMG","vxvrz2C","CfzjyMK","sLztCwe","qLvrsxe","u2ztqwm","x2nSzwfYvgK","zwz2D04","B25LCNjVCG","wMDlt0W","B1LZqKK","qwHUCNK","Aw5PDcbrB1m","wevjB0m","z1rPBwvVDxq","zKj2qKW","Ae5tCuG","A1zWuK8","yun1DMq","CwTyvNq","zuTqEKS","tKfusvzfx0u","Aw9ZBMy","zxrJs1G","reTlzgy","rw1HyxO","CM92AwrLige","CMrYzu4","zxH0ugf5Bg8","x3bYB3rVy28","r2Dzqxi","r251D1a","Aw9Ul2PZB24","yxbWzw5Kq2G","y2fSBa","yxv0BW","zwHdvg0","tfDqwLm","D2j3s28","rwLABLO","Dg9cExrLC0W","yNL0zu9MzNm","Chjxs2e","ywrKq291BNq","Dw5RBM93BIa","A1j1sMq","ufrKC0e","t1PvBfG","zxj2AwnL","sMfgDKC","BgvMwNu","BNvTyMvY","zxq9DxrMltG","A2zYDeq","EMDXAuS","sw1eEuW","vw5PBxbSzw0","z2zbq00","BwvqAuq","CMvKDwnL","BMvKANy","y3jLyxrLq2W","y3rqsgm","vu5AAKG","quHwBhm","B2fcCfm","sxvvu04","y3vYC29Yx24","x3nVy2TLDa","y2vZC0HHBMq","C2fNzq","DMfSDwvZ","CIb0DhDjra","sKfJtMS","ihrPBwvVDxq","CuHbzw0","A0frte8","AKzPCMS","zNjVBujPDhm","s3vqsfG","rgT4sK4","B25szwnLAxy","DgTJD3y","qxDAz00","A2v0ignVBNm","yKDpvLK","BMvLzf9Hy2S","DhjPzxmGCMu","vM94Efy","B1nrwue","sfHezee","thL6qLO","zvzyt08","DgLTzw91Da","tff3Dvq","qLzqCvC","Ef9MCM9UDgK","Efrurw52","qxbQquS","weLtsgK","t3bLBKv2zw4","zMXVB3i","CgLUz19VBMm","qKrNv2y","q291BNq","z2vtEw5J","twvcCe4","yLL1zvK","tLnmDfG","qMLVuum","vhPYCxK","yKj0u2u","Cfr0uKm","C1fXDge","BfHmB3y","ELffuKK","vwLvww4","C0Xf","qMvcyui","y3vxwLq","t05tDvm","sevOz2e","DLr2DKi","ywDLu2HVDW","ywrKt25L","zKPKEgC","D3jPDgvvAw4","u2vYDMLJzvC","D3jPDgu","uMnRtNy","C3rVCMu","sxbiAK4","x2fKzfDZtgK","Ae9dsfi","v09SCwC","sfrozgq","wKvctMq","A2vwt1i","x2rLyNvN","y3jLyxrLrwW","qKDnDxm","shLRqva","C2vYDMLJzq","ndu2ntCYmfrAzufvEa","rNjgzeu","q29UzMLN","zMzmAw5L","ufD2tM4","mtiWndD1u2PlCva","sxH4ALO","x2rPC2nVBM4","t21JANe","z2v0q3vYCMu","ihrYEsbYzwm","Aw1LCYbPBIa","DMXSuhO","BeLus3G","AeXxCw0","t3jvuwS","rNjVBNrPzxi","ndu3nZuWrvLRvujg","zw50","v25nwg0","BxPyBhm","EhzNEfK","vuXct04","C2vUza","B2jQzwn0u3q","DKLzqu4","AKTLuui","DMfSDwu","CgfYC2u","qM9hvKe","sKPuANe","r2Xxy2G","t2foDKC","x2TLEvbHDgG","rgXTExu","C3bfzxG","u1voq2C","ywnfvLu","zvL5uMe","zKnJt1y","zgf0yq","C3vIC3rYAw4","zLnODwS","EeDprve","BMrWB2LUDfq","x2DLBMvYyxq","suDLDe8","B25SAw5L","q2TUyMG","rKz6s1a","zxH0zw5ZAw8","EezcCNa","u0jtuNO","C3LnvuC","vgjlAgK","t1LTweS","svbnsM0","rvvYA1C","AuH6uey","BwHUwgS","BNruCMLLC0m","B2zMC2v0","rNDfCui","rLrQqNy","uw9Hqu0","Dxz1uwS","C3vIyxjYyxK","Aw9U","rND3yNG","uxzVyKe","Aw47y2HHCNm","B25ozxr3B3i","rwHxuwu","ywDL","CKvXue4","zxrxB3jRq2G","Bhnet04","CMf4yw4","u3fiz2q","CK5yBvq","D0zAt04","tg9Nsuq","t21vt04","Dw50","yvnUvgC","sNHryKK","CMvZDwX0","aaaaaaaaaaa","BM5Ly3q","ihrPBwvZ","Cgf5Bg9Hza","C2XPy2u","ywX3yxLZ","yuzXu2K","x2HHBMrSzu8","BK9WC2y","AgLNAa","y1bpBKW","Cg9W","zxjYtxnN","C1nOyMG","tuTssuG","DKjHsLi","D3m6lY8","q0DIyvi","DwT3BMq","Agzbz2q","zxjFAxnFywm","z3j6yvy","zNPmBwW","yw1L","se9MAfO","zv9ZDwnJzxm","Aw50zwDLCIa","z0DRvNq","qM1PC3e","ihn1y2nLC3m","D24GCMvHC28","AxjjBu8","ntztB1HZuxe","D1jbuvO","yuTXvw8","uMvHzcbWyxm","q09otKvdveK","zfn3rw0","uKHXtxC","AenSB3nLrxy","x29Ut3bLBG","zvr2que","zMvY","qNDtCge","x2LZtM9Kzq","B3LKCMe","qMDJyKK","C3vJy2vZCW","qwPAuLq","CfztAK0","BxzHAhK","DMfS","rwPiCKO","y1HeD0y","rwDIrNu","A1n0yxr1C0m","yMLUyxj5vhK","CMvTB3zLq2G","CNjVCK1LC3m","CLfKqLC","wxr2Cui","ywvRwgS","Cg9PBNrdB24","AfrXD2O","BNrLCG","u2rwDvC","BevVveW","Cgzquxe","y29Uy2f0","D2Htuwi","ExrRrhO","DMvYC2LVBMm","nMf6wu1NrG","yMrFzgLK","tu9fzvO","C3rHCNq","zeDjBvu","x3fVC0rc","t1fIyMG","y3bcEKK","CM9YrxzLBNq","BvreDvm","BwLUzW","sNroCvG","AM9PBG","tM95vxC","wefRtgm","vM91v3i","ExzYrKG","mxWYFdn8mhW","u0rst1m","pxv0zI04","uMTkD04","CgjICdi","z2v0","uxvLDwu","rKnvsxG","u3HHsuy","z2v0sxrLBq","x29WDgLVBNm","B25nzxnZywC","zw5JB2rLrNi","Cxrky1a","rvnVrLq","wNL0uvK","Dw5ZAwDUzwq","yKXQwfC","AevYCM9Yrxy","yxKSig5LDhC","ig1LC3nHz2u","B3bLBIa","s1zHDLy","AxnrB1nnzxm","Chr5CLy","s1PAzLO","rgvMCuW","quTcquq","DejkDfK","v1nXrgO","B3jfEeS","q0Xpu0ve","y09Wzw4","CNzHBfzHBhu","mtqZmZeZm2DkEezuEq","zvvYBa","x2rPC3bHDgm","tg9NsurozxC","uKPrAuu","C0nVDw50zxi","BgLUzw5V","y3ruAw1LB3u","wMjhCLO","CYbWyxjHBxm","twvVz2i","BwvZC2fNztO","z1LWzeC","zuTnDha","ChPAA2q","wNrtzem","uNvmugC","z2v0u3rVCMe","tfnIv04","vePYs3y","DefzzMO","thzQv2m","DePLquG","ChjVDg9JB2W","zMX1C2HfEha","tg1UzLO","s1Pky1G","tMXzzNa","Cgu6ia","yLnrzNK","yMLUza","twzHDvO","zwvlB3a","sNL5Dvm","y2XVC2uSihC","zwrPyxrLBhK","zgDtDuW","y2HLy2TdDxi","r0LUzw8","EMPyBe8","y29UBMvJDfm","DxrMofDYAxq","tMX0tKe","BuPks2C","DMXWzvq","AeXnue0","ywXPzcb1CMW","Ewroz1K","CuLZze0","y29UBMvJDca","EfvZzuvUDG","rffSy1C","tKXXyLa","Cw9Z","C2v0","sw9IrMq","zg9Uzq","B2rPweO","zxjFywnRx20","Dev2zw50","zMLSzw5HBwu","Agvky3C","BMvJDa","BLrdCfq","yuDOEve","CMPAuNe","B0Pmt2K","x2nYzwf0zvm","DhLoC2i","tgnIvg4","wKnACNe","qwHLsei","s3vSzue","CvLtveS","EvjLy29UBMu","x2LUDgvYDMe","CMvJB25Uzwm","CujUEvK","BfPqwLm","y2HHCKnVzgu","BfrPBwvVDxq","EuT4te8","D3nZoI8V","EevJzwC","uuL1t1a","sKDeBw8","BKrhtxi","uuTAEfK","turgzxC","sK9rD3G","vNfqCfe","ENDswg0","DMvUDa","zM9Yy2u","B2zM","y3vYCMvUDeu","BKPHqK0","x2rItMfTzq","AMrNqxO","DcbVzIbYyw4","Exv4tw0","BxfHALm","EwXLu2G","CeXHDu8","t1bltuK","Efn2wMG","quXm","ywnRtxnNswq","BNf4t0m","AgjUEvm","vfPQuNy","AvLRDvO","BeHHBMrSzxi","vfzXu3C","B2nRzxq","t3HxCKG","z2v0q3vYC28","vvHWEwW","BwLXvgK","zMLSDgvY","CMjyz2K","zuTAu0K","B3nLza","AgfUz2u","DxvzB1a","Bg9Nsurhzw4","Fdf8ohW5","sgfhBxy","ChbPrhO","B25dBg9Zzq","ANPUEeW","BM9Uzv9UB24","t1Piuum","ywT4vvi","CYbPBNn0yw4","lcbTyxGGCMu","rvb3quS","CxD6uNK","BgTWBuK","sLnptLa","A3PLrNa","wLzpBMO","EKnzzwq","EM5OtMq","wKDjwgC","Bwf4twvZC2e","EKrwCxO","r0ryA3G","uefAzw0","tMzqEeO","EePOveC","id4G","ELHtwuW","BxPRu1C","AefJA01LC3m","D0Plv1q","Ec1TC2CTy3u","ChvZAa","C0Pds1q","zxjFCw9Zx2e","B2LWvgW","EKX0Afy","Dg9cExrLCW","EKvcuvu","C2v0y3vYC28","De1HBMfNzxi","yxrHlcbKyxq","ru5yrey","sMjXs20","AhHZC0C","vwLrsKC","yKPmAvK","Bxj5v2m","igzHAwWSig0","CuHxCLu","wvr1u2G","zMDlC28","z2v0qwXS","CgLUz0LUDgu","vxnhsuC","ugfwswm","yLL4B1C","C3bSAxq","qMHqsvG","C0XPC3rLBMu","zMzLCG","A09oAfC","DMvY","wvjHsK4","Bu5Rz08","rwfeweS","v2DUB2y","wezbDe4","uLjpuG","ENvTEwO","yxjcC2y","D0jRDNq","CgLUz09Uy2u","Cgf5Bg9Hzeu","shDPy0K","A1zuv3m","B0zYzLm","AfnbteG","BgLUzq","Exb5rLC","rxzuAKu","BwLZzq","zwn0","qNLvA2G","ru1VEMy","yMXVy2TLza","vxLAyM0","D3nrEMm","rvjst1i","CMvTB3zLrxy","CMT4sgu","y2HnyxHuCMK","yMLUyxj5","yLbIr28","whzoz1q","zgvMAw5Luhi","C3nHz2vfDMu","zw5XDwv1zq","uKDdCwG","vKvMs1q","tu9kANe","B2fK","CwfhtuS","EKjYAfq","yMP2Avy","y2XVC2u","vNjtzKC","ihzHBgLKihm","BxnNsuq","DhbizwfKzxi","BxrhAuS","x2vUzhbVAw4","AgHIt3i","re1Ay1u","r2Xqyw4","C0jf","x29UvgLTzw8","u0HMyKm","uxbdwwi","ufPXwhe","ywXSB2nvBNm","B2LUDfjLywm","t1niuu0","qw1VDw50","CeTxug0","tunMDgu","BMnVzgLUzW","x25HDMLNyxq","zNjVBunOyxi","Aw5KzxHpzG","z2rvuw0","lcbOB3n0BMe","BwvZC2fNzv8","B2PvvwK","DKH4C1e","wezHrvO","sMfwr2K","uhjfCwK","wLDyweq","C2TYA0W","CMvHC29U","vKz5suq","quz3see","sMnftuC","BeHwCMe","zeTKzLe","uhrQqMq","CND6q24","x3bYzwzPEa","y29UBMvJDgK","DgPSsvq","zxjYB3i","AKjlsuC","yNvorNm","BMCGDxjSoIa","CgfNzwHPzgu","svrPDfy","D3HwBMK","tKnbtLi","BMDuAw1LCG","uLftBMm","DhjRz0G","swTuC3a","qw1qCgi","B25TzxnZywC","tKfiqxu","Ehb4D1G","y3jLyxrLtwu","vgLTzw91Da","vhfpvMK","Ag9Tz0S","DgL3sMq","uwLpsKC","AgvHzgvYCW","Dg9iyxnO","CM92AwrLigi","AhfiCg0","B3nLrxzLBNq","Dw5KuuW","sunNAe4","A1bSvuy","Aw5L","EM9xAei","x29UrxjYB3i","tKLKs0m","CxDitvC","yxrLq291BNq","BgjlwfK","twvZC2fNzuu","BvvID1m","CxPWz3K","x0vysvnu","u3HPyMG","wwDtzeC","BhLft3q","wKLUt1a","uKvSww8","uuz4Dum","Dw5KzwzPBMu","x194x21Zz18","qxblse0","ywXNq2G","q3bvq0C","ENzSDKC","ELL4D2i","zNjVBu51Bwi","zM5lsxq","qLjXAxy","ywDLsgLKzq","yuXRyNG","zNzgvuC","rMjyuNG","BwvY","wK5myLC","DwHoAvO","wMD2whG","x19LC01Vzhu","DgLTzw91DcW","zwPwtvm","v2vIu29JA2u","s1nIAvm","yvnIt1q","mteYmtm4mfbQsNb3Bq","EuvxCvu","yxHsy3a","CMvZzxruCMK","ywXSzwqGBxu","y291BNq","zhbWEfK","B2nRzxrgywK","tMvRBvC","x2jPBMfYEvq","vvjfuwm","CMfUzg9T","rKLmrv9ot1q","zK5pCKG","nNWYFdb8nhW","t2jQzwn0","vKLTAuu","DKX6zfm","B2XKvMvYC2K","r3H5CMy","zgvS","y3jLyxrLuMu","zNH6tvG","x0rctMfTzq","C1PivK8","AKX0v0e","B3bLCNr5","B3jRig9MzMW","CvP5z0C","ELv4AhC","ywnRx2nVzgu","Cg93","v09jwuO","v3veuve","wLfXwuG","zxmGCMvHy2G","ugniC24","EhbkEeC","zMLN","CK9Mvfa","zw5fDMvUDa","Dg9tDhjPBMC","txbnBfK","BNbtAeq","z2v0qwXSs2u","BMCGzMfPBgu","DxbKyxrLq3u","zNjVBNrPzxi","y3jLyxrLt3a","zg1zC3i","zNjHBwvuExa","ugXQrwe","q3LcwhO","ywzL","CNzHBa","BgLZDgvUtMu","y3jLyxrLrxi","AMPUtxy","x2HHBMrSzva","uLPjsxy","CMvQzwn0","ExvlEKe","BNnLEgW","uNDAuMG","ru5LCwu","rgP3sLy","yNLL","x2n1CNnVCK0","BM93","qKLLwLm","DujwwLq","x3bHDgHlzxK","reTpsM8","DhLWzq","CM14v2W","u1jnwKq","q3vZDg9Tq2W","tKDFrvjst1i","zfDVCMTLCKC","rfrNr2W","zfbStLq","z21mBwu","BNrfBMrWB2K","zxHgCLy","ww5oExK","yM5VBxC","Ee5lzee","Aw5JBhvKzxm","ChbRBeu","zxnPww8","y0HdseC","CMvWBgfJzq","BwvKAwf0zwW","C2v0u3rVCMe","z3zks04","C3rYAw5N","CK9pwvO","CMLyyKm","Ae9Wzw5fDMu","zw50zwqGDhK","Cg9PBNrbBMq","Fdb8n3W2Fdm","CvHPsfu","CMLLC0nVDw4","x29UtwvZC2e","vej6zfq","y2HLy2Tszwe","AgvKtwf4uMu","zw5NDgG","Bwf4uMv0CMK","EKPSDKS","AxnmB25N","q0TPCgm","x2LZsw5PDa","CNnVCL9Uyw0","zgL3B1G","zur6vKW","yxGGCMv0CMK","Bhfnr0O","rMX5vgW","m3WYFdr8mxW","x2rYB3bhBg8","uMvJB25Uzwm","Ew9ttha","txfWBxy","y3DhAhy","x2LZtwLUAvC","DgDcrgS","Aez3zK0","t3DsrMG","x2rLC3rYB3K","zw50tgLZDgu","rwXODxa","qMP4sLK","v2PhtfK","AurnwuS","EKjgCKu","rLfoA1i","D3flsxO","rwTpshe","wvzsCuW","zLD4yKm","y3vYC29Y","z2u6ia","A0reuw8","CMvZB2X2zq","r3PitK8","r3fXsgm","zsbHihn0CMK","x2LZqNjVD3m","ywDLrxzLBNq","DePYtum","y3vYC29YlNm","x3bPBMDqB24","EKXKqxO","Bwf4tg9ZC0m","rw1VBK4","yw5Nzq","vwjusfK","wLn5u3m","qMvIDNG","B3jLtMfTzxm","Exrsy20","qK9LBfC","rhLcBuO","u1bHyKK","x3nLBMrby2S","uuv0tLK","BMDLza","yxjYyxLIDwy","u3rYyxrLz3K","ruTdze4","AKrbsg4","Chv0","yMPYCuq","weLKDgK","CMvHzhLtDge","Aw5N","vxftrNm","CMvUDevUzha","ChrVCG","svbtC1u","zcWGDw5RBM8","rwfpDg4","Cenny28","tNPXuhi","ufLNEfi","ihbYB3rVy28","rMPNt2G","AeLms2C","nhWXFdn8mte","x2zVCM1HDeu","ufP4CNG","vhneuMC","CLPlq2G","zcbLCNjVCI4","CeXZCuq","zxHWB3j0CW","y2XLyxjtDg8","yw1Lu3bHy2u","svjjt0S","rgnMr2q","CMfTzq","wuDTsuO","qxPyDKe","tufhAvm","rxnkzgi","CMvJzxzPzwq","EwzszLm","B3fJs00","EeTnswe","z0rrDK8","ChjVDg90Exa","zKfwrKS","rxDoqwO","zgvIDwC","yM9KEq","B3v0sw50zxi","zxjYtM8","BKXPBMu","D0TRC0u","rMfKuxm","v2rAv2u","AxnrB1nby2S","zMzMzG","x2n1CNnVCK4","sgjtBwO","x21LC3nHz2u","C0zRzgy","DKzuBKK","u2TPCcbWyxm","BLDjBwm","yw5ky04","v1nrug8","B25JBg9Zzq","q0Xpu0LorW","vKHtsvK","ue5uzMW","DgLUzYbZzxi","zw1LBNq","CK5lv2W","t1jevui","sezHCxO","AwDHDg9Yt24","DLfPExC","BMX1reW","yxHtt3e","vwLZvwO","CMv0CNLdB3u","uLrHuMC","Dg5LA20","BgLTAxq","zNnWvK4","qw1iwuO","uMPss1O","rLfrz3y","vw1nvgG","y2XLyxi","AwXLtMfTzq","Aw9UvgLTzw8","z2PMqK8","BwvZC2fNzq","C3rYAw5NAwy","CK5iEwq","x3bPBMC","zLHmrK8","wfLvweG","whHMC1O","ww5WDNO","r1Posfm","Dgv4Dc9WBge","DeXqsKO","EejZtKq","qM5cDwi","y3vYC29Yx2y","ywXS","s0TxA3y","uu9IAe8","wKnTEe0","zhDwz3q","vvvLBhG","Ag5by0O","Evr3BK0","y2uGBM90igK","yxnZAwDU","mNWZFdb8mxW","wLHsC1i","B3jpBMXPBMu","EKLXuuy","x3DHAxq","B3jRzxjhBg8","D3DLCu0","z1bprhy","u2vju1q","yMfSrxzLBNq","x2LUAxq","vxjlC1q","q25wy0S","Dhr6shO","BwLUAvbYB2C","Ec11C2uT","mdaWmdaWmda","Ahr0Chm6","Ae1LC3nHz2u","swfrsvm","t05kAMm","DvHJuLK","A2v5CW","turnv20","ywHwEuO","Ag9NzKi","rhfuzwS","DLLMAe4","A2jqBxm","tMfTzq","BNrbBMrvCgq","sK5VCg0","x3nLCuLK","wNbbz2u","DwvAqLq","BhniDKy","verru2e","yxflvfe","ywnR","m3WXFdu","u09mAgq","tgLZDgvUzxi","r2nmC1O","zNjVBuj5Dgu","sLHjzxC","uwLQyKG","C3rVCcbPBw0","BKvTsvi","AM9wBva","CMvJzwL2zwq","BMrLEa","AMvJDfn0B3i","t1bftG","yw5ZzM9YBvq","Dhjlv2S","rxPiy00","t3D6y0O","rLjptLrjrvi","B25Uzwn0Aw4","ze9dvfq","qxrguuG","x3jLy29UBMu","ywXSq3vYC28","veLfEMC","y29UDgLUDwu","y3HQAMm","zxjFBxnNAwq","zgLZywjSzue","qujZAMe","C2v0sxrLBq","rNv4CuO","x2HHBMrSzvi","C2vYDMvYvgK","BLrhs2S","D0TlBMG","DgT3zhG","ufLxv0i","vxzquNu","CgLUz1rPBwu","rxjYB3jdB2q","we1NDuG","AgfZt3DUuhi","s1vmAxm","nhWZFdb8mxW","tfbkDwe","t2nrDvi","CMfNzvn5BMm","A0r6r24","yxbWBgLJyxq","wK1gC3q","rffIz0C","ExvfENG","D1nKvvq","zwnVBM5Ly3q","q09oveLovuu","C1jTq1m","qM9ys3m","BgvUz3rO","Dg9mB3DLCKm","v1rXBNi","qwjVCNrfCNi","AwXK","B29qBgG","EufJtNe","uLreyNu","x3DZ","zMLUza","BffNz3q","ywXty29Wzq","y0fxCKq","CM92AwrLihC","DefNuuG","Dg9VigXHCMC","y29UC3rYDwm","ALf1wuy","z0DKwei"];return wa=function(){return t},wa()}function dI(t){let e=M,n={mqajS:e(1678)+"d error.",AFwHA:e(318),Bmisq:function(i,s){return i(s)},WezoK:e(686)+e(1380),wewxB:function(i){return i()}};return t===IDBDatabase[e(1431)+"e"][e(309)+"ion"]&&!(n.WezoK in IDBTransaction[e(1431)+"e"])?function(i,...s){let a=e,d={bbPdH:function(u,f){return u instanceof f},HKyBU:function(u,f){return u+f},lSwDH:n[a(973)]};if(n.AFwHA===n[a(1139)]){let u=t[a(553)](n[a(777)](ys,this),i,...s);return hl[a(926)](u,i[a(1621)]?i[a(1621)]():[i]),n[a(777)](Jt,u)}else{let u=_0x4877fc[a(1601)]&&_0x31acac[0];if(d.bbPdH(u,_0x1e8e84))throw u;let f=new _0x5d9870(d[a(384)](d[a(1703)],u?d[a(384)](d[a(384)](" (",u[a(1480)]),")"):""));throw f[a(354)]=u,u}}:n[e(1664)](sI)[e(1306)](t)?function(...i){let s=e;return t[s(275)](ys(this),i),Jt(xl[s(843)](this))}:function(...i){let s=e;return n.Bmisq(Jt,t[s(275)](n[s(777)](ys,this),i))}}function lI(t){let e=M,n={zEJTd:function(i,s){return i===s},HqXLw:e(291),uLGBk:function(i,s){return i(s)},IDitU:function(i,s){return i instanceof s},PrEqi:function(i,s){return i(s)},JmfMA:function(i,s,a){return i(s,a)}};return n[e(466)](typeof t,n.HqXLw)?n[e(1721)](dI,t):(n[e(1669)](t,IDBTransaction)&&n[e(1134)](aI,t),n.JmfMA(zp,t,iI())?new Proxy(t,ba):t)}function Jt(t){let e=M,n={JJTjq:function(s,a){return s(a)},azBpA:function(s,a){return s(a)},JKtTV:function(s,a){return s instanceof a},zQERI:function(s,a){return s!==a},jFirk:e(1516),tkcwv:e(1473)};if(n.JKtTV(t,IDBRequest))return oI(t);if(ga.has(t))return ga[e(843)](t);let i=n.azBpA(lI,t);if(i!==t)if(n[e(634)](n[e(596)],n[e(601)]))ga.set(t,i),_a[e(926)](i,t);else return n[e(692)](_0x460b8e,n[e(393)](_0x142d16,_0x279807));return i}var zp,Op,Lp,xl,ya,hl,ga,_a,ba,ys,Np=Fp({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={TplWm:function(n,i){return n!=i},zXrtv:t(1314),Gjhfk:function(n,i){return n instanceof i},SdVuW:function(n,i){return n instanceof i},eQnTw:t(1592)+t(551),MIyPk:function(n,i){return n instanceof i},Vvnva:function(n,i){return n===i},MDMWm:function(n,i){return n===i},nluDL:t(1055),CKipc:"store",RTaRg:function(n,i){return n(i)},eBHhy:t(928),zXSYL:function(n,i){return n in i}};zp=(n,i)=>i[t(387)](s=>n instanceof s),xl=new WeakMap,ya=new WeakMap,hl=new WeakMap,ga=new WeakMap,_a=new WeakMap,ba={get(n,i,s){let a=t,d={RQSnc:function(u,f){return e.TplWm(u,f)},vTGoj:e.zXrtv,bfqtD:function(u,f){return e[j(367)](u,f)},efvwN:function(u,f){return e[j(814)](u,f)},XVYzH:e.eQnTw};if(e[a(1670)](n,IDBTransaction)){if(e[a(1653)](i,"done"))return ya[a(843)](n);if(e[a(1527)](i,a(686)+a(1380)))return e[a(1653)](a(1643),e[a(1464)])?d[a(1157)](d[a(1661)],typeof _0x6c82bd)&&(d[a(1715)](_0xe33a62,_0x2392cf)||_0xdbb1f6.buffer&&d[a(526)](_0x4422a6[a(327)],_0x911c99))||d[a(1157)](d[a(1661)],typeof _0x5d71b1)?"":(_0x4396c5[a(690)](_0x577363),d.XVYzH):n[a(686)+a(1380)]||hl[a(843)](n);if(e.Vvnva(i,e[a(1331)]))return s.objectStoreNames[1]?void 0:s[a(686)+a(1690)](s["objectSt"+a(1380)][0])}return e[a(1468)](Jt,n[i])},set(n,i,s){return n[i]=s,!0},has(n,i){let s=t;return n instanceof IDBTransaction&&(i===e.eBHhy||e[s(1653)](i,e[s(1331)]))?!0:e[s(1024)](i,n)}},ys=n=>_a[t(843)](n)}}),Up={};rI(Up,{deleteDB:()=>fI,openDB:()=>uI,unwrap:()=>ys,wrap:()=>Jt});function uI(t,e,{blocked:n,upgrade:i,blocking:s,terminated:a}={}){let d=M,u={OUBDA:function(p,m,b){return p(m,b)},AobSs:function(p,m,b,y,v){return p(m,b,y,v)},ZgvXx:function(p,m){return p(m)},VouWr:function(p,m){return p(m)},AwZgM:d(1102),BzTIf:d(820)+d(995),zdNKw:function(p,m){return p(m)},oojEr:function(p,m){return p!==m},lbKXY:d(1384),sRTqY:d(1688)+"eeded"},f=indexedDB[d(262)](t,e),x=u.zdNKw(Jt,f);if(i)if(u.oojEr(u[d(1184)],d(1384))){this["_dispatc"+d(788)+d(680)](u[d(1748)](_0x397e33,"close",{code:1e3,reason:d(1285)})),this[d(1108)+d(1037)]?.[d(415)+d(811)+d(1257)](),this["_pingLos"+d(877)]?.[d(287)+d(813)]();return}else f[d(356)+d(1545)](u.sRTqY,p=>{let m=d;u.AobSs(i,u[m(1212)](Jt,f[m(748)]),p[m(1237)+"on"],p[m(1682)+"on"],u[m(836)](Jt,f[m(309)+m(729)]))});return n&&f[d(356)+d(1545)](d(1082),()=>n()),x[d(1657)](p=>{let m=d;a&&p[m(356)+m(1545)](u[m(602)],()=>a()),s&&p[m(356)+m(1545)](u.BzTIf,()=>s())})[d(340)](()=>{}),x}function fI(t,{blocked:e}={}){let n=M,i={VOgVG:n(1082),EaOtn:function(a,d){return a(d)}},s=indexedDB[n(1772)+n(1758)](t);return e&&s[n(356)+n(1545)](i[n(368)],()=>e()),i[n(1402)](Jt,s)[n(1657)](()=>{})}function Mp(t,e){let n=M,i={nhtin:function(f,x){return f(x)},dxOzB:function(f,x){return f(x)},ojsMq:n(286)+"e",pVSjM:n(1798),hjlTJ:function(f,x){return f instanceof x},eglue:function(f,x){return f in x},spEex:function(f,x){return f===x},ApjAK:"string",PIAbb:function(f,x){return f!==x},kRuJd:"kquXj",HWEhX:function(f,x){return f!==x}};if(!(i[n(1736)](t,IDBDatabase)&&!i.eglue(e,t)&&i[n(697)](typeof e,i[n(617)])))return i[n(1692)](i[n(564)],i[n(564)])?UZWCiK[n(248)](_0x496e96,_0x444309[n(275)](UZWCiK.dxOzB(_0x345509,this),_0xfd5348)):void 0;if(ma[n(843)](e))return ma[n(843)](e);let s=e[n(1310)](/FromIndex$/,""),a=i.HWEhX(e,s),d=Gp.includes(s);if(!(s in(a?IDBIndex:IDBObjectStore).prototype)||!(d||Hp[n(1306)](s)))return;let u=async function(f,...x){let p=n,m=this[p(309)+p(729)](f,d?i[p(1631)]:i[p(798)]),b=m[p(649)];return a&&(b=b.index(x[p(360)]())),(await Promise[p(1494)]([b[s](...x),d&&m[p(928)]]))[0]};return ma[n(926)](e,u),u}var Hp,Gp,ma,hI=Fp({"node_modules/idb/build/index.js"(){let t=M,e={YlWJw:"5|3|2|4|"+t(1729),FuxqJ:function(s,a){return s(a)},SHfbC:t(843),ypyFW:t(1049),zfhtb:"count",Hahvr:function(s){return s()},XxAeP:t(313),OSHQM:"delete",PaVIc:function(s){return s()}},n=e[t(1795)].split("|"),i=0;for(;;){switch(n[i++]){case"0":e[t(1574)](cI,s=>({...s,get:(a,d,u)=>Mp(a,d)||s[t(843)](a,d,u),has:(a,d)=>!!Mp(a,d)||s[t(1668)](a,d)}));continue;case"1":ma=new Map;continue;case"2":Hp=[e[t(1114)],"getKey",e[t(1076)],"getAllKeys",e.zfhtb];continue;case"3":e.Hahvr(Np);continue;case"4":Gp=[t(1392),e[t(375)],e[t(1119)],t(1476)];continue;case"5":e[t(1052)](Np);continue}break}}}),xI={idb:function(t){let e=M;t[e(1416)]=Promise[e(1364)]()[e(1657)](()=>(hI(),Up)).then(function(n){return n})}},Bp={};function Zt(t){let e=M,n={hIZfo:function(u,f){return u!==f}},i=(e(838)+"4")[e(1054)]("|"),s=0;for(;;){switch(i[s++]){case"0":xI[t](d,d.exports,Zt);continue;case"1":var a=Bp[t];continue;case"2":if(n[e(1656)](void 0,a))return a.exports;continue;case"3":var d=Bp[t]={exports:{}};continue;case"4":return d.exports}break}}Zt.d=(t,e)=>{let n=j;for(var i in e)Zt.o(e,i)&&!Zt.o(t,i)&&Object[n(1092)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Zt.o=(e,n)=>Object[t(1431)+"e"][t(1585)+t(1245)][t(553)](e,n)})(),(()=>{let t={xvgxY:"__esModule"};Zt.r=e=>{let n=j;typeof Symbol<"u"&&Symbol[n(1260)+n(1759)]&&Object[n(1092)+"operty"](e,Symbol[n(1260)+n(1759)],{value:n(1723)}),Object[n(1092)+n(1245)](e,t[n(683)],{value:!0})}})();var Me={};(()=>{let t=M,e={mUbwS:function(c,r){return c(r)},yAcNq:function(c,r){return c+r},cbkOj:function(c,r){return c+r},Sxibh:function(c,r){return c*r},PAiyx:function(c,r){return c*r},tAYfj:function(c,r){return c!==r},IobFd:"EZytJ",IRBQR:"GDjAU",trkgH:function(c,r,o){return c(r,o)},Nyngp:function(c,r){return c(r)},cHCHG:function(c,r){return c(r)},dPlNT:function(c,r){return c+r},VHSIY:t(1633),aKwNL:function(c,r){return c(r)},PvDfk:t(1520)+t(1520)+t(1520)+"00000000",mePiD:t(1148),vFTnI:function(c,r,o){return c(r,o)},GHFrr:t(1102),DqTek:function(c,r){return c>r},hTqwj:function(c,r){return c<r},cpBzI:function(c,r){return c>r},IGetO:function(c,r){return c!==r},CepBg:function(c,r){return c-r},QGmbp:function(c,r){return c-r},ZcCaS:function(c,r){return c-r},IxxjZ:function(c,r){return c<r},LekAp:function(c,r){return c===r},wYvIc:function(c,r){return c<r},IaKSd:"lNwkz",HHlMJ:function(c,r){return c!==r},BDgWf:function(c,r,o){return c(r,o)},BUQIq:function(c,r,o){return c(r,o)},Xcvqu:t(845),XZmlm:"YdqqC",WuDQQ:function(c,r,o){return c(r,o)},TIEzg:t(948)+"t",MKRIH:t(824),ICghN:t(1200),skrkL:function(c,r){return c>>>r},rwzCn:function(c,r){return c(r)},trKWk:function(c,r){return c&r},ApKHM:t(1697)+"required"+t(408)+"key",ZCmxM:function(c,r){return c===r},FQNkR:t(1149),gmLme:function(c){return c()},RGCqh:function(c,r,o){return c(r,o)},fBvBL:t(838)+"4",qtJcP:function(c,r){return c<r},jjnMv:function(c,r){return c+r},bjviV:function(c,r,o,l){return c(r,o,l)},zoWhB:function(c,r,o){return c(r,o)},bYxoW:function(c,r){return c instanceof r},WjGLY:t(928),lMgnC:t(649),tGnlf:function(c,r,o){return c(r,o)},NzqPr:function(c,r,o){return c(r,o)},Zzmqk:function(c,r,o){return c(r,o)},taZcw:function(c,r,o){return c(r,o)},nILNk:function(c,r,o){return c(r,o)},YGmIJ:function(c,r,o){return c(r,o)},SBSRz:function(c,r){return c(r)},WdZWe:function(c,r){return c!==r},uBVZT:t(1298),tyNsb:function(c,r,o){return c(r,o)},yuxMm:function(c){return c()},OZHQC:function(c,r,o){return c(r,o)},jDAHn:function(c,r){return c!==r},UiUYn:function(c,r,o){return c(r,o)},yvrFH:function(c,r){return c!==r},RkIOU:function(c,r,o){return c(r,o)},UsGIG:function(c,r,o){return c(r,o)},ZCZrq:function(c,r,o){return c(r,o)},Vpkyp:t(326),wCeiH:t(1461),oaBpS:function(c,r){return c(r)},UYxFD:t(794),wKKnh:"BxQrS",mvahy:function(c,r){return c(r)},gGkVt:function(c,r,o){return c(r,o)},PAZem:function(c,r){return c&r},sJCKT:function(c,r){return c===r},TAhtF:t(1697)+"required field: "+t(283),kVpRO:function(c,r){return c===r},lHVra:t(1697)+t(355)+t(408)+t(743),LyzBZ:t(1697)+t(355)+t(408)+t(661),FTjBv:function(c,r){return c===r},mtGiK:function(c,r){return c(r)},kydcY:function(c,r,o){return c(r,o)},UqSFs:t(575)+t(1318)+t(900),syMUG:function(c,r){return c>>r},xNKdA:"DSpVj",gGdXB:function(c,r){return c!==r},LOkBH:"XTQsU",sFkdf:t(908),nFypX:function(c,r){return c+r},aekXk:t(1449)+"t limit",kPlUF:function(c,r){return c+r},yevHu:function(c,r){return c*r},cxjjc:function(c,r){return c>r},FFzKP:function(c,r){return c(r)},axRcp:t(1344),NAHAu:t(1719),QEtNY:function(c,r){return c+r},eIyHy:"is_ack",dppxY:t(1769),XEIoC:function(c,r){return c||r},TZjRv:t(1249),PMkNm:function(c,r){return c+r},OwzcJ:function(c,r){return c<r},FQQgv:function(c,r){return c+r},VzSna:function(c,r){return c>=r},pzZkd:function(c,r){return c+r},LNyly:function(c,r){return c+r},UisUj:function(c,r){return c!==r},GVdeH:function(c,r){return c|r},PNTfl:function(c,r){return c<<r},yEWqU:function(c,r){return c&r},fexaY:function(c,r){return c==r},XvNgT:function(c,r){return c>=r},JtNqX:function(c,r){return c===r},Knvlr:t(323),zJlvK:t(960),VFyID:function(c,r){return c+r},dKdfQ:function(c,r){return c+r},vHxsQ:function(c,r){return c+r},ttzHz:function(c,r){return c+r},SNhKb:function(c,r){return c&r},BnBub:function(c,r){return c|r},YTuSh:function(c,r){return c|r},OwRFh:function(c,r){return c&r},YgSdG:function(c,r){return c>=r},vBaJR:function(c,r){return c<=r},JEBFT:function(c,r){return c==r},jvBvQ:t(486),hsFWL:t(1182),KKQqZ:function(c,r){return c+r},KZJcX:function(c,r){return c+r},FPKTS:function(c,r){return c+r},CyBXz:function(c,r){return c<<r},oipTl:function(c,r){return c&r},yTwnM:function(c,r){return c&r},XroIz:function(c,r){return c&r},vfGev:function(c,r){return c>r},ppklE:t(666),riXbC:t(1087),pTtRC:function(c,r,o){return c(r,o)},VqPpQ:function(c,r){return c+r},nWImc:function(c,r){return c>>r},grzaV:function(c,r){return c&r},JcEMG:function(c,r){return c===r},mTDuS:t(1110),tXmpK:"CZYra",pqmGz:function(c,r){return c>=r},UiGlB:function(c,r){return c<=r},hfAgd:function(c,r){return c+r},oYsBI:function(c,r){return c-r},suGGJ:function(c,r){return c+r},MeBpN:function(c,r){return c<r},Mscwm:function(c,r,o){return c(r,o)},sXgwX:function(c,r){return c<r},ONJjc:function(c,r){return c<<r},ctPHc:function(c,r){return c<r},JSQLG:function(c,r){return c&r},ejVMS:function(c,r){return c<r},NTXZH:function(c,r){return c>>r},fNOrH:function(c,r){return c&r},gdUQm:function(c,r){return c>>r},NlYfp:function(c,r){return c>>r},fWxbC:function(c,r){return c===r},fnKIt:t(566),RTDbu:function(c,r){return c<<r},KuPHX:function(c,r){return c&r},wFZON:function(c,r){return c&r},gDQvO:function(c,r){return c>=r},rxGLg:function(c,r){return c&r},NhNff:function(c,r){return c&r},IPSsU:t(1623),TDQSa:function(c,r){return c&r},Mqpmv:function(c,r){return c&r},OQbbh:function(c,r){return c<<r},FSfNx:function(c,r){return c&r},nedjv:function(c,r){return c<<r},DBQiQ:function(c,r){return c&r},yOZtX:function(c,r){return c(r)},HTNdd:function(c,r){return c<<r},VoxxV:function(c,r){return c&r},ytRcm:function(c,r){return c&r},XAkLc:t(1282),BtrTl:t(1247),czXRM:function(c,r){return c>>>r},DiyVx:function(c,r){return c<<r},OrUQk:function(c,r){return c===r},TJrKv:function(c,r){return c===r},VNbmf:function(c,r){return c<r},IPMJm:function(c,r){return c+r},LcbTn:function(c,r){return c|r},LwYLY:function(c,r){return c&r},QpCYb:function(c,r){return c>>>r},axbjB:function(c,r){return c!==r},UvPRu:function(c,r){return c>>>r},BGLRD:function(c,r){return c&r},ImDyL:function(c,r){return c|r},qKZpx:function(c,r){return c>>>r},kHreC:function(c,r){return c&r},ojUUi:function(c,r){return c!==r},vdMFP:function(c,r){return c|r},YAefo:function(c,r){return c&r},JGDmo:function(c,r){return c+r},gSkAI:function(c,r){return c!==r},UslYT:function(c,r){return c|r},YnNyy:function(c,r){return c>>>r},pVIbi:function(c,r){return c>>>r},buNFs:function(c,r){return c+r},YyFXK:function(c,r){return c!==r},focmA:function(c,r){return c&r},WzjAj:function(c,r){return c!==r},RKewe:function(c,r){return c&r},wJyJf:function(c,r){return c(r)},bYueY:function(c,r){return c|r},eHOVE:function(c,r){return c|r},xpxwX:function(c,r){return c<<r},RkJwN:function(c,r){return c|r},hmnyv:function(c,r){return c|r},lyEOt:function(c,r){return c|r},ZQqYH:function(c,r){return c<<r},XFAtN:function(c,r){return c|r},CNWGC:function(c,r){return c<<r},FbXRx:function(c,r){return c>>>r},EzHcM:function(c,r){return c|r},bjrqD:function(c,r){return c>>>r},JFXCn:function(c,r){return c|r},NtqbL:function(c,r){return c|r},xKMIa:function(c,r){return c<<r},bBtSe:function(c,r){return c>>>r},GcLsZ:function(c,r){return c&r},zwRXm:function(c,r){return c>>>r},FadQs:function(c,r){return c&r},TbMHu:function(c,r){return c>>>r},SOLhd:function(c,r){return c(r)},MITwA:function(c,r){return c>=r},ArQKI:function(c,r){return c<=r},OcQuR:function(c,r){return c%r},FACSz:function(c,r){return c|r},NLqbP:function(c,r){return c/r},RyKKL:function(c,r){return c>>>r},NIdKC:function(c,r){return c>>>r},XMguH:function(c,r){return c>>>r},fxzMX:function(c,r){return c+r},BoYTc:function(c,r){return c+r},Criqd:function(c,r){return c+r},QRoKn:function(c,r){return c<<r},mzkSW:function(c,r){return c===r},omsWS:function(c,r){return c>>>r},zgqiK:t(1648)+t(464)+t(948)+t(1457)+t(1059),FvOUT:function(c,r){return c===r},lsedC:t(1432),bGOVY:function(c,r){return c&r},VRWGE:function(c,r){return c&r},EvTjE:function(c,r){return c&r},undQL:function(c,r){return c>>>r},cAWrD:function(c,r){return c>>>r},EwNAj:function(c,r){return c&r},TbKhi:function(c,r){return c&r},mxbel:function(c,r){return c>>>r},yKxLO:function(c,r){return c&r},ooPlh:"Read pas"+t(445),YGpsB:"KkmDL",GZNHS:t(1650),FLVEZ:function(c,r){return c&r},DyBmJ:function(c,r){return c>>>r},LHYOz:function(c,r){return c&r},VrqEL:function(c,r){return c&r},jRZsZ:function(c,r){return c>>>r},odiXJ:t(1504)+"5|4",BjxJY:t(1796)+t(1630)+"R",npShD:t(488)+t(1085),eeKop:"NATIVE_E"+t(1065),RVHUf:t(785)+t(1296),tBJtY:function(c,r){return c===r},tnekm:"Bzvwj",IRIOK:t(1563),ransQ:t(1233)+t(1543),qzzEJ:function(c,r){return c===r},EhWQe:t(411)+"0",EiLDx:function(c,r){return c<r},cXDwF:function(c,r){return c&r},OVnUX:t(700),XZSDy:t(1472),Akvkg:t(1641),ZmPUI:function(c,r,o){return c(r,o)},EKKlJ:t(888),dmYsr:t(524),hhbOr:function(c,r){return c+r},ydNgY:function(c,r){return c<<r},jUxWE:function(c,r){return c>>r},wAMZZ:function(c,r){return c|r},ZbGrZ:function(c,r){return c&r},UYwHc:"VNHKU",ukwnd:function(c,r){return c>=r},uvuQk:function(c,r){return c-r},KYXTp:function(c,r){return c===r},encWm:function(c,r){return c instanceof r},irImO:function(c,r){return c+r},HasbW:function(c,r){return c===r},ABsja:function(c,r){return c===r},pLauO:function(c,r){return c<r},OaNvG:function(c,r){return c!==r},uTzbX:t(542),YtvqB:function(c,r){return c(r)},qYojX:function(c,r){return c===r},BRqiv:"pKckM",oAcGe:"hTVjG",Zdhna:function(c,r){return c!==r},RNwRw:t(834),GAHwm:t(262),rsTKQ:function(c,r){return c===r},bHJzH:t(1666),DKVPA:function(c,r,o){return c(r,o)},KtnWk:function(c,r){return c!==r},dopIS:t(352),YdEvZ:function(c,r,o,l,h){return c(r,o,l,h)},vlpeT:function(c,r){return c(r)},NekmW:function(c,r){return c(r)},Tjfdg:function(c,r){return c-r},jznxL:function(c,r){return c>r},ZVOnj:t(1496),oSQYA:t(1580),rGxfw:function(c,r){return c|r},IaQIS:t(330),wcmxj:"message",uuYoP:t(736),DcfGd:function(c,r,o){return c(r,o)},xEceg:function(c,r){return c instanceof r},exFrV:function(c,r){return c+r},fijxO:function(c,r){return c!==r},tnNjD:t(550),GIneo:function(c,r){return c||r},whSQb:function(c,r){return c!=r},hbSWD:t(1195)+"d",ffXaS:function(c,r){return c===r},JWhRu:"SXqVJ",ITitV:"tRxbI",PTdsA:t(307)+"3",vYfhN:function(c,r){return c||r},Bebvx:"mfrAz",zLIgf:t(353)+t(1223)+t(1716)+t(673)+t(1699),MeMIu:function(c,r){return c<r},bzuRq:function(c,r){return c&r},RNVpK:function(c,r){return c+r},NREtO:function(c,r){return c<r},SeIST:t(884),QFxuC:function(c,r){return c<r},DZyxR:function(c,r){return c|r},BVPqW:function(c,r){return c<<r},tsiql:function(c,r){return c<r},fXLFO:function(c,r){return c&r},sRmCS:function(c,r){return c&r},uOsBM:function(c,r){return c&r},VaRKd:function(c,r){return c>=r},WnMXm:function(c,r){return c|r},LOAEU:function(c,r){return c|r},lEoTL:function(c,r){return c<<r},wRAQZ:function(c,r){return c<<r},BwSpa:function(c,r){return c<r},pldFw:function(c,r){return c<r},cuquD:t(546),GlPan:function(c,r){return c>>r},TgCKW:function(c,r){return c===r},DLmmJ:function(c,r){return c&r},PrnRb:function(c,r){return c&r},pLsqD:function(c,r){return c|r},AKBAD:function(c,r){return c>>r},Qmuek:function(c,r){return c|r},AfckK:function(c,r){return c|r},aSbOT:function(c,r){return c&r},CUWgn:function(c,r){return c>>r},utNoD:function(c,r){return c|r},AtFQH:function(c,r){return c|r},Yvryj:function(c,r){return c>>r},EjHrJ:function(c,r){return c|r},Gxyrf:function(c,r){return c-r},ZEJJm:function(c,r){return c==r},ZgbVt:t(1314),HikJp:function(c,r){return c(r)},TWiOl:function(c,r,o,l){return c(r,o,l)},eRKBv:function(c,r){return c==r},aFqSi:function(c,r){return c instanceof r},GrWYO:t(628),Cknbh:function(c,r){return c!=r},XYUXH:function(c,r){return c instanceof r},KVavV:"applicat"+t(551),JVSqa:function(c,r){return c!==r},lsDON:"ZbvhT",HZtrb:t(825),ZtSdC:t(1711),zCYed:t(449),VKqVM:t(563)+t(1137),hVFSl:t(274)+"ascript",WOlqg:function(c,r){return c+r},idnAx:t(406),hAALA:t(1780)+"ack=fron"+t(1626)+"P",PZqXq:t(1722),ENXDF:"yUcFV",RaaHN:t(1707),rUdcl:function(c,r,o){return c(r,o)},mNkgO:"message_id",vPkAN:t(1033),zumyj:function(c,r){return c|r},BLUeE:function(c,r){return c<<r},SxaIF:function(c,r){return c<<r},uAmUZ:function(c,r){return c|r},aLkbx:function(c,r){return c|r},OPKMI:"PYgxR",bkSZF:"sBCFj",eKPzK:function(c,r){return c>r},algCh:function(c,r){return c||r},aSnTg:function(c,r){return c>>>r},bnomw:function(c,r){return c===r},AkMSs:t(855),lsHvF:function(c,r){return c|r},XxxRO:function(c,r){return c>>>r},ZEBNd:function(c,r){return c<<r},fYdKW:function(c,r){return c===r},wweqM:function(c,r){return c<r},PZxrx:function(c,r){return c<r},LYvcK:function(c,r){return c<r},nDGMr:function(c,r){return c<r},HEhga:function(c,r){return c&r},isbMy:function(c,r){return c|r},kVTWs:function(c,r){return c|r},ZInOP:function(c,r){return c>>>r},HwicI:function(c,r){return c>>>r},UmiBf:function(c,r){return c+r},hLMPM:function(c,r){return c!==r},VrSfG:function(c,r){return c|r},AjZRT:function(c,r){return c>>>r},Xnlli:function(c,r){return c&r},jKeQB:function(c,r){return c>>>r},HHtIp:function(c,r){return c!==r},sMHYW:function(c,r){return c&r},ehCTm:function(c,r){return c!==r},eVXOO:function(c,r){return c+r},nTCpT:function(c,r){return c&r},UrKsT:function(c,r){return c>>>r},mNVRv:function(c,r){return c!==r},IYUtz:function(c,r){return c|r},DjwJV:function(c,r){return c>>>r},pfjTR:function(c,r){return c!==r},vLzdS:function(c,r){return c|r},ppiDz:t(1058),OxWrH:t(1460),WOIYJ:function(c,r){return c||r},Tzrqy:function(c,r){return c||r},ooRBU:function(c,r){return c===r},hbnyS:t(999),vIYAN:"DyiQg",qkXVt:function(c,r){return c||r},LlDNL:t(1489)+t(732)+"et=utf-8",UnZrQ:t(1592)+t(551)+t(1680)+t(840),evZyd:function(c,r,o,l){return c(r,o,l)},SUNCg:function(c,r){return c!==r},pNwOu:"YnxFI",jKdFf:function(c,r,o,l){return c(r,o,l)},QiOJG:function(c,r){return c&&r},raxan:t(1412),vQiyw:t(1684),HPEeV:t(699),hLWqm:function(c,r){return c||r},NwVUa:function(c,r){return c||r},BgcbI:function(c,r){return c||r},ENeqe:t(531)+t(294)+"d",NCANR:function(c,r,o){return c(r,o)},pfPQq:t(1593),JaFvG:function(c,r){return c(r)},Emaaz:function(c,r){return c!==r},fgKso:t(852),PpyzI:function(c,r){return c(r)},gMsDk:t(615)+"er_qos",PkSyY:function(c,r,o,l){return c(r,o,l)},zBFrE:t(615)+t(769)+"k",KKWkv:t(615)+t(930)+"sgid",rOfTP:t(605),LSbWN:function(c,r){return c&&r},NKgaV:t(1553),esiYo:function(c,r){return c instanceof r},FYSsp:function(c,r){return c instanceof r},uDWgJ:"binary",EICZB:function(c,r){return c(r)},VNeSi:function(c,r){return c+r},yleSh:function(c,r){return c|r},tZqmQ:function(c,r){return c===r},AHVls:"BxWyC",OoaQo:t(489),EmonN:function(c,r){return c(r)},fShuk:function(c,r){return c+r},IpHjN:function(c,r){return c+r},GqqHc:t(418)+t(971)+t(1362),NUyEZ:t(506),iosnf:t(1023),qaGMK:function(c,r){return c>r},qKUSa:t(775)+t(1616)+"e",BmjYe:function(c,r){return c&r},dwVgt:"1|3|0|2|4",ULBON:function(c,r){return c+r},zUxhw:function(c,r){return c<r},bJLiY:function(c,r){return c+r},XvSca:function(c,r){return c<<r},rNHyd:function(c,r){return c+r},mJJKg:function(c,r){return c+r},tNHrw:function(c,r){return c|r},QkOOv:function(c,r){return c+r},GdAaJ:function(c,r){return c<<r},MfauZ:function(c,r){return c+r},LzAUb:function(c,r){return c>>>r},qIsdM:function(c,r){return c+r},QGdwO:function(c,r){return c&r},akxUR:function(c,r){return c+r},ckUhV:function(c,r){return c>>>r},iYkuZ:function(c,r){return c&r},UNZjH:function(c,r){return c>>>r},pKWPm:t(509),MvXHg:function(c,r){return c+r},rmxWl:function(c,r){return c(r)},YnPKX:function(c,r,o,l){return c(r,o,l)},JXIew:function(c,r){return c<<r},UaStp:function(c,r){return c|r},IhiSC:function(c,r){return c<<r},ozDwi:function(c,r){return c&r},QIuOP:function(c,r){return c<r},TVqSw:function(c,r){return c===r},QpToE:"htEkf",WetDV:t(1594),ZSySs:function(c,r){return c<r},wLBDB:function(c,r){return c===r},homgK:t(1620),iRhEI:function(c,r){return c(r)},cMoqk:t(1371)+"ervice",SRMZD:t(358)+t(1752),rQUgn:t(514),nBucs:function(c,r){return c(r)},EKCdN:function(c,r){return c(r)},TBzdT:t(773),eOlFp:function(c,r,o){return c(r,o)},xSvZh:function(c,r,o){return c(r,o)},Elhup:function(c,r,o){return c(r,o)},nJaBM:function(c,r,o,l){return c(r,o,l)},HXDdA:function(c,r,o){return c(r,o)},YGSev:t(1493)+t(1714),jdgAz:"FILE_NOT_EXIST",gfACM:function(c,r,o){return c(r,o)},aHxnx:t(1074),mhnXk:function(c,r,o,l){return c(r,o,l)},znhNd:t(456),CpUCG:t(1598),Yowmh:function(c,r,o,l){return c(r,o,l)},arBsf:function(c,r){return c(r)},xqMhH:function(c,r){return c===r},xBsND:t(517),rNKWl:function(c,r){return c(r)},rQdBW:function(c,r){return c===r},LWPZS:t(1408),mQQPc:t(250),bSQfy:"x_fronti"+t(1570),PXKjC:function(c,r){return c(r)},xGOEQ:t(383)+"s",GXWro:t(1028)+t(1333)+"e",kfrtD:function(c,r,o){return c(r,o)},qHWrU:t(1028)+t(254)+"ue",zDVqz:function(c,r){return c>r},wKksE:t(1788),UyZbm:t(599),pzSdg:function(c){return c()},VBEtQ:function(c,r){return c!==r},qHAem:t(766),QvobA:function(c,r){return c===r},ttRPe:function(c){return c()},BoXKs:function(c,r){return c||r},LvjWc:t(1016),Klhll:function(c,r){return c(r)},UuTXC:function(c,r){return c!==r},vxCcE:function(c){return c()},lkpmI:function(c,r){return c===r},PtjBd:function(c,r){return c!==r},hnAcJ:t(618),ZytQY:function(c,r){return c===r},rbXgi:function(c){return c()},wJKWT:function(c,r,o){return c(r,o)},gtAPF:t(621)+t(774)+"s",wmoqG:t(796),IWpEs:function(c,r){return c===r},OYmXK:"rqZwM",EkOHq:t(1229),rOOYZ:function(c,r,o,l){return c(r,o,l)},GzHNO:function(c,r,o){return c(r,o)},UDnDJ:t(1285),nAuOy:function(c,r,o){return c(r,o)},kGHbG:t(1388)+t(791),xJhTG:t(842),xOLwH:function(c,r){return c/r},ueZBT:t(554),UXpyl:t(273)+"rovide v"+t(918),RrgUk:"please p"+t(1614)+t(881)+", WebSoc"+t(603)+"tructor is undefined",keVOR:function(c,r){return c(r)},ZNLbW:function(c,r){return c===r},HzPTp:t(1062),dXypP:"opAhT",eTvAA:t(1550)+t(907)+" reconnect",gjfBO:t(709),KKtqh:t(288),BOelW:"pageshow",BAtzQ:"pagehide",rsfjp:t(1339)+"0",IzayX:t(1586),RpHKv:t(365),eBIdw:t(585),kPfao:t(479),bxTNN:function(c,r){return c==r},tJrMC:t(765),kDDQo:t(822),YRaJN:t(265)+"d",fvFUG:function(c,r){return c||r},HLKro:t(273)+t(1172)+t(371)+"viceID o"+t(591),sFgjm:t(291),LmYZA:function(c,r,o){return c(r,o)},ZAQJd:"fws_1.0.0",gPODv:function(c,r,o){return c(r,o)},cPOnL:function(c,r){return c>r},KZZfZ:function(c,r){return c-r},UmMTh:function(c,r){return c(r)},qJqbB:t(1097),CvBHl:t(1561)+">",BEvhN:function(c,r){return c-r},fWrod:function(c,r){return c>r},zWtpK:function(c,r){return c===r},aRAWs:t(1577),RvFUi:function(c,r,o){return c(r,o)},sMNMQ:function(c,r){return c!==r},KpToE:t(484),hHjqB:t(1337),xVHQL:t(612),hNSqH:"VYcJk",bPbGo:t(1261),eDzVL:function(c,r,o){return c(r,o)},JWUdm:t(1214)+t(672)+t(1562)+"g",JxQbI:"send_ack",MAGiS:function(c,r,o,l){return c(r,o,l)},tiwJd:"FMGKL",aGhyQ:function(c,r){return c<r},orExK:function(c,r){return c&r},BIeZS:function(c,r){return c&r},QNNEj:function(c,r){return c<r},xpJxG:function(c,r){return c<<r},PcHsn:function(c,r){return c&r},yuEzx:function(c,r){return c&r},aKqUo:function(c,r){return c&r},ONSuS:function(c,r){return c+r},HzHUv:function(c,r){return c!==r},aDJUO:"RHqMw",AheHB:t(1587)+"2",tJeAH:function(c,r,o){return c(r,o)},RZIIv:t(303),kbPms:t(1040),NltNA:function(c,r,o){return c(r,o)},OwoJg:function(c,r){return c===r},eaVuM:t(938),zBrhT:t(1737),MFlNE:function(c,r,o){return c(r,o)},vXTNd:t(1648)+t(857)+t(1246)+t(1178),ndjKP:function(c,r){return c|r},ZxoDT:function(c,r){return c<<r},qXiHU:function(c,r){return c<<r},GgYAr:function(c,r){return c<<r},EPwAK:function(c,r){return c&r},XvtlR:function(c,r){return c&r},qZEbo:t(1499),sShbh:t(1542),jdHUo:function(c,r){return c==r},ZgKOL:function(c,r){return c===r},IkTsp:t(1201),kAQLO:function(c,r){return c+r},cuWZT:t(1529),RElYo:t(823),VibQP:"7|2|4|3|5|6|0|1",yFUbc:t(906)+t(246)+"y closed",SDROS:t(906)+t(1006)+t(1502)+"nitialized",BZvqg:"please provide a valid d"+t(1038)+t(412)+t(1367)+t(389)+t(500)+t(1057),YVRqL:function(c,r){return c==r},UbTHY:t(570),EUrkW:function(c,r){return c!=r},YIbVA:t(273)+t(545)+t(1104)+t(567),diwoX:function(c,r){return c(r)},rCgEG:function(c,r){return c===r},HykAP:t(1535),XIdti:t(290),knZEu:t(1094),fOmBl:function(c,r){return c==r},mryWc:function(c,r){return c!==r},RckNv:"manual reconnect"+t(1396),ZpAge:function(c,r){return c!==r},qzpgy:t(696),NOHDC:function(c,r){return c instanceof r},eKMtp:function(c,r){return c instanceof r},iiWsd:t(621)+t(1693)+"t",tkwdx:function(c,r,o){return c(r,o)},zIqQF:function(c,r){return c!==r},tFngZ:"PdfGI",CfwqW:t(749),oFrfS:function(c,r){return c*r},nnpfW:function(c,r){return c===r},EMozf:"Window",mzXls:function(c,r){return c!=r},rKsfZ:function(c,r){return c===r},edPsj:function(c,r){return c!=r},EgbFu:t(1234),gQmwS:function(c,r){return c===r},fspVN:"Dedicate"+t(1297)+"lobalScope",nqxOC:function(c,r){return c!=r},jiWxI:function(c,r){return c===r},OmUON:function(c,r){return c===r},DwYJH:t(646)+t(1509)+t(403),sZHVO:function(c,r){return c!=r},uhNiZ:function(c,r){return c!=r},dvKfn:function(c,r){return c===r},UqCUE:function(c,r){return c!=r}};Zt.r(Me),Zt.d(Me,{FWS:()=>Tm,CustomErrorEvent:()=>Ll,createCloseEvent:()=>vt,ReconnectEvent:()=>Ol,createErrorEvent:()=>pt,decodedFrame:()=>gn,createOpenEvent:()=>Ul,CustomCloseEvent:()=>Nl,createReconnectEvent:()=>Fa,FrontierMessageEvent:()=>Bl,encodeFrame:()=>Yt,createMessageEvent:()=>zl,OpenEvent:()=>Fl,ErrorCode:()=>wn,Event:()=>mr,MessageEvent:()=>Ml});let n="";function i(c=""){let r=t,o="02",l=""+Date.now(),h=n||(n=e[r(1186)](f,c)),w=Math[r(1230)]()[r(1260)](16).slice(-6);return e[r(1607)](e[r(1607)](e[r(281)](o,l),h),w)}function s(){let c=t;return e[c(281)](e.Sxibh(1e4,Date[c(1287)]()),Math[c(620)](e.PAiyx(1e4,Math[c(1230)]())))}function a(c){let r=t;return e[r(892)](e[r(927)],e.IRBQR)?e[r(1607)](Array(8)[r(833)]("0"),e.trkgH(parseInt,c,10)[r(1260)](2))[r(753)](-8):_0x37621e.objectStoreNames[1]?void 0:_0x51d861[r(686)+r(1690)](_0x10d26f[r(686)+r(1380)][0])}function d(c){let r=t;return e[r(1607)](e[r(1778)](Array,4)[r(833)]("0"),e.trkgH(parseInt,c,2)[r(1260)](16))[r(753)](-4)}function u(c){let r=t,o=c.split(/\./)[r(414)](w=>a(w)),l=[];return l[0]=e[r(1309)](d,e[r(1299)](o[0],o[1])),l[1]=e[r(1186)](d,o[2]+o[3]),[e[r(1455)],e[r(1455)],e[r(1455)],e[r(1455)],e[r(1455)],r(1443),l[0],l[1]][r(833)]("")}function f(c){let r=t,o=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(c),l=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[r(1654)](c);return o?e[r(481)](u,c):l?e[r(1778)](x,c):e.PvDfk}function x(c){let r=t,o="",l=[],h=0,w=0,_=!0,S=e[r(1455)];if(e[r(1530)](c[r(1126)]("::"),-1)){let g=c[r(1054)]("::");for(let L=0;e[r(812)](L,g.length);L++){let B=g[L];if(e[r(828)](B.indexOf(":"),0)){let W=B[r(1054)](":");_&&(h=W[r(1601)]),w+=W.length;for(let ne=0;e[r(812)](ne,W[r(1601)]);ne++)if(e[r(708)](4,W[ne].length)){let J=S.substring(0,e.CepBg(4,W[ne][r(1601)])),Ge=J[r(817)](W[ne]);l.push(Ge)}else l[r(1029)](W[ne]);_=!1}else{if(e[r(892)](4,B[r(1601)])){let W=S.substring(0,e[r(1727)](4,B[r(1601)])),ne=W[r(817)](B);l[r(1029)](ne)}else l[r(1029)](B);_&&(h+=1),w+=1,_=!1}}let O="";for(let L=0;L<e[r(1791)](8,w);L++)O=O[r(817)](S);for(let L=0;e[r(668)](L,l[r(1601)]);L++)e[r(1679)](L,h)?(o=o.concat(O),o=o[r(817)](l[L])):o=o.concat(l[L]);return o}{let g=c.split(":");for(let O=0;e[r(1720)](O,g[r(1601)]);O++){let L=g[O];if(g[O].length!==4)if(e[r(892)](e.IaKSd,e.IaKSd)){let B=_0x14f7c2(e[r(577)],{message:this["_formatE"+r(807)+r(735)](_0x1aa917)});this.emit(e[r(577)],B);let W=e[r(1448)](_0x16a249,e.GHFrr,{reason:this[r(1410)+r(807)+r(735)](_0x2c2af8)});this[r(249)](e[r(454)],W)}else{let B=S[r(703)+"g"](0,4-g[O][r(1601)]),W=B[r(817)](L);o=o[r(817)](W)}else o=o[r(817)](L)}return o}}function p(c,r){let o=t,l={SsNUJ:function(_,S,g){return e[j(1158)](_,S,g)}},h=c.key;e[o(1708)](void 0,h)&&(e.BDgWf(xe,r,10),e[o(523)](C,r,h));let w=c[o(689)];e[o(892)](void 0,w)&&(e[o(892)](e.Xcvqu,e.XZmlm)?(xe(r,18),e[o(1252)](C,r,w)):(l[o(1761)](_0x1ef34f,_0x25acdc,66),l[o(1761)](_0x5f2f3e,_0x5d53b8,_0x1b61de[o(1601)]),_0x2fabbd(_0xfeefe5,_0x3d46ea)))}function m(c){let r=t,o={lITKx:e[r(1567)],aWzpD:e[r(763)]};if(e[r(1176)]!==e[r(1176)]){let l=_0x5c8b9b(o[r(675)],{message:o.aWzpD});this[r(282)+r(1597)]&&this[r(282)+r(1597)](l)}else{let l={};e:for(;!e.aKwNL($,c);){let h=e.cHCHG(de,c);switch(e[r(1136)](h,3)){case 0:break e;case 1:l[r(1634)]=e.BUQIq(Se,c,e[r(1144)](de,c));break;case 2:l[r(689)]=e.trkgH(Se,c,de(c));break;default:e.trkgH(T,c,e[r(1558)](7,h))}}if(e[r(1679)](void 0,l[r(1634)]))throw new Error(e[r(1197)]);if(e.ZCmxM(void 0,l[r(689)]))throw new Error(r(1697)+r(355)+r(408)+r(689));return l}}function b(c){let r=t;if(e.tAYfj(e[r(1356)],r(944))){let o=e[r(1300)](P);return e[r(1095)](y,c,o),e.rwzCn(N,o)}else return _0x1487e4?.[r(1610)](o=>o[r(1634)]===_0x9fa30a)?.[r(689)]}function y(c,r){let o=t,l={hxssG:function(Ie,we,it){return e[j(1179)](Ie,we,it)},UuQgg:e[o(454)],MZPmo:function(Ie,we){return e[o(1053)](Ie,we)},tAgQH:e[o(1353)],nKwsW:function(Ie,we){return Ie===we},uXcRY:o(686)+o(1380),StFEn:e[o(417)]},h=c[o(283)];h!==void 0&&(e[o(1792)](xe,r,8),e[o(1448)](dt,r,h));let w=c[o(743)];w!==void 0&&(e.NzqPr(xe,r,16),e.Zzmqk(dt,r,w));let _=c[o(661)];_!==void 0&&(e[o(1649)](xe,r,24),e.nILNk(dt,r,R(_)));let S=c.method;S!==void 0&&(e[o(523)](xe,r,32),e[o(1422)](dt,r,e[o(714)](R,S)));let g=c[o(1170)];if(e.IGetO(void 0,g))for(let Ie of g)if(e.WdZWe(e.uBVZT,e[o(1289)])){let we=this[o(1108)+o(1037)]?.getCurrentEndpoint(),it=this[o(848)]["reconnectInterce"+o(1399)](_0x52a0a9[o(250)],_0x289f0f[o(1137)]);this[o(874)+o(788)+o(680)](l[o(1041)](_0x3e7a2f,l[o(520)],{code:1006,reason:_0x3329b6.reason||o(1146)+o(1264)+"d, unkno"+o(779)+o(295)+"ame: "+we,willReconnect:it})),it&&this[o(470)]();return}else{e[o(940)](xe,r,42);let we=e[o(972)](P);e[o(1404)](p,Ie,we),e[o(1095)](xe,r,we.limit),e[o(1095)](q,r,we),e.Nyngp(D,we)}let O=c["payloadE"+o(1123)];O!==void 0&&(e[o(1179)](xe,r,50),C(r,O));let L=c[o(328)+o(1724)];L!==void 0&&(e.OZHQC(xe,r,58),C(r,L));let B=c[o(752)];e[o(1391)](void 0,B)&&(xe(r,66),e.UiUYn(xe,r,B[o(1601)]),ae(r,B));let W=c[o(875)];if(e[o(1708)](void 0,W))if(e.jDAHn(o(1347),o(431)))e[o(1649)](xe,r,74),e.nILNk(C,r,W);else{let Ie=e[o(534)].split("|"),we=0;for(;;){switch(Ie[we++]){case"0":if(_0x46850d[o(647)])return _0xc3d75[o(647)](_0x3e5695,_0x266798)+_0x5d26dc;continue;case"1":if(!_0x4a8233)return _0x1c849c;continue;case"2":if(e[o(851)](_0x38619f[o(1601)],40))return _0x10f2c9(_0x2b52a0,_0x3995b9,_0x1019b4)+_0x2052f0;continue;case"3":if(_0x941c29[o(913)+"e"])return e[o(1276)](_0x22d150[o(913)+"e"](_0x38ff62,_0xacedbf),_0x2f188a);continue;case"4":return e[o(1607)](e.bjviV(_0x1fd27b,_0x54d780,_0x5c99a7,_0x3efda0),_0x423dec)}break}}let ne=c[o(1576)+o(831)];e[o(837)](void 0,ne)&&(e.RkIOU(xe,r,82),e[o(1051)](C,r,ne));let J=c[o(1105)];J!==void 0&&(e[o(942)](xe,r,90),e[o(1622)](C,r,J));let Ge=c.frameType;if(Ge!==void 0)if(e[o(1679)](e.Vpkyp,e.wCeiH)){if(iAyrhn[o(1681)](_0x37d6e0,_0x54d59a)){if(_0x363b67===iAyrhn[o(1615)])return _0xdee49f[o(843)](_0x4b4d09);if(iAyrhn.nKwsW(_0x135cd4,iAyrhn[o(1525)]))return _0x12b0d9[o(686)+"oreNames"]||_0x434798[o(843)](_0x3164d0);if(_0x5d73aa===iAyrhn.StFEn)return _0x106100["objectSt"+o(1380)][1]?void 0:_0xb62a93[o(686)+o(1690)](_0x570400[o(686)+o(1380)][0])}return _0x26a94f(_0x2af86e[_0x36a663])}else e[o(1792)](xe,r,96),dt(r,R(Ge))}function v(c){return e[t(1778)](I,z(c))}function I(c){let r=t,o={sQqta:function(h,w){return h!==w}},l={};e:for(;!e.oaBpS($,c);){let h=de(c);switch(e[r(1136)](h,3)){case 0:break e;case 1:l.SeqID=e.WuDQQ(Rt,c,!0);break;case 2:l[r(743)]=Rt(c,!0);break;case 3:l.service=e[r(1144)](de,c);break;case 4:l.method=de(c);break;case 5:if(e[r(708)](e.UYxFD,e[r(1578)])){let w=e[r(799)](A,c);(l[r(1170)]||(l.headers=[]))[r(1029)](e[r(1309)](m,c)),c[r(1470)]=w;break}else{if(oyhqDw[r(632)](4,_0x2ec6b0[r(1601)])){let w=_0x12575f[r(703)+"g"](0,4-_0x280d28[r(1601)]),_=w[r(817)](_0x554685);_0x262300.push(_)}else _0x2bf338[r(1029)](_0x3c9c32);_0x2be96a&&(_0x377bd9+=1),_0x4cdf85+=1,_0x5f46c9=!1}case 6:l[r(1070)+r(1123)]=e[r(635)](Se,c,e[r(799)](de,c));break;case 7:l[r(328)+r(1724)]=Se(c,e.rwzCn(de,c));break;case 8:l.payload=e.RGCqh(ce,c,e[r(584)](de,c));break;case 9:l[r(875)]=e[r(635)](Se,c,de(c));break;case 10:l[r(1576)+r(831)]=e[r(940)](Se,c,e[r(1778)](de,c));break;case 11:l[r(1105)]=e[r(776)](Se,c,de(c));break;case 12:l[r(1269)+"e"]=de(c);break;default:T(c,e.PAZem(7,h))}}if(e[r(1030)](void 0,l[r(283)]))throw new Error(e[r(419)]);if(e.kVpRO(void 0,l[r(743)]))throw new Error(e[r(1141)]);if(e[r(1679)](void 0,l[r(661)]))throw new Error(e[r(610)]);if(e[r(725)](void 0,l[r(317)]))throw new Error(r(1697)+r(355)+" field: method");return l}function A(c){let r=t,o=de(c),l=c[r(1470)];return c[r(1470)]=c[r(723)]+o,l}function T(c,r){let o=t;switch(r){case 0:for(;128&e.oaBpS(F,c););break;case 2:e.NzqPr(V,c,e[o(1107)](de,c));break;case 5:e[o(776)](V,c,4);break;case 1:e.kydcY(V,c,8);break;default:throw new Error(e[o(1299)](e[o(1397)],r))}}function R(c){let r=t;return c|=0,{low:c,high:e[r(715)](c,31),unsigned:c>=0}}let E=[];function P(){let c=t,r=E[c(760)]();return r?(r[c(723)]=r[c(1470)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(c){E[t(1029)](c)}function z(c){let r=t;return e[r(1497)](e[r(1305)],e[r(1305)])?{bytes:c,offset:0,limit:c[r(1601)]}:!!this._qosDB}function N(c){let r=t,o=c.bytes,l=c.limit;return o[r(1601)]===l?o:o[r(728)](0,l)}function V(c,r){let o=t;if(e[o(1619)](e.LOkBH,e[o(1447)])){if(e[o(1530)](e[o(347)](c[o(723)],r),c.limit))throw new Error(e[o(810)]);c.offset+=r}else return this._socket[o(494)]}function $(c){let r=t;return c[r(723)]>=c[r(1470)]}function se(c,r){let o=t,l=c[o(439)],h=c[o(723)],w=c[o(1470)],_=e[o(1177)](h,r);if(e[o(1530)](_,l[o(1601)])){let S=new Uint8Array(e.yevHu(2,_));S[o(926)](l),c[o(439)]=S}return c.offset=_,_>w&&(c[o(1470)]=_),h}function Q(c,r){let o=t,l=c[o(723)];if(e.cxjjc(e[o(281)](l,r),c[o(1470)]))throw new Error(o(784)+o(445));return c[o(723)]+=r,l}function ce(c,r){let o=t,l={Ahnry:function(h,w){return e.FFzKP(h,w)}};if(e[o(1391)](e[o(1221)],e[o(1162)])){let h=e[o(1404)](Q,c,r);return c.bytes[o(728)](h,e[o(1386)](h,r))}else{let h={WSQPo:function(w,_){let S=o;return qYgnHo[S(530)](w,_)},vTvvB:function(w,_){let S=o;return qYgnHo[S(530)](w,_)}};return function(...w){let _=o;return _0x377ed5[_(275)](h[_(1452)](_0x50309f,this),w),h[_(641)](_0x4613e7,_0x1c6a46[_(843)](this))}}}function ae(c,r){let o=t,l=se(c,r[o(1601)]);c[o(439)][o(926)](r,l)}function Se(c,r){let o=t,l={TKSSS:function(O,L){return e[j(1642)](O,L)},oxAnl:function(O,L){return e[j(1558)](O,L)}},h=e[o(1252)](Q,c,r),w=String[o(1125)+o(450)],_=c[o(439)],S="\uFFFD",g="";for(let O=0;e.OwzcJ(O,r);O++){let L=_[e.FQQgv(O,h)],B,W,ne,J;if((128&L)===0)g+=e[o(1107)](w,L);else if(e[o(1679)](224&L,192))e[o(339)](e[o(886)](O,1),r)?g+=S:(B=_[e[o(1687)](e[o(1642)](O,h),1)],e.UisUj(192&B,128)?g+=S:(J=e.GVdeH(e[o(1456)](e[o(1220)](31,L),6),e[o(1558)](63,B)),J<128?g+=S:(g+=e[o(714)](w,J),O++)));else if(e[o(342)](e[o(1020)](240,L),224))if(e[o(1091)](e[o(886)](O,2),r))g+=S;else{if(e[o(832)](e[o(310)],e[o(1329)]))return _0x1764c4[o(491)+"8"]?{value:_0x328696[o(491)+"8"](_0x58161e),offset:l[o(1740)](_0x5133fb,1)}:{value:l.oxAnl(255,_0x3dd2d1[_0x54b9c9]),offset:_0x460630+1};B=_[e[o(1138)](e[o(1142)](O,h),1)],W=_[e[o(1131)](e[o(1517)](O,h),2)],e[o(1708)](e[o(267)](B|e[o(1456)](W,8),49344),32896)?g+=S:(J=e[o(1492)](e[o(1047)](e[o(1456)](e.SNhKb(15,L),12),e.PAZem(63,B)<<6),e[o(1348)](63,W)),J<2048||e[o(1190)](J,55296)&&e[o(764)](J,57343)?g+=S:(g+=e[o(799)](w,J),O+=2))}else if(e[o(510)](e[o(1020)](248,L),240))if(e[o(1091)](O+3,r))g+=S;else if(e[o(374)]===e.hsFWL){let{SeqID:Ge,LogID:Ie,service:we,LogIDNew:it,method:mi}=_0x304353[o(1480)];this[o(1385)]({SeqID:Ge,LogID:Ie,LogIDNew:it,service:we,method:mi,headers:[{key:e[o(437)],value:"1"},{key:e[o(1225)],value:e[o(532)](it,"")},{key:e.TZjRv,value:"0"}]})}else B=_[e[o(1474)](e.KKQqZ(O,h),1)],W=_[e[o(1131)](e[o(898)](O,h),2)],ne=_[e.FPKTS(O,h)+3],e.HHlMJ((e.YTuSh(B,e[o(1456)](W,8))|ne<<16)&12632256,8421504)?g+=S:(J=e.GVdeH(e[o(1746)](e[o(1271)](e[o(1220)](7,L),18),e.PNTfl(e[o(1032)](63,B),12))|e[o(1456)](e.yTwnM(63,W),6),e.XroIz(63,ne)),e[o(1560)](J,65536)||e.vfGev(J,1114111)?g+=S:e[o(1619)](e[o(1307)],e[o(1316)])?(J-=65536,g+=e[o(631)](w,e.VqPpQ(e.nWImc(J,10),55296),e[o(281)](e[o(770)](1023,J),56320)),O+=3):this.on(_0x2fc5c6,_0x1324ca));else g+=S}return g}function C(c,r){let o=t;if(e[o(1140)](e[o(830)],e[o(1754)]))return _0x3094bd[o(1638)](_0x209c64),!1;{let l=r.length,h=0;for(let S=0;S<l;S++){let g=r[o(951)+"At"](S);e[o(333)](g,55296)&&e.UiGlB(g,56319)&&e[o(668)](e[o(768)](S,1),l)&&(g=e[o(529)](e.suGGJ(e[o(1456)](g,10),r[o(951)+"At"](++S)),56613888)),h+=e[o(625)](g,128)?1:e[o(668)](g,2048)?2:g<65536?3:4}e[o(942)](xe,c,h);let w=e[o(271)](se,c,h),_=c[o(439)];for(let S=0;e[o(485)](S,l);S++){let g=r[o(951)+"At"](S);e[o(333)](g,55296)&&g<=56319&&S+1<l&&(g=e.QGmbp(e[o(1386)](e[o(1524)](g,10),r[o(951)+"At"](++S)),56613888)),e[o(581)](g,128)?_[w++]=g:(g<2048?_[w++]=e[o(446)](e[o(1450)](g,6),31)|192:(e[o(1215)](g,65536)?_[w++]=e[o(1450)](g,12)&15|224:(_[w++]=e[o(1746)](e.NTXZH(g,18)&7,240),_[w++]=e[o(1232)](e.gdUQm(g,12),63)|128),_[w++]=e[o(899)](g,6)&63|128),_[w++]=e[o(1047)](e[o(1558)](63,g),128))}}}function q(c,r){let o=t,l=e[o(1422)](se,c,r[o(1470)]),h=c[o(439)],w=r.bytes;for(let _=0,S=r.limit;e[o(1720)](_,S);_++)h[_+l]=w[_]}function F(c){let r=t;return c[r(439)][e[r(1095)](Q,c,1)]}function pe(c,r){let o=t,l=e[o(776)](se,c,1);c[o(439)][l]=r}function de(c){let r=t;if(e[r(1360)](e[r(1203)],e.fnKIt)){let o=0,l=0,h;do h=e[r(1186)](F,c),e[r(625)](o,32)&&(l|=e[r(1608)](e[r(598)](127,h),o)),o+=7;while(e.wFZON(128,h));return l}else return!!this[r(826)]}function xe(c,r){let o=t;for(r>>>=0;e[o(1430)](r,128);)e[o(1179)](pe,c,e[o(1492)](e[o(421)](127,r),128)),r>>>=7;e[o(1004)](pe,c,r)}function Rt(c,r){let o=t,l=0,h=0,w=0,_;if(_=e[o(1144)](F,c),l=e.NhNff(127,_),e[o(742)](128,_))if(e[o(892)](o(1423),e[o(1400)])){if(_=e[o(714)](F,c),l|=e[o(1524)](e.TDQSa(127,_),7),e[o(1343)](128,_)&&(_=e[o(1778)](F,c),l|=e[o(1501)](127,_)<<14,e[o(1540)](128,_)&&(_=F(c),l|=e[o(827)](127&_,21),e[o(1558)](128,_)&&(_=F(c),h=e[o(770)](127,_),e.FSfNx(128,_)&&(_=e.cHCHG(F,c),h|=e.nedjv(e[o(1343)](127,_),7),e.DBQiQ(128,_)&&(_=e[o(315)](F,c),h|=e[o(827)](e[o(446)](127,_),14),e.grzaV(128,_)&&(_=F(c),h|=e[o(654)](e[o(267)](127,_),21),e[o(1540)](128,_)&&(_=e.SBSRz(F,c),w=e[o(607)](127,_),e[o(1381)](128,_)))))))))if(e[o(892)](e[o(835)],e.BtrTl))_=e[o(584)](F,c),w|=(127&_)<<7;else return this[o(826)][o(490)]}else return this[o(826)]?.[o(490)];return{low:l|h<<28,high:h>>>4|e.RTDbu(w,24),unsigned:r}}function dt(c,r){let o=t,l=e[o(1136)](r[o(1662)],0),h=e[o(257)](r[o(1662)]>>>28|e.DiyVx(r[o(758)],4),0),w=e[o(257)](r[o(758)],24),_=e.OrUQk(0,w)?e[o(891)](0,h)?e[o(581)](l,16384)?e[o(341)](l,128)?1:2:e.ctPHc(l,2097152)?3:4:e[o(341)](h,16384)?e.ctPHc(h,128)?5:6:e[o(485)](h,2097152)?7:8:e.wYvIc(w,128)?9:10,S=e[o(635)](se,c,_),g=c.bytes;switch(_){case 10:g[e[o(1142)](S,9)]=e.PAZem(w>>>7,1);case 9:g[e[o(718)](S,8)]=_!==9?e[o(1746)](128,w):e[o(607)](127,w);case 8:g[S+7]=e[o(837)](8,_)?e.LcbTn(e[o(257)](h,21),128):e[o(1686)](e[o(1115)](h,21),127);case 7:g[S+6]=e[o(1785)](7,_)?e[o(1581)](h,14)|128:e[o(278)](h>>>14,127);case 6:g[e[o(1517)](S,5)]=e[o(1466)](6,_)?e[o(574)](e.qKZpx(h,7),128):e[o(421)](e[o(257)](h,7),127);case 5:g[S+4]=_!==5?e[o(1746)](128,h):e[o(386)](127,h);case 4:g[e.suGGJ(S,3)]=e[o(1130)](4,_)?e[o(405)](e[o(1581)](l,21),128):e.YAefo(l>>>21,127);case 3:g[e[o(957)](S,2)]=e[o(438)](3,_)?e.UslYT(e[o(1303)](l,14),128):e.pVIbi(l,14)&127;case 2:g[e[o(1150)](S,1)]=e.YyFXK(2,_)?e[o(405)](e.skrkL(l,7),128):e[o(1789)](l>>>7,127);case 1:g[S]=e.WzjAj(1,_)?128|l:e.RKewe(127,l)}}function gn(c){return e.SBSRz(v,c)}function Yt(c){return e[t(325)](b,c)}let mn=65536,zn=e[t(247)],Dt=e.oFrfS(mn,mn),ze=e[t(1073)](Dt,Dt),De=ze/2,xt=String.prototype[t(951)+"At"];class te{constructor(r,o,l){let h=t;this[h(1330)]=!0,this[h(1662)]=e[h(626)](0,r),this[h(758)]=e[h(319)](0,o),this[h(854)]=!!l}static[t(1330)](r){return r&&e[t(536)](!0,r.isLong)}static[t(597)](r,o,l){return new te(r,o,l)}static fromBytes(r,o,l){let h=t;return l?te[h(1547)+h(636)](r,o):te["fromByte"+h(1112)](r,o)}static[t(1547)+t(636)](r,o){let l=t;return new te(r[0]|e[l(654)](r[1],8)|e[l(1163)](r[2],16)|e[l(1524)](r[3],24),e[l(626)](e[l(841)](e[l(399)](r[4],e.RTDbu(r[5],8)),e.OQbbh(r[6],16)),r[7]<<24),o)}static[t(1547)+t(1112)](r,o){let l=t;return new te(e[l(941)](e[l(1191)](e[l(827)](r[4],24),r[5]<<16),e[l(1253)](r[6],8))|r[7],e[l(1064)](e[l(1492)](e[l(654)](r[0],24),r[1]<<16)|e.CNWGC(r[2],8),r[3]),o)}static fromHash(r){let o=t;return e[o(725)](r,zn)?Dl:new te(e[o(1208)](e[o(1559)](xt[o(553)](r,0),e[o(827)](xt.call(r,1),8))|e[o(654)](xt.call(r,2),16)|xt[o(553)](r,3)<<24,0),e[o(1393)](e[o(1492)](e[o(496)](e[o(332)](xt[o(553)](r,4),xt[o(553)](r,5)<<8),e[o(1429)](xt[o(553)](r,6),16)),xt[o(553)](r,7)<<24),0),!0)}[t(1171)](){let r=t;return String.fromCharCode(255&this[r(1662)],e[r(1540)](this[r(1662)]>>>8,255),e[r(630)](this[r(1662)],16)&255,this[r(1662)]>>>24,255&this.high,e[r(1546)](e[r(963)](this.high,8),255),e.FadQs(e[r(385)](this[r(758)],16),255),this[r(758)]>>>24)}static[t(1202)+"er"](r,o=!0){let l=t;if(e.SOLhd(isNaN,r))return o?Ug:Dl;if(o){if(e.MITwA(r,ze))return Gg}else{if(e.ArQKI(r,-De))return qg;if(e[l(1739)](r,1)>=De)return Hg}return te[l(597)](e[l(941)](e[l(1589)](r,Dt),0),e.FACSz(e[l(924)](r,Dt),0),o)}toNumber(){let r=t;return this[r(854)]?e[r(281)](e[r(1189)](e[r(1303)](this[r(758)],0),Dt),e[r(385)](this[r(1662)],0)):e[r(1142)](this[r(758)]*Dt,e[r(521)](this[r(1662)],0))}isZero(){let r=t;return e[r(536)](0,this[r(758)])&&e.JcEMG(0,this[r(1662)])}add(r){let o=t;te[o(1330)](r)||(r=te.fromNumber(r));let l=e[o(306)](this[o(758)],16),h=65535&this[o(758)],w=e[o(1181)](this[o(1662)],16),_=65535&this[o(1662)],S=e[o(1584)](r[o(758)],16),g=e[o(770)](65535,r.high),O=e[o(1115)](r.low,16),L=e[o(267)](65535,r[o(1662)]),B=0,W=0,ne=0,J=0;return J+=e[o(1241)](_,L),ne+=J>>>16,J&=65535,ne+=e[o(1645)](w,O),W+=e.RyKKL(ne,16),ne&=65535,W+=e[o(1797)](h,g),B+=e[o(1136)](W,16),W&=65535,B+=e[o(518)](l,S),B&=65535,te[o(597)](e.QRoKn(ne,16)|J,e.QRoKn(B,16)|W,this[o(854)])}[t(1782)](r){let o=t;return te[o(1330)](r)||(r=te[o(1202)+"er"](r)),e[o(1466)](this.unsigned,r[o(854)])&&this[o(758)]>>>31===1&&e[o(1025)](e.omsWS(r.high,31),1)?!1:this[o(758)]===r[o(758)]&&e[o(1030)](this[o(1662)],r[o(1662)])}[t(643)](){let r=t;return e[r(1030)](-1,this.low)&&e[r(832)](-1,this.high)?te[r(597)](0,0,this[r(854)]):this.low===-1?te[r(597)](0,this[r(758)]+1,this[r(854)]):te[r(597)](this[r(1662)]+1,this.high,this.unsigned)}[t(1034)](r){let o=t,l={piAef:e.zgqiK};if(e.FvOUT(e[o(280)],o(1490))){if(!this[o(1124)+o(1506)]()||this[o(279)+"osed"])return;this[o(1108)+o(1037)]?.[o(415)+o(811)+o(1257)](),this["_pingLos"+o(877)]?.[o(287)+"nter"](),this[o(1609)]?this[o(669)+o(1079)](1001,l.piAef,!0):this._connect()}else return r?this[o(559)+"E"]():this.toBytesBE()}toBytesLE(){let r=t,o=this.high,l=this[r(1662)];return[e[r(604)](255,l),e[r(498)](e.qKZpx(l,8),255),e[r(1077)](e[r(1175)](l,16),255),e[r(1613)](l,24),e[r(1433)](255,o),e[r(716)](e.mxbel(o,8),255),e.yKxLO(o>>>16,255),e[r(1584)](o,24)]}toBytesBE(){let r=t;if(e.YGpsB===e[r(1488)]){let o=_0x57678a[r(723)];if(e.FPKTS(o,_0x190f64)>_0x1db82d[r(1470)])throw new _0x850aac(e[r(1606)]);return _0x495651[r(723)]+=_0x1582be,o}else{let o=this.high,l=this[r(1662)];return[e[r(1208)](o,24),e[r(394)](e[r(1383)](o,16),255),e[r(366)](e[r(1115)](o,8),255),e.VrqEL(255,o),e[r(1696)](l,24),e[r(1686)](e[r(1584)](l,16),255),e[r(1613)](l,8)&255,255&l]}}}let Dl=new te(0,0,!1),Ug=new te(0,0,!0),Hg=te[t(597)](-1,2147483647,!1),Gg=te.fromBits(-1,-1,!0),qg=te[t(597)](0,-2147483648,!1);var wn=(function(c){let r=t,o=e[r(929)][r(1054)]("|"),l=0;for(;;){switch(o[l++]){case"0":c[c[e.BjxJY]=5003]=e[r(1352)];continue;case"1":c[c[e[r(1262)]]=5004]=e[r(1262)];continue;case"2":c[c[e[r(904)]]=5001]=e[r(904)];continue;case"3":c[c[e[r(324)]]=5002]=e[r(324)];continue;case"4":return c;case"5":c[c[r(252)+"OR"]=5005]=r(252)+"OR";continue}break}})({});class mr{constructor(r){let o=t;e[o(866)](e[o(1469)],e[o(1419)])?this.off(_0xfcc8a1,_0x45a906):(this[o(1292)]=r,this.target=null)}}class Ol extends mr{constructor(r,o){let l=t;super(r),this[l(1480)]=o&&o[l(1480)]||null}}class Ll extends mr{constructor(r,o){let l=t,h=e[l(455)].split("|"),w=0;for(;;){switch(h[w++]){case"0":this.colno=o&&o[l(448)]||0;continue;case"1":this[l(1480)]=o&&o[l(1480)]||"";continue;case"2":this.error=o&&o.error||null;continue;case"3":this[l(878)]=o&&o[l(878)]||0;continue;case"4":this[l(932)]=o&&o[l(932)]||"";continue;case"5":this[l(250)]=o&&o[l(250)]||5001;continue;case"6":super(r);continue}break}}}class Nl extends mr{constructor(r,o){let l=t;if(e[l(1776)]("SAxHz","ezMrn"))return this[l(826)]?.[l(843)](_0x1e4629);{let h=e[l(734)].split("|"),w=0;for(;;){switch(h[w++]){case"0":this[l(1760)+"nnect"]=o&&o["willReco"+l(750)]||!1;continue;case"1":this[l(250)]=o&&o[l(250)]||0;continue;case"2":this[l(296)]=o&&o[l(296)]||!1;continue;case"3":this[l(1137)]=o&&o[l(1137)]||"";continue;case"4":super(r);continue}break}}}}class Ml extends mr{constructor(r,o){let l=t;super(r),this[l(702)]=o&&o[l(702)]||null}}class Bl extends Ml{constructor(r,o){let l=t,h={Sinth:function(w,_){return e[j(1309)](w,_)},nOpsf:function(w,_){return e[j(297)](w,_)},LwjQZ:function(w,_){return w<<_},miqTi:function(w,_){return e[j(802)](w,_)}};e[l(471)]===e[l(471)]?(super(r),this.data=o&&o[l(702)]||null,this[l(1480)]=o&&o[l(1480)]||null):(_0x34c074=UWZHDN.Sinth(_0x208f07,_0x4168d1),UWZHDN[l(757)](_0x4ac08f,32)&&(_0x516687|=UWZHDN[l(1743)](UWZHDN[l(990)](127,_0x13d8bc),_0x3c4c57)),_0x391ab8+=7)}}class Fl extends mr{constructor(r,o){let l=t;super(r),this[l(702)]=o&&o[l(702)]||null}}function pt(c,{message:r,code:o,error:l}){return new Ll(c,{message:r,code:o,error:l})}function vt(c,{code:r,reason:o,wasClean:l,willReconnect:h}){let w=t;if(e.XZSDy===e[w(1773)])_0x434b56(_0x1b5e5f,96),e[w(622)](_0x554f66,_0xf28c29,e[w(711)](_0x51f876,_0xfb7695));else return new Nl(c,{code:r,reason:o,wasClean:l,willReconnect:h})}function zl(c,{data:r,message:o}){return new Bl(c,{data:r,message:o})}function Ul(c,{data:r}){return new Fl(c,{data:r})}function Fa(c,{message:r}){let o=t,l={sumhE:o(1480),NfPxJ:function(h,w,_){return e[o(423)](h,w,_)}};if(e[o(1744)]!==e[o(1268)])return new Ol(c,{message:r});this[o(249)](l[o(1658)],l[o(1021)](_0x3a49f2,l[o(1658)],{..._0x4fa419}))}class Hl{constructor(r,o){let l=t;this.endpoints=r,this[l(1328)+"es"]=o,this[l(377)+l(1554)]=0,this[l(967)+l(706)+"riesCount"]=0}[t(415)+t(811)+t(1257)](){let r=t;this["currentI"+r(1554)]=0,this[r(967)+r(706)+"riesCount"]=0}[t(1222)+"es"](){let r=t;this["currentE"+r(706)+"riesCount"]=0}[t(671)+t(1301)+"nt"](){let r=t;return this[r(497)+"s"][this[r(377)+"ndex"]]}["getCurre"+t(1301)+"ntTriesCount"](){let r=t;if(e.WdZWe(r(724),e[r(407)]))return this[r(967)+"ndpointT"+r(1322)+"t"];_0x388a63=e[r(1109)](e[r(347)](65536,e[r(919)](e.kHreC(1023,_0x3ff322),10)),e.FadQs(1023,_0x3961fe)),++_0x783d10,_0x42e2a1[_0x3862cc++]=e[r(319)](e[r(1768)](_0x30e15e,18),240),_0x1f41c5[_0x92138f++]=e.wAMZZ(e.nWImc(_0x2cd213,12)&63,128),_0x57064a[_0x1f26a6++]=e[r(1440)](_0x2ffeaf>>6,63)|128,_0x28154e[_0x2605ca++]=e[r(880)](63,_0x5761aa)|128}["checkRea"+t(1088)+"es"](){let r=t;return!!(e[r(767)](this[r(377)+r(1554)],this[r(497)+"s"][r(1601)])||e.fWxbC(this.currentIndex,e[r(727)](this[r(497)+"s"][r(1601)],1))&&e[r(258)](this[r(967)+r(706)+"riesCount"],this.maxRetries))}[t(909)+t(1398)+"ointReac"+t(1326)+t(477)](){let r=t;return e[r(510)](this[r(377)+r(1554)],this[r(497)+"s"][r(1601)])?!0:e[r(1569)](this["currentE"+r(706)+r(1322)+"t"],this[r(1328)+"es"])}["replaceBackupEnd"+t(1319)+"UpdateCo"+t(745)](){let r=t;return this[r(967)+"ndpointT"+r(1322)+"t"]=1,this[r(377)+r(1554)]++,this[r(497)+"s"][this["currentI"+r(1554)]]}[t(671)+t(1301)+t(1534)+t(1183)](){let r=t;return this[r(967)+"ndpointTriesCount"]++,this[r(671)+r(1301)+"nt"]()}}let wr=(e.Cknbh(e[t(443)],typeof globalThis)&&e.nnpfW(e[t(1081)],globalThis[t(1617)+t(1659)][t(1752)])||e[t(682)](t(1195)+"d",typeof window)&&e.rKsfZ(e[t(1081)],window[t(1617)+t(1659)][t(1752)]))&&e.edPsj(e.hbSWD,typeof document),Un=e.Cknbh(e[t(443)],typeof globalThis)&&(e[t(1629)](e[t(803)],globalThis["construc"+t(1659)][t(1752)])||e.gQmwS(e[t(1471)],globalThis["construc"+t(1659)][t(1752)]))&&e[t(818)](e[t(443)],typeof tt),pi=(e.whSQb(e[t(443)],typeof globalThis)&&e[t(853)](e[t(803)],globalThis["construc"+t(1659)][t(1752)])||e[t(443)]==typeof globalThis||e[t(719)](e[t(443)],typeof globalThis)&&!!globalThis["WeixinJS"+t(396)])&&e[t(443)]!=typeof wx,gi=e[t(980)](e[t(443)],typeof globalThis)&&(e[t(1784)](e[t(1471)],globalThis[t(1617)+t(1659)][t(1752)])||e[t(744)](t(1728)+"rkerGlob"+t(1612),globalThis[t(1617)+t(1659)][t(1752)])||e[t(1572)](e[t(1730)],globalThis["construc"+t(1659)][t(1752)]))&&e[t(1243)](e[t(443)],typeof self),jg=e[t(1211)](e[t(443)],typeof globalThis)&&e[t(424)](e[t(803)],globalThis[t(1617)+t(1659)].name)&&e[t(443)]!=typeof global&&e[t(1632)](t(1234),global["construc"+t(1659)].name)&&e.UqCUE(e[t(443)],typeof process)&&!!process.version;class za{constructor(){this._listeners={}}[t(249)](r,...o){let l=t,h=this[l(350)+"rs"][r];if(h)h[l(753)]()[l(398)](w=>w.fn[l(275)](w.ctx,o));else if(e.mePiD===r&&!this.onerror){let w=o[l(1601)]&&o[0];if(e[l(1665)](w,Error))throw w;let _=new Error(e[l(780)](l(1678)+l(1414),w?e[l(1687)](e.FPKTS(" (",w[l(1480)]),")"):""));throw _[l(354)]=w,w}return this}[t(966)](r,o){let l=t;if(e[l(515)](void 0,r))this[l(350)+"rs"]={};else if(e.ABsja(void 0,o))this._listeners[r]=null;else{let h=this[l(350)+"rs"][r];if(h)for(let w=0;e[l(975)](w,h[l(1601)]);)e[l(1572)](h[w].fn,o)?h.splice(w,1):++w}return this}on(r,o,l){let h=t;if(e[h(694)](e.uTzbX,e[h(285)]))try{this[h(826)]?.[h(1102)](),this[h(826)]=void 0}catch(w){_0x1dfe72.log(w)}else return(this._listeners[r]||(this[h(350)+"rs"][r]=[])).push({fn:o,ctx:l||this}),this}}class Kg extends za{["_formatE"+t(807)+t(735)](r){let o=t;return r.errMsg||r[o(1437)]?(o(883)+" "+(r[o(761)]||"")+" code: "+(r[o(1437)]||"")).trim():JSON[o(1481)+"y"](r)}constructor(r,o,l){let h=t;e[h(424)](e[h(1204)],e[h(1717)])?(_0x384cbb+=e[h(809)](_0x2f9858,_0x9aa164),_0x1c1590+=2):(super(),this._socket=null,pi&&wx.connectSocket&&(this._socket=wx["connectS"+h(986)]({url:r,protocols:o,header:l,fail:this[h(939)+h(1226)+h(984)][h(902)](this),success:this[h(939)+h(495)+h(588)+h(376)][h(902)](this)})),Un&&tt[h(912)+h(986)]&&(this[h(587)]=tt["connectS"+h(986)]({url:r,protocols:o,header:l,fail:this[h(939)+h(1226)+h(984)][h(902)](this),success:this[h(939)+"ocketSuc"+h(588)+h(376)].bind(this)})))}["_createSocketSuc"+t(588)+t(376)](){let r=t;if(e[r(511)](e[r(308)],r(834)))return new _0x521ab5(_0x43964d,{message:_0x506ad2});Promise.resolve()[r(1657)](()=>{this[r(651)+"steners"]()})}[t(939)+"ocketFailHandler"](r){let o=t,l={lDExt:function(h,w,_){return h(w,_)},vllPz:e[o(1663)],WSqDj:function(h,w){return e[o(462)](h,w)},Wgnof:e[o(372)],tjlIT:function(h,w,_){return e[o(1757)](h,w,_)},SxsCy:o(1148),eKZSI:e[o(454)]};if(e.KtnWk("pSqZT",e.dopIS))return this[o(1609)]?this._ws[o(805)+"pe"]:this[o(1228)+o(1724)];Promise.resolve()[o(1657)](()=>{let h=o,w={oqcKM:function(_,S,g){return l[j(1790)](_,S,g)},EiZnZ:l[h(674)]};if(l[h(867)](l[h(1063)],l[h(1063)])){let _=l[h(1147)](pt,l[h(1694)],{message:this[h(1410)+h(807)+h(735)](r)});this.emit(l[h(1694)],_);let S=l[h(1790)](vt,l[h(993)],{reason:this[h(1410)+"rrorMessage"](r)});this.emit(l[h(993)],S)}else this[h(249)]("open",w[h(1428)](_0x1ab2ad,w[h(558)],{..._0xd8ff0c,data:_0x36346f[h(761)]||""}))})}[t(651)+t(1685)](){let r=t,o={PclLz:function(l,h){return e.rGxfw(l,h)},LAViB:e[r(1523)],QoaAM:e[r(253)],VImiE:r(1148)};e[r(996)]!=="rEqPN"?sYOoOE.YdEvZ(_0x316f7f,sYOoOE[r(916)](_0xfc1dd2,_0x19a5b6[r(748)]),_0x415a87.oldVersion,_0x2d379d[r(1682)+"on"],sYOoOE[r(1227)](_0x548f8c,_0x28afb7[r(309)+r(729)])):(this[r(587)][r(1677)](l=>{let h=r,w={WMvRU:function(_,S){return e.Sxibh(_,S)},XFaEZ:function(_,S){return e.Tjfdg(_,S)},xgpas:function(_,S){return e[j(1002)](_,S)}};if(e[h(1013)]!==e[h(608)])this[h(249)](e.GAHwm,Ul(e[h(1663)],{...l,data:l[h(761)]||""}));else{let{initReconnectInterval:_,maxReconnectInterval:S,reconnectIntervalGrowFactor:g}=this._options,O=w.WMvRU(_,_0x4ef5fd[h(1250)](g,w[h(1132)](_0x157999,1)));return w.xgpas(O,S)?S:O}}),this[r(587)][r(1001)](l=>{let h=r;this[h(249)](e[h(454)],e[h(1689)](vt,e[h(454)],{...l}))}),this._socket[r(849)+"e"](l=>{let h=r;o.LAViB!==h(330)?(this[h(1330)]=!0,this.low=CiCZbH.PclLz(0,_0x312395),this[h(758)]=0|_0x44729a,this[h(854)]=!!_0x55d812):this[h(249)]("message",zl(o[h(726)],{...l}))}),this[r(587)].onError(l=>{let h=r;this[h(249)](o.VImiE,pt(o[h(1235)],{...l,message:l[h(761)]||""}))}))}[t(685)](r){let o=t,l={wsQzc:e.mePiD,SqHgd:function(h,w,_){return e[j(1420)](h,w,_)}};if(e.xEceg(r,Uint8Array)){let h=r.buffer[o(753)](r[o(560)+"et"],e[o(1302)](r[o(1700)+"th"],r.byteOffset));this[o(587)]&&this[o(587)][o(685)]({data:h,fail:w=>{let _=o;this[_(249)](e[_(577)],e[_(1095)](pt,e.mePiD,{message:this[_(1410)+"rrorMessage"](w)}))}})}else this[o(587)]&&this[o(587)][o(685)]({data:r,fail:h=>{let w=o;this[w(249)](l.wsQzc,l[w(740)](pt,l[w(1084)],{message:this[w(1410)+w(807)+"age"](h)}))}})}[t(1102)](r,o){let l=t;this._socket&&this[l(587)].close({code:r,reason:o})}[t(356)+t(1545)](r,o){this.on(r,o)}["removeEventListe"+t(468)](r,o){this[t(966)](r,o)}get readyState(){let r=t;return this[r(587)][r(1395)+"te"]}get[t(805)+"pe"](){return this[t(587)].binaryType}set[t(805)+"pe"](r){}get[t(494)](){let r=t;return this[r(587)][r(494)]}get[t(895)](){let r=t;return this[r(587)][r(895)]}get extensions(){let r=t;if(e.fijxO(e[r(444)],r(550)))this[r(1609)]&&this[r(1609)].close(_0x330723,_0x23a7cf);else return this._socket[r(712)+"ns"]}get[t(335)+t(1120)](){return 0}}function Wg(c,r){let o=t;if(r)return new r(c[o(494)],c[o(895)]);if(pi||Un)return new Kg(c.url,c[o(895)],c[o(1170)]);if(e[o(910)](wr,gi)&&e[o(818)](e[o(443)],typeof WebSocket)&&WebSocket)return new WebSocket(c[o(494)],c[o(895)+"s"])}function $g(c){let r=t;if(e.ffXaS(e.JWhRu,e[r(1153)]))_0x2b46cc.log(_0x118379);else{let o=e[r(565)][r(1054)]("|"),l=0;for(;;){switch(o[l++]){case"0":if(Un&&tt[r(912)+r(986)])return!0;continue;case"1":if(pi&&wx[r(912)+r(986)])return!0;continue;case"2":if(c)return!0;continue;case"3":return!1;case"4":if(e[r(1531)](wr,gi)&&e[r(818)](e[r(443)],typeof WebSocket)&&WebSocket)return!0;continue}break}}}function Gl(c,r,o){let l=t,h={DKOJo:function(S,g){return S(g)},qYSTK:e[l(1379)],iDMYK:function(S,g){return S<=g},joVmP:e[l(378)],ifZXS:function(S,g){return e[l(898)](S,g)}},w=-1;async function _(S){let g=l,O={JEQTi:function(L,B){return h[j(1291)](L,B)}};if(h[g(945)]===g(613))_0x442255[g(1266)+"JSONP"]=void 0,O.JEQTi(_0x1bfafa,"unknown "+g(1137));else return h[g(1354)](S,w)?Promise[g(1279)](new Error(h[g(1552)])):(w=S,S===o[g(1601)]?Promise[g(1364)]():o[S].bind(c)(r,_[g(902)](null,h.ifZXS(S,1))))}e[l(711)](_,0)}function ql(c){let r=t,o=0,l=0;for(let h=0;h<c[r(1601)];++h)l=c.charCodeAt(h),e[r(668)](l,128)?o+=1:e[r(482)](l,2048)?o+=2:e.FvOUT(e[r(1745)](64512,l),55296)&&e.sJCKT(e[r(1077)](64512,c[r(951)+"At"](e.RNVpK(h,1))),56320)?(++h,o+=4):o+=3;return o}function jl(c,r,o){let l=t;if(e[l(1775)](o-r,1))return"";let h="";for(let w=r;e[l(975)](w,o);)if(e[l(1512)]!==e[l(1512)])this[l(249)](l(1148),_0x7a68da),this[l(527)]&&this[l(527)](_0x43d0b1);else{let _=c[w++];if(_<=127)h+=String[l(1125)+l(450)](_);else if(_>=192&&e[l(1194)](_,224))h+=String[l(1125)+"Code"](e[l(270)](e.BVPqW(e[l(1232)](31,_),6),63&c[w++]));else if(_>=224&&e[l(440)](_,240))h+=String[l(1125)+l(450)](e[l(1484)](15,_)<<12|e[l(1599)](63,c[w++])<<6|e.uOsBM(63,c[w++]));else if(e[l(388)](_,240)){let S=e[l(681)](e[l(405)](e.LOAEU(e[l(815)](e[l(1077)](7,_),18),e[l(782)](e[l(1558)](63,c[w++]),12)),(63&c[w++])<<6),63&c[w++])-65536;h+=String[l(1125)+l(450)](55296+e[l(1127)](S,10)),h+=String[l(1125)+"Code"](e[l(1302)](56320,e.yKxLO(1023,S)))}}return h}function Ua(c,r,o){let l=t,h=o,w,_;for(let S=0;e[l(1775)](S,c[l(1601)]);++S)w=c.charCodeAt(S),e[l(792)](w,128)?r[o++]=w:e.pldFw(w,2048)?e[l(1441)](e[l(460)],e[l(460)])?_0x1d2934&&this[l(1286)+l(410)][l(1265)+l(400)+l(1533)](_0x5b7b9d):(r[o++]=e[l(1111)](w,6)|192,r[o++]=e[l(332)](e[l(366)](63,w),128)):e[l(1030)](e[l(716)](64512,w),55296)&&e.TgCKW(64512&(_=c[l(951)+"At"](e[l(718)](S,1))),56320)?(w=e[l(1642)](65536,e.DLmmJ(1023,w)<<10)+e.PrnRb(1023,_),++S,r[o++]=e[l(1415)](e[l(865)](w,18),240),r[o++]=e.Qmuek(e.sRmCS(e[l(715)](w,12),63),128),r[o++]=e[l(474)](e[l(1218)](e.CUWgn(w,6),63),128),r[o++]=e[l(467)](63&w,128)):(r[o++]=e[l(1564)](w>>12,224),r[o++]=e.Yvryj(w,6)&63|128,r[o++]=e[l(801)](e[l(598)](63,w),128));return e[l(1238)](o,h)}async function Kl(c){let r=t;if(e[r(1695)](e[r(1774)],typeof c)){let o=new Uint8Array(e[r(362)](ql,c));return e.TWiOl(Ua,c,o,0),o}return e[r(955)](c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c[r(327)],c[r(560)+"et"],c[r(1700)+"th"])}function Vg(c){let r=t;try{if(e[r(1441)](r(628),e[r(1705)])){if(e[r(483)](e[r(1774)],typeof _0x18a748)){let o=new _0x371ef9(_0x4ca418(_0x48623f));return e[r(1101)](_0xeff3e5,_0x3a8cfd,o,0),o}return e[r(755)](_0x2be4d2,_0x2db90d)?new _0x3315d2(_0x311174):new _0x18c7c4(_0x1a1ed8[r(327)],_0x39d3f7[r(560)+"et"],_0x55fd52.byteLength)}else return e.Cknbh(e[r(1774)],typeof c)&&(e[r(1485)](c,ArrayBuffer)||c.buffer&&c[r(327)]instanceof ArrayBuffer)||r(1314)!=typeof c?"":(JSON.parse(c),e[r(860)])}catch{return e.ZgbVt==typeof c?"text/plain;chars"+r(571):""}}let Zg=(c,r)=>{let o=t;if(e[o(522)](e[o(738)],e.HZtrb))switch(c){case e[o(887)]:case e[o(1014)]:return{[o(1519)+c]:1,"x-tt-env":r};default:return{}}else Ce["_miniNav"+o(1462)+o(1075)]=_0x1c9ee8,_0x1faa89?Ce._handleOnLine():Ce[o(756)+"ffLine"]()};class Jg{constructor(r){let o=t;this.maxLossCount=r,this[o(1224)]=0}[t(562)](){let r=t;this[r(1224)]++}[t(1325)+"chMaxCount"](){let r=t;return this[r(1224)]>=this["maxLossC"+r(472)]}[t(287)+t(813)](r=0){let o=t;this[o(1374)+o(472)]=r,this.count=0}}async function Yg(c){let r=t,o={LmnfZ:function(l,h){return e[j(315)](l,h)},VEfKT:e[r(1732)],oEfkz:r(476),rZKCh:e.hVFSl,ggNfd:function(l,h){return e[r(653)](l,h)},axSOq:e.idnAx,yMiwz:e.hAALA};return new Promise(l=>{let h=r,w={zEBQU:function(_,S){return o[j(897)](_,S)},dLRHJ:o[h(1096)]};if(!wr)return o[h(897)](l,h(563)+h(1137));try{let _=document[h(658)+h(1458)](o.oEfkz);window["frontier"+h(1011)]=S=>{let g=h;document.body[g(806)+g(1605)](_),window[g(1266)+g(1011)]=void 0,w[g(1035)](l,S&&S[g(321)]||w.dLRHJ)},_[h(1292)]=o[h(1413)],_[h(1639)]=o.ggNfd(c[h(1310)](/^ws/,o[h(1465)]),o.yMiwz);try{document[h(1435)][h(552)+"ild"](_)}catch{document[h(1435)][h(806)+"ild"](_)}}catch{window[h(1266)+h(1011)]=void 0,l(o.VEfKT)}})}function yn(c,r,o){let l=t;return!!c?.[l(1610)](h=>h[l(1634)]===r&&h[l(689)]===o)}function yr(c,r){let o=t;return c?.[o(1610)](l=>l[o(1634)]===r)?.[o(689)]}let Ha=null;async function Xg(){let c=t;return Ha||(Ha=Promise[c(1364)]()[c(1657)](Zt[c(902)](Zt,e[c(1116)]))),Ha}class Qg extends za{constructor(r,o){let l=t;super(),this[l(969)]=r,this[l(695)]=o,this[l(826)]=void 0,this[l(346)+l(1078)]=null}async[t(1675)](){await this[t(1514)]()}async[t(1514)](){let r=t,o={CxrXj:function(l,h){return e[j(339)](l,h)},ytkDz:function(l,h){return l!==h},dqunF:e[r(251)],BGMus:function(l,h,w){return e[r(329)](l,h,w)},FlyTl:e[r(1061)]};if(e[r(677)](e.vPkAN,"eLVVi"))return _0x1d96b5|=0,{low:_0x30b565,high:_0x45f27a>>31,unsigned:lcRgEx.CxrXj(_0x3a55cb,0)};if(this[r(826)])return;if(this[r(346)+r(1078)])return this["_initPro"+r(1078)];try{let l=this[r(969)],h=this._keyPath;this["_initPro"+r(1078)]=(async()=>{let w=r;if(e[w(832)](e[w(1039)],e[w(1039)])){let{openDB:_}=await e[w(1300)](Xg);this[w(826)]=await e.bjviV(_,w(1266)+"_"+l,1,{upgrade(S){let g=w;o[g(819)](o[g(299)],o[g(299)])?(this[g(1368)+"er"]&&_0x2e5b89[g(1086)+g(1350)+g(468)]("online",this[g(756)+g(1438)]),this._isBrowser&&_0x5ad3e9[g(1086)+g(1350)+g(468)](g(288),this[g(756)+g(665)]),this._isBrowser&&_0x31686b[g(1086)+"entListe"+g(468)](g(1152),this[g(1277)+g(1205)]),this[g(1368)+"er"]&&_0x305098["removeEventListe"+g(468)](g(1671),this[g(1277)+g(642)])):S[g(305)+g(1555)+"e"](l,{keyPath:h})}})}else this["_interva"+w(952)+"Id"]=null,this[w(947)+"l"]=36e5,this[w(826)]=o[w(659)](_0x5d0b98,w(925),o[w(1338)])})(),await this["_initPro"+r(1078)]}catch(l){console[r(1638)](l)}finally{this[r(346)+r(1078)]=null}}async[t(843)](r){let o=t;try{return await this[o(1514)](),this[o(826)]?.[o(843)](this[o(969)],r)}catch(l){console[o(1638)](l)}}async[t(926)](r,o){let l=t;return await this[l(1514)](),this[l(826)]?.[l(1392)](this[l(969)],r)}async[t(1239)](r){let o=t;try{return await this[o(1514)](),this[o(826)]?.delete(this[o(969)],r)}catch(l){console[o(1638)](l)}}async clear(){let r=t;try{return await this[r(1514)](),this[r(826)]?.[r(1476)](this._dbName)}catch(o){console[r(1638)](o)}}async[t(1526)](){let r=t;return await this._init(),this[r(826)]?.[r(1263)+"ys"](this._dbName)}async[t(1049)](){let r=t;return e[r(976)]!==r(1405)?_0x4dc439===_0x107545?_0x5f4be8:new _0x51d9eb(e[r(467)](e[r(1066)](_0x50c33f[r(553)](_0x5e5429,0),e[r(276)](_0x4e9286[r(553)](_0x32c0f9,1),8))|e[r(614)](_0x12097a[r(553)](_0x1f92d6,2),16),e[r(846)](_0x192e77.call(_0x30c6be,3),24))>>>0,e.uAmUZ(e[r(1206)](_0x4b50eb[r(553)](_0xbcccc3,4),_0x4336bf[r(553)](_0x1c3c61,5)<<8)|_0x4cebc9[r(553)](_0x1d05cd,6)<<16,_0xece93.call(_0x4486b1,7)<<24)>>>0,!0):(await this[r(1514)](),this[r(826)]?.getAll(this._dbName))}async[t(345)](){let r=t;try{this[r(826)]?.[r(1102)](),this[r(826)]=void 0}catch(o){console[r(1638)](o)}}get isReady(){let r=t;try{return e.bkSZF==="sBCFj"?!!this[r(826)]:_0x93e967?_0x555708[r(1547)+r(636)](_0x242459,_0x2ceca5):_0x1a52e0[r(1547)+r(1112)](_0x3d354a,_0x5a2f29)}catch(o){return console[r(1638)](o),!1}}}class em{constructor(r,o){let l=t;if(e[l(1304)]("bLjXW",e[l(289)]))this[l(1242)]=r,this[l(1290)]=o,this._qosDB=localStorage;else{let h={KOMfA:function(O,L){return O<L},Omcjq:function(O,L){return e[l(539)](O,L)},DIZeA:function(O,L){return e[l(809)](O,L)},AmPpb:function(O,L){return O+L},dvprf:function(O,L){return O&L}},w=e[l(1198)](_0x4aabe7,8192),_=e[l(746)](w,1),S=null,g=w;return function(O){let L=l;if(h.KOMfA(O,1)||h[L(670)](O,_))return h[L(1783)](_0x5c7c11,O);h[L(1160)](g,O)>w&&(S=h[L(1783)](_0x29883e,w),g=0);let B=_0xbed278[L(553)](S,g,g+=O);return h.dvprf(7,g)&&(g=(7|g)+1),B}}}async[t(1675)](){}get[t(1145)](){let r=t;if(e.TJrKv(e[r(1e3)],e.ppiDz))return r(1266)+"_"+this[r(1242)];{let o=e[r(1175)](_0x18fe58[r(1662)],0),l=e[r(746)](e[r(1539)](e.XxxRO(_0x3142e8.low,28),e[r(655)](_0x4183f2.high,4)),0),h=_0x46076e[r(758)]>>>24,w=e[r(401)](0,h)?e[r(891)](0,l)?e[r(1510)](o,16384)?o<128?1:2:e[r(341)](o,2097152)?3:4:e[r(1411)](l,16384)?e.LYvcK(l,128)?5:6:e[r(958)](l,2097152)?7:8:e.hTqwj(h,128)?9:10,_=e[r(1622)](_0x34dd4d,_0x5f1679,w),S=_0x49ac29[r(439)];switch(w){case 10:S[_+9]=e[r(640)](e[r(257)](h,7),1);case 9:S[e.FQQgv(_,8)]=e[r(708)](9,w)?e.isbMy(128,h):127&h;case 8:S[e[r(962)](_,7)]=e[r(1130)](8,w)?e[r(1072)](e.ZInOP(l,21),128):e[r(1071)](l,21)&127;case 7:S[e.UmiBf(_,6)]=e[r(917)](7,w)?e[r(1103)](e[r(797)](l,14),128):e.Xnlli(e[r(688)](l,14),127);case 6:S[e[r(1734)](_,5)]=w!==6?e[r(1581)](l,7)|128:e[r(607)](e[r(1581)](l,7),127);case 5:S[_+4]=e.HHtIp(5,w)?128|l:e[r(379)](127,l);case 4:S[e[r(886)](_,3)]=e[r(555)](4,w)?e[r(1206)](e[r(963)](o,21),128):e.zwRXm(o,21)&127;case 3:S[e[r(611)](_,2)]=w!==3?e[r(1492)](e[r(480)](o,14),128):e[r(935)](e[r(1515)](o,14),127);case 2:S[_+1]=e[r(1765)](2,w)?e.IYUtz(e[r(1284)](o,7),128):e[r(953)](o>>>7,127);case 1:S[_]=e[r(272)](1,w)?e[r(1236)](128,o):e[r(1628)](127,o)}}}async[t(843)](r){let o=t;if(e[o(987)]===o(1460)){let l=this[o(826)][o(847)](this._prefix);return JSON.parse(e[o(910)](l,"{}"))[r]}else return o(1266)+"_"+this[o(1242)]}async[t(926)](r,o){let l=t,h=this[l(826)][l(847)](this._prefix),w=JSON[l(690)](e.WOIYJ(h,"{}"));return w[o||r[this._pathKey]]=r,this[l(826)][l(1573)](this[l(1145)],JSON[l(1481)+"y"](w)),o||r[this[l(1290)]]}async[t(1239)](r){let o=t,l=this[o(826)][o(847)](this[o(1145)]),h=JSON[o(690)](e[o(629)](l,"{}"));return h[r]=void 0,this[o(826)][o(1573)](this[o(1145)],JSON[o(1481)+"y"](h))}async clear(){let r=t;return e.ooRBU(e[r(981)],e[r(687)])?null:this[r(826)][r(1476)]()}async[t(1526)](){let r=t,o=this[r(826)][r(847)](this._prefix),l=JSON[r(690)](e[r(538)](o,"{}"));return Object[r(1526)](l)}async[t(1049)](){let r=t;if(e[r(698)](e.pNwOu,e.pNwOu)){let o=e[r(955)](this[r(848)]["payloadE"+r(1123)],_0xebfc62)?{force:!!this[r(848)][r(1070)+r(1123)][r(965)],encoding:this[r(848)][r(1070)+r(1123)][r(268)]?this[r(848)][r(1070)+r(1123)][r(268)][r(1310)](/\s/g,"")["toLowerC"+r(461)]():""}:{force:!1,encoding:this[r(848)][r(1070)+"ncoding"]?this[r(848)][r(1070)+r(1123)].replace(/\s/g,"")[r(1602)+r(461)]():""},l=_0x359055[r(1070)+"ncoding"]?_0x5e7174[r(1070)+"ncoding"][r(1310)](/\s/g,"")[r(1602)+r(461)]():"",h=e[r(1053)](this[r(848)]["payloadT"+r(1724)],_0x2925c7)?{force:!!this[r(848)][r(328)+"ype"].force,type:this[r(848)]["payloadT"+r(1724)][r(1292)]?this[r(848)][r(328)+r(1724)].type[r(1310)](/\s/g,"")[r(1602)+r(461)]():""}:{force:!1,type:this[r(848)][r(328)+r(1724)]?this[r(848)][r(328)+"ype"].replace(/\s/g,"")[r(1602)+r(461)]():""},w=_0x408694[r(328)+"ype"]?_0xa40287[r(328)+"ype"][r(1310)](/\s/g,"")[r(1602)+r(461)]():"",_=h[r(965)]?h.type:w||h[r(1292)],S=o[r(965)]?o[r(268)]:l||o[r(268)],g=[e.LlDNL,e[r(860)],e[r(336)],e[r(1774)]],O=["none_none",r(1089)];this._options[r(420)+r(1557)+"extPayload"]&&g.includes(_)&&(!S||O[r(1306)](S))?_0x4068e2[r(473)+r(1098)]=e[r(1640)](_0x2bcae4,_0x458741[r(752)],0,_0x2b2a06[r(752)][r(1700)+"th"]):_0x195c07[r(473)+"oad"]=""}else{let o=this._qosDB.getItem(this._prefix),l=JSON.parse(e[r(629)](o,"{}"));return Object.values(l)}}[t(345)](){return Promise.resolve()}get[t(490)](){return!!this[t(826)]}}class tm{constructor(r,o){let l=t,h={HbSmj:function(w,_,S,g){return e[j(304)](w,_,S,g)},wSdUT:e.eIyHy,LBQTq:function(w,_){return e[j(1169)](w,_)},fJdxg:e[l(1225)],ZXixw:function(w,_){return w||_},MCfte:e[l(982)],ZBrQm:function(w){return e[l(1300)](w)}};if(e[l(739)]!==l(1412)){let{enableAutoAck:w}=this[l(848)],_=h[l(1445)](_0x8560de,_0x3091d9[l(1480)][l(1170)],l(605),"1"),S=h[l(1445)](_0x472318,_0x398676.message[l(1170)],h[l(1596)],"1"),g=_0x235096[l(553)](this,_0x131dbb);if(h.LBQTq(w,_)){let{SeqID:O,LogID:L,service:B,LogIDNew:W,method:ne}=_0x42b6e2[l(1480)];this[l(1385)]({SeqID:O,LogID:L,LogIDNew:W,service:B,method:ne,headers:[{key:h[l(1596)],value:"1"},{key:h[l(644)],value:h.ZXixw(W,"")},{key:h[l(1122)],value:"0"}]})}S&&!g[l(1442)]&&this["_dispatc"+l(1026)+l(1369)](_0x2feb07),h[l(1667)](_0x490e42)}else this[l(1242)]=r,this[l(1290)]=o,this[l(826)]=Un?tt:pi?wx:null}async openDB(){}get _prefix(){let r=t;return e[r(1463)]===e.HPEeV?this[r(967)+r(706)+r(1322)+"t"]:r(1266)+"_"+this[r(1242)]}async get(r){let o=t,l=this._qosDB[o(889)+o(624)](this[o(1145)]);return JSON[o(690)](l||"{}")[r]}async[t(926)](r,o){let l=t,h=this[l(826)].getStorageSync(this[l(1145)]),w=JSON[l(690)](h||"{}");return w[o||r[this[l(1290)]]]=r,this._qosDB[l(1312)+l(624)](this[l(1145)],JSON.stringify(w)),o||r[this._pathKey]}async[t(1239)](r){let o=t,l=this[o(826)][o(889)+"geSync"](this._prefix),h=JSON[o(690)](e[o(1251)](l,"{}"));return h[r]=void 0,this[o(826)][o(1312)+"geSync"](this[o(1145)],JSON[o(1481)+"y"](h))}async[t(1476)](){let r=t;return this[r(826)][r(1417)+"rageSync"]()}async[t(1526)](){let r=t,o=this[r(826)][r(889)+"geInfoSync"](this._prefix),l=JSON.parse(e[r(676)](o,"{}"));return Object[r(1526)](l)}async[t(1049)](){let r=t,o=this[r(826)][r(889)+"geInfoSync"](this._prefix),l=JSON[r(690)](e.NwVUa(o,"{}"));return Object.values(l)}[t(345)](){return Promise[t(1364)]()}get[t(490)](){return!!this._qosDB}}function Wl(c,r){let o=t;if(e[o(795)](Un,Un))return new tm(c,r);if(e.NwVUa(wr,gi)&&e[o(710)](e.hbSWD,typeof indexedDB))return new Qg(c,r);if(e[o(795)](wr,gi)&&e[o(818)](o(1195)+"d",typeof localStorage))return new em(c,r);throw new Error(e[o(1283)])}class nm{constructor(){let r=t;this[r(947)+r(952)+"Id"]=null,this[r(947)+"l"]=36e5,this[r(826)]=e[r(1155)](Wl,r(925),e[r(1061)])}async["_interva"+t(359)](){let r=t;e[r(568)](clearInterval,this[r(947)+"lTimeoutId"]),this["_interva"+r(952)+"Id"]=e[r(1792)](setInterval,()=>{let o=r;e[o(1466)](e.pfPQq,e[o(816)])?this[o(947)+o(359)]():this[o(896)+o(269)]()},this[r(947)+"l"])}async[t(1675)](){let r=t,o={BeBaB:e[r(577)],vDmGU:function(l,h,w){return l(h,w)}};await this[r(826)][r(1675)]().then(()=>{let l=r;e[l(544)]("ESoFT",e[l(1048)])?this[l(249)](YqdlNU[l(637)],YqdlNU[l(442)](_0x1e61fe,YqdlNU[l(637)],{message:this[l(1410)+l(807)+l(735)](_0x4bf3c5)})):this[l(947)+l(359)]()})}async[t(896)+t(269)](){let r=t;(await this[r(826)]?.[r(1049)]()||[])[r(991)](({timestamp:h})=>h<Date.now())[r(398)](h=>{let w=r;this._qosDB?.del(h[w(1129)+"id"])})}async[t(1239)](r){let o=t;return this._qosDB?.[o(1239)](r)}async[t(926)](r,o){let l=t;return this[l(826)]?.[l(926)]({message_id:r,timestamp:o})}async get(r){let o=t;return this._qosDB?.[o(843)](r)}async closeDB(){let r=t;e.PpyzI(clearInterval,this[r(947)+r(952)+"Id"]),await this[r(826)]?.closeDB()}get[t(490)](){let r=t;return this[r(826)]?.[r(490)]}}function Ga(c){let r=t,o=!!this[r(848)][r(1706)+"S"];if(!o)return{enabled:o,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(304)](yn,c[r(1480)][r(1170)],e.gMsDk,"2"),h=l&&yn(c[r(1480)][r(1170)],r(615)+r(1031)+"ck","1"),w=l&&e[r(1753)](yn,c[r(1480)][r(1170)],e[r(1355)],"1"),_=w?e.pTtRC(yr,c[r(1480)][r(1170)],e[r(1495)])?.[r(1054)](",")[r(991)](Boolean)||[]:[];return{enabled:o,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:w,ackMsgIds:_}}async function $l(){let c=t;return this[c(301)+"ger"]||(this[c(301)+c(261)]=new nm),this[c(301)+"ger"][c(490)]||await this[c(301)+"ger"][c(1675)](),this[c(301)+"ger"]}async function rm(c,r){let o=t,{enableAutoAck:l}=this._options,h=e.jKdFf(yn,c[o(1480)][o(1170)],e[o(1258)],"1"),w=yn(c[o(1480)].headers,o(1755),"1"),_=Ga.call(this,c);if(e[o(890)](l,h)){let{SeqID:S,LogID:g,service:O,LogIDNew:L,method:B}=c.message;this[o(1385)]({SeqID:S,LogID:g,LogIDNew:L,service:O,method:B,headers:[{key:e[o(437)],value:"1"},{key:e.dppxY,value:e[o(676)](L,"")},{key:o(1249),value:"0"}]})}w&&!_[o(1442)]&&this[o(874)+o(1026)+o(1369)](c),r()}async function im(c,r){let o=t;this[o(657)](e[o(416)],c[o(1480)]),r()}async function sm(c,r){let o=t,l=gn(await e[o(799)](Kl,c.data));try{if(e[o(1308)](l[o(752)],Uint8Array)){let h=e.FYSsp(this[o(848)][o(1070)+o(1123)],Object)?{force:!!this[o(848)][o(1070)+o(1123)][o(965)],encoding:this[o(848)][o(1070)+"ncoding"].encoding?this[o(848)][o(1070)+"ncoding"][o(268)][o(1310)](/\s/g,"")["toLowerC"+o(461)]():""}:{force:!1,encoding:this[o(848)][o(1070)+"ncoding"]?this._options.payloadEncoding[o(1310)](/\s/g,"")["toLowerC"+o(461)]():""},w=l["payloadE"+o(1123)]?l[o(1070)+o(1123)].replace(/\s/g,"")[o(1602)+"ase"]():"",_=this[o(848)]["payloadT"+o(1724)]instanceof Object?{force:!!this[o(848)][o(328)+o(1724)][o(965)],type:this[o(848)][o(328)+o(1724)].type?this[o(848)][o(328)+"ype"][o(1292)].replace(/\s/g,"")[o(1602)+o(461)]():""}:{force:!1,type:this[o(848)][o(328)+o(1724)]?this[o(848)][o(328)+o(1724)][o(1310)](/\s/g,"")[o(1602)+o(461)]():""},S=l[o(328)+o(1724)]?l[o(328)+o(1724)][o(1310)](/\s/g,"")[o(1602)+o(461)]():"",g=_[o(965)]?_.type:S||_[o(1292)],O=h[o(965)]?h[o(268)]:w||h[o(268)],L=[e.LlDNL,e[o(860)],e[o(336)],e[o(1774)]],B=[o(1003)+"e",e[o(260)]];this[o(848)][o(420)+"ansformT"+o(547)+"ad"]&&L[o(1306)](g)&&(!O||B.includes(O))?l[o(473)+o(1098)]=jl(l[o(752)],0,l[o(752)][o(1700)+"th"]):l[o(473)+o(1098)]=""}else l.textPayload=""}catch(h){l.textPayload="",console[o(1638)](h)}c[o(1480)]=l,e[o(972)](r)}function om(c,r,o){let l=t,h=o||8192,w=e[l(1192)](h,1),_=null,S=h;return function(g){let O=l;if(g<1||g>w)return e[O(1144)](c,g);e[O(1302)](S,g)>h&&(_=e[O(1701)](c,h),S=0);let L=r[O(553)](_,S,S+=g);return e[O(446)](7,S)&&(S=e.VNeSi(e[O(974)](7,S),1)),L}}let am=4294967295;function cm(c,r,o){let l=t;if(e[l(433)](e[l(583)],e.OoaQo))this[l(504)+l(1477)]=_0x3ce217;else return e[l(1375)](RangeError,e[l(704)](e[l(1177)](e[l(650)](e[l(1366)],c)+e[l(1691)]+(r||1),e[l(541)]),o))}function dm(c,r,o){let l=t;if(e[l(1099)](o,am))throw new Error(e[l(369)]);let h=3;for(;e[l(1430)](h,0);){let w=e.BmjYe(255,o);ja(w,c,e[l(1142)](r,h)),o>>>=8,h--}return e[l(898)](r,4)}function lm(c,r){let o=t,l=0,h=r,w=e.nFypX(r,4);for(;h<w;){let{value:_,offset:S}=e[o(423)](qa,c,h);h=S,l=e[o(827)](l,8)>>>0,l+=_}return{value:l,offset:w}}function um(c,r,o){let l=t,h=e[l(1498)][l(1054)]("|"),w=0;for(;;){switch(h[w++]){case"0":if(r[l(913)+"e"])return e[l(898)](r[l(913)+"e"](c,o),o);continue;case"1":if(!c)return o;continue;case"2":if(r.write)return e[l(684)](r[l(647)](c,o),o);continue;case"3":if(e[l(1248)](c[l(1601)],40))return e[l(1797)](Ua(c,r,o),o);continue;case"4":return e[l(1043)](e[l(1101)](Ua,c,r,o),o)}break}}function fm(c,r){let o=t,l=new te(e[o(1072)](e[o(270)](e.IYUtz(e[o(1647)](c[e[o(1482)](r,4)],24),c[r+5]<<16),c[e[o(1302)](r,6)]<<8),c[e[o(915)](r,7)]),e[o(1206)](e[o(256)](e[o(319)](e.QRoKn(c[e[o(392)](r,0)],24),e.GdAaJ(c[e[o(281)](r,1)],16)),c[e[o(1607)](r,2)]<<8),c[r+3]),!0);return r+=8,{value:l,offset:e[o(903)](r,8)}}function hm(c,r,o){let l=t,h=c[l(1662)],w=c[l(758)];return r[o]=e.LzAUb(w,24),r[e[l(920)](o,1)]=e[l(1175)](w,16)&255,r[o+2]=e[l(1115)](w,8)&255,r[e.bJLiY(o,3)]=e.QGdwO(255,w),r[e[l(1150)](o,4)]=e.bjrqD(h,24),r[e[l(1005)](o,5)]=e[l(351)](h,16)&255,r[e[l(962)](o,6)]=e[l(983)](e[l(582)](h,8),255),r[e[l(1177)](o,7)]=255&h,o+=8,o}function qa(c,r){let o=t;return c[o(491)+"8"]?{value:c[o(491)+"8"](r),offset:r+1}:{value:e[o(953)](255,c[r]),offset:r+1}}function ja(c,r,o){let l=t;if(e[l(1121)]!==e[l(1121)])_0x3644b2[l(926)](_0xb4a9ed,_0xcc4902),_0x3cf603[l(926)](_0x250705,_0x28cbc0);else return r[l(645)+"t8"]?r[l(645)+"t8"](c,o):r[o]=255&c,e[l(357)](o,1)}let xm=function(c){return new Uint8Array(c)},pm=e[t(1211)](e[t(443)],typeof Buffer)?Buffer[t(1117)+t(1272)]:e[t(1404)](om,xm,Uint8Array[t(1431)+"e"].subarray);(()=>{let c=t,r={GlWch:function(o,l){return e[j(1613)](o,l)},aqKTQ:function(o,l){return o&l},xFBrp:function(o,l){return o|l},jLtWA:function(o,l,h,w){return e.YnPKX(o,l,h,w)},RWrHw:function(o,l){return o|l},ByUkh:function(o,l){return e[j(1548)](o,l)},AgBKQ:function(o,l){return o&l},ZXRsR:function(o,l){return o<l},Nrqkw:function(o,l){return e.yleSh(o,l)},PVgKN:function(o,l){return e[j(404)](o,l)},heJcw:function(o,l){return o|l},yfRfS:function(o,l){return e[j(264)](o,l)},anJcN:function(o,l){return e[j(1745)](o,l)},jQuYF:function(o,l){return e[j(1192)](o,l)},KoFSt:function(o,l){return e.ozDwi(o,l)},AdHYX:function(o,l){return e[j(956)](o,l)},qwzRy:function(o,l){return o|l}};if(e[c(985)](e[c(1749)],e.WetDV))return _0x4d4e04&&(_0x5f2a6f=(0,_0x552df0[sYOoOE[c(1293)](_0x56f918,_0x2b6ec1)[0]])(_0x46fc66=0)),_0xc0046d;{let o=4294967295;return function(l,h,w=!0){let _=c,S=(_(1409)+"|7|5|0|10|8|9|2|6")[_(1054)]("|"),g=0;for(;;){switch(S[g++]){case"0":o=r[_(693)](o|r[_(1541)](127,l[h])<<21,0);continue;case"1":if(l[h++]<128)return{value:w?o:r[_(713)](0,o),offset:h};continue;case"2":if((h+=5)>l[_(1601)])throw h=l.length,r[_(1244)](cm,h,10,l[_(1601)]);continue;case"3":o=r[_(693)](r.RWrHw(o,r[_(1080)](r.AgBKQ(127,l[h]),7)),0);continue;case"4":o=r.AgBKQ(127,l[h])>>>0;continue;case"5":if(r.ZXRsR(l[h++],128))return{value:w?o:r[_(1751)](0,o),offset:h};continue;case"6":return{value:w?o:r[_(503)](0,o),offset:h};case"7":o=r[_(933)](o,r[_(1427)](r[_(1451)](127,l[h]),14))>>>0;continue;case"8":o=r[_(1618)](r[_(933)](o,r[_(1427)](r.KoFSt(15,l[h]),28)),0);continue;case"9":if(r[_(1505)](l[h++],128))return{value:w?o:0|o,offset:h};continue;case"10":if(l[h++]<128)return{value:w?o:r[_(1793)](0,o),offset:h};continue;case"11":if(r[_(373)](l[h++],128))return{value:w?o:r[_(1009)](0,o),offset:h};continue}break}}}})();let gm=16,Ka=32;function mm(c){let r=t,o={Ynpvz:function(w,_,S){return e[j(635)](w,_,S)},vwyZe:function(w,_){return e[j(1378)](w,_)},wBkvt:function(w,_){return w+_}},l=0,h={};for(let w=0;e[r(1378)](w,c[r(1601)]);w++)if(e[r(1629)](e.homgK,e[r(1167)]))h[c[w][r(586)+r(772)]]=e[r(1726)](ql,c[w]["cursor_n"+r(772)]),l+=e[r(1797)](14,h[c[w]["cursor_n"+r(772)]]);else{let _=XvIFzK[r(1487)](_0x18749e,_0x4934c9,_0x1fa419.limit),S=_0xc521f8[r(439)],g=_0x1ccd44[r(439)];for(let O=0,L=_0x10f166[r(1470)];XvIFzK[r(1710)](O,L);O++)S[XvIFzK[r(1068)](O,_)]=g[O]}return[l,h]}function Vl(c,r,o){let l=t,h={GvFug:l(661),lZPZS:l(1752),eNpkz:e[l(1733)],LNUHK:function(O,L,B,W){return e[l(304)](O,L,B,W)},arFwn:"header",JaVGi:e[l(1294)],OoKDx:e.rQUgn},[w,_]=e.nBucs(mm,c),S=e[l(1390)](pm,w),g=0;return c[l(398)](O=>{let L=l,B=("2|5|4|10"+L(1320)+L(998)).split("|"),W=0;for(;;){switch(B[W++]){case"0":console[L(1638)](h.GvFug,g);continue;case"1":console[L(1638)](h[L(950)],g);continue;case"2":console[L(1638)](h.eNpkz,O,O.service);continue;case"3":g=h[L(402)](um,O[L(586)+"ame"],S,g);continue;case"4":console[L(1638)](h[L(428)],g);continue;case"5":g=ja(0,S,g);continue;case"6":console[L(1638)](h[L(1133)],g);continue;case"7":g=h[L(402)](ja,_[O[L(586)+L(772)]],S,g);continue;case"8":g=h.LNUHK(hm,te[L(1202)+"er"](O[L(1361)]||r),S,g);continue;case"9":console.log(h.OoKDx,g);continue;case"10":g=dm(S,g,O.service||0);continue}break}}),{frameType:Ka,headers:[{key:l(1493)+l(1714),value:o}],payload:S}}function wm(c){let r=t;if(e[r(511)](e[r(1324)],e[r(1324)])){let o=this[r(826)][r(847)](this._prefix),l=_0x2ac661[r(690)](e.qkXVt(o,"{}"));return _0x5de214[r(590)](l)}else{let o=0,l=[];for(;o<c.byteLength;){let{offset:h}=e.eOlFp(qa,c,o);o=h;let w={cursor_name:"",cursor:0,service:0},{value:_,offset:S}=e[r(977)](lm,c,o);w.service=_,o=S;let{value:g,offset:O}=e[r(1351)](qa,c,o);o=O,w[r(586)+r(772)]=e[r(968)](jl,c,o,e[r(1645)](o,g)),o+=g;let{value:L,offset:B}=e[r(609)](fm,c,o);w[r(1361)]=L.toNumber(),o=B,l[r(1029)](w)}return l}}function ym(){let c=t;return{frameType:Ka,headers:[{key:e[c(1652)],value:e[c(970)]}],payload:void 0}}class _m{constructor(r,o,l){let h=t;this["_cursorN"+h(1418)]=r,this[h(504)+h(1477)]=o,this[h(1446)+h(1389)]=l,this._qosDB=e[h(576)](Wl,this[h(1444)+"ameSpace"],h(586)+h(772))}async[t(1675)](){await this._qosDB.openDB()}async[t(988)+"rs"](){let r=t;if(e.jDAHn(e[r(1676)],r(1074)))_0x49ef01(_0x2e03a5,10),_0x5650e8(_0x276183,_0x304c60);else{if(!this._qosDB[r(490)])return;let o=this[r(1446)+r(1389)],l=await this[r(826)].getAll();switch(console[r(1638)](r(1566)+r(349),l),o){case r(978):return l&&l[r(1601)]?e[r(721)](Vl,l,0,this[r(504)+r(1477)]):void 0;case e[r(1015)]:return;case e[r(1199)]:return l&&l.length?e[r(293)](Vl,l,0,this[r(504)+"ileName"]):e.yuxMm(ym)}}}async[t(926)](r,o,l){let h=t;return console.log("setdb",r,o,l),this[h(826)][h(926)]({cursor_name:r,cursor:o,service:l})}async[t(331)+"rs"](r){let o=t;if(e.xqMhH(e[o(1491)],"DVPTG")){let l=wm(r);for(let h of l)console[o(1638)](o(1036)+"r",l),await this._qosDB[o(926)](h)}else return e[o(1067)](_0x1437a6,_0x40ec87)}async[t(843)](r){let o=t;return(await this[o(826)][o(843)](r))?.cursor}async closeDB(){await this[t(826)].closeDB()}["updateCu"+t(400)+t(1533)](r){let o=t;this[o(504)+"ileName"]=r}get isReady(){let r=t;return this._qosDB[r(490)]}}let bm=t(1196)+t(426);async function Zl(c){let r=t;if(!this._options[r(1706)+"S"])return null;let{aID:o,fpID:l,messageStrategy:h}=this[r(848)],w=e.algCh(c,bm);try{return this[r(1286)+"anager"]?c&&this["_cursorM"+r(410)][r(1265)+r(400)+"Name"](c):this[r(1286)+r(410)]=new _m(l+"_"+o+"_"+w,w,h),this[r(1286)+r(410)].isReady||await this["_cursorM"+r(410)][r(1675)](),this[r(1286)+r(410)]}catch{return null}}async function Em(c,r){let o=t,l={zGPVz:function(h,w){return h(w)},MUaSi:function(h,w){return e[j(1177)](h,w)},CuQXR:function(h,w){return e[j(1459)](h,w)}};if(e[o(808)](e[o(556)],o(876)))_0x27d23c[_0x208b4b[_0x2ea3d8][o(586)+o(772)]]=QOcMQD.zGPVz(_0x58be47,_0x2494d0[_0x3f5c26].cursor_name),_0x49943e+=QOcMQD.MUaSi(14,_0xb8f790[_0x577c8c[_0x1b48b9][o(586)+"ame"]]);else{let h=yn(c[o(1480)][o(1170)],e[o(451)],"-1"),w=yn(c[o(1480)][o(1170)],e.eIyHy,"1"),_=yr(c[o(1480)][o(1170)],e[o(901)]),S=e.PXKjC(Number,e[o(940)](yr,c[o(1480)][o(1170)],"x_fronti"+o(1742)))||0,g=Ga[o(553)](this,c),O=yn(c[o(1480)].headers,e[o(705)],"2"),L=yr(c[o(1480)][o(1170)],e.GXWro),B=e[o(1544)](Number,e[o(572)](yr,c[o(1480)].headers,e[o(1046)]));if(g[o(1442)])return e.yuxMm(r);let W=g[o(861)+o(589)]?await $l[o(553)](this):null;if(e[o(1018)](c[o(1480)][o(661)],0)&&w&&!h||e[o(1530)](c[o(1480)][o(661)],0)){if(_&&g[o(861)+o(589)]&&W){if(!!!await W[o(843)](_))if(e.wKksE===e[o(1439)])this[o(874)+o(1522)+o(1741)](c),await W[o(926)](_,e[o(611)](Date[o(1287)](),S));else{let J={ODCXx:function(Ge,Ie){return QOcMQD.CuQXR(Ge,Ie)}};return function(Ge,...Ie){let we=o,it=_0x2bc79a[we(553)](_0x11bb88(this),Ge,...Ie);return _0x43c0b1[we(926)](it,Ge[we(1621)]?Ge[we(1621)]():[Ge]),J.ODCXx(_0x5cc62b,it)}}return e[o(1300)](r)}if(O)if(e[o(1083)]!==o(453)){let ne=await Zl.call(this);if(!ne)return this["_dispatc"+o(1522)+o(1741)](c),e.pzSdg(r);let J=await ne[o(843)](L)??-1;if(J<B)e.VBEtQ(o(1313),e[o(594)])?(this["_dispatc"+o(1522)+o(1741)](c),ne.set(L,B,c.message[o(661)])):(this.emit(e[o(253)],_0x3d4d81),this.onmessage&&this[o(1161)+"e"](_0x2eb41a));else throw new Error(o(1426)+o(858)+" cursor "+B+(" larger than loc"+o(1735)+"r ")+J);return r()}else return this[o(826)]["clearSto"+o(1590)]();return this[o(874)+"hMessageEvent"](c),e.yuxMm(r)}}}async function vm(c,r){let o=t,l=Ga.call(this,c);if(!l[o(861)+o(589)])return e[o(1300)](r);let h=await $l[o(553)](this);if(l[o(322)+"anupMess"+o(735)]&&l[o(979)+"s"][o(1601)])for(let w of l[o(979)+"s"])await h[o(1239)](w);e.gmLme(r)}async function Sm(c,r){let o=t,l=c[o(1480)].frameType===gm,h=e[o(731)](c.message[o(1269)+"e"],Ka);if(e.LSbWN(!l,!h))return r();let w=e.kfrtD(yr,c.message.headers,e[o(1652)]);if(!w)return e.ttRPe(r);let _=await Zl[o(553)](this,w);if(!_)return e.pzSdg(r);if(l){let S=await _[o(988)+"rs"](),g={frameType:S?.["frameType"],SeqID:te[o(1202)+"er"](this[o(1536)]++),LogID:te.fromNumber(this[o(848)][o(997)+"erator"]()),service:9e3,method:5,headers:S?.[o(1170)],payload:S?.[o(752)]},O=b(g);this[o(1609)]&&this._ws[o(1395)+"te"]&&this[o(1609)].send(O)}if(h){let S=c[o(1480)].payload;S&&_[o(331)+"rs"](S)}}let Im=async function(c,r){let o=t;if(e[o(1679)](e[o(893)],e[o(893)]))this[o(1332)]=!1,e.Klhll(clearTimeout,this[o(470)+o(1478)+o(1747)]),e[o(1300)](r);else{let l=this[o(826)][o(847)](this[o(1145)]);return _0x4e9bf3.parse(e[o(1600)](l,"{}"))[_0x29e75b]}},Am=async function(c,r){let o=t;if(!this[o(1609)]||e.UuTXC(this[o(1609)][o(1395)+"te"],this[o(1556)]))return e[o(255)](r);let{pingInterval:l}=this._options;this[o(1108)+o(1037)]?.["resetEnd"+o(811)+o(1257)]();for(let w=0;e.nDGMr(w,this._messageQueue.length);w++){let _=this[o(1446)+"Queue"][w];if(e[o(1010)](this._ws.readyState,this[o(1556)])&&e[o(1143)](null,_))o(618)===e[o(1500)]?(this[o(1609)]&&this[o(1609)][o(685)](_),this[o(1446)+o(844)][w]=null):(this.maxLossCount=_0x3cd173,this.count=0);else break}this["_message"+o(844)]=this[o(1446)+o(844)][o(991)](w=>!!w),this[o(1372)+o(533)+"Id"]=e.eOlFp(setTimeout,()=>this[o(1483)](),l),this["_dispatc"+o(1317)+"nt"](c),this[o(1368)+"er"]&&this[o(1609)]&&(this._ws.binaryType=this[o(1228)+o(1724)]);let h=this[o(1108)+o(1037)]?.[o(671)+o(1301)+"nt"]();this[o(657)](o(859)+h+o(778)),e.ttRPe(r)},km=async function(c,r){let o=t,l={rjZRq:function(h,w){return h===w},ZeOTZ:function(h,w,_){return h(w,_)}};if(e.ZytQY("BIMwy",o(519))){if(this[o(1609)]&&l[o(937)](this[o(1609)].readyState,this[o(785)+"NG"])){this[o(1731)+o(1156)](),this[o(1372)+"gTimeoutId"]=l[o(1787)](_0x4fcad8,this[o(1483)][o(902)](this),this._options["pingInte"+o(1273)]);return}if(!this._ws||this[o(1609)][o(1395)+"te"]!==this.OPEN)return void this["_handleR"+o(1597)]();this[o(1609)]&&this[o(1609)][o(685)]("hi"),this[o(1565)+o(879)+o(298)]=_0x5534c2(this["_handleR"+o(1597)+o(1165)][o(902)](this),this[o(848)][o(1582)+"outInterval"])}else{let h=this[o(1108)+o(1037)]?.[o(671)+o(1301)+"nt"]();this._debug("open "+h),e[o(992)](r)}};class Tm extends za{constructor(r){let o=t,l={ysbyq:function(S,g){return S===g},SvJLX:function(S,g,O){return e.GzHNO(S,g,O)},lQggt:e[o(577)],VeltI:"close",ozgHh:function(S,g){return e.pfjTR(S,g)},CzHYp:function(S,g,O){return e[o(1365)](S,g,O)},IlJIK:e[o(513)],bihlh:function(S,g,O){return e.nAuOy(S,g,O)}};super(),this[o(1764)+o(1462)+o(1075)]=!0,this._isBrowser=wr,this[o(793)]=jg,this[o(364)+"T"]=Un,this[o(1345)+"X"]=pi,this[o(314)+"r"]=gi,this["_message"+o(844)]=[],this["_endpoin"+o(1037)]=null,this[o(279)+o(994)]=!1,this[o(1228)+o(1724)]=e.kGHbG,this[o(470)+"Lock"]=!1,this["_connect"+o(1478)+o(1747)]=null,this[o(1565)+"ctTimeou"+o(298)]=null,this[o(1372)+"gTimeoutId"]=null,this[o(1536)]=0,this._isInit=!1,this[o(1646)]="",this[o(301)+o(261)]=null,this[o(1286)+o(410)]=null,this["_pingLos"+o(877)]=null,this[o(548)+"ls"]=e[o(1022)],this[o(869)]=3,this[o(785)+"NG"]=0,this[o(1556)]=1,this[o(1454)]=2,this._onOpen=S=>{let g=o;try{e[g(316)](Gl,this,S,[Im,Am,km])}catch(O){let L=e[g(1027)](pt,e[g(577)],{message:O[g(1480)],code:wn[g(252)+"OR"],error:O});this[g(874)+"hErrorEvent"](L)}},this[o(1323)+"ge"]=async S=>{let g=o,{pingInterval:O,pingFrequency:L}=this[g(848)];if((e[g(1572)]("hi",S.data)&&g(754)===L||g(554)===L)&&(this._clearPingTimer(),this[g(249)](e.gtAPF,e.wmoqG),this[g(1372)+g(533)+"Id"]=e.taZcw(setTimeout,this._ping[g(902)](this),O)),!e[g(458)]("hi",S.data))try{e[g(1143)](e[g(717)],e[g(1358)])?e[g(1315)](Gl,this,S,[sm,rm,vm,Sm,Em,im]):_0x1613ae.d=(B,W)=>{let ne=g;for(var J in W)_0x46fc21.o(W,J)&&!_0x4c48d4.o(B,J)&&_0x5226c8[ne(1092)+ne(1245)](B,J,{enumerable:!0,get:W[J]})}}catch(B){let W=e[g(622)](pt,e.mePiD,{message:B[g(1480)],code:wn[g(488)+"ERROR"],error:B});this["_dispatchErrorEv"+g(680)](W)}},this[o(1180)]=S=>{let g=o,O=this[g(1108)+"tManager"]?.[g(1325)+g(1088)+"es"](),L=this[g(1108)+g(1037)]?.[g(671)+"ntEndpoint"]();if(O&&!S[g(1480)]){let B=g(921)+L+(g(1045)+g(1336)+g(1254)+"ed");this["_dispatc"+g(856)+g(680)](pt(g(1148),{message:B,code:wn[g(1796)+g(1630)+"R"],error:S}));return}this[g(1609)]&&l.ysbyq(this[g(1609)].readyState,this[g(1556)])&&this[g(669)+"ect"](),this[g(874)+"hErrorEvent"](l[g(436)](pt,l[g(1611)],{message:S.message,code:wn[g(540)+g(1065)],error:S}))},this[o(302)]=async S=>{let g=o;this[g(525)+g(1209)](),this["_clearPi"+g(1156)](),this[g(501)+g(1056)+"rs"](),this[g(1609)]=null,this[g(470)+"Lock"]=!1;let O=this[g(1108)+g(1037)]?.[g(1325)+g(1088)+"es"]();if(!O&&this[g(1124)+g(1506)]()&&!this[g(279)+"osed"]){let L=this["_endpoin"+g(1037)]?.["getCurre"+g(1301)+"nt"](),B=this[g(848)][g(948)+"tInterce"+g(1399)](S[g(250)],S[g(1137)]);this["_dispatc"+g(788)+"ent"](l[g(436)](vt,l.VeltI,{code:1006,reason:S[g(1137)]||"connecti"+g(1264)+g(1401)+"wn reason, hostname: "+L,willReconnect:B})),B&&this._connect();return}if(l[g(266)](1e3,S[g(250)])&&this[g(279)+g(994)]){this["_dispatc"+g(788)+g(680)](l[g(320)](vt,l.VeltI,{code:1e3,reason:l.IlJIK})),this[g(1108)+g(1037)]?.["resetEnd"+g(811)+g(1257)](),this[g(1756)+g(877)]?.["resetCou"+g(813)]();return}if(S[g(250)]!==1e3&&O){let L=this[g(1108)+g(1037)]?.[g(671)+"ntEndpoint"](),B=S.reason;B||(B=await Yg(this[g(1646)])),B="connecti"+g(1264)+g(390)+B+(g(1128)+g(434))+L+(g(1007)+g(606)+g(465)),this[g(874)+g(788)+g(680)](l[g(277)](vt,l[g(1637)],{code:S[g(250)],reason:B}));let W="connect "+L+(" fail, m"+g(1336)+g(1254)+"ed");this["_dispatc"+g(856)+g(680)](pt(l.lQggt,{message:W,code:wn["MAX_RETR"+g(1630)+"R"]})),this[g(1108)+g(1037)]?.[g(415)+g(811)+"fig"](),this[g(1756)+"sCounter"]?.[g(287)+g(813)]();return}if(S[g(250)]!==1e3&&!S[g(1137)]){let L=this[g(1108)+"tManager"]?.[g(671)+g(1301)+"nt"]();this["_dispatc"+g(788)+g(680)](l[g(320)](vt,l[g(1637)],{code:S[g(250)],reason:g(1146)+g(1264)+g(1401)+g(779)+g(295)+"ame: "+L})),this["_endpoin"+g(1037)]?.[g(415)+g(811)+"fig"](),this[g(1756)+g(877)]?.[g(287)+"nter"]();return}this["_dispatc"+g(788)+g(680)](S),this[g(1108)+g(1037)]?.[g(415)+g(811)+g(1257)](),this[g(1756)+g(877)]?.[g(287)+g(813)]()},this[o(1453)]=null,this[o(527)]=null,this[o(1161)+"e"]=null,this[o(1766)]=null,this[o(282)+"econnect"]=null,this.onReceiveAck=null,this[o(1627)+"mediatelyReconnect"]=null,this[o(756)+o(1438)]=this[o(756)+"nLine"][o(902)](this),this[o(756)+o(665)]=this[o(756)+o(665)].bind(this),this[o(1277)+"ageHide"]=this._handlePageHide[o(902)](this),this[o(1277)+"ageShow"]=this["_handleP"+o(642)].bind(this),this[o(848)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[o(337)](1,0),service:0,logIDGenerator:s,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[o(1538)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.CpUCG,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:w}=r,_=Array[o(447)](h)?h:o(1314)==typeof h?[h]:[];if(!_||_[o(1601)]===0)throw new Error(e[o(989)]);if(!$g(w))throw new Error(e[o(343)]);Object[o(1503)](this._options,r),this[o(1108)+o(1037)]=new Hl(_,this[o(848)].maxRetries),this[o(1756)+o(877)]=new Jg(this[o(848)][o(263)+o(623)]),this._options[o(441)+o(870)]&&(this[o(1332)]=!0,this[o(470)]()),this[o(848)][o(1274)+o(338)+"nged"]&&(this[o(364)+"T"]||this[o(1345)+"X"]?this[o(430)+o(737)+"ange"]():this[o(1368)+"er"]&&this["_initGlo"+o(1513)+o(1545)]())}["_handleO"+t(1438)](){let r=t;this._options[r(1571)+r(427)+r(934)]||this[r(279)+r(994)]||this["_handleR"+r(1597)]()}[t(756)+t(665)](){let r=t,o={tVmGR:function(l,h,w){return l(h,w)},vBinj:function(l,h){return e[j(656)](l,h)}};if(e[r(1210)](e.HzPTp,e.dXypP))iflzQO[r(413)](_0x4e59a3,_0x3a9554,32),iflzQO[r(413)](_0x457661,_0xb89a48,iflzQO.vBinj(_0x596b47,_0xd1a501));else{this[r(1349)+r(1216)+"t"]();let l=e[r(1004)](Fa,e[r(1567)],{message:e[r(790)]});this["onStopImmediatel"+r(946)+"ct"]&&this[r(1627)+r(1311)+"yReconnect"](l)}}["_initGlo"+t(1513)+"Listener"](){let r=t;this[r(1368)+"er"]&&window[r(356)+r(1545)](e.gjfBO,this[r(756)+r(1438)]),this[r(1368)+"er"]&&window[r(356)+r(1545)](e[r(1763)],this["_handleO"+r(665)]),this[r(1368)+"er"]&&window[r(356)+r(1545)](r(1152),this._handlePageHide),this[r(1368)+"er"]&&window["addEvent"+r(1545)](e[r(1382)],this["_handleP"+r(642)])}[t(1340)+t(1513)+"Listener"](){let r=t;this._isBrowser&&window[r(1086)+r(1350)+r(468)](e[r(1479)],this[r(756)+r(1438)]),this[r(1368)+"er"]&&window[r(1086)+r(1350)+r(468)](e[r(1763)],this["_handleO"+r(665)]),this[r(1368)+"er"]&&window[r(1086)+r(1350)+r(468)](e[r(1624)],this[r(1277)+r(1205)]),this[r(1368)+"er"]&&window[r(1086)+r(1350)+"ner"](e.BOelW,this[r(1277)+r(642)])}[t(1277)+t(1205)](r){let o=t;if(e[o(837)](e.IzayX,e[o(478)]))!r[o(361)+"d"]&&(this[o(1368)+"er"]&&window[o(1086)+o(1350)+o(468)](e[o(1624)],this["_handleP"+o(1205)]),this._isBrowser&&window[o(1086)+"entListe"+o(468)](e.BOelW,this["_handleP"+o(642)]),this[o(1102)]()),this[o(1368)+"er"]&&window[o(1086)+o(1350)+o(468)](e[o(1479)],this[o(756)+o(1438)]),this[o(1368)+"er"]&&window[o(1086)+o(1350)+o(468)](e[o(1763)],this[o(756)+o(665)]);else{let l=e.rsfjp[o(1054)]("|"),h=0;for(;;){switch(l[h++]){case"0":this._ws[o(1086)+o(1350)+"ner"](o(1148),this[o(1180)]);continue;case"1":this[o(1609)][o(1086)+o(1350)+o(468)](e[o(253)],this[o(1323)+"ge"]);continue;case"2":this[o(1609)][o(1086)+o(1350)+o(468)](e[o(1663)],this[o(789)]);continue;case"3":if(!this[o(1609)])return;continue;case"4":this._ws[o(1086)+"entListe"+o(468)](e[o(454)],this[o(302)]);continue}break}}}[t(1277)+t(642)](r){let o=t;r[o(361)+"d"]&&(this["_navigat"+o(1506)]()&&(!this._ws||e.axbjB(this._ws[o(1395)+"te"],this[o(1556)])||e[o(555)](this[o(1609)][o(1395)+"te"],this[o(785)+"NG"]))&&this[o(756)+o(1438)](),this._isBrowser&&window["addEvent"+o(1545)](e[o(1479)],this[o(756)+o(1438)]),this[o(1368)+"er"]&&window[o(356)+o(1545)](o(288),this[o(756)+o(665)]))}async[t(707)+"eUrl"](r){let o=t,l={QKZxY:e[o(887)]},{fpID:h,deviceID:w,bddID:_,ttwID:S,accessKey:g,aID:O,customParams:L={},enableAutoAck:B,enableQoS:W,QoSLevel:ne,env:J}=this[o(848)],Ge,Ie,we;if(this[o(1368)+"er"]||this[o(1345)+"X"]||this[o(364)+"T"])if(e[o(1130)](e[o(1725)],e[o(259)]))Ge=location&&e[o(463)](o(1521),location[o(895)])?o(954):e[o(1370)],Ie=r[o(1310)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),we=/^wss(.*:\/\/)/.test(r)?r:""+Ge+Ie;else switch(_0x4aaa41){case hGhGwz[o(959)]:case"ppe":return{[o(1519)+_0x511533]:1,"x-tt-env":_0x356231};default:return{}}else Ge=o(954),Ie=r[o(1310)](/(^http)((?:[s]*:\/\/))/,""),we=/(^ws)((?:[s]*:\/\/))/.test(Ie)?Ie:""+Ge+Ie;let it=_?e[o(1363)]:S?o(459):e[o(1060)],mi=_||S||w;if(e.fvFUG(!mi,!it))throw new Error(e.HLKro);let Cm=e[o(1673)]==typeof L?await L():L,Pm=J?e[o(1672)](Zg,J[o(922)],J[o(616)]):{},Wa=Object[o(1503)]({device_platform:o(493),version_code:e.ZAQJd,access_key:g,fpid:h,aid:O,[it]:mi,xsack:B?1:0,xaack:B?1:0,xsqos:W?1:0,qos_level:W?ne:void 0,qos_sdk_version:2,...Pm},Cm),Rm=Object[o(1526)](Wa)[o(578)](($a,Va)=>Wa[Va]!==void 0?""+$a+($a?"&":"?")+Va+"="+Wa[Va]:$a,"");return we+"/ws/v2"+Rm}async[t(470)](){let r=t;if(!(this[r(470)+r(311)]||this[r(279)+r(994)])){this._connectLock=!0;try{let o=this["_endpoin"+r(1037)]?.[r(909)+r(1398)+r(1118)+r(1326)+r(477)](),{timeoutInterval:l}=this[r(848)];if(o){let w=this[r(1108)+r(1037)]?.[r(671)+r(1301)+"nt"](),_=this[r(1108)+r(1037)]?.["replaceBackupEnd"+r(1319)+r(1651)+r(745)](),S=this[r(1108)+r(1037)]?.["getCurre"+r(1301)+r(722)+"ount"]();if(_){let g=r(921)+w+(r(593)+", max re"+r(606)+"ached, will use "+r(457)+"ndpoint ")+_+" to retry",O=pt(e.mePiD,{message:g,code:wn[r(1796)+r(1630)+"R"]});this[r(657)](g),this[r(874)+"hErrorEv"+r(680)](O),this[r(1646)]=await this[r(707)+"eUrl"](_),this._debug(r(921)+_+" "+S+r(751)),this[r(501)+"sListeners"]()}else{let g=r(921)+w+(r(593)+r(1007)+r(606)+r(465));this._debug(g),this["_dispatchErrorEv"+r(680)](pt(r(1148),{message:g,code:wn.MAX_RETRIES_ERROR}));return}}else{let w=this[r(1108)+r(1037)]?.[r(671)+r(1301)+r(1534)+r(1183)](),_=this[r(1108)+r(1037)]?.[r(671)+r(1301)+"ntTriesC"+r(472)]();this._url=await this["_generat"+r(873)](e[r(1207)](w,"")),this[r(657)]("connect "+w+" "+_+r(751)),this["_removeW"+r(1056)+"rs"]()}if(this[r(1332)])this[r(1332)]=!1;else{let w=e[r(1511)](Fa,r(948)+"t",{message:e[r(763)]});this[r(282)+r(1597)]&&this["onStartR"+r(1597)](w)}let h=this[r(1108)+r(1037)]?.[r(671)+"ntEndpoi"+r(722)+r(472)]()||0;e[r(759)](h,1)&&await this._wait(e[r(863)](h,1)),this._debug("connecti"+r(1151)+this[r(1646)]+(r(1406)+r(508))+this[r(548)+"ls"]),this[r(1609)]=Wg({url:this[r(1646)],protocols:[this[r(548)+"ls"]],headers:this[r(848)][r(1518)+"ramParams"]["customHt"+r(1106)]},this._options.ws),(this[r(1368)+"er"]||this[r(314)+"r"])&&this[r(1609)]&&(this[r(1609)][r(805)+"pe"]=this[r(1228)+r(1724)]),this[r(651)+r(1685)](),this[r(470)+"ionTimeo"+r(1747)]=e[r(329)](setTimeout,this[r(1113)+"ut"][r(902)](this),l)}catch(o){throw this[r(470)+r(311)]=!1,o}}}["_clearTi"+t(1209)](){let r=t;e[r(1475)](clearTimeout,this[r(470)+r(1478)+r(1747)]),this[r(470)+r(1478)+"utId"]=null}[t(1731)+t(1156)](){let r=t;if(e[r(1619)](e[r(1738)],e[r(1738)]))return _0x27d0ad||(_0x4297df=[_0x701352,_0x3de8c6,_0x1c1dba,_0x2a681f,_0x17ccd5]);e.PXKjC(clearTimeout,this[r(1372)+"gTimeoutId"]),e[r(1544)](clearTimeout,this[r(1565)+r(879)+r(298)]),this[r(1372)+"gTimeoutId"]=null,this[r(1565)+"ctTimeou"+r(298)]=null}[t(657)](...r){let o=t;this._options[o(1434)]&&console[o(1638)][o(275)](console,[e[o(499)],...r])}[t(1767)+t(871)+"e"](r){let o=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:w}=this[o(848)],_=e[o(1189)](l,Math[o(1250)](w,e.BEvhN(r,1)));return e.fWrod(_,h)?h:_}[t(1483)](){let r=t,o={HZNEW:e[r(1652)]};if(this[r(1609)]&&e[r(1636)](this[r(1609)][r(1395)+"te"],this[r(785)+"NG"]))if(e.zWtpK(e.aRAWs,e.aRAWs)){this[r(1731)+r(1156)](),this[r(1372)+r(533)+"Id"]=e.RvFUi(setTimeout,this[r(1483)].bind(this),this[r(848)][r(1050)+r(1273)]);return}else return{frameType:_0x45e89c,headers:[{key:KTJihf[r(422)],value:r(1231)+r(1188)}],payload:void 0};if(!this[r(1609)]||e.sMNMQ(this[r(1609)][r(1395)+"te"],this.OPEN))return void this[r(1575)+r(1597)]();this._ws&&this[r(1609)][r(685)]("hi"),this[r(1565)+r(879)+"tId"]=e[r(1420)](setTimeout,this[r(1575)+r(1597)+r(1165)][r(902)](this),this._options[r(1582)+r(1436)+r(800)])}[t(1575)+"econnect"+t(1165)](){let r=t;e.KpToE===e.hHjqB?this[r(651)+r(1685)]():(this[r(1756)+r(877)]?.[r(562)](),this[r(249)]("ping_onc"+r(1693)+"t",e.xVHQL),this[r(1756)+r(877)]?.[r(1325)+r(475)+"nt"]()?this["_handleR"+r(1597)]():this[r(1483)]())}[t(1124)+t(1506)](){let r=t;return this[r(364)+"T"]||this[r(1345)+"X"]?this._miniNavigatorOnline:(this[r(1368)+"er"]||this._isWorker)&&this[r(848)][r(1274)+r(338)+r(1387)]?navigator[r(363)]:!0}[t(1575)+t(1597)](){let r=t;!this._navigatorOnline()||this[r(279)+r(994)]||(this[r(1108)+r(1037)]?.[r(415)+r(811)+r(1257)](),this[r(1756)+"sCounter"]?.[r(287)+r(813)](),this[r(1609)]?this[r(669)+r(1079)](1001,e[r(573)],!0):this[r(470)]())}["_onPageN"+t(737)+t(1376)](){let r=t,o={DQlcW:e[r(535)]};this[r(364)+"T"]?tt["onNetwor"+r(804)+r(995)](({isConnected:l})=>{let h=r;this[h(1764)+h(1462)+h(1075)]=l,l?this._handleOnLine():this._handleOffLine()}):this[r(1345)+"X"]&&wx[r(733)+r(804)+r(995)](({isConnected:l})=>{let h=r;o[h(923)]!==h(1549)&&(this[h(1764)+h(1462)+h(1075)]=l,l?this[h(756)+h(1438)]():this[h(756)+h(665)]())})}[t(1508)](r){let o=t,l={CQDoD:function(h,w){return h!==w},FrFdE:e[o(1090)],kzeFp:function(h,w,_){return e[o(1335)](h,w,_)}};return new Promise(h=>{let w=o;if(l[w(452)](l[w(663)],"iTOuU"))l[w(1012)](setTimeout,h,this[w(1767)+w(871)+"e"](r));else return(this._listeners[_0x1371ec]||(this[w(350)+"rs"][_0x5212b9]=[]))[w(1029)]({fn:_0x36f707,ctx:_0x1ff8ed||this}),this})}["_disconn"+t(1079)](r=1e3,o="",l=!1){let h=t;this._ws&&this[h(1349)+h(1216)+"t"](r,o,l)}[t(1113)+"ut"](){let r=t,o=this[r(1108)+"tManager"]?.[r(671)+"ntEndpoint"]();this[r(657)](r(921)+o+r(593)),this._disconnect(1001,e[r(505)],!0)}[t(1385)](r){let o=t,l=Yt(r);this[o(1609)]&&this[o(1609)][o(1395)+"te"]===this[o(1556)]&&(this[o(1609)]&&this[o(1609)][o(685)](l),this[o(657)](e[o(747)],r))}["_removeW"+t(1056)+"rs"](){let r=t,o={JAcNk:function(l,h){return e[j(812)](l,h)},fzLml:function(l,h,w){return e[j(1095)](l,h,w)},tgBDk:function(l,h,w,_){return e[j(1424)](l,h,w,_)},lXLov:function(l,h){return e[j(1177)](l,h)}};if(r(961)===e[r(1168)]){let l=0,h=[];for(;PXQEaw[r(592)](l,_0x5db163[r(1700)+"th"]);){let{offset:w}=PXQEaw[r(771)](_0x2ee941,_0x1e38c8,l);l=w;let _={cursor_name:"",cursor:0,service:0},{value:S,offset:g}=PXQEaw[r(771)](_0x4e2a0e,_0x3ae460,l);_[r(661)]=S,l=g;let{value:O,offset:L}=PXQEaw[r(771)](_0x217e70,_0x44fb21,l);l=L,_[r(586)+r(772)]=PXQEaw[r(1346)](_0x598a49,_0x2d5b98,l,PXQEaw[r(633)](l,O)),l+=O;let{value:B,offset:W}=PXQEaw.fzLml(_0x5e5973,_0x241448,l);_[r(1361)]=B.toNumber(),l=W,h[r(1029)](_)}return h}else{if(!this[r(1609)])return;this[r(1609)][r(1086)+r(1350)+r(468)](e[r(1663)],this[r(789)]),this[r(1609)][r(1086)+r(1350)+r(468)](r(1102),this[r(302)]),this[r(1609)]["removeEventListe"+r(468)](e[r(253)],this._onMessage),this[r(1609)]["removeEv"+r(1350)+r(468)]("error",this[r(1180)])}}["_addWsLi"+t(1685)](){let r=t,o={XqDSW:function(l,h){return l>=h},wqKIz:function(l,h){return e[j(936)](l,h)},zlTYh:function(l,h){return e[j(1456)](l,h)},Fwwbx:function(l,h){return e[j(868)](l,h)},TqOVi:function(l,h){return e[j(1288)](l,h)},mXUvH:function(l,h){return e.QNNEj(l,h)},hCDvD:function(l,h){return l|h},fiyCM:function(l,h){return l<<h},FjgOh:function(l,h){return e[j(1256)](l,h)},ahVyJ:function(l,h){return e[j(1255)](l,h)},WTqnr:function(l,h){return e[j(1595)](l,h)},nsexl:function(l,h){return e[j(1727)](l,h)},qIDHr:function(l,h){return e.vdMFP(l,h)},prWKa:function(l,h){return e[j(579)](l,h)},UiQJG:function(l,h){return l<<h},qBnyY:function(l,h){return e[j(783)](l,h)},sBoRh:function(l,h){return l>>h},DKKdf:function(l,h){return e[j(639)](l,h)}};if(e[r(1713)](r(787),e[r(409)])){let l=_0x259ed4[_0x5e0910++];if(l<=127)_0x1c4cb5+=_0x383611[r(1125)+r(450)](l);else if(bLpfuL.XqDSW(l,192)&&bLpfuL[r(1357)](l,224))_0x54c517+=_0x3bacd4[r(1125)+"Code"](bLpfuL.zlTYh(bLpfuL[r(730)](31,l),6)|bLpfuL[r(1166)](63,_0x5666f2[_0x22a3fe++]));else if(l>=224&&bLpfuL[r(1683)](l,240))_0x1de76e+=_0x4226f9[r(1125)+"Code"](bLpfuL.hCDvD(bLpfuL[r(382)](15&l,12)|bLpfuL[r(1407)](bLpfuL[r(1528)](63,_0x2bb06e[_0x325c1c++]),6),bLpfuL.WTqnr(63,_0x7eb1a3[_0x49ab1f++])));else if(bLpfuL.XqDSW(l,240)){let h=bLpfuL[r(1281)](bLpfuL[r(1777)](bLpfuL.qIDHr(bLpfuL[r(561)](bLpfuL[r(1603)](7,l),18),bLpfuL[r(1407)](bLpfuL[r(1166)](63,_0x59c091[_0x1d5d00++]),12)),bLpfuL[r(1042)](bLpfuL[r(949)](63,_0x1d26f3[_0x5719d2++]),6))|bLpfuL[r(1528)](63,_0x596a6b[_0x34d2af++]),65536);_0x2d30b3+=_0x3d6d1d[r(1125)+"Code"](55296+bLpfuL[r(1750)](h,10)),_0x12fc4b+=_0x22d61b[r(1125)+"Code"](bLpfuL[r(543)](56320,bLpfuL[r(949)](1023,h)))}}else{let l=e[r(943)][r(1054)]("|"),h=0;for(;;){switch(l[h++]){case"0":this[r(1609)][r(356)+r(1545)](e.GHFrr,this._onClose);continue;case"1":this[r(1609)]["addEvent"+r(1545)](r(1480),this[r(1323)+"ge"]);continue;case"2":this[r(1609)][r(356)+r(1545)](e[r(577)],this[r(1180)]);continue;case"3":this._ws[r(356)+r(1545)](e.GAHwm,this._onOpen);continue;case"4":if(!this[r(1609)])return;continue}break}}}[t(435)+t(1702)](r=1e3,o=""){let l=t;if(e[l(1466)](e[l(1278)],e[l(1532)]))try{this[l(1609)]&&this[l(1609)][l(1102)](r,o)}catch{}else{let h=this[l(848)][l(948)+l(1762)+l(1399)](_0x2307b2,_0x1f6524);this[l(874)+l(788)+"ent"](e[l(894)](_0x5eb64e,e[l(454)],{code:_0x442b2c,reason:_0x27602f,wasClean:!0,willReconnect:h})),h&&this._connect()}}[t(1349)+t(1216)+"t"](r=1e3,o="",l=!1){let h=t;if(this._clearPingTimer(),this[h(525)+"mer"](),this._removeWsListeners(),this._wsInstanceClose(1e3,o),this[h(470)+h(311)]=!1,l&&this[h(1124)+"orOnline"]()&&!this._readyClosed){if(this[h(1108)+h(1037)]?.[h(1325)+h(1088)+"es"]()){let _=this[h(1108)+h(1037)]?.[h(671)+h(1301)+"nt"]();this[h(874)+h(788)+h(680)](e.NltNA(vt,h(1102),{code:1006,reason:h(921)+_+(h(593)+h(1007)+h(606)+h(465)),wasClean:!0}))}else if(e.OwoJg(e.eaVuM,e[h(1100)])){if(!this[h(1609)])return;this[h(1349)+h(1216)+"t"](_0x3d4399,_0xc60791,_0x42f3d4)}else{let _=this._options[h(948)+h(1762)+h(1399)](r,o);this[h(874)+h(788)+h(680)](e[h(914)](vt,e[h(454)],{code:r,reason:o,wasClean:!0,willReconnect:_})),_&&this[h(470)]()}return}this[h(1124)+"orOnline"]()||this._readyClosed?this[h(874)+h(788)+h(680)](e.MFlNE(vt,e.GHFrr,{code:r,reason:e[h(513)]})):this[h(874)+"hCloseEv"+h(680)](e[h(1757)](vt,e.GHFrr,{code:1006,reason:e.vXTNd})),this[h(1609)]=null,this._endpointManager?.[h(415)+"pointCon"+h(1257)](),this[h(1756)+h(877)]?.["resetCou"+h(813)]()}[t(874)+"hOpenEvent"](r){let o=t;this.emit(e[o(1663)],r),this[o(1766)]&&this[o(1766)](r)}[t(874)+"hMessage"+t(1741)](r){let o=t;this[o(249)](e[o(253)],r),this[o(1161)+"e"]&&this.onmessage(r)}[t(874)+"hAckMess"+t(1369)](r){let o=t;if(e[o(312)](e.qZEbo,e[o(492)]))this[o(249)](e[o(762)],r),this[o(600)+o(1698)]&&this[o(600)+o(1698)](r);else{let l=e[o(395)](e.ZxoDT(e[o(394)](7,_0x395255),18)|e[o(1321)](63&_0x2ca534[_0x5c6837++],12)|e[o(549)](63&_0x521a20[_0x919eb9++],6),e[o(1008)](63,_0x4c0f57[_0x517946++]))-65536;_0x26c43e+=_0x37aa93[o(1125)+"Code"](55296+(l>>10)),_0x5a7606+=_0x59e43f[o(1125)+o(450)](e[o(1241)](56320,e.XvtlR(1023,l)))}}[t(874)+t(856)+"ent"](r){let o=t;this[o(249)](e.mePiD,r),this[o(527)]&&this.onerror(r)}[t(874)+"hCloseEv"+t(680)](r){let o=t;this.emit(e.GHFrr,r),this[o(1453)]&&this.onclose(r)}get binaryType(){let r=t;return e[r(528)]("YxTOs",e[r(1159)])?e.jdHUo(this[r(377)+r(1554)],this[r(497)+"s"].length)?!0:this[r(967)+r(706)+"riesCount"]>this.maxRetries:this[r(1609)]?this[r(1609)][r(805)+"pe"]:this["_binaryT"+r(1724)]}set[t(805)+"pe"](r){let o=t;if(e[o(1636)](o(1551),e[o(638)])){if(_0x35ffbe<=-_0x402af4)return _0x485be3;if(e[o(767)](e[o(595)](_0x118c85,1),_0x5a88bd))return _0x2ae05a}else this["_binaryT"+o(1724)]=r,this._ws&&(this[o(1609)][o(805)+"pe"]=r)}get[t(1467)+"nt"](){let r=t;return this[r(1108)+r(1037)]?.["getCurre"+r(1301)+"ntTriesC"+r(472)]()||0}get["buffered"+t(1120)](){let r=t;return this._messageQueue[r(578)]((l,h)=>(l+=h&&h[r(1700)+"th"]||0,l),0)+(this[r(1609)]?this._ws[r(335)+"Amount"]:0)}get[t(712)+"ns"](){let r=t;return this[r(1609)]?this[r(1609)].extensions:""}get[t(895)](){let r=t;return this._ws?this[r(1609)][r(895)]:""}get readyState(){let r=t;return this[r(1609)]?this[r(1609)][r(1395)+"te"]:this[r(848)][r(441)+"cOpen"]?this[r(785)+"NG"]:this[r(869)]}get[t(494)](){let r=t;return this[r(1609)]?this[r(1609)][r(494)]:this._url}close(r=1e3,o){let l=t,h={xmlJN:l(1148)};if(e.gSkAI(e[l(1193)],e[l(1193)]))this[l(249)](ncDlEQ[l(432)],_0x4ddb13(ncDlEQ[l(432)],{message:this[l(1410)+l(807)+"age"](_0x4f2939)}));else{let w=e[l(1770)][l(1054)]("|"),_=0;for(;;){switch(w[_++]){case"0":if(e[l(985)](this[l(1609)][l(1395)+"te"],this[l(869)])||e[l(1497)](this._ws.readyState,this.CLOSING))return void this[l(657)](e[l(284)]);continue;case"1":this[l(1349)+"WebSocket"](r,o);continue;case"2":this[l(525)+l(1209)]();continue;case"3":this[l(1340)+l(1513)+l(1545)]();continue;case"4":this[l(1731)+l(1156)]();continue;case"5":this[l(301)+l(261)]?.[l(345)]();continue;case"6":if(!this[l(1609)])return void this._debug(e[l(839)]);continue;case"7":this[l(279)+l(994)]=!0;continue}break}}}async[t(685)](r,o){let l=t;if(e[l(510)](null,r))throw new Error(e.BZvqg);e[l(1359)](e[l(1377)],typeof r)&&(r=JSON[l(1481)+"y"](r)),e[l(719)](e[l(1774)],typeof r)&&!e[l(955)](r,ArrayBuffer)&&!(r[l(327)]&&e[l(755)](r.buffer,ArrayBuffer))&&(r=JSON.stringify(r));let h=await e[l(656)](Kl,r),w=Vg(r),{method:_=0,service:S=this._options[l(661)],logID:g=this._options[l(997)+l(370)](),headers:O=this[l(848)].headers,payloadEncoding:L=this[l(848)]["payloadE"+l(1123)],payloadType:B=this[l(848)][l(328)+l(1724)],logIDNew:W=this[l(848)][l(292)+l(664)][l(1718)+l(1794)+"teLogIDNew"]?i(this[l(848)][l(292)+"Config"][l(1635)]):""}=e[l(1531)](o,{});if(!S)throw new Error(e.YIbVA);let ne={SeqID:te[l(1202)+"er"](this[l(1536)]++),LogID:te[l(1202)+"er"](g),service:S,method:_,headers:O,payloadEncoding:e[l(955)](L,Object)?L[l(268)]?L[l(268)]:"":L,payloadType:e.esiYo(B,Object)?B[l(1292)]?B[l(1292)]:w:B||w,payload:h,LogIDNew:W},J=e[l(1334)](Yt,ne);return this[l(1609)]&&this[l(1609)][l(1395)+"te"]===this[l(1556)]?e.rCgEG(e[l(660)],l(344))?(this[l(1228)+l(1724)]=_0x3213bc,this._ws&&(this[l(1609)][l(805)+"pe"]=_0x44a38a)):(this[l(1609)]&&this[l(1609)].send(J),this[l(657)](e[l(1394)],ne)):e.ctPHc(this["_message"+l(844)][l(1601)],this[l(848)][l(1017)+"geQueueL"+l(1327)])?(this["_message"+l(844)].push(J),this._debug(e.knZEu,ne)):(this[l(1446)+l(844)][l(360)](),this[l(1446)+l(844)].push(J)),{seqID:this[l(1536)],logID:g,logIDNew:W}}async[t(948)+"t"](r){let o=t,{url:l}=r||{},h=Array[o(447)](l)?l:e[o(381)](e[o(1774)],typeof l)?[l]:[];r&&Object[o(1503)](this[o(848)],r),h&&h[o(1601)]?this[o(1108)+o(1037)]=new Hl(h,this[o(848)][o(1328)+"es"]):this[o(1108)+o(1037)]?.[o(415)+o(811)+"fig"](),this[o(1756)+"sCounter"]?.["resetCou"+o(813)](this[o(848)][o(263)+o(623)]),this[o(279)+o(994)]=!1,this[o(1609)]&&e[o(1044)](this._ws[o(1395)+"te"],this[o(869)])?this[o(669)+o(1079)](1e3,e[o(648)],!0):(this[o(1332)]=!0,this[o(470)]())}async[t(348)](){let r=t;if(!this["_connect"+r(311)]){let o=e[r(534)].split("|"),l=0;for(;;){switch(o[l++]){case"0":this[r(1332)]=!0;continue;case"1":this["_endpoin"+r(1037)]?.[r(415)+r(811)+r(1257)]();continue;case"2":this[r(1756)+r(877)]?.[r(287)+"nter"]();continue;case"3":this[r(279)+r(994)]=!1;continue;case"4":this._connect();continue}break}}}[t(356)+"Listener"](r,o){this.on(r,o)}["dispatch"+t(1741)](r){let o=t;if(e[o(1537)](e[o(1187)],e[o(1187)]))return{bytes:_0x52d13a,offset:0,limit:_0x4cb841[o(1601)]};{let{type:l}=r;this[o(249)](l,r)}}[t(1086)+"entListe"+t(468)](r,o){this[t(966)](r,o)}[t(1069)](){let r=t,o={EsJdb:function(l,h){return e[j(818)](l,h)},lzfDv:r(1314),GAdbc:function(l,h){return e.NOHDC(l,h)},pCMco:function(l,h){return e[r(885)](l,h)},iHzPF:r(1592)+r(551),CjXWC:e.LlDNL,zJVOh:e.wmoqG,lefZu:r(621)+r(774)+"s",NSLtX:function(l,h){return e[r(1544)](l,h)},zjXlO:e[r(397)],ZWXXD:e.iiWsd,mwLFd:function(l,h,w){return e[r(1579)](l,h,w)}};if(e[r(1507)](r(429),e[r(1709)]))try{return HXfPmU[r(1425)](HXfPmU[r(1771)],typeof _0x245e67)&&(HXfPmU.GAdbc(_0x3b1e1b,_0x159cfa)||_0x4fde87.buffer&&HXfPmU[r(1403)](_0x4ef0e3[r(327)],_0x472403))||typeof _0x3d3215!="string"?"":(_0x5425ac[r(690)](_0x25cc5c),HXfPmU[r(720)])}catch{return HXfPmU[r(1771)]==typeof _0x3513c1?HXfPmU.CjXWC:""}else return new Promise((l,h)=>{let w=r;this[w(1731)+w(1156)](),this[w(1372)+w(533)+"Id"]=o[w(1781)](setTimeout,this[w(1483)][w(902)](this),this[w(848)][w(1050)+"rval"]);let _=()=>{let g=w;l(o[g(1779)]),this[g(966)](o[g(569)],_),this[g(966)](g(621)+g(1693)+"t",S)},S=()=>{let g=w;o[g(627)](h,o[g(911)]),this[g(966)](o.lefZu,_),this[g(966)](o[g(1135)],S)};this.on(o[w(569)],_),this.on(w(621)+w(1693)+"t",S),this[w(1483)]()})}}})(),Ce[M(1295)+M(1174)]=Me[M(1295)+"oseEvent"],Ce["CustomEr"+M(829)]=Me[M(1660)+"rorEvent"],Ce[M(1583)+"e"]=Me[M(1583)+"e"],Ce[M(1741)]=Me[M(1741)],Ce[M(469)]=Me.FWS,Ce[M(678)+M(1185)+M(964)]=Me["Frontier"+M(1185)+M(964)],Ce[M(1185)+M(964)]=Me[M(1185)+M(964)],Ce[M(619)+"t"]=Me[M(619)+"t"],Ce[M(1341)+M(931)]=Me[M(1341)+M(931)],Ce[M(580)+"oseEvent"]=Me["createCl"+M(1174)],Ce[M(1275)+M(829)]=Me[M(1275)+M(829)],Ce[M(1164)+M(1093)+"nt"]=Me["createMe"+M(1093)+"nt"],Ce[M(1267)+"enEvent"]=Me[M(1267)+"enEvent"],Ce[M(1240)+M(1712)+M(964)]=Me[M(1240)+M(1712)+M(964)],Ce[M(512)+M(1421)]=Me["decodedF"+M(1421)],Ce[M(850)+M(772)]=Me[M(850)+M(772)];for(pa in Me)[M(1295)+"oseEvent",M(1660)+M(829),M(1583)+"e",M(1741),"FWS",M(678)+M(1185)+"vent",M(1185)+M(964),"OpenEvent","Reconnec"+M(931),M(580)+M(1174),"createEr"+M(829),M(1164)+M(1093)+"nt",M(1267)+M(1259),"createRe"+M(1712)+M(964),M(512)+"rame",M(850)+M(772)][M(1126)](pa)===-1&&(Ce[pa]=Me[pa]);var pa;Object[M(1092)+M(1245)](Ce,M(1213)+"le",{value:!0})});import{existsSync as NI,openSync as MI}from"node:fs";import{mkdir as BI}from"node:fs/promises";import{dirname as FI}from"node:path";import{fileURLToPath as zI}from"node:url";function HI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function yl(t=Z()){return NI(t.libEntry)?t.libEntry:zI(new URL("../index.ts",import.meta.url))}async function tg(t={}){let e=t.paths??Z(),n=t.entryOverride??yl(e),i=HI(e,process.env.COZE_BRIDGE_LOG_MODE);await BI(FI(i),{recursive:!0});let s=MI(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=ct(process.execPath,d,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[Es]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return UI.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var UI,Es,Aa=st(()=>{"use strict";an();re();Pe();UI=H("spawn-daemon"),Es="COZE_BRIDGE_DAEMON"});import{spawn as FA}from"node:child_process";import{mkdir as zA,unlink as UA,writeFile as HA}from"node:fs/promises";import{dirname as GA,join as qA}from"node:path";function hi(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function jA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${hi(n)}</key>
21
+ <string>${hi(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function aA(t,e){return new Promise((n,i)=>{let o=eA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var ii,ms,Ia,_l,Qp=it(()=>{"use strict";te();ii=G("supervisor.launchd"),ms="ai.coze.bridge",Ia=aA,_l={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function KA(t,e){return new Promise((n,i)=>{let s=FA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var fi,Is,Da,Tl,Sg=st(()=>{"use strict";re();fi=H("supervisor.launchd"),Is="ai.coze.bridge",Da=KA,Tl={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>${ms}</string>
31
+ <string>${Is}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${si(t.nodeBin)}</string>
35
- <string>${si(t.entry)}</string>
34
+ <string>${hi(t.nodeBin)}</string>
35
+ <string>${hi(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>${si(t.logFile)}</string>
45
+ <string>${hi(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${si(t.logFile)}</string>${oA(t.env)}
47
+ <string>${hi(t.logFile)}</string>${jA(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return sA(t.homeDir,"Library","LaunchAgents",`${ms}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await tA(iA(i),{recursive:!0}),await rA(i,this.renderConfig(t),"utf8"),ii.info("plist written",{plistPath:i,activate:n}),!n)return;await Ia("launchctl",["unload","-w",i]).catch(a=>ii.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Ia("launchctl",["load","-w",i]),ii.info("launchd job loaded",{label:ms});let o=process.getuid?.()??0;await Ia("launchctl",["kickstart","-k",`gui/${o}/${ms}`]),ii.info("launchd job kickstarted",{label:ms,uid:o})},async uninstall(t){let e=this.configPath(t);await Ia("launchctl",["unload","-w",e]).catch(n=>ii.warn("launchctl unload failed (ignored)",{err:String(n)})),await nA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),ii.info("launchd job removed",{plistPath:e})}}});import{spawn as cA}from"node:child_process";import{mkdir as dA,unlink as lA,writeFile as uA}from"node:fs/promises";import{dirname as fA,join as eg}from"node:path";function ka(t,e){return t.isRoot?e:["--user",...e]}function xA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function Ta(t,e){return new Promise((n,i)=>{let o=cA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Aa,oi,hA,yl,tg=it(()=>{"use strict";te();Aa=G("supervisor.systemd"),oi="coze-bridge.service",hA="/etc/systemd/system";yl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return qA(t.homeDir,"Library","LaunchAgents",`${Is}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await zA(GA(i),{recursive:!0}),await HA(i,this.renderConfig(t),"utf8"),fi.info("plist written",{plistPath:i,activate:n}),!n)return;await Da("launchctl",["unload","-w",i]).catch(a=>fi.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Da("launchctl",["load","-w",i]),fi.info("launchd job loaded",{label:Is});let s=process.getuid?.()??0;await Da("launchctl",["kickstart","-k",`gui/${s}/${Is}`]),fi.info("launchd job kickstarted",{label:Is,uid:s})},async uninstall(t){let e=this.configPath(t);await Da("launchctl",["unload","-w",e]).catch(n=>fi.warn("launchctl unload failed (ignored)",{err:String(n)})),await UA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),fi.info("launchd job removed",{plistPath:e})}}});import{spawn as WA}from"node:child_process";import{mkdir as $A,unlink as VA,writeFile as ZA}from"node:fs/promises";import{dirname as JA,join as Ig}from"node:path";function La(t,e){return t.isRoot?e:["--user",...e]}function XA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function Na(t,e){return new Promise((n,i)=>{let s=WA(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Oa,xi,YA,Cl,Ag=st(()=>{"use strict";re();Oa=H("supervisor.systemd"),xi="coze-bridge.service",YA="/etc/systemd/system";Cl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
52
52
  Description=Coze Bridge daemon
53
53
  After=network.target
54
54
 
@@ -59,10 +59,10 @@ Restart=always
59
59
  RestartSec=3
60
60
  StandardOutput=append:${t.logFile}
61
61
  StandardError=append:${t.logFile}
62
- ${xA(t.env)}
62
+ ${XA(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?eg(hA,oi):eg(t.homeDir,".config","systemd","user",oi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await dA(fA(i),{recursive:!0}),await uA(i,this.renderConfig(t),"utf8"),Aa.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await Ta("systemctl",ka(t,["daemon-reload"])),await Ta("systemctl",ka(t,n?["enable","--now",oi]:["enable",oi])),Aa.info("systemd unit enabled",{unitName:oi,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await Ta("systemctl",ka(t,["disable","--now",oi])).catch(n=>Aa.warn("systemctl disable failed (ignored)",{err:String(n)})),await lA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Ta("systemctl",ka(t,["daemon-reload"])).catch(()=>{}),Aa.info("systemd unit removed",{unitPath:e})}}});import{spawn as pA}from"node:child_process";import{join as gA}from"node:path";function ng(t,e){return new Promise((n,i)=>{let o=pA(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),a="";o.stderr?.on("data",d=>{a+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var bl,Ca,El,rg=it(()=>{"use strict";te();bl=G("supervisor.taskscheduler"),Ca="CozeBridge",El={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Ig(YA,xi):Ig(t.homeDir,".config","systemd","user",xi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await $A(JA(i),{recursive:!0}),await ZA(i,this.renderConfig(t),"utf8"),Oa.info("systemd unit written",{unitPath:i,mode:s,activate:n}),await Na("systemctl",La(t,["daemon-reload"])),await Na("systemctl",La(t,n?["enable","--now",xi]:["enable",xi])),Oa.info("systemd unit enabled",{unitName:xi,mode:s,activate:n})},async uninstall(t){let e=this.configPath(t);await Na("systemctl",La(t,["disable","--now",xi])).catch(n=>Oa.warn("systemctl disable failed (ignored)",{err:String(n)})),await VA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Na("systemctl",La(t,["daemon-reload"])).catch(()=>{}),Oa.info("systemd unit removed",{unitPath:e})}}});import{spawn as QA}from"node:child_process";import{join as ek}from"node:path";function kg(t,e){return new Promise((n,i)=>{let s=QA(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Pl,Ma,Rl,Tg=st(()=>{"use strict";re();Pl=H("supervisor.taskscheduler"),Ma="CozeBridge",Rl={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,65 +86,64 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return gA(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await ng("schtasks",["/Create","/SC","ONLOGON","/TN",Ca,"/TR",n,"/RU",t.userName,"/F"]),bl.info("task scheduler entry created",{task:Ca,logFile:t.logFile})},async uninstall(t){await ng("schtasks",["/Delete","/TN",Ca,"/F"]).catch(e=>bl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),bl.info("task scheduler entry removed",{task:Ca})}}});var ig={};qa(ig,{buildContext:()=>EA,getSupervisor:()=>_A,launchdSupervisor:()=>_l,systemdSupervisor:()=>yl,taskSchedulerSupervisor:()=>El});import{homedir as mA,userInfo as wA}from"node:os";function _A(t=process.platform){switch(t){case"darwin":return _l;case"linux":return yl;case"win32":return El;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function bA(){let t={};for(let e of yA){let n=process.env[e];n&&(t[e]=n)}return t}function EA(){let t=Z();return{nodeBin:process.execPath,entry:ll(t),logFile:t.logFile,homeDir:mA(),userName:wA().username,isRoot:process.getuid?.()===0,env:bA()}}var yA,sg=it(()=>{"use strict";Pe();_a();Qp();tg();rg();yA=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();fn();var Xl=G("acp-installer-warmup"),Om=["claude-code","codex"];async function Ql(t={}){let e=t.ensure??gr,i=(await Promise.allSettled(Om.map(async o=>{let a=await e(o);Xl.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&Xl.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))})}$t();te();import{readdir as Zm}from"node:fs/promises";import{mkdir as ru,readFile as $m,writeFile as iu}from"node:fs/promises";import{join as Ja}from"node:path";var Vm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function mr(t,e,n){await ru(t,{recursive:!0});let i=Vm[e],o=Ja(t,i);return await iu(o,n??"","utf8"),o}async function Ya(t,e,n){let i=Ja(t,".claude");await ru(i,{recursive:!0});let o=Ja(i,"settings.local.json"),a={};try{let u=await $m(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(a=f)}catch{}let d=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return a.permissions=d,await iu(o,JSON.stringify(a,null,2),"utf8"),o}var et=G("agent-detail-sync"),Jm=6e4,Ym=5*6e4,Rs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Zm(n)}catch(o){et.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}et.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await Ie(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){et.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){et.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),et.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&n.push(i);if(n.length!==0){et.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){et.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await Ie(e,this.opts.paths);if(!i){et.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){et.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,Ym):Jm;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(o.agentId&&o.agentId!==e){et.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let a=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,a=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,a=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,a=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(et.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&et.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){et.debug("detail sync: no diff",{agentId:e});return}await qe(i,this.opts.paths),et.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}),et.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await mr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Sd=Wt(Bu(),1);import{createHash as Hy}from"node:crypto";import{lstat as gd,mkdir as md,readFile as Ao,readdir as R0,rm as wd,stat as Ed,writeFile as _d}from"node:fs/promises";import{homedir as Gy}from"node:os";import{basename as k0,dirname as qy,join as fe,normalize as jy,relative as vd,resolve as yd,sep as P0}from"node:path";import{Readable as D0}from"node:stream";import{pipeline as O0}from"node:stream/promises";import _w from"events";import ot from"fs";import{EventEmitter as Yc}from"node:events";import yf from"node:stream";import{StringDecoder as yw}from"node:string_decoder";import vf from"node:path";import Cr from"node:fs";import{dirname as Ow,parse as Lw}from"path";import{EventEmitter as Gw}from"events";import Dc from"assert";import{Buffer as Kn}from"buffer";import*as Gu from"zlib";import qw from"zlib";import{posix as Er}from"node:path";import{basename as m_}from"node:path";import co from"fs";import Lt from"fs";import Ju from"path";import{win32 as R_}from"node:path";import rf from"path";import Ff from"node:fs";import $_ from"node:assert";import{randomBytes as zf}from"node:crypto";import oe from"node:fs";import Ue from"node:path";import Uf from"fs";import wo from"node:fs";import Li from"node:path";import ut from"node:fs";import ey from"node:fs/promises";import fo from"node:path";import{join as Yf}from"node:path";import lt from"node:fs";import e0 from"node:path";var mw=Object.defineProperty,ww=(t,e)=>{for(var n in e)mw(t,n,{get:e[n],enumerable:!0})},Fu=typeof process=="object"&&process?process:{stdout:null,stderr:null},bw=t=>!!t&&typeof t=="object"&&(t instanceof Zn||t instanceof yf||Ew(t)||vw(t)),Ew=t=>!!t&&typeof t=="object"&&t instanceof Yc&&typeof t.pipe=="function"&&t.pipe!==yf.Writable.prototype.pipe,vw=t=>!!t&&typeof t=="object"&&t instanceof Yc&&typeof t.write=="function"&&typeof t.end=="function",Vt=Symbol("EOF"),Zt=Symbol("maybeEmitEnd"),gn=Symbol("emittedEnd"),Ns=Symbol("emittingEnd"),gi=Symbol("emittedError"),Ms=Symbol("closed"),zu=Symbol("read"),Bs=Symbol("flush"),Uu=Symbol("flushChunk"),Et=Symbol("encoding"),br=Symbol("decoder"),je=Symbol("flowing"),mi=Symbol("paused"),Ar=Symbol("resume"),We=Symbol("buffer"),nt=Symbol("pipes"),Ke=Symbol("bufferLength"),rc=Symbol("bufferPush"),Fs=Symbol("bufferShift"),Qe=Symbol("objectMode"),De=Symbol("destroyed"),ic=Symbol("error"),sc=Symbol("emitData"),Hu=Symbol("emitEnd"),oc=Symbol("emitEnd2"),Rt=Symbol("async"),ac=Symbol("abort"),zs=Symbol("aborted"),wi=Symbol("signal"),Bn=Symbol("dataListeners"),dt=Symbol("discarded"),_i=t=>Promise.resolve().then(t),Sw=t=>t(),Iw=t=>t==="end"||t==="finish"||t==="prefinish",Aw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,kw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),bf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Ar](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Tw=class extends bf{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,n){super(t,e,n),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},Cw=t=>!!t.objectMode,Rw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Zn=class extends Yc{[je]=!1;[mi]=!1;[nt]=[];[We]=[];[Qe];[Et];[Rt];[br];[Vt]=!1;[gn]=!1;[Ns]=!1;[Ms]=!1;[gi]=null;[Ke]=0;[De]=!1;[wi];[zs]=!1;[Bn]=0;[dt]=!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");Cw(e)?(this[Qe]=!0,this[Et]=null):Rw(e)?(this[Et]=e.encoding,this[Qe]=!1):(this[Qe]=!1,this[Et]=null),this[Rt]=!!e.async,this[br]=this[Et]?new yw(this[Et]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[We]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[nt]});let{signal:n}=e;n&&(this[wi]=n,n.aborted?this[ac]():n.addEventListener("abort",()=>this[ac]()))}get bufferLength(){return this[Ke]}get encoding(){return this[Et]}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[Qe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Rt]}set async(t){this[Rt]=this[Rt]||!!t}[ac](){this[zs]=!0,this.emit("abort",this[wi]?.reason),this.destroy(this[wi]?.reason)}get aborted(){return this[zs]}set aborted(t){}write(t,e,n){if(this[zs])return!1;if(this[Vt])throw new Error("write after end");if(this[De])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Rt]?_i:Sw;if(!this[Qe]&&!Buffer.isBuffer(t)){if(kw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Aw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Qe]?(this[je]&&this[Ke]!==0&&this[Bs](!0),this[je]?this.emit("data",t):this[rc](t),this[Ke]!==0&&this.emit("readable"),n&&i(n),this[je]):t.length?(typeof t=="string"&&!(e===this[Et]&&!this[br]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Et]&&(t=this[br].write(t)),this[je]&&this[Ke]!==0&&this[Bs](!0),this[je]?this.emit("data",t):this[rc](t),this[Ke]!==0&&this.emit("readable"),n&&i(n),this[je]):(this[Ke]!==0&&this.emit("readable"),n&&i(n),this[je])}read(t){if(this[De])return null;if(this[dt]=!1,this[Ke]===0||t===0||t&&t>this[Ke])return this[Zt](),null;this[Qe]&&(t=null),this[We].length>1&&!this[Qe]&&(this[We]=[this[Et]?this[We].join(""):Buffer.concat(this[We],this[Ke])]);let e=this[zu](t||null,this[We][0]);return this[Zt](),e}[zu](t,e){if(this[Qe])this[Fs]();else{let n=e;t===n.length||t===null?this[Fs]():typeof n=="string"?(this[We][0]=n.slice(t),e=n.slice(0,t),this[Ke]-=t):(this[We][0]=n.subarray(t),e=n.subarray(0,t),this[Ke]-=t)}return this.emit("data",e),!this[We].length&&!this[Vt]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[Vt]=!0,this.writable=!1,(this[je]||!this[mi])&&this[Zt](),this}[Ar](){this[De]||(!this[Bn]&&!this[nt].length&&(this[dt]=!0),this[mi]=!1,this[je]=!0,this.emit("resume"),this[We].length?this[Bs]():this[Vt]?this[Zt]():this.emit("drain"))}resume(){return this[Ar]()}pause(){this[je]=!1,this[mi]=!0,this[dt]=!1}get destroyed(){return this[De]}get flowing(){return this[je]}get paused(){return this[mi]}[rc](t){this[Qe]?this[Ke]+=1:this[Ke]+=t.length,this[We].push(t)}[Fs](){return this[Qe]?this[Ke]-=1:this[Ke]-=this[We][0].length,this[We].shift()}[Bs](t=!1){do;while(this[Uu](this[Fs]())&&this[We].length);!t&&!this[We].length&&!this[Vt]&&this.emit("drain")}[Uu](t){return this.emit("data",t),this[je]}pipe(t,e){if(this[De])return t;this[dt]=!1;let n=this[gn];return e=e||{},t===Fu.stdout||t===Fu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[nt].push(e.proxyErrors?new Tw(this,t,e):new bf(this,t,e)),this[Rt]?_i(()=>this[Ar]()):this[Ar]()),t}unpipe(t){let e=this[nt].find(n=>n.dest===t);e&&(this[nt].length===1?(this[je]&&this[Bn]===0&&(this[je]=!1),this[nt]=[]):this[nt].splice(this[nt].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[dt]=!1,this[Bn]++,!this[nt].length&&!this[je]&&this[Ar]();else if(t==="readable"&&this[Ke]!==0)super.emit("readable");else if(Iw(t)&&this[gn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[gi]){let i=e;this[Rt]?_i(()=>i.call(this,this[gi])):i.call(this,this[gi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Bn]=this.listeners("data").length,this[Bn]===0&&!this[dt]&&!this[nt].length&&(this[je]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Bn]=0,!this[dt]&&!this[nt].length&&(this[je]=!1)),e}get emittedEnd(){return this[gn]}[Zt](){!this[Ns]&&!this[gn]&&!this[De]&&this[We].length===0&&this[Vt]&&(this[Ns]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ms]&&this.emit("close"),this[Ns]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==De&&this[De])return!1;if(t==="data")return!this[Qe]&&!n?!1:this[Rt]?(_i(()=>this[sc](n)),!0):this[sc](n);if(t==="end")return this[Hu]();if(t==="close"){if(this[Ms]=!0,!this[gn]&&!this[De])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[gi]=n,super.emit(ic,n);let o=!this[wi]||this.listeners("error").length?super.emit("error",n):!1;return this[Zt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Zt](),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[Zt](),i}[sc](t){for(let n of this[nt])n.dest.write(t)===!1&&this.pause();let e=this[dt]?!1:super.emit("data",t);return this[Zt](),e}[Hu](){return this[gn]?!1:(this[gn]=!0,this.readable=!1,this[Rt]?(_i(()=>this[oc]()),!0):this[oc]())}[oc](){if(this[br]){let e=this[br].end();if(e){for(let n of this[nt])n.dest.write(e);this[dt]||super.emit("data",e)}}for(let e of this[nt])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Qe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Qe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Qe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(De,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[dt]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[Vt])return e();let i,o,a=x=>{this.off("data",d),this.off("end",u),this.off(De,f),e(),o(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(De,f),this.pause(),i({value:x,done:!!this[Vt]})},u=()=>{this.off("error",a),this.off("data",d),this.off(De,f),e(),i({done:!0,value:void 0})},f=()=>a(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(De,f),this.once("error",a),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[dt]=!1;let t=!1,e=()=>(this.pause(),this.off(ic,e),this.off(De,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(ic,e),this.once(De,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[De])return t?this.emit("error",t):this.emit(De),this;this[De]=!0,this[dt]=!0,this[We].length=0,this[Ke]=0;let e=this;return typeof e.close=="function"&&!this[Ms]&&e.close(),t?this.emit("error",t):this.emit(De),this}static get isStream(){return bw}},Pw=ot.writev,In=Symbol("_autoClose"),At=Symbol("_close"),yi=Symbol("_ended"),ue=Symbol("_fd"),cc=Symbol("_finished"),Qt=Symbol("_flags"),dc=Symbol("_flush"),Rc=Symbol("_handleChunk"),Pc=Symbol("_makeBuf"),Di=Symbol("_mode"),Us=Symbol("_needDrain"),Pr=Symbol("_onerror"),Dr=Symbol("_onopen"),lc=Symbol("_onread"),kr=Symbol("_onwrite"),An=Symbol("_open"),It=Symbol("_path"),yn=Symbol("_pos"),Pt=Symbol("_queue"),Tr=Symbol("_read"),uc=Symbol("_readSize"),Xt=Symbol("_reading"),bi=Symbol("_remain"),fc=Symbol("_size"),Js=Symbol("_write"),Fn=Symbol("_writing"),Ys=Symbol("_defaultFlag"),Wn=Symbol("_errored"),Xc=class extends Zn{[Wn]=!1;[ue];[It];[uc];[Xt]=!1;[fc];[bi];[In];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Wn]=!1,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[It]=t,this[uc]=e.readSize||16*1024*1024,this[Xt]=!1,this[fc]=typeof e.size=="number"?e.size:1/0,this[bi]=this[fc],this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ue]=="number"?this[Tr]():this[An]()}get fd(){return this[ue]}get path(){return this[It]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[An](){ot.open(this[It],"r",(t,e)=>this[Dr](t,e))}[Dr](t,e){t?this[Pr](t):(this[ue]=e,this.emit("open",e),this[Tr]())}[Pc](){return Buffer.allocUnsafe(Math.min(this[uc],this[bi]))}[Tr](){if(!this[Xt]){this[Xt]=!0;let t=this[Pc]();if(t.length===0)return process.nextTick(()=>this[lc](null,0,t));ot.read(this[ue],t,0,t.length,null,(e,n,i)=>this[lc](e,n,i))}}[lc](t,e,n){this[Xt]=!1,t?this[Pr](t):this[Rc](e,n)&&this[Tr]()}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Pr](t){this[Xt]=!0,this[At](),this.emit("error",t)}[Rc](t,e){let n=!1;return this[bi]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[bi]<=0)&&(n=!1,this[At](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ue]=="number"&&this[Tr](),!1;case"error":return this[Wn]?!1:(this[Wn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Dw=class extends Xc{[An](){let t=!0;try{this[Dr](null,ot.openSync(this[It],"r")),t=!1}finally{t&&this[At]()}}[Tr](){let t=!0;try{if(!this[Xt]){this[Xt]=!0;do{let e=this[Pc](),n=e.length===0?0:ot.readSync(this[ue],e,0,e.length,null);if(!this[Rc](n,e))break}while(!0);this[Xt]=!1}t=!1}finally{t&&this[At]()}}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.closeSync(t),this.emit("close")}}},ho=class extends _w{readable=!1;writable=!0;[Wn]=!1;[Fn]=!1;[yi]=!1;[Pt]=[];[Us]=!1;[It];[Di];[In];[ue];[Ys];[Qt];[cc]=!1;[yn];constructor(t,e){e=e||{},super(e),this[It]=t,this[ue]=typeof e.fd=="number"?e.fd:void 0,this[Di]=e.mode===void 0?438:e.mode,this[yn]=typeof e.start=="number"?e.start:void 0,this[In]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[yn]!==void 0?"r+":"w";this[Ys]=e.flags===void 0,this[Qt]=e.flags===void 0?n:e.flags,this[ue]===void 0&&this[An]()}emit(t,...e){if(t==="error"){if(this[Wn])return!1;this[Wn]=!0}return super.emit(t,...e)}get fd(){return this[ue]}get path(){return this[It]}[Pr](t){this[At](),this[Fn]=!0,this.emit("error",t)}[An](){ot.open(this[It],this[Qt],this[Di],(t,e)=>this[Dr](t,e))}[Dr](t,e){this[Ys]&&this[Qt]==="r+"&&t&&t.code==="ENOENT"?(this[Qt]="w",this[An]()):t?this[Pr](t):(this[ue]=e,this.emit("open",e),this[Fn]||this[dc]())}end(t,e){return t&&this.write(t,e),this[yi]=!0,!this[Fn]&&!this[Pt].length&&typeof this[ue]=="number"&&this[kr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[yi]?(this.emit("error",new Error("write() after end()")),!1):this[ue]===void 0||this[Fn]||this[Pt].length?(this[Pt].push(t),this[Us]=!0,!1):(this[Fn]=!0,this[Js](t),!0)}[Js](t){ot.write(this[ue],t,0,t.length,this[yn],(e,n)=>this[kr](e,n))}[kr](t,e){t?this[Pr](t):(this[yn]!==void 0&&typeof e=="number"&&(this[yn]+=e),this[Pt].length?this[dc]():(this[Fn]=!1,this[yi]&&!this[cc]?(this[cc]=!0,this[At](),this.emit("finish")):this[Us]&&(this[Us]=!1,this.emit("drain"))))}[dc](){if(this[Pt].length===0)this[yi]&&this[kr](null,0);else if(this[Pt].length===1)this[Js](this[Pt].pop());else{let t=this[Pt];this[Pt]=[],Pw(this[ue],t,this[yn],(e,n)=>this[kr](e,n))}}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Ef=class extends ho{[An](){let t;if(this[Ys]&&this[Qt]==="r+")try{t=ot.openSync(this[It],this[Qt],this[Di])}catch(e){if(e?.code==="ENOENT")return this[Qt]="w",this[An]();throw e}else t=ot.openSync(this[It],this[Qt],this[Di]);this[Dr](null,t)}[At](){if(this[In]&&typeof this[ue]=="number"){let t=this[ue];this[ue]=void 0,ot.closeSync(t),this.emit("close")}}[Js](t){let e=!0;try{this[kr](null,ot.writeSync(this[ue],t,0,t.length,this[yn])),e=!1}finally{if(e)try{this[At]()}catch{}}}},Nw=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"]]),Mw=t=>!!t.sync&&!!t.file,Bw=t=>!t.sync&&!!t.file,Fw=t=>!!t.sync&&!t.file,zw=t=>!t.sync&&!t.file,Uw=t=>!!t.file,Hw=t=>Nw.get(t)||t,Qc=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=Hw(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Hi=(t,e,n,i,o)=>Object.assign((a=[],d,u)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let f=Qc(a);if(o?.(f,d),Mw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(Bw(f)){let x=e(f,d);return u?x.then(()=>u(),u):x}else if(Fw(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,d)}else if(zw(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),jw=qw.constants||{ZLIB_VERNUM:4736},Mt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},jw)),Ww=Kn.concat,qu=Object.getOwnPropertyDescriptor(Kn,"concat"),Kw=t=>t,hc=qu?.writable===!0||qu?.set!==void 0?t=>{Kn.concat=t?Kw:Ww}:t=>{},$n=Symbol("_superWrite"),Hs=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"}},xc=Symbol("flushFlag"),ed=class extends Zn{#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 Gu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Gu[e](t)}catch(n){throw new Hs(n,this.constructor)}this.#o=n=>{this.#e||(this.#e=!0,this.close(),this.emit("error",n))},this.#t?.on("error",n=>this.#o(new Hs(n))),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(Kn.alloc(0),{[xc]:t})))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(n)}get ended(){return this.#n}[$n](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Kn.from(t,e)),this.#e)return;Dc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},hc(!0);let d;try{let f=typeof t[xc]=="number"?t[xc]:this.#r;d=this.#t._processChunk(t,f),hc(!1)}catch(f){hc(!1),this.#o(new Hs(f,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",f=>this.#o(new Hs(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[$n](Kn.from(f));for(let x=1;x<d.length;x++)u=this[$n](d[x])}else u=this[$n](Kn.from(d));return n&&n(),u}},Sf=class extends ed{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Mt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Mt.Z_FINISH,t.fullFlushFlag=Mt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Mt.Z_SYNC_FLUSH),Dc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},$w=class extends Sf{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[$n](t){return this.#e?(this.#e=!1,t[9]=255,super[$n](t)):super[$n](t)}},Vw=class extends Sf{constructor(t){super(t,"Unzip")}},If=class extends ed{constructor(t,e){t=t||{},t.flush=t.flush||Mt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Mt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Mt.BROTLI_OPERATION_FLUSH,super(t,e)}},Zw=class extends If{constructor(t){super(t,"BrotliCompress")}},Jw=class extends If{constructor(t){super(t,"BrotliDecompress")}},Af=class extends ed{constructor(t,e){t=t||{},t.flush=t.flush||Mt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Mt.ZSTD_e_end,t.fullFlushFlag=Mt.ZSTD_e_flush,super(t,e)}},Yw=class extends Af{constructor(t){super(t,"ZstdCompress")}},Xw=class extends Af{constructor(t){super(t,"ZstdDecompress")}},Qw=(t,e)=>{if(Number.isSafeInteger(t))t<0?t_(t,e):e_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},e_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},t_=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),n?e[i-1]=kf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=Tf(o))}},n_=t=>{let e=t[0],n=e===128?i_(t.subarray(1,t.length)):e===255?r_(t):null;if(n===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(n))throw Error("parsed number outside of javascript safe integer range");return n},r_=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=kf(a):a===0?d=a:(i=!0,d=Tf(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},i_=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(n+=o*Math.pow(256,e-i-1))}return n},kf=t=>(255^t)&255,Tf=t=>(255^t)+1&255,s_={};ww(s_,{code:()=>td,isCode:()=>Xs,isName:()=>o_,name:()=>xo,normalFsTypes:()=>Cf});var Xs=t=>xo.has(t),o_=t=>td.has(t),Cf=new Set(["0","","1","2","3","4","5","6","7","D"]),xo=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"]]),td=new Map(Array.from(xo).map(t=>[t[1],t[0]])),a_=t=>t===void 0||t<0?void 0:t,Vn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=zn(t,e+156,1),a=Cf.has(o),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??zn(t,e,100),this.mode=d?.mode??u?.mode??bn(t,e+100,8),this.uid=d?.uid??u?.uid??bn(t,e+108,8),this.gid=d?.gid??u?.gid??bn(t,e+116,8),this.size=a_(d?.size??u?.size??bn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??pc(t,e+136,12),this.cksum=bn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Xs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=zn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??zn(t,e+265,32),this.gname=d?.gname??u?.gname??zn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??bn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??bn(t,e+337,8)??0,t[e+475]!==0){let x=zn(t,e+345,155);this.path=x+"/"+this.path}else{let x=zn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??pc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??pc(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="size"&&Number(i)<0||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=c_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Un(t,e,100,o)||this.needPax,this.needPax=En(t,e+100,8,this.mode)||this.needPax,this.needPax=En(t,e+108,8,this.uid)||this.needPax,this.needPax=En(t,e+116,8,this.gid)||this.needPax,this.needPax=En(t,e+124,12,this.size)||this.needPax,this.needPax=gc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Un(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Un(t,e+265,32,this.uname)||this.needPax,this.needPax=Un(t,e+297,32,this.gname)||this.needPax,this.needPax=En(t,e+329,8,this.devmaj)||this.needPax,this.needPax=En(t,e+337,8,this.devmin)||this.needPax,this.needPax=Un(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Un(t,e+345,155,a)||this.needPax:(this.needPax=Un(t,e+345,130,a)||this.needPax,this.needPax=gc(t,e+476,12,this.atime)||this.needPax,this.needPax=gc(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,En(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:xo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(td.get(t));if(Xs(e)||e==="Unsupported")this.#e=e;else if(Xs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},c_=(t,e)=>{let n=t,i="",o,a=Er.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Er.dirname(n),n=Er.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?o=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?o=[n.slice(0,99),i,!0]:(n=Er.join(Er.basename(i),n),i=Er.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},zn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),pc=(t,e,n)=>d_(bn(t,e,n)),d_=t=>t===void 0?void 0:new Date(t*1e3),bn=(t,e,n)=>Number(t[e])&128?n_(t.subarray(e,e+n)):u_(t,e,n),l_=t=>isNaN(t)?void 0:t,u_=(t,e,n)=>l_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),f_={12:8589934591,8:2097151},En=(t,e,n,i)=>i===void 0?!1:i>f_[n]||i<0?(Qw(i,t.subarray(e,e+n)),!0):(h_(t,e,n,i),!1),h_=(t,e,n,i)=>t.write(x_(i,n),e,n,"ascii"),x_=(t,e)=>p_(Math.floor(t).toString(8),e),p_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",gc=(t,e,n,i)=>i===void 0?!1:En(t,e,n,i.getTime()/1e3),g_=new Array(156).join("\0"),Un=(t,e,n,i)=>i===void 0?!1:(t.write(i+g_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),ao=class Rf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),o=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)o[a]=0;new Vn({path:("PaxHeader/"+m_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,n,"utf8");for(let a=n+512;a<o.length;a++)o[a]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,a=Buffer.byteLength(o),d=Math.floor(Math.log(a)/Math.log(10))+1;return a+d>=Math.pow(10,d)&&(d+=1),d+a+o}static parse(e,n,i=!1){return new Rf(w_(__(e),n),i)}},w_=(t,e)=>e?Object.assign({},e,t):t,__=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(y_,Object.create(null)),y_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let a=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(a){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[a]=d;break;case"ctime":case"atime":case"mtime":t[a]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[a]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},b_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Q=b_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),E_=class extends Zn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Q(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Q(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,i=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#e(t,e=!1){t.path&&(t.path=Q(t.path)),t.linkpath&&(t.linkpath=Q(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},po=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},v_=1024*1024,Oc=Buffer.from([31,139]),Lc=Buffer.from([40,181,47,253]),S_=Math.max(Oc.length,Lc.length),xt=Symbol("state"),Hn=Symbol("writeEntry"),Jt=Symbol("readEntry"),mc=Symbol("nextEntry"),ju=Symbol("processEntry"),Dt=Symbol("extendedHeader"),Ei=Symbol("globalExtendedHeader"),mn=Symbol("meta"),Wu=Symbol("emitMeta"),we=Symbol("buffer"),Yt=Symbol("queue"),wn=Symbol("ended"),wc=Symbol("emittedEnd"),Gn=Symbol("emit"),Te=Symbol("unzip"),Gs=Symbol("consumeChunk"),qs=Symbol("consumeChunkSub"),_c=Symbol("consumeBody"),Ku=Symbol("consumeMeta"),$u=Symbol("consumeHeader"),vi=Symbol("consuming"),yc=Symbol("bufferConcat"),js=Symbol("maybeEnd"),vr=Symbol("writing"),Ot=Symbol("aborted"),Ws=Symbol("onDone"),qn=Symbol("sawValidEntry"),Ks=Symbol("sawNullBlock"),$s=Symbol("sawEOF"),Vu=Symbol("closeStream"),I_=1e3,Si=Symbol("compressedBytesRead"),bc=Symbol("decompressedBytesRead"),Zu=Symbol("checkDecompressionRatio"),A_=()=>!0,Ui=class extends Gw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[Yt]=[];[we];[Jt];[Hn];[xt]="begin";[mn]="";[Dt];[Ei];[wn]=!1;[Te];[Ot]=!1;[qn];[Ks]=!1;[$s]=!1;[vr]=!1;[vi]=!1;[wc]=!1;[Si]=0;[bc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Ws,()=>{(this[xt]==="begin"||this[qn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ws,t.ondone):this.on(Ws,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:I_,this.maxMetaEntrySize=t.maxMetaEntrySize||v_,this.filter=typeof t.filter=="function"?t.filter:A_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[Vu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){po(this,t,e,n)}[$u](t,e){this[qn]===void 0&&(this[qn]=!1);let n;try{n=new Vn(t,e,this[Dt],this[Ei])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Ks]?(this[$s]=!0,this[xt]==="begin"&&(this[xt]="header"),this[Gn]("eof")):(this[Ks]=!0,this[Gn]("nullBlock"));else if(this[Ks]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let o=this[Hn]=new E_(n,this[Dt],this[Ei]);if(!this[qn])if(o.remain){let a=()=>{o.invalid||(this[qn]=!0)};o.on("end",a)}else this[qn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Gn]("ignoredEntry",o),this[xt]="ignore",o.resume()):o.size>0&&(this[mn]="",o.on("data",a=>this[mn]+=a),this[xt]="meta"):(this[Dt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Gn]("ignoredEntry",o),this[xt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[xt]="body":(this[xt]="header",o.end()),this[Jt]?this[Yt].push(o):(this[Yt].push(o),this[mc]())))}}}[Vu](){queueMicrotask(()=>this.emit("close"))}[ju](t){let e=!0;if(!t)this[Jt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Jt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[mc]()),e=!1);return e}[mc](){do;while(this[ju](this[Yt].shift()));if(this[Yt].length===0){let t=this[Jt];!t||t.flowing||t.size===t.remain?this[vr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[_c](t,e){let n=this[Hn];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(o),n.blockRemain||(this[xt]="header",this[Hn]=void 0,n.end()),o.length}[Ku](t,e){let n=this[Hn],i=this[_c](t,e);return!this[Hn]&&n&&this[Wu](n),i}[Gn](t,e,n){this[Yt].length===0&&!this[Jt]?this.emit(t,e,n):this[Yt].push([t,e,n])}[Wu](t){switch(this[Gn]("meta",this[mn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Dt]=ao.parse(this[mn],this[Dt],!1);break;case"GlobalExtendedHeader":this[Ei]=ao.parse(this[mn],this[Ei],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Dt]??Object.create(null);this[Dt]=e,e.path=this[mn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Dt]||Object.create(null);this[Dt]=e,e.linkpath=this[mn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ot]){if(this[Te]){let e=this[Te];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ot]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Zu](t){this[bc]+=t.length;let e=this[bc]/this[Si];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Ot])return n?.(),!1;if((this[Te]===void 0||this.brotli===void 0&&this[Te]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<S_)return this[we]=t,n?.(),!0;for(let d=0;this[Te]===void 0&&d<Oc.length;d++)t[d]!==Oc[d]&&(this[Te]=!1);let o=!1;if(this[Te]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Lc.length;d++)if(t[d]!==Lc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Te]===!1&&a)if(t.length<512)if(this[wn])this.brotli=!0;else return this[we]=t,n?.(),!0;else try{new Vn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Te]===void 0||this[Te]===!1&&(this.brotli||o)){let d=this[wn];this[wn]=!1,this[Te]=this[Te]===void 0?new Vw({}):o?new Xw({}):new Jw({}),this[Te].on("data",f=>{this[Zu](f)&&this[Gs](f)}),this[Te].on("error",f=>{this[Ot]||this.abort(f)}),this[Te].on("end",()=>{this[wn]=!0,this[Gs]()}),this[vr]=!0,this[Si]+=t.length;let u=!!this[Te][d?"end":"write"](t);return this[vr]=!1,n?.(),u}}this[vr]=!0,this[Te]?(this[Si]+=t.length,this[Te].write(t)):this[Gs](t),this[vr]=!1;let i=this[Yt].length>0?!1:this[Jt]?this[Jt].flowing:!0;return!i&&this[Yt].length===0&&this[Jt]?.once("drain",()=>this.emit("drain")),n?.(),i}[yc](t){t&&!this[Ot]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[js](){if(this[wn]&&!this[wc]&&!this[Ot]&&!this[vi]){this[wc]=!0;let t=this[Hn];if(t?.blockRemain){let e=this[we]?this[we].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[we]&&t.write(this[we]),t.end()}this[Gn](Ws)}}[Gs](t){if(this[vi]&&t)this[yc](t);else if(!t&&!this[we])this[js]();else if(t){if(this[vi]=!0,this[we]){this[yc](t);let e=this[we];this[we]=void 0,this[qs](e)}else this[qs](t);for(;this[we]&&this[we]?.length>=512&&!this[Ot]&&!this[$s];){let e=this[we];this[we]=void 0,this[qs](e)}this[vi]=!1}(!this[we]||this[wn])&&this[js]()}[qs](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ot]&&!this[$s];)switch(this[xt]){case"begin":case"header":this[$u](t,e),e+=512;break;case"ignore":case"body":e+=this[_c](t,e);break;case"meta":e+=this[Ku](t,e);break;default:throw new Error("invalid state: "+this[xt])}e<n&&(this[we]=this[we]?Buffer.concat([t.subarray(e),this[we]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Ot]||(this[Te]?(t&&(this[Si]+=t.length,this[Te].write(t)),this[Te].end()):(this[wn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[js]())),this}},Oi=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},k_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Pf=(t,e)=>{let n=new Map(e.map(a=>[Oi(a),!0])),i=t.filter,o=(a,d="")=>{let u=d||Lw(a).root||".",f;if(a===u)f=!1;else{let x=n.get(a);f=x!==void 0?x:o(Ow(a),u)}return n.set(a,f),f};t.filter=i?(a,d)=>i(a,d)&&o(Oi(a)):a=>o(Oi(a))},T_=t=>{let e=new Ui(t),n=t.file,i;try{i=Cr.openSync(n,"r");let o=Cr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=Cr.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(a);for(;d<o.size;){let f=Cr.readSync(i,u,0,a,d);if(f===0)break;d+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Cr.closeSync(i)}catch{}}},C_=(t,e)=>{let n=new Ui(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Cr.stat(o,(u,f)=>{if(u)d(u);else{let x=new Xc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},Or=Hi(T_,C_,t=>new Ui(t),t=>new Ui(t),(t,e)=>{e?.length&&Pf(t,e),t.noResume||k_(t)}),Df=(t,e,n)=>(t&=4095,n&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:P_,parse:Yu}=R_,nd=t=>{let e="",n=Yu(t);for(;P_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Yu(t)}return[e,t]},go=["|","<",">","?",":"],rd=go.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),D_=new Map(go.map((t,e)=>[t,rd[e]])),O_=new Map(rd.map((t,e)=>[t,go[e]])),Xu=t=>go.reduce((e,n)=>e.split(n).join(D_.get(n)),t),L_=t=>rd.reduce((e,n)=>e.split(n).join(O_.get(n)),t),Of=(t,e)=>e?(t=Q(t).replace(/^\.(\/|$)/,""),Oi(e)+"/"+t):Q(t),N_=16*1024*1024,Qu=Symbol("process"),ef=Symbol("file"),tf=Symbol("directory"),Nc=Symbol("symlink"),nf=Symbol("hardlink"),Ii=Symbol("header"),Qs=Symbol("read"),Mc=Symbol("lstat"),eo=Symbol("onlstat"),Bc=Symbol("onread"),Fc=Symbol("onreadlink"),zc=Symbol("openfile"),Uc=Symbol("onopenfile"),vn=Symbol("close"),lo=Symbol("mode"),Hc=Symbol("awaitDrain"),Ec=Symbol("ondrain"),Nt=Symbol("prefix"),Lf=class extends Zn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let n=Qc(e);super(),this.path=Q(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||N_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=Q(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?Q(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[a,d]=nd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=L_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Q(n.absolute||Ju.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[eo](o):this[Mc]()}warn(t,e,n={}){return po(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Mc](){Lt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[eo](e)})}[eo](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=F_(t),this.emit("stat",t),this[Qu]()}[Qu](){switch(this.type){case"File":return this[ef]();case"Directory":return this[tf]();case"SymbolicLink":return this[Nc]();default:return this.end()}}[lo](t){return Df(t,this.type==="Directory",this.portable)}[Nt](t){return Of(t,this.prefix)}[Ii](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new Vn({path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](this.linkpath):this.linkpath,mode:this[lo](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 ao({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[tf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ii](),this.end()}[Nc](){Lt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Fc](e)})}[Fc](t){this.linkpath=Q(t),this[Ii](),this.end()}[nf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Q(Ju.relative(this.cwd,t)),this.stat.size=0,this[Ii](),this.end()}[ef](){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[nf](e);this.linkCache.set(t,this.absolute)}if(this[Ii](),this.stat.size===0)return this.end();this[zc]()}[zc](){Lt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Uc](e)})}[Uc](t){if(this.fd=t,this.#e)return this[vn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Qs]()}[Qs](){let{fd:t,buf:e,offset:n,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Lt.read(t,e,n,i,o,(a,d)=>{if(a)return this[vn](()=>this.emit("error",a));this[Bc](d)})}[vn](t=()=>{}){this.fd!==void 0&&Lt.close(this.fd,t)}[Bc](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[vn](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[vn](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[Ec]():this[Hc](()=>this[Ec]())}[Hc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[Ec](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[vn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Qs]()}},M_=class extends Lf{sync=!0;[Mc](){this[eo](Lt.lstatSync(this.absolute))}[Nc](){this[Fc](Lt.readlinkSync(this.absolute))}[zc](){this[Uc](Lt.openSync(this.absolute,"r"))}[Qs](){let t=!0;try{let{fd:e,buf:n,offset:i,length:o,pos:a}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Lt.readSync(e,n,i,o,a);this[Bc](d),t=!1}finally{if(t)try{this[vn](()=>{})}catch{}}}[Hc](t){t()}[vn](t=()=>{}){this.fd!==void 0&&Lt.closeSync(this.fd),t()}},B_=class extends Zn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return po(this,t,e,n)}constructor(t,e={}){let n=Qc(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=Q(t.path),this.mode=t.mode!==void 0?this[lo](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:n.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Q(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=nd(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new Vn({path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new ao({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Nt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Nt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let a=this.header?.block;if(!a)throw new Error("failed to encode header");super.write(a),t.pipe(this)}[Nt](t){return Of(t,this.prefix)}[lo](t){return Df(t,this.type==="Directory",this.portable)}write(t,e,n){typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,n)}end(t,e,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),n&&this.once("finish",n),t?super.end(t,n):super.end(n),this}},F_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",z_=class Rr{tail;head;length=0;static create(e=[]){return new Rr(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)H_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)G_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,o=0;i;o++)e.call(n,i.value,o,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(n,i.value,o,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Rr;for(let o=this.head;o;)i.push(e.call(n,o.value,this)),o=o.next;return i}mapReverse(e,n){n=n||this;var i=new Rr;for(let o=this.tail;o;)i.push(e.call(n,o.value,this)),o=o.prev;return i}reduce(e,n){let i,o=this.head;if(arguments.length>1)i=n;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;o;a++)i=e(i,o.value,a),o=o.next;return i}reduceReverse(e,n){let i,o=this.tail;if(arguments.length>1)i=n;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;o;a--)i=e(i,o.value,a),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Rr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.head,a=0;for(a=0;o&&a<e;a++)o=o.next;for(;o&&a<n;a++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Rr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let o=this.length,a=this.tail;for(;a&&o>n;o--)a=a.prev;for(;a&&o>e;o--,a=a.prev)i.push(a.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let a=[];for(let d=0;o&&d<n;d++)a.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=U_(this,o,d);return a}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=n,this.tail=e,this}};function U_(t,e,n){let i=e,o=e?e.next:t.head,a=new id(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function H_(t,e){t.tail=new id(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function G_(t,e){t.head=new id(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var id=class{list;next;prev;value;constructor(t,e,n,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},sf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},of=Buffer.alloc(1024),to=Symbol("onStat"),Ai=Symbol("ended"),vt=Symbol("queue"),ki=Symbol("pendingLinks"),_n=Symbol("current"),jn=Symbol("process"),Ti=Symbol("processing"),Vs=Symbol("processJob"),St=Symbol("jobs"),vc=Symbol("jobDone"),no=Symbol("addFSEntry"),af=Symbol("addTarEntry"),Gc=Symbol("stat"),qc=Symbol("readdir"),ro=Symbol("onreaddir"),io=Symbol("pipe"),cf=Symbol("entry"),Sc=Symbol("entryOpt"),so=Symbol("writeEntryClass"),Nf=Symbol("write"),Ic=Symbol("ondrain"),mo=class extends Zn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[so];onWriteEntry;[vt];[ki]=new Map;[St]=0;[Ti]=!1;[Ai]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Q(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[so]=Lf,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 $w(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Zw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Yw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[Ic]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Ic]);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[vt]=new z_,this[St]=0,this.jobs=Number(t.jobs)||4,this[Ti]=!1,this[Ai]=!1}[Nf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&this.add(t),this[Ai]=!0,this[jn](),n&&n(),this}write(t){if(this[Ai])throw new Error("write after end");return typeof t=="string"?this[no](t):this[af](t),this.flowing}[af](t){let e=Q(rf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new sf(t.path,e);n.entry=new B_(t,this[Sc](n)),n.entry.on("end",()=>this[vc](n)),this[St]+=1,this[vt].push(n)}this[jn]()}[no](t){let e=Q(rf.resolve(this.cwd,t));this[vt].push(new sf(t,e)),this[jn]()}[Gc](t){t.pending=!0,this[St]+=1;let e=this.follow?"stat":"lstat";co[e](t.absolute,(n,i)=>{t.pending=!1,this[St]-=1,n?this.emit("error",n):this[to](t,i)})}[to](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[_n])this[Vs](t);else{let n=`${e.dev}:${e.ino}`,i=this[ki].get(n);i?i.push(t):this[ki].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[jn]()}[qc](t){t.pending=!0,this[St]+=1,co.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[St]-=1,e)return this.emit("error",e);this[ro](t,n)})}[ro](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[jn]()}[jn](){if(!this[Ti]){this[Ti]=!0;for(let t=this[vt].head;t&&this[St]<this.jobs;t=t.next)if(this[Vs](t.value),t.value.ignore){let e=t.next;this[vt].removeNode(t),t.next=e}this[Ti]=!1,this[Ai]&&this[vt].length===0&&this[St]===0&&(this.zip?this.zip.end(of):(super.write(of),super.end()))}}get[_n](){return this[vt]&&this[vt].head&&this[vt].head.value}[vc](t){this[vt].shift(),this[St]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[ki].get(n);if(i){this[ki].delete(n);for(let o of i)o.pending=!1,this[Vs](o)}}this[jn]()}[Vs](t){if(t.pending&&t.pendingLink&&t===this[_n]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[_n]&&!t.piped&&this[io](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[to](t,e):this[Gc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[ro](t,e):this[qc](t),!t.readdir)return}if(t.entry=this[cf](t),!t.entry){t.ignore=!0;return}t===this[_n]&&!t.piped&&this[io](t)}}}[Sc](t){return{onwarn:(e,n,i)=>this.warn(e,n,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[cf](t){this[St]+=1;try{return new this[so](t.path,this[Sc](t)).on("end",()=>this[vc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Ic](){this[_n]&&this[_n].entry&&this[_n].entry.resume()}[io](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[no](a+i)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",i=>{n.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,n={}){po(this,t,e,n)}},sd=class extends mo{sync=!0;constructor(t){super(t),this[so]=M_}pause(){}resume(){}[Gc](t){let e=this.follow?"statSync":"lstatSync";this[to](t,co[e](t.absolute))}[qc](t){this[ro](t,co.readdirSync(t.absolute))}[io](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[no](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Nf](i)})}},q_=(t,e)=>{let n=new sd(t),i=new Ef(t.file,{mode:t.mode||438});n.pipe(i),Mf(n,e)},j_=(t,e)=>{let n=new mo(t),i=new ho(t.file,{mode:t.mode||438});n.pipe(i);let o=new Promise((a,d)=>{i.on("error",d),i.on("close",a),n.on("error",d)});return Bf(n,e).catch(a=>n.emit("error",a)),o},Mf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Or({file:vf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Bf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Or({file:vf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},W_=(t,e)=>{let n=new sd(t);return Mf(n,e),n},K_=(t,e)=>{let n=new mo(t);return Bf(n,e).catch(i=>n.emit("error",i)),n},ik=Hi(q_,j_,W_,K_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),V_=process.env.__FAKE_PLATFORM__||process.platform,Hf=V_==="win32",{O_CREAT:Gf,O_NOFOLLOW:df,O_TRUNC:qf,O_WRONLY:jf}=Uf.constants,Wf=Number(process.env.__FAKE_FS_O_FILENAME__)||Uf.constants.UV_FS_O_FILEMAP||0,Z_=Hf&&!!Wf,J_=512*1024,Y_=Wf|qf|Gf|jf,lf=!Hf&&typeof df=="number"?df|qf|Gf|jf:null,Kf=lf!==null?()=>lf:Z_?t=>t<J_?Y_:"w":()=>"w",jc=(t,e,n)=>{try{return wo.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},uo=(t,e,n,i)=>{wo.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},X_=(t,e,n,i,o)=>{if(e.isDirectory())$f(Li.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=Li.resolve(t,e.name);uo(d,n,i,o)});else{let a=Li.resolve(t,e.name);uo(a,n,i,o)}},$f=(t,e,n,i)=>{wo.readdir(t,{withFileTypes:!0},(o,a)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!a.length)return uo(t,e,n,i);let d=a.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return uo(t,e,n,i)}};for(let x of a)X_(t,x,e,n,f)})},Q_=(t,e,n,i)=>{e.isDirectory()&&Vf(Li.resolve(t,e.name),n,i),jc(Li.resolve(t,e.name),n,i)},Vf=(t,e,n)=>{let i;try{i=wo.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return jc(t,e,n);throw a}for(let o of i)Q_(t,o,e,n);return jc(t,e,n)},Zf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},_o=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"}},ty=(t,e)=>{ut.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new Zf(t,n?.code||"ENOTDIR")),e(n)})},ny=(t,e,n)=>{t=Q(t);let i=e.umask??18,o=e.mode|448,a=(o&i)!==0,d=e.uid,u=e.gid,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,m=Q(e.cwd),v=(b,S)=>{b?n(b):S&&f?$f(S,d,u,I=>v(I)):a?ut.chmod(t,o,n):n()};if(t===m)return ty(t,v);if(x)return ey.mkdir(t,{mode:o,recursive:!0}).then(b=>v(null,b??void 0),v);let _=Q(fo.relative(m,t)).split("/");Wc(m,_,o,p,m,void 0,v)},Wc=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),f=Q(fo.resolve(t+"/"+u));ut.mkdir(f,n,Jf(f,e,n,i,o,a,d))},Jf=(t,e,n,i,o,a,d)=>u=>{u?ut.lstat(t,(f,x)=>{if(f)f.path=f.path&&Q(f.path),d(f);else if(x.isDirectory())Wc(t,e,n,i,o,a,d);else if(i)ut.unlink(t,p=>{if(p)return d(p);ut.mkdir(t,n,Jf(t,e,n,i,o,a,d))});else{if(x.isSymbolicLink())return d(new _o(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,Wc(t,e,n,i,o,a,d))},ry=t=>{let e=!1,n;try{e=ut.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new Zf(t,n??"ENOTDIR")}},iy=(t,e)=>{t=Q(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),f=e.preserve,x=e.unlink,p=Q(e.cwd),m=b=>{b&&u&&Vf(b,a,d),o&&ut.chmodSync(t,i)};if(t===p)return ry(p),m();if(f)return m(ut.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=Q(fo.relative(p,t)).split("/"),_;for(let b=v.shift(),S=p;b&&(S+="/"+b);b=v.shift()){S=Q(fo.resolve(S));try{ut.mkdirSync(S,i),_=_||S}catch{let I=ut.lstatSync(S);if(I.isDirectory())continue;if(x){ut.unlinkSync(S),ut.mkdirSync(S,i),_=_||S;continue}else if(I.isSymbolicLink())return new _o(S,S+"/"+v.join("/"))}}return m(_)},Ac=Object.create(null),uf=1e4,Sr=new Set,sy=t=>{Sr.has(t)?Sr.delete(t):Ac[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Sr.add(t);let e=Ac[t],n=Sr.size-uf;if(n>uf/10){for(let i of Sr)if(Sr.delete(i),delete Ac[i],--n<=0)break}return e},oy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ay=oy==="win32",cy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Yf(i,n)),e.push(n||"/"),e},[]),dy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=ay?["win32 parallelization disabled"]:t.map(i=>Oi(Yf(sy(i))));let n=new Set(t.map(i=>cy(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of n){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let a=o.at(-1);a instanceof Set?a.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,o=new Set;for(let a of n){let d=this.#e.get(a);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(a);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let a of i){let d=this.#e.get(a),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(a);continue}else if(u.size===1){d.shift();let f=d[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(a=>this.#i(a)),!0}},ly=()=>process.umask(),ff=Symbol("onEntry"),Kc=Symbol("checkFs"),hf=Symbol("checkFs2"),$c=Symbol("isReusable"),pt=Symbol("makeFs"),Vc=Symbol("file"),Zc=Symbol("directory"),oo=Symbol("link"),xf=Symbol("symlink"),pf=Symbol("hardlink"),Pi=Symbol("ensureNoSymlink"),gf=Symbol("unsupported"),mf=Symbol("checkPath"),kc=Symbol("stripAbsolutePath"),Sn=Symbol("mkdir"),$e=Symbol("onError"),Zs=Symbol("pending"),wf=Symbol("pend"),Ir=Symbol("unpend"),Tc=Symbol("ended"),Cc=Symbol("maybeClose"),Jc=Symbol("skip"),Ni=Symbol("doChown"),Mi=Symbol("uid"),Bi=Symbol("gid"),Fi=Symbol("checkedCwd"),uy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,zi=uy==="win32",fy=1024,hy=(t,e)=>{if(!zi)return oe.unlink(t,e);let n=t+".DELETE."+zf(16).toString("hex");oe.rename(t,n,i=>{if(i)return e(i);oe.unlink(n,e)})},xy=t=>{if(!zi)return oe.unlinkSync(t);let e=t+".DELETE."+zf(16).toString("hex");oe.renameSync(t,e),oe.unlinkSync(e)},_f=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,od=class extends Ui{[Tc]=!1;[Fi]=!1;[Zs]=0;reservations=new dy;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[Tc]=!0,this[Cc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:fy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||zi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Q(Ue.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:ly():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[ff](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Cc](){this[Tc]&&this[Zs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[kc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=nd(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||zi&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=Ue.posix.dirname(t.path),f=Ue.posix.normalize(Ue.posix.join(u,d.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return o&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:n})),!0}[mf](t){let e=Q(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=Q(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[kc](t,"path")||!this[kc](t,"linkpath"))return!1;if(t.absolute=Ue.isAbsolute(t.path)?Q(Ue.resolve(t.path)):Q(Ue.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Q(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Ue.win32.parse(String(t.absolute));t.absolute=i+Xu(String(t.absolute).slice(i.length));let{root:o}=Ue.win32.parse(t.path);t.path=o+Xu(t.path.slice(o.length))}return!0}[ff](t){if(!this[mf](t))return t.resume();switch($_.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[gf](t)}}[$e](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Ir](),e.resume())}[Sn](t,e,n){ny(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[Ni](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}[Mi](t){return _f(this.uid,t.uid,this.processUid)}[Bi](t){return _f(this.gid,t.gid,this.processGid)}[Vc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new ho(String(t.absolute),{flags:Kf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&oe.close(i.fd,()=>{}),i.write=()=>!0,this[$e](u,t),e()});let o=1,a=u=>{if(u){i.fd&&oe.close(i.fd,()=>{}),this[$e](u,t),e();return}--o===0&&i.fd!==void 0&&oe.close(i.fd,f=>{f?this[$e](f,t):this[Ir](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;oe.futimes(f,x,p,m=>m?oe.utimes(u,x,p,v=>a(v&&m)):a())}if(typeof f=="number"&&this[Ni](t)){o++;let x=this[Mi](t),p=this[Bi](t);typeof x=="number"&&typeof p=="number"&&oe.fchown(f,x,p,m=>m?oe.chown(u,x,p,v=>a(v&&m)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[$e](u,t),e()}),t.pipe(d)),d.pipe(i)}[Zc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Sn](String(t.absolute),n,i=>{if(i){this[$e](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Ir](),t.resume())};t.mtime&&!this.noMtime&&(o++,oe.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ni](t)&&(o++,oe.chown(String(t.absolute),Number(this[Mi](t)),Number(this[Bi](t)),a)),a()})}[gf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[xf](t,e){let n=Q(Ue.relative(this.cwd,Ue.resolve(Ue.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Pi](t,this.cwd,n,()=>this[oo](t,String(t.linkpath),"symlink",e),i=>{this[$e](i,t),e()})}[pf](t,e){let n=Q(Ue.resolve(this.cwd,String(t.linkpath))),i=Q(String(t.linkpath)).split("/");this[Pi](t,this.cwd,i,()=>this[oo](t,n,"link",e),o=>{this[$e](o,t),e()})}[Pi](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Ue.resolve(e,a);oe.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new _o(d,Ue.resolve(d,n.join("/"))));this[Pi](t,d,n,i,o)})}[wf](){this[Zs]++}[Ir](){this[Zs]--,this[Cc]()}[Jc](t){this[Ir](),t.resume()}[$c](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!zi}[Kc](t){this[wf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[hf](t,n))}[hf](t,e){let n=d=>{e(d)},i=()=>{this[Sn](this.cwd,this.dmode,d=>{if(d){this[$e](d,t),n();return}this[Fi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=Q(Ue.dirname(String(t.absolute)));if(d!==this.cwd)return this[Sn](d,this.dmode,u=>{if(u){this[$e](u,t),n();return}a()})}a()},a=()=>{oe.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Jc](t),n();return}if(d||this[$c](t,u))return this[pt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[pt](p??null,t,n);return f?oe.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return oe.rmdir(String(t.absolute),f=>this[pt](f??null,t,n))}if(t.absolute===this.cwd)return this[pt](null,t,n);hy(String(t.absolute),f=>this[pt](f??null,t,n))})};this[Fi]?o():i()}[pt](t,e,n){if(t){this[$e](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Vc](e,n);case"Link":return this[pf](e,n);case"SymbolicLink":return this[xf](e,n);case"Directory":case"GNUDumpDir":return this[Zc](e,n)}}[oo](t,e,n,i){oe[n](e,String(t.absolute),o=>{o?this[$e](o,t):(this[Ir](),t.resume()),i()})}},Ci=t=>{try{return[null,t()]}catch(e){return[e,null]}},Xf=class extends od{sync=!0;[pt](t,e){return super[pt](t,e,()=>{})}[Kc](t){if(!this[Fi]){let o=this[Sn](this.cwd,this.dmode);if(o)return this[$e](o,t);this[Fi]=!0}if(t.absolute!==this.cwd){let o=Q(Ue.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[Sn](o,this.dmode);if(a)return this[$e](a,t)}}let[e,n]=Ci(()=>oe.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Jc](t);if(e||this[$c](t,n))return this[pt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Ci(()=>{oe.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[pt](d,t)}let[o]=Ci(()=>oe.rmdirSync(String(t.absolute)));this[pt](o,t)}let[i]=t.absolute===this.cwd?[]:Ci(()=>xy(String(t.absolute)));this[pt](i,t)}[Vc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{oe.closeSync(o)}catch(f){u=f}(d||u)&&this[$e](d||u,t),e()},o;try{o=oe.openSync(String(t.absolute),Kf(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[$e](d,t)),t.pipe(a)),a.on("data",d=>{try{oe.writeSync(o,d,0,d.length)}catch(u){i(u)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{oe.futimesSync(o,u,f)}catch(x){try{oe.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[Ni](t)){let u=this[Mi](t),f=this[Bi](t);try{oe.fchownSync(o,Number(u),Number(f))}catch(x){try{oe.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[Zc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Sn](String(t.absolute),n);if(i){this[$e](i,t),e();return}if(t.mtime&&!this.noMtime)try{oe.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ni](t))try{oe.chownSync(String(t.absolute),Number(this[Mi](t)),Number(this[Bi](t)))}catch{}e(),t.resume()}[Sn](t,e){try{return iy(Q(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[Pi](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Ue.resolve(a,d);let[u,f]=Ci(()=>oe.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return o(new _o(a,Ue.resolve(e,n.join("/"))))}i()}[oo](t,e,n,i){let o=`${n}Sync`;try{oe[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[$e](a,t)}}},py=t=>{let e=new Xf(t),n=t.file,i=Ff.statSync(n),o=t.maxReadSize||16*1024*1024;new Dw(n,{readSize:o,size:i.size}).pipe(e)},gy=(t,e)=>{let n=new od(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Ff.stat(o,(u,f)=>{if(u)d(u);else{let x=new Xc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},Qf=Hi(py,gy,t=>new Xf(t),t=>new od(t),(t,e)=>{e?.length&&Pf(t,e)}),my=(t,e)=>{let n=new sd(t),i=!0,o,a;try{try{o=lt.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=lt.openSync(t.file,"w+");else throw f}let d=lt.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,m=0;p<512;p+=m){if(m=lt.readSync(o,u,p,u.length-p,a+p),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let f=new Vn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,wy(t,n,a,o,e)}finally{if(i)try{lt.closeSync(o)}catch{}}},wy=(t,e,n,i,o)=>{let a=new Ef(t.file,{fd:i,start:n});e.pipe(a),yy(e,o)},_y=(t,e)=>{e=Array.from(e);let n=new mo(t),i=(o,a,d)=>{let u=(v,_)=>{v?lt.close(o,b=>d(v)):d(null,_)},f=0;if(a===0)return u(null,0);let x=0,p=Buffer.alloc(512),m=(v,_)=>{if(v||_===void 0)return u(v);if(x+=_,x<512&&_)return lt.read(o,p,x,p.length-x,f+x,m);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let b=new Vn(p);if(!b.cksumValid)return u(null,f);let S=512*Math.ceil((b.size??0)/512);if(f+S+512>a||(f+=S+512,f>=a))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),x=0,lt.read(o,p,0,512,f,m)};lt.read(o,p,0,512,f,m)};return new Promise((o,a)=>{n.on("error",a);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",lt.open(t.file,d,u);if(f||!x)return a(f);lt.fstat(x,(p,m)=>{if(p)return lt.close(x,()=>a(p));i(x,m.size,(v,_)=>{if(v)return a(v);let b=new ho(t.file,{fd:x,start:_});n.pipe(b),b.on("error",a),b.on("close",o),by(n,e)})})};lt.open(t.file,d,u)})},yy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Or({file:e0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},by=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Or({file:e0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Ri=Hi(my,_y,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Uw(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")}),_k=Hi(Ri.syncFile,Ri.asyncFile,Ri.syncNoFile,Ri.asyncNoFile,(t,e=[])=>{Ri.validate?.(t,e),Ey(t)}),Ey=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(n,i)=>e(n,i)&&!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0)):(n,i)=>!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0))};$t();var gt={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 yo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function t0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function bo(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function n0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function r0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function i0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function Jn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}en();Je();te();Pe();Je();function Lr(t,e){if(yo(t)!=="cloud")throw new A("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Gi(t){return t.startsWith("http://")||t.startsWith("https://")}function Nr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as lT}from"node:fs";import{dirname as fT,join as hT}from"node:path";import{fileURLToPath as pT}from"node:url";var Bt="0.3.2-alpha.1";import{mkdir as zy,rm as E0}from"node:fs/promises";import{join as Ki}from"node:path";Kt();import{readFileSync as Ry}from"node:fs";var Py=384;async function ad(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await xn(t.agentEnvFile,n,{mode:Py})}function Yn(t){try{let e=JSON.parse(Ry(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Eo(t,e,n={},i=o=>o){return{...i({...t,...Yn(e)}),...n}}Kt();function qi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(Dy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return ek(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await kg("schtasks",["/Create","/SC","ONLOGON","/TN",Ma,"/TR",n,"/RU",t.userName,"/F"]),Pl.info("task scheduler entry created",{task:Ma,logFile:t.logFile})},async uninstall(t){await kg("schtasks",["/Delete","/TN",Ma,"/F"]).catch(e=>Pl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Pl.info("task scheduler entry removed",{task:Ma})}}});var Cg={};Ja(Cg,{buildContext:()=>ok,getSupervisor:()=>rk,launchdSupervisor:()=>Tl,systemdSupervisor:()=>Cl,taskSchedulerSupervisor:()=>Rl});import{homedir as tk,userInfo as nk}from"node:os";function rk(t=process.platform){switch(t){case"darwin":return Tl;case"linux":return Cl;case"win32":return Rl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function sk(){let t={};for(let e of ik){let n=process.env[e];n&&(t[e]=n)}return t}function ok(){let t=Z();return{nodeBin:process.execPath,entry:yl(t),logFile:t.logFile,homeDir:tk(),userName:nk().username,isRoot:process.getuid?.()===0,env:sk()}}var ik,Pg=st(()=>{"use strict";Pe();Aa();Sg();Ag();Tg();ik=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});re();_n();var au=H("acp-installer-warmup"),iw=["claude-code","codex"];async function cu(t={}){let e=t.ensure??Sr,i=(await Promise.allSettled(iw.map(async s=>{let a=await e(s);au.info("acp wrapper warmup ok",{framework:s,path:a})}))).filter(s=>s.status==="rejected");i.length>0&&au.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(s=>s.reason instanceof Error?s.reason.message:String(s.reason))})}Qt();re();import{readdir as _w}from"node:fs/promises";import{mkdir as fu,readFile as ww,writeFile as hu}from"node:fs/promises";import{join as rc}from"node:path";var yw={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function Ir(t,e,n){await fu(t,{recursive:!0});let i=yw[e],s=rc(t,i);return await hu(s,n??"","utf8"),s}async function ic(t,e,n){let i=rc(t,".claude");await fu(i,{recursive:!0});let s=rc(i,"settings.local.json"),a={};try{let u=await ww(s,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(a=f)}catch{}let d=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return a.permissions=d,await hu(s,JSON.stringify(a,null,2),"utf8"),s}var Qe=H("agent-detail-sync"),bw=6e4,Ew=5*6e4,Bs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await _w(n)}catch(s){Qe.info("agents dir not found, skip detail sync",{root:n,err:String(s)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let a=await me(s,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,a)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:s,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,s]of this.retryQueue)e>=s.dueAt&&n.push(i);if(n.length!==0){Qe.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(s){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,n){let i=n??await me(e,this.opts.paths);if(!i){Qe.info("detail sync: agent config missing, skip",{agentId:e});return}let s;try{s=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,Ew):bw;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(s.agentId&&s.agentId!==e){Qe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:s.agentId});return}let a=!1,d=!1;s.agentName&&s.agentName!==i.agentName&&(i.agentName=s.agentName,a=!0),s.description!==void 0&&s.description!==i.description&&(i.description=s.description,a=!0),s.cozeIdentity&&s.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=s.cozeIdentity,a=!0,d=!0);let u=!1;if(s.deployType==="cloud"&&i.deployType!=="cloud"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):s.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:s.deployType}),!a){Qe.debug("detail sync: no diff",{agentId:e});return}await Ne(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await Ir(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Od=Xt(Wu(),1);import{createHash as Ib}from"node:crypto";import{lstat as Id,mkdir as Ad,readFile as Oo,readdir as Q0,rm as kd,stat as Rd,writeFile as Td}from"node:fs/promises";import{homedir as Ab}from"node:os";import{basename as J0,dirname as kb,join as he,normalize as Tb,relative as Dd,resolve as Cd,sep as eh}from"node:path";import{Readable as th}from"node:stream";import{pipeline as nh}from"node:stream/promises";import jw from"events";import at from"fs";import{EventEmitter as id}from"node:events";import Cf from"node:stream";import{StringDecoder as Kw}from"node:string_decoder";import Df from"node:path";import Br from"node:fs";import{dirname as iy,parse as sy}from"path";import{EventEmitter as hy}from"events";import zc from"assert";import{Buffer as Xn}from"buffer";import*as Yu from"zlib";import xy from"zlib";import{posix as Pr}from"node:path";import{basename as Gy}from"node:path";import go from"fs";import zt from"fs";import of from"path";import{win32 as t_}from"node:path";import hf from"path";import $f from"node:fs";import w_ from"node:assert";import{randomBytes as Vf}from"node:crypto";import oe from"node:fs";import He from"node:path";import Zf from"fs";import Io from"node:fs";import Gi from"node:path";import ft from"node:fs";import I_ from"node:fs/promises";import yo from"node:path";import{join as o0}from"node:path";import ut from"node:fs";import d0 from"node:path";var Gw=Object.defineProperty,qw=(t,e)=>{for(var n in e)Gw(t,n,{get:e[n],enumerable:!0})},$u=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ww=t=>!!t&&typeof t=="object"&&(t instanceof tr||t instanceof Cf||$w(t)||Vw(t)),$w=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.pipe=="function"&&t.pipe!==Cf.Writable.prototype.pipe,Vw=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.write=="function"&&typeof t.end=="function",en=Symbol("EOF"),tn=Symbol("maybeEmitEnd"),En=Symbol("emittedEnd"),Gs=Symbol("emittingEnd"),Si=Symbol("emittedError"),qs=Symbol("closed"),Vu=Symbol("read"),js=Symbol("flush"),Zu=Symbol("flushChunk"),St=Symbol("encoding"),Cr=Symbol("decoder"),qe=Symbol("flowing"),Ii=Symbol("paused"),Lr=Symbol("resume"),je=Symbol("buffer"),et=Symbol("pipes"),Ke=Symbol("bufferLength"),lc=Symbol("bufferPush"),Ks=Symbol("bufferShift"),Xe=Symbol("objectMode"),Re=Symbol("destroyed"),uc=Symbol("error"),fc=Symbol("emitData"),Ju=Symbol("emitEnd"),hc=Symbol("emitEnd2"),Nt=Symbol("async"),xc=Symbol("abort"),Ws=Symbol("aborted"),Ai=Symbol("signal"),qn=Symbol("dataListeners"),lt=Symbol("discarded"),ki=t=>Promise.resolve().then(t),Zw=t=>t(),Jw=t=>t==="end"||t==="finish"||t==="prefinish",Yw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Xw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Pf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Lr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Qw=class extends Pf{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,n){super(t,e,n),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},ey=t=>!!t.objectMode,ty=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",tr=class extends id{[qe]=!1;[Ii]=!1;[et]=[];[je]=[];[Xe];[St];[Nt];[Cr];[en]=!1;[En]=!1;[Gs]=!1;[qs]=!1;[Si]=null;[Ke]=0;[Re]=!1;[Ai];[Ws]=!1;[qn]=0;[lt]=!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");ey(e)?(this[Xe]=!0,this[St]=null):ty(e)?(this[St]=e.encoding,this[Xe]=!1):(this[Xe]=!1,this[St]=null),this[Nt]=!!e.async,this[Cr]=this[St]?new Kw(this[St]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[je]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:n}=e;n&&(this[Ai]=n,n.aborted?this[xc]():n.addEventListener("abort",()=>this[xc]()))}get bufferLength(){return this[Ke]}get encoding(){return this[St]}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[Xe]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Nt]}set async(t){this[Nt]=this[Nt]||!!t}[xc](){this[Ws]=!0,this.emit("abort",this[Ai]?.reason),this.destroy(this[Ai]?.reason)}get aborted(){return this[Ws]}set aborted(t){}write(t,e,n){if(this[Ws])return!1;if(this[en])throw new Error("write after end");if(this[Re])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Nt]?ki:Zw;if(!this[Xe]&&!Buffer.isBuffer(t)){if(Xw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Yw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Xe]?(this[qe]&&this[Ke]!==0&&this[js](!0),this[qe]?this.emit("data",t):this[lc](t),this[Ke]!==0&&this.emit("readable"),n&&i(n),this[qe]):t.length?(typeof t=="string"&&!(e===this[St]&&!this[Cr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[St]&&(t=this[Cr].write(t)),this[qe]&&this[Ke]!==0&&this[js](!0),this[qe]?this.emit("data",t):this[lc](t),this[Ke]!==0&&this.emit("readable"),n&&i(n),this[qe]):(this[Ke]!==0&&this.emit("readable"),n&&i(n),this[qe])}read(t){if(this[Re])return null;if(this[lt]=!1,this[Ke]===0||t===0||t&&t>this[Ke])return this[tn](),null;this[Xe]&&(t=null),this[je].length>1&&!this[Xe]&&(this[je]=[this[St]?this[je].join(""):Buffer.concat(this[je],this[Ke])]);let e=this[Vu](t||null,this[je][0]);return this[tn](),e}[Vu](t,e){if(this[Xe])this[Ks]();else{let n=e;t===n.length||t===null?this[Ks]():typeof n=="string"?(this[je][0]=n.slice(t),e=n.slice(0,t),this[Ke]-=t):(this[je][0]=n.subarray(t),e=n.subarray(0,t),this[Ke]-=t)}return this.emit("data",e),!this[je].length&&!this[en]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[en]=!0,this.writable=!1,(this[qe]||!this[Ii])&&this[tn](),this}[Lr](){this[Re]||(!this[qn]&&!this[et].length&&(this[lt]=!0),this[Ii]=!1,this[qe]=!0,this.emit("resume"),this[je].length?this[js]():this[en]?this[tn]():this.emit("drain"))}resume(){return this[Lr]()}pause(){this[qe]=!1,this[Ii]=!0,this[lt]=!1}get destroyed(){return this[Re]}get flowing(){return this[qe]}get paused(){return this[Ii]}[lc](t){this[Xe]?this[Ke]+=1:this[Ke]+=t.length,this[je].push(t)}[Ks](){return this[Xe]?this[Ke]-=1:this[Ke]-=this[je][0].length,this[je].shift()}[js](t=!1){do;while(this[Zu](this[Ks]())&&this[je].length);!t&&!this[je].length&&!this[en]&&this.emit("drain")}[Zu](t){return this.emit("data",t),this[qe]}pipe(t,e){if(this[Re])return t;this[lt]=!1;let n=this[En];return e=e||{},t===$u.stdout||t===$u.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[et].push(e.proxyErrors?new Qw(this,t,e):new Pf(this,t,e)),this[Nt]?ki(()=>this[Lr]()):this[Lr]()),t}unpipe(t){let e=this[et].find(n=>n.dest===t);e&&(this[et].length===1?(this[qe]&&this[qn]===0&&(this[qe]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[lt]=!1,this[qn]++,!this[et].length&&!this[qe]&&this[Lr]();else if(t==="readable"&&this[Ke]!==0)super.emit("readable");else if(Jw(t)&&this[En])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Si]){let i=e;this[Nt]?ki(()=>i.call(this,this[Si])):i.call(this,this[Si])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[qn]=this.listeners("data").length,this[qn]===0&&!this[lt]&&!this[et].length&&(this[qe]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[qn]=0,!this[lt]&&!this[et].length&&(this[qe]=!1)),e}get emittedEnd(){return this[En]}[tn](){!this[Gs]&&!this[En]&&!this[Re]&&this[je].length===0&&this[en]&&(this[Gs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[qs]&&this.emit("close"),this[Gs]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Re&&this[Re])return!1;if(t==="data")return!this[Xe]&&!n?!1:this[Nt]?(ki(()=>this[fc](n)),!0):this[fc](n);if(t==="end")return this[Ju]();if(t==="close"){if(this[qs]=!0,!this[En]&&!this[Re])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[Si]=n,super.emit(uc,n);let s=!this[Ai]||this.listeners("error").length?super.emit("error",n):!1;return this[tn](),s}else if(t==="resume"){let s=super.emit("resume");return this[tn](),s}else if(t==="finish"||t==="prefinish"){let s=super.emit(t);return this.removeAllListeners(t),s}let i=super.emit(t,...e);return this[tn](),i}[fc](t){for(let n of this[et])n.dest.write(t)===!1&&this.pause();let e=this[lt]?!1:super.emit("data",t);return this[tn](),e}[Ju](){return this[En]?!1:(this[En]=!0,this.readable=!1,this[Nt]?(ki(()=>this[hc]()),!0):this[hc]())}[hc](){if(this[Cr]){let e=this[Cr].end();if(e){for(let n of this[et])n.dest.write(e);this[lt]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Xe]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Xe]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Xe])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[St]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Re,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[lt]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[en])return e();let i,s,a=x=>{this.off("data",d),this.off("end",u),this.off(Re,f),e(),s(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(Re,f),this.pause(),i({value:x,done:!!this[en]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Re,f),e(),i({done:!0,value:void 0})},f=()=>a(new Error("stream destroyed"));return new Promise((x,p)=>{s=p,i=x,this.once(Re,f),this.once("error",a),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[lt]=!1;let t=!1,e=()=>(this.pause(),this.off(uc,e),this.off(Re,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(uc,e),this.once(Re,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Re])return t?this.emit("error",t):this.emit(Re),this;this[Re]=!0,this[lt]=!0,this[je].length=0,this[Ke]=0;let e=this;return typeof e.close=="function"&&!this[qs]&&e.close(),t?this.emit("error",t):this.emit(Re),this}static get isStream(){return Ww}},ny=at.writev,Rn=Symbol("_autoClose"),Tt=Symbol("_close"),Ti=Symbol("_ended"),fe=Symbol("_fd"),pc=Symbol("_finished"),on=Symbol("_flags"),gc=Symbol("_flush"),Bc=Symbol("_handleChunk"),Fc=Symbol("_makeBuf"),Ui=Symbol("_mode"),$s=Symbol("_needDrain"),zr=Symbol("_onerror"),Ur=Symbol("_onopen"),mc=Symbol("_onread"),Nr=Symbol("_onwrite"),Dn=Symbol("_open"),kt=Symbol("_path"),An=Symbol("_pos"),Mt=Symbol("_queue"),Mr=Symbol("_read"),wc=Symbol("_readSize"),sn=Symbol("_reading"),Ci=Symbol("_remain"),yc=Symbol("_size"),ro=Symbol("_write"),jn=Symbol("_writing"),io=Symbol("_defaultFlag"),Yn=Symbol("_errored"),sd=class extends tr{[Yn]=!1;[fe];[kt];[wc];[sn]=!1;[yc];[Ci];[Rn];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[Yn]=!1,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[kt]=t,this[wc]=e.readSize||16*1024*1024,this[sn]=!1,this[yc]=typeof e.size=="number"?e.size:1/0,this[Ci]=this[yc],this[Rn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[fe]=="number"?this[Mr]():this[Dn]()}get fd(){return this[fe]}get path(){return this[kt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Dn](){at.open(this[kt],"r",(t,e)=>this[Ur](t,e))}[Ur](t,e){t?this[zr](t):(this[fe]=e,this.emit("open",e),this[Mr]())}[Fc](){return Buffer.allocUnsafe(Math.min(this[wc],this[Ci]))}[Mr](){if(!this[sn]){this[sn]=!0;let t=this[Fc]();if(t.length===0)return process.nextTick(()=>this[mc](null,0,t));at.read(this[fe],t,0,t.length,null,(e,n,i)=>this[mc](e,n,i))}}[mc](t,e,n){this[sn]=!1,t?this[zr](t):this[Bc](e,n)&&this[Mr]()}[Tt](){if(this[Rn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[zr](t){this[sn]=!0,this[Tt](),this.emit("error",t)}[Bc](t,e){let n=!1;return this[Ci]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Ci]<=0)&&(n=!1,this[Tt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[fe]=="number"&&this[Mr](),!1;case"error":return this[Yn]?!1:(this[Yn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},ry=class extends sd{[Dn](){let t=!0;try{this[Ur](null,at.openSync(this[kt],"r")),t=!1}finally{t&&this[Tt]()}}[Mr](){let t=!0;try{if(!this[sn]){this[sn]=!0;do{let e=this[Fc](),n=e.length===0?0:at.readSync(this[fe],e,0,e.length,null);if(!this[Bc](n,e))break}while(!0);this[sn]=!1}t=!1}finally{t&&this[Tt]()}}[Tt](){if(this[Rn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.closeSync(t),this.emit("close")}}},_o=class extends jw{readable=!1;writable=!0;[Yn]=!1;[jn]=!1;[Ti]=!1;[Mt]=[];[$s]=!1;[kt];[Ui];[Rn];[fe];[io];[on];[pc]=!1;[An];constructor(t,e){e=e||{},super(e),this[kt]=t,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[Ui]=e.mode===void 0?438:e.mode,this[An]=typeof e.start=="number"?e.start:void 0,this[Rn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[An]!==void 0?"r+":"w";this[io]=e.flags===void 0,this[on]=e.flags===void 0?n:e.flags,this[fe]===void 0&&this[Dn]()}emit(t,...e){if(t==="error"){if(this[Yn])return!1;this[Yn]=!0}return super.emit(t,...e)}get fd(){return this[fe]}get path(){return this[kt]}[zr](t){this[Tt](),this[jn]=!0,this.emit("error",t)}[Dn](){at.open(this[kt],this[on],this[Ui],(t,e)=>this[Ur](t,e))}[Ur](t,e){this[io]&&this[on]==="r+"&&t&&t.code==="ENOENT"?(this[on]="w",this[Dn]()):t?this[zr](t):(this[fe]=e,this.emit("open",e),this[jn]||this[gc]())}end(t,e){return t&&this.write(t,e),this[Ti]=!0,!this[jn]&&!this[Mt].length&&typeof this[fe]=="number"&&this[Nr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Ti]?(this.emit("error",new Error("write() after end()")),!1):this[fe]===void 0||this[jn]||this[Mt].length?(this[Mt].push(t),this[$s]=!0,!1):(this[jn]=!0,this[ro](t),!0)}[ro](t){at.write(this[fe],t,0,t.length,this[An],(e,n)=>this[Nr](e,n))}[Nr](t,e){t?this[zr](t):(this[An]!==void 0&&typeof e=="number"&&(this[An]+=e),this[Mt].length?this[gc]():(this[jn]=!1,this[Ti]&&!this[pc]?(this[pc]=!0,this[Tt](),this.emit("finish")):this[$s]&&(this[$s]=!1,this.emit("drain"))))}[gc](){if(this[Mt].length===0)this[Ti]&&this[Nr](null,0);else if(this[Mt].length===1)this[ro](this[Mt].pop());else{let t=this[Mt];this[Mt]=[],ny(this[fe],t,this[An],(e,n)=>this[Nr](e,n))}}[Tt](){if(this[Rn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Rf=class extends _o{[Dn](){let t;if(this[io]&&this[on]==="r+")try{t=at.openSync(this[kt],this[on],this[Ui])}catch(e){if(e?.code==="ENOENT")return this[on]="w",this[Dn]();throw e}else t=at.openSync(this[kt],this[on],this[Ui]);this[Ur](null,t)}[Tt](){if(this[Rn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,at.closeSync(t),this.emit("close")}}[ro](t){let e=!0;try{this[Nr](null,at.writeSync(this[fe],t,0,t.length,this[An])),e=!1}finally{if(e)try{this[Tt]()}catch{}}}},oy=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"]]),ay=t=>!!t.sync&&!!t.file,cy=t=>!t.sync&&!!t.file,dy=t=>!!t.sync&&!t.file,ly=t=>!t.sync&&!t.file,uy=t=>!!t.file,fy=t=>oy.get(t)||t,od=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let s=fy(n);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Zi=(t,e,n,i,s)=>Object.assign((a=[],d,u)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let f=od(a);if(s?.(f,d),ay(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(cy(f)){let x=e(f,d);return u?x.then(()=>u(),u):x}else if(dy(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(f,d)}else if(ly(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:s}),py=xy.constants||{ZLIB_VERNUM:4736},Ht=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},py)),gy=Xn.concat,Xu=Object.getOwnPropertyDescriptor(Xn,"concat"),my=t=>t,_c=Xu?.writable===!0||Xu?.set!==void 0?t=>{Xn.concat=t?my:gy}:t=>{},Qn=Symbol("_superWrite"),Vs=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"}},bc=Symbol("flushFlag"),ad=class extends tr{#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(n){throw new Vs(n,this.constructor)}this.#o=n=>{this.#e||(this.#e=!0,this.close(),this.emit("error",n))},this.#t?.on("error",n=>this.#o(new Vs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return zc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Xn.alloc(0),{[bc]:t})))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(n)}get ended(){return this.#n}[Qn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Xn.from(t,e)),this.#e)return;zc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},_c(!0);let d;try{let f=typeof t[bc]=="number"?t[bc]:this.#r;d=this.#t._processChunk(t,f),_c(!1)}catch(f){_c(!1),this.#o(new Vs(f,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=s,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",f=>this.#o(new Vs(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[Qn](Xn.from(f));for(let x=1;x<d.length;x++)u=this[Qn](d[x])}else u=this[Qn](Xn.from(d));return n&&n(),u}},Of=class extends ad{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ht.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ht.Z_FINISH,t.fullFlushFlag=Ht.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(Ht.Z_SYNC_FLUSH),zc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,s)=>{typeof i=="function"&&(s=i,i=this.flushFlag),this.flush(i),s?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},wy=class extends Of{#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)}},yy=class extends Of{constructor(t){super(t,"Unzip")}},Lf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||Ht.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ht.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ht.BROTLI_OPERATION_FLUSH,super(t,e)}},_y=class extends Lf{constructor(t){super(t,"BrotliCompress")}},by=class extends Lf{constructor(t){super(t,"BrotliDecompress")}},Nf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||Ht.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ht.ZSTD_e_end,t.fullFlushFlag=Ht.ZSTD_e_flush,super(t,e)}},Ey=class extends Nf{constructor(t){super(t,"ZstdCompress")}},vy=class extends Nf{constructor(t){super(t,"ZstdDecompress")}},Sy=(t,e)=>{if(Number.isSafeInteger(t))t<0?Ay(t,e):Iy(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Iy=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},Ay=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var s=t&255;t=Math.floor(t/256),n?e[i-1]=Mf(s):s===0?e[i-1]=0:(n=!0,e[i-1]=Bf(s))}},ky=t=>{let e=t[0],n=e===128?Cy(t.subarray(1,t.length)):e===255?Ty(t):null;if(n===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(n))throw Error("parsed number outside of javascript safe integer range");return n},Ty=t=>{for(var e=t.length,n=0,i=!1,s=e-1;s>-1;s--){var a=Number(t[s]),d;i?d=Mf(a):a===0?d=a:(i=!0,d=Bf(a)),d!==0&&(n-=d*Math.pow(256,e-s-1))}return n},Cy=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var s=Number(t[i]);s!==0&&(n+=s*Math.pow(256,e-i-1))}return n},Mf=t=>(255^t)&255,Bf=t=>(255^t)+1&255,Py={};qw(Py,{code:()=>cd,isCode:()=>so,isName:()=>Ry,name:()=>bo,normalFsTypes:()=>Ff});var so=t=>bo.has(t),Ry=t=>cd.has(t),Ff=new Set(["0","","1","2","3","4","5","6","7","D"]),bo=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"]]),cd=new Map(Array.from(bo).map(t=>[t[1],t[0]])),Dy=t=>t===void 0||t<0?void 0:t,er=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let s=Kn(t,e+156,1),a=Ff.has(s),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??Kn(t,e,100),this.mode=d?.mode??u?.mode??kn(t,e+100,8),this.uid=d?.uid??u?.uid??kn(t,e+108,8),this.gid=d?.gid??u?.gid??kn(t,e+116,8),this.size=Dy(d?.size??u?.size??kn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??Ec(t,e+136,12),this.cksum=kn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),so(s)&&(this.#e=s||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Kn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Kn(t,e+265,32),this.gname=d?.gname??u?.gname??Kn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??kn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??kn(t,e+337,8)??0,t[e+475]!==0){let x=Kn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Kn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??Ec(t,e+476,12),this.ctime=n?.ctime??i?.ctime??Ec(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="size"&&Number(i)<0||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,i=Oy(this.path||"",n),s=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Wn(t,e,100,s)||this.needPax,this.needPax=Tn(t,e+100,8,this.mode)||this.needPax,this.needPax=Tn(t,e+108,8,this.uid)||this.needPax,this.needPax=Tn(t,e+116,8,this.gid)||this.needPax,this.needPax=Tn(t,e+124,12,this.size)||this.needPax,this.needPax=vc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Wn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Wn(t,e+265,32,this.uname)||this.needPax,this.needPax=Wn(t,e+297,32,this.gname)||this.needPax,this.needPax=Tn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Tn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Wn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Wn(t,e+345,155,a)||this.needPax:(this.needPax=Wn(t,e+345,130,a)||this.needPax,this.needPax=vc(t,e+476,12,this.atime)||this.needPax,this.needPax=vc(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,Tn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:bo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(cd.get(t));if(so(e)||e==="Unsupported")this.#e=e;else if(so(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Oy=(t,e)=>{let n=t,i="",s,a=Pr.parse(t).root||".";if(Buffer.byteLength(n)<100)s=[n,i,!1];else{i=Pr.dirname(n),n=Pr.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?s=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?s=[n.slice(0,99),i,!0]:(n=Pr.join(Pr.basename(i),n),i=Pr.dirname(i));while(i!==a&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},Kn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),Ec=(t,e,n)=>Ly(kn(t,e,n)),Ly=t=>t===void 0?void 0:new Date(t*1e3),kn=(t,e,n)=>Number(t[e])&128?ky(t.subarray(e,e+n)):My(t,e,n),Ny=t=>isNaN(t)?void 0:t,My=(t,e,n)=>Ny(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),By={12:8589934591,8:2097151},Tn=(t,e,n,i)=>i===void 0?!1:i>By[n]||i<0?(Sy(i,t.subarray(e,e+n)),!0):(Fy(t,e,n,i),!1),Fy=(t,e,n,i)=>t.write(zy(i,n),e,n,"ascii"),zy=(t,e)=>Uy(Math.floor(t).toString(8),e),Uy=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",vc=(t,e,n,i)=>i===void 0?!1:Tn(t,e,n,i.getTime()/1e3),Hy=new Array(156).join("\0"),Wn=(t,e,n,i)=>i===void 0?!1:(t.write(i+Hy,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),po=class zf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),s=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)s[a]=0;new er({path:("PaxHeader/"+Gy(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(s),s.write(e,512,n,"utf8");for(let a=n+512;a<s.length;a++)s[a]=0;return s}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,s=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,a=Buffer.byteLength(s),d=Math.floor(Math.log(a)/Math.log(10))+1;return a+d>=Math.pow(10,d)&&(d+=1),d+a+s}static parse(e,n,i=!1){return new zf(qy(jy(e),n),i)}},qy=(t,e)=>e?Object.assign({},e,t):t,jy=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(Ky,Object.create(null)),Ky=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),s=i.shift();if(!s)return t;let a=s.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(a){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[a]=d;break;case"ctime":case"atime":case"mtime":t[a]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[a]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},Wy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ee=Wy!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),$y=class extends tr{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=ee(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?ee(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,i=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#e(t,e=!1){t.path&&(t.path=ee(t.path)),t.linkpath&&(t.linkpath=ee(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},Eo=(t,e,n,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=n instanceof Error&&n.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(n instanceof Error&&(i=Object.assign(n,i),n=n.message),t.emit("warn",e,n,i)):n instanceof Error?t.emit("error",Object.assign(n,i)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),i))},Vy=1024*1024,Uc=Buffer.from([31,139]),Hc=Buffer.from([40,181,47,253]),Zy=Math.max(Uc.length,Hc.length),wt=Symbol("state"),$n=Symbol("writeEntry"),nn=Symbol("readEntry"),Sc=Symbol("nextEntry"),Qu=Symbol("processEntry"),Bt=Symbol("extendedHeader"),Pi=Symbol("globalExtendedHeader"),vn=Symbol("meta"),ef=Symbol("emitMeta"),ye=Symbol("buffer"),rn=Symbol("queue"),Sn=Symbol("ended"),Ic=Symbol("emittedEnd"),Vn=Symbol("emit"),Te=Symbol("unzip"),Zs=Symbol("consumeChunk"),Js=Symbol("consumeChunkSub"),Ac=Symbol("consumeBody"),tf=Symbol("consumeMeta"),nf=Symbol("consumeHeader"),Ri=Symbol("consuming"),kc=Symbol("bufferConcat"),Ys=Symbol("maybeEnd"),Rr=Symbol("writing"),Ft=Symbol("aborted"),Xs=Symbol("onDone"),Zn=Symbol("sawValidEntry"),Qs=Symbol("sawNullBlock"),eo=Symbol("sawEOF"),rf=Symbol("closeStream"),Jy=1e3,Di=Symbol("compressedBytesRead"),Tc=Symbol("decompressedBytesRead"),sf=Symbol("checkDecompressionRatio"),Yy=()=>!0,Vi=class extends hy{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[rn]=[];[ye];[nn];[$n];[wt]="begin";[vn]="";[Bt];[Pi];[Sn]=!1;[Te];[Ft]=!1;[Zn];[Qs]=!1;[eo]=!1;[Rr]=!1;[Ri]=!1;[Ic]=!1;[Di]=0;[Tc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Xs,()=>{(this[wt]==="begin"||this[Zn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Xs,t.ondone):this.on(Xs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Jy,this.maxMetaEntrySize=t.maxMetaEntrySize||Vy,this.filter=typeof t.filter=="function"?t.filter:Yy;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[rf]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){Eo(this,t,e,n)}[nf](t,e){this[Zn]===void 0&&(this[Zn]=!1);let n;try{n=new er(t,e,this[Bt],this[Pi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Qs]?(this[eo]=!0,this[wt]==="begin"&&(this[wt]="header"),this[Vn]("eof")):(this[Qs]=!0,this[Vn]("nullBlock"));else if(this[Qs]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let s=this[$n]=new $y(n,this[Bt],this[Pi]);if(!this[Zn])if(s.remain){let a=()=>{s.invalid||(this[Zn]=!0)};s.on("end",a)}else this[Zn]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[Vn]("ignoredEntry",s),this[wt]="ignore",s.resume()):s.size>0&&(this[vn]="",s.on("data",a=>this[vn]+=a),this[wt]="meta"):(this[Bt]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[Vn]("ignoredEntry",s),this[wt]=s.remain?"ignore":"header",s.resume()):(s.remain?this[wt]="body":(this[wt]="header",s.end()),this[nn]?this[rn].push(s):(this[rn].push(s),this[Sc]())))}}}[rf](){queueMicrotask(()=>this.emit("close"))}[Qu](t){let e=!0;if(!t)this[nn]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[nn]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Sc]()),e=!1);return e}[Sc](){do;while(this[Qu](this[rn].shift()));if(this[rn].length===0){let t=this[nn];!t||t.flowing||t.size===t.remain?this[Rr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ac](t,e){let n=this[$n];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,s=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(s),n.blockRemain||(this[wt]="header",this[$n]=void 0,n.end()),s.length}[tf](t,e){let n=this[$n],i=this[Ac](t,e);return!this[$n]&&n&&this[ef](n),i}[Vn](t,e,n){this[rn].length===0&&!this[nn]?this.emit(t,e,n):this[rn].push([t,e,n])}[ef](t){switch(this[Vn]("meta",this[vn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Bt]=po.parse(this[vn],this[Bt],!1);break;case"GlobalExtendedHeader":this[Pi]=po.parse(this[vn],this[Pi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Bt]??Object.create(null);this[Bt]=e,e.path=this[vn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Bt]||Object.create(null);this[Bt]=e,e.linkpath=this[vn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ft]){if(this[Te]){let e=this[Te];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ft]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[sf](t){this[Tc]+=t.length;let e=this[Tc]/this[Di];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),!1):!0}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Ft])return n?.(),!1;if((this[Te]===void 0||this.brotli===void 0&&this[Te]===!1)&&t){if(this[ye]&&(t=Buffer.concat([this[ye],t]),this[ye]=void 0),t.length<Zy)return this[ye]=t,n?.(),!0;for(let d=0;this[Te]===void 0&&d<Uc.length;d++)t[d]!==Uc[d]&&(this[Te]=!1);let s=!1;if(this[Te]===!1&&this.zstd!==!1){s=!0;for(let d=0;d<Hc.length;d++)if(t[d]!==Hc[d]){s=!1;break}}let a=this.brotli===void 0&&!s;if(this[Te]===!1&&a)if(t.length<512)if(this[Sn])this.brotli=!0;else return this[ye]=t,n?.(),!0;else try{new er(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Te]===void 0||this[Te]===!1&&(this.brotli||s)){let d=this[Sn];this[Sn]=!1,this[Te]=this[Te]===void 0?new yy({}):s?new vy({}):new by({}),this[Te].on("data",f=>{this[sf](f)&&this[Zs](f)}),this[Te].on("error",f=>{this[Ft]||this.abort(f)}),this[Te].on("end",()=>{this[Sn]=!0,this[Zs]()}),this[Rr]=!0,this[Di]+=t.length;let u=!!this[Te][d?"end":"write"](t);return this[Rr]=!1,n?.(),u}}this[Rr]=!0,this[Te]?(this[Di]+=t.length,this[Te].write(t)):this[Zs](t),this[Rr]=!1;let i=this[rn].length>0?!1:this[nn]?this[nn].flowing:!0;return!i&&this[rn].length===0&&this[nn]?.once("drain",()=>this.emit("drain")),n?.(),i}[kc](t){t&&!this[Ft]&&(this[ye]=this[ye]?Buffer.concat([this[ye],t]):t)}[Ys](){if(this[Sn]&&!this[Ic]&&!this[Ft]&&!this[Ri]){this[Ic]=!0;let t=this[$n];if(t?.blockRemain){let e=this[ye]?this[ye].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ye]&&t.write(this[ye]),t.end()}this[Vn](Xs)}}[Zs](t){if(this[Ri]&&t)this[kc](t);else if(!t&&!this[ye])this[Ys]();else if(t){if(this[Ri]=!0,this[ye]){this[kc](t);let e=this[ye];this[ye]=void 0,this[Js](e)}else this[Js](t);for(;this[ye]&&this[ye]?.length>=512&&!this[Ft]&&!this[eo];){let e=this[ye];this[ye]=void 0,this[Js](e)}this[Ri]=!1}(!this[ye]||this[Sn])&&this[Ys]()}[Js](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ft]&&!this[eo];)switch(this[wt]){case"begin":case"header":this[nf](t,e),e+=512;break;case"ignore":case"body":e+=this[Ac](t,e);break;case"meta":e+=this[tf](t,e);break;default:throw new Error("invalid state: "+this[wt])}e<n&&(this[ye]=this[ye]?Buffer.concat([t.subarray(e),this[ye]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Ft]||(this[Te]?(t&&(this[Di]+=t.length,this[Te].write(t)),this[Te].end()):(this[Sn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ys]())),this}},Hi=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},Xy=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Uf=(t,e)=>{let n=new Map(e.map(a=>[Hi(a),!0])),i=t.filter,s=(a,d="")=>{let u=d||sy(a).root||".",f;if(a===u)f=!1;else{let x=n.get(a);f=x!==void 0?x:s(iy(a),u)}return n.set(a,f),f};t.filter=i?(a,d)=>i(a,d)&&s(Hi(a)):a=>s(Hi(a))},Qy=t=>{let e=new Vi(t),n=t.file,i;try{i=Br.openSync(n,"r");let s=Br.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(s.size<a){let d=Buffer.allocUnsafe(s.size),u=Br.readSync(i,d,0,s.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(a);for(;d<s.size;){let f=Br.readSync(i,u,0,a,d);if(f===0)break;d+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Br.closeSync(i)}catch{}}},e_=(t,e)=>{let n=new Vi(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Br.stat(s,(u,f)=>{if(u)d(u);else{let x=new sd(s,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},Hr=Zi(Qy,e_,t=>new Vi(t),t=>new Vi(t),(t,e)=>{e?.length&&Uf(t,e),t.noResume||Xy(t)}),Hf=(t,e,n)=>(t&=4095,n&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:n_,parse:af}=t_,dd=t=>{let e="",n=af(t);for(;n_(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=af(t)}return[e,t]},vo=["|","<",">","?",":"],ld=vo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),r_=new Map(vo.map((t,e)=>[t,ld[e]])),i_=new Map(ld.map((t,e)=>[t,vo[e]])),cf=t=>vo.reduce((e,n)=>e.split(n).join(r_.get(n)),t),s_=t=>ld.reduce((e,n)=>e.split(n).join(i_.get(n)),t),Gf=(t,e)=>e?(t=ee(t).replace(/^\.(\/|$)/,""),Hi(e)+"/"+t):ee(t),o_=16*1024*1024,df=Symbol("process"),lf=Symbol("file"),uf=Symbol("directory"),Gc=Symbol("symlink"),ff=Symbol("hardlink"),Oi=Symbol("header"),oo=Symbol("read"),qc=Symbol("lstat"),ao=Symbol("onlstat"),jc=Symbol("onread"),Kc=Symbol("onreadlink"),Wc=Symbol("openfile"),$c=Symbol("onopenfile"),Cn=Symbol("close"),mo=Symbol("mode"),Vc=Symbol("awaitDrain"),Cc=Symbol("ondrain"),Ut=Symbol("prefix"),qf=class extends tr{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let n=od(e);super(),this.path=ee(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||o_,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=ee(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?ee(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[a,d]=dd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=s_(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ee(n.absolute||of.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 s=this.statCache.get(this.absolute);s?this[ao](s):this[qc]()}warn(t,e,n={}){return Eo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[qc](){zt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ao](e)})}[ao](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=d_(t),this.emit("stat",t),this[df]()}[df](){switch(this.type){case"File":return this[lf]();case"Directory":return this[uf]();case"SymbolicLink":return this[Gc]();default:return this.end()}}[mo](t){return Hf(t,this.type==="Directory",this.portable)}[Ut](t){return Gf(t,this.prefix)}[Oi](){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 er({path:this[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](this.linkpath):this.linkpath,mode:this[mo](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 po({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[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](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)}[uf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Oi](),this.end()}[Gc](){zt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Kc](e)})}[Kc](t){this.linkpath=ee(t),this[Oi](),this.end()}[ff](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ee(of.relative(this.cwd,t)),this.stat.size=0,this[Oi](),this.end()}[lf](){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[ff](e);this.linkCache.set(t,this.absolute)}if(this[Oi](),this.stat.size===0)return this.end();this[Wc]()}[Wc](){zt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[$c](e)})}[$c](t){if(this.fd=t,this.#e)return this[Cn]();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[oo]()}[oo](){let{fd:t,buf:e,offset:n,length:i,pos:s}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");zt.read(t,e,n,i,s,(a,d)=>{if(a)return this[Cn](()=>this.emit("error",a));this[jc](d)})}[Cn](t=()=>{}){this.fd!==void 0&&zt.close(this.fd,t)}[jc](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Cn](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Cn](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[Cc]():this[Vc](()=>this[Cc]())}[Vc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[Cc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Cn](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[oo]()}},a_=class extends qf{sync=!0;[qc](){this[ao](zt.lstatSync(this.absolute))}[Gc](){this[Kc](zt.readlinkSync(this.absolute))}[Wc](){this[$c](zt.openSync(this.absolute,"r"))}[oo](){let t=!0;try{let{fd:e,buf:n,offset:i,length:s,pos:a}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=zt.readSync(e,n,i,s,a);this[jc](d),t=!1}finally{if(t)try{this[Cn](()=>{})}catch{}}}[Vc](t){t()}[Cn](t=()=>{}){this.fd!==void 0&&zt.closeSync(this.fd),t()}},c_=class extends tr{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return Eo(this,t,e,n)}constructor(t,e={}){let n=od(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=ee(t.path),this.mode=t.mode!==void 0?this[mo](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:n.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?ee(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let s=!1;if(!this.preservePaths){let[d,u]=dd(this.path);d&&typeof u=="string"&&(this.path=u,s=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new er({path:this[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](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}),s&&this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute path`,{entry:this,path:s+this.path}),this.header.encode()&&!this.noPax&&super.write(new po({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[Ut](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ut](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let a=this.header?.block;if(!a)throw new Error("failed to encode header");super.write(a),t.pipe(this)}[Ut](t){return Gf(t,this.prefix)}[mo](t){return Hf(t,this.type==="Directory",this.portable)}write(t,e,n){typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,n)}end(t,e,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),n&&this.once("finish",n),t?super.end(t,n):super.end(n),this}},d_=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",l_=class Fr{tail;head;length=0;static create(e=[]){return new Fr(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,i=e.prev;return n&&(n.prev=i),i&&(i.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,i=e.length;n<i;n++)f_(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)h_(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,s=0;i;s++)e.call(n,i.value,s,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,s=this.length-1;i;s--)e.call(n,i.value,s,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Fr;for(let s=this.head;s;)i.push(e.call(n,s.value,this)),s=s.next;return i}mapReverse(e,n){n=n||this;var i=new Fr;for(let s=this.tail;s;)i.push(e.call(n,s.value,this)),s=s.prev;return i}reduce(e,n){let i,s=this.head;if(arguments.length>1)i=n;else if(this.head)s=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;s;a++)i=e(i,s.value,a),s=s.next;return i}reduceReverse(e,n){let i,s=this.tail;if(arguments.length>1)i=n;else if(this.tail)s=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;s;a--)i=e(i,s.value,a),s=s.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Fr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.head,a=0;for(a=0;s&&a<e;a++)s=s.next;for(;s&&a<n;a++,s=s.next)i.push(s.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Fr;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.length,a=this.tail;for(;a&&s>n;s--)a=a.prev;for(;a&&s>e;s--,a=a.prev)i.push(a.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let s=this.head;for(let d=0;s&&d<e;d++)s=s.next;let a=[];for(let d=0;s&&d<n;d++)a.push(s.value),s=this.removeNode(s);s?s!==this.tail&&(s=s.prev):s=this.tail;for(let d of i)s=u_(this,s,d);return a}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let s=i.prev;i.prev=i.next,i.next=s}return this.head=n,this.tail=e,this}};function u_(t,e,n){let i=e,s=e?e.next:t.head,a=new ud(n,i,s,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function f_(t,e){t.tail=new ud(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function h_(t,e){t.head=new ud(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var ud=class{list;next;prev;value;constructor(t,e,n,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},xf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},pf=Buffer.alloc(1024),co=Symbol("onStat"),Li=Symbol("ended"),It=Symbol("queue"),Ni=Symbol("pendingLinks"),In=Symbol("current"),Jn=Symbol("process"),Mi=Symbol("processing"),to=Symbol("processJob"),At=Symbol("jobs"),Pc=Symbol("jobDone"),lo=Symbol("addFSEntry"),gf=Symbol("addTarEntry"),Zc=Symbol("stat"),Jc=Symbol("readdir"),uo=Symbol("onreaddir"),fo=Symbol("pipe"),mf=Symbol("entry"),Rc=Symbol("entryOpt"),ho=Symbol("writeEntryClass"),jf=Symbol("write"),Dc=Symbol("ondrain"),So=class extends tr{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ho];onWriteEntry;[It];[Ni]=new Map;[At]=0;[Mi]=!1;[Li]=!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=ee(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[ho]=qf,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 wy(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new _y(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ey(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[Dc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Dc]);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[It]=new l_,this[At]=0,this.jobs=Number(t.jobs)||4,this[Mi]=!1,this[Li]=!1}[jf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&this.add(t),this[Li]=!0,this[Jn](),n&&n(),this}write(t){if(this[Li])throw new Error("write after end");return typeof t=="string"?this[lo](t):this[gf](t),this.flowing}[gf](t){let e=ee(hf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new xf(t.path,e);n.entry=new c_(t,this[Rc](n)),n.entry.on("end",()=>this[Pc](n)),this[At]+=1,this[It].push(n)}this[Jn]()}[lo](t){let e=ee(hf.resolve(this.cwd,t));this[It].push(new xf(t,e)),this[Jn]()}[Zc](t){t.pending=!0,this[At]+=1;let e=this.follow?"stat":"lstat";go[e](t.absolute,(n,i)=>{t.pending=!1,this[At]-=1,n?this.emit("error",n):this[co](t,i)})}[co](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[In])this[to](t);else{let n=`${e.dev}:${e.ino}`,i=this[Ni].get(n);i?i.push(t):this[Ni].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Jn]()}[Jc](t){t.pending=!0,this[At]+=1,go.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[At]-=1,e)return this.emit("error",e);this[uo](t,n)})}[uo](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Jn]()}[Jn](){if(!this[Mi]){this[Mi]=!0;for(let t=this[It].head;t&&this[At]<this.jobs;t=t.next)if(this[to](t.value),t.value.ignore){let e=t.next;this[It].removeNode(t),t.next=e}this[Mi]=!1,this[Li]&&this[It].length===0&&this[At]===0&&(this.zip?this.zip.end(pf):(super.write(pf),super.end()))}}get[In](){return this[It]&&this[It].head&&this[It].head.value}[Pc](t){this[It].shift(),this[At]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Ni].get(n);if(i){this[Ni].delete(n);for(let s of i)s.pending=!1,this[to](s)}}this[Jn]()}[to](t){if(t.pending&&t.pendingLink&&t===this[In]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[In]&&!t.piped&&this[fo](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[co](t,e):this[Zc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[uo](t,e):this[Jc](t),!t.readdir)return}if(t.entry=this[mf](t),!t.entry){t.ignore=!0;return}t===this[In]&&!t.piped&&this[fo](t)}}}[Rc](t){return{onwarn:(e,n,i)=>this.warn(e,n,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[mf](t){this[At]+=1;try{return new this[ho](t.path,this[Rc](t)).on("end",()=>this[Pc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Dc](){this[In]&&this[In].entry&&this[In].entry.resume()}[fo](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[lo](a+i)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",i=>{n.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,n={}){Eo(this,t,e,n)}},fd=class extends So{sync=!0;constructor(t){super(t),this[ho]=a_}pause(){}resume(){}[Zc](t){let e=this.follow?"statSync":"lstatSync";this[co](t,go[e](t.absolute))}[Jc](t){this[uo](t,go.readdirSync(t.absolute))}[fo](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[lo](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[jf](i)})}},x_=(t,e)=>{let n=new fd(t),i=new Rf(t.file,{mode:t.mode||438});n.pipe(i),Kf(n,e)},p_=(t,e)=>{let n=new So(t),i=new _o(t.file,{mode:t.mode||438});n.pipe(i);let s=new Promise((a,d)=>{i.on("error",d),i.on("close",a),n.on("error",d)});return Wf(n,e).catch(a=>n.emit("error",a)),s},Kf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Hr({file:Df.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Wf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Hr({file:Df.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},g_=(t,e)=>{let n=new fd(t);return Kf(n,e),n},m_=(t,e)=>{let n=new So(t);return Wf(n,e).catch(i=>n.emit("error",i)),n},G2=Zi(x_,p_,g_,m_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),y_=process.env.__FAKE_PLATFORM__||process.platform,Jf=y_==="win32",{O_CREAT:Yf,O_NOFOLLOW:wf,O_TRUNC:Xf,O_WRONLY:Qf}=Zf.constants,e0=Number(process.env.__FAKE_FS_O_FILENAME__)||Zf.constants.UV_FS_O_FILEMAP||0,__=Jf&&!!e0,b_=512*1024,E_=e0|Xf|Yf|Qf,yf=!Jf&&typeof wf=="number"?wf|Xf|Yf|Qf:null,t0=yf!==null?()=>yf:__?t=>t<b_?E_:"w":()=>"w",Yc=(t,e,n)=>{try{return Io.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},wo=(t,e,n,i)=>{Io.lchown(t,e,n,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},v_=(t,e,n,i,s)=>{if(e.isDirectory())n0(Gi.resolve(t,e.name),n,i,a=>{if(a)return s(a);let d=Gi.resolve(t,e.name);wo(d,n,i,s)});else{let a=Gi.resolve(t,e.name);wo(a,n,i,s)}},n0=(t,e,n,i)=>{Io.readdir(t,{withFileTypes:!0},(s,a)=>{if(s){if(s.code==="ENOENT")return i();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return i(s)}if(s||!a.length)return wo(t,e,n,i);let d=a.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return wo(t,e,n,i)}};for(let x of a)v_(t,x,e,n,f)})},S_=(t,e,n,i)=>{e.isDirectory()&&r0(Gi.resolve(t,e.name),n,i),Yc(Gi.resolve(t,e.name),n,i)},r0=(t,e,n)=>{let i;try{i=Io.readdirSync(t,{withFileTypes:!0})}catch(s){let a=s;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Yc(t,e,n);throw a}for(let s of i)S_(t,s,e,n);return Yc(t,e,n)},i0=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"}},Ao=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"}},A_=(t,e)=>{ft.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new i0(t,n?.code||"ENOTDIR")),e(n)})},k_=(t,e,n)=>{t=ee(t);let i=e.umask??18,s=e.mode|448,a=(s&i)!==0,d=e.uid,u=e.gid,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,m=ee(e.cwd),b=(v,I)=>{v?n(v):I&&f?n0(I,d,u,A=>b(A)):a?ft.chmod(t,s,n):n()};if(t===m)return A_(t,b);if(x)return I_.mkdir(t,{mode:s,recursive:!0}).then(v=>b(null,v??void 0),b);let y=ee(yo.relative(m,t)).split("/");Xc(m,y,s,p,m,void 0,b)},Xc=(t,e,n,i,s,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),f=ee(yo.resolve(t+"/"+u));ft.mkdir(f,n,s0(f,e,n,i,s,a,d))},s0=(t,e,n,i,s,a,d)=>u=>{u?ft.lstat(t,(f,x)=>{if(f)f.path=f.path&&ee(f.path),d(f);else if(x.isDirectory())Xc(t,e,n,i,s,a,d);else if(i)ft.unlink(t,p=>{if(p)return d(p);ft.mkdir(t,n,s0(t,e,n,i,s,a,d))});else{if(x.isSymbolicLink())return d(new Ao(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,Xc(t,e,n,i,s,a,d))},T_=t=>{let e=!1,n;try{e=ft.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new i0(t,n??"ENOTDIR")}},C_=(t,e)=>{t=ee(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),f=e.preserve,x=e.unlink,p=ee(e.cwd),m=v=>{v&&u&&r0(v,a,d),s&&ft.chmodSync(t,i)};if(t===p)return T_(p),m();if(f)return m(ft.mkdirSync(t,{mode:i,recursive:!0})??void 0);let b=ee(yo.relative(p,t)).split("/"),y;for(let v=b.shift(),I=p;v&&(I+="/"+v);v=b.shift()){I=ee(yo.resolve(I));try{ft.mkdirSync(I,i),y=y||I}catch{let A=ft.lstatSync(I);if(A.isDirectory())continue;if(x){ft.unlinkSync(I),ft.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new Ao(I,I+"/"+b.join("/"))}}return m(y)},Oc=Object.create(null),_f=1e4,Dr=new Set,P_=t=>{Dr.has(t)?Dr.delete(t):Oc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Dr.add(t);let e=Oc[t],n=Dr.size-_f;if(n>_f/10){for(let i of Dr)if(Dr.delete(i),delete Oc[i],--n<=0)break}return e},R_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,D_=R_==="win32",O_=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=o0(i,n)),e.push(n||"/"),e},[]),L_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=D_?["win32 parallelization disabled"]:t.map(i=>Hi(o0(P_(i))));let n=new Set(t.map(i=>O_(i)).reduce((i,s)=>i.concat(s)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let s=this.#e.get(i);s?s.push(e):this.#e.set(i,[e])}for(let i of n){let s=this.#e.get(i);if(!s)this.#e.set(i,[new Set([e])]);else{let a=s.at(-1);a instanceof Set?a.add(e):s.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,s=new Set;for(let a of n){let d=this.#e.get(a);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(a);continue}if(d.shift(),typeof u=="function")s.add(u);else for(let f of u)s.add(f)}for(let a of i){let d=this.#e.get(a),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(a);continue}else if(u.size===1){d.shift();let f=d[0];typeof f=="function"&&s.add(f)}else u.delete(t)}return this.#r.delete(t),s.forEach(a=>this.#i(a)),!0}},N_=()=>process.umask(),bf=Symbol("onEntry"),Qc=Symbol("checkFs"),Ef=Symbol("checkFs2"),ed=Symbol("isReusable"),yt=Symbol("makeFs"),td=Symbol("file"),nd=Symbol("directory"),xo=Symbol("link"),vf=Symbol("symlink"),Sf=Symbol("hardlink"),zi=Symbol("ensureNoSymlink"),If=Symbol("unsupported"),Af=Symbol("checkPath"),Lc=Symbol("stripAbsolutePath"),Pn=Symbol("mkdir"),We=Symbol("onError"),no=Symbol("pending"),kf=Symbol("pend"),Or=Symbol("unpend"),Nc=Symbol("ended"),Mc=Symbol("maybeClose"),rd=Symbol("skip"),qi=Symbol("doChown"),ji=Symbol("uid"),Ki=Symbol("gid"),Wi=Symbol("checkedCwd"),M_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,$i=M_==="win32",B_=1024,F_=(t,e)=>{if(!$i)return oe.unlink(t,e);let n=t+".DELETE."+Vf(16).toString("hex");oe.rename(t,n,i=>{if(i)return e(i);oe.unlink(n,e)})},z_=t=>{if(!$i)return oe.unlinkSync(t);let e=t+".DELETE."+Vf(16).toString("hex");oe.renameSync(t,e),oe.unlinkSync(e)},Tf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,hd=class extends Vi{[Nc]=!1;[Wi]=!1;[no]=0;reservations=new L_;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[Nc]=!0,this[Mc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:B_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||$i,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ee(He.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:N_():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[bf](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Mc](){this[Nc]&&this[no]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Lc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[s,a]=dd(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||$i&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let u=He.posix.dirname(t.path),f=He.posix.normalize(He.posix.join(u,d.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return s&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:n})),!0}[Af](t){let e=ee(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=ee(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[Lc](t,"path")||!this[Lc](t,"linkpath"))return!1;if(t.absolute=He.isAbsolute(t.path)?ee(He.resolve(t.path)):ee(He.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:ee(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}=He.win32.parse(String(t.absolute));t.absolute=i+cf(String(t.absolute).slice(i.length));let{root:s}=He.win32.parse(t.path);t.path=s+cf(t.path.slice(s.length))}return!0}[bf](t){if(!this[Af](t))return t.resume();switch(w_.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[Qc](t);default:return this[If](t)}}[We](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Or](),e.resume())}[Pn](t,e,n){k_(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[qi](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}[ji](t){return Tf(this.uid,t.uid,this.processUid)}[Ki](t){return Tf(this.gid,t.gid,this.processGid)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new _o(String(t.absolute),{flags:t0(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&oe.close(i.fd,()=>{}),i.write=()=>!0,this[We](u,t),e()});let s=1,a=u=>{if(u){i.fd&&oe.close(i.fd,()=>{}),this[We](u,t),e();return}--s===0&&i.fd!==void 0&&oe.close(i.fd,f=>{f?this[We](f,t):this[Or](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){s++;let x=t.atime||new Date,p=t.mtime;oe.futimes(f,x,p,m=>m?oe.utimes(u,x,p,b=>a(b&&m)):a())}if(typeof f=="number"&&this[qi](t)){s++;let x=this[ji](t),p=this[Ki](t);typeof x=="number"&&typeof p=="number"&&oe.fchown(f,x,p,m=>m?oe.chown(u,x,p,b=>a(b&&m)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[We](u,t),e()}),t.pipe(d)),d.pipe(i)}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Pn](String(t.absolute),n,i=>{if(i){this[We](i,t),e();return}let s=1,a=()=>{--s===0&&(e(),this[Or](),t.resume())};t.mtime&&!this.noMtime&&(s++,oe.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[qi](t)&&(s++,oe.chown(String(t.absolute),Number(this[ji](t)),Number(this[Ki](t)),a)),a()})}[If](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[vf](t,e){let n=ee(He.relative(this.cwd,He.resolve(He.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[zi](t,this.cwd,n,()=>this[xo](t,String(t.linkpath),"symlink",e),i=>{this[We](i,t),e()})}[Sf](t,e){let n=ee(He.resolve(this.cwd,String(t.linkpath))),i=ee(String(t.linkpath)).split("/");this[zi](t,this.cwd,i,()=>this[xo](t,n,"link",e),s=>{this[We](s,t),e()})}[zi](t,e,n,i,s){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=He.resolve(e,a);oe.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return s(new Ao(d,He.resolve(d,n.join("/"))));this[zi](t,d,n,i,s)})}[kf](){this[no]++}[Or](){this[no]--,this[Mc]()}[rd](t){this[Or](),t.resume()}[ed](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!$i}[Qc](t){this[kf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[Ef](t,n))}[Ef](t,e){let n=d=>{e(d)},i=()=>{this[Pn](this.cwd,this.dmode,d=>{if(d){this[We](d,t),n();return}this[Wi]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let d=ee(He.dirname(String(t.absolute)));if(d!==this.cwd)return this[Pn](d,this.dmode,u=>{if(u){this[We](u,t),n();return}a()})}a()},a=()=>{oe.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[rd](t),n();return}if(d||this[ed](t,u))return this[yt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[yt](p??null,t,n);return f?oe.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return oe.rmdir(String(t.absolute),f=>this[yt](f??null,t,n))}if(t.absolute===this.cwd)return this[yt](null,t,n);F_(String(t.absolute),f=>this[yt](f??null,t,n))})};this[Wi]?s():i()}[yt](t,e,n){if(t){this[We](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[td](e,n);case"Link":return this[Sf](e,n);case"SymbolicLink":return this[vf](e,n);case"Directory":case"GNUDumpDir":return this[nd](e,n)}}[xo](t,e,n,i){oe[n](e,String(t.absolute),s=>{s?this[We](s,t):(this[Or](),t.resume()),i()})}},Bi=t=>{try{return[null,t()]}catch(e){return[e,null]}},a0=class extends hd{sync=!0;[yt](t,e){return super[yt](t,e,()=>{})}[Qc](t){if(!this[Wi]){let s=this[Pn](this.cwd,this.dmode);if(s)return this[We](s,t);this[Wi]=!0}if(t.absolute!==this.cwd){let s=ee(He.dirname(String(t.absolute)));if(s!==this.cwd){let a=this[Pn](s,this.dmode);if(a)return this[We](a,t)}}let[e,n]=Bi(()=>oe.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[rd](t);if(e||this[ed](t,n))return this[yt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Bi(()=>{oe.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[yt](d,t)}let[s]=Bi(()=>oe.rmdirSync(String(t.absolute)));this[yt](s,t)}let[i]=t.absolute===this.cwd?[]:Bi(()=>z_(String(t.absolute)));this[yt](i,t)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{oe.closeSync(s)}catch(f){u=f}(d||u)&&this[We](d||u,t),e()},s;try{s=oe.openSync(String(t.absolute),t0(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[We](d,t)),t.pipe(a)),a.on("data",d=>{try{oe.writeSync(s,d,0,d.length)}catch(u){i(u)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{oe.futimesSync(s,u,f)}catch(x){try{oe.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[qi](t)){let u=this[ji](t),f=this[Ki](t);try{oe.fchownSync(s,Number(u),Number(f))}catch(x){try{oe.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Pn](String(t.absolute),n);if(i){this[We](i,t),e();return}if(t.mtime&&!this.noMtime)try{oe.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[qi](t))try{oe.chownSync(String(t.absolute),Number(this[ji](t)),Number(this[Ki](t)))}catch{}e(),t.resume()}[Pn](t,e){try{return C_(ee(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[zi](t,e,n,i,s){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=He.resolve(a,d);let[u,f]=Bi(()=>oe.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return s(new Ao(a,He.resolve(e,n.join("/"))))}i()}[xo](t,e,n,i){let s=`${n}Sync`;try{oe[s](e,String(t.absolute)),i(),t.resume()}catch(a){return this[We](a,t)}}},U_=t=>{let e=new a0(t),n=t.file,i=$f.statSync(n),s=t.maxReadSize||16*1024*1024;new ry(n,{readSize:s,size:i.size}).pipe(e)},H_=(t,e)=>{let n=new hd(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),$f.stat(s,(u,f)=>{if(u)d(u);else{let x=new sd(s,{readSize:i,size:f.size});x.on("error",d),x.pipe(n)}})})},c0=Zi(U_,H_,t=>new a0(t),t=>new hd(t),(t,e)=>{e?.length&&Uf(t,e)}),G_=(t,e)=>{let n=new fd(t),i=!0,s,a;try{try{s=ut.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")s=ut.openSync(t.file,"w+");else throw f}let d=ut.fstatSync(s),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,m=0;p<512;p+=m){if(m=ut.readSync(s,u,p,u.length-p,a+p),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!m)break e}let f=new er(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,q_(t,n,a,s,e)}finally{if(i)try{ut.closeSync(s)}catch{}}},q_=(t,e,n,i,s)=>{let a=new Rf(t.file,{fd:i,start:n});e.pipe(a),K_(e,s)},j_=(t,e)=>{e=Array.from(e);let n=new So(t),i=(s,a,d)=>{let u=(b,y)=>{b?ut.close(s,v=>d(b)):d(null,y)},f=0;if(a===0)return u(null,0);let x=0,p=Buffer.alloc(512),m=(b,y)=>{if(b||y===void 0)return u(b);if(x+=y,x<512&&y)return ut.read(s,p,x,p.length-x,f+x,m);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let v=new er(p);if(!v.cksumValid)return u(null,f);let I=512*Math.ceil((v.size??0)/512);if(f+I+512>a||(f+=I+512,f>=a))return u(null,f);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,ut.read(s,p,0,512,f,m)};ut.read(s,p,0,512,f,m)};return new Promise((s,a)=>{n.on("error",a);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",ut.open(t.file,d,u);if(f||!x)return a(f);ut.fstat(x,(p,m)=>{if(p)return ut.close(x,()=>a(p));i(x,m.size,(b,y)=>{if(b)return a(b);let v=new _o(t.file,{fd:x,start:y});n.pipe(v),v.on("error",a),v.on("close",s),W_(n,e)})})};ut.open(t.file,d,u)})},K_=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Hr({file:d0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},W_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Hr({file:d0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Fi=Zi(G_,j_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!uy(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")}),rT=Zi(Fi.syncFile,Fi.asyncFile,Fi.syncNoFile,Fi.asyncNoFile,(t,e=[])=>{Fi.validate?.(t,e),$_(t)}),$_=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(n,i)=>e(n,i)&&!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0)):(n,i)=>!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0))};Qt();var nt={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",SET_CONFIG_OPTION:"_agent/setConfigOption",LIST_AVAILABLE_MODELS:"_agent/listAvailableModels"};function nr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function l0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ko(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function u0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function f0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function h0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function rr(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Lt();import{homedir as Z_}from"node:os";import x0 from"node:path";var p0=".claude",g0="settings.json",To=new Map;function m0(t){return x0.join(t,p0,g0)}async function w0(t,e){let n=m0(t),s=(To.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=await gt(n)??{};a.effortLevel=e,await Ot(n,a)});To.set(n,s);try{await s}finally{To.get(n)===s&&To.delete(n)}}async function y0(t){let n=(await gt(m0(t)))?.effortLevel;return typeof n=="string"?n:void 0}async function _0(){let t=x0.join(Z_(),p0,g0),n=(await gt(t))?.effortLevel;return typeof n=="string"?n:void 0}an();Je();re();Pe();Je();function Ji(t,e){if(nr(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function xd(t,e){if(nr(t)==="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_CLOUD",`${e} is not allowed for cloud agent`)}function Yi(t){return t.startsWith("http://")||t.startsWith("https://")}function Gr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as XT}from"node:fs";import{dirname as eC,join as tC}from"node:path";import{fileURLToPath as rC}from"node:url";var Gt="0.3.2-alpha.101";var pd={"claude-code":{effort:["default","low","medium","high","xhigh","max"],fastMode:null},codex:{effort:["low","medium","high","xhigh"],fastMode:["off","on"]},hermes:{effort:null,fastMode:null},openclaw:{effort:null,fastMode:null}};function S0(t,e){return pd[t][e]}import{mkdir as ub,rm as z0}from"node:fs/promises";import{join as ts}from"node:path";Lt();import{readFileSync as nb}from"node:fs";var rb=384;async function gd(t,e=process.env){let n={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(n[i]=s);await Ot(t.agentEnvFile,n,{mode:rb})}function ir(t){try{let e=JSON.parse(nb(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Co(t,e,n={},i=s=>s){return{...i({...t,...ir(e)}),...n}}Lt();function Xi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let s=t[i];s!==void 0&&(ib(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
92
92
  `)}
93
- `}function Dy(t){if(t.includes(`
94
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}te();Pe();import{homedir as Ny}from"node:os";import{join as My}from"node:path";Je();te();var vo="1008033",c0="1289";var d0="pbbp2",l0="https://www.coze.cn",u0="/api/coze_claw/resource/get_frontier_key",Oy="https://www.coze.cn",Ly="wss://frontier.coze.cn";function Mr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Oy}function f0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Ly}function kn(t){let e={},n=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return n&&(e["x-tt-env"]=n),i&&(e["x-use-ppe"]=i),e}function Wi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var ji=G("handshake");async function cd(t){let e=Mr(t.endpoint),n=t.timeoutMs??1e4,i=`${Nr(e)}${u0}?aid=${encodeURIComponent(vo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...kn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);ji.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:a.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let b=await u.text().catch(()=>"");throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${f}`);let m=p.data??{},v=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,_=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!v||!_){let b=JSON.stringify(p).slice(0,500);throw new A("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return ji.info("handshake ok",{remoteDeviceId:_,logid:f,traceId:x}),{accessKey:v,deviceId:_}}catch(u){if(u instanceof A)throw ji.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw ji.warn("handshake timeout",{base:e,timeoutMs:n}),new A("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw ji.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new A("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var So=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",kt="auto",dd=19e4,h0=32e3;function p0(t){return{model:ld(t.model)??kt,...t.modelToken?{modelToken:t.modelToken}:{}}}function g0(t){return!t||t===kt}var By=new Set(["auto","\u81EA\u52A8"]);function ld(t){let e=t?.trim();if(e)return By.has(e.toLowerCase())?kt:e}function m0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=So,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||kt;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else g0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function w0(t,e,n,i){let o={};if(t.modelToken?o.model=t.model||kt:g0(t.model)||(o.model=t.model),t.modelToken){let a={name:"coze",base_url:`${So}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Io(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),o.model_providers={coze:a},o.model_context_window=t.modelInfo?.contextWindow??dd}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function _0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Io(t,e,n){let{ttEnv:i,usePpe:o}=Wi(t),a={};return i&&(a["x-tt-env"]=i),o&&(a["x-use-ppe"]=o),e&&(a["x-mock-scenario"]=e),n&&(a["x-coze-request-scene"]=n),a}function y0(t,e,n,i){if(!t.modelToken)return{};let o=Io(e,n,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
95
- `)}}function ud(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function fd(t){return t.model||kt}function x0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function b0(t,e,n,i,o){if(!t.modelToken)return null;let a=fd(t),d=Io(e,n,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let f=[x0(a,u,t.modelInfo?.contextWindow??dd,t.modelInfo?.maxOutput??h0)],x=new Set([a]);for(let m of i??[])!m||x.has(m)||(x.add(m),f.push(x0(m,["text"],dd,h0)));let p={baseUrl:`${So}/v1`,api:"openai-completions",apiKey:t.modelToken,models:f};return Object.keys(d).length>0&&(p.headers=d),p}function Fy(t){if(t!==void 0)return t?"auto":"text"}function hd(t,e,n){let i=Io(e,n),o=t.model||kt,a=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${So}/v1`];if(t.modelInfo?.contextWindow&&a.push(` context_length: ${t.modelInfo.contextWindow}`),t.modelInfo?.maxOutput&&a.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&a.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){a.push(" default_headers:");for(let[u,f]of Object.entries(i))a.push(` ${u}: ${JSON.stringify(f)}`)}a.push("compression:"),a.push(" threshold: 0.8"),a.push("approvals:"),a.push(` mode: ${JSON.stringify("off")}`),a.push(` cron_mode: ${JSON.stringify("approve")}`);let d=Fy(t.modelInfo?.capabilities?.image);return d&&(a.push("agent:"),a.push(` image_input_mode: ${JSON.stringify(d)}`)),a.push("skills:"),a.push(" external_dirs:"),a.push(` - ${My(Ny(),".hermes","skills")}`),`${a.join(`
93
+ `}function ib(t){if(t.includes(`
94
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}re();Pe();import{homedir as ab}from"node:os";import{join as cb}from"node:path";Je();re();var Po="1008033",I0="1289";var A0="pbbp2",k0="https://www.coze.cn",T0="/api/coze_claw/resource/get_frontier_key",sb="https://www.coze.cn",ob="wss://frontier.coze.cn";function qr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??sb}function C0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??ob}function On(t){let e={},n=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return n&&(e["x-tt-env"]=n),i&&(e["x-use-ppe"]=i),e}function es(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Qi=H("handshake");async function md(t){let e=qr(t.endpoint),n=t.timeoutMs??1e4,i=`${Gr(e)}${T0}?aid=${encodeURIComponent(Po)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...On(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);Qi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:s,signal:a.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let v=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${v.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${f}`);let m=p.data??{},b=typeof m.access_key=="string"&&m.access_key||typeof m.accessKey=="string"&&m.accessKey||void 0,y=typeof m.device_id=="string"&&m.device_id||typeof m.deviceId=="string"&&m.deviceId||void 0;if(!b||!y){let v=JSON.stringify(p).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${v}`)}return Qi.info("handshake ok",{remoteDeviceId:y,logid:f,traceId:x}),{accessKey:b,deviceId:y}}catch(u){if(u instanceof k)throw Qi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Qi.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw Qi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Ro=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ct="auto",wd=19e4,P0=32e3;function D0(t){if(!(qt(t.model)&&!t.effort&&!t.fastMode))return{model:t.model,...t.effort?{effort:t.effort}:{},...t.fastMode?{fastMode:t.fastMode}:{}}}function O0(t){return{model:yd(t.model)??Ct,...t.modelToken?{modelToken:t.modelToken}:{}}}function qt(t){return!t||t===Ct}var db=new Set(["auto","\u81EA\u52A8"]);function yd(t){let e=t?.trim();if(e)return db.has(e.toLowerCase())?Ct:e}function L0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Ro,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Ct;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=n,e.ANTHROPIC_DEFAULT_OPUS_MODEL=n,e.ANTHROPIC_DEFAULT_SONNET_MODEL=n,e.CLAUDE_CODE_SUBAGENT_MODEL=n,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow)),t.modelInfo?.maxOutput&&(e.CLAUDE_CODE_MAX_OUTPUT_TOKENS=String(t.modelInfo.maxOutput))}else qt(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function N0(t,e,n,i){let s={};if(t.modelToken?s.model=t.model||Ct:qt(t.model)||(s.model=t.model),t.effort&&(s.model_reasoning_effort=t.effort),t.modelToken){let a={name:"coze",base_url:`${Ro}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Do(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),s.model_providers={coze:a},s.model_context_window=t.modelInfo?.contextWindow??wd}return Object.keys(s).length===0?{}:{CODEX_CONFIG:JSON.stringify(s),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function M0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Do(t,e,n){let{ttEnv:i,usePpe:s}=es(t),a={};return i&&(a["x-tt-env"]=i),s&&(a["x-use-ppe"]=s),e&&(a["x-mock-scenario"]=e),n&&(a["x-coze-request-scene"]=n),a}function B0(t,e,n,i){if(!t.modelToken)return{};let s=Do(e,n,i);return Object.keys(s).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(s).map(([d,u])=>`${d}:${u}`).join(`
95
+ `)}}function _d(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function bd(t){return t.model||Ct}function R0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function F0(t,e,n,i,s){if(!t.modelToken)return null;let a=bd(t),d=Do(e,n,s),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let f=[R0(a,u,t.modelInfo?.contextWindow??wd,t.modelInfo?.maxOutput??P0)],x=new Set([a]);for(let m of i??[])!m||x.has(m)||(x.add(m),f.push(R0(m,["text"],wd,P0)));let p={baseUrl:`${Ro}/v1`,api:"openai-completions",apiKey:t.modelToken,models:f};return Object.keys(d).length>0&&(p.headers=d),p}function lb(t){if(t!==void 0)return t?"auto":"text"}function Ed(t,e,n){let i=Do(e,n),s=t.model||Ct,a=["model:"," provider: custom",` default: ${JSON.stringify(s)}`,` base_url: ${Ro}/v1`];if(t.modelInfo?.contextWindow&&a.push(` context_length: ${t.modelInfo.contextWindow}`),t.modelInfo?.maxOutput&&a.push(` max_tokens: ${t.modelInfo.maxOutput}`),t.modelToken&&a.push(` api_key: ${JSON.stringify(t.modelToken)}`),Object.keys(i).length>0){a.push(" default_headers:");for(let[u,f]of Object.entries(i))a.push(` ${u}: ${JSON.stringify(f)}`)}a.push("compression:"),a.push(" threshold: 0.8"),a.push("approvals:"),a.push(` mode: ${JSON.stringify("off")}`),a.push(` cron_mode: ${JSON.stringify("approve")}`);let d=lb(t.modelInfo?.capabilities?.image);return d&&(a.push("agent:"),a.push(` image_input_mode: ${JSON.stringify(d)}`)),a.push("skills:"),a.push(" external_dirs:"),a.push(` - ${cb(ab(),".hermes","skills")}`),`${a.join(`
96
96
  `)}
97
- `}var Xn=G("hermes-config"),v0="dont_ask",S0="default";function Qn(t,e){return Ki(Re(t,e).root,"hermes-home")}async function Uy(t){let e=Qn(t.agentId,t.paths);await zy(e,{recursive:!0,mode:448});let n=qi({...process.env,...Yn(t.paths.agentEnvFile)});await ct(Ki(e,".env"),n,{mode:384});let i=hd(t.modelConfig,t.cozeEnv,t.mockScenario);await ct(Ki(e,"config.yaml"),i,{mode:384}),Xn.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function I0(t){let e=Qn(t.agentId,t.paths),n=Ki(e,"state.db"),i=Ki(e,"config.yaml");Xn.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:n,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
- `).slice(1,6).join(" | ")}),await E0(n,{force:!0}).catch(a=>Xn.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let o=hd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await ct(i,o,{mode:384}).catch(a=>Xn.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),Xn.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function pd(t,e){let n=Qn(t,e);Xn.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:n,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
- `).slice(1,6).join(" | ")}),await E0(n,{recursive:!0,force:!0}).catch(i=>Xn.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var xd=new Map;function A0(t){let e=xd.get(t.agentId);if(e)return e;let n=Uy(t).finally(()=>xd.delete(t.agentId));return xd.set(t.agentId,n),n}var ie=G("agent-handlers"),T0=5*1024*1024,Wy=1,Ky=6,$y=new Set(["node_modules",".git",".coze","dist","build",".next"]),Vy=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Zy=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Jy=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Yy(t){let e=t?.trim();return e?Jy.test(e)||Zy.test(e)?e:(ie.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Xy(t){return new Promise((e,n)=>{let i=at("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,a=d=>{o||(o=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",d=>a(d))})}function Qy(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var ko=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let n=Jn(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Re(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Fr(a,n,o,this.paths),f=[],x=new Set;for(let m of d){let v=fe(u,m.relPath,"SKILL.md");await Ed(v).then(b=>b.isFile()).catch(()=>!1)&&(f.push(ib(m)),x.add(m.relPath))}if(e.scanLocal){let m=await z0(n,o,a,this.paths),v=await U0(n,a);for(let _ of[...m,...v])x.has(_.relPath)||(x.add(_.relPath),f.push(_.skill))}return{skills:a==="hermes"?f.filter(m=>m.skillName!=="yuanbao"):f}}async addSkills(e){e._meta;let n=Jn(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await To({agentId:n,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});Co(a,d,x),u.push(f)}return await xi(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=Jn(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Fr(i.framework,n,i.workspace,this.paths);for(let f of a){if(!o.has(f.skillId)){d.push(f);continue}let x=fe(u,f.relPath);ie.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:x}),await wd(x,{recursive:!0,force:!0}),ie.info("skill removed",{agentId:n,skillId:f.skillId,relPath:f.relPath})}return await xi(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=Jn(e._meta);if(!e.skillName)throw new A("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ie.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),o=i?.workspace??Re(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await tb(n,o,a,e.skillName,d,this.paths);if(!u){let R=d?"global":"workspace";throw new A("SKILL_NOT_FOUND",`skill not found in ${R}: ${e.skillName}`)}let{absDir:f,relPath:x,dirName:p}=u,m=fe(f,"SKILL.md"),v=new Sd.default;v.addLocalFolder(f,p);let _=v.toBuffer();if(_.length>C0)throw new A("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${C0}`);let b=await Ao(m,{encoding:"utf8"}).then(R=>B0(R).description).catch(()=>{}),S={};this.opts.publishSkillToMarketplace?S=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...b?{description:b}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ie.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let I=S.version??"v1.0",T=S.skillId??e.skillId??M0(n,x);if(i&&!d){let R=i.skills??[],E=R.find(P=>P.relPath===x);E?(E.version=I,E.skillId=T):R.push({skillId:T,skillName:e.skillName,relPath:x,version:I,installedAt:Date.now(),...b?{description:b}:{}}),await xi(n,R)}return ie.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.length,skillId:T,version:I}),{ok:!0,skillId:T,version:I}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[o,a]of i.sessions){if(!a.downstream)continue;let d=a.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,ie.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let f=a.downstream;a.downstream=void 0,ie.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(n).catch(x=>ie.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ie.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await Ie(n);if(!i)throw new A("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return ie.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await mr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw ie.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new A("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await qe(i),ie.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new A("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Ie(n))throw new A("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Gi(e.registry)&&o.push(`--registry=${e.registry}`);let a=Yy(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Vy.test(d)&&o.push("--env",d);let u=await Xy(o);return ie.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:a,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new A("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Ie(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await qe(i),ie.info("agent disconnected",{agentId:n,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(n,e.reason??"disconnect"),{ok:!0}):(ie.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new A("IPC_BAD_REQUEST",`${gt.DELETE}: missing agentId`);ie.warn("[AUDIT] deleteAgent handler entry",{agentId:n,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
- `).slice(1,6).join(" | ")});let i=await Ie(n),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=Re(n);return a==="cloud"?(ie.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:n,path:d.root,deployType:a,reason:e.reason??""}),await wd(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await qe(i)),ie.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(Lr(e._meta,"_agent/switchModel"),!e.agentId)throw new A("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=ld(e.model)??kt,i=await Ie(e.agentId);if(!i)throw new A("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await qe(i),ie.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return ie.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let a=o.model,d=o.modelInfo;o.model=n,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o,a).catch(x=>ie.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=o.framework==="hermes"&&Qy(d,o.modelInfo);if(o.framework==="hermes"&&!u){let x=[];for(let[p,m]of o.allSessionQueues())x.push(m.enqueue(async()=>{let v=o.sessions.get(p);if(!(!v?.downstream||!v.acpSessionId))try{await v.downstream.setSessionModel?.({sessionId:v.acpSessionId,modelId:n})}catch(_){ie.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:v.acpSessionId,err:String(_)})}}));return await Promise.all(x),ie.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let f=[];for(let[x,p]of o.allSessionQueues())f.push(p.enqueue(async()=>{let m=o.sessions.get(x);m?.downstream&&(await m.downstream.stop(`switchModel: ${n}`).catch(()=>{}),m.downstream=void 0)}));return await Promise.all(f),ie.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:f.length}),{ok:!0}}async resetAgent(e){if(Lr(e._meta,gt.RESET),!e.agentId)throw new A("IPC_BAD_REQUEST",`${gt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,gt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>ie.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,gt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),ie.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let a of i.sessions.values())a.acpSessionId=void 0,a.replySeq=0,a.loadingSession=!1,a.spawnFailCount=void 0,a.spawnFailedAt=void 0;let o=new Map;for(let[a,d]of i.sessions)o.set(a,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await hi(e,o)}async clearPersistedAcpSessionIds(e){let n=await Ie(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let o of Object.values(n.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await qe(n)}async repairAgent(e){if(Lr(e._meta,gt.REPAIR),!e.agentId)throw new A("IPC_BAD_REQUEST",`${gt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new A("IPC_BAD_REQUEST",`${gt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){ie.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,gt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){ie.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){ie.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Lr(e._meta,"_agent/getFileTree");let n=e._meta,i=Jn(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),u=await gd(d).catch(()=>null);if(!u)throw new A("IPC_BAD_REQUEST",`path not found: ${a}`);if(u.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await fi(d,o))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=gb(e.depth);return u.isDirectory()?{tree:await pb(o,d,a,f)}:{tree:[{name:mb(a),path:q0(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Lr(e._meta,"_agent/getFileContent");let n=Jn(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new A("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),a=await gd(o).catch(()=>null);if(!a||!a.isFile())throw new A("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new A("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await fi(o,i))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>T0)throw new A("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${T0})`);let d=await Ao(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:a.size}:{content:d.toString("utf8"),encoding:"utf-8",size:a.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await Ie(e).catch(()=>null))?.workspace??Re(e).workspace}safeJoin(e,n){let i=yd(e,n||"."),o=vd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${P0}`))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return Ie(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new A("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function L0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new A("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new A("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Fr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:fe(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:fe(".agents","skills")};case"hermes":return{base:Qn(e,i??Z()),subdir:"skills"}}}function N0(t){let e=Gy();if(t==="claude-code")return[fe(e,".claude","skills")];if(t==="codex")return[fe(e,".agents","skills"),fe(e,".codex","skills")];if(t==="openclaw")return[fe(e,".agents","skills"),fe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||fe(e,"AppData","Local");return[fe(n,"hermes","skills"),fe(e,".hermes","skills")]}return[fe(e,".hermes","skills")]}return[]}async function eb(t,e,n,i,o,a){let d=async u=>Ed(fe(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=Fr(n,t,e,a),x=fe(f,i),p=fe(u,x);return await d(p)?{absDir:p,relPath:x}:null}for(let u of N0(n)){let f=fe(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function tb(t,e,n,i,o,a){let d=L0(i),u=await eb(t,e,n,d,o,a);if(u)return{...u,dirName:d};let x=(o?await U0(t,n):await z0(t,e,n,a)).filter(v=>v.skill.skillName===i);if(x.length>1)throw new A("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${x.map(v=>k0(v.relPath)).join(", ")} \u2014 rename or remove duplicates`);let p=x[0];return p?{absDir:o?p.relPath:fe(e,p.relPath),relPath:p.relPath,dirName:k0(p.relPath)}:null}function M0(t,e){return(Hy("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function B0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
- ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.split(`
102
- `)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!a||!a[2])continue;let d=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function F0(t,e,n,i){let o=await R0(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let a=[];for(let d of o){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await Ed(fe(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,x=fe(n,f),p=fe(e,f,"SKILL.md"),m=await Ao(p,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let v=B0(m);a.push({relPath:x,skill:{skillId:M0(t,x),skillName:v.name||f,...v.description?{description:v.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function z0(t,e,n,i){let{base:o,subdir:a}=Fr(n,t,e,i);return F0(t,fe(o,a),a,!1)}async function U0(t,e){let n=[],i=new Set;for(let o of N0(e)){let a=await F0(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var nb=3e4,rb=50*1024*1024,C0=10*1024*1024,Br=3e4;async function To(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:a}=t;if(!o.skillName)throw new A("IPC_BAD_REQUEST","skill missing skillName");let d=typeof o.content=="string"&&o.content.length>0,u=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!u)throw new A("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=L0(o.skillName),{base:x,subdir:p}=Fr(i,e,n,a),m=fe(p,f),v=fe(x,m);if(await md(v,{recursive:!0}),d){let b=Buffer.from(o.content,"utf8");$i(b.length),await _d(fe(v,"SKILL.md"),b,"utf8")}else{let b=await ob(o.downloadUrl);cb(b)?await fb(b,v):db(b)?await lb(b,v):await _d(fe(v,"SKILL.md"),b.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:m,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 ie.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:m,source:d?"content":"downloadUrl"}),_}function Co(t,e,n){let i=e.get(n.skillId);if(i!==void 0){t[i]=n;return}e.set(n.skillId,t.length),t.push(n)}function ib(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 sb(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function H0(t,e){let n=await Ie(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Bt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await qe(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((m,v)=>[m.skillId,v])),u=a.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await qe(n,e),{status:"noop",count:0};let f=0,x=0,{base:p}=Fr(n.framework,t,n.workspace,e);ie.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:p,builtinCount:u.length,builtinRelPaths:u.map(m=>m.relPath)});for(let m of u)try{let v=fe(p,m.relPath);ie.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:m.skillId,relPath:m.relPath,rmTarget:v}),await wd(v,{recursive:!0,force:!0});let _=await To({agentId:t,workspace:n.workspace,framework:n.framework,skill:sb(m),...e?{paths:e}:{}});Co(a,d,_),f+=1}catch(v){x+=1,ie.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(v)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await qe(n,e),ie.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function ob(t){if(!t)throw new A("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);$i(e);let n=ab(t);return $i(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Ao(e);return $i(n.length),n}if(Gi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),nb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new A("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return $i(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new A("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function $i(t){if(t>rb)throw new A("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function ab(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new A("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function cb(t){return t.length>=2&&t[0]===31&&t[1]===139}function db(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],n=t[3];return e===3&&n===4||e===5&&n===6}function bd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function lb(t,e){let n,i;try{n=new Sd.default(t),i=n.getEntries()}catch(d){throw new A("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||bd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new A("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new A("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new A("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=ub(i),a=yd(e);for(let d of i){if(bd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=yd(e,u),x=vd(a,f);if(x.startsWith("..")||x==="..")throw new A("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await md(f,{recursive:!0});continue}await md(qy(f),{recursive:!0});let p;try{p=d.getData()}catch(m){throw new A("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${m.message}`,{cause:m})}await _d(f,p)}}function ub(t){let e;for(let n of t){let i=n.entryName;if(!i||bd(i))continue;let o=i.indexOf("/");if(o<=0)return;let a=i.slice(0,o+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function fb(t,e){await hb(t);let n=Qf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new A("IPC_BAD_REQUEST",`tar extract timeout (${Br}ms)`))},Br);try{await O0(D0.from(t),n)}catch(a){throw a instanceof A?a:i?new A("IPC_BAD_REQUEST",`tar extract timeout (${Br}ms)`):new A("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function hb(t){let e=[],n=Or({onReadEntry:a=>{let d=a.path,u=a.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new A("IPC_BAD_REQUEST",`tar list timeout (${Br}ms)`))},Br);try{await O0(D0.from(t),n)}catch(a){throw i?new A("IPC_BAD_REQUEST",`tar list timeout (${Br}ms)`):new A("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new A("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var xb=5e3;async function pb(t,e,n,i){return G0(t,e,n,i,{count:0})}async function G0(t,e,n,i,o){if(i<=0)return[];let a;try{a=await R0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if($y.has(u.name)||u.isSymbolicLink())continue;if(o.count>=xb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=fe(e,u.name),x=jy(fe(n,u.name)),p=null;try{p=await gd(f)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let m={name:u.name,path:q0(vd(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(m.children=await G0(t,f,x,i-1,o)),d.push(m)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function gb(t){return!t||t<=0?Wy:Math.min(t,Ky)}function mb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function q0(t){return t.split(P0).join("/")}te();var Tn=G("agent-health-reporter"),wb=1e4,_b=3,Vi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??wb,this.livenessFailureThreshold=e.livenessFailureThreshold??_b}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Tn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Tn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Tn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Tn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=yb(d);if(!u)continue;let f={agentId:d.agentId,status:u};d.patToken&&(f.patToken=d.patToken),d.accountId&&(f.accountId=d.accountId),n.push(f)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Bt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Tn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(Tn.warn("heartbeat received authFailures from cloud",{count:a.length,agentIds:a.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(a)}catch(d){Tn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Tn.warn("onTickEnd hook failed",{err:String(n)})}}};function yb(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}$t();import{copyFile as BE,cp as FE,mkdir as Ho,readFile as zE,rm as UE,stat as Dd,writeFile as HE}from"node:fs/promises";import{homedir as Ah}from"node:os";import{basename as GE,join as zt}from"node:path";fn();import{existsSync as Pb}from"node:fs";import{release as Db}from"node:os";import{basename as Ob,isAbsolute as Lb}from"node:path";function Zi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function zr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Ur(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Cn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Je();var Ro=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 j0(t){return"method"in t&&"id"in t&&t.id!==void 0}function W0(t){return"method"in t&&!("id"in t)}function Po(t){return!("method"in t)&&"id"in t}var bb={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 Eb(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ji(t.message)}:typeof t=="string"?Ji(t):typeof t=="object"?Sb(t):t}var vb=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Ji(t){let e=t;for(let[n,i]of vb)e=e.replace(n,i);return e}function Sb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=Ji(i):e[n]=i;return e}function Yi(t){if(t instanceof A){let e=Eb(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(n.reason=e.reason),{code:bb[t.code]??Y.INTERNAL_ERROR,message:Ji(t.message),data:n}}return{code:Y.INTERNAL_ERROR,message:Ji(t instanceof Error?t.message:String(t))}}function K0(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,a=t.data;if(i&&e){let{message:d,...u}=e;a=u}return new A(n,o,{retriable:e?.retriable??!1,cause:a})}function V0(t){return`${JSON.stringify(t)}
103
- `}var $0=10*1024*1024,Do=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>$0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${$0} bytes`)}),[]}let n=this.buffer.split(`
104
- `);this.buffer=n.pop()??"";let i=[];for(let o of n){let a=o.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(d){this.onError?.({line:a,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var J0={"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"},gC=Object.fromEntries(Object.entries(J0).map(([t,e])=>[e,t])),Ib={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Hr=class{seq=0;next(e,n){this.seq+=1;let i=J0[e]??Ab(e),o=Ib[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>Z0(n?.[f]??"")),u=kb(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>Z0(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function Ab(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Z0(t){return t.replace(/[:_\s]+/g,"-")}function kb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}en();fr();Je();te();Pe();import{execFileSync as Tb,spawnSync as Cb}from"node:child_process";function Xi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Qi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),Cb("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Id=new Set;function Y0(t){typeof t=="number"&&t>0&&Id.add(t)}function X0(t){typeof t=="number"&&Id.delete(t)}function Q0(){for(let t of Id)Qi(t,"SIGKILL")}var Gr="coze-bridge-daemon";function eh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Tb("pgrep",["-U",String(o),"-f",Gr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
105
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function th(t,e){if(t.length===0)return;let n=e?.killFn??Qi,i=e?.isAliveFn??Xi,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<a&&t.some(f=>i(f));u+=d)await o(Math.min(d,a-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var Rb=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function nh(t,e){if(!e)return null;for(let n of Rb)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function rh(t,e){return nh(t,e)}function ih(t,e){return nh(t,e)}function qr(t,e,n){return!e&&n.firstUpdateMs>0&&t<n.firstUpdateMs?Math.max(1,n.firstUpdateMs-t):t<n.phase2GateMs?Math.max(1,n.phase2GateMs-t):Math.max(1,n.livenessWindowMs)}function sh(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,p=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:qr(p,t.firstFrameSeen,e)}}let a=n-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return a>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?a<e.phase2GateMs?{action:"continue",rearmMs:qr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:qr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:qr(a,!1,e)}}var oh=Xe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Nb=200,Mb=40,Bb=Xe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fb=Xe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zb=Xe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Ub=Xe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hb=Xe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Gb=Xe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),ah=500;function qb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=ah?t:`${e.slice(0,ah)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function jb(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:n}=t;if(typeof n=="string")e.push(n);else if(n&&typeof n=="object")try{e.push(JSON.stringify(n))}catch{}return e.join(" ")}function ch(t){try{return Pb(t)}catch{return}}function Wb(t,e){return{platform:process.platform,osRelease:Db(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Lb(e.command)?ch(e.command):void 0,cwd:e.cwd,cwdExists:ch(e.cwd),envKeys:e.envKeys}}function Kb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Ob(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var mt=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Do({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Hr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new A("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=Eo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=at(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Y0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let a of this.decoder.push(o))this.dispatch(a)}catch(a){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(a)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let a=o.trimEnd();this.stderrRing.push(a),this.stderrRing.length>Nb&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,a)=>{this.stopped=!0,X0(i.pid),(o!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:a,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,a));for(let u of this.exitHandlers)u(o,a)}),i.on("error",o=>{let a=o,d=Wb(a,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new A("AGENT_SPAWN_FAILED",Kb(a,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let n=this.child,i=new Promise(a=>n.once("exit",()=>a()));Qi(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||Qi(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Hb,phase2GateMs:Bb,livenessWindowMs:Fb,absoluteMaxMs:zb,approvalMaxMs:Gb,suspendThresholdMs:Ub,...n};return this.call("session/prompt",e,oh,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(zr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Ur(e,n))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Cn(e,n))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,n,i=oh,o){if(!this.child||this.stopped)return Promise.reject(new A("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=Zi(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let f=n.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let p={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let m=this.now(),v={cfg:o,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:qr(0,!1,o),sessionId:u};p.promptTimeout=v;let _=()=>{let b={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},S=this.now(),I=sh(b,v.cfg,S),T=R=>{v.armedAt=S,v.expectedIntervalMs=R,p.timer=setTimeout(_,R)};if(I.action==="suspend"){v.suspendedMs+=I.suspendedDeltaMs,v.lastActivityAt=S,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:I.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),T(I.rearmMs);return}if(I.action==="continue"){T(I.rearmMs);return}this.pending.delete(a),I.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:I.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(I.awaitingApproval?new A("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new A("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new A("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,p);try{this.writeFrame(d)}catch(m){p.timer&&clearTimeout(p.timer),this.pending.delete(a),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new A("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(V0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Po(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new A("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:qb(e.result)}),n.resolve(e.result));return}if(W0(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(j0(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let a=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!a)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Cn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let n of this.agentRequestHandlers)try{await n(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(Cn(e.id,Yi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=K0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=ih(this.framework,jb(e));return i?new A(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new A("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(Mb).join(`
106
- `),o=rh(this.framework,i);return o?new A(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:n,stderrTail:i}}):new A("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function $b(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=i));return e}var Oo=class extends mt{framework="claude-code";constructor(e){let{command:n,args:i}=ui("claude-code",e.command,e.args??[]),o={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return $b(e)}};fn();import{spawn as Vb}from"node:child_process";import{closeSync as Zb,existsSync as Td,mkdirSync as Jb,mkdtempSync as Yb,openSync as Xb,readFileSync as ph,readSync as Qb,readdirSync as eE,rmSync as tE,statSync as nE}from"node:fs";import{homedir as rE,tmpdir as iE}from"node:os";import{join as jr}from"node:path";var dh=["default","acceptEdits","plan","auto","bypassPermissions"],lh=["read-only","auto","full-access"];var uh=["default","accept_edits","dont_ask"];function Ft(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return dh.includes(e);case"codex":return lh.includes(e);case"hermes":return uh.includes(e);case"openclaw":return!1}}function Lo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function fh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Ad(t){switch(t){case"claude-code":return dh.join("/");case"codex":return lh.join("/");case"hermes":return uh.join("/");case"openclaw":return""}}Pe();var Cd=9e4,sE=64*1024,oE=100;function aE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Cd:Math.max(1,Math.floor(e*1e3))}function cE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Cd:Math.max(1,Math.floor(e))}function dE(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return Object.keys(e).length>0?e:void 0}function hh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:Cd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let n=typeof e.command=="string"?e.command.trim():"";if(!n)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,o=dE(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?aE(e.timeout):cE(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function kd(t){if(Array.isArray(t))return t.flatMap(i=>kd(i));if(!t||typeof t!="object"){let i=hh(t);return i?[i]:[]}let e=t;if(e.hooks)return kd(e.hooks);let n=hh(e);return n?[n]:[]}function lE(t){let e=jr(t,"hooks.json");if(!Td(e))return[];let n=JSON.parse(ph(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return kd(o.Stop??o.stop)}function uE(t,e){let n=jr(t,"sessions");if(!Td(n))return;let i=[],o=a=>{let d;try{d=eE(a,{withFileTypes:!0})}catch{return}for(let u of d){let f=jr(a,u.name);if(u.isDirectory())o(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:nE(f).mtimeMs})}catch{}}};o(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,oE))if(fE(a.path,e))return a.path}function fE(t,e){let n;try{n=Xb(t,"r");let i=Buffer.alloc(sE),o=Qb(n,i,0,i.length,0),a=i.subarray(0,o).toString("utf8");return a.includes(JSON.stringify(e))||a.includes(e)}catch{return!1}finally{if(n!==void 0)try{Zb(n)}catch{}}}function hE(t){return Yn(t??Z().agentEnvFile)}function xE(t){let e=t.trim();if(e.length>=2){let n=e[0];if((n==='"'||n==="'")&&e.endsWith(n)){let i=e.slice(1,-1);return n==='"'?i.replace(/\\n/g,`
107
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function pE(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.startsWith("export ")?i.slice(7).trimStart():i,a=o.indexOf("=");if(a<=0)continue;let d=o.slice(0,a).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=xE(o.slice(a+1)))}return e}function gE(t){let e=jr(t,"cozeloop.env");return Td(e)?pE(ph(e,"utf8")):{}}function xh(t){let e=t?.trim();return e||void 0}function mE(t){let e=hE(t.agentEnvFile),n=xh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=xh(t.env?.HOME??e.HOME??process.env.HOME)??rE();return jr(i,".codex")}var No=class extends mt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:a}=ui("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Yb(jr(iE(),"coze-bridge-codex-home-")):mE(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Jb(d,{recursive:!0});let f=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:o,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=Ft("codex",e.modeId)?Lo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(wE(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=lE(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let o=uE(n,e),a=JSON.stringify({hook_event_name:"Stop",session_id:e,...o?{transcript_path:o}:{},trigger:"coze-bridge"});await Promise.all(i.map(async d=>{try{await this.runHookCommand(d,a)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:n,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,n){return new Promise((i,o)=>{let a=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=a?gE(a):{},u=Eo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let f=Vb(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",p=setTimeout(()=>{f.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);f.stderr?.setEncoding("utf8"),f.stderr?.on("data",m=>{x+=m,x.length>4e3&&(x=x.slice(-4e3))}),f.on("error",m=>{clearTimeout(p),o(m)}),f.on("close",(m,v)=>{if(clearTimeout(p),m===0){i();return}o(new Error(`hook exited code=${m} signal=${v} stderr=${x.slice(-1e3)}`))}),f.stdin.end(`${n}
108
- `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{tE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function wE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=fh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}te();var _E=G("hermes-downstream"),Mo=class extends mt{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setSessionModel({sessionId:e,modelId:this.modelId})}catch(n){_E.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}};Je();var yE=3e4,Wr=class extends mt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},yE))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Kt();Je();te();Pe();function Rd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}fn();var Rn=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((n,i)=>{this.slots.push({task:e,resolve:n,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let n=await e.task();e.resolve(n)}catch(n){e.reject(n)}}}finally{this.running=!1}}}};var Bo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Rn,this.sessionQueues.set(e,n)),n}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let n=this.sessionQueues.get(e);return!!n&&!n.isDisposed}async dispose(e){this.status="stopped";let n=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(n);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let n=[];for(let[,i]of this.sessions)Kr(i),i.downstream&&(n.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(n),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Kr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function tn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}en();te();import{constants as gh}from"node:fs";import{access as bE,readFile as EE}from"node:fs/promises";import{delimiter as vE,dirname as SE,join as mh}from"node:path";var rt=G("framework-detector"),wh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},IE=[".exe",".cmd",".bat",".ps1"],er=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??at,access:e.access??bE,readFile:e.readFile??EE}}async detect(e){let n=wh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return rt.debug("framework binary not found",{framework:e,bin:n}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(wh).map(async i=>[i,await this.detect(i)])),n={};for(let[i,o]of e)o&&(n[i]=o);return n}async which(e){let n=this.env.pathEnv.split(vE).filter(Boolean),i=this.env.platform==="win32"?["",...IE]:[""];for(let o of n)for(let a of i){let d=mh(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?gh.F_OK:gh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(d){return rt.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let o=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!o)return rt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=mh(SE(o),"hermes-acp");return await this.isExecutable(a)?(rt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(rt.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:a}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return rt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return rt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return rt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return rt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=o.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(rt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(rt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return rt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return rt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||rt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let o={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){rt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(kE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",a=!1,d,u=f=>{a||(a=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},AE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function kE(t){return t.replace(AE,"")}import{homedir as yh}from"node:os";import{join as zo}from"node:path";Kt();en();fr();Je();te();async function bh(){let t=zo(yh(),".openclaw/openclaw.json");return hn(t)}async function Eh(){return(await bh())?.gateway?.auth?.token??""}var tr=G("openclaw.config"),TE=[0,5e3,5e3],CE=Xe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),_h="models.providers.",Fo="agents.defaults.models",RE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function $r(t,e){let n=Array.isArray(t)?[...t]:[],i=new Set(n);for(let o of e)i.has(o)||(i.add(o),n.push(o));return n}var Uo=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Rn;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??TE,this.cliTimeoutMs=e.cliTimeoutMs??CE,this.openclawDir=e.openclawDir??zo(yh(),".openclaw")}async withRetry(e,n){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let a=this.retryDelaysMs[o]??0;a>0&&await new Promise(d=>setTimeout(d,a));try{return await n()}catch(d){i=d,tr.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new A("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=at(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{a+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let o=String(i);if(n.some(a=>o.includes(a)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){tr.warn(`${e} failed (best-effort)`,{configPath:n,err:String(i)})}}ensureProvider(e,n){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${_h}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${_h}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Fo}[${e}]`,()=>this.runCli(["config","set",Fo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Fo}[${e}]`,`${Fo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await bh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let o=`${e}/`,a=[];for(let d of Object.keys(i))d.startsWith(o)&&a.push(d.slice(o.length));return a}ensureAgent(e,n,i){let o=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}ensureAcpDeviceScopes(){return this.queue.enqueue(()=>this.ensureAcpDeviceScopesUnlocked())}async ensureAcpDeviceScopesUnlocked(){try{let e=zo(this.openclawDir,"identity","device.json"),i=(await hn(e))?.deviceId?.trim();if(!i)return tr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=zo(this.openclawDir,"devices","paired.json"),a=await hn(o),d=a?.[i];if(!a||!d)return tr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,f=$r($r(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(b=>b.startsWith("operator.")),x=$r([...RE],f),p=$r(d.scopes,x),m=$r(d.approvedScopes,x),v=u?$r(u.scopes,x):void 0;return p.length!==(d.scopes?.length??0)||m.length!==(d.approvedScopes?.length??0)||u!==void 0&&v?.length!==(u.scopes?.length??0)?(d.scopes=p,d.approvedScopes=m,u&&v&&(u.scopes=v),await xn(o,a,{mode:384}),tr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(tr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return tr.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as PE,writeFile as DE}from"node:fs/promises";import{join as OE}from"node:path";var LE=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
109
- `),NE=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
110
- `);function ME(t){return t.length===0?t:`${(t.endsWith(`
97
+ `}var sr=H("hermes-config"),U0="dont_ask",H0="default";function or(t,e){return ts(Le(t,e).root,"hermes-home")}async function fb(t){let e=or(t.agentId,t.paths);await ub(e,{recursive:!0,mode:448});let n=Xi({...process.env,...ir(t.paths.agentEnvFile)});await mt(ts(e,".env"),n,{mode:384});let i=Ed(t.modelConfig,t.cozeEnv,t.mockScenario);await mt(ts(e,"config.yaml"),i,{mode:384}),sr.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function G0(t){let e=or(t.agentId,t.paths),n=ts(e,"state.db"),i=ts(e,"config.yaml");sr.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:n,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
+ `).slice(1,6).join(" | ")}),await z0(n,{force:!0}).catch(a=>sr.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let s=Ed({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await mt(i,s,{mode:384}).catch(a=>sr.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),sr.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function Sd(t,e){let n=or(t,e);sr.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:n,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
+ `).slice(1,6).join(" | ")}),await z0(n,{recursive:!0,force:!0}).catch(i=>sr.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var vd=new Map;function q0(t){let e=vd.get(t.agentId);if(e)return e;let n=fb(t).finally(()=>vd.delete(t.agentId));return vd.set(t.agentId,n),n}import{execFile as hb}from"node:child_process";import{createHash as j0}from"node:crypto";import{readFile as xb}from"node:fs/promises";import{homedir as pb}from"node:os";import gb from"node:path";import{promisify as mb}from"node:util";var wb=mb(hb),yb=3e4;function cn(t){return typeof t=="object"&&t!==null?t:null}function jr(t){return Array.isArray(t)?t:[]}function jt(t){return typeof t=="string"?t:void 0}function K0(t,e){return t.map(n=>cn(n)).filter(n=>n!==null).map(n=>{let i={id:jt(n[e])??""},s=jt(n.name),a=jt(n.description);return s&&(i.name=s),a&&(i.description=a),i}).filter(n=>n.id!=="")}function _b(t){let e=jr(t.configOptions);if(e.length===0)return null;let n=null,i,s,a;for(let d of e){let u=cn(d);if(!u)continue;let f=jt(u.id);if(!f)continue;let x=jr(u.options);f==="model"?(n=K0(x,"value"),i=jt(u.currentValue)):f==="effort"||f==="reasoning_effort"?s=x.map(p=>jt(cn(p)?.value)).filter(p=>p!==void 0):f==="fast-mode"&&(a=x.map(p=>jt(cn(p)?.value)).filter(p=>p!==void 0))}return n?{models:n,...i?{currentModelId:i}:{},...s?{effortLevels:s}:{},...a?{fastModes:a}:{}}:null}function bb(t){let e=cn(t.models);if(!e)return null;let n=jr(e.availableModels);if(n.length===0)return null;let i=K0(n,"modelId");if(i.length===0)return null;let s=jt(e.currentModelId);return{models:i,...s?{currentModelId:s}:{}}}function W0(t,e){let n=cn(e);if(!n)return null;let i=cn(n.result)??n;return t==="hermes"?bb(i):_b(i)}function Eb(t){let e=[],n=t.split(/\r?\n/),i=!1,s=-1,a=null,d=-1,u=!1,f=-1,x=p=>p.length-p.trimStart().length;for(let p of n){let m=p.replace(/#.*$/,"").trimEnd();if(m.trim()==="")continue;let b=x(m),y=m.trim();if(!i){y==="providers:"&&(i=!0,s=b);continue}if(b<=s&&!y.startsWith("-"))break;if((a===null||b<=d)&&y.endsWith(":")&&!y.startsWith("-")){a=y.slice(0,-1).trim(),d=b,u=!1;continue}if(a!==null){if(!u){y==="models:"&&(u=!0,f=b);continue}if(y.startsWith("-")&&b>f){let v=y.slice(1).trim(),I,A=v.match(/^(?:model|id)\s*:\s*(.+)$/);if(A?.[1]?I=A[1].trim():v&&!v.includes(":")&&(I=v),I){let T=I.replace(/^["']|["']$/g,"");e.push({id:`${a}:${T}`,providerId:a})}continue}b<=f&&(u=!1,b<=d&&y.endsWith(":")&&(a=y.slice(0,-1).trim(),d=b))}}return e}async function $0(t){let e=t??pb(),n=gb.join(e,".hermes","config.yaml"),i;try{i=await xb(n,"utf8")}catch{return null}let s=Eb(i);return s.length===0?null:{models:s}}async function V0(t){let e;try{({stdout:e}=await wb(t,["models","list","--json","--log-level","silent"],{timeout:yb,maxBuffer:4*1024*1024}))}catch{return null}return vb(e)}function vb(t){let e;try{e=JSON.parse(t)}catch{return null}let n=jr(cn(e)?.models);if(n.length===0)return null;let i=n.map(f=>cn(f)).filter(f=>f!==null&&f.available!==!1),s=i.filter(f=>jr(f.tags).some(x=>x==="configured")),a=s.length>0?s:i,d=[],u;for(let f of a){let x=jt(f.key);if(!x)continue;let p={id:x},m=jt(f.name);m&&(p.name=m);let b=x.indexOf("/");b>0&&(p.providerId=x.slice(0,b)),d.push(p),!u&&jr(f.tags).some(y=>y==="default")&&(u=x)}return d.length===0?null:{models:d,...u?{defaultModelId:u}:{}}}function Sb(t){let e=[...t].sort((n,i)=>n.id.localeCompare(i.id));return j0("sha1").update(JSON.stringify(e)).digest("hex")}function Z0(t){return j0("sha1").update(Sb(t.models)).update(JSON.stringify(t.effortLevels??null)).update(JSON.stringify(t.fastModes??null)).digest("hex")}var Y=H("agent-handlers"),Y0=5*1024*1024,Cb=1,Pb=6,Rb=new Set(["node_modules",".git",".coze","dist","build",".next"]),Db=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ob=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Lb=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Nb(t){let e=t?.trim();return e?Lb.test(e)||Ob.test(e)?e:(Y.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Mb(t){return new Promise((e,n)=>{let i=ct("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),s=!1,a=d=>{s||(s=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",d=>a(d))})}function Bb(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var Lo=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let n=rr(e._meta),i=await this.loadAgentCfg(n),s=i?.workspace??Le(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Wr(a,n,s,this.paths),f=[],x=new Set;for(let m of d){let b=he(u,m.relPath,"SKILL.md");await Rd(b).then(v=>v.isFile()).catch(()=>!1)&&(f.push(Gb(m)),x.add(m.relPath))}if(e.scanLocal){let m=await ch(n,s,a,this.paths),b=await dh(n,a);for(let y of[...m,...b])x.has(y.relPath)||(x.add(y.relPath),f.push(y.skill))}return{skills:a==="hermes"?f.filter(m=>m.skillName!=="yuanbao"):f}}async addSkills(e){e._meta;let n=rr(e._meta),i=await this.requireAgentCfg(n),s=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((f,x)=>[f.skillId,x])),u=[];for(let f of s){let x=await No({agentId:n,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});Mo(a,d,x),u.push(f)}return await Ei(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=rr(e._meta),i=await this.requireAgentCfg(n),s=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Wr(i.framework,n,i.workspace,this.paths);for(let f of a){if(!s.has(f.skillId)){d.push(f);continue}let x=he(u,f.relPath);Y.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:x}),await kd(x,{recursive:!0,force:!0}),Y.info("skill removed",{agentId:n,skillId:f.skillId,relPath:f.relPath})}return await Ei(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=rr(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");Y.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),s=i?.workspace??Le(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await zb(n,s,a,e.skillName,d,this.paths);if(!u){let R=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${R}: ${e.skillName}`)}let{absDir:f,relPath:x,dirName:p}=u,m=he(f,"SKILL.md"),b=new Od.default;b.addLocalFolder(f,p);let y=b.toBuffer();if(y.length>X0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${X0}`);let v=await Oo(m,{encoding:"utf8"}).then(R=>oh(R).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):Y.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??sh(n,x);if(i&&!d){let R=i.skills??[],E=R.find(P=>P.relPath===x);E?(E.version=A,E.skillId=T):R.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await Ei(n,R)}return Y.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:y.length,skillId:T,version:A}),{ok:!0,skillId:T,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[s,a]of i.sessions){if(!a.downstream)continue;let d=a.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,Y.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d});continue}let f=a.downstream;a.downstream=void 0,Y.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d}),f.stop(n).catch(x=>Y.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:s,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return Y.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await me(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return Y.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Ir(i.workspace,i.framework,e.cozeIdentity)}catch(s){throw Y.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(s)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(s)}`,{cause:s})}return i.cozeIdentity=e.cozeIdentity,await Ne(i),Y.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await me(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=["-y"];e.registry&&Yi(e.registry)&&s.push(`--registry=${e.registry}`);let a=Nb(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Db.test(d)&&s.push("--env",d);let u=await Mb(s);return Y.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:a,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await me(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Ne(i),Y.info("agent disconnected",{agentId:n,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(n,e.reason??"disconnect"),{ok:!0}):(Y.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST",`${nt.DELETE}: missing agentId`);Y.warn("[AUDIT] deleteAgent handler entry",{agentId:n,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
+ `).slice(1,6).join(" | ")});let i=await me(n),s=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??s??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=Le(n);return a==="cloud"?(Y.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:n,path:d.root,deployType:a,reason:e.reason??""}),await kd(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Ne(i)),Y.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=yd(e.model)??Ct;if(nr(e._meta)!=="cloud")return this.switchModelLocal(e,n);let i=await me(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,e.modelInfo&&(i.modelInfo=e.modelInfo),await Ne(i),Y.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return Y.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let a=s.model,d=s.modelInfo;s.model=n,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s,a).catch(x=>Y.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=s.framework==="hermes"&&Bb(d,s.modelInfo);if(s.framework==="hermes"&&!u){let x=[];for(let[p,m]of s.allSessionQueues())x.push(m.enqueue(async()=>{let b=s.sessions.get(p);if(!(!b?.downstream||!b.acpSessionId))try{await b.downstream.setSessionModel?.({sessionId:b.acpSessionId,modelId:n})}catch(y){Y.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:b.acpSessionId,err:String(y)})}}));return await Promise.all(x),Y.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let f=[];for(let[x,p]of s.allSessionQueues())f.push(p.enqueue(async()=>{let m=s.sessions.get(x);m?.downstream&&(await m.downstream.stop(`switchModel: ${n}`).catch(()=>{}),m.downstream=void 0)}));return await Promise.all(f),Y.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:f.length}),{ok:!0}}async switchModelLocal(e,n){let i=await me(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,await Ne(i),Y.info("_agent/switchModel(local): model persisted",{agentId:e.agentId,model:n});let s=this.opts.agents.get(e.agentId);if(!s)return Y.info("_agent/switchModel(local): agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};if(s.model=n,qt(n))return Y.info("_agent/switchModel(local): auto sentinel, skip runtime fan-out",{agentId:e.agentId}),{ok:!0};let a=await this.fanOutConfigAxis(s,e.agentId,"model",n,"_agent/switchModel(local)");return Y.info("_agent/switchModel(local): sessions updated via set_config_option",{agentId:e.agentId,model:n,cloudSessions:a}),{ok:!0}}async fanOutConfigAxis(e,n,i,s,a){let d=[];for(let[u,f]of e.allSessionQueues())d.push(f.enqueue(async()=>{let x=e.sessions.get(u);!x?.downstream||!x.acpSessionId||await x.downstream.setConfigOption(x.acpSessionId,i,s).catch(p=>Y.warn(`${a}: set_config_option failed (ignored)`,{agentId:n,cloudId:u,err:String(p)}))}));return await Promise.all(d),d.length}async setConfigOption(e){if(xd(e._meta,nt.SET_CONFIG_OPTION),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/setConfigOption: missing agentId");let n=await me(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=S0(n.framework,e.configType);if(!i)throw new k("CAPABILITY_UNSUPPORTED",`${n.framework} does not support config '${e.configType}'`);let s=this.opts.modelListCache?.get(n.framework);if(!((e.configType==="effort"?s?.effortLevels:s?.fastModes)??i).includes(e.value))throw new k("IPC_BAD_REQUEST",`invalid ${e.configType} value '${e.value}' for ${n.framework}`);let d=e.value;n.framework==="claude-code"&&e.configType==="effort"&&e.value==="default"&&(d=await this.resolveEffortDefault(n.workspace));let u=n[e.configType];n[e.configType]=d,await Ne(n),Y.info("_agent/setConfigOption: persisted",{agentId:e.agentId,configType:e.configType,value:d}),n.framework==="claude-code"&&e.configType==="effort"&&await w0(n.workspace,d).catch(x=>Y.warn("_agent/setConfigOption: writeCcWorkspaceEffort failed (ignored)",{agentId:e.agentId,err:String(x)}));let f=this.opts.agents.get(e.agentId);return f&&(e.configType==="effort"?f.setEffort(d):f.setFastMode(d),await this.fanOutConfigAxis(f,e.agentId,e.configType,d,"_agent/setConfigOption")),{ok:!0,previousValue:u,currentValue:d}}async resolveEffortDefault(e){let n=await y0(e).catch(()=>{});if(n)return n;let i=await _0().catch(()=>{});return i||"default"}async listAvailableModels(e){if(xd(e._meta,nt.LIST_AVAILABLE_MODELS),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/listAvailableModels: missing agentId");let n=await me(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=n.framework,s=this.opts.modelListCache,a=[],d,u="fallback",f=s?.get(i);if(f&&f.models.length>0)a=f.models,d=f.defaultModelId,u="cache";else if(i==="hermes"){let T=await $0().catch(()=>null);T&&T.models.length>0&&(a=T.models,d=T.defaultModelId,u="disk")}else if(i==="openclaw"){let T=await this.opts.openclawModelLister?.().catch(()=>null);T&&T.models.length>0&&(a=T.models,d=T.defaultModelId,u="disk")}let x=s?.getRuntimeCurrent(e.agentId),p;n.model&&!qt(n.model)?p=n.model:p=x?.model??d;let m=n.effort??x?.effort,b=n.fastMode??x?.fastMode,y=pd[i],v=f?.effortLevels??y.effort,I=f?.fastModes??y.fastMode,A={switchModel:!0,switchEffort:y.effort!==null,switchFastMode:y.fastMode!==null,...v?{supportedEffortLevels:[...v]}:{},...I?{supportedFastModes:[...I]}:{}};return{framework:i,models:a,...d?{defaultModelId:d}:{},...p?{currentModelId:p}:{},...A.switchEffort&&m?{currentEffort:m}:{},...A.switchFastMode&&b?{currentFastMode:b}:{},source:u,capabilities:A}}async detail(e){let n=e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST",`${nt.DETAIL}: missing cozeAgentId`);let i=await me(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=this.opts.modelListCache?.getRuntimeCurrent(n),a=i.effort??s?.effort,d=i.fastMode??s?.fastMode;return{agentId:n,agentName:i.agentName??"",cozeIdentity:i.cozeIdentity??"",framework:i.framework,...i.description!==void 0?{description:i.description}:{},...i.model?{model:i.model}:{},...a?{effort:a}:{},...d?{fastMode:d}:{}}}async resetAgent(e){if(Ji(e._meta,nt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${nt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,nt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>Y.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,nt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),Y.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let a of i.sessions.values())a.acpSessionId=void 0,a.replySeq=0,a.loadingSession=!1,a.spawnFailCount=void 0,a.spawnFailedAt=void 0;let s=new Map;for(let[a,d]of i.sessions)s.set(a,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await bi(e,s)}async clearPersistedAcpSessionIds(e){let n=await me(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let s of Object.values(n.sessions))s.acpSessionId&&(s.acpSessionId=void 0,i=!0);i&&await Ne(n)}async repairAgent(e){if(Ji(e._meta,nt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${nt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${nt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){Y.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,nt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){Y.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){Y.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(s)})}}async getFileTree(e){Ji(e._meta,"_agent/getFileTree");let n=e._meta,i=rr(n),s=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(s,a),u=await Id(d).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${a}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await _i(d,s))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=eE(e.depth);return u.isDirectory()?{tree:await Qb(s,d,a,f)}:{tree:[{name:tE(a),path:fh(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Ji(e._meta,"_agent/getFileContent");let n=rr(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(i,e.filePath),a=await Id(s).catch(()=>null);if(!a||!a.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await _i(s,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>Y0)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${Y0})`);let d=await Oo(s);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:a.size}:{content:d.toString("utf8"),encoding:"utf-8",size:a.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await me(e).catch(()=>null))?.workspace??Le(e).workspace}safeJoin(e,n){let i=Cd(e,n||"."),s=Dd(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${eh}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return me(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function rh(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 Wr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:he(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:he(".agents","skills")};case"hermes":return{base:or(e,i??Z()),subdir:"skills"}}}function ih(t){let e=Ab();if(t==="claude-code")return[he(e,".claude","skills")];if(t==="codex")return[he(e,".agents","skills"),he(e,".codex","skills")];if(t==="openclaw")return[he(e,".agents","skills"),he(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||he(e,"AppData","Local");return[he(n,"hermes","skills"),he(e,".hermes","skills")]}return[he(e,".hermes","skills")]}return[]}async function Fb(t,e,n,i,s,a){let d=async u=>Rd(he(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!s){let{base:u,subdir:f}=Wr(n,t,e,a),x=he(f,i),p=he(u,x);return await d(p)?{absDir:p,relPath:x}:null}for(let u of ih(n)){let f=he(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function zb(t,e,n,i,s,a){let d=rh(i),u=await Fb(t,e,n,d,s,a);if(u)return{...u,dirName:d};let x=(s?await dh(t,n):await ch(t,e,n,a)).filter(b=>b.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${s?"global":"workspace"}: ${x.map(b=>J0(b.relPath)).join(", ")} \u2014 rename or remove duplicates`);let p=x[0];return p?{absDir:s?p.relPath:he(e,p.relPath),relPath:p.relPath,dirName:J0(p.relPath)}:null}function sh(t,e){return(Ib("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function oh(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
+ ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let s of n.split(`
102
+ `)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(s);if(!a||!a[2])continue;let d=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function ah(t,e,n,i){let s=await Q0(e,{withFileTypes:!0}).catch(()=>null);if(!s)return[];let a=[];for(let d of s){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await Rd(he(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,x=he(n,f),p=he(e,f,"SKILL.md"),m=await Oo(p,{encoding:"utf8"}).catch(()=>null);if(m===null)continue;let b=oh(m);a.push({relPath:x,skill:{skillId:sh(t,x),skillName:b.name||f,...b.description?{description:b.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function ch(t,e,n,i){let{base:s,subdir:a}=Wr(n,t,e,i);return ah(t,he(s,a),a,!1)}async function dh(t,e){let n=[],i=new Set;for(let s of ih(e)){let a=await ah(t,s,s,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var Ub=3e4,Hb=50*1024*1024,X0=10*1024*1024,Kr=3e4;async function No(t){let{agentId:e,workspace:n,framework:i,skill:s,paths:a}=t;if(!s.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let d=typeof s.content=="string"&&s.content.length>0,u=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!d&&!u)throw new k("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let f=rh(s.skillName),{base:x,subdir:p}=Wr(i,e,n,a),m=he(p,f),b=he(x,m);if(await Ad(b,{recursive:!0}),d){let v=Buffer.from(s.content,"utf8");ns(v.length),await Td(he(b,"SKILL.md"),v,"utf8")}else{let v=await jb(s.downloadUrl);Wb(v)?await Jb(v,b):$b(v)?await Vb(v,b):await Td(he(b,"SKILL.md"),v.toString("utf8"),"utf8")}let y={skillId:s.skillId,skillName:s.skillName,relPath:m,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return Y.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:m,source:d?"content":"downloadUrl"}),y}function Mo(t,e,n){let i=e.get(n.skillId);if(i!==void 0){t[i]=n;return}e.set(n.skillId,t.length),t.push(n)}function Gb(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 qb(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 lh(t,e){let n=await me(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Gt,s=n.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return n.skillsRefreshedForVersion=i,await Ne(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((m,b)=>[m.skillId,b])),u=a.filter(m=>m.builtin===!0&&!!m.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Ne(n,e),{status:"noop",count:0};let f=0,x=0,{base:p}=Wr(n.framework,t,n.workspace,e);Y.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:s,current:i,skillBase:p,builtinCount:u.length,builtinRelPaths:u.map(m=>m.relPath)});for(let m of u)try{let b=he(p,m.relPath);Y.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:m.skillId,relPath:m.relPath,rmTarget:b}),await kd(b,{recursive:!0,force:!0});let y=await No({agentId:t,workspace:n.workspace,framework:n.framework,skill:qb(m),...e?{paths:e}:{}});Mo(a,d,y),f+=1}catch(b){x+=1,Y.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:m.skillId,skillName:m.skillName,err:String(b)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await Ne(n,e),Y.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function jb(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);ns(e);let n=Kb(t);return ns(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Oo(e);return ns(n.length),n}if(Yi(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Ub);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 s=await i.arrayBuffer();return ns(s.byteLength),Buffer.from(s)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function ns(t){if(t>Hb)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Kb(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],i=e[3]??"";return n?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function Wb(t){return t.length>=2&&t[0]===31&&t[1]===139}function $b(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],n=t[3];return e===3&&n===4||e===5&&n===6}function Pd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Vb(t,e){let n,i;try{n=new Od.default(t),i=n.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||Pd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let s=Zb(i),a=Cd(e);for(let d of i){if(Pd(d.entryName))continue;let u=d.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let f=Cd(e,u),x=Dd(a,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Ad(f,{recursive:!0});continue}await Ad(kb(f),{recursive:!0});let p;try{p=d.getData()}catch(m){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${m.message}`,{cause:m})}await Td(f,p)}}function Zb(t){let e;for(let n of t){let i=n.entryName;if(!i||Pd(i))continue;let s=i.indexOf("/");if(s<=0)return;let a=i.slice(0,s+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function Jb(t,e){await Yb(t);let n=c0({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Kr}ms)`))},Kr);try{await nh(th.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Kr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}}async function Yb(t){let e=[],n=Hr({onReadEntry:a=>{let d=a.path,u=a.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Kr}ms)`))},Kr);try{await nh(th.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Kr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Xb=5e3;async function Qb(t,e,n,i){return uh(t,e,n,i,{count:0})}async function uh(t,e,n,i,s){if(i<=0)return[];let a;try{a=await Q0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if(Rb.has(u.name)||u.isSymbolicLink())continue;if(s.count>=Xb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=he(e,u.name),x=Tb(he(n,u.name)),p=null;try{p=await Id(f)}catch{continue}if(p.isSymbolicLink())continue;s.count++;let m={name:u.name,path:fh(Dd(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(m.children=await uh(t,f,x,i-1,s)),d.push(m)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function eE(t){return!t||t<=0?Cb:Math.min(t,Pb)}function tE(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function fh(t){return t.split(eh).join("/")}re();var Ln=H("agent-health-reporter"),nE=1e4,rE=3,rs=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??nE,this.livenessFailureThreshold=e.livenessFailureThreshold??rE}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()}),Ln.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Ln.info("heartbeat stopped"))}async tick(){if(this.inFlight){Ln.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Ln.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=iE(d);if(!u)continue;let f={agentId:d.agentId,status:u};d.patToken&&(f.patToken=d.patToken),d.accountId&&(f.accountId=d.accountId),n.push(f)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Gt,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Ln.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=s?.authFailures;if(a&&a.length>0&&(Ln.warn("heartbeat received authFailures from cloud",{count:a.length,agentIds:a.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(a)}catch(d){Ln.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Ln.warn("onTickEnd hook failed",{err:String(n)})}}};function iE(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Qt();import{copyFile as bv,cp as Ev,mkdir as Vo,readFile as vv,rm as Sv,stat as Hd,writeFile as Iv}from"node:fs/promises";import{homedir as Yh}from"node:os";import{basename as Av,join as ln}from"node:path";_n();import{existsSync as pE}from"node:fs";import{release as gE}from"node:os";import{basename as mE,isAbsolute as wE}from"node:path";function is(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function $r(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Vr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Nn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Je();var Bo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},X={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function hh(t){return"method"in t&&"id"in t&&t.id!==void 0}function xh(t){return"method"in t&&!("id"in t)}function Fo(t){return!("method"in t)&&"id"in t}var sE={AGENT_NOT_FOUND:X.AGENT_NOT_FOUND,AGENT_BUSY:X.AGENT_BUSY,AGENT_DISCONNECTED:X.AGENT_DISCONNECTED,AGENT_TIMEOUT:X.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:X.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:X.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:X.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:X.INTERNAL_ERROR,BRIDGE_INTERNAL:X.INTERNAL_ERROR,IPC_AUTH_FAILED:X.INTERNAL_ERROR,IPC_BAD_REQUEST:X.INVALID_REQUEST,METHOD_NOT_FOUND:X.METHOD_NOT_FOUND,CAPABILITY_UNSUPPORTED:X.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:X.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:X.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:X.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:X.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:X.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:X.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:X.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:X.FILE_TOO_LARGE,UNSUPPORTED_MIME:X.UNSUPPORTED_MIME,UPLOAD_FAILED:X.UPLOAD_FAILED,UPSTREAM_NOT_READY:X.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:X.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:X.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:X.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:X.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:X.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:X.SKILL_ZIP_TOO_LARGE};function oE(t){if(t!=null)return t instanceof Error?{name:t.name,message:ss(t.message)}:typeof t=="string"?ss(t):typeof t=="object"?cE(t):t}var aE=[[/\/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 ss(t){let e=t;for(let[n,i]of aE)e=e.replace(n,i);return e}function cE(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=ss(i):e[n]=i;return e}function os(t){if(t instanceof k){let e=oE(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(n.reason=e.reason),{code:sE[t.code]??X.INTERNAL_ERROR,message:ss(t.message),data:n}}return{code:X.INTERNAL_ERROR,message:ss(t instanceof Error?t.message:String(t))}}function ph(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,s=i?e?.message:t.message,a=t.data;if(i&&e){let{message:d,...u}=e;a=u}return new k(n,s,{retriable:e?.retriable??!1,cause:a})}function mh(t){return`${JSON.stringify(t)}
103
+ `}var gh=10*1024*1024,zo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>gh){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${gh} bytes`)}),[]}let n=this.buffer.split(`
104
+ `);this.buffer=n.pop()??"";let i=[];for(let s of n){let a=s.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(d){this.onError?.({line:a,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var yh={"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"},pP=Object.fromEntries(Object.entries(yh).map(([t,e])=>[e,t])),dE={"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:[]},Zr=class{seq=0;next(e,n){this.seq+=1;let i=yh[e]??lE(e),s=dE[i]??[],a=[i,String(this.seq)];if(s.length>0){let d=s.map(f=>wh(n?.[f]??"")),u=uE(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>wh(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function lE(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function wh(t){return t.replace(/[:_\s]+/g,"-")}function uE(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}an();_r();Je();re();Pe();import{execFileSync as fE,spawnSync as hE}from"node:child_process";function as(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function cs(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),hE("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Ld=new Set;function _h(t){typeof t=="number"&&t>0&&Ld.add(t)}function bh(t){typeof t=="number"&&Ld.delete(t)}function Eh(){for(let t of Ld)cs(t,"SIGKILL")}var Jr="coze-bridge-daemon";function vh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return fE("pgrep",["-U",String(s),"-f",Jr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
105
+ `).map(s=>Number.parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0&&s!==i)}async function Sh(t,e){if(t.length===0)return;let n=e?.killFn??cs,i=e?.isAliveFn??as,s=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)n(u,"SIGTERM");for(let u=0;u<a&&t.some(f=>i(f));u+=d)await s(Math.min(d,a-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var xE=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/import\.meta\.resolve is not a function|\.resolve is not a function/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (codex ACP \u9700\u8981 import.meta.resolve)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20 \u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @zed-industries\/codex-acp|optional dependency was not installed/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find (module|package)[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|openai[\\/]codex|zed-industries[\\/]codex-acp)|Cannot find package ['"]@openai[\\/]codex['"][\s\S]*node_modules[\\/]@agentclientprotocol[\\/]codex-acp/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"hermes_provider_not_configured",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["hermes"],match:/(no.*openai.*provider|OPENAI_API_KEY.*(not set|missing)|(provider|model).*(not configured|misconfigured)|hermes.*setup.*required)/i,message:"hermes provider/API key \u672A\u914D\u7F6E\u597D, \u8BF7\u68C0\u67E5 <HERMES_HOME>/config.yaml + .env \u540E\u91CD\u8BD5"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function Ih(t,e){if(!e)return null;for(let n of xE)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function Ah(t,e){return Ih(t,e)}function kh(t,e){return Ih(t,e)}function Yr(t,e,n){return!e&&n.firstUpdateMs>0&&t<n.firstUpdateMs?Math.max(1,n.firstUpdateMs-t):t<n.phase2GateMs?Math.max(1,n.phase2GateMs-t):Math.max(1,n.livenessWindowMs)}function Th(t,e,n){let s=n-t.armedAt-t.expectedIntervalMs;if(s>e.suspendThresholdMs){let x=t.suspendedMs+s,p=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:s,rearmMs:Yr(p,t.firstFrameSeen,e)}}let a=n-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return a>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?a<e.phase2GateMs?{action:"continue",rearmMs:Yr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Yr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Yr(a,!1,e)}}var Ch=Ze("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),yE=200,_E=40,bE=Ze("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),EE=Ze("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),vE=Ze("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),SE=Ze("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),IE=Ze("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),AE=Ze("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ph=500,kE=process.env.COZE_BRIDGE_TRACE_RPC==="1",Rh=Ze("COZE_BRIDGE_TRACE_RPC_MAX",2e3);function TE(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ph?t:`${e.slice(0,Ph)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function CE(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:n}=t;if(typeof n=="string")e.push(n);else if(n&&typeof n=="object")try{e.push(JSON.stringify(n))}catch{}return e.join(" ")}function Dh(t){try{return pE(t)}catch{return}}function PE(t,e){return{platform:process.platform,osRelease:gE(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:wE(e.command)?Dh(e.command):void 0,cwd:e.cwd,cwdExists:Dh(e.cwd),envKeys:e.envKeys}}function RE(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${mE(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var _t=class{constructor(e){this.opts=e;this.log=H(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new zo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Zr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=Co(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=ct(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,_h(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",s=>{try{for(let a of this.decoder.push(s))this.dispatch(a)}catch(a){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(a)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",s=>{let a=s.trimEnd();this.stderrRing.push(a),this.stderrRing.length>yE&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),i.stdin?.on("error",s=>{this.log.warn("child stdin error",{err:String(s)})}),i.stdout?.on("error",s=>{this.log.warn("child stdout error",{err:String(s)})}),i.stderr?.on("error",s=>{this.log.warn("child stderr error",{err:String(s)})}),i.on("exit",(s,a)=>{this.stopped=!0,bh(i.pid),(s!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:s,signal:a,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(s,a));for(let u of this.exitHandlers)u(s,a)}),i.on("error",s=>{let a=s,d=PE(a,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(s),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",RE(a,d),{cause:d}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let n=this.child,i=new Promise(a=>n.once("exit",()=>a()));cs(n.pid,"SIGTERM");let s=setTimeout(()=>{n.killed||cs(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:IE,phase2GateMs:bE,livenessWindowMs:EE,absoluteMaxMs:vE,approvalMaxMs:AE,suspendThresholdMs:SE,...n};return this.call("session/prompt",e,Ch,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame($r("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}configIdFor(e){return e==="model"?"model":null}sendSetConfigOption(e,n,i){return this.call("session/set_config_option",{sessionId:e,configId:n,value:i}).then(()=>{})}setConfigOption(e,n,i){let s=this.configIdFor(n);return s===null?Promise.reject(new k("CAPABILITY_UNSUPPORTED",`${this.framework} does not support axis '${n}'`)):this.sendSetConfigOption(e,s,i)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Vr(e,n))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Nn(e,n))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,n,i=Ch,s){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=is(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let f=n.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let p={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(s){let m=this.now(),b={cfg:s,startedAt:m,lastActivityAt:m,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:m,expectedIntervalMs:Yr(0,!1,s),sessionId:u};p.promptTimeout=b;let y=()=>{let v={startedAt:b.startedAt,lastActivityAt:b.lastActivityAt,firstFrameSeen:b.firstFrameSeen,hasActiveTool:b.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:b.suspendedMs,armedAt:b.armedAt,expectedIntervalMs:b.expectedIntervalMs},I=this.now(),A=Th(v,b.cfg,I),T=R=>{b.armedAt=I,b.expectedIntervalMs=R,p.timer=setTimeout(y,R)};if(A.action==="suspend"){b.suspendedMs+=A.suspendedDeltaMs,b.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:b.suspendedMs,...b.sessionId?{sessionId:b.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...b.sessionId?{sessionId:b.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${b.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${b.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...b.sessionId?{sessionId:b.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${b.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(y,b.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,p);try{this.writeFrame(d)}catch(m){p.timer&&clearTimeout(p.timer),this.pending.delete(a),x(m)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.traceFrame("->",e),this.child.stdin.write(mh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}traceFrame(e,n){if(!kE)return;let i=n,s;try{let a=JSON.stringify(n);s=a===void 0||a.length<=Rh?n:`${a.slice(0,Rh)}...<truncated, total ${a.length} chars>`}catch{s="<unserializable>"}this.log.info(`rpc ${e}`,{dir:e,method:i.method,id:i.id,frame:s})}dispatch(e){if(this.traceFrame("<-",e),Fo(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new k("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:TE(e.result)}),n.resolve(e.result));return}if(xh(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let s=i.promptTimeout;s&&(s.firstFrameSeen=!0,s.lastActivityAt=this.now(),this.trackToolCall(s,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(s=>this.log.warn("update handler failed (async)",{err:String(s)}))}catch(s){this.log.warn("update handler threw sync, swallowed",{err:String(s)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(hh(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,s=i?.sessionUpdate;if(s!=="tool_call"&&s!=="tool_call_update")return;let a=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!a)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";s==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Nn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let n of this.agentRequestHandlers)try{await n(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(Nn(e.id,os(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=ph(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=kh(this.framework,CE(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):n}buildExitError(e,n){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(_E).join(`
106
+ `),s=Ah(this.framework,i);return s?new k(s.bridgeCode,s.message,{cause:{reason:s.reason,code:e,signal:n,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function DE(t){let e={};for(let[n,i]of Object.entries(t))i!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=i));return e}var Uo=class extends _t{framework="claude-code";constructor(e){let{command:n,args:i}=yi("claude-code",e.command,e.args??[]),s={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return DE(e)}configIdFor(e){return e==="model"?"model":e==="effort"?"effort":null}};_n();import{spawn as OE}from"node:child_process";import{closeSync as LE,existsSync as Bd,mkdirSync as NE,mkdtempSync as ME,openSync as BE,readFileSync as zh,readSync as FE,readdirSync as zE,rmSync as UE,statSync as HE}from"node:fs";import{homedir as GE,tmpdir as qE}from"node:os";import{join as Xr}from"node:path";var Oh=["default","acceptEdits","plan","auto","bypassPermissions"],Lh=["read-only","auto","full-access"];var Nh=["default","accept_edits","dont_ask"];function Kt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Oh.includes(e);case"codex":return Lh.includes(e);case"hermes":return Nh.includes(e);case"openclaw":return!1}}function Ho(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Mh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Nd(t){switch(t){case"claude-code":return Oh.join("/");case"codex":return Lh.join("/");case"hermes":return Nh.join("/");case"openclaw":return""}}Pe();var Fd=9e4,jE=64*1024,KE=100;function WE(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Fd:Math.max(1,Math.floor(e*1e3))}function $E(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?Fd:Math.max(1,Math.floor(e))}function VE(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return Object.keys(e).length>0?e:void 0}function Bh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:Fd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let n=typeof e.command=="string"?e.command.trim():"";if(!n)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,s=VE(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?WE(e.timeout):$E(e.timeout_ms),...i?{cwd:i}:{},...s?{env:s}:{}}}function Md(t){if(Array.isArray(t))return t.flatMap(i=>Md(i));if(!t||typeof t!="object"){let i=Bh(t);return i?[i]:[]}let e=t;if(e.hooks)return Md(e.hooks);let n=Bh(e);return n?[n]:[]}function ZE(t){let e=Xr(t,"hooks.json");if(!Bd(e))return[];let n=JSON.parse(zh(e,"utf8")),s=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return Md(s.Stop??s.stop)}function JE(t,e){let n=Xr(t,"sessions");if(!Bd(n))return;let i=[],s=a=>{let d;try{d=zE(a,{withFileTypes:!0})}catch{return}for(let u of d){let f=Xr(a,u.name);if(u.isDirectory())s(f);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:f,mtimeMs:HE(f).mtimeMs})}catch{}}};s(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,KE))if(YE(a.path,e))return a.path}function YE(t,e){let n;try{n=BE(t,"r");let i=Buffer.alloc(jE),s=FE(n,i,0,i.length,0),a=i.subarray(0,s).toString("utf8");return a.includes(JSON.stringify(e))||a.includes(e)}catch{return!1}finally{if(n!==void 0)try{LE(n)}catch{}}}function XE(t){return ir(t??Z().agentEnvFile)}function QE(t){let e=t.trim();if(e.length>=2){let n=e[0];if((n==='"'||n==="'")&&e.endsWith(n)){let i=e.slice(1,-1);return n==='"'?i.replace(/\\n/g,`
107
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function ev(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.startsWith("export ")?i.slice(7).trimStart():i,a=s.indexOf("=");if(a<=0)continue;let d=s.slice(0,a).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=QE(s.slice(a+1)))}return e}function tv(t){let e=Xr(t,"cozeloop.env");return Bd(e)?ev(zh(e,"utf8")):{}}function Fh(t){let e=t?.trim();return e||void 0}function nv(t){let e=XE(t.agentEnvFile),n=Fh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=Fh(t.env?.HOME??e.HOME??process.env.HOME)??GE();return Xr(i,".codex")}var Go=class extends _t{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;fastMode;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:s,args:a}=yi("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??ME(Xr(qE(),"coze-bridge-codex-home-")):nv(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&NE(d,{recursive:!0});let f=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:s,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u,this.fastMode=e.fastMode}configIdFor(e){return e==="model"?"model":e==="effort"?"reasoning_effort":e==="fastMode"?"fast-mode":null}async afterSessionEstablished(e){if(this.fastMode)try{await this.setConfigOption(e,"fastMode",this.fastMode)}catch(n){this.log.warn("codex fast-mode post-establish failed (ignored)",{sessionId:e,err:String(n)})}}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=Kt("codex",e.modeId)?Ho(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(rv(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=ZE(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let s=JE(n,e),a=JSON.stringify({hook_event_name:"Stop",session_id:e,...s?{transcript_path:s}:{},trigger:"coze-bridge"});await Promise.all(i.map(async d=>{try{await this.runHookCommand(d,a)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:n,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,n){return new Promise((i,s)=>{let a=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=a?tv(a):{},u=Co(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let f=OE(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",p=setTimeout(()=>{f.kill("SIGTERM"),s(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);f.stderr?.setEncoding("utf8"),f.stderr?.on("data",m=>{x+=m,x.length>4e3&&(x=x.slice(-4e3))}),f.on("error",m=>{clearTimeout(p),s(m)}),f.on("close",(m,b)=>{if(clearTimeout(p),m===0){i();return}s(new Error(`hook exited code=${m} signal=${b} stderr=${x.slice(-1e3)}`))}),f.stdin.end(`${n}
108
+ `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{UE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function rv(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=Mh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}re();var iv=H("hermes-downstream"),qo=class extends _t{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setConfigOption(e,"model",this.modelId)}catch(n){iv.warn("hermes model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}setConfigOption(e,n,i){return n==="model"?this.setSessionModel({sessionId:e,modelId:i}).then(()=>{}):super.setConfigOption(e,n,i)}};Je();var Uh=3e4,Qr=class extends _t{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let s={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Uh))}get acpSessionName(){return this.sessionName}async setConfigOption(e,n,i){if(n!=="model")throw new k("CAPABILITY_UNSUPPORTED",`openclaw does not support axis '${n}'`);await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${i}`}]},Uh)}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Lt();Je();re();Pe();function zd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}_n();var Wt=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((n,i)=>{this.slots.push({task:e,resolve:n,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let n=await e.task();e.resolve(n)}catch(n){e.reject(n)}}}finally{this.running=!1}}}};var jo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;effort;fastMode;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),e.effort&&(this.effort=e.effort),e.fastMode&&(this.fastMode=e.fastMode)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}setEffort(e){this.effort=e}setFastMode(e){this.fastMode=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Wt,this.sessionQueues.set(e,n)),n}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let n=this.sessionQueues.get(e);return!!n&&!n.isDisposed}async dispose(e){this.status="stopped";let n=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(n);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let n=[];for(let[,i]of this.sessions)ei(i),i.downstream&&(n.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(n),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function ei(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function dn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}an();re();import{constants as Hh}from"node:fs";import{access as sv,readFile as ov}from"node:fs/promises";import{delimiter as av,dirname as cv,join as Gh}from"node:path";var rt=H("framework-detector"),qh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},dv=[".exe",".cmd",".bat",".ps1"],ar=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??ct,access:e.access??sv,readFile:e.readFile??ov}}async detect(e){let n=qh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return rt.debug("framework binary not found",{framework:e,bin:n}),null;let s=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,s),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(qh).map(async i=>[i,await this.detect(i)])),n={};for(let[i,s]of e)s&&(n[i]=s);return n}async which(e){let n=this.env.pathEnv.split(av).filter(Boolean),i=this.env.platform==="win32"?["",...dv]:[""];for(let s of n)for(let a of i){let d=Gh(s,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Hh.F_OK:Hh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(d){return rt.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let s=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!s)return rt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=Gh(cv(s),"hermes-acp");return await this.isExecutable(a)?(rt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(rt.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:a}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return rt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return rt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return rt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let s=JSON.parse(i[0]);if(!Array.isArray(s))return rt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=s.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(rt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(rt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return rt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(s),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return rt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||rt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let s={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(s.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(s.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(s.detail=d.rpc.error)}catch(d){rt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return s}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(uv(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let s="",a=!1,d,u=f=>{a||(a=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{s+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:s}))}catch{u(null)}})}},lv=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function uv(t){return t.replace(lv,"")}import{homedir as Kh}from"node:os";import{join as Wo}from"node:path";Lt();an();_r();Je();re();async function Wh(){let t=Wo(Kh(),".openclaw/openclaw.json");return gt(t)}async function $h(){return(await Wh())?.gateway?.auth?.token??""}var cr=H("openclaw.config"),fv=[0,5e3,5e3],hv=Ze("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),jh="models.providers.",Ko="agents.defaults.models",xv=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function ti(t,e){let n=Array.isArray(t)?[...t]:[],i=new Set(n);for(let s of e)i.has(s)||(i.add(s),n.push(s));return n}var $o=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Wt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??fv,this.cliTimeoutMs=e.cliTimeoutMs??hv,this.openclawDir=e.openclawDir??Wo(Kh(),".openclaw")}async withRetry(e,n){let i;for(let s=0;s<this.retryDelaysMs.length;s++){let a=this.retryDelaysMs[s]??0;a>0&&await new Promise(d=>setTimeout(d,a));try{return await n()}catch(d){i=d,cr.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let s=ct(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(f),x())};s.stderr?.on("data",x=>{a+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),s.on("error",x=>u(()=>i(x))),s.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let s=String(i);if(n.some(a=>s.includes(a)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){cr.warn(`${e} failed (best-effort)`,{configPath:n,err:String(i)})}}ensureProvider(e,n){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${jh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${jh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ko}[${e}]`,()=>this.runCli(["config","set",Ko,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ko}[${e}]`,`${Ko}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await Wh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let s=`${e}/`,a=[];for(let d of Object.keys(i))d.startsWith(s)&&a.push(d.slice(s.length));return a}ensureAgent(e,n,i){let s=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&s.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}ensureAcpDeviceScopes(){return this.queue.enqueue(()=>this.ensureAcpDeviceScopesUnlocked())}async ensureAcpDeviceScopesUnlocked(){try{let e=Wo(this.openclawDir,"identity","device.json"),i=(await gt(e))?.deviceId?.trim();if(!i)return cr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let s=Wo(this.openclawDir,"devices","paired.json"),a=await gt(s),d=a?.[i];if(!a||!d)return cr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,f=ti(ti(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(v=>v.startsWith("operator.")),x=ti([...xv],f),p=ti(d.scopes,x),m=ti(d.approvedScopes,x),b=u?ti(u.scopes,x):void 0;return p.length!==(d.scopes?.length??0)||m.length!==(d.approvedScopes?.length??0)||u!==void 0&&b?.length!==(u.scopes?.length??0)?(d.scopes=p,d.approvedScopes=m,u&&b&&(u.scopes=b),await Ot(s,a,{mode:384}),cr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(cr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return cr.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as pv,writeFile as gv}from"node:fs/promises";import{join as mv}from"node:path";var wv=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
109
+ `),yv=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
110
+ `);function _v(t){return t.length===0?t:`${(t.endsWith(`
111
111
  `)?t.slice(0,-1):t).split(`
112
- `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
112
+ `).map(s=>s.endsWith("\r")?s.slice(0,-1):s).join(`
113
113
  `)}
114
- `}async function vh(t){let e=OE(t,"HEARTBEAT.md"),n=await PE(e,"utf8");return ME(n)!==LE?!1:(await DE(e,NE),!0)}var ne=G("agent-manager"),qE=["hooks.json","cozeloop.env"],jE=["hooks"];async function WE(t,e){let n=zt(Re(t,e).root,"codex-home"),i=zt(Ah(),".codex");if(n!==i){await Ho(n,{recursive:!0});for(let o of jE){let a=zt(i,o),d=zt(n,o);try{await Dd(d);continue}catch{}try{await FE(a,d,{recursive:!0,errorOnExist:!0,filter:u=>{let f=GE(u);return!f.endsWith(".log")&&!f.includes(".bak")}}),ne.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ne.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of qE){let a=zt(i,o),d=zt(n,o);try{await Dd(d);continue}catch{}try{if(o==="cozeloop.env"){let f=(await zE(a,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
115
- `);await HE(d,f,{mode:384})}else await BE(a,d);ne.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&ne.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var Od="acceptEdits",kh="full-access",Th="read-only";function KE(t){return{INITIAL_AGENT_MODE:Lo(t)}}var $E=(t,e,n,i,o,a,d,u,f,x,p,m)=>{switch(t){case"claude-code":{let v={...o?{...m0(o),...y0(o,d,u,m)}:{},...f??{},IS_SANDBOX:"1"};return new Oo({cwd:n,env:v,agentId:i})}case"codex":{let v=kh;x!==void 0&&(Ft("codex",x)?v=x:ne.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _={...o?{..._0(o),...w0(o,d,u,m)}:{},...KE(v),...o?{NO_BROWSER:"1"}:{},...f??{},...o?{COZELAB_ONBOARD_CLOUD:"true"}:{}},b=!!o;return new No({cwd:n,agentId:i,...Object.keys(_).length>0?{env:_}:{},...b?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new Wr({command:e,cwd:n,agentId:i,...a?{sessionName:Rd(a)}:{}});case"hermes":return new Mo({command:e,cwd:n,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model?{modelId:o.model}:{}})}};function Pd(t){return t==="claude-code"||t==="codex"}var VE={path:"",version:"cloud-deployed"},Sh="openclaw_gateway_unavailable",ZE="openclaw_default_agent_missing";function Ih(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var JE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},YE=6e4,Go=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Map;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??$E,this.createTimeoutMs=e.createTimeoutMs??YE,this.detectorFactory=e.detectorFactory??(()=>new er),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Uo({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??zt(Ah(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}async buildAgentToolEnv(e,n){let i=this.buildBinShimPathEnv();if(e.deployType!=="cloud")return i;let o=zt(Re(e.agentId,this.paths).root,"coze-cli-config.json");return await ct(o,`${JSON.stringify({xTTEnv:n??""},null,2)}
116
- `,{mode:384}),i.COZE_CONFIG_FILE=o,i}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{ne.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=zt(e,".env");if(await Dd(n).then(a=>a.isFile()).catch(()=>!1)){ne.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=qi({...process.env,...Yn(this.paths.agentEnvFile)});await ct(n,o,{mode:384}),ne.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),ne.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new A("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new A("IPC_BAD_REQUEST","framework required");let i=await Ie(e.agentId,this.paths).catch(()=>null),o=yo(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new A("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")ne.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>ne.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")ne.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>ne.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){ne.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await Ie(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await qe(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){ne.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await Ie(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await qe(T,this.paths))}return ne.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework]){let R=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${R}`)}let u=Re(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??m??u.workspace,_=new AbortController,b=setTimeout(()=>_.abort(new A("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),S,I=!1;try{o&&Pd(e.framework)&&await gr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new A("AGENT_TIMEOUT","_agent/create aborted")};await Ho(u.root,{recursive:!0}),await Ho(v,{recursive:!0}),await Ho(u.logs,{recursive:!0}),T(),x||await mr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Ya(v,"cloud"):await Ya(v,"local",Od)),T();let R=i,E=p0({model:e.model??R?.model}),P=t0(e._meta)??R?.accountId,D=e.patToken??R?.patToken,M=f==="cloud"?e.modelInfo??R?.modelInfo:void 0;if(S=new Bo({agentId:e.agentId,framework:e.framework,workspace:v,model:E.model??kt,deployType:f,...P?{accountId:P}:{},...D?{patToken:D}:{},...M?{modelInfo:M}:{}}),S.status="ok",R?.sessions){let V=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,re]of Object.entries(R.sessions)){let ae={acpSessionId:re.acpSessionId,modelToken:re.modelToken,tokenGeneratedAt:re.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?re.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ne.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:ae.permissionMode})):Ft(e.framework,re.permissionMode)?ae.permissionMode=re.permissionMode:ne.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:re.permissionMode}):re.permissionMode!==void 0&&ne.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:f}),re.cozeGroupId&&(ae.cozeGroupId=re.cozeGroupId),re.tokenGroupId&&(ae.tokenGroupId=re.tokenGroupId),re.requestScene&&(ae.requestScene=re.requestScene),S.sessions.set(X,ae)}let se=Object.keys(R.sessions).length;se>0&&ne.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:se})}this.registry.register(S),I=!0;let N={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:R?.createdAt??Date.now(),sessions:R?.sessions??{},model:E.model};if(f==="cloud"&&(N.deployType="cloud"),P&&(N.accountId=P),D&&(N.patToken=D),M&&(N.modelInfo=M),R?.skills&&(N.skills=R.skills),R?.agentName&&(N.agentName=R.agentName),R?.description&&(N.description=R.description),N.skillsRefreshedForVersion=R?.skillsRefreshedForVersion??Bt,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):ne.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await vh(v)&&ne.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:v})}catch(V){ne.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:v,err:String(V)})}}let J=e.initialSkills??[];if(J.length>0){let V=[...N.skills??[]],se=new Map(V.map((ae,C)=>[ae.skillId,C])),X=await Promise.allSettled(J.map(ae=>To({agentId:e.agentId,workspace:v,framework:e.framework,skill:ae,paths:this.paths}))),re=0;for(let[ae,C]of X.entries()){let z=J[ae];z&&(C.status==="fulfilled"?(Co(V,se,C.value),re++):ne.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:z.skillId,skillName:z.skillName,err:String(C.reason)}))}re>0&&(N.skills=V,ne.info("initialSkills installed",{agentId:e.agentId,installed:re,requested:J.length}))}return await qe(N,this.paths),ne.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(T){throw ne.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),I&&S&&(await S.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ne.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await UE(u.root,{recursive:!0,force:!0}).catch(R=>ne.warn("rm agent dir failed (ignored)",{err:String(R)})),T instanceof A?T:new A("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(b)}}async spawnSessionDownstream(e,n,i,o,a,d){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&Pd(e.framework))f=VE;else throw e.framework==="hermes"?new A("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new A("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Pd(e.framework)&&!As(e.framework)&&(ne.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await gr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,p=await this.buildAgentToolEnv(e,o),m;if(e.framework==="openclaw")m=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:f.path});else if(e.framework==="hermes"){let v={...p};x&&(await A0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:a}),v.HERMES_HOME=Qn(e.agentId,this.paths)),m=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,o,a,v)}else{let v=e.sessions.get(i),_=tn(e)?v?.permissionMode??kh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await WE(e.agentId,this.paths),m=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,o,a,p,_,e.framework==="codex"&&e.deployType==="cloud"?zt(Re(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await m.start(),await m.initialize(JE),m}catch(v){let _=m instanceof mt?m.getStderrTail():[];throw _.length>0&&ne.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:v instanceof A?v.code:"unknown",recentStderr:_}),await m.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,f.path,v)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let o=await this.detectorFactory().probeOpenclawGateway(n);if(!o.reachable)return new A("AGENT_ENV_NOT_READY",Ih(o),{cause:{reason:Sh}})}catch(o){ne.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof A?i:new A("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};ne.warn("openclaw default agent stale or missing, attempting lazy re-detect");let n=await this.detectorFactory().detect("openclaw");if(n?.defaultAgent?.id&&n.defaultAgent.workspace)return ne.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.defaultAgent.workspace};throw new A("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:ZE}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new A("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new A("AGENT_ENV_NOT_READY",Ih(n),{cause:{reason:Sh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:u,command:f}=e,x=Rd(o);if(n.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Wr({command:f,cwd:v.workspace,agentId:v.id,sessionName:x})}let p=await Eh();try{let v=this.getOpenclawConfig();await v.ensureAcpDeviceScopes()&&await v.restartGateway()}catch(v){ne.warn("acp device scope ensure failed (ignored)",{err:String(v)})}let m;if(i?.modelToken){let v=ud(o),_=fd(i),b=`${v}/${_}`,S=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(b)!==S){let I=this.getOpenclawConfig(),T=await I.getAllowlistModelsForProvider(v),R=b0(i,a,d,T,u);R&&(await I.ensureProvider(v,R),await I.addModelToAllowlist(b),this.ensuredProviders.set(b,S))}m=b}return new Wr({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,o=n??e.model;for(let a of e.sessions.keys()){let d=ud(a),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(x){f=!1,ne.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,ne.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as Oh}from"node:crypto";import{promises as iv}from"node:fs";import{basename as Lh}from"node:path";Je();te();import{promises as XE}from"node:fs";import{basename as QE}from"node:path";var Ch=G("file-upload"),ev="/api/coze_claw/file/agent_upload",tv=6e4;async function Rh(t,e={}){let i=`${Nr(Mr(e.handshakeBase))}${ev}`,o=e.timeoutMs??tv,a=await XE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);Ch.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),m=p.headers.get("x-tt-logid")??"";if(!p.ok){let b=await p.text().catch(()=>"");throw new A("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${m}: ${b.slice(0,200)}`)}let v=await p.json();if(v.code!==void 0&&v.code!==0)throw new A("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${m}`);let _=v.data?.file?.file_url;if(!_)throw new A("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(v).slice(0,200)}`);return Ch.info("file upload ok",{uri:_,logid:m}),{uri:_}}catch(p){throw p instanceof A?p:p.name==="AbortError"?new A("UPLOAD_FAILED",`upload timeout (${o}ms) for ${QE(t.path)}`):new A("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Je();te();import{extname as nv}from"node:path";var rv={".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 Ph(t){let e=nv(t).toLowerCase();return rv[e]??"application/octet-stream"}Pe();var qo=G("agent-send"),Dh=50*1024*1024;function Nh(t,e,n){let i=t.get(e);if(!i)throw new A("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new A("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(n);if(!o)throw new A("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function Mh(t,e,n,i,o,a){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){u=x,f<2&&(qo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new A("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function Bh(t,e){let{session:n,runtime:i}=Nh(e.core,t.agentId,t.sessionId);if(!await fi(t.path,n.workspace))throw new A("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await iv.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new A("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>Dh)throw new A("FILE_TOO_LARGE",`${o.size} bytes > limit ${Dh}`);let a=await Ph(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new A("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??Lh(t.path),u;try{u=await Rh({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:d,sizeBytes:o.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw qo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:x instanceof A?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:Oh(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Mh(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),qo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Fh(t,e){let{session:n,runtime:i}=Nh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new A("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new A("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??Lh(t.path),a={sessionUpdate:"group_file",messageId:Oh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Mh(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),qo.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 zh(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(n.length,i.length);for(let a=0;a<o;a++){let d=n[a]??0,u=i[a]??0;if(d<u)return!0;if(d>u)return!1}return!1}en();te();fn();var Ut=G("coze-cli-installer"),Uh="@coze/cli@latest",sv="coze",Hh="0.1.8",ov=5e3,av=5e3,cv=9e4,Gh=1e4,es=null,jo=!1;async function Nd(t,e={}){if(jo)return;if(es)return es;let n=e.exec??a0;return es=(async()=>{try{let i=await dv(sv,n),o=!1;if(i){let d=await lv(n);if(d===void 0)Ut.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(zh(d,Hh))Ut.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:Hh}),o=!0;else{Ut.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),jo=!0;return}}let a=o?"upgrade-only":"full";Ut.info("coze-cli install start",{package:Uh,mode:a});try{await n("npm",["i","-g","--prefer-online",Uh],{timeout:cv,maxBuffer:10*1024*1024}),Ut.info("coze-cli install ok")}catch(d){Ut.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){jo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:Gh}),Ut.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Ut.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:Gh}),Ut.info("coze auth login ok")}catch(d){Ut.warn("coze auth login failed",{err:String(d)});return}jo=!0}finally{es=null}})(),es}async function dv(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:ov});return Za(i)}catch{return}}async function lv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:av});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}$t();Kt();Pe();var uv=10*6e4;function qh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?uv:e}function Wo(t){return hn(t??Z().configFile)}function ts(t,e){return xn(e??Z().configFile,t)}import{randomBytes as Pv}from"node:crypto";fr();Je();te();import{createReadStream as fv}from"node:fs";import{mkdir as hv,readFile as xv,realpath as pv,stat as gv,writeFile as mv}from"node:fs/promises";import{basename as wv,dirname as Md,isAbsolute as _v,join as yv,relative as bv,resolve as jh,sep as Ev}from"node:path";import{createInterface as vv}from"node:readline";var Kh=G("fs-rpc"),ns=Xe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function $h(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>ns)throw new A("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${ns} bytes`);let i=await Zh(t.path,e);return await hv(Md(i),{recursive:!0}),await mv(i,t.content,"utf8"),Kh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Vh(t,e){let n=await Zh(t.path,e),i=await gv(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>ns&&!o)throw new A("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${ns} bytes`);let a;if(o&&i.size>ns)a=await Sv(n,t.line??1,t.limit);else{let d=await xv(n,"utf8");if(o){let u=d.split(`
114
+ `}async function Vh(t){let e=mv(t,"HEARTBEAT.md"),n=await pv(e,"utf8");return _v(n)!==wv?!1:(await gv(e,yv),!0)}var ie=H("agent-manager"),kv=["hooks.json","cozeloop.env"],Tv=["hooks"];async function Cv(t,e){let n=ln(Le(t,e).root,"codex-home"),i=ln(Yh(),".codex");if(n!==i){await Vo(n,{recursive:!0});for(let s of Tv){let a=ln(i,s),d=ln(n,s);try{await Hd(d);continue}catch{}try{await Ev(a,d,{recursive:!0,errorOnExist:!0,filter:u=>{let f=Av(u);return!f.endsWith(".log")&&!f.includes(".bak")}}),ie.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&ie.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}for(let s of kv){let a=ln(i,s),d=ln(n,s);try{await Hd(d);continue}catch{}try{if(s==="cozeloop.env"){let f=(await vv(a,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
115
+ `);await Iv(d,f,{mode:384})}else await bv(a,d);ie.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&ie.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}}}var Gd="acceptEdits",Xh="full-access",Qh="read-only";function Pv(t){return{INITIAL_AGENT_MODE:Ho(t)}}var Rv=(t,e,n,i,s,a,d,u,f,x,p,m)=>{switch(t){case"claude-code":{let b={...s?{...L0(s),...B0(s,d,u,m)}:{},...f??{},IS_SANDBOX:"1"};return new Uo({cwd:n,env:b,agentId:i})}case"codex":{let b=Xh;x!==void 0&&(Kt("codex",x)?b=x:ie.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let y=!!s?.modelToken,v={...s?{...M0(s),...N0(s,d,u,m)}:{},...Pv(b),...y?{NO_BROWSER:"1"}:{},...f??{},...y?{COZELAB_ONBOARD_CLOUD:"true"}:{}};return new Go({cwd:n,agentId:i,...Object.keys(v).length>0?{env:v}:{},...s?.fastMode?{fastMode:s.fastMode}:{},...y?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new Qr({command:e,cwd:n,agentId:i,...a?{sessionName:zd(a)}:{}});case"hermes":return new qo({command:e,cwd:n,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...s?.model&&!qt(s.model)?{modelId:s.model}:{}})}};function Ud(t){return t==="claude-code"||t==="codex"}var Dv={path:"",version:"cloud-deployed"},Zh="openclaw_gateway_unavailable",Ov="openclaw_default_agent_missing";function Jh(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 Lv={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Nv=6e4,Zo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Map;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Rv,this.createTimeoutMs=e.createTimeoutMs??Nv,this.detectorFactory=e.detectorFactory??(()=>new ar),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new $o({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??ln(Yh(),".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=>{ie.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=ln(e,".env");if(await Hd(n).then(a=>a.isFile()).catch(()=>!1)){ie.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let s=Xi({...process.env,...ir(this.paths.agentEnvFile)});await mt(n,s,{mode:384}),ie.info("openclaw .env bootstrapped",{envFile:n,bytes:s.length}),await this.getOpenclawConfig().restartGateway(),ie.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,n){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await me(e.agentId,this.paths).catch(()=>null),s=nr(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")ie.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>ie.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(s&&a.deployType!=="cloud")ie.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>ie.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){ie.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await me(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Ne(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){ie.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await me(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Ne(T,this.paths))}return ie.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!s&&!this.config.frameworksCache?.[e.framework]){let R=e.framework==="hermes"?"; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache":"; rerun daemon to refresh frameworks_cache";throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${R}`)}let u=Le(e.agentId,this.paths),f=s?"cloud":"local",x=e.framework==="openclaw"&&f==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let m=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),b=e.workspace??m??u.workspace,y=new AbortController,v=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{s&&Ud(e.framework)&&await Sr(e.framework,y.signal);let T=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await Vo(u.root,{recursive:!0}),await Vo(b,{recursive:!0}),await Vo(u.logs,{recursive:!0}),T(),x||await Ir(b,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await ic(b,"cloud"):await ic(b,"local",Gd)),T();let R=i,E=O0({model:e.model??R?.model}),P=l0(e._meta)??R?.accountId,D=e.patToken??R?.patToken,z=f==="cloud"?e.modelInfo??R?.modelInfo:void 0;if(I=new jo({agentId:e.agentId,framework:e.framework,workspace:b,model:E.model??Ct,deployType:f,...P?{accountId:P}:{},...D?{patToken:D}:{},...z?{modelInfo:z}:{}}),I.status="ok",R?.sessions){let $=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Q,ce]of Object.entries(R.sessions)){let ae={acpSessionId:ce.acpSessionId,modelToken:ce.modelToken,tokenGeneratedAt:ce.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};$?ce.permissionMode===void 0?(ae.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",ie.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Q,framework:e.framework,fallback:ae.permissionMode})):Kt(e.framework,ce.permissionMode)?ae.permissionMode=ce.permissionMode:ie.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Q,framework:e.framework,value:ce.permissionMode}):ce.permissionMode!==void 0&&ie.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Q,framework:e.framework,deployType:f}),ce.cozeGroupId&&(ae.cozeGroupId=ce.cozeGroupId),ce.tokenGroupId&&(ae.tokenGroupId=ce.tokenGroupId),ce.requestScene&&(ae.requestScene=ce.requestScene),I.sessions.set(Q,ae)}let se=Object.keys(R.sessions).length;se>0&&ie.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:se})}this.registry.register(I),A=!0;let N={agentId:e.agentId,framework:e.framework,workspace:b,cozeIdentity:e.cozeIdentity,createdAt:R?.createdAt??Date.now(),sessions:R?.sessions??{},model:E.model};if(f==="cloud"&&(N.deployType="cloud"),P&&(N.accountId=P),D&&(N.patToken=D),z&&(N.modelInfo=z),R?.skills&&(N.skills=R.skills),R?.agentName&&(N.agentName=R.agentName),R?.description&&(N.description=R.description),N.skillsRefreshedForVersion=R?.skillsRefreshedForVersion??Gt,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,b)):ie.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Vh(b)&&ie.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:b})}catch($){ie.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:b,err:String($)})}}let V=e.initialSkills??[];if(V.length>0){let $=[...N.skills??[]],se=new Map($.map((ae,Se)=>[ae.skillId,Se])),Q=await Promise.allSettled(V.map(ae=>No({agentId:e.agentId,workspace:b,framework:e.framework,skill:ae,paths:this.paths}))),ce=0;for(let[ae,Se]of Q.entries()){let C=V[ae];C&&(Se.status==="fulfilled"?(Mo($,se,Se.value),ce++):ie.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:C.skillId,skillName:C.skillName,err:String(Se.reason)}))}ce>0&&(N.skills=$,ie.info("initialSkills installed",{agentId:e.agentId,installed:ce,requested:V.length}))}return await Ne(N,this.paths),ie.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:b,framework:e.framework}}catch(T){throw ie.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),ie.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await Sv(u.root,{recursive:!0,force:!0}).catch(R=>ie.warn("rm agent dir failed (ignored)",{err:String(R)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,s,a,d){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&Ud(e.framework))f=Dv;else throw e.framework==="hermes"?new k("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Ud(e.framework)&&!Os(e.framework)&&(ie.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await Sr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:D0({model:e.model,effort:e.effort,fastMode:e.fastMode}),p;if(e.framework==="openclaw")p=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:s,mockScenario:a,requestScene:d,command:f.path});else if(e.framework==="hermes"){let m={...this.buildBinShimPathEnv()};x?.modelToken&&(await q0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:s,mockScenario:a}),m.HERMES_HOME=or(e.agentId,this.paths)),p=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,s,a,m)}else{let m=e.sessions.get(i),b=dn(e)?m?.permissionMode??Xh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await Cv(e.agentId,this.paths),p=this.factory(e.framework,f.path,e.workspace,e.agentId,x,i,s,a,this.buildBinShimPathEnv(),b,e.framework==="codex"&&e.deployType==="cloud"?ln(Le(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await p.start(),await p.initialize(Lv),p}catch(m){let b=p instanceof _t?p.getStderrTail():[];throw b.length>0&&ie.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:m instanceof k?m.code:"unknown",recentStderr:b}),await p.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,f.path,m)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let s=await this.detectorFactory().probeOpenclawGateway(n);if(!s.reachable)return new k("AGENT_ENV_NOT_READY",Jh(s),{cause:{reason:Zh}})}catch(s){ie.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(s)})}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};ie.warn("openclaw default agent stale or missing, attempting lazy re-detect");let n=await this.detectorFactory().detect("openclaw");if(n?.defaultAgent?.id&&n.defaultAgent.workspace)return ie.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:Ov}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new k("AGENT_ENV_NOT_READY",Jh(n),{cause:{reason:Zh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:s,cozeEnv:a,mockScenario:d,requestScene:u,command:f}=e,x=zd(s);if(n.deployType==="local"){let b=await this.ensureOpenclawDefaultAgent(),y=i&&!qt(i.model)?i.model:void 0;return new Qr({command:f,cwd:b.workspace,agentId:b.id,sessionName:x,...y?{slashModelOnStart:y}:{}})}let p=await $h();try{let b=this.getOpenclawConfig();await b.ensureAcpDeviceScopes()&&await b.restartGateway()}catch(b){ie.warn("acp device scope ensure failed (ignored)",{err:String(b)})}let m;if(i?.modelToken){let b=_d(s),y=bd(i),v=`${b}/${y}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(v)!==I){let A=this.getOpenclawConfig(),T=await A.getAllowlistModelsForProvider(b),R=F0(i,a,d,T,u);R&&(await A.ensureProvider(b,R),await A.addModelToAllowlist(v),this.ensuredProviders.set(v,I))}m=v}else i&&!qt(i.model)&&(m=i.model);return new Qr({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...m?{slashModelOnStart:m}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,s=n??e.model;for(let a of e.sessions.keys()){let d=_d(a),u=`${d}/${s}`,f=!0;try{await i.removeProvider(d)}catch(x){f=!1,ie.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){f=!1,ie.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as ix}from"node:crypto";import{promises as Gv}from"node:fs";import{basename as sx}from"node:path";Je();re();import{promises as Mv}from"node:fs";import{basename as Bv}from"node:path";var ex=H("file-upload"),Fv="/api/coze_claw/file/agent_upload",zv=6e4;async function tx(t,e={}){let i=`${Gr(qr(e.handshakeBase))}${Fv}`,s=e.timeoutMs??zv,a=await Mv.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...On(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),s);ex.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),m=p.headers.get("x-tt-logid")??"";if(!p.ok){let v=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${m}: ${v.slice(0,200)}`)}let b=await p.json();if(b.code!==void 0&&b.code!==0)throw new k("UPLOAD_FAILED",`upload code=${b.code} msg=${b.msg??"-"} logid=${m}`);let y=b.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${m}: ${JSON.stringify(b).slice(0,200)}`);return ex.info("file upload ok",{uri:y,logid:m}),{uri:y}}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${s}ms) for ${Bv(t.path)}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Je();re();import{extname as Uv}from"node:path";var Hv={".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 nx(t){let e=Uv(t).toLowerCase();return Hv[e]??"application/octet-stream"}Pe();var Jo=H("agent-send"),rx=50*1024*1024;function ox(t,e,n){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let s=i.sessions.get(n);if(!s)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:s}}async function ax(t,e,n,i,s,a){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,n,i,s);return}catch(x){u=x,f<2&&(Jo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function cx(t,e){let{session:n,runtime:i}=ox(e.core,t.agentId,t.sessionId);if(!await _i(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let s=await Gv.stat(t.path).catch(()=>null);if(!s||!s.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(s.size>rx)throw new k("FILE_TOO_LARGE",`${s.size} bytes > limit ${rx}`);let a=await nx(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??sx(t.path),u;try{u=await tx({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:d,sizeBytes:s.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Jo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.size,mime:a,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:ix(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:d,sizeBytes:s.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await ax(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Jo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:s.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:s.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function dx(t,e){let{session:n,runtime:i}=ox(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 s=t.name??sx(t.path),a={sessionUpdate:"group_file",messageId:ix(),content:{uri:t.path,name:s,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ax(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Jo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:s,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function lx(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),s=Math.max(n.length,i.length);for(let a=0;a<s;a++){let d=n[a]??0,u=i[a]??0;if(d<u)return!0;if(d>u)return!1}return!1}an();re();_n();var $t=H("coze-cli-installer"),ux="@coze/cli@latest",qv="coze",fx="0.1.8",jv=5e3,Kv=5e3,Wv=9e4,hx=1e4,ds=null,Yo=!1;async function jd(t,e={}){if(Yo)return;if(ds)return ds;let n=e.exec??v0;return ds=(async()=>{try{let i=await $v(qv,n),s=!1;if(i){let d=await Vv(n);if(d===void 0)$t.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(lx(d,fx))$t.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:fx}),s=!0;else{$t.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Yo=!0;return}}let a=s?"upgrade-only":"full";$t.info("coze-cli install start",{package:ux,mode:a});try{await n("npm",["i","-g","--prefer-online",ux],{timeout:Wv,maxBuffer:10*1024*1024}),$t.info("coze-cli install ok")}catch(d){$t.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(s){Yo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:hx}),$t.info("coze config set xTTEnv ok",{env:t.env})}catch(d){$t.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:hx}),$t.info("coze auth login ok")}catch(d){$t.warn("coze auth login failed",{err:String(d)});return}Yo=!0}finally{ds=null}})(),ds}async function $v(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:jv});return nc(i)}catch{return}}async function Vv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Kv});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Lt();Pe();var Zv=10*6e4;function xx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Zv:e}function dr(t){return gt(t??Z().configFile)}function lr(t,e){return Ot(e??Z().configFile,t)}var Xo=class{configPath;memory=new Map;runtimeCurrent=new Map;writeQueue=new Wt;constructor(e){this.configPath=e}async loadFromDisk(){let n=(await dr(this.configPath))?.modelListsCache;if(n)for(let[i,s]of Object.entries(n))s&&this.memory.set(i,s)}get(e){return this.memory.get(e)}update(e,n){return this.writeQueue.enqueue(async()=>{let i=Z0(n),s=this.memory.get(e);if(s&&s.hash===i)return!1;let a={cachedAt:Date.now(),hash:i,models:n.models,...n.defaultModelId?{defaultModelId:n.defaultModelId}:{},...n.effortLevels?{effortLevels:n.effortLevels}:{},...n.fastModes?{fastModes:n.fastModes}:{}};this.memory.set(e,a);let d=await dr(this.configPath)??{};return d.modelListsCache={...d.modelListsCache,[e]:a},await lr(d,this.configPath),!0})}setRuntimeCurrent(e,n){let i=this.runtimeCurrent.get(e)??{};this.runtimeCurrent.set(e,{...i,...n.model!==void 0?{model:n.model}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.fastMode!==void 0?{fastMode:n.fastMode}:{}})}getRuntimeCurrent(e){return this.runtimeCurrent.get(e)}};Qt();import{randomBytes as pS}from"node:crypto";_r();Je();re();import{createReadStream as Jv}from"node:fs";import{mkdir as Yv,readFile as Xv,realpath as Qv,stat as eS,writeFile as tS}from"node:fs/promises";import{basename as nS,dirname as Kd,isAbsolute as rS,join as iS,relative as sS,resolve as px,sep as oS}from"node:path";import{createInterface as aS}from"node:readline";var mx=H("fs-rpc"),ls=Ze("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function yx(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>ls)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${ls} bytes`);let i=await bx(t.path,e);return await Yv(Kd(i),{recursive:!0}),await tS(i,t.content,"utf8"),mx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function _x(t,e){let n=await bx(t.path,e),i=await eS(n),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>ls&&!s)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${ls} bytes`);let a;if(s&&i.size>ls)a=await cS(n,t.line??1,t.limit);else{let d=await Xv(n,"utf8");if(s){let u=d.split(`
117
116
  `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;a=u.slice(f,x).join(`
118
- `)}else a=d}return Kh.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function Sv(t,e,n){let i=vv({input:fv(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),a=typeof n=="number"?o+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let f of i)if(u>=o&&u<a&&d.push(f),u++,u>=a)break}finally{i.close()}return d.join(`
119
- `)}async function Zh(t,e){if(typeof t!="string"||t.length===0)throw new A("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([Wh(jh(e)),Wh(jh(t))]),o=bv(n,i);if(Iv(o,Ev,_v(o)))throw new A("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Iv(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Wh(t){let e=[],n=t;for(;n!==Md(n);)try{let i=await pv(n);return e.length?yv(i,...e.reverse()):i}catch{e.push(wv(n)),n=Md(n)}return t}te();var Jh=G("prompt-multimodal"),Yh=10*1024*1024,Av=15e3,kv=6;async function Xh(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let a=n++,d=t[a];d!==void 0&&(e[a]=await Tv(d))}}let o=Array.from({length:Math.min(kv,t.length)},()=>i());return await Promise.all(o),e}function Qh(t){return t.some(e=>e.type==="image")}async function Tv(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Gi(e.uri))return t;try{let{buf:n,contentType:i}=await Rv(e.uri),o=e.mimeType||Cv(i)||"application/octet-stream";return Jh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:o}),{type:"image",data:n.toString("base64"),mimeType:o}}catch(n){return Jh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Cv(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function Rv(t){let e=new AbortController,n=setTimeout(()=>e.abort(),Av);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>Yh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Yh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}$t();Je();te();var $=G("core"),Dv=3e4,Ov=/^(boe|ppe)_[A-Za-z0-9_-]+$/,Lv="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",Nv="\u5BA1\u6279\u5DF2\u8D85\u65F6",Mv=3e4,Ko=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Hr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=qh(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),$.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){$.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),$.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(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,n,i){let o=i.downstream;o&&(o.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),o.onAgentRequest(a=>{this.handleAgentRequest(e,o,a)}),o.onExit((a,d)=>{$.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),Kr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[o,a]of this.pendingUpstream)a.downstream===e&&i.push(o);if(i.length!==0){$.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let o of i){let a=this.pendingUpstream.get(o);if(a){this.pendingUpstream.delete(o),this.upstream.send(Cn(o,{code:Y.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>$.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:Y.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){$.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Y.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new A("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Po(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&Ov.test(i)?this.currentCozeEnv=i:i&&$.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=n0(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),$.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),$.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,Y.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):$.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(Ur(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Ur(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Ur(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Y.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):$.warn("drop unknown notification",{method:e.method})}catch(u){$.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Cn(n,Yi(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new A("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new A("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new A("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new A("AGENT_NOT_FOUND",`agent not found: ${i}`);let a=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!a)return this.dispatchSessionCall(o,e.method,n);if(e.method==="session/prompt"){let f=o.sessions.get(a);if(f?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,p=bo(n._meta);return $.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,f,a,Lv,x,p)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return u=!0,f}finally{$.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=i0(i);switch(n){case"session/new":{let a=Bv();return $.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return $.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=o,d=a.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=tn(e)?r0(i._meta):void 0;if(u!==void 0&&!Ft(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Ad(e.framework)}`);let f=bo(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,f,x);if(u!==void 0&&p.permissionMode===void 0&&(p.permissionMode=u,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new A("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==u){let _=p.permissionMode;p.permissionMode=u,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(b){throw p.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),b}}let m=i._meta?.cozeTriggerMsgId;if(m?e.activeTriggers.set(p.acpSessionId,m):e.activeTriggers.delete(p.acpSessionId),f?e.activeGroupIds.set(p.acpSessionId,f):e.activeGroupIds.delete(p.acpSessionId),f&&p.cozeGroupId!==f&&(p.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Qh(a.prompt))throw new A("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let v=await Xh(a.prompt);try{let _=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:v});return p.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof A&&_.code==="AGENT_APPROVAL_TIMEOUT"){let b=p.pendingPermission;b&&(b.downstream.respondAgentRequest(b.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(b.upstreamId),p.pendingPermission=void 0);let S=p.acpSessionId,I=S?e.activeTriggers.get(S):void 0,T=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,p,d,Nv,I,T)}throw _}finally{if(e.activeTriggers.delete(p.acpSessionId),e.activeGroupIds.delete(p.acpSessionId),p.pendingPermission=void 0,p.reloadAfterTurn){p.reloadAfterTurn=!1;let _=p.downstream;_&&(p.downstream=void 0,$.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),_.stop("reload-after-turn").catch(b=>$.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(b)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new A("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&($.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new A("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=o,d=a.sessionId,u=a.modeId,f=bo(i._meta);if(!d)throw new A("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!tn(e))throw e.framework==="openclaw"?new A("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new A("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Ft(e.framework,u))throw new A("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Ad(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let p=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),m}else $.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new A("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return $.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};$.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of o){let u=d.runtime.downstream,f=d.runtime.acpSessionId;u?.isAlive()&&f&&a.push({downstream:u,acpSessionId:f,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,o){let a=e.sessions.get(n);if(a){let f=a.cozeGroupId!==i,x=e.deployType==="cloud"&&a.tokenGroupId!==i,p=a.requestScene!==o;if(x&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),x||p){Kr(a);let m=a.downstream;a.downstream=void 0,m&&await m.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(f||x||p)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...o?{requestScene:o}:{}};return tn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?v0:S0:u.permissionMode=e.framework==="claude-code"?Od:Th),e.sessions.set(n,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,n,i){let o={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(gt.GEN_MODEL_TOKEN,o,Mv);if(!a?.modelToken)throw new A("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return a.modelToken}catch(a){throw a instanceof A&&a.code==="MODEL_TOKEN_GEN_FAILED"?a:new A("MODEL_TOKEN_GEN_FAILED",a instanceof Error?a.message:String(a),{cause:a})}}async ensureDownstream(e,n,i){if(Kr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new A("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<a)throw new A("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-u))/1e3)}s`);let f;try{let x=this.requestSceneBySession.get(n);x&&$.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){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:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),$.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(x){$.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw $.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),tn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){$.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(Kr(i),this.isRuntimeBusy(e,i)){$.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){$.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}$.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(a=>$.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,o){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(zr("session/update",{sessionId:i,update:o,_meta:a}))}async synthesizePromptReply(e,n,i,o,a,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(u.cozeTriggerMsgId=a),d&&(u.cozeGroupId=d),await this.upstream.send(zr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>$.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,o=this.reverseSessionId(e,i);if(!o){$.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){$.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Uv(n)){$.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&tn(e)){let p=d.currentModeId;Ft(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(m=>$.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof p=="string"&&!Ft(e.framework,p)&&$.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(zr("session/update",{...n,sessionId:o,_meta:u})).catch(p=>$.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}$.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:Y.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let a=i.params??{},d=await $h(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Vh(a,o);n.respondAgentRequest(i.id,d)}}catch(o){$.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,Yi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let o=this.upstreamIds.next("session/request_permission"),a=i.params??{},u=a.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let m=u?this.reverseSessionId(e,u):void 0,v=m?e.sessions.get(m):void 0;v&&(v.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...a,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:m}),$.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:m,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Zi(o,"session/request_permission",_)).catch(b=>{this.pendingUpstream.delete(o),$.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),n.respondAgentRequestError(i.id,{code:Y.INTERNAL_ERROR,message:`upstream send failed: ${String(b)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.value;this.clearPendingPermissionFor(o),e.error?($.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"&&Fv(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 Ro(e.error)):i.value.resolve(e.result);return}$.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let o=e.get(n);if(o)return{value:o,key:n};if(typeof n=="number"){let a=String(n),d=e.get(a);if(d)return $.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=Dv){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new A("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(Zi(o,e,n)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,o]of e.sessions){let a={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(a.acpSessionId=o.acpSessionId),o.permissionMode&&tn(e)&&(a.permissionMode=o.permissionMode),o.cozeGroupId&&(a.cozeGroupId=o.cozeGroupId),o.tokenGroupId&&(a.tokenGroupId=o.tokenGroupId),o.requestScene&&(a.requestScene=o.requestScene),n.set(i,a)}await hi(e.agentId,n,this.paths)}catch(n){$.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Cn(e,{code:n,message:i,data:{bridgeVersion:Bt}}))}};function Bv(){return Pv(16).toString("hex")}function Fv(t,e){if(!t||typeof t!="object"){$.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){$.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.outcome;if(!i||typeof i!="object"){$.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let a=i.outcome;(typeof a!="string"||a!=="selected"&&a!=="cancelled")&&$.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var zv=["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."],ex="Warning: ";function Uv(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let o=i.text.startsWith(ex)?i.text.slice(ex.length):i.text;return zv.some(a=>o.startsWith(a))}Kt();te();Pe();import{randomBytes as Hv}from"node:crypto";import{createServer as Gv}from"node:http";var qv=1e6,tx=G("ipc"),$o=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(n=>[`${n.method} ${n.path}`,n])),this.paths=e.paths??Z()}async start(){this.token=Hv(32).toString("hex");let e=Gv((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),tx.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(o=>o?i(o):n())}),this.server=null)}async persistAuthFiles(){await ct(this.paths.portFile,String(this.port)),await ct(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){rs(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){rs(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await jv(e)}catch(u){rs(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);rs(n,200,u??{ok:!0})}catch(u){tx.error("IPC handler failed",{key:o,err:String(u)}),rs(n,500,{error:u instanceof Error?u.message:String(u)})}}};function rs(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function jv(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>qv)throw new Error("body too large");e.push(a)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var l1=Wt(Yx(),1),u1=Wt(na(),1),f1=Wt(Jr(),1),h1=Wt($d(),1),x1=Wt(Jd(),1),p1=Wt(nl(),1),op=Wt(oa(),1),g1=Wt(sp(),1);var ap=op.default;Je();te();var{FWS:D1}=wp(),Me=G("upstream.frontier"),yp="application/json",bp="none",O1=15e3;function L1(t){class e extends ap{constructor(i){super(i,d0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Me.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(Wl("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let d=Buffer.from(a.slice(0,128)).toString("hex");Me.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Me.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var fs=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){Me.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:l0,...kn(this.opts.ppeOverride)},n=L1(e),i=f0(this.opts.urlOverride),o={url:i,ws:n,fpID:c0,aID:vo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:yp,force:!0},payloadEncoding:{encoding:bp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new D1(o),d=!1,u=null,f,x,p=new Promise((_,b)=>{f=_,x=b}),m=_=>{d||(d=!0,u&&(clearTimeout(u),u=null),_?x(_):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Me.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&m();for(let b of this.connectHandlers)Promise.resolve(b({initial:_})).catch(S=>Me.warn("onConnect handler threw (ignored)",{err:String(S)}))},a.onclose=_=>{this.opened=!1,Me.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Me.warn("frontier error",{code:_.code,msg:_.message}),m(new A("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let v=this.opts.openTimeoutMs??O1;u=setTimeout(()=>{m(new A("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await a.connect();try{await p}catch(_){try{a.close(1e3,"open failed")}catch(b){Me.warn("fws close during start failure threw (ignored)",{err:String(b)})}throw this.fws=null,this.opened=!1,_}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Me.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Me.warn("frontier send refused: upstream not started",{method:i}),new A("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Me.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new A("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),a=e;Ep(a)||Me.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:yp,payloadEncoding:bp})}catch(u){throw Me.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new A("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Me.debug("drop non-adapter frontier frame",{service:n});return}let i=B1(e);if(!i){Me.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Me.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Me.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;Ep(a)||Me.info("frontier frame in",{logid:M1(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:N1(i)}),Promise.resolve(this.handler(o)).catch(d=>Me.warn("frontier frame handler threw",{err:String(d)}))}};function Ep(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var vp=2e3;function N1(t){return t.length<=vp?t:`${t.slice(0,vp)}...<truncated, total ${t.length} chars>`}function M1(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function B1(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Je();te();var ol=G("skill-publish"),F1="/api/marketplace/product/skill/publish_with_assets",z1=15e4;async function Sp(t,e={}){let i=`${Nr(Mr(e.handshakeBase))}${F1}`,o=e.timeoutMs??z1,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...kn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);ol.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new A("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${_.slice(0,200)}`)}let m=await x.json();if(ol.info("skill publish response",{logid:p,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new A("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${p}`);let v={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(v.skillId=String(m.data.skill_id)),m.data?.version&&(v.version=m.data.version),ol.info("skill publish ok",{logid:p,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof A?x:x.name==="AbortError"?new A("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new A("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}te();var al=G("upstream.switchable"),pa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;al.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw al.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>al.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 cl=G("upstream"),ni=class{handler=null;async start(){cl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){cl.info("NoopUpstream stopped",{reason:e})}async send(e){cl.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();te();Kt();te();Pe();import{promises as U1}from"node:fs";var Ip=G("pat-token-store");async function ga(t=Z()){try{let n=(await U1.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Ip.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):n}catch(e){let n=e?.code;return n!=="ENOENT"&&Ip.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function hs(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await ct(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as ma}from"node:fs";import{join as H1}from"node:path";function G1(t,e){return`#!/bin/sh
117
+ `)}else a=d}return mx.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function cS(t,e,n){let i=aS({input:Jv(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),s=Math.max(0,e-1),a=typeof n=="number"?s+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let f of i)if(u>=s&&u<a&&d.push(f),u++,u>=a)break}finally{i.close()}return d.join(`
118
+ `)}async function bx(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([gx(px(e)),gx(px(t))]),s=sS(n,i);if(dS(s,oS,rS(s)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function dS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function gx(t){let e=[],n=t;for(;n!==Kd(n);)try{let i=await Qv(n);return e.length?iS(i,...e.reverse()):i}catch{e.push(nS(n)),n=Kd(n)}return t}re();var Ex=H("prompt-multimodal"),vx=10*1024*1024,lS=15e3,uS=6;async function Sx(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let a=n++,d=t[a];d!==void 0&&(e[a]=await fS(d))}}let s=Array.from({length:Math.min(uS,t.length)},()=>i());return await Promise.all(s),e}function Ix(t){return t.some(e=>e.type==="image")}async function fS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Yi(e.uri))return t;try{let{buf:n,contentType:i}=await xS(e.uri),s=e.mimeType||hS(i)||"application/octet-stream";return Ex.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:s}),{type:"image",data:n.toString("base64"),mimeType:s}}catch(n){return Ex.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function hS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function xS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),lS);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let s=await i.arrayBuffer();if(s.byteLength>vx)throw new Error(`image too large: ${s.byteLength} bytes (max ${vx})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Qt();Je();re();var K=H("core"),gS=3e4,mS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,wS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",yS="\u5BA1\u6279\u5DF2\u8D85\u65F6",_S=3e4,Qo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Zr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;modelListCache;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=xx(e.bridgeConfig),this.modelListCache=e.modelListCache}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}getRequestSceneForSession(e){return this.requestSceneBySession.get(e)}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),K.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){K.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of n)await this.agents.get(i)?.killAllRuntimes("reload");return n}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),K.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){K.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)&&K.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let s=i.downstream;s&&(s.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),s.onAgentRequest(a=>{this.handleAgentRequest(e,s,a)}),s.onExit((a,d)=>{K.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),ei(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(s,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[s,a]of this.pendingUpstream)a.downstream===e&&i.push(s);if(i.length!==0){K.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let s of i){let a=this.pendingUpstream.get(s);if(a){this.pendingUpstream.delete(s),this.upstream.send(Nn(s,{code:X.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>K.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:X.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){K.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:X.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Fo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&mS.test(i)?this.currentCozeEnv=i:i&&K.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let s=e.params,a=u0(s?._meta),d=s?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),K.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),K.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,X.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):K.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(Vr(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Vr(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Vr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,X.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):K.warn("drop unknown notification",{method:e.method})}catch(u){K.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Nn(n,os(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(i);if(!s)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 a=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!a)return this.dispatchSessionCall(s,e.method,n);if(e.method==="session/prompt"){let f=s.sessions.get(a);if(f?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,p=ko(n._meta);return K.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:a}),this.synthesizePromptReply(s,f,a,wS,x,p)}}let d=Date.now(),u=!1;try{let f=await s.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(s,e.method,n));return u=!0,f}finally{K.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:s}=h0(i);switch(n){case"session/new":{let a=bS();return K.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=s;return K.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=s,d=a.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=dn(e)?f0(i._meta):void 0;if(u!==void 0&&!Kt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Nd(e.framework)}`);let f=ko(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,f,x);if(u!==void 0&&p.permissionMode===void 0&&(p.permissionMode=u,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==u){let y=p.permissionMode;p.permissionMode=u,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(v){throw p.permissionMode=y,await this.persistSessionMapping(e).catch(()=>{}),v}}let m=i._meta?.cozeTriggerMsgId;if(m?e.activeTriggers.set(p.acpSessionId,m):e.activeTriggers.delete(p.acpSessionId),f?e.activeGroupIds.set(p.acpSessionId,f):e.activeGroupIds.delete(p.acpSessionId),f&&p.cozeGroupId!==f&&(p.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Ix(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let b=await Sx(a.prompt);try{let y=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:b});return p.lastActiveAt=Date.now(),y}catch(y){if(y instanceof k&&y.code==="AGENT_APPROVAL_TIMEOUT"){let v=p.pendingPermission;v&&(v.downstream.respondAgentRequest(v.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(v.upstreamId),p.pendingPermission=void 0);let I=p.acpSessionId,A=I?e.activeTriggers.get(I):void 0,T=I?e.activeGroupIds.get(I):void 0;return K.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,p,d,yS,A,T)}throw y}finally{if(e.activeTriggers.delete(p.acpSessionId),e.activeGroupIds.delete(p.acpSessionId),p.pendingPermission=void 0,p.reloadAfterTurn){p.reloadAfterTurn=!1;let y=p.downstream;y&&(p.downstream=void 0,K.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),y.stop("reload-after-turn").catch(v=>K.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(v)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=s.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&(K.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=s,d=a.sessionId,u=a.modeId,f=ko(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!dn(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(!Kt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Nd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let p=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(m){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),m}else K.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let s=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&s.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(s.length===0)return K.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};K.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:s.length});for(let d of s)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of s){let u=d.runtime.downstream,f=d.runtime.acpSessionId;u?.isAlive()&&f&&a.push({downstream:u,acpSessionId:f,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let f of s)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,s){let a=e.sessions.get(n);if(a){let f=a.cozeGroupId!==i,x=e.deployType==="cloud"&&a.tokenGroupId!==i,p=a.requestScene!==s;if(x&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),x||p){ei(a);let m=a.downstream;a.downstream=void 0,m&&await m.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=s,(f||x||p)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...s?{requestScene:s}:{}};return dn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?U0:H0:u.permissionMode=e.framework==="claude-code"?Gd:Qh),e.sessions.set(n,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,n,i){let s={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(nt.GEN_MODEL_TOKEN,s,_S);if(!a?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);return a.modelToken}catch(a){throw a instanceof k&&a.code==="MODEL_TOKEN_GEN_FAILED"?a:new k("MODEL_TOKEN_GEN_FAILED",a instanceof Error?a.message:String(a),{cause:a})}}async ensureDownstream(e,n,i){if(ei(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=s&&Date.now()-u<a)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-u))/1e3)}s`);let f;try{let x=this.requestSceneBySession.get(n);x&&K.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=s&&i.acpSessionId&&(K.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{let x=await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace});K.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId}),this.piggybackModelList(e,x)}catch(x){K.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,this.piggybackModelList(e,p),await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,this.piggybackModelList(e,x),await this.persistSessionMapping(e)}}catch(x){throw K.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),dn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){K.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(ei(i),this.isRuntimeBusy(e,i)){K.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){K.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}K.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let s=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),s&&s.stop("idle timeout").catch(a=>K.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,s){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send($r("session/update",{sessionId:i,update:s,_meta:a}))}async synthesizePromptReply(e,n,i,s,a,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(u.cozeTriggerMsgId=a),d&&(u.cozeGroupId=d),await this.upstream.send($r("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(f=>K.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,s=this.reverseSessionId(e,i);if(!s){K.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(s);if(!a){K.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(SS(n)){K.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&dn(e)){let p=d.currentModeId;Kt(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(m=>K.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(m)}))):typeof p=="string"&&!Kt(e.framework,p)&&K.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}if(d&&typeof d=="object"&&d.sessionUpdate==="config_option_update"){let p=d.configOptions;Array.isArray(p)&&this.piggybackModelList(e,{configOptions:p})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send($r("session/update",{...n,sessionId:s,_meta:u})).catch(p=>K.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}piggybackModelList(e,n){let i=this.modelListCache;if(i)try{let s=W0(e.framework,n);if(!s)return;s.models.length>0&&i.update(e.framework,s).catch(a=>K.warn("piggyback model-list update failed (ignored)",{agentId:e.agentId,err:String(a)})),s.currentModelId&&i.setRuntimeCurrent(e.agentId,{model:s.currentModelId})}catch(s){K.warn("piggyback model-list parse failed (ignored)",{agentId:e.agentId,err:String(s)})}}handleAgentRequest(e,n,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,n,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,i);return}K.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:X.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let s=e.workspace;if(i.method==="fs/write_text_file"){let a=i.params??{},d=await yx(a,s);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await _x(a,s);n.respondAgentRequest(i.id,d)}}catch(s){K.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),n.respondAgentRequestError(i.id,os(s))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let s=this.upstreamIds.next("session/request_permission"),a=i.params??{},u=a.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let m=u?this.reverseSessionId(e,u):void 0,b=m?e.sessions.get(m):void 0;b&&(b.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:s});let y={...a,...m?{sessionId:m}:{},_meta:x};this.pendingUpstream.set(s,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:m}),K.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:u,cloudSessionId:m,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(is(s,"session/request_permission",y)).catch(v=>{this.pendingUpstream.delete(s),K.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:X.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let s=n.value;this.clearPendingPermissionFor(s),e.error?(K.info("upstream \u2192 permission response (error)",{agentId:s.agentId,upstreamId:e.id,method:s.method,error:e.error}),s.downstream.respondAgentRequestError(s.agentRequestId,e.error)):(s.method==="session/request_permission"&&ES(e.result,s),K.info("upstream \u2192 permission response (result)",{agentId:s.agentId,upstreamId:e.id,method:s.method,result:e.result}),s.downstream.respondAgentRequest(s.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 Bo(e.error)):i.value.resolve(e.result);return}K.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let s=e.get(n);if(s)return{value:s,key:n};if(typeof n=="number"){let a=String(n),d=e.get(a);if(d)return K.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=gS){let s=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(is(s,e,n)).catch(f=>{let x=this.pendingBridge.get(s);x&&(clearTimeout(x.timer),this.pendingBridge.delete(s)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,s]of e.sessions){let a={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(a.acpSessionId=s.acpSessionId),s.permissionMode&&dn(e)&&(a.permissionMode=s.permissionMode),s.cozeGroupId&&(a.cozeGroupId=s.cozeGroupId),s.tokenGroupId&&(a.tokenGroupId=s.tokenGroupId),s.requestScene&&(a.requestScene=s.requestScene),n.set(i,a)}await bi(e.agentId,n,this.paths)}catch(n){K.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,s]of e.sessions.entries())if(s.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Nn(e,{code:n,message:i,data:{bridgeVersion:Gt}}))}};function bS(){return pS(16).toString("hex")}function ES(t,e){if(!t||typeof t!="object"){K.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){K.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=n.outcome;if(!i||typeof i!="object"){K.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let a=i.outcome;(typeof a!="string"||a!=="selected"&&a!=="cancelled")&&K.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var vS=["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."],Ax="Warning: ";function SS(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let s=i.text.startsWith(Ax)?i.text.slice(Ax.length):i.text;return vS.some(a=>s.startsWith(a))}Lt();re();Pe();import{randomBytes as IS}from"node:crypto";import{createServer as AS}from"node:http";var kS=1e6,kx=H("ipc"),ea=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(n=>[`${n.method} ${n.path}`,n])),this.paths=e.paths??Z()}async start(){this.token=IS(32).toString("hex");let e=AS((i,s)=>{this.dispatch(i,s)});this.server=e,await new Promise((i,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),kx.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(s=>s?i(s):n())}),this.server=null)}async persistAuthFiles(){await mt(this.paths.portFile,String(this.port)),await mt(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){us(n,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(s);if(!a){us(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await TS(e)}catch(u){us(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);us(n,200,u??{ok:!0})}catch(u){kx.error("IPC handler failed",{key:s,err:String(u)}),us(n,500,{error:u instanceof Error?u.message:String(u)})}}};function us(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function TS(t){let e=[],n=0;for await(let s of t){let a=s;if(n+=a.length,n>kS)throw new Error("body too large");e.push(a)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var V1=Xt(Ep(),1),Z1=Xt(da(),1),J1=Xt(ii(),1),Y1=Xt(nl(),1),X1=Xt(sl(),1),Q1=Xt(ul(),1),Rp=Xt(ha(),1),eI=Xt(Pp(),1);var Dp=Rp.default;Je();re();var{FWS:gI}=qp(),Be=H("upstream.frontier"),Kp="application/json",Wp="none",mI=15e3;function wI(t){class e extends Dp{constructor(i){super(i,A0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Be.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,s){this.guardTeardown(),super.close(i,s)}terminate(){this.guardTeardown(),super.terminate()}send(i,...s){if(eu("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let d=Buffer.from(a.slice(0,128)).toString("hex");Be.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Be.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...s)}}return e}var _s=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){Be.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:k0,...On(this.opts.ppeOverride)},n=wI(e),i=C0(this.opts.urlOverride),s={url:i,ws:n,fpID:I0,aID:Po,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Kp,force:!0},payloadEncoding:{encoding:Wp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new gI(s),d=!1,u=null,f,x,p=new Promise((y,v)=>{f=y,x=v}),m=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(y):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Be.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&m();for(let v of this.connectHandlers)Promise.resolve(v({initial:y})).catch(I=>Be.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=y=>{this.opened=!1,Be.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},a.onerror=y=>{Be.warn("frontier error",{code:y.code,msg:y.message}),m(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},a.onmessage=y=>this.handleMessage(y),this.fws=a;let b=this.opts.openTimeoutMs??mI;u=setTimeout(()=>{m(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${b}ms (handshake or upgrade slow)`))},b),await a.connect();try{await p}catch(y){try{a.close(1e3,"open failed")}catch(v){Be.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Be.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Be.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?(Be.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let s=JSON.stringify(e),a=e;$p(a)||Be.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:s.length});try{await n.send(s,{service:33555712,method:1,payloadType:Kp,payloadEncoding:Wp})}catch(u){throw Be.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let s=n(i.cozeAgentId);s&&(i.cozePatToken=s)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Be.debug("drop non-adapter frontier frame",{service:n});return}let i=bI(e);if(!i){Be.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Be.debug("frame received but no onFrame handler",{size:i.length});return}let s;try{s=JSON.parse(i)}catch(d){Be.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=s;$p(a)||Be.info("frontier frame in",{logid:_I(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:yI(i)}),Promise.resolve(this.handler(s)).catch(d=>Be.warn("frontier frame handler threw",{err:String(d)}))}};function $p(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Vp=2e3;function yI(t){return t.length<=Vp?t:`${t.slice(0,Vp)}...<truncated, total ${t.length} chars>`}function _I(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function bI(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Je();re();var pl=H("skill-publish"),EI="/api/marketplace/product/skill/publish_with_assets",vI=15e4;async function Zp(t,e={}){let i=`${Gr(qr(e.handshakeBase))}${EI}`,s=e.timeoutMs??vI,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...On(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),s);pl.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${y.slice(0,200)}`)}let m=await x.json();if(pl.info("skill publish response",{logid:p,httpStatus:x.status,code:m.code,msg:m.msg,dataSkillId:m.data?.skill_id??"",dataVersion:m.data?.version??""}),m.code!==void 0&&m.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${m.code} msg=${m.msg??"-"} logid=${p}`);let b={};return m.data?.skill_id!==void 0&&m.data.skill_id!==""&&(b.skillId=String(m.data.skill_id)),m.data?.version&&(b.version=m.data.version),pl.info("skill publish ok",{logid:p,skillId:b.skillId??"",version:b.version??""}),b}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${s}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}re();var gl=H("upstream.switchable"),Ea=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;gl.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let s of this.connectHandlers)e.onConnect(s);try{await e.start()}catch(s){throw gl.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(n??"swapped").catch(s=>gl.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};re();var ml=H("upstream"),li=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)}};Je();re();Lt();re();Pe();import{promises as SI}from"node:fs";var Jp=H("pat-token-store");async function va(t=Z()){try{let n=(await SI.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Jp.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):n}catch(e){let n=e?.code;return n!=="ENOENT"&&Jp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function bs(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await mt(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as Sa}from"node:fs";import{join as II}from"node:path";function AI(t,e){return`#!/bin/sh
120
119
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
121
- `}function q1(t,e){return`@echo off\r
120
+ `}function kI(t,e){return`@echo off\r
122
121
  "${e}" "${t}" %*\r
123
- `}async function Ap(t,e=Z()){let n=e.binDir;await ma.mkdir(n,{recursive:!0});let i=H1(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,a=process.platform==="win32"?q1(t,o):G1(t,o);return await ma.readFile(i,"utf8").catch(()=>null)===a||(await ma.writeFile(i,a,"utf8"),process.platform!=="win32"&&await ma.chmod(i,493)),n}te();Pe();import{execSync as kp}from"node:child_process";import{readFileSync as Tp,unlinkSync as j1}from"node:fs";import{mkdir as W1,open as K1,readFile as Cp,unlink as dl,writeFile as $1}from"node:fs/promises";import{dirname as V1}from"node:path";var Z1=G("single-instance"),J1=t=>new Promise(e=>setTimeout(e,t)),wa=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Z().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>Xi(n),isDaemon:n=>this.matchesDaemonTitle(n)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let n=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&Z1.warn("removing stale pid file",{stalePid:i}),await $1(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return n.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),n}async release(){if(this.acquired){try{(await Cp(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await dl(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await Cp(e,"utf8"),i=Number.parseInt(n.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(n){if(n.code==="ENOENT")return null;throw n}}async withClaimLock(e){let n=`${this.pidFile}.lock`;await W1(V1(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await K1(n,"wx")}catch(a){if(a.code!=="EEXIST")throw a;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await J1(this.claimLockIntervalMs);continue}await dl(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await dl(n).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${n} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=Tp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Gr)||n.includes("lib/index.js"))}catch{}try{let n=kp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Gr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=kp(`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{Tp(this.pidFile,"utf8").trim()===String(this.selfPid)&&j1(this.pidFile)}catch{}})}};_a();te();var ar=G("daemon.upstream-watchdog"),iI=12e4,sI=9e5,oI=3e4;function ul(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ya=class{constructor(e){this.opts=e;this.softMs=e.softMs??ul("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",iI),this.hardMs=e.hardMs??ul("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",sI),this.intervalMs=e.intervalMs??ul("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",oI),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?.(),ar.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&&ar.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&&ar.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,ar.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){ar.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,ar.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>ar.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var j=G("daemon");async function Dp(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){ql({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>Re(C,t).logs,listAgentIds:()=>ks(t)});try{let{writeFileSync:C}=await import("node:fs");C(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
122
+ `}async function Yp(t,e=Z()){let n=e.binDir;await Sa.mkdir(n,{recursive:!0});let i=II(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,a=process.platform==="win32"?kI(t,s):AI(t,s);return await Sa.readFile(i,"utf8").catch(()=>null)===a||(await Sa.writeFile(i,a,"utf8"),process.platform!=="win32"&&await Sa.chmod(i,493)),n}re();Pe();import{execSync as Xp}from"node:child_process";import{readFileSync as Qp,unlinkSync as TI}from"node:fs";import{mkdir as CI,open as PI,readFile as eg,unlink as wl,writeFile as RI}from"node:fs/promises";import{dirname as DI}from"node:path";var OI=H("single-instance"),LI=t=>new Promise(e=>setTimeout(e,t)),Ia=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Z().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>as(n),isDaemon:n=>this.matchesDaemonTitle(n)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let n=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&OI.warn("removing stale pid file",{stalePid:i}),await RI(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return n.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),n}async release(){if(this.acquired){try{(await eg(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await wl(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await eg(e,"utf8"),i=Number.parseInt(n.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(n){if(n.code==="ENOENT")return null;throw n}}async withClaimLock(e){let n=`${this.pidFile}.lock`;await CI(DI(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await PI(n,"wx")}catch(a){if(a.code!=="EEXIST")throw a;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await LI(this.claimLockIntervalMs);continue}await wl(n).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await wl(n).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${n} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=Qp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Jr)||n.includes("lib/index.js"))}catch{}try{let n=Xp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Jr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Xp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let s=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return s.includes("node")||s.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Qp(this.pidFile,"utf8").trim()===String(this.selfPid)&&TI(this.pidFile)}catch{}})}};Aa();re();var gr=H("daemon.upstream-watchdog"),GI=12e4,qI=9e5,jI=3e4;function _l(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ka=class{constructor(e){this.opts=e;this.softMs=e.softMs??_l("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",GI),this.hardMs=e.hardMs??_l("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",qI),this.intervalMs=e.intervalMs??_l("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",jI),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?.(),gr.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&&gr.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&&gr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,gr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){gr.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,gr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>gr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var G=H("daemon");async function rg(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Xl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>Le(C,t).logs,listAgentIds:()=>Ls(t)});try{let{writeFileSync:C}=await import("node:fs");C(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
124
123
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
125
124
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
126
- `)}catch{}}let e=new wa({processTitle:Gr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Wo(),o=i??{};vs({pid:process.pid}),j.info(i?"loaded bridge config":"initialized bridge config");let a=new pa(new ni),d=null,u=new Ko({upstream:a,paths:t,bridgeConfig:o,sessionSpawner:async(C,z,q,ee,He,he)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(C,z,q,ee,He,he)}}),f=new Go({paths:t,config:o,registry:u});d=f;let x,p,m=null,v={},_,b=null,S=null,I=null,T=new Rn;function R(C,z){return T.enqueue(()=>P(C,z))}function E(){S||(S=new ya({isConnected:()=>a.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>I?R(I,{force:!0}):void 0,onFatal:C=>{if(process.env[xs]==="1"){j.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}j.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),S.start()}async function P(C,z){let q=C,ee=q?.privatecode;if(!ee)throw new A("IPC_BAD_REQUEST","/connect requires privatecode");let He=Wi(q.env),he=q.handshake_url,me=q.frontier_url,Ct=Pp(q.env,he,me);if(I=q,!z?.force&&x===ee&&p===Ct){let ye=await aI(t);return u.agents.size===0&&ye?(j.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ea(t,f).catch(Oe=>j.warn("connect-noop auto-revive error (ignored)",{err:String(Oe)}))):j.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let yt=!!x&&x!==ee,cn=p!==void 0&&p!==Ct,jt=yt||cn,dn=await cd({privatecode:ee,...he?{endpoint:he}:{},ppeOverride:He});if(jt){j.warn("connect config switched, resetting agents",{pcChanged:yt,envChanged:cn,previousPc:x?ba(x):"",nextPc:ba(ee)});for(let ye of[...u.agents.values()])await ye.dispose("connect config switch").catch(()=>{}),u.agents.delete(ye.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ni,"connect switch").catch(()=>{})}m=dn.deviceId,vs({deviceId:m,pid:process.pid}),Nd({patToken:ee,env:q.env}).catch(ye=>j.warn("coze-cli setup error (ignored)",{err:String(ye)}));let ai=new fs({handshake:dn,privatecode:ee,...me?{urlOverride:me}:{},ppeOverride:He,getPatTokenForAgent:ye=>u.agents.get(ye)?.patToken});return await a.swap(ai,"connect"),x=ee,p=Ct,v=He,_=he,q.mock_scenario!==void 0&&(u.setMockScenario(q.mock_scenario),j.info("mock scenario set",{scenario:q.mock_scenario})),b||(b=new Vi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>N.retryPending().catch(ye=>j.warn("detailSync.retryPending failed (ignored)",{err:String(ye)})),onAuthFailures:J})),b.start(),E(),jt&&Ea(t,f).catch(ye=>j.warn("post-connect-switch auto-revive error (ignored)",{err:String(ye)})),hs(ee,t).catch(ye=>j.warn("writePatToken after /connect failed (ignored)",{err:String(ye)})),j.info("/connect: WS established",{deviceId:m}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>f.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let D={},M=new ko({agents:u.agents,paths:t,publishSkillToMarketplace:async C=>{let z=u.agents.get(C.agentId)?.patToken??x;if(!z)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Sp({patToken:z,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:_,ppeOverride:v})},disposeAndMarkDisconnected:async(C,z)=>{let q=u.agents.get(C);if(q){await f.cleanupOpenclawSessionProviders(q).catch(He=>j.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(He)})),q.framework==="hermes"&&q.deployType==="cloud"&&await pd(C,t).catch(He=>j.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(He)}));let ee=!0;try{await q.dispose(`disconnect: ${z}`)}catch(He){ee=!1,j.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(He)}),q.status="error"}ee&&(q.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,z)=>{let q=u.agents.get(C);q&&(await f.cleanupOpenclawSessionProviders(q).catch(ee=>j.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),q.framework==="hermes"&&q.deployType==="cloud"&&await pd(C,t).catch(ee=>j.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(ee)})),await q.dispose(`delete: ${z}`).catch(ee=>j.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!D.ref)throw new Error("agent-detail-sync not initialized yet");await D.ref.syncOne(C)},cleanupOpenclawProviders:async(C,z)=>{await f.cleanupOpenclawSessionProviders(C,z)},openclawRepair:async(C,z)=>{await f.openclawRepair(C,z)},hermesReset:async(C,z)=>{let q=await Ie(C).catch(()=>null);!q||q.framework!=="hermes"||q.deployType!=="cloud"||await I0({paths:t,agentId:C,model:q.model,modelInfo:q.modelInfo,cozeEnv:z,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>M.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>M.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>M.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>M.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>M.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>M.getFileContent(C.params)),u.registerExtension("_agent/update",C=>M.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>M.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>M.switchModel(C.params)),u.registerExtension("_agent/reset",C=>M.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>M.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>M.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>M.upgradeBridge(C.params));let N=new Rs({paths:t,handlers:M,agentManager:f,sendDetail:C=>u.sendRequest("_agent/detail",C)});D.ref=N;let J=async C=>{await Promise.allSettled(C.map(async z=>{try{await M.disconnectAgent({agentId:z.agentId,reason:`auth_failure: code=${z.code} ${z.message}`}),j.info("agent disconnected due to auth failure from heartbeat response",{agentId:z.agentId,code:z.code,message:z.message})}catch(q){j.warn("disconnect during authFailure handling failed (ignored)",{agentId:z.agentId,err:String(q)})}}))};a.onConnect(({initial:C})=>{j.info("frontier upstream connected, triggering detail sync",{initial:C}),N.syncAll(C?"initial-connect":"reconnect").catch(z=>j.warn("detail sync top-level error (ignored)",{err:String(z)}))});let V=new $o({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=u.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[xs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:m??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let z=C,q=z?.privatecode,ee=z?.pairing_code;if(!q||!ee)throw new A("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let He=Wi(z.env),he=z.handshake_url,me=z.frontier_url,Ct=Pp(z.env,he,me),yt=!!x&&x!==q,cn=p!==void 0&&p!==Ct,jt=yt||cn,dn=await cd({privatecode:q,...he?{endpoint:he}:{},ppeOverride:He});if(jt){j.warn("pair config switched, resetting agents",{pcChanged:yt,envChanged:cn,previousPc:x?ba(x):"",nextPc:ba(q),previousEnvKey:p??"",nextEnvKey:Ct});for(let Oe of[...u.agents.values()])await Oe.dispose("pair config switch").catch(()=>{}),u.agents.delete(Oe.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new ni,"pair switch").catch(()=>{})}m=dn.deviceId,vs({deviceId:m,pid:process.pid}),Nd({patToken:q,env:z.env}).catch(Oe=>j.warn("coze-cli setup error (ignored)",{err:String(Oe)}));let ai=new fs({handshake:dn,privatecode:q,...me?{urlOverride:me}:{},ppeOverride:He,getPatTokenForAgent:Oe=>u.agents.get(Oe)?.patToken});await a.swap(ai,"pair");try{let Oe=new er;o.frameworksCache=await Oe.detectAll(),await ts(o),j.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Oe){j.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Oe)})}let ye=Object.keys(o.frameworksCache??{});try{let Oe=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:q,frameworks:ye,_meta:{cozeDeviceId:m}});j.info("_agent/pair ok",{pairResult:Oe}),x=q,p=Ct,v=He,_=he,z.mock_scenario!==void 0&&(u.setMockScenario(z.mock_scenario),j.info("mock scenario set",{scenario:z.mock_scenario})),hs(q,t).catch(Fe=>j.warn("writePatToken after /pair failed (ignored)",{err:String(Fe)})),b||(b=new Vi({core:u,getDeviceId:()=>m??"",onTickEnd:()=>N.retryPending().catch(Fe=>j.warn("detailSync.retryPending failed (ignored)",{err:String(Fe)})),onAuthFailures:J})),b.start(),E(),jt&&Ea(t,f).catch(Fe=>j.warn("post-pair-switch auto-revive error (ignored)",{err:String(Fe)}));let cr;return z.agent_id&&(cr=await dI(z.agent_id,t,f,Fe=>u.sendRequest("_agent/detail",Fe),q).catch(Fe=>(j.error("--agent-id ensureAgent failed",{agentId:z.agent_id,err:String(Fe)}),{ok:!1,agentId:z.agent_id??"",note:String(Fe)}))),{ok:!0,note:"paired with cloud",...cr?{agent:cr}:{}}}catch(Oe){return j.error("_agent/pair failed",{err:String(Oe)}),{ok:!1,note:`pair failed: ${String(Oe)}`}}}},{method:"POST",path:"/connect",handler:C=>R(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let z=C;return{ok:!0,result:await f.createAgent(z)}}},{method:"POST",path:"/agent/send",handler:async C=>{let z=C;if(!z?.agentId||!z?.sessionId||!z?.kind||!z?.path)throw new A("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new A("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let q=z;return await(q.groupFile?Fh:Bh)(q,{core:u,patToken:x,handshakeBase:_,ppeOverride:v})}catch(q){if(q instanceof A)return{ok:!1,code:q.code,message:q.message};throw q}}},{method:"POST",path:"/reload",handler:async C=>{let z=C?.agent_id,q=await u.reloadAgents(z);return j.info("IPC /reload: recycled agent subprocesses",{agentId:z??"(all)",recycled:q}),{ok:!0,recycled:q}}},{method:"POST",path:"/shutdown",handler:async()=>(j.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:se,token:X}=await V.start();try{await Ap(t.libEntry,t)}catch(C){j.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await u.start(),lI({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new er().detectAll(),await ts(o),o.frameworksCache)}).catch(C=>j.warn("startup warmup error (ignored)",{err:String(C)})),Ql().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(fn(),Yl));for(let z of["claude-code","codex"]){let q=await C(z);q&&j.info("acp wrapper version",{framework:z,version:q})}}).catch(C=>j.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let re=null,ae={port:se,token:X,core:u,ipc:V,shutdown(C){return re||(j.info("daemon shutdown",{reason:C}),re=(async()=>{b?.stop(),S?.stop(),await u.stop(C),await V.stop(),await e.release()})(),re)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{ae.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>Q0()),process.on("unhandledRejection",C=>{j.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{j.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
127
- `)}catch{}process.exit(1)}),j.info("daemon ready",{port:se,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),fI({cliSpawned:process.env[xs]==="1",readPatToken:()=>ga(t),connect:R}).catch(C=>j.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),ae}async function aI(t){return ks(t).length>0}function ba(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Pp(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function cI(t,e){let n=ks(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>($t(),Cs));for(let a of n){await o(a,t).catch(d=>j.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),j.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),j.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){j.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function dI(t,e,n,i,o){let{loadAgentConfig:a}=await Promise.resolve().then(()=>($t(),Cs)),d=await a(t,e);if(d){if(d.deletedAt)throw new A("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);j.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=Op(d),m={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...p?{_meta:p}:{}};return await n.createAgent(m),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}j.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new A("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(f);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function lI(t){let e=t.logger??j;try{let n=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(n??{})})}catch(n){e.warn("framework detection failed (using cached)",{err:String(n)})}await cI(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Ea(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await uI(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Ea(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>($t(),Cs));j.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){j.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){j.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){j.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{j.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=Op(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),a+=1}catch(x){j.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return j.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function uI(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let o of n)try{(await H0(o,t)).status==="refreshed"&&(i+=1)}catch(a){j.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(a)})}return i>0&&j.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function fI(t){let e=t.logger??j;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function Op(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}_a();Pe();import{readFile as Lp}from"node:fs/promises";var an=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let n=await va(this.paths);if(!n)return{kind:"not-running"};try{let i=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...n,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:xI(i)}}}async request(e){let n=await va(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let a=new AbortController,d=setTimeout(()=>a.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:o,body:i?JSON.stringify(n.body):void 0,signal:a.signal}),f=await u.text();return{status:u.status,body:hI(f)}}finally{clearTimeout(d)}}};async function va(t){try{let[e,n]=await Promise.all([Lp(t.portFile,"utf8"),Lp(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=n.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function hI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function xI(t){return t instanceof Error?t.message:String(t)}en();te();fr();import{spawn as pI}from"node:child_process";import{userInfo as Mp}from"node:os";var fl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",gI=new Set(["bash","zsh","sh","dash","ksh"]),Np=Xe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),mI=2e3;function wI(t,e=fl){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let o=t.slice(n+e.length,i),a={};for(let d of o.split(`
128
- `)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function _I(){let t=(process.env.SHELL??"").trim()||(Mp().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return gI.has(e)?t:null}function yI(t){return new Promise(e=>{let n=`printf '%s' '${fl}'; env; printf '%s' '${fl}'`,i;try{i=pI(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Mp().homedir}})}catch{e(null);return}let o="",a=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{a||(a=!0,clearTimeout(f),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{o+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),Np),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},Np+mI)})}async function hl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=_I();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??yI)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=wI(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Pe();function On(t,...e){let n=[],i;for(let o=0;o<t.length;o++){let a=t[o],d=!1;for(let u of e){if(a===u){i=t[o+1],o+=1,d=!0;break}if(a.startsWith(`${u}=`)){i=a.slice(u.length+1),d=!0;break}}d||n.push(a)}return{value:i,rest:n}}fn();import{chmod as bI,copyFile as Bp,mkdir as zp,readFile as gs,rename as Fp,rm as gl,stat as Up,writeFile as EI}from"node:fs/promises";import{homedir as aO}from"node:os";import{dirname as vI,join as Be,resolve as ml,sep as ps}from"node:path";import{fileURLToPath as SI}from"node:url";en();te();Pe();function ri(t,e,n,i){st(t.bridgeLogsDir,e,"dist-install",n,i)}function Hp(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function II(){return{darwin:{arm64:Be("vendor","aarch64-apple-darwin","bin","codex"),x64:Be("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Be("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Be("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Be("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Be("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function AI(t){let e=SI(t),n=vI(e),i=`${ps}src${ps}`;if(n.includes(i)||n.endsWith(`${ps}src${ps}cli`))return null;let o=ml(n,"index.js"),a=ml(n,"..","package.json");return{dist:o,pkgJson:a}}async function wl(t={}){let e=t.paths??Z(),n=AI(import.meta.url),i=t.sourceDist??n?.dist,o=t.sourcePackageJson??n?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let a,d;try{let b=JSON.parse(await gs(o,"utf8"));a=b.version??"unknown",d=b.dependencies??{}}catch(b){throw ri(e,"error","cannot read source package.json",{err:String(b)}),new Error(`cannot read source package.json: ${String(b)}`,{cause:b})}let u=Is.map(b=>({name:b,spec:d[b]??"latest"})),f=u.map(({name:b,spec:S})=>`${b}@${S}`),x=await Wo(e.configFile)??{},p=x.libVersion,m=await gs(e.libEntry).then(()=>!0).catch(()=>!1),v=p===a,_=await Gp(e,u);if(v&&m&&_)return{kind:"already-current",libVersion:a};if(!v||!m){await zp(e.libDir,{recursive:!0}),await Bp(i,e.libEntry),await Bp(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let b=ml(e.libDir,"package.json"),S=`${JSON.stringify({type:"module"},null,2)}
129
- `;await gs(b,"utf8").catch(()=>null)!==S&&await EI(b,S)}return _||(t.installWrappers?await t.installWrappers(e,f):await CI(e,f,u)),x.libVersion=a,await ts(x,e.configFile),ri(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:a}),v&&m?{kind:"already-current",libVersion:a}:p?{kind:"version-changed",fromVersion:p,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function Gp(t,e){for(let n of e){let i=Be(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await gs(i,"utf8"))}catch(d){return ri(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let a=o.version;if(!a)return ri(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!kI(a,n.spec))return ri(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await qp(Be(t.libDir,"node_modules"))}function kI(t,e){let n=xl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=xl(i.slice(1));if(!a)return!0;if(pl(n,a)<0)return!1;let d=TI(a);return pl(n,d)<0}let o=xl(i);return o?pl(n,o)===0:!0}function TI(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function xl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function pl(t,e){for(let n=0;n<3;n++){let i=(t[n]??0)-(e[n]??0);if(i!==0)return i}return 0}async function CI(t,e,n){await DI(t.installLock,async()=>{if(await Gp(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ps}.staging-${process.pid}-${i}`,a=Be(o,"node_modules"),d=Be(t.libDir,"node_modules");try{await zp(o,{recursive:!0}),await RI(e,o),await PI(a);let u=`${d}.trash-${i}`;await Fp(d,u).catch(()=>{}),await Fp(a,d),await gl(u,{recursive:!0,force:!0}).catch(()=>{}),ri(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await gl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function RI(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let a=at("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),a.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function PI(t){for(let e of Is){let n=Be(t,...e.split("/")),i=JSON.parse(await gs(Be(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let a=Be(t,".bin",o),d=await Up(a);process.platform!=="win32"&&!(d.mode&73)&&await bI(a,d.mode|73).catch(()=>{})}if(!await qp(t)){let e=Hp()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function qp(t){let e=Hp(),n=II();if(!e||!n)return!0;let i=Be(t,"@openai","codex"),o=Be(t,...e.split("/")),a=[Be(i,"package.json"),Be(i,"bin","codex.js"),Be(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Be(o,"package.json"),Be(o,n)];return(await Promise.all(a.map(u=>Up(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function DI(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(a=>setTimeout(a,500))}try{return await e()}finally{i&&await gl(t,{force:!0}).catch(()=>{})}}Wa();te();Pe();import{closeSync as Wp,fstatSync as Kp,openSync as $p,readFileSync as OI,readSync as LI,readdirSync as NI,statSync as MI}from"node:fs";import{join as Sa}from"node:path";var BI=new Set(["debug","info","warn","error"]);function Vp(t){let e=t,n=On(e,"--agent-id");e=n.rest;let i=On(e,"--date");e=i.rest;let o=On(e,"-n","--lines");e=o.rest;let a=On(e,"--level");e=a.rest;let d=On(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=a.value&&BI.has(a.value)?a.value:void 0,p={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(p.agentId=n.value),i.value&&(p.date=i.value),x&&(p.level=x),d.value&&(p.grep=d.value),p}function FI(t,e){return t.agentId?Sa(Re(t.agentId,e).logs,hr("agent",t.date)):Sa(e.bridgeLogsDir,hr("bridge",t.date))}function zI(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function UI(t,e){let n;try{n=NI(t)}catch{return[]}let i=[];for(let o of n){let a=ja(o,e);if(!a)continue;let d=0;try{d=MI(Sa(t,o)).size}catch{}i.push({file:Sa(t,o),date:a,size:d})}return i.sort((o,a)=>a.date.localeCompare(o.date)),i}function Zp(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let n;try{n=JSON.parse(t).level}catch{return!0}if(typeof n=="string"&&!Kl(n,e.level))return!1}return!0}var jp={debug:"90",info:"36",warn:"33",error:"31"},HI=new Set(["ts","level","module","msg"]);function GI(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Jp(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=GI(n.ts),o=typeof n.level=="string"?n.level:"",a=o.toUpperCase().padEnd(5);e.color&&jp[o]&&(a=`\x1B[${jp[o]}m${a}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",f=Object.entries(n).filter(([x])=>!HI.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${a} ${d} ${u}${f}`}function qI(t,e,n){let a=OI(t,"utf8").split(`
130
- `).filter(d=>d.length>0).filter(d=>Zp(d,{level:e.level,grep:e.grep}));for(let d of zI(a,e.lines))process.stdout.write(`${Jp(d,{raw:e.raw,color:n})}
131
- `)}async function Yp(t,e){let n=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Re(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=UI(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
125
+ `)}catch{}}let e=new Ia({processTitle:Jr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await dr(),s=i??{};Ps({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let a=new Ea(new li),d=new Xo;await d.loadFromDisk().catch(C=>G.warn("modelListCache.loadFromDisk failed (ignored)",{err:String(C)}));let u=null,f=new Qo({upstream:a,paths:t,bridgeConfig:s,modelListCache:d,sessionSpawner:async(C,q,F,pe,de,xe)=>{if(!u)throw new Error("agentManager not ready");return u.spawnSessionDownstream(C,q,F,pe,de,xe)}}),x=new Zo({paths:t,config:s,registry:f});u=x;let p,m,b=null,y={},v,I=null,A=null,T=null,R=new Wt;function E(C,q){return R.enqueue(()=>D(C,q))}function P(){A||(A=new ka({isConnected:()=>a.isConnected()&&!(I?.isLivenessLost()??!1),forceReconnect:()=>T?E(T,{force:!0}):void 0,onFatal:C=>{if(process.env[Es]==="1"){G.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}G.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),A.start()}async function D(C,q){let F=C,pe=F?.privatecode;if(!pe)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let de=es(F.env),xe=F.handshake_url,Rt=F.frontier_url,dt=ng(F.env,xe,Rt);if(T=F,!q?.force&&p===pe&&m===dt){let ze=await KI(t);return f.agents.size===0&&ze?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ca(t,x).catch(De=>G.warn("connect-noop auto-revive error (ignored)",{err:String(De)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let gn=!!p&&p!==pe,Yt=m!==void 0&&m!==dt,mn=gn||Yt,zn=await md({privatecode:pe,...xe?{endpoint:xe}:{},ppeOverride:de});if(mn){G.warn("connect config switched, resetting agents",{pcChanged:gn,envChanged:Yt,previousPc:p?Ta(p):"",nextPc:Ta(pe)});for(let ze of[...f.agents.values()])await ze.dispose("connect config switch").catch(()=>{}),f.agents.delete(ze.agentId);f.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:f.disconnectedAgents.size}),f.disconnectedAgents.clear()),await a.swap(new li,"connect switch").catch(()=>{})}b=zn.deviceId,Ps({deviceId:b,pid:process.pid}),jd({patToken:pe,env:F.env}).catch(ze=>G.warn("coze-cli setup error (ignored)",{err:String(ze)}));let Dt=new _s({handshake:zn,privatecode:pe,...Rt?{urlOverride:Rt}:{},ppeOverride:de,getPatTokenForAgent:ze=>f.agents.get(ze)?.patToken});return await a.swap(Dt,"connect"),p=pe,m=dt,y=de,v=xe,F.mock_scenario!==void 0&&(f.setMockScenario(F.mock_scenario),G.info("mock scenario set",{scenario:F.mock_scenario})),I||(I=new rs({core:f,getDeviceId:()=>b??"",onTickEnd:()=>V.retryPending().catch(ze=>G.warn("detailSync.retryPending failed (ignored)",{err:String(ze)})),onAuthFailures:$})),I.start(),P(),mn&&Ca(t,x).catch(ze=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(ze)})),bs(pe,t).catch(ze=>G.warn("writePatToken after /connect failed (ignored)",{err:String(ze)})),G.info("/connect: WS established",{deviceId:b}),{ok:!0,note:"connected"}}f.registerExtension("_agent/create",async C=>x.createAgent(C.params)),f.registerExtension("_agent/health",async()=>({ok:!0}));let z={},N=new Lo({agents:f.agents,modelListCache:d,openclawModelLister:async()=>{let C=s.frameworksCache?.openclaw?.path;return C?V0(C):null},paths:t,publishSkillToMarketplace:async C=>{let q=f.agents.get(C.agentId)?.patToken??p;if(!q)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Zp({patToken:q,zip:C.zip,...C.skillId?{skillId:C.skillId}:{},skillName:C.skillName,...C.description?{description:C.description}:{},agentId:C.agentId,...C.accountId?{accountId:C.accountId}:{}},{handshakeBase:v,ppeOverride:y})},disposeAndMarkDisconnected:async(C,q)=>{let F=f.agents.get(C);if(F){await x.cleanupOpenclawSessionProviders(F).catch(de=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(de)})),F.framework==="hermes"&&F.deployType==="cloud"&&await Sd(C,t).catch(de=>G.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(de)}));let pe=!0;try{await F.dispose(`disconnect: ${q}`)}catch(de){pe=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(de)}),F.status="error"}pe&&(F.status="disconnected",f.unregister(C),f.disconnectedAgents.add(C))}else f.disconnectedAgents.add(C)},disposeForDelete:async(C,q)=>{let F=f.agents.get(C);F&&(await x.cleanupOpenclawSessionProviders(F).catch(pe=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(pe)})),F.framework==="hermes"&&F.deployType==="cloud"&&await Sd(C,t).catch(pe=>G.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(pe)})),await F.dispose(`delete: ${q}`).catch(pe=>G.warn("dispose during delete failed (ignored)",{agentId:C,err:String(pe)})),f.unregister(C)),f.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!z.ref)throw new Error("agent-detail-sync not initialized yet");await z.ref.syncOne(C)},cleanupOpenclawProviders:async(C,q)=>{await x.cleanupOpenclawSessionProviders(C,q)},openclawRepair:async(C,q)=>{await x.openclawRepair(C,q)},hermesReset:async(C,q)=>{let F=await me(C).catch(()=>null);!F||F.framework!=="hermes"||F.deployType!=="cloud"||await G0({paths:t,agentId:C,model:F.model,modelInfo:F.modelInfo,cozeEnv:q,mockScenario:f.getMockScenario()})},isRuntimePendingPermission:C=>f.hasPendingPermissionFor(C)});f.registerExtension("_agent/listSkills",C=>N.listSkills(C.params)),f.registerExtension("_agent/addSkills",C=>N.addSkills(C.params)),f.registerExtension("_agent/removeSkills",C=>N.removeSkills(C.params)),f.registerExtension("_agent/publishSkill",C=>N.publishSkill(C.params)),f.registerExtension("_agent/getFileTree",C=>N.getFileTree(C.params)),f.registerExtension("_agent/getFileContent",C=>N.getFileContent(C.params)),f.registerExtension("_agent/update",C=>N.updateAgent(C.params)),f.registerExtension("_agent/disconnect",C=>N.disconnectAgent(C.params)),f.registerExtension("_agent/switchModel",C=>N.switchModel(C.params)),f.registerExtension("_agent/setConfigOption",C=>N.setConfigOption(C.params)),f.registerExtension("_agent/listAvailableModels",C=>N.listAvailableModels(C.params)),f.registerExtension("_agent/detail",C=>N.detail(C.params)),f.registerExtension("_agent/reset",C=>N.resetAgent(C.params)),f.registerExtension("_agent/repair",C=>N.repairAgent(C.params)),f.registerExtension("_agent/delete",C=>N.deleteAgent(C.params)),f.registerExtension("_agent/upgrade",C=>N.upgradeBridge(C.params));let V=new Bs({paths:t,handlers:N,agentManager:x,sendDetail:C=>f.sendRequest("_agent/detail",C)});z.ref=V;let $=async C=>{await Promise.allSettled(C.map(async q=>{try{await N.disconnectAgent({agentId:q.agentId,reason:`auth_failure: code=${q.code} ${q.message}`}),G.info("agent disconnected due to auth failure from heartbeat response",{agentId:q.agentId,code:q.code,message:q.message})}catch(F){G.warn("disconnect during authFailure handling failed (ignored)",{agentId:q.agentId,err:String(F)})}}))};a.onConnect(({initial:C})=>{G.info("frontier upstream connected, triggering detail sync",{initial:C}),V.syncAll(C?"initial-connect":"reconnect").catch(q=>G.warn("detail sync top-level error (ignored)",{err:String(q)}))});let se=new ea({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=f.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[Es]==="1"?"manual":"supervisor",agents:[...f.agents.keys()],deviceId:b??"",frameworksCache:s.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let q=C,F=q?.privatecode,pe=q?.pairing_code;if(!F||!pe)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let de=es(q.env),xe=q.handshake_url,Rt=q.frontier_url,dt=ng(q.env,xe,Rt),gn=!!p&&p!==F,Yt=m!==void 0&&m!==dt,mn=gn||Yt,zn=await md({privatecode:F,...xe?{endpoint:xe}:{},ppeOverride:de});if(mn){G.warn("pair config switched, resetting agents",{pcChanged:gn,envChanged:Yt,previousPc:p?Ta(p):"",nextPc:Ta(F),previousEnvKey:m??"",nextEnvKey:dt});for(let De of[...f.agents.values()])await De.dispose("pair config switch").catch(()=>{}),f.agents.delete(De.agentId);f.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on pair config switch",{count:f.disconnectedAgents.size}),f.disconnectedAgents.clear()),await a.swap(new li,"pair switch").catch(()=>{})}b=zn.deviceId,Ps({deviceId:b,pid:process.pid}),jd({patToken:F,env:q.env}).catch(De=>G.warn("coze-cli setup error (ignored)",{err:String(De)}));let Dt=new _s({handshake:zn,privatecode:F,...Rt?{urlOverride:Rt}:{},ppeOverride:de,getPatTokenForAgent:De=>f.agents.get(De)?.patToken});await a.swap(Dt,"pair");try{let De=new ar;s.frameworksCache=await De.detectAll(),await lr(s),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(De){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(De)})}let ze=Object.keys(s.frameworksCache??{});try{let De=await f.sendRequest("_agent/pair",{pairCode:pe,patToken:F,frameworks:ze,_meta:{cozeDeviceId:b}});G.info("_agent/pair ok",{pairResult:De}),p=F,m=dt,y=de,v=xe,q.mock_scenario!==void 0&&(f.setMockScenario(q.mock_scenario),G.info("mock scenario set",{scenario:q.mock_scenario})),bs(F,t).catch(te=>G.warn("writePatToken after /pair failed (ignored)",{err:String(te)})),I||(I=new rs({core:f,getDeviceId:()=>b??"",onTickEnd:()=>V.retryPending().catch(te=>G.warn("detailSync.retryPending failed (ignored)",{err:String(te)})),onAuthFailures:$})),I.start(),P(),mn&&Ca(t,x).catch(te=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(te)}));let xt;return q.agent_id&&(xt=await $I(q.agent_id,t,x,te=>f.sendRequest("_agent/detail",te),F).catch(te=>(G.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(te)}),{ok:!1,agentId:q.agent_id??"",note:String(te)}))),{ok:!0,note:"paired with cloud",...xt?{agent:xt}:{}}}catch(De){return G.error("_agent/pair failed",{err:String(De)}),{ok:!1,note:`pair failed: ${String(De)}`}}}},{method:"POST",path:"/connect",handler:C=>E(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let q=C;return{ok:!0,result:await x.createAgent(q)}}},{method:"POST",path:"/agent/send",handler:async C=>{let q=C;if(!q?.agentId||!q?.sessionId||!q?.kind||!q?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!p)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let F=q;return await(F.groupFile?dx:cx)(F,{core:f,patToken:p,handshakeBase:v,ppeOverride:y})}catch(F){if(F instanceof k)return{ok:!1,code:F.code,message:F.message};throw F}}},{method:"POST",path:"/reload",handler:async C=>{let q=C?.agent_id,F=await f.reloadAgents(q);return G.info("IPC /reload: recycled agent subprocesses",{agentId:q??"(all)",recycled:F}),{ok:!0,recycled:F}}},{method:"POST",path:"/shutdown",handler:async()=>(G.info("IPC /shutdown received"),setImmediate(()=>{Se.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:Q,token:ce}=await se.start();try{await Yp(t.libEntry,t)}catch(C){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await f.start(),VI({paths:t,core:f,agentManager:x,detectAll:async()=>(s.frameworksCache=await new ar().detectAll(),await lr(s),s.frameworksCache)}).catch(C=>G.warn("startup warmup error (ignored)",{err:String(C)})),cu().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(_n(),ou));for(let q of["claude-code","codex"]){let F=await C(q);F&&G.info("acp wrapper version",{framework:q,version:F})}}).catch(C=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let ae=null,Se={port:Q,token:ce,core:f,ipc:se,shutdown(C){return ae||(G.info("daemon shutdown",{reason:C}),ae=(async()=>{I?.stop(),A?.stop(),await f.stop(C),await se.stop(),await e.release()})(),ae)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{Se.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>Eh()),process.on("unhandledRejection",C=>{G.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{G.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
126
+ `)}catch{}process.exit(1)}),G.info("daemon ready",{port:Q,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),JI({cliSpawned:process.env[Es]==="1",readPatToken:()=>va(t),connect:E}).catch(C=>G.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),Se}async function KI(t){return Ls(t).length>0}function Ta(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function ng(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function WI(t,e){let n=Ls(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(Qt(),Ms));for(let a of n){await s(a,t).catch(d=>G.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),G.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),G.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){G.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function $I(t,e,n,i,s){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(Qt(),Ms)),d=await a(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);G.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=ig(d),m={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...s?{patToken:s}:{},...p?{_meta:p}:{}};return await n.createAgent(m),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}G.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...s?{patToken:s}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(f);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function VI(t){let e=t.logger??G;try{let n=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(n??{})})}catch(n){e.warn("framework detection failed (using cached)",{err:String(n)})}await WI(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Ca(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await ZI(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Ca(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(Qt(),Ms));G.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=0;for(let u of i){let f;try{f=await s(u,t)}catch(x){G.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){G.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){G.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{G.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=ig(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),a+=1}catch(x){G.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return G.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function ZI(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let s of n)try{(await lh(s,t)).status==="refreshed"&&(i+=1)}catch(a){G.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(a)})}return i>0&&G.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function JI(t){let e=t.logger??G;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function ig(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Aa();Pe();import{readFile as sg}from"node:fs/promises";var pn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let n=await Pa(this.paths);if(!n)return{kind:"not-running"};try{let i=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...n,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:XI(i)}}}async request(e){let n=await Pa(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,s={Authorization:`Bearer ${e.token}`};i&&(s["content-type"]="application/json");let a=new AbortController,d=setTimeout(()=>a.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:s,body:i?JSON.stringify(n.body):void 0,signal:a.signal}),f=await u.text();return{status:u.status,body:YI(f)}}finally{clearTimeout(d)}}};async function Pa(t){try{let[e,n]=await Promise.all([sg(t.portFile,"utf8"),sg(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),s=n.trim();return!Number.isFinite(i)||i<=0||!s?null:{port:i,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}function YI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function XI(t){return t instanceof Error?t.message:String(t)}an();re();_r();import{spawn as QI}from"node:child_process";import{userInfo as ag}from"node:os";var bl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",eA=new Set(["bash","zsh","sh","dash","ksh"]),og=Ze("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),tA=2e3;function nA(t,e=bl){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let s=t.slice(n+e.length,i),a={};for(let d of s.split(`
127
+ `)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function rA(){let t=(process.env.SHELL??"").trim()||(ag().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return eA.has(e)?t:null}function iA(t){return new Promise(e=>{let n=`printf '%s' '${bl}'; env; printf '%s' '${bl}'`,i;try{i=QI(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ag().homedir}})}catch{e(null);return}let s="",a=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{a||(a=!0,clearTimeout(f),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{s+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(s.length>0?s:null));let f=setTimeout(()=>d("SIGTERM"),og),x=setTimeout(()=>{d("SIGKILL"),u(s.length>0?s:null)},og+tA)})}async function El(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=rA();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??iA)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=nA(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Pe();function Fn(t,...e){let n=[],i;for(let s=0;s<t.length;s++){let a=t[s],d=!1;for(let u of e){if(a===u){i=t[s+1],s+=1,d=!0;break}if(a.startsWith(`${u}=`)){i=a.slice(u.length+1),d=!0;break}}d||n.push(a)}return{value:i,rest:n}}_n();import{chmod as sA,copyFile as cg,mkdir as lg,readFile as Ss,rename as dg,rm as Il,stat as ug,writeFile as oA}from"node:fs/promises";import{homedir as h3}from"node:os";import{dirname as aA,join as Fe,resolve as Al,sep as vs}from"node:path";import{fileURLToPath as cA}from"node:url";an();re();Pe();function ui(t,e,n,i){ot(t.bridgeLogsDir,e,"dist-install",n,i)}function fg(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function dA(){return{darwin:{arm64:Fe("vendor","aarch64-apple-darwin","bin","codex"),x64:Fe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Fe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Fe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Fe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Fe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function lA(t){let e=cA(t),n=aA(e),i=`${vs}src${vs}`;if(n.includes(i)||n.endsWith(`${vs}src${vs}cli`))return null;let s=Al(n,"index.js"),a=Al(n,"..","package.json");return{dist:s,pkgJson:a}}async function kl(t={}){let e=t.paths??Z(),n=lA(import.meta.url),i=t.sourceDist??n?.dist,s=t.sourcePackageJson??n?.pkgJson;if(!i||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let a,d;try{let v=JSON.parse(await Ss(s,"utf8"));a=v.version??"unknown",d=v.dependencies??{}}catch(v){throw ui(e,"error","cannot read source package.json",{err:String(v)}),new Error(`cannot read source package.json: ${String(v)}`,{cause:v})}let u=Ds.map(v=>({name:v,spec:d[v]??"latest"})),f=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await dr(e.configFile)??{},p=x.libVersion,m=await Ss(e.libEntry).then(()=>!0).catch(()=>!1),b=p===a,y=await hg(e,u);if(b&&m&&y)return{kind:"already-current",libVersion:a};if(!b||!m){await lg(e.libDir,{recursive:!0}),await cg(i,e.libEntry),await cg(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Al(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
128
+ `;await Ss(v,"utf8").catch(()=>null)!==I&&await oA(v,I)}return y||(t.installWrappers?await t.installWrappers(e,f):await hA(e,f,u)),x.libVersion=a,await lr(x,e.configFile),ui(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:a}),b&&m?{kind:"already-current",libVersion:a}:p?{kind:"version-changed",fromVersion:p,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function hg(t,e){for(let n of e){let i=Fe(t.libDir,"node_modules",...n.name.split("/"),"package.json"),s;try{s=JSON.parse(await Ss(i,"utf8"))}catch(d){return ui(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let a=s.version;if(!a)return ui(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!uA(a,n.spec))return ui(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await xg(Fe(t.libDir,"node_modules"))}function uA(t,e){let n=vl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=vl(i.slice(1));if(!a)return!0;if(Sl(n,a)<0)return!1;let d=fA(a);return Sl(n,d)<0}let s=vl(i);return s?Sl(n,s)===0:!0}function fA(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function vl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Sl(t,e){for(let n=0;n<3;n++){let i=(t[n]??0)-(e[n]??0);if(i!==0)return i}return 0}async function hA(t,e,n){await gA(t.installLock,async()=>{if(await hg(t,n))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${vs}.staging-${process.pid}-${i}`,a=Fe(s,"node_modules"),d=Fe(t.libDir,"node_modules");try{await lg(s,{recursive:!0}),await xA(e,s),await pA(a);let u=`${d}.trash-${i}`;await dg(d,u).catch(()=>{}),await dg(a,d),await Il(u,{recursive:!0,force:!0}).catch(()=>{}),ui(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Il(s,{recursive:!0,force:!0}).catch(()=>{})}})}function xA(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,s)=>{let a=ct("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",f=>{clearTimeout(u),s(new Error(`spawn npm failed: ${String(f)}`))}),a.once("close",f=>{clearTimeout(u),f===0?i():s(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function pA(t){for(let e of Ds){let n=Fe(t,...e.split("/")),i=JSON.parse(await Ss(Fe(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let s=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!s)throw new Error(`${e}: package.json \u7F3A bin`);let a=Fe(t,".bin",s),d=await ug(a);process.platform!=="win32"&&!(d.mode&73)&&await sA(a,d.mode|73).catch(()=>{})}if(!await xg(t)){let e=fg()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function xg(t){let e=fg(),n=dA();if(!e||!n)return!0;let i=Fe(t,"@openai","codex"),s=Fe(t,...e.split("/")),a=[Fe(i,"package.json"),Fe(i,"bin","codex.js"),Fe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Fe(s,"package.json"),Fe(s,n)];return(await Promise.all(a.map(u=>ug(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function gA(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let s=0;s<60&&!i;s++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(a=>setTimeout(a,500))}try{return await e()}finally{i&&await Il(t,{force:!0}).catch(()=>{})}}Xa();re();Pe();import{closeSync as gg,fstatSync as mg,openSync as wg,readFileSync as mA,readSync as wA,readdirSync as yA,statSync as _A}from"node:fs";import{join as Ra}from"node:path";var bA=new Set(["debug","info","warn","error"]);function yg(t){let e=t,n=Fn(e,"--agent-id");e=n.rest;let i=Fn(e,"--date");e=i.rest;let s=Fn(e,"-n","--lines");e=s.rest;let a=Fn(e,"--level");e=a.rest;let d=Fn(e,"--grep");e=d.rest;let u=s.value===void 0?200:Number(s.value),f=Number.isInteger(u)&&u>=0?u:200,x=a.value&&bA.has(a.value)?a.value:void 0,p={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(p.agentId=n.value),i.value&&(p.date=i.value),x&&(p.level=x),d.value&&(p.grep=d.value),p}function EA(t,e){return t.agentId?Ra(Le(t.agentId,e).logs,br("agent",t.date)):Ra(e.bridgeLogsDir,br("bridge",t.date))}function vA(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function SA(t,e){let n;try{n=yA(t)}catch{return[]}let i=[];for(let s of n){let a=Ya(s,e);if(!a)continue;let d=0;try{d=_A(Ra(t,s)).size}catch{}i.push({file:Ra(t,s),date:a,size:d})}return i.sort((s,a)=>a.date.localeCompare(s.date)),i}function _g(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let n;try{n=JSON.parse(t).level}catch{return!0}if(typeof n=="string"&&!tu(n,e.level))return!1}return!0}var pg={debug:"90",info:"36",warn:"33",error:"31"},IA=new Set(["ts","level","module","msg"]);function AA(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function bg(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=AA(n.ts),s=typeof n.level=="string"?n.level:"",a=s.toUpperCase().padEnd(5);e.color&&pg[s]&&(a=`\x1B[${pg[s]}m${a}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",f=Object.entries(n).filter(([x])=>!IA.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${a} ${d} ${u}${f}`}function kA(t,e,n){let a=mA(t,"utf8").split(`
129
+ `).filter(d=>d.length>0).filter(d=>_g(d,{level:e.level,grep:e.grep}));for(let d of vA(a,e.lines))process.stdout.write(`${bg(d,{raw:e.raw,color:n})}
130
+ `)}async function Eg(t,e){let n=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Le(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=SA(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
132
131
  `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
133
- `);return 0}let o=t.date??Nn(new Date),a=FI({agentId:t.agentId,date:o},n);try{qI(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
132
+ `);return 0}let s=t.date??Hn(new Date),a=EA({agentId:t.agentId,date:s},n);try{kA(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
134
133
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
135
134
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
136
- `),1}return t.follow&&await KI(a,t,i),0}var jI=500;function WI(t){try{let e=$p(t,"r");try{return Kp(e).size}finally{Wp(e)}}catch{return 0}}async function KI(t,e,n){let i=WI(t),o="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let f=$p(t,"r");try{let x=Kp(f).size;if(x>i){let p=Buffer.allocUnsafe(x-i),m=LI(f,p,0,p.length,i);u=p.subarray(0,m).toString("utf8"),i+=m}}finally{Wp(f)}}catch{}if(u){let f=(o+u).split(`
137
- `);o=f.pop()??"";for(let x of f)x.length>0&&Zp(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Jp(x,{raw:e.raw,color:n})}
138
- `)}await new Promise(f=>setTimeout(f,jI))}}finally{process.off("SIGINT",d)}}import{basename as $I,resolve as VI}from"node:path";Pe();var ZI=9e4,JI={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 YI(t){return JI[t]??1}async function Xp(t,e={}){let n=e.paths??Z();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
135
+ `),1}return t.follow&&await PA(a,t,i),0}var TA=500;function CA(t){try{let e=wg(t,"r");try{return mg(e).size}finally{gg(e)}}catch{return 0}}async function PA(t,e,n){let i=CA(t),s="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let f=wg(t,"r");try{let x=mg(f).size;if(x>i){let p=Buffer.allocUnsafe(x-i),m=wA(f,p,0,p.length,i);u=p.subarray(0,m).toString("utf8"),i+=m}}finally{gg(f)}}catch{}if(u){let f=(s+u).split(`
136
+ `);s=f.pop()??"";for(let x of f)x.length>0&&_g(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${bg(x,{raw:e.raw,color:n})}
137
+ `)}await new Promise(f=>setTimeout(f,TA))}}finally{process.off("SIGINT",d)}}import{basename as RA,resolve as DA}from"node:path";Pe();var OA=9e4,LA={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,CAPABILITY_UNSUPPORTED: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 NA(t){return LA[t]??1}async function vg(t,e={}){let n=e.paths??Z();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
139
138
  `),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.
140
- `),3;let i=await va(n).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${n.portFile} / ${n.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
141
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:VI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},a;try{a=await XI(i,"/agent/send",o,ZI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
139
+ `),3;let i=await Pa(n).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${n.portFile} / ${n.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
140
+ `),4;let s={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:DA(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},a;try{a=await MA(i,"/agent/send",s,OA)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
142
141
  `),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
143
- `),YI(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
144
- `);else{let d=t.name??$I(o.path);if(t.groupFile){let u=a.uri.length>60?`${a.uri.slice(0,57)}...`:a.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
145
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${QI(a.bytes)})
146
- `)}return 0}async function XI(t,e,n,i){let o=new AbortController,a=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:o.signal}),u=await d.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(a)}}function QI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var cg=G("cli");function Ze(t,e){let{value:n,rest:i}=On(t,e);return{value:n,rest:i}}function Ra(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
147
- `)}function vA(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:R}=Ze(e.slice(1),"--agent-id");return R?{mode:"reload",agentId:R}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return SA(e.slice(1));if(e[0]==="log")return{mode:"log",...Vp(e.slice(1))};if(e[0]==="connect")return IA(e.slice(1));if(e.includes("--status"))return Ra("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ra("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ra("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ra("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:o}=Ze(n,"--pat-token");n=o;let{value:a,rest:d}=Ze(n,"--pair-code");n=d;let{value:u,rest:f}=Ze(n,"--env");n=f;let{value:x,rest:p}=Ze(n,"--handshake-url");n=p;let{value:m,rest:v}=Ze(n,"--frontier-url");n=v;let{value:_,rest:b}=Ze(n,"--mock-scenario");n=b;let{value:S}=Ze(n,"--agent-id"),I=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:a};return u&&(T.env=u),x&&(T.handshakeUrl=x),m&&(T.frontierUrl=m),_&&(T.mockScenario=_),S&&(T.agentId=S),I&&(T.skipRebuildEnv=!0),T}function SA(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:a}=Ze(i,"--caption");i=a;let{value:d,rest:u}=Ze(i,"--name");i=u;let{value:f,rest:x}=Ze(i,"--agent-id");i=x;let{value:p,rest:m}=Ze(i,"--session-id");i=m;let{value:v,rest:_}=Ze(i,"--mime");i=_;let b=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let S=i.includes("--json"),I={mode:"send",kind:e,path:n,json:S};return o&&(I.caption=o),d&&(I.name=d),f&&(I.agentId=f),p&&(I.sessionId=p),b&&(I.groupFile=!0),v&&(I.mimeType=v),I}function IA(t){let e=t,{value:n,rest:i}=Ze(e,"--pat-token");e=i;let{value:o,rest:a}=Ze(e,"--env");e=a;let{value:d,rest:u}=Ze(e,"--handshake-url");e=u;let{value:f,rest:x}=Ze(e,"--frontier-url");e=x;let{value:p,rest:m}=Ze(e,"--mock-scenario");e=m;let v=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),d&&(_.handshakeUrl=d),f&&(_.frontierUrl=f),p&&(_.mockScenario=p),v&&(_.skipRebuildEnv=!0),_}var AA=`
142
+ `),NA(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
143
+ `);else{let d=t.name??RA(s.path);if(t.groupFile){let u=a.uri.length>60?`${a.uri.slice(0,57)}...`:a.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
144
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${BA(a.bytes)})
145
+ `)}return 0}async function MA(t,e,n,i){let s=new AbortController,a=setTimeout(()=>s.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:s.signal}),u=await d.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(a)}}function BA(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Og=H("cli");function Ve(t,e){let{value:n,rest:i}=Fn(t,e);return{value:n,rest:i}}function Ba(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
146
+ `)}function ak(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:R}=Ve(e.slice(1),"--agent-id");return R?{mode:"reload",agentId:R}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return ck(e.slice(1));if(e[0]==="log")return{mode:"log",...yg(e.slice(1))};if(e[0]==="connect")return dk(e.slice(1));if(e.includes("--status"))return Ba("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ba("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ba("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ba("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:s}=Ve(n,"--pat-token");n=s;let{value:a,rest:d}=Ve(n,"--pair-code");n=d;let{value:u,rest:f}=Ve(n,"--env");n=f;let{value:x,rest:p}=Ve(n,"--handshake-url");n=p;let{value:m,rest:b}=Ve(n,"--frontier-url");n=b;let{value:y,rest:v}=Ve(n,"--mock-scenario");n=v;let{value:I}=Ve(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:a};return u&&(T.env=u),x&&(T.handshakeUrl=x),m&&(T.frontierUrl=m),y&&(T.mockScenario=y),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function ck(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:s,rest:a}=Ve(i,"--caption");i=a;let{value:d,rest:u}=Ve(i,"--name");i=u;let{value:f,rest:x}=Ve(i,"--agent-id");i=x;let{value:p,rest:m}=Ve(i,"--session-id");i=m;let{value:b,rest:y}=Ve(i,"--mime");i=y;let v=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return s&&(A.caption=s),d&&(A.name=d),f&&(A.agentId=f),p&&(A.sessionId=p),v&&(A.groupFile=!0),b&&(A.mimeType=b),A}function dk(t){let e=t,{value:n,rest:i}=Ve(e,"--pat-token");e=i;let{value:s,rest:a}=Ve(e,"--env");e=a;let{value:d,rest:u}=Ve(e,"--handshake-url");e=u;let{value:f,rest:x}=Ve(e,"--frontier-url");e=x;let{value:p,rest:m}=Ve(e,"--mock-scenario");e=m;let b=e.includes("--skip-rebuild-env"),y={mode:"connect"};return n&&(y.privatecode=n),s&&(y.env=s),d&&(y.handshakeUrl=d),f&&(y.frontierUrl=f),p&&(y.mockScenario=p),b&&(y.skipRebuildEnv=!0),y}var lk=`
148
147
  coze-bridge - local bridge daemon for cloud Agent Service
149
148
 
150
149
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -225,52 +224,52 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
225
224
 
226
225
  Internal:
227
226
  <node> <entry> --daemon daemon mode (OS supervisor only)
228
- `.trimStart();async function dg(t=process.argv,e={}){let n=vA(t);switch(n.mode){case"help":return process.stdout.write(AA),0;case"version":return process.stdout.write(`${Bt}
229
- `),0;case"daemon":{try{await Dp()}catch(i){return cg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return kA(e);case"stop":return ug(e);case"reload":return RA(n.agentId,e);case"log":return Yp(n,e);case"update":return TA(e);case"purge":return DA(e);case"service-install":return OA(e);case"service-uninstall":return LA(e);case"pair":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),NA(n.privatecode,n.pairingCode,e,i,n.agentId,n.skipRebuildEnv)}case"connect":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),MA(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return Xp({kind:n.kind,path:n.path,...n.agentId?{agentId:n.agentId}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.caption?{caption:n.caption}:{},...n.name?{name:n.name}:{},...n.groupFile?{groupFile:!0}:{},...n.mimeType?{mimeType:n.mimeType}:{},json:n.json},e)}}async function lg(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 kA(t){let e=t.paths??Z(),n=new an(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
230
- `),1;if(i.kind==="stale")return await lg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
231
- `),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
232
- ${JSON.stringify(o.body,null,2)}
233
- `),0}async function ug(t){let e=t.paths??Z(),n=new an(e),i=t.daemonSweep??(async()=>{let f=eh();return await th(f),f}),o=async()=>{t.skipProcessKill||await i(e)},a=await ws(t),d=!1;if(a)try{await a.uninstall(),d=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
234
- `)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
227
+ `.trimStart();async function Lg(t=process.argv,e={}){let n=ak(t);switch(n.mode){case"help":return process.stdout.write(lk),0;case"version":return process.stdout.write(`${Gt}
228
+ `),0;case"daemon":{try{await rg()}catch(i){return Og.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return uk(e);case"stop":return Mg(e);case"reload":return xk(n.agentId,e);case"log":return Eg(n,e);case"update":return fk(e);case"purge":return gk(e);case"service-install":return mk(e);case"service-uninstall":return wk(e);case"pair":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),yk(n.privatecode,n.pairingCode,e,i,n.agentId,n.skipRebuildEnv)}case"connect":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),_k(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return vg({kind:n.kind,path:n.path,...n.agentId?{agentId:n.agentId}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.caption?{caption:n.caption}:{},...n.name?{name:n.name}:{},...n.groupFile?{groupFile:!0}:{},...n.mimeType?{mimeType:n.mimeType}:{},json:n.json},e)}}async function Ng(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 uk(t){let e=t.paths??Z(),n=new pn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
229
+ `),1;if(i.kind==="stale")return await Ng(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
230
+ `),1;let s=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
231
+ ${JSON.stringify(s.body,null,2)}
232
+ `),0}async function Mg(t){let e=t.paths??Z(),n=new pn(e),i=t.daemonSweep??(async()=>{let f=vh();return await Sh(f),f}),s=async()=>{t.skipProcessKill||await i(e)},a=await As(t),d=!1;if(a)try{await a.uninstall(),d=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
233
+ `)}let u=await n.probe();if(u.kind==="not-running")return await s(),process.stdout.write(d?`coze-bridge: stopped
235
234
  `:`coze-bridge: not running
236
- `),0;if(u.kind==="stale")return await lg(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
237
- `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
238
- `),0}catch(f){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
239
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
240
- `),1)}}async function TA(t){return await ug(t),(t.spawnNpx??CA)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function CA(t){return new Promise(e=>{let n=at("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
241
- `),e(1)})})}async function RA(t,e){let n=new an(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
242
- `),1;try{let o=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let a=o.body.recycled??[];return t&&a.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
235
+ `),0;if(u.kind==="stale")return await Ng(e),await s(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
236
+ `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await s(),process.stdout.write(`coze-bridge: stopped
237
+ `),0}catch(f){return(await n.probe()).kind!=="connected"?(await s(),process.stdout.write(`coze-bridge: stopped
238
+ `),0):(await s(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
239
+ `),1)}}async function fk(t){return await Mg(t),(t.spawnNpx??hk)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function hk(t){return new Promise(e=>{let n=ct("npx",t,{stdio:"inherit"});n.on("exit",i=>e(i??1)),n.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
240
+ `),e(1)})})}async function xk(t,e){let n=new pn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
241
+ `),1;try{let s=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(s.status===200&&s.body?.ok){let a=s.body.recycled??[];return t&&a.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
243
242
  `):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
244
- `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
245
- `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
246
- `),1}}async function ws(t){if(t.supervisor){let a=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:a.platform,install:u=>a.install(d,u),uninstall:()=>a.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(sg(),ig)),i=e(),o=n();return{platform:i.platform,install:a=>i.install(o,a),uninstall:()=>i.uninstall(o)}}async function fg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??BA,a=t.paths??Z();if(n.kind==="connected"){if(!PA(n.body))return n;st(a.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(f=>st(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await ag(a.pidFile,o)}let d=t.spawnDaemon??Rp,u=await ws(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await og(e,i,o);if(f.kind==="connected")return f;st(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(f){st(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}st(a.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await ag(a.pidFile,o)}else u&&await u.install({activate:!1}).catch(f=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(f)}
243
+ `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(s.body)}
244
+ `),1}catch(s){return process.stderr.write(`coze-bridge: reload failed: ${String(s)}
245
+ `),1}}async function As(t){if(t.supervisor){let a=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:a.platform,install:u=>a.install(d,u),uninstall:()=>a.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Pg(),Cg)),i=e(),s=n();return{platform:i.platform,install:a=>i.install(s,a),uninstall:()=>i.uninstall(s)}}async function Bg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,s=t.sleep??bk,a=t.paths??Z();if(n.kind==="connected"){if(!pk(n.body))return n;ot(a.bridgeLogsDir,"warn","cli","daemon Node \u4E0E\u5F53\u524D CLI \u4E0D\u4E00\u81F4, \u91CD\u542F daemon",{currentNode:process.execPath,currentArch:process.arch,daemon:n.body}),await e.request({method:"POST",path:"/shutdown"}).catch(f=>ot(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await Dg(a.pidFile,s)}let d=t.spawnDaemon??tg,u=await As(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await Rg(e,i,s);if(f.kind==="connected")return f;ot(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(f){ot(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}ot(a.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await Dg(a.pidFile,s)}else u&&await u.install({activate:!1}).catch(f=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(f)}
247
246
  `));return process.stdout.write(`coze-bridge: starting daemon...
248
- `),await d({paths:t.paths}),og(e,i,o)}function PA(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.nodeExecPath!="string"||typeof e.nodeArch!="string"?!1:e.nodeExecPath!==process.execPath||e.nodeArch!==process.arch}async function DA(t){let e=new an(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
247
+ `),await d({paths:t.paths}),Rg(e,i,s)}function pk(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.nodeExecPath!="string"||typeof e.nodeArch!="string"?!1:e.nodeExecPath!==process.execPath||e.nodeArch!==process.arch}async function gk(t){let e=new pn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
249
248
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
250
- `)}await new Promise(d=>setTimeout(d,500))}let i=await ws(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
249
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await As(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
251
250
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
252
- `)}let o=t.paths??Z(),{rm:a}=await import("node:fs/promises");try{await a(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
251
+ `)}let s=t.paths??Z(),{rm:a}=await import("node:fs/promises");try{await a(s.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${s.bridgeRoot}
253
252
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
254
253
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
255
- `),0}async function OA(t){let e=await ws(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
254
+ `),0}async function mk(t){let e=await As(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
256
255
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
257
256
  `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
258
- `),1}}async function LA(t){let e=await ws(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
257
+ `),1}}async function wk(t){let e=await As(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
259
258
  `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
260
- `),1}}async function hg(t,e,n){if(e)return st(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(st(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(st(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)
261
- `),st(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function NA(t,e,n,i={},o,a){let d=new an(n.paths),u=n.paths??Z(),f=await hg(u,a,n.reconstructEnv??hl);if(await ad(u,f).catch(m=>st(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!n.skipDistInstall){let m=await wl({paths:n.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
262
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
263
- `)}let x=await fg(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
264
- `),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let m=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let v=m.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
259
+ `),1}}async function Fg(t,e,n){if(e)return ot(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(ot(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ot(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)
260
+ `),ot(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function yk(t,e,n,i={},s,a){let d=new pn(n.paths),u=n.paths??Z(),f=await Fg(u,a,n.reconstructEnv??El);if(await gd(u,f).catch(m=>ot(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(m)})),!n.skipDistInstall){let m=await kl({paths:n.paths});m.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${m.fromVersion} \u2192 ${m.toVersion}
261
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):m.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${m.libVersion}
262
+ `)}let x=await Bg(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
263
+ `),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),s&&(p.agent_id=s);try{let m=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(m.status===200&&m.body?.ok){let b=m.body.agent;return b&&!b.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${b.agentId}): ${b.note}
265
264
  `),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"
266
265
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
267
266
  `),1}catch(m){return process.stderr.write(`coze-bridge: pair failed: ${String(m)}
268
- `),1}}async function MA(t,e,n={},i){let o=e.paths??Z(),a=t??await ga(o);if(!a)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new an(e.paths),u=await hg(o,i,e.reconstructEnv??hl);if(await ad(o,u).catch(p=>st(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await wl({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
269
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
270
- `)}let f=await fg(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
267
+ `),1}}async function _k(t,e,n={},i){let s=e.paths??Z(),a=t??await va(s);if(!a)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new pn(e.paths),u=await Fg(s,i,e.reconstructEnv??El);if(await gd(s,u).catch(p=>ot(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await kl({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
268
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(b=>setTimeout(b,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
269
+ `)}let f=await Bg(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
271
270
  `),1;let x={privatecode:a};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let p=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return p.status===200&&p.body?.ok?(process.stdout.write(`coze-bridge: connected (${p.body.note??"ok"})
272
- `),t!==void 0&&await hs(a,o).catch(m=>cg.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
271
+ `),t!==void 0&&await bs(a,s).catch(m=>Og.warn("writePatToken after connect failed (ignored)",{err:String(m)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
273
272
  `),1)}catch(p){return process.stderr.write(`coze-bridge: connect failed: ${String(p)}
274
- `),1}}async function og(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await n(200)}return t.probe(500)}async function ag(t,e,n=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let a=0;a<n;a++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Xi(u))return;await e(i)}}function BA(t){return new Promise(e=>setTimeout(e,t))}te();function FA(t){let e=/^v?(\d+)/.exec(t.trim());return e&&Number(e[1])<22?"fatal":"ok"}function xg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){if(FA(t)==="ok")return;let o=t.replace(/^v/,"");e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v22.0.0)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
275
- `),n(1)}xg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&jl("warn");dg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
273
+ `),1}}async function Rg(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let s=await t.probe(500);if(s.kind==="connected")return s;await n(200)}return t.probe(500)}async function Dg(t,e,n=60,i=200){let{readFile:s}=await import("node:fs/promises");for(let a=0;a<n;a++){let d;try{d=await s(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!as(u))return;await e(i)}}function bk(t){return new Promise(e=>setTimeout(e,t))}re();function Ek(t){let e=/^v?(\d+)/.exec(t.trim());return e&&Number(e[1])<22?"fatal":"ok"}function zg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){if(Ek(t)==="ok")return;let s=t.replace(/^v/,"");e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${s} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v22.0.0)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
274
+ `),n(1)}zg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Ql("warn");Lg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
276
275
  `),process.exit(1)});