coze-bridge 0.3.1 → 0.3.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +86 -85
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var am=Object.create;var ja=Object.defineProperty;var cm=Object.getOwnPropertyDescriptor;var dm=Object.getOwnPropertyNames;var lm=Object.getPrototypeOf,um=Object.prototype.hasOwnProperty;var ye=(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 at=(t,e)=>()=>(t&&(e=t(t=0)),e);var he=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Wa=(t,e)=>{for(var n in e)ja(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&&ja(t,o,{get:()=>e[o],enumerable:!(i=cm(e,o))||i.enumerable});return t};var Vt=(t,e,n)=>(n=t!=null?am(lm(t)):{},fm(e||!t||!t.__esModule?ja(n,"default",{value:t,enumerable:!0}):n,t));function Qe(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var gr=at(()=>{"use strict"});import{createWriteStream as hm,mkdirSync as pm,readdirSync as xm,unlinkSync as gm}from"node:fs";import{join as ql}from"node:path";function zn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function mr(t,e){return`${t}-${e}.log`}function Ka(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 vs(t,e,n,i){let o;try{o=xm(t)}catch{return}for(let a of o){let d=Ka(a,e);if(d&&mm(d,n,i))try{gm(ql(t,a))}catch{}}}var pi,$a=at(()=>{"use strict";pi=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>zn(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{pm(this.dir,{recursive:!0});let n=hm(ql(this.dir,mr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
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)}
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&&vs(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 ym}from"node:fs";import{join as _m}from"node:path";function Wl(t){let e=t.retentionDays??vm,n=t.clock??(()=>zn(new Date));Is={bridgeSink:new pi(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new pi(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();vs(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])vs(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 Kl(t){Va=t}function $l(t){return wr[Va]<=wr[t]}function Vl(t,e){let n=wr[t];return n===void 0?!0:n>=wr[e]}function As(t){jl={...t}}function Jl(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`${zn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function ct(t,e,n,i,o){try{let a=`${JSON.stringify({ts:Jl(new Date),level:e,module:n,msg:i,...o})}
11
- `;ym(t,{recursive:!0}),wm(_m(t,mr("bridge",zn(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 Ss(t,e,n,i,o){if(wr[t]<wr[Va])return;let a=`${JSON.stringify({ts:Jl(new Date),level:t,module:e,msg:n,...jl,...i})}
12
- `;if(Is){let d=Im(o,i),u=d?Sm(Is,d):Is.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?Em.write(a):bm.write(a)}function q(t,e){return{debug:(n,i)=>Ss("debug",t,n,i,e),info:(n,i)=>Ss("info",t,n,i,e),warn:(n,i)=>Ss("warn",t,n,i,e),error:(n,i)=>Ss("error",t,n,i,e),child:n=>q(`${t}.${n}`,e),forAgent:n=>q(t,n)}}var wr,Va,bm,Em,jl,vm,Is,ie=at(()=>{"use strict";gr();$a();wr={debug:10,info:20,warn:30,error:40},Va=(()=>{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,jl={},vm=Qe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Is=null});var k,Ye=at(()=>{"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 Ql={};Wa(Ql,{ACP_WRAPPER_NPM_PACKAGES:()=>Ts,_resetAcpInstallerForTests:()=>Dm,_setBinaryPathCacheForTests:()=>Rm,buildAcpSpawn:()=>xi,ensureAcpInstalled:()=>_r,getAcpBinaryPath:()=>Cs,pickWhichLine:()=>Ya,probeAcpVersion:()=>Pm,resolveAcpCommand:()=>Xl});import{readFileSync as Zl}from"node:fs";import{createRequire as Am}from"node:module";import{dirname as km,resolve as Tm}from"node:path";function Za(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function Ya(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=Yl.resolve(`${t.npmPackage}/package.json`),n=km(e),i=JSON.parse(Zl(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 _r(t,e){let n=Ja[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=yr.get(t);if(i)return i;let o=Za(t);if(o)return yr.set(t,o),ks.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let a=Cm(n);return yr.set(t,a),ks.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw ks.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 Pm(t){let e=Ja[t];if(e)try{let n=Yl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(Zl(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){ks.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Cs(t){return yr.get(t)}function Xl(t,e){if(e)return e;let n=Za(t);if(n)return n;let i=Cs(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 xi(t,e,n){if(e)return{command:e,args:[...n]};let i=Za(t);if(i)return{command:i,args:[...n]};let o=Xl(t);return{command:process.execPath,args:[o,...n]}}function Dm(){yr.clear()}function Rm(t,e){yr.set(t,e)}var ks,Ja,Ts,Yl,yr,gn=at(()=>{"use strict";Ye();ie();ks=q("agents.acp-installer"),Ja={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Ts=Object.values(Ja).filter(t=>t!==void 0).map(t=>t.npmPackage),Yl=Am(import.meta.url),yr=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 mn(t){try{let e=await Mm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function mt(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 wn(t,e,n){await mt(t,`${JSON.stringify(e,null,2)}
14
- `,n)}var Jt=at(()=>{"use strict"});import{promises as nu,readdirSync as Hm}from"node:fs";import{homedir as Gm}from"node:os";import{sep as qm,join as Ne,resolve as ru}from"node:path";function Y(t){let e=t??Gm(),n=Ne(e,".coze"),i=Ne(n,"bridge"),o=Ne(i,"lib"),a=Ne(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Ne(o,"index.js"),binDir:Ne(i,"bin"),pidFile:Ne(i,"bridge.pid"),portFile:Ne(i,"bridge.port"),tokenFile:Ne(i,"bridge.token"),patTokenFile:Ne(i,"pat-token"),agentEnvFile:Ne(i,"agent-env.json"),logFile:Ne(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Ne(a,"daemon-stdio.log"),installLock:Ne(i,"install.lock"),configFile:Ne(i,"config.json"),agentsRoot:Ne(n,"agents")}}function Me(t,e=Y()){let n=Ne(e.agentsRoot,t);return{root:n,config:Ne(n,"config.json"),workspace:Ne(n,"workspace"),logs:Ne(n,"logs")}}function Ps(t=Y()){try{return Hm(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function gi(t,e){let n=await nu.realpath(ru(t)).catch(()=>null);if(!n)return!1;let i=await nu.realpath(ru(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 De=at(()=>{"use strict"});var Rs={};Wa(Rs,{AGENT_CONFIG_FILE_MODE:()=>Ds,enforceAgentConfigMode:()=>Km,loadAgentConfig:()=>ke,persistAgentSessions:()=>mi,persistAgentSkills:()=>wi,saveAgentConfig:()=>je});import{chmod as jm,stat as Wm}from"node:fs/promises";function ke(t,e){return mn(Me(t,e).config)}function je(t,e){return wn(Me(t.agentId,e).config,t,{mode:Ds})}async function Km(t,e){if(process.platform==="win32")return;let n=Me(t,e).config;try{let i=await Wm(n);if(!i.isFile())return;let o=i.mode&511;o!==Ds&&(await jm(n,Ds),iu.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;iu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function mi(t,e,n){let i=await ke(t,n);i&&(i.sessions=Object.fromEntries(e),await je(i,n))}async function wi(t,e,n){let i=await ke(t,n);i&&(i.skills=e,await je(i,n))}var iu,Ds,Zt=at(()=>{"use strict";Jt();ie();De();iu=q("agent-config"),Ds=384});var ec=he((vk,au)=>{au.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 Ls=he(du=>{var cu={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(cu))du[t]=Xm(cu[t])});var pu=he((Ik,hu)=>{var Qm=ye("fs"),He=ye("path"),lu=ec(),ew=Ls(),tw=typeof process=="object"&&process.platform==="win32",uu=t=>typeof t=="object"&&t!==null,fu=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 Te(t){this.sep=He.sep,this.fs=Qm,uu(t)&&uu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}hu.exports=Te;Te.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)};Te.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=He.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};Te.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 p=He.dirname(t);a.fs.exists(p,function(x){x||a.makeDir(p),a.fs.open(t,"w",438,function(g,E){g?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(y,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)})})})})}):E?a.fs.write(E,e,0,e.length,0,function(){a.fs.close(E,function(){a.fs.chmod(t,i||438,function(){o(!0)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};Te.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=He.join(i,u),p=e.fs.statSync(f);(!o||o.test(f))&&d.push(He.normalize(f)+(p.isDirectory()?e.sep:"")),p.isDirectory()&&a&&(d=d.concat(n(f,o,a)))}),d}return n(t,void 0,!0)};Te.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=He.join(t,u),n.fs.stat(u,function(f,p){if(f)return e(f);p&&(i.push(He.normalize(u)+(p.isDirectory()?n.sep:"")),p.isDirectory()?n.findFilesAsync(u,function(x,g){if(x)return e(x);i=i.concat(g),--d||e(null,i)}):--d||e(null,i))})})})};Te.prototype.getAttributes=function(){};Te.prototype.setAttributes=function(){};Te.crc32update=function(t,e){return fu[(t^e)&255]^t>>>8};Te.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Te.crc32update(n,t[i++]);return~n>>>0};Te.methodToString=function(t){switch(t){case lu.STORED:return"STORED ("+t+")";case lu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Te.canonical=function(t){if(!t)return"";let e=He.posix.normalize("/"+t.split("\\").join("/"));return He.join(".",e)};Te.zipnamefix=function(t){if(!t)return"";let e=He.posix.normalize("/"+t.split("\\").join("/"));return He.posix.join(".",e)};Te.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]};Te.sanitize=function(t,e){t=He.resolve(He.normalize(t));for(var n=e.split("/"),i=0,o=n.length;i<o;i++){var a=He.normalize(He.join(t,n.slice(i,o).join(He.sep)));if(a.indexOf(t)===0)return a}return He.normalize(He.join(t,He.basename(e)))};Te.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Te.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Te.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)};Te.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};Te.isWin=tw;Te.crcTable=fu});var gu=he((Ak,xu)=>{var nw=ye("path");xu.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 wu=he((kk,mu)=>{mu.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var vr=he((Tk,Er)=>{Er.exports=pu();Er.exports.Constants=ec();Er.exports.Errors=Ls();Er.exports.FileAttr=gu();Er.exports.decoder=wu()});var _u=he((Ck,yu)=>{var yn=vr(),G=yn.Constants;yu.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,u=0,f=0,p=0,x=0,g=0,E=0,y=0,b=0;t|=yn.isWin?2560:768,n|=G.FLG_EFS;let I={extraLen:0},A=_=>Math.max(0,_)>>>0,T=_=>Math.max(0,_)&65535,P=_=>Math.max(0,_)&255;return o=yn.fromDate2DOS(new Date),{get made(){return t},set made(_){t=_},get version(){return e},set version(_){e=_},get flags(){return n},set flags(_){n=_},get flags_efs(){return(n&G.FLG_EFS)>0},set flags_efs(_){_?n|=G.FLG_EFS:n&=~G.FLG_EFS},get flags_desc(){return(n&G.FLG_DESC)>0},set flags_desc(_){_?n|=G.FLG_DESC:n&=~G.FLG_DESC},get method(){return i},set method(_){switch(_){case G.STORED:this.version=10;case G.DEFLATED:default:this.version=20}i=_},get time(){return yn.fromDOS2Date(this.timeval)},set time(_){_=new Date(_),this.timeval=yn.fromDate2DOS(_)},get timeval(){return o},set timeval(_){o=A(_)},get timeHighByte(){return P(o>>>8)},get crc(){return a},set crc(_){a=A(_)},get compressedSize(){return d},set compressedSize(_){d=A(_)},get size(){return u},set size(_){u=A(_)},get fileNameLength(){return f},set fileNameLength(_){f=_},get extraLength(){return p},set extraLength(_){p=_},get extraLocalLength(){return I.extraLen},set extraLocalLength(_){I.extraLen=_},get commentLength(){return x},set commentLength(_){x=_},get diskNumStart(){return g},set diskNumStart(_){g=A(_)},get inAttr(){return E},set inAttr(_){E=A(_)},get attr(){return y},set attr(_){y=A(_)},get fileAttr(){return(y||0)>>16&4095},get offset(){return b},set offset(_){b=A(_)},get encrypted(){return(n&G.FLG_ENC)===G.FLG_ENC},get centralHeaderSize(){return G.CENHDR+f+p+x},get realDataOffset(){return b+G.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(_){var D=_.slice(b,b+G.LOCHDR);if(D.readUInt32LE(0)!==G.LOCSIG)throw yn.Errors.INVALID_LOC();I.version=D.readUInt16LE(G.LOCVER),I.flags=D.readUInt16LE(G.LOCFLG),I.flags_desc=(I.flags&G.FLG_DESC)>0,I.method=D.readUInt16LE(G.LOCHOW),I.time=D.readUInt32LE(G.LOCTIM),I.crc=D.readUInt32LE(G.LOCCRC),I.compressedSize=D.readUInt32LE(G.LOCSIZ),I.size=D.readUInt32LE(G.LOCLEN),I.fnameLen=D.readUInt16LE(G.LOCNAM),I.extraLen=D.readUInt16LE(G.LOCEXT);let R=b+G.LOCHDR+I.fnameLen,z=R+I.extraLen;return _.slice(R,z)},loadFromBinary:function(_){if(_.length!==G.CENHDR||_.readUInt32LE(0)!==G.CENSIG)throw yn.Errors.INVALID_CEN();t=_.readUInt16LE(G.CENVEM),e=_.readUInt16LE(G.CENVER),n=_.readUInt16LE(G.CENFLG),i=_.readUInt16LE(G.CENHOW),o=_.readUInt32LE(G.CENTIM),a=_.readUInt32LE(G.CENCRC),d=_.readUInt32LE(G.CENSIZ),u=_.readUInt32LE(G.CENLEN),f=_.readUInt16LE(G.CENNAM),p=_.readUInt16LE(G.CENEXT),x=_.readUInt16LE(G.CENCOM),g=_.readUInt16LE(G.CENDSK),E=_.readUInt16LE(G.CENATT),y=_.readUInt32LE(G.CENATX),b=_.readUInt32LE(G.CENOFF)},localHeaderToBinary:function(){var _=Buffer.alloc(G.LOCHDR);return _.writeUInt32LE(G.LOCSIG,0),_.writeUInt16LE(e,G.LOCVER),_.writeUInt16LE(n,G.LOCFLG),_.writeUInt16LE(i,G.LOCHOW),_.writeUInt32LE(o,G.LOCTIM),_.writeUInt32LE(a,G.LOCCRC),_.writeUInt32LE(d,G.LOCSIZ),_.writeUInt32LE(u,G.LOCLEN),_.writeUInt16LE(f,G.LOCNAM),_.writeUInt16LE(I.extraLen,G.LOCEXT),_},centralHeaderToBinary:function(){var _=Buffer.alloc(G.CENHDR+f+p+x);return _.writeUInt32LE(G.CENSIG,0),_.writeUInt16LE(t,G.CENVEM),_.writeUInt16LE(e,G.CENVER),_.writeUInt16LE(n,G.CENFLG),_.writeUInt16LE(i,G.CENHOW),_.writeUInt32LE(o,G.CENTIM),_.writeUInt32LE(a,G.CENCRC),_.writeUInt32LE(d,G.CENSIZ),_.writeUInt32LE(u,G.CENLEN),_.writeUInt16LE(f,G.CENNAM),_.writeUInt16LE(p,G.CENEXT),_.writeUInt16LE(x,G.CENCOM),_.writeUInt16LE(g,G.CENDSK),_.writeUInt16LE(E,G.CENATT),_.writeUInt32LE(y,G.CENATX),_.writeUInt32LE(b,G.CENOFF),_},toJSON:function(){let _=function(D){return D+" bytes"};return{made:t,version:e,flags:n,method:yn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:_(d),size:_(u),fileNameLength:_(f),extraLength:_(p),commentLength:_(x),diskNumStart:g,inAttr:E,attr:y,offset:b,centralHeaderSize:_(G.CENHDR+f+p+x)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Eu=he((Pk,bu)=>{var Sr=vr(),Se=Sr.Constants;bu.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 Se.ENDHDR+o},loadFromBinary:function(a){if((a.length!==Se.ENDHDR||a.readUInt32LE(0)!==Se.ENDSIG)&&(a.length<Se.ZIP64HDR||a.readUInt32LE(0)!==Se.ZIP64SIG))throw Sr.Errors.INVALID_END();a.readUInt32LE(0)===Se.ENDSIG?(t=a.readUInt16LE(Se.ENDSUB),e=a.readUInt16LE(Se.ENDTOT),n=a.readUInt32LE(Se.ENDSIZ),i=a.readUInt32LE(Se.ENDOFF),o=a.readUInt16LE(Se.ENDCOM)):(t=Sr.readBigUInt64LE(a,Se.ZIP64SUB),e=Sr.readBigUInt64LE(a,Se.ZIP64TOT),n=Sr.readBigUInt64LE(a,Se.ZIP64SIZE),i=Sr.readBigUInt64LE(a,Se.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(Se.ENDHDR+o);return a.writeUInt32LE(Se.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,Se.ENDSUB),a.writeUInt16LE(e,Se.ENDTOT),a.writeUInt32LE(n,Se.ENDSIZ),a.writeUInt32LE(i,Se.ENDOFF),a.writeUInt16LE(o,Se.ENDCOM),a.fill(" ",Se.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 nc=he(tc=>{tc.EntryHeader=_u();tc.MainHeader=Eu()});var Su=he((Rk,vu)=>{vu.exports=function(t){var e=ye("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 p=0;p<a.length;p++){var x=a[p];x.copy(u,f),f+=x.length}i&&i(u)}),o.end(t)}}}});var Au=he((Ok,Iu)=>{var rw=+(process.versions?process.versions.node:"").split(".")[0]||0;Iu.exports=function(t,e){var n=ye("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),p=0;f.fill(0);for(var x=0;x<d.length;x++){var g=d[x];g.copy(f,p),p+=g.length}o&&o(f)}),a.end(t)}}}});var Du=he((Lk,Pu)=>{"use strict";var{randomFillSync:ku}=ye("crypto"),iw=Ls(),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}),Cu=(t,e)=>Math.imul(t,e)>>>0,Tu=(t,e)=>sw[(t^e)&255]^t>>>8,yi=()=>typeof ku=="function"?ku(Buffer.alloc(12)):yi.node();yi.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 Ns={genSalt:yi};function Ms(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])}Ms.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Tu(e[0],t),e[1]+=e[0]&255,e[1]=Cu(e[1],134775813)+1,e[2]=Tu(e[2],e[1]>>>24),t};Ms.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Cu(t,t^1)>>8&255};function ow(t){let e=new Ms(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 Ms(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?Ns.genSalt=function(){return t.slice(0,12)}:t==="node"?Ns.genSalt=yi.node:Ns.genSalt=yi}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=Ns.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)}Pu.exports={decrypt:cw,encrypt:lw,_salter:dw}});var Ru=he(Bs=>{Bs.Deflater=Su();Bs.Inflater=Au();Bs.ZipCrypto=Du()});var ic=he((Mk,Ou)=>{var pe=vr(),uw=nc(),Ce=pe.Constants,rc=Ru();Ou.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),p=!0;let x=t,g=typeof x.decoder=="object"?x.decoder:pe.decoder;p=g.hasOwnProperty("efs")?g.efs:!1;function E(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function y(_){if(!n.flags_desc&&!n.localHeader.flags_desc){if(pe.crc32(_)!==n.localHeader.crc)return!1}else{let D={},R=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(R)==Ce.LOCSIG||e.readUInt32LE(R)==Ce.CENSIG)throw pe.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(R)==Ce.EXTSIG)D.crc=e.readUInt32LE(R+Ce.EXTCRC),D.compressedSize=e.readUInt32LE(R+Ce.EXTSIZ),D.size=e.readUInt32LE(R+Ce.EXTLEN);else if(e.readUInt16LE(R+12)===19280)D.crc=e.readUInt32LE(R+Ce.EXTCRC-4),D.compressedSize=e.readUInt32LE(R+Ce.EXTSIZ-4),D.size=e.readUInt32LE(R+Ce.EXTLEN-4);else throw pe.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==n.compressedSize||D.size!==n.size||D.crc!==n.crc)throw pe.Errors.DESCRIPTOR_FAULTY();if(pe.crc32(_)!==D.crc)return!1}return!0}function b(_,D,R){if(typeof D>"u"&&typeof _=="string"&&(R=_,_=void 0),a)return _&&D&&D(Buffer.alloc(0),pe.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=E();if(z.length===0)return _&&D&&D(z),z;if(n.encrypted){if(typeof R!="string"&&!Buffer.isBuffer(R))throw pe.Errors.INVALID_PASS_PARAM();z=rc.ZipCrypto.decrypt(z,n,R)}var F=Buffer.alloc(n.size);switch(n.method){case pe.Constants.STORED:if(z.copy(F),y(F))return _&&D&&D(F),F;throw _&&D&&D(F,pe.Errors.BAD_CRC()),pe.Errors.BAD_CRC();case pe.Constants.DEFLATED:var X=new rc.Inflater(z,n.size);if(_)X.inflateAsync(function(Z){Z.copy(Z,0),D&&(y(Z)?D(Z):D(Z,pe.Errors.BAD_CRC()))});else{if(X.inflate(F).copy(F,0),!y(F))throw pe.Errors.BAD_CRC(`"${g.decode(i)}"`);return F}break;default:throw _&&D&&D(Buffer.alloc(0),pe.Errors.UNKNOWN_METHOD()),pe.Errors.UNKNOWN_METHOD()}}function I(_,D){if((!d||!d.length)&&Buffer.isBuffer(e))return _&&D&&D(E()),E();if(d.length&&!a){var R;switch(n.method){case pe.Constants.STORED:return n.compressedSize=n.size,R=Buffer.alloc(d.length),d.copy(R),_&&D&&D(R),R;default:case pe.Constants.DEFLATED:var z=new rc.Deflater(d);if(_)z.deflateAsync(function(X){R=Buffer.alloc(X.length),n.compressedSize=X.length,X.copy(R),D&&D(R)});else{var F=z.deflate();return n.compressedSize=F.length,F}z=null;break}}else if(_&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function A(_,D){return pe.readBigUInt64LE(_,D)}function T(_){try{for(var D=0,R,z,F;D+4<_.length;)R=_.readUInt16LE(D),D+=2,z=_.readUInt16LE(D),D+=2,F=_.slice(D,D+z),D+=z,Ce.ID_ZIP64===R&&P(F)}catch{throw pe.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(_){var D,R,z,F;_.length>=Ce.EF_ZIP64_SCOMP&&(D=A(_,Ce.EF_ZIP64_SUNCOMP),n.size===Ce.EF_ZIP64_OR_32&&(n.size=D)),_.length>=Ce.EF_ZIP64_RHO&&(R=A(_,Ce.EF_ZIP64_SCOMP),n.compressedSize===Ce.EF_ZIP64_OR_32&&(n.compressedSize=R)),_.length>=Ce.EF_ZIP64_DSN&&(z=A(_,Ce.EF_ZIP64_RHO),n.offset===Ce.EF_ZIP64_OR_32&&(n.offset=z)),_.length>=Ce.EF_ZIP64_DSN+4&&(F=_.readUInt32LE(Ce.EF_ZIP64_DSN),n.diskNumStart===Ce.EF_ZIP64_OR_16&&(n.diskNumStart=F))}return{get entryName(){return g.decode(i)},get rawEntryName(){return i},set entryName(_){i=pe.toBuffer(_,g.encode);var D=i[i.length-1];a=D===47||D===92,n.fileNameLength=i.length},get efs(){return typeof p=="function"?p(this.entryName):p},get extra(){return u},set extra(_){u=_,n.extraLength=_.length,T(_)},get comment(){return g.decode(o)},set comment(_){if(o=pe.toBuffer(_,g.encode),n.commentLength=o.length,o.length>65535)throw pe.Errors.COMMENT_TOO_LONG()},get name(){var _=g.decode(i);return a?_.substr(_.length-1).split("/").pop():_.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(_){I(!0,_)},setData:function(_){d=pe.toBuffer(_,pe.decoder.encode),!a&&d.length?(n.size=d.length,n.method=pe.Constants.DEFLATED,n.crc=pe.crc32(_),n.changed=!0):n.method=pe.Constants.STORED},getData:function(_){return n.changed?d:b(!1,null,_)},getDataAsync:function(_,D){n.changed?_(d):b(!0,_,D)},set attr(_){n.attr=_},get attr(){return n.attr},set header(_){n.loadFromBinary(_)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=u.length;var _=n.centralHeaderToBinary(),D=pe.Constants.CENHDR;return i.copy(_,D),D+=i.length,u.copy(_,D),D+=n.extraLength,o.copy(_,D),_},packLocalHeader:function(){let _=0;n.flags_efs=this.efs,n.extraLocalLength=f.length;let D=n.localHeaderToBinary(),R=Buffer.alloc(D.length+i.length+n.extraLocalLength);return D.copy(R,_),_+=D.length,i.copy(R,_),_+=i.length,f.copy(R,_),_+=f.length,R},toJSON:function(){let _=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:_(e),data:_(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Mu=he((Bk,Nu)=>{var Lu=ic(),fw=nc(),Xe=vr();Nu.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new fw.MainHeader,d=!1,u=null;let f=new Set,p=e,{noSort:x,decoder:g}=p;t?b(p.readEntries):d=!0;function E(){let A=new Set;for(let T of Object.keys(i)){let P=T.split("/");if(P.pop(),!!P.length)for(let _=0;_<P.length;_++){let D=P.slice(0,_+1).join("/")+"/";A.add(D)}}for(let T of A)if(!(T in i)){let P=new Lu(p);P.entryName=T,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,f.add(P)}}function y(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Xe.Constants.CENHDR)throw Xe.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,T=0;T<n.length;T++){var P=A,_=new Lu(p,t);_.header=t.slice(P,P+=Xe.Constants.CENHDR),_.entryName=t.slice(P,P+=_.header.fileNameLength),_.header.extraLength&&(_.extra=t.slice(P,P+=_.header.extraLength)),_.header.commentLength&&(_.comment=t.slice(P,P+_.header.commentLength)),A+=_.header.centralHeaderSize,n[T]=_,i[_.entryName]=_}f.clear(),E()}function b(A){var T=t.length-Xe.Constants.ENDHDR,P=Math.max(0,T-65535),_=P,D=t.length,R=-1,z=0;for(typeof p.trailingSpace=="boolean"&&p.trailingSpace&&(P=0),T;T>=_;T--)if(t[T]===80){if(t.readUInt32LE(T)===Xe.Constants.ENDSIG){R=T,z=T,D=T+Xe.Constants.ENDHDR,_=T-Xe.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Xe.Constants.END64SIG){_=P;continue}if(t.readUInt32LE(T)===Xe.Constants.ZIP64SIG){R=T,D=T+Xe.readBigUInt64LE(t,T+Xe.Constants.ZIP64SIZE)+Xe.Constants.ZIP64LEAD;break}}if(R==-1)throw Xe.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(R,D)),a.commentLength&&(o=t.slice(z+Xe.Constants.ENDHDR)),A&&y()}function I(){n.length>1&&!x&&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 g.decode(o)},set comment(A){o=Xe.toBuffer(A,g.encode),a.commentLength=o.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 P=i[A];this.getEntryChildren(P,T).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let T=i[A],P=n.indexOf(T);P>=0&&(n.splice(P,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&T){let P=[],_=A.entryName;for(let D of n)D.entryName.startsWith(_)&&P.push(D);return P}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=[],P=0,_=0;a.size=0,a.offset=0;let D=0;for(let F of this.entries){let X=F.getCompressedData();F.header.offset=_;let Z=F.packLocalHeader(),ce=Z.length+X.length;_+=ce,A.push(Z),A.push(X);let te=F.packCentralHeader();T.push(te),a.size+=te.length,P+=ce+te.length,D++}P+=a.mainHeaderSize,a.offset=_,a.totalEntries=D,_=0;let R=Buffer.alloc(P);for(let F of A)F.copy(R,_),_+=F.length;for(let F of T)F.copy(R,_),_+=F.length;let z=a.toBinary();return o&&o.copy(z,Xe.Constants.ENDHDR),z.copy(R,_),t=R,d=!1,R},toAsyncBuffer:function(A,T,P,_){try{d||y(),I();let D=[],R=[],z=0,F=0,X=0;a.size=0,a.offset=0;let Z=function(ce){if(ce.length>0){let te=ce.shift(),oe=te.entryName+te.extra.toString();P&&P(oe),te.getCompressedDataAsync(function(le){_&&_(oe),te.header.offset=F;let C=te.packLocalHeader(),H=C.length+le.length;F+=H,D.push(C),D.push(le);let j=te.packCentralHeader();R.push(j),a.size+=j.length,z+=H+j.length,X++,Z(ce)})}else{z+=a.mainHeaderSize,a.offset=F,a.totalEntries=X,F=0;let te=Buffer.alloc(z);D.forEach(function(le){le.copy(te,F),F+=le.length}),R.forEach(function(le){le.copy(te,F),F+=le.length});let oe=a.toBinary();o&&o.copy(oe,Xe.Constants.ENDHDR),oe.copy(te,F),t=te,d=!1,A(te)}};Z(Array.from(this.entries))}catch(D){T(D)}}}}});var zu=he((Fk,Fu)=>{var Ae=vr(),Ie=ye("path"),hw=ic(),pw=Mu(),Un=(...t)=>Ae.findLast(t,e=>typeof e=="boolean"),Bu=(...t)=>Ae.findLast(t,e=>typeof e=="string"),xw=(...t)=>Ae.findLast(t,e=>typeof e=="function"),gw={noSort:!1,readEntries:!1,method:Ae.Constants.NONE,fs:null};Fu.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=Ae.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Ae(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ae.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Ae.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw Ae.Errors.INVALID_FILENAME();let a=new pw(n,i),{canonical:d,sanitize:u,zipnamefix:f}=Ae;function p(y){if(y&&a){var b;if(typeof y=="string"&&(b=a.getEntry(Ie.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(b=a.getEntry(y.entryName)),b)return b}return null}function x(y){let{join:b,normalize:I,sep:A}=Ie.posix;return b(Ie.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function g(y){return y instanceof RegExp?(function(b){return function(I){return b.test(I)}})(y):typeof y!="function"?()=>!0:y}let E=(y,b)=>{let I=b.slice(-1);return I=I===o.sep?o.sep:"",Ie.relative(y,b)+I};return{readFile:function(y,b){var I=p(y);return I&&I.getData(b)||null},childCount:function(y){let b=p(y);if(b)return a.getChildCount(b)},readFileAsync:function(y,b){var I=p(y);I?I.getDataAsync(b):b(null,"getEntry failed for:"+y)},readAsText:function(y,b){var I=p(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(b||"utf8")}return""},readAsTextAsync:function(y,b,I){var A=p(y);A?A.getDataAsync(function(T,P){if(P){b(T,P);return}T&&T.length?b(T.toString(I||"utf8")):b("")}):b("")},deleteFile:function(y,b=!0){var I=p(y);I&&a.deleteFile(I.entryName,b)},deleteEntry:function(y){var b=p(y);b&&a.deleteEntry(b.entryName)},addZipComment:function(y){a.comment=y},getZipComment:function(){return a.comment||""},addZipEntryComment:function(y,b){var I=p(y);I&&(I.comment=b)},getZipEntryComment:function(y){var b=p(y);return b&&b.comment||""},updateFile:function(y,b){var I=p(y);I&&I.setData(b)},addLocalFile:function(y,b,I,A){if(o.fs.existsSync(y)){b=b?x(b):"";let T=Ie.win32.basename(Ie.win32.normalize(y));b+=I||T;let P=o.fs.statSync(y),_=P.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);P.isDirectory()&&(b+=o.sep),this.addFile(b,_,A,P)}else throw Ae.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,b){y=typeof y=="object"?y:{localPath:y};let I=Ie.resolve(y.localPath),{comment:A}=y,{zipPath:T,zipName:P}=y,_=this;o.fs.stat(I,function(D,R){if(D)return b(D,!1);T=T?x(T):"";let z=Ie.win32.basename(Ie.win32.normalize(I));if(T+=P||z,R.isFile())o.fs.readFile(I,function(F,X){return F?b(F,!1):(_.addFile(T,X,A,R),setImmediate(b,void 0,!0))});else if(R.isDirectory())return T+=o.sep,_.addFile(T,Buffer.alloc(0),A,R),setImmediate(b,void 0,!0)})},addLocalFolder:function(y,b,I){if(I=g(I),b=b?x(b):"",y=Ie.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),T=this;if(A.length)for(let P of A){let _=Ie.join(b,E(y,P));I(_)&&T.addLocalFile(P,Ie.dirname(_))}}else throw Ae.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,b,I,A){A=g(A),I=I?x(I):"",y=Ie.normalize(y);var T=this;o.fs.open(y,"r",function(P){if(P&&P.code==="ENOENT")b(void 0,Ae.Errors.FILE_NOT_FOUND(y));else if(P)b(void 0,P);else{var _=o.findFiles(y),D=-1,R=function(){if(D+=1,D<_.length){var z=_[D],F=E(y,z).split("\\").join("/");F=F.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(F)?o.fs.stat(z,function(X,Z){X&&b(void 0,X),Z.isFile()?o.fs.readFile(z,function(ce,te){ce?b(void 0,ce):(T.addFile(I+F,te,"",Z),R())}):(T.addFile(I+F+"/",Buffer.alloc(0),"",Z),R())}):process.nextTick(()=>{R()})}else b(!0,void 0)};R()}})},addLocalFolderAsync2:function(y,b){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=Ie.resolve(x(y.localPath));let{zipPath:A,filter:T,namefix:P}=y;T instanceof RegExp?T=(function(R){return function(z){return R.test(z)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?x(A):"",P=="latin1"&&(P=R=>R.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=R=>R);let _=R=>Ie.join(A,P(E(localPath,R))),D=R=>Ie.win32.basename(Ie.win32.normalize(P(R)));o.fs.open(localPath,"r",function(R){R&&R.code==="ENOENT"?b(void 0,Ae.Errors.FILE_NOT_FOUND(localPath)):R?b(void 0,R):o.findFilesAsync(localPath,function(z,F){if(z)return b(z);F=F.filter(X=>T(_(X))),F.length||b(void 0,!1),setImmediate(F.reverse().reduce(function(X,Z){return function(ce,te){if(ce||te===!1)return setImmediate(X,ce,!1);I.addLocalFileAsync({localPath:Z,zipPath:Ie.dirname(_(Z)),zipName:D(Z)},X)}},b))})})},addLocalFolderPromise:function(y,b){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},b),(T,P)=>{T&&A(T),P&&I(this)})})},addFile:function(y,b,I,A){y=f(y);let T=p(y),P=T!=null;P||(T=new hw(i),T.entryName=y),T.comment=I||"";let _=typeof A=="object"&&A instanceof o.fs.Stats;_&&(T.header.time=A.mtime);var D=T.isDirectory?16:0;let R=T.isDirectory?16384:32768;return _?R|=4095&A.mode:typeof A=="number"?R|=4095&A:R|=T.isDirectory?493:420,D=(D|R<<16)>>>0,T.attr=D,T.setData(b),P||a.setEntry(T),T},getEntries:function(y){return a.password=y,a?a.entries:[]},getEntry:function(y){return p(y)},getEntryCount:function(){return a.getEntryCount()},forEach:function(y){return a.forEach(y)},extractEntryTo:function(y,b,I,A,T,P){A=Un(!1,A),T=Un(!1,T),I=Un(!0,I),P=Bu(T,P);var _=p(y);if(!_)throw Ae.Errors.NO_ENTRY();var D=d(_.entryName),R=u(b,P&&!_.isDirectory?P:I?D:Ie.basename(D));if(_.isDirectory){var z=a.getEntryChildren(_);return z.forEach(function(Z){if(Z.isDirectory)return;var ce=Z.getData();if(!ce)throw Ae.Errors.CANT_EXTRACT_FILE();var te=d(Z.entryName),oe=u(b,I?te:Ie.basename(te));let le=T?Z.header.fileAttr:void 0;o.writeFileTo(oe,ce,A,le)}),!0}var F=_.getData(a.password);if(!F)throw Ae.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(R)&&!A)throw Ae.Errors.CANT_OVERRIDE();let X=T?y.header.fileAttr:void 0;return o.writeFileTo(R,F,A,X),!0},test:function(y){if(!a)return!1;for(var b in a.entries)try{if(b.isDirectory)continue;var I=a.entries[b].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,b,I,A){if(I=Un(!1,I),A=Bu(I,A),b=Un(!1,b),!a)throw Ae.Errors.NO_ZIP();a.entries.forEach(function(T){var P=u(y,d(T.entryName));if(T.isDirectory){o.makeDir(P);return}var _=T.getData(A);if(!_)throw Ae.Errors.CANT_EXTRACT_FILE();let D=I?T.header.fileAttr:void 0;o.writeFileTo(P,_,b,D);try{o.fs.utimesSync(P,T.header.time,T.header.time)}catch{throw Ae.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,b,I,A){if(A=xw(b,I,A),I=Un(!1,I),b=Un(!1,b),!A)return new Promise((R,z)=>{this.extractAllToAsync(y,b,I,function(F){F?z(F):R(this)})});if(!a){A(Ae.Errors.NO_ZIP());return}y=Ie.resolve(y);let T=R=>u(y,Ie.normalize(d(R.entryName))),P=(R,z)=>new Error(R+': "'+z+'"'),_=[],D=[];a.entries.forEach(R=>{R.isDirectory?_.push(R):D.push(R)});for(let R of _){let z=T(R),F=I?R.header.fileAttr:void 0;try{o.makeDir(z),F&&o.fs.chmodSync(z,F),o.fs.utimesSync(z,R.header.time,R.header.time)}catch{A(P("Unable to create folder",z))}}D.reverse().reduce(function(R,z){return function(F){if(F)R(F);else{let X=Ie.normalize(d(z.entryName)),Z=u(y,X);z.getDataAsync(function(ce,te){if(te)R(te);else if(!ce)R(Ae.Errors.CANT_EXTRACT_FILE());else{let oe=I?z.header.fileAttr:void 0;o.writeFileToAsync(Z,ce,b,oe,function(le){le||R(P("Unable to write file",Z)),o.fs.utimes(Z,z.header.time,z.header.time,function(C){C?R(P("Unable to set times",Z)):R()})})}})}}},A)()},writeZip:function(y,b){if(arguments.length===1&&typeof y=="function"&&(b=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=a.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof b=="function"&&b(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,b){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},b);return new Promise((T,P)=>{!y&&i.filename&&(y=i.filename),y||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(_=>{let D=R=>R?T(R):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(y,_,I,A,D)},P)})},toBufferPromise:function(){return new Promise((y,b)=>{a.toAsyncBuffer(y,b)})},toBuffer:function(y,b,I,A){return typeof y=="function"?(a.toAsyncBuffer(y,b,I,A),null):a.compressToBuffer()}}}});import{execFile as S_,spawn as I_,spawnSync as n2}from"node:child_process";import{promisify as A_}from"node:util";function T_(t){if(process.platform!=="win32")return!1;if(a0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(a0,"").toLowerCase();return k_.has(n)}function c0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return T_(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function lt(t,e=[],n={}){return I_(t,e,c0(t,n))}function d0(t,e=[],n={}){return C_(t,e,c0(t,n))}var k_,a0,C_,rn=at(()=>{"use strict";k_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),a0=/\.(cmd|bat|ps1)$/i;C_=A_(S_)});var an=he((hR,op)=>{"use strict";var ip=["nodebuffer","arraybuffer","fragments"],sp=typeof Blob<"u";sp&&ip.push("blob");op.exports={BINARY_TYPES:ip,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:sp,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var cs=he((pR,Yo)=>{"use strict";var{EMPTY_BUFFER:Wv}=an(),zd=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 zd(n.buffer,n.byteOffset,i):n}function ap(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function cp(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 Ud(t){if(Ud.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new zd(t):ArrayBuffer.isView(t)?e=new zd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ud.readOnly=!1),e}Yo.exports={concat:Kv,mask:ap,toArrayBuffer:$v,toBuffer:Ud,unmask:cp};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ye("bufferutil");Yo.exports.mask=function(e,n,i,o,a){a<48?ap(e,n,i,o,a):t.mask(e,n,i,o,a)},Yo.exports.unmask=function(e,n){e.length<32?cp(e,n):t.unmask(e,n)}}catch{}});var up=he((xR,lp)=>{"use strict";var dp=Symbol("kDone"),Hd=Symbol("kRun"),Gd=class{constructor(e){this[dp]=()=>{this.pending--,this[Hd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hd]()}[Hd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[dp])}}};lp.exports=Gd});var ei=he((gR,xp)=>{"use strict";var ds=ye("zlib"),fp=cs(),Vv=up(),{kStatusCode:hp}=an(),Jv=Buffer[Symbol.species],Zv=Buffer.from([0,0,255,255]),Qo=Symbol("permessage-deflate"),cn=Symbol("total-length"),Xr=Symbol("callback"),Nn=Symbol("buffers"),Qr=Symbol("error"),Xo,qd=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,!Xo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Xo=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[Xr];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){Xo.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){Xo.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"?ds.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=ds.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Qo]=this,this._inflate[cn]=0,this._inflate[Nn]=[],this._inflate.on("error",Xv),this._inflate.on("data",pp)}this._inflate[Xr]=i,this._inflate.write(e),n&&this._inflate.write(Zv),this._inflate.flush(()=>{let a=this._inflate[Qr];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=fp.concat(this._inflate[Nn],this._inflate[cn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[cn]=0,this._inflate[Nn]=[],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"?ds.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=ds.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[cn]=0,this._deflate[Nn]=[],this._deflate.on("data",Yv)}this._deflate[Xr]=i,this._deflate.write(e),this._deflate.flush(ds.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=fp.concat(this._deflate[Nn],this._deflate[cn]);n&&(a=new Jv(a.buffer,a.byteOffset,a.length-4)),this._deflate[Xr]=null,this._deflate[cn]=0,this._deflate[Nn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};xp.exports=qd;function Yv(t){this[Nn].push(t),this[cn]+=t.length}function pp(t){if(this[cn]+=t.length,this[Qo]._maxPayload<1||this[cn]<=this[Qo]._maxPayload){this[Nn].push(t);return}this[Qr]=new RangeError("Max payload size exceeded"),this[Qr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Qr][hp]=1009,this.removeListener("data",pp),this.reset()}function Xv(t){if(this[Qo]._inflate=null,this[Qr]){this[Xr](this[Qr]);return}t[hp]=1007,this[Xr](t)}});var ti=he((mR,ea)=>{"use strict";var{isUtf8:gp}=ye("buffer"),{hasBlob:Qv}=an(),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 jd(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")}ea.exports={isBlob:nS,isValidStatusCode:tS,isValidUTF8:jd,tokenChars:eS};if(gp)ea.exports.isValidUTF8=function(t){return t.length<24?jd(t):gp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ye("utf-8-validate");ea.exports.isValidUTF8=function(e){return e.length<32?jd(e):t(e)}}catch{}});var Jd=he((wR,vp)=>{"use strict";var{Writable:rS}=ye("stream"),mp=ei(),{BINARY_TYPES:iS,EMPTY_BUFFER:wp,kStatusCode:sS,kWebSocket:oS}=an(),{concat:Wd,toArrayBuffer:aS,unmask:cS}=cs(),{isValidStatusCode:dS,isValidUTF8:yp}=ti(),ta=Buffer[Symbol.species],Et=0,_p=1,bp=2,Ep=3,Kd=4,$d=5,na=6,Vd=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=Et}_write(e,n,i){if(this._opcode===8&&this._state==Et)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 ta(i.buffer,i.byteOffset+e,i.length-e),new ta(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 ta(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 Et:this.getInfo(e);break;case _p:this.getPayloadLength16(e);break;case bp:this.getPayloadLength64(e);break;case Ep:this.getMask();break;case Kd:this.getData(e);break;case $d:case na: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[mp.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=_p:this._payloadLength===127?this._state=bp: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=Ep:this._state=Kd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Kd}getData(e){let n=wp;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=$d,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[mp.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===Et&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Et;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=Wd(i,n):this._binaryType==="arraybuffer"?o=aS(Wd(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Et):(this._state=na,setImmediate(()=>{this.emit("message",o,!0),this._state=Et,this.startLoop(e)}))}else{let o=Wd(i,n);if(!this._skipUTF8Validation&&!yp(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===$d||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Et):(this._state=na,setImmediate(()=>{this.emit("message",o,!1),this._state=Et,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,wp),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 ta(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!yp(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=Et;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Et):(this._state=na,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Et,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}};vp.exports=Vd});var Xd=he((_R,Ap)=>{"use strict";var{Duplex:yR}=ye("stream"),{randomFillSync:lS}=ye("crypto"),Sp=ei(),{EMPTY_BUFFER:uS,kWebSocket:fS,NOOP:hS}=an(),{isBlob:ni,isValidStatusCode:pS}=ti(),{mask:Ip,toBuffer:or}=cs(),vt=Symbol("kByteLength"),xS=Buffer.alloc(4),ra=8*1024,ar,ri=ra,Rt=0,gS=1,mS=2,Zd=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=Rt,this.onerror=hS,this[fS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||xS,n.generateMask?n.generateMask(i):(ri===ra&&(ar===void 0&&(ar=Buffer.alloc(ra)),lS(ar,0,ra),ri=0),i[0]=ar[ri++],i[1]=ar[ri++],i[2]=ar[ri++],i[3]=ar[ri++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[vt]!==void 0?u=n[vt]:(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 p=Buffer.allocUnsafe(o?u+a:a);return p[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(p[0]|=64),p[1]=f,f===126?p.writeUInt16BE(u,2):f===127&&(p[2]=p[3]=0,p.writeUIntBE(u,4,6)),n.mask?(p[1]|=128,p[a-4]=i[0],p[a-3]=i[1],p[a-2]=i[2],p[a-1]=i[3],d?[p,e]:o?(Ip(e,i,p,a,u),[p]):(Ip(e,i,e,0,u),[p,e])):[p,e]}close(e,n,i,o){let a;if(e===void 0)a=uS;else{if(typeof e!="number"||!pS(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={[vt]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Rt?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):ni(e)?(o=e.size,a=!1):(e=or(e),o=e.length,a=or.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[vt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};ni(e)?this._state!==Rt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Rt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let o,a;if(typeof e=="string"?(o=Buffer.byteLength(e),a=!1):ni(e)?(o=e.size,a=!1):(e=or(e),o=e.length,a=or.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[vt]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};ni(e)?this._state!==Rt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Rt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[Sp.extensionName],a=n.binary?2:1,d=n.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):ni(e)?(u=e.size,f=!1):(e=or(e),u=e.length,f=or.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 p={[vt]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:f,rsv1:d};ni(e)?this._state!==Rt?this.enqueue([this.getBlobData,e,this._compress,p,i]):this.getBlobData(e,this._compress,p,i):this._state!==Rt?this.enqueue([this.dispatch,e,this._compress,p,i]):this.dispatch(e,this._compress,p,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[vt],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(Yd,this,u,o);return}this._bufferedBytes-=i[vt];let d=or(a);n?this.dispatch(d,n,i,o):(this._state=Rt,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[Sp.extensionName];this._bufferedBytes+=i[vt],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");Yd(this,f,o);return}this._bufferedBytes-=i[vt],this._state=Rt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===Rt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][vt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][vt],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)}};Ap.exports=Zd;function Yd(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){Yd(t,e,n),t.onerror(e)}});var Np=he((bR,Lp)=>{"use strict";var{kForOnEventAttribute:ls,kListener:Qd}=an(),kp=Symbol("kCode"),Tp=Symbol("kData"),Cp=Symbol("kError"),Pp=Symbol("kMessage"),Dp=Symbol("kReason"),ii=Symbol("kTarget"),Rp=Symbol("kType"),Op=Symbol("kWasClean"),dn=class{constructor(e){this[ii]=null,this[Rp]=e}get target(){return this[ii]}get type(){return this[Rp]}};Object.defineProperty(dn.prototype,"target",{enumerable:!0});Object.defineProperty(dn.prototype,"type",{enumerable:!0});var cr=class extends dn{constructor(e,n={}){super(e),this[kp]=n.code===void 0?0:n.code,this[Dp]=n.reason===void 0?"":n.reason,this[Op]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[kp]}get reason(){return this[Dp]}get wasClean(){return this[Op]}};Object.defineProperty(cr.prototype,"code",{enumerable:!0});Object.defineProperty(cr.prototype,"reason",{enumerable:!0});Object.defineProperty(cr.prototype,"wasClean",{enumerable:!0});var si=class extends dn{constructor(e,n={}){super(e),this[Cp]=n.error===void 0?null:n.error,this[Pp]=n.message===void 0?"":n.message}get error(){return this[Cp]}get message(){return this[Pp]}};Object.defineProperty(si.prototype,"error",{enumerable:!0});Object.defineProperty(si.prototype,"message",{enumerable:!0});var us=class extends dn{constructor(e,n={}){super(e),this[Tp]=n.data===void 0?null:n.data}get data(){return this[Tp]}};Object.defineProperty(us.prototype,"data",{enumerable:!0});var yS={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[ls]&&o[Qd]===e&&!o[ls])return;let i;if(t==="message")i=function(a,d){let u=new us("message",{data:d?a:a.toString()});u[ii]=this,ia(e,this,u)};else if(t==="close")i=function(a,d){let u=new cr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[ii]=this,ia(e,this,u)};else if(t==="error")i=function(a){let d=new si("error",{error:a,message:a.message});d[ii]=this,ia(e,this,d)};else if(t==="open")i=function(){let a=new dn("open");a[ii]=this,ia(e,this,a)};else return;i[ls]=!!n[ls],i[Qd]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Qd]===e&&!n[ls]){this.removeListener(t,n);break}}};Lp.exports={CloseEvent:cr,ErrorEvent:si,Event:dn,EventTarget:yS,MessageEvent:us};function ia(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var sa=he((ER,Mp)=>{"use strict";var{tokenChars:fs}=ti();function jt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function _S(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,u,f=-1,p=-1,x=-1,g=0;for(;g<t.length;g++)if(p=t.charCodeAt(g),d===void 0)if(x===-1&&fs[p]===1)f===-1&&(f=g);else if(g!==0&&(p===32||p===9))x===-1&&f!==-1&&(x=g);else if(p===59||p===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);x===-1&&(x=g);let y=t.slice(f,x);p===44?(jt(e,y,n),n=Object.create(null)):d=y,f=x=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);else if(u===void 0)if(x===-1&&fs[p]===1)f===-1&&(f=g);else if(p===32||p===9)x===-1&&f!==-1&&(x=g);else if(p===59||p===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);x===-1&&(x=g),jt(n,t.slice(f,x),!0),p===44&&(jt(e,d,n),n=Object.create(null),d=void 0),f=x=-1}else if(p===61&&f!==-1&&x===-1)u=t.slice(f,g),f=x=-1;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(o){if(fs[p]!==1)throw new SyntaxError(`Unexpected character at index ${g}`);f===-1?f=g:i||(i=!0),o=!1}else if(a)if(fs[p]===1)f===-1&&(f=g);else if(p===34&&f!==-1)a=!1,x=g;else if(p===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(p===34&&t.charCodeAt(g-1)===61)a=!0;else if(x===-1&&fs[p]===1)f===-1&&(f=g);else if(f!==-1&&(p===32||p===9))x===-1&&(x=g);else if(p===59||p===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${g}`);x===-1&&(x=g);let y=t.slice(f,x);i&&(y=y.replace(/\\/g,""),i=!1),jt(n,u,y),p===44&&(jt(e,d,n),n=Object.create(null),d=void 0),u=void 0,f=x=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);if(f===-1||a||p===32||p===9)throw new SyntaxError("Unexpected end of input");x===-1&&(x=g);let E=t.slice(f,x);return d===void 0?jt(e,E,n):(u===void 0?jt(n,E,!0):i?jt(n,u,E.replace(/\\/g,"")):jt(n,u,E),jt(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(", ")}Mp.exports={format:bS,parse:_S}});var da=he((IR,Vp)=>{"use strict";var ES=ye("events"),vS=ye("https"),SS=ye("http"),zp=ye("net"),IS=ye("tls"),{randomBytes:AS,createHash:kS}=ye("crypto"),{Duplex:vR,Readable:SR}=ye("stream"),{URL:el}=ye("url"),Mn=ei(),TS=Jd(),CS=Xd(),{isBlob:PS}=ti(),{BINARY_TYPES:Bp,CLOSE_TIMEOUT:DS,EMPTY_BUFFER:oa,GUID:RS,kForOnEventAttribute:tl,kListener:OS,kStatusCode:LS,kWebSocket:Je,NOOP:Up}=an(),{EventTarget:{addEventListener:NS,removeEventListener:MS}}=Np(),{format:BS,parse:FS}=sa(),{toBuffer:zS}=cs(),Hp=Symbol("kAborted"),nl=[8,13],ln=["CONNECTING","OPEN","CLOSING","CLOSED"],US=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ee=class t extends ES{constructor(e,n,i){super(),this._binaryType=Bp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=oa,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]),Gp(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Bp.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[Je]=this,a[Je]=this,e[Je]=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=JS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Wp),e.on("data",ca),e.on("end",Kp),e.on("error",$p),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[Mn.extensionName]&&this._extensions[Mn.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){pt(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())}),jp(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){rl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||oa,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){rl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||oa,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){rl(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Mn.extensionName]||(o.compress=!1),this._sender.send(e||oa,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){pt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ee,"CONNECTING",{enumerable:!0,value:ln.indexOf("CONNECTING")});Object.defineProperty(Ee.prototype,"CONNECTING",{enumerable:!0,value:ln.indexOf("CONNECTING")});Object.defineProperty(Ee,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(Ee.prototype,"OPEN",{enumerable:!0,value:ln.indexOf("OPEN")});Object.defineProperty(Ee,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(Ee.prototype,"CLOSING",{enumerable:!0,value:ln.indexOf("CLOSING")});Object.defineProperty(Ee,"CLOSED",{enumerable:!0,value:ln.indexOf("CLOSED")});Object.defineProperty(Ee.prototype,"CLOSED",{enumerable:!0,value:ln.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ee.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ee.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[tl])return e[OS];return null},set(e){for(let n of this.listeners(t))if(n[tl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[tl]:!0})}})});Ee.prototype.addEventListener=NS;Ee.prototype.removeEventListener=MS;Vp.exports=Ee;function Gp(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:DS,protocolVersion:nl[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,!nl.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${nl.join(", ")})`);let a;if(e instanceof el)a=e;else try{a=new el(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;aa(t,I);return}let p=d?443:80,x=AS(16).toString("base64"),g=d?vS.request:SS.request,E=new Set,y;if(o.createConnection=o.createConnection||(d?GS:HS),o.defaultPort=o.defaultPort||p,o.port=a.port||p,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":x,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(y=new Mn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=BS({[Mn.extensionName]:y.offer()})),n.length){for(let I of n){if(typeof I!="string"||!US.test(I)||E.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");E.add(I)}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 I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let b;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath: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?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),b=t._req=g(o),t._redirects&&t.emit("redirect",t.url,b)}else b=t._req=g(o);o.timeout&&b.on("timeout",()=>{pt(t,b,"Opening handshake has timed out")}),b.on("error",I=>{b===null||b[Hp]||(b=t._req=null,aa(t,I))}),b.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){pt(t,b,"Maximum redirects exceeded");return}b.abort();let P;try{P=new el(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);aa(t,D);return}Gp(t,P,n,i)}else t.emit("unexpected-response",b,I)||pt(t,b,`Unexpected server response: ${I.statusCode}`)}),b.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==Ee.CONNECTING)return;b=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){pt(t,A,"Invalid Upgrade header");return}let _=kS("sha1").update(x+RS).digest("base64");if(I.headers["sec-websocket-accept"]!==_){pt(t,A,"Invalid Sec-WebSocket-Accept header");return}let D=I.headers["sec-websocket-protocol"],R;if(D!==void 0?E.size?E.has(D)||(R="Server sent an invalid subprotocol"):R="Server sent a subprotocol but none was requested":E.size&&(R="Server sent no subprotocol"),R){pt(t,A,R);return}D&&(t._protocol=D);let z=I.headers["sec-websocket-extensions"];if(z!==void 0){if(!y){pt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let F;try{F=FS(z)}catch{pt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let X=Object.keys(F);if(X.length!==1||X[0]!==Mn.extensionName){pt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(F[Mn.extensionName])}catch{pt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Mn.extensionName]=y}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(b,t):b.end()}function aa(t,e){t._readyState=Ee.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function HS(t){return t.path=t.socketPath,zp.connect(t)}function GS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=zp.isIP(t.host)?"":t.host),IS.connect(t)}function pt(t,e,n){t._readyState=Ee.CLOSING;let i=new Error(n);Error.captureStackTrace(i,pt),e.setHeader?(e[Hp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(aa,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function rl(t,e,n){if(e){let i=PS(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} (${ln[t.readyState]})`);process.nextTick(n,i)}}function qS(t,e){let n=this[Je];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Je]!==void 0&&(n._socket.removeListener("data",ca),process.nextTick(qp,n._socket),t===1005?n.close():n.close(t,e))}function jS(){let t=this[Je];t.isPaused||t._socket.resume()}function WS(t){let e=this[Je];e._socket[Je]!==void 0&&(e._socket.removeListener("data",ca),process.nextTick(qp,e._socket),e.close(t[LS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Fp(){this[Je].emitClose()}function KS(t,e){this[Je].emit("message",t,e)}function $S(t){let e=this[Je];e._autoPong&&e.pong(t,!this._isServer,Up),e.emit("ping",t)}function VS(t){this[Je].emit("pong",t)}function qp(t){t.resume()}function JS(t){let e=this[Je];e.readyState!==Ee.CLOSED&&(e.readyState===Ee.OPEN&&(e._readyState=Ee.CLOSING,jp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function jp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Wp(){let t=this[Je];if(this.removeListener("close",Wp),this.removeListener("data",ca),this.removeListener("end",Kp),t._readyState=Ee.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Fp),t._receiver.on("finish",Fp))}function ca(t){this[Je]._receiver.write(t)||this.pause()}function Kp(){let t=this[Je];t._readyState=Ee.CLOSING,t._receiver.end(),this.end()}function $p(){let t=this[Je];this.removeListener("error",$p),this.on("error",Up),t&&(t._readyState=Ee.CLOSING,this.destroy())}});var Xp=he((kR,Yp)=>{"use strict";var AR=da(),{Duplex:ZS}=ye("stream");function Jp(t){t.emit("close")}function YS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Zp(t){this.removeListener("error",Zp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function XS(t,e){let n=!0,i=new ZS({...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(Jp,i);return}let d=!1;t.once("error",function(f){d=!0,a(f)}),t.once("close",function(){d||a(o),process.nextTick(Jp,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",Zp),i}Yp.exports=XS});var il=he((TR,Qp)=>{"use strict";var{tokenChars:QS}=ti();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}Qp.exports={parse:e1}});var ox=he((PR,sx)=>{"use strict";var t1=ye("events"),la=ye("http"),{Duplex:CR}=ye("stream"),{createHash:n1}=ye("crypto"),ex=sa(),dr=ei(),r1=il(),i1=da(),{CLOSE_TIMEOUT:s1,GUID:o1,kWebSocket:a1}=an(),c1=/^[+/0-9A-Za-z]{22}==$/,tx=0,nx=1,ix=2,sl=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=la.createServer((i,o)=>{let a=la.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=tx}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===ix){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(hs,this);return}if(e&&this.once("close",e),this._state!==nx)if(this._state=nx,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(hs,this):process.nextTick(hs,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{hs(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",rx);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){lr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){lr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!c1.test(a)){lr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){lr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ps(n,400);return}let f=e.headers["sec-websocket-protocol"],p=new Set;if(f!==void 0)try{p=r1.parse(f)}catch{lr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let x=e.headers["sec-websocket-extensions"],g={};if(this.options.perMessageDeflate&&x!==void 0){let E=new dr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=ex.parse(x);y[dr.extensionName]&&(E.accept(y[dr.extensionName]),g[dr.extensionName]=E)}catch{lr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let E={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(E,(y,b,I,A)=>{if(!y)return ps(n,b||401,I,A);this.completeUpgrade(g,a,p,e,n,i,o)});return}if(!this.options.verifyClient(E))return ps(n,401)}this.completeUpgrade(g,a,p,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>tx)return ps(a,503);let p=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${n1("sha1").update(n+o1).digest("base64")}`],x=new this.options.WebSocket(null,void 0,this.options);if(i.size){let g=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;g&&(p.push(`Sec-WebSocket-Protocol: ${g}`),x._protocol=g)}if(e[dr.extensionName]){let g=e[dr.extensionName].params,E=ex.format({[dr.extensionName]:[g]});p.push(`Sec-WebSocket-Extensions: ${E}`),x._extensions=e}this.emit("headers",p,o),a.write(p.concat(`\r
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
15
15
  `).join(`\r
16
- `)),a.removeListener("error",rx),x.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(x),x.on("close",()=>{this.clients.delete(x),this._shouldEmitClose&&!this.clients.size&&process.nextTick(hs,this)})),u(x,o)}};sx.exports=sl;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 hs(t){t._state=ix,t.emit("close")}function rx(){this.destroy()}function ps(t,e,n,i){n=n||la.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} ${la.STATUS_CODES[e]}\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
17
  `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+n)}function lr(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,lr),t.emit("wsClientError",d,n,e)}else ps(n,i,o,a)}});var _x=he(Oe=>{"use strict";var B=K;(function(t,e){let n=K,i=t();for(;;)try{if(-parseInt(n(1295))/1*(-parseInt(n(487))/2)+-parseInt(n(1451))/3*(parseInt(n(1631))/4)+parseInt(n(935))/5*(-parseInt(n(400))/6)+-parseInt(n(1212))/7+parseInt(n(1383))/8+-parseInt(n(968))/9+parseInt(n(1081))/10*(parseInt(n(354))/11)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ma,635453);var m1=Object[B(1247)+B(1149)],w1=Object["getOwnPr"+B(1718)+"mes"],px=(t,e)=>function(){return t&&(e=(0,t[{UprIf:function(a,d){return a(d)}}[B(1461)](w1,t)[0]])(t=0)),e},y1=(t,e)=>{let n=B,i={awWff:function(a,d,u,f){return a(d,u,f)}};for(var o in e)i[n(1008)](m1,t,o,{get:e[o],enumerable:!0})};function _1(){return dx||(dx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function b1(){let t=B;return lx||(lx=[IDBCursor[t(1467)+"e"][t(1226)],IDBCursor[t(1467)+"e"].continue,IDBCursor.prototype[t(1543)+t(1251)+"ey"]])}function E1(t){let e=B,n={WwWPw:function(o,a){return o!==a},bLLao:e(1168),fWoyE:function(o){return o()},pLdMT:e(928),fZgct:function(o,a){return o*a},gKhFW:function(o,a){return o(a)},nUCzj:function(o){return o()},tyMwA:function(o,a){return o>=a},eXywk:e(1260),enNcS:function(o,a){return o instanceof a}},i=new Promise((o,a)=>{let d=e,u={YzwiY:d(1260),HxIxX:d(858),zdRFe:n[d(1190)],Gnojz:function(g,E){return n.fZgct(g,E)},gVyiA:function(g,E){return g===E},QoqOf:function(g,E){return n[d(1621)](g,E)},LKzJy:function(g){return n[d(1038)](g)},FmxGT:function(g,E){return n[d(1130)](g,E)}},f=()=>{let g=d;u[g(1803)]===u[g(1803)]?(t[g(1327)+"entListener"](u[g(1612)],p),t[g(1327)+"entListener"](u[g(644)],x)):(this[g(1488)](u.YzwiY,_0xf7813a),this[g(605)]&&this[g(605)](_0x246814))},p=()=>{let g=d;if(u[g(696)](g(664),g(934))){let{initReconnectInterval:E,maxReconnectInterval:y,reconnectIntervalGrowFactor:b}=this[g(457)],I=u[g(807)](E,_0x4d4625[g(757)](b,_0x230796-1));return I>y?y:I}else u[g(873)](o,u.QoqOf(Kt,t[g(1067)])),u.LKzJy(f)},x=()=>{let g=d;if(n[g(994)](n[g(375)],n[g(375)]))return u[g(864)](_0x542045[g(689)],_0x295660[g(992)]);a(t[g(1260)]),n[g(1791)](f)};t[d(584)+d(1643)](n.pLdMT,p),t[d(584)+d(1643)](n.eXywk,x)});return i[e(1266)](o=>{let a=e;n[a(847)](o,IDBCursor)&&al[a(1351)](o,t)})[e(444)](()=>{}),xa[e(1351)](i,t),i}function v1(t){let e=B,n={bGZgb:function(o){return o()},lEEWU:function(o){return o()},iORrR:e(423),iXXOd:function(o,a){return o(a)},qdfZW:e(1774)+"or",ClhGF:e(1260),MmVFD:"abort"};if(pa[e(384)](t))return;let i=new Promise((o,a)=>{let d=e,u={sYSKn:n[d(638)],igZhu:function(g,E){return n.iXXOd(g,E)},iWPFO:n[d(959)],BHmUW:function(g){return g()}},f=()=>{let g=d;t[g(1327)+g(681)+g(1492)](u.sYSKn,p),t[g(1327)+g(681)+"ner"](g(1260),x),t[g(1327)+"entListe"+g(1492)](g(588),x)},p=()=>{let g=d;n[g(1477)](o),n[g(1641)](f)},x=()=>{let g=d;u[g(634)](a,t[g(1260)]||new DOMException(u[g(1332)],u.iWPFO)),u[g(443)](f)};t[d(584)+d(1643)](d(423),p),t[d(584)+d(1643)](n.ClhGF,x),t[d(584)+d(1643)](n[d(981)],x)});pa[e(1351)](t,i)}function S1(t){ga=t(ga)}function I1(t){let e=B,n={YjOGk:function(i,o){return i===o},ITfjb:function(i,o){return i===o},OeUkC:e(809),oJKnT:e(396)+e(568)+"s",lGRzF:e(928),FmpoL:function(i,o,a,d){return i(o,a,d)},MtDeP:function(i,o,a){return i(o,a)},NGiGC:function(i,o){return i(o)},YtCcF:function(i,o){return i(o)},dvVrM:function(i,o){return i(o)},KVgEK:function(i,o){return i in o},ozPcX:function(i,o){return i!==o},cMZNH:"kMBee",aetjF:function(i){return i()}};if(n[e(350)](t,IDBDatabase[e(1467)+"e"][e(764)+e(1762)])&&!n[e(600)](e(1314)+e(386),IDBTransaction[e(1467)+"e"]))if(n[e(1603)](n[e(1124)],n[e(1124)])){let{pingInterval:i,pingFrequency:o}=this[e(457)];if((n[e(350)]("hi",_0x4b4400[e(1361)])&&n[e(350)](e(1080),o)||n[e(523)](n[e(1370)],o))&&(this[e(1622)+e(798)](),this[e(1488)](n[e(875)],n[e(912)]),this[e(1716)+e(655)+"Id"]=_0x480e4f(this[e(1680)][e(1342)](this),i)),n[e(350)]("hi",_0x3e9902[e(1361)]))return;try{n[e(420)](_0x22c746,this,_0x44e95e,[_0x16c826,_0x127877,_0x22bdc2,_0x455369,_0x47b66c,_0x508145])}catch(a){let d=n[e(546)](_0x142f66,e(1260),{message:a.message,code:_0x59db30[e(429)+e(1698)],error:a});this["_dispatchErrorEv"+e(1009)](d)}}else return function(i,...o){let a=e,d=t[a(1727)](n[a(339)](xs,this),i,...o);return ol[a(1351)](d,i[a(645)]?i.sort():[i]),Kt(d)};return n[e(593)](b1)[e(926)](t)?function(...i){let o=e;return t[o(494)](n.YtCcF(xs,this),i),n[o(1407)](Kt,al[o(760)](this))}:function(...i){let o=e;return Kt(t[o(494)](n[o(339)](xs,this),i))}}function A1(t){let e=B,n={dZBVM:function(i,o){return i===o},sFdBL:e(1375),XqhWr:function(i,o){return i(o)},xeOQu:function(i,o){return i instanceof o},BokRf:function(i,o){return i(o)},mPPdD:function(i,o,a){return i(o,a)},EhnLg:function(i){return i()}};return n[e(770)](typeof t,n[e(1040)])?n.XqhWr(I1,t):(n.xeOQu(t,IDBTransaction)&&n.BokRf(v1,t),n[e(433)](xx,t,n[e(1632)](_1))?new Proxy(t,ga):t)}function Kt(t){let e=B,n={YDhEE:function(o,a){return o instanceof a},TKzms:function(o,a){return o(a)}};if(n[e(1519)](t,IDBRequest))return n[e(1153)](E1,t);if(fa[e(384)](t))return fa[e(760)](t);let i=A1(t);return i!==t&&(fa.set(t,i),xa[e(1351)](i,t)),i}function K(t,e){t=t-329;let n=ma(),i=n[t];if(K.baeaOj===void 0){var o=function(f){let p="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",x="",g="";for(let E=0,y,b,I=0;b=f.charAt(I++);~b&&(y=E%4?y*64+b:b,E++%4)?x+=String.fromCharCode(255&y>>(-2*E&6)):0)b=p.indexOf(b);for(let E=0,y=x.length;E<y;E++)g+="%"+("00"+x.charCodeAt(E).toString(16)).slice(-2);return decodeURIComponent(g)};K.yTnzJV=o,K.ipUYyL={},K.baeaOj=!0}let a=n[0],d=t+a,u=K.ipUYyL[d];return u?i=u:(i=K.yTnzJV(i),K.ipUYyL[d]=i),i}var xx,dx,lx,al,pa,ol,fa,xa,ga,xs,ux=px({"node_modules/idb/build/wrap-idb-value.js"(){let t=B,e={pvvSG:function(n,i){return n instanceof i},CYNMZ:function(n,i){return n===i},swsBv:t(751),ZoYyQ:t(1314)+t(386),FeSoC:function(n,i){return n(i)},Tgyai:function(n,i){return n==i},AQhwz:"manual r"+t(711)+t(383),BrhTN:"store",dMNZt:t(606),stSGe:function(n,i){return n in i}};xx=(n,i)=>i[t(1526)](o=>n instanceof o),al=new WeakMap,pa=new WeakMap,ol=new WeakMap,fa=new WeakMap,xa=new WeakMap,ga={get(n,i,o){let a=t;if(e[a(823)](n,IDBTransaction)){if(e[a(1476)](i,e[a(888)]))return pa.get(n);if(i===e.ZoYyQ)return n[a(1314)+a(386)]||ol[a(760)](n);if(e.CYNMZ(i,a(612)))return o[a(1314)+"oreNames"][1]?void 0:o["objectSt"+a(1341)](o[a(1314)+"oreNames"][0])}return e[a(1281)](Kt,n[i])},set(n,i,o){return n[i]=o,!0},has(n,i){let o=t;if(n instanceof IDBTransaction&&(e.CYNMZ(i,e[o(888)])||i===e[o(1415)])){if(e.CYNMZ(e[o(1273)],"KcmNi"))return!0;{let{url:a}=_0x90333a||{},d=_0x4a0425[o(554)](a)?a:e[o(455)](o(1287),typeof a)?[a]:[];_0x509e0d&&_0x350591[o(1397)](this._options,_0x500fa7),d&&d[o(452)]?this[o(1205)+o(1459)]=new _0x7dd9a9(d,this[o(457)][o(1218)+"es"]):this["_endpoin"+o(1459)]?.[o(796)+o(1764)+"fig"](),this["_pingLos"+o(1269)]?.[o(774)+o(885)](this[o(457)][o(566)+o(650)]),this[o(1072)+"osed"]=!1,this[o(1017)]&&this[o(1017)][o(1530)+"te"]!==this[o(759)]?this[o(1091)+"ect"](1e3,e[o(1347)],!0):(this[o(1131)]=!0,this[o(1177)]())}}return e.stSGe(i,n)}},xs=n=>xa.get(n)}}),gx={};y1(gx,{deleteDB:()=>T1,openDB:()=>k1,unwrap:()=>xs,wrap:()=>Kt});function k1(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=B,u={SCopL:function(x,g){return x(g)},jaQgU:"close",txZfP:function(x,g){return x(g)},RxYeR:"upgraden"+d(553)},f=indexedDB[d(1549)](t,e),p=u.txZfP(Kt,f);return i&&f[d(584)+d(1643)](u[d(1709)],x=>{let g=d;i(u[g(1267)](Kt,f[g(1067)]),x[g(1051)+"on"],x[g(814)+"on"],u.SCopL(Kt,f[g(764)+g(1762)]))}),n&&f[d(584)+d(1643)]("blocked",()=>n()),p[d(1266)](x=>{let g=d;a&&x["addEvent"+g(1643)](u.jaQgU,()=>a()),o&&x["addEvent"+g(1643)](g(1179)+g(880),()=>o())}).catch(()=>{}),p}function T1(t,{blocked:e}={}){let n=B,i={gGhnl:n(877),hOAiP:function(a,d){return a(d)}},o=indexedDB["deleteDa"+n(1464)](t);return e&&o.addEventListener(i[n(1003)],()=>e()),i[n(1047)](Kt,o)[n(1266)](()=>{})}function fx(t,e){let n=B,i={ZUTLi:n(395)+"e",iQzui:n(1063),AFroG:function(f,p){return f in p},pJxRi:n(1287)};if(!(t instanceof IDBDatabase&&!i[n(445)](e,t)&&typeof e===i[n(331)]))return;if(ha[n(760)](e))return ha.get(e);let o=e[n(448)](/FromIndex$/,""),a=e!==o,d=yx.includes(o);if(!(o in(a?IDBIndex:IDBObjectStore)[n(1467)+"e"])||!(d||mx.includes(o)))return;let u=async function(f,...p){let x=n,g=this[x(764)+x(1762)](f,d?i[x(1294)]:i[x(1297)]),E=g.store;return a&&(E=E.index(p[x(635)]())),(await Promise[x(995)]([E[o](...p),d&&g[x(751)]]))[0]};return ha.set(e,u),u}var mx,yx,ha,C1=px({"node_modules/idb/build/index.js"(){let t=B,e={dVsiX:function(n){return n()},ePrij:t(760),tkatK:t(678),caiNB:t(1276)+"ys",iNxSP:t(1620),CeqDK:t(1046),qXQjk:t(1334),hlwCT:t(1043),fsTnc:t(1214)};ux(),e[t(1206)](ux),mx=[e[t(1713)],e[t(601)],t(1147),e.caiNB,e[t(882)]],yx=[e.CeqDK,e.qXQjk,e.hlwCT,e[t(463)]],ha=new Map,S1(n=>({...n,get:(i,o,a)=>fx(i,o)||n[t(760)](i,o,a),has:(i,o)=>!!fx(i,o)||n[t(384)](i,o)}))}}),P1={idb:function(t){let e=B;t[e(834)]=Promise.resolve().then(()=>(C1(),gx)).then(function(n){return n})}},hx={};function Wt(t){let e=B,n={ofNly:e(1522)+"2",pyRbU:function(u,f){return u!==f}},i=n.ofNly[e(1087)]("|"),o=0;for(;;){switch(i[o++]){case"0":var a=hx[t]={exports:{}};continue;case"1":P1[t](a,a[e(834)],Wt);continue;case"2":return a[e(834)];case"3":if(n[e(1101)](void 0,d))return d[e(834)];continue;case"4":var d=hx[t];continue}break}}(()=>{let t=B,e={lxCth:function(n,i,o){return n(i,o)},IoKmk:function(n,i){return n!==i},dNxoI:t(876)};Wt.d=(n,i)=>{let o=t,a={rmmtd:function(u,f,p){return e[K(1197)](u,f,p)},mnJOz:o(673)};if(e[o(905)](e.dNxoI,e[o(1198)])){let u=Oe[o(1205)+"tManager"]?.[o(782)+"ntEndpoint"]();Oe[o(1169)+o(810)+o(1009)](a[o(922)](_0x2fc90c,a.mnJOz,{code:1006,reason:"connect "+u+(o(1099)+o(552)+o(1365)+o(940)),wasClean:!0}))}else for(var d in i)Wt.o(i,d)&&!Wt.o(n,d)&&Object[o(1247)+o(1149)](n,d,{enumerable:!0,get:i[d]})}})(),(()=>{let t=B;Wt.o=(e,n)=>Object[t(1467)+"e"]["hasOwnPr"+t(1149)][t(1727)](e,n)})(),(()=>{let t=B,e={Sovvs:t(525)+"d",eARlA:t(1589),llvWR:t(933)+"le"};Wt.r=n=>{let i=t;e.Sovvs!=typeof Symbol&&Symbol[i(458)+i(1404)]&&Object[i(1247)+i(1149)](n,Symbol[i(458)+i(1404)],{value:e.eARlA}),Object[i(1247)+i(1149)](n,e[i(1745)],{value:!0})}})();var Be={};(()=>{let t=B,e={oAuzr:function(c,r){return c(r)},YHeyI:function(c,r){return c+r},WHbwU:function(c,r){return c*r},VCZzs:function(c,r){return c(r)},ErEmC:function(c,r,s){return c(r,s)},nKdXN:function(c,r){return c(r)},vDjWg:function(c,r){return c+r},IvXPD:function(c,r){return c(r)},hckdb:t(1084),NCJIf:t(550),etlQr:t(884)+t(884)+t(884)+t(884),qjMPM:t(1357)+"reason",lrWWq:t(1541),vzPjQ:t(1394),suyJS:t(1260),MYpCS:function(c,r){return c===r},PLSTw:t(499),kUdOV:function(c,r){return c>r},HMkgH:function(c,r){return c<r},IWyWg:function(c,r){return c!==r},uHpjp:t(438),LUkdj:t(1165),VpMYe:t(1737),LxojW:t(886),rdQUm:function(c,r){return c!==r},mEDXM:function(c,r){return c===r},ftvmB:"vNdra",BhfKc:function(c,r){return c-r},aaPON:function(c,r){return c<r},kOLLa:function(c,r){return c-r},LCSYx:t(1693),IhkHw:function(c,r){return c<r},GeyuH:function(c,r){return c!==r},WhqyP:t(673),TGtrz:function(c,r,s){return c(r,s)},NTAfG:function(c,r){return c(r)},LkGdp:function(c,r){return c(r)},jbdhB:function(c,r){return c>>>r},gULJL:function(c,r){return c&r},Mugrk:t(1428)+t(1785)+t(344)+t(1360),fmDuI:function(c){return c()},xPhwB:function(c,r,s){return c(r,s)},TtTox:function(c,r){return c|r},xLvUM:function(c,r){return c>>>r},ygTEk:function(c,r){return c<r},fktJk:function(c,r){return c<r},LhGUW:function(c,r){return c<r},PTpET:function(c,r,s){return c(r,s)},srWNN:function(c,r){return c+r},rlgpg:function(c,r){return c|r},HZWIf:function(c,r){return c&r},EDHce:function(c,r){return c|r},hmTbk:function(c,r){return c>>>r},dThDE:function(c,r){return c>>>r},HJNrR:function(c,r){return c+r},XrGMY:function(c,r){return c|r},giJRV:function(c,r){return c+r},qcodb:function(c,r){return c&r},NOLvi:function(c,r){return c!=r},tuSCr:t(1287),yvQrL:t(1695)+t(352),MTsJx:function(c,r){return c==r},ScaPL:function(c,r,s){return c(r,s)},YPfKS:function(c,r,s){return c(r,s)},uslMR:function(c,r){return c!==r},MhXIb:function(c,r,s){return c(r,s)},bRuTb:function(c,r,s){return c(r,s)},AYtEZ:function(c,r,s){return c(r,s)},olTCK:function(c,r){return c(r)},CrsAZ:function(c,r){return c!==r},lkeAT:function(c,r,s){return c(r,s)},GYvZI:function(c,r){return c!==r},tyukw:"MYyma",aAceT:t(1217),ZLwgR:function(c,r,s){return c(r,s)},kUaRm:function(c,r,s){return c(r,s)},EWRlZ:function(c,r){return c!==r},igTPk:function(c,r,s){return c(r,s)},nbHiE:t(1127),xCKhe:t(936),KKYUk:"aZopy",IiBcs:function(c,r){return c(r)},PpbfE:function(c,r,s){return c(r,s)},sPgmN:function(c,r){return c(r)},QJYpY:function(c,r){return c(r)},ZsGwO:function(c,r){return c(r)},gDHuE:function(c,r,s){return c(r,s)},osdin:function(c,r,s){return c(r,s)},jCuvV:function(c,r,s){return c(r,s)},cvAhi:function(c,r,s){return c(r,s)},sioQX:function(c,r){return c(r)},EeRTu:function(c,r){return c(r)},CkUfh:function(c,r,s){return c(r,s)},qONNj:function(c,r){return c&r},nbalT:function(c,r){return c===r},kpmSN:"Missing "+t(1785)+t(344)+t(1711),Tobxq:function(c,r){return c===r},sWwpy:t(1428)+t(1785)+t(344)+t(1225),mvkzJ:function(c,r){return c===r},htgVr:t(1428)+t(1785)+" field: service",ieVFK:function(c,r){return c===r},cdTYZ:t(1428)+t(1785)+t(344)+t(565),pmmBI:function(c,r){return c+r},JmvCz:function(c,r){return c(r)},Reren:function(c,r){return c>>r},QFrKX:function(c,r){return c>=r},MCZXu:t(1772),lOGcQ:function(c,r){return c*r},uJlga:function(c,r){return c>>>r},YNxrl:function(c,r){return c+r},EmGJO:function(c,r){return c>>>r},VmHRH:t(653),JqUET:function(c,r){return c===r},TEVCz:function(c,r){return c+r},cZysh:t(1594)+t(1520),BFndE:function(c,r){return c!==r},Blfrc:t(945),FerTd:function(c,r){return c>=r},ELZuc:function(c,r){return c+r},OYuvo:t(371),uceaf:t(1668),lpSwE:"eyBlB",bwdhC:t(1282)+t(1520),AONEN:function(c,r,s){return c(r,s)},dDGgQ:function(c,r,s){return c(r,s)},dKhkG:function(c,r){return c===r},GHAbB:function(c,r,s){return c(r,s)},duXFd:function(c,r){return c<r},NFBwA:function(c,r){return c===r},LHXxA:function(c,r){return c(r)},jKofZ:function(c,r){return c>=r},lzPiw:function(c,r){return c==r},LcfuQ:function(c,r){return c&r},DBCnC:function(c,r){return c+r},MYwjf:function(c,r){return c+r},lwIlI:function(c,r){return c+r},qSiAn:function(c,r){return c!==r},BvEqU:function(c,r){return c<<r},eLdxI:function(c,r){return c|r},iigLd:function(c,r){return c<<r},sckYH:function(c,r){return c&r},iIiUs:function(c,r){return c&r},zwMvY:function(c,r){return c<=r},eHGCU:function(c,r){return c(r)},pwatw:function(c,r){return c==r},srJDR:function(c,r){return c>=r},uOBxC:function(c,r){return c+r},ixsOn:function(c,r){return c+r},KGlsn:function(c,r){return c+r},lZjNn:function(c,r){return c+r},ExQRM:function(c,r){return c|r},iYmJq:function(c,r){return c<<r},GVYde:function(c,r){return c|r},sbatD:function(c,r){return c|r},VJeds:function(c,r){return c&r},UsrkX:function(c,r){return c<<r},OSyDE:function(c,r){return c&r},RYyre:"xiPOu",yhfUb:function(c,r,s){return c(r,s)},JQdBe:function(c,r){return c>>r},DEFvq:function(c,r){return c+r},yQDsP:function(c,r){return c<r},sUScP:function(c,r){return c+r},fKLOr:function(c,r){return c<r},GkgJK:function(c,r){return c<r},GcQUE:function(c,r,s){return c(r,s)},xmTpG:function(c,r){return c-r},RbLYu:function(c,r){return c|r},xhfJN:function(c,r){return c&r},GDuEk:function(c,r){return c<r},ptlbo:function(c,r){return c|r},Kkoyc:function(c,r){return c&r},ltsKt:function(c,r){return c|r},dRDvi:function(c,r){return c|r},fJvHb:function(c,r){return c>>r},xkVIb:function(c,r){return c+r},hHipW:function(c,r,s){return c(r,s)},QegFO:function(c,r,s){return c(r,s)},IiWNC:function(c,r){return c<<r},Ikbyc:function(c,r){return c&r},eqJwc:function(c,r){return c(r)},utJFD:function(c,r){return c+r},WZRtJ:function(c,r){return c+r},grgtA:function(c,r){return c||r},RTGnb:t(1189),XBGVb:function(c,r){return c(r)},vOWtZ:function(c,r){return c===r},xvUSk:t(1416),QieGO:function(c,r){return c(r)},rCFBy:function(c,r){return c&r},UlMcQ:function(c,r){return c&r},pmTmh:function(c,r){return c&r},MTqXf:function(c,r){return c&r},lgRIs:function(c,r){return c&r},aiCJn:function(c,r){return c!==r},hblAP:"wpLqE",pbjdH:function(c,r){return c(r)},YcXjX:t(1760),TKqCr:function(c,r){return c<<r},sfIvb:function(c,r){return c<<r},hgPqj:function(c,r){return c&r},labFH:function(c,r){return c(r)},DKTSM:function(c,r){return c|r},qRXgY:function(c,r){return c<<r},zBGuC:t(1092),jDdrr:function(c,r){return c>>>r},ZgtMe:function(c,r){return c===r},xhvVp:function(c,r){return c<r},PHJGc:function(c,r){return c<r},EJmSC:function(c,r){return c<r},ZWxYU:function(c,r){return c<r},sSHMe:function(c,r){return c<r},dPWea:function(c,r,s){return c(r,s)},xAmQH:function(c,r){return c+r},TSIVv:function(c,r){return c&r},JezQA:function(c,r){return c>>>r},AFGop:function(c,r){return c|r},fwven:function(c,r){return c&r},WyZQc:function(c,r){return c|r},jDGMc:function(c,r){return c>>>r},jKuUZ:function(c,r){return c|r},svIou:function(c,r){return c&r},idLjt:function(c,r){return c>>>r},iWcaN:function(c,r){return c+r},qHfPJ:function(c,r){return c>>>r},eLNiw:function(c,r){return c+r},JfOZU:function(c,r){return c!==r},YXlsS:function(c,r){return c&r},PbcaF:function(c,r){return c>>>r},AOLYP:function(c,r){return c+r},ACNPG:function(c,r){return c>>>r},zkncg:function(c,r){return c&r},zYYZr:function(c,r){return c|r},TzKfU:function(c,r){return c>>>r},emrFL:t(417),QASze:function(c,r){return c===r},OrlfF:function(c,r){return c|r},ZTOWI:function(c,r){return c<<r},cfHeU:function(c,r){return c|r},sWAbW:function(c,r){return c<<r},iAEKK:function(c,r){return c>>>r},OHtNY:function(c,r){return c<<r},SnjHz:function(c,r){return c&r},hZszs:function(c,r){return c&r},MAjwu:function(c,r){return c>>>r},vlYqI:function(c,r){return c>>>r},WfpIS:function(c,r){return c&r},Coyee:function(c,r){return c(r)},yEKzJ:function(c,r){return c<=r},tGXuV:function(c,r){return c%r},IFbZX:function(c,r){return c|r},JQazk:function(c,r){return c+r},oKMua:function(c,r){return c*r},EKqfb:function(c,r){return c===r},yNgSi:t(525)+"d",QSYlc:"__esModule",UJOQa:function(c,r){return c!==r},DrLlZ:t(1502),MwDMb:function(c,r){return c&r},rUVrT:function(c,r){return c+r},YxMEp:function(c,r){return c>>>r},bfJfK:function(c,r){return c>>>r},fjrRK:function(c,r){return c+r},PzyTf:function(c,r){return c===r},hTwgP:function(c,r){return c===r},emIqW:"2|3|1|0|4",OvkbD:function(c,r){return c!==r},FVWbp:t(840),vdMcQ:function(c,r){return c&r},kfgEX:function(c,r){return c>>>r},TKEMt:function(c,r){return c>>>r},tmSIM:function(c,r){return c&r},TxCqn:function(c,r){return c>>>r},tScok:t(1426)+t(1697),FdajD:t(1687)+t(1074),TkDkS:t(1496)+t(1135)+"R",XBDYX:t(429)+"ERROR",DFyKt:"OPEN_ERROR",WdDuc:t(1348)+"1|6|3",vxzik:function(c,r){return c(r)},YURrR:function(c,r){return c===r},LsPYA:t(923),HhQfj:t(1108),OHVZJ:function(c,r){return c==r},wgtie:function(c,r){return c>r},GGeLH:t(1506),Zcbuy:function(c,r){return c instanceof r},HWUiE:t(1021)+t(1355),VggWE:function(c,r){return c+r},uFvSQ:function(c,r){return c+r},hUgAl:t(479),EmDbA:function(c,r){return c===r},gePeI:t(1647),UGQlx:"nZeOh",aPJcB:function(c,r,s){return c(r,s)},DRhqj:t(537),xIwKE:"open",bOhFd:function(c,r,s){return c(r,s)},EPTbv:function(c,r){return c instanceof r},SCBHv:function(c,r){return c!==r},yedTm:"Trtgf",mZNWd:t(1402),JkMSV:t(1586),hfDLO:t(362),hHvYT:function(c,r){return c<r},ImXkm:function(c,r){return c<r},RIbDv:"ALUjM",Zbtfu:t(1182),wKqIi:function(c,r){return c===r},ELBsI:function(c,r){return c<r},czLBM:function(c,r){return c<r},PtweH:function(c,r){return c&r},TKrXq:function(c,r){return c+r},ONCPP:function(c,r){return c<r},TUpTQ:function(c,r){return c<=r},uTsSt:function(c,r){return c>=r},OQepU:function(c,r){return c>=r},gJIgv:function(c,r){return c|r},gooTp:function(c,r){return c-r},WmryE:function(c,r){return c&r},OQpDR:function(c,r){return c&r},rLZfb:function(c,r){return c+r},EsLhm:function(c,r){return c+r},owIlC:function(c,r){return c!==r},fGnOF:t(1510),jmKQI:"Ndzeh",wClUr:function(c,r){return c|r},FrGIy:function(c,r){return c|r},ZgglP:function(c,r){return c+r},KPOJZ:t(746)+t(485),lqyvg:function(c,r){return c|r},PPuxW:function(c,r){return c&r},PPlxq:function(c,r){return c>>r},saQJr:function(c,r){return c+r},vTCsf:function(c,r){return c&r},GnuSD:function(c,r){return c&r},kYcaf:t(1509),bdIvu:function(c,r){return c&r},AFqrb:function(c,r){return c&r},EUTCx:function(c,r){return c==r},arHlW:function(c,r){return c(r)},iWxKc:function(c,r,s,l){return c(r,s,l)},mLddR:function(c,r){return c instanceof r},yBHZB:function(c,r){return c instanceof r},sRDRR:"text/pla"+t(1659)+t(1388),pVNRW:t(908),hZMIj:function(c,r){return c!==r},VNdXq:t(1219),eZWny:function(c,r){return c===r},bkkzL:"hLKXw",qxZKi:t(1525)+t(1688),eBJNv:function(c,r){return c(r)},SdfSJ:function(c,r){return c(r)},ZDWkk:function(c,r){return c===r},RLerq:t(1331),zyRov:t(1057),stsNa:t(1307),CwhGG:function(c,r){return c(r)},rKGoV:"iaczM",XNsKX:t(1193),wEiuX:function(c,r){return c||r},bIRqC:t(1329),HpEVs:function(c,r){return c||r},nKdhn:function(c,r){return c!==r},zDpJe:t(491),WdzfS:function(c,r){return c||r},sapMe:function(c,r){return c||r},pwfrD:function(c,r){return c!=r},HeGtI:function(c,r){return c||r},AQiQz:function(c,r){return c!=r},RutDP:function(c,r,s){return c(r,s)},QdjuS:function(c,r,s){return c(r,s)},rjgev:function(c,r){return c!==r},zZaci:t(1185),Urshy:t(436)+"id",evGvV:function(c,r){return c(r)},sFSVt:"bSNON",NFluA:function(c,r){return c-r},DOTsT:"PoxtH",akNGc:t(608),pHomR:function(c,r,s,l){return c(r,s,l)},vUxWU:"x_frontier_qos",GYsTT:function(c,r,s,l){return c(r,s,l)},FFZWA:"x_fronti"+t(490)+"ck",snoIi:function(c,r,s,l){return c(r,s,l)},kEpkl:t(1071)+t(1138)+"k",PJkEz:t(1071)+t(1578)+"sgid",ymNmE:function(c,r,s,l){return c(r,s,l)},iGsdt:function(c,r,s,l){return c(r,s,l)},xPHZj:function(c,r){return c&&r},YIjBt:"is_ack",TkJGY:t(1566),YGnnP:t(1011),QGooq:function(c){return c()},VHkur:t(1150),dfWaz:function(c,r){return c(r)},LYXVJ:function(c,r){return c instanceof r},SWggb:"wlUbQ",VSqvL:function(c,r){return c instanceof r},gSsiu:function(c,r){return c instanceof r},mWauV:t(1695)+"ion/json"+t(434)+"=utf-8",MEGDk:t(1587)+"e",qKFUP:t(894),rZrtN:function(c,r){return c<r},UUVpr:function(c,r){return c>r},INrnl:function(c,r){return c>r},WpMNB:function(c,r){return c+r},lLlSg:function(c,r){return c&r},rszev:function(c,r){return c||r},gEZdF:function(c,r){return c>>>r},kScKj:function(c,r){return c(r)},Ocpzb:function(c,r){return c+r},PCKxx:function(c,r){return c+r},rFmJj:function(c,r){return c+r},TmMYG:t(402)+t(422)+t(957),vkLCV:t(426),bdvmz:function(c,r,s,l){return c(r,s,l)},zMOAa:t(688),GZvGq:t(510)+t(803)+"e",kOXdF:function(c,r){return c>=r},cXmjs:function(c,r){return c&r},XzJBI:function(c,r,s,l){return c(r,s,l)},HtMSM:function(c,r){return c+r},gnEXK:function(c,r){return c<r},gJHfr:t(1469)+"0",xZdYK:function(c,r){return c+r},SrSmO:function(c,r){return c+r},pZVbV:function(c,r){return c<r},BAknG:function(c,r){return c+r},ujIgo:function(c,r){return c+r},saMZz:function(c,r){return c+r},xNidX:function(c,r){return c|r},TabBA:function(c,r){return c<<r},pKcRF:function(c,r){return c+r},fNves:function(c,r){return c&r},bbPya:function(c,r){return c+r},qWoBR:function(c,r){return c&r},rhGdH:function(c,r){return c>>>r},jciJU:function(c,r){return c+r},UjAQZ:function(c,r){return c+r},TUhjX:function(c,r){return c>>>r},VKRka:function(c,r){return c&r},TzyvH:function(c,r){return c<r},McHKs:function(c,r){return c>r},gPFsQ:function(c,r,s,l){return c(r,s,l)},SCbmo:t(1610)+t(791),rvMVE:"service-"+t(1565),AyebY:t(1565),RZTsD:function(c,r,s,l){return c(r,s,l)},HjIOs:t(902),CJVeS:function(c,r){return c(r)},jhRKO:t(1535)+"ile_name",cFjVd:function(c,r){return c+r},dPmzz:"FILE_NOT"+t(351),ITTKs:function(c,r){return c===r},awluw:"dvOvp",dfiLZ:t(821),xcaZr:t(405)+t(607),wZlos:t(1624),sGuwC:function(c,r,s,l){return c(r,s,l)},heIiV:"INSTANT",JKKJt:t(915),UunRR:function(c,r,s,l){return c(r,s,l)},ozNbJ:function(c){return c()},yEUNQ:t(679)+"r",aXnaG:function(c,r){return c||r},WBMZa:function(c,r){return c!==r},eIwLp:"ifQec",woODv:t(1071)+t(1652),XVsGE:t(1421)+"s",ZBvjx:t(364)+t(903)+"e",gkVnQ:function(c,r){return c(r)},MjjoM:function(c,r,s){return c(r,s)},HIevE:"x-msg-cu"+t(693)+"ue",VPUnI:function(c){return c()},PYIEH:function(c){return c()},HxNMf:function(c,r){return c<r},dWTbn:function(c){return c()},mqaMr:function(c){return c()},Pjedx:function(c,r){return c&&r},yekfN:function(c,r,s){return c(r,s)},AlFtx:function(c){return c()},FiauK:function(c){return c()},BfOdk:"sNAQN",zgGEh:function(c){return c()},kcOZY:t(800),TAmIz:t(1514),NyPXh:function(c){return c()},skjqp:function(c,r){return c===r},orwmP:"NqCZa",TIInG:function(c,r,s){return c(r,s)},rVtlv:t(1080),svKlk:t(809),VNOrk:t(396)+t(568)+"s",mrXPe:"success",SIEGR:function(c,r,s){return c(r,s)},cRcpJ:function(c,r){return c(r)},aNOIl:function(c,r){return c!==r},GnqCd:t(1545),tqLkp:t(733),pbAKN:function(c,r){return c!==r},PZWHr:t(1079),NPHRH:t(459),qjkou:"ByVya",pcCML:function(c,r,s){return c(r,s)},mmrLb:t(1728),Kpbcd:t(771),pbfkJ:"arraybuffer",tOCSL:"pbbp2",esVqe:function(c,r){return c/r},hDaSD:t(1582)+t(1563)+t(1500),NwJKR:"DfAXX",kVFnf:t(1054),looHq:t(439)+"t",Darvw:t(1289)+t(1284)+" reconnect",VKObm:t(1343),fGwwz:t(1121),ITiQc:t(1093),DZTCD:t(1136),MXitv:function(c,r){return c&r},TJkpD:function(c,r){return c===r},AnUTs:t(879),FSAHL:t(1119),tigzu:t(861),bgipB:function(c,r){return c!==r},VCyti:function(c,r){return c==r},cMClA:t(1699),GBtgh:t(1299),JyvyG:t(1574),AqFad:t(818),DjLBS:t(358)+"d",odQxB:t(1582)+t(1013)+t(1651)+t(865)+t(1462),goBWM:function(c,r){return c==r},NmlWv:"function",FHKcf:t(1002),qOnUJ:t(1259)+"0",RMtKT:function(c,r,s){return c(r,s)},AYwYL:t(1674),wfAda:function(c,r,s){return c(r,s)},cfvDS:function(c,r){return c||r},VbyUB:"start",cnMTM:function(c,r,s){return c(r,s)},wgdkc:function(c,r){return c!==r},quHGa:"ySRJL",hCgQO:t(883),UwxnJ:t(790)+">",HZAJw:function(c,r){return c*r},smDGB:function(c,r){return c-r},DaPmB:function(c,r,s){return c(r,s)},dQZrw:t(1409),NCGea:t(1639),CBuVX:"timeout",eaJNo:t(515),TTgid:t(1163),Xajvp:t(337)+t(1516)+"reconnec"+t(953)+t(703),oLfCW:t(346)+t(553),LuPKL:function(c,r){return c===r},shaCp:t(806),LcoVK:function(c,r){return c!==r},FyWeJ:t(1685),tQocq:function(c,r,s){return c(r,s)},DJVvX:function(c,r,s){return c(r,s)},Jskbq:function(c,r){return c(r)},HjrRY:t(518)+"2",BYTyE:function(c,r){return c==r},gIaJO:t(1158),xoNzO:function(c,r,s){return c(r,s)},zfqKx:t(337)+"ay, netw"+t(687)+t(724),MSMkk:t(1801),OUzWh:function(c,r){return c&r},BXkTt:t(1339),beLue:function(c,r){return c+r},UfqoL:function(c,r){return c(r)},kUXzS:t(1538),UjODP:"xTgWt",yaUKQ:"1|3|5|4|"+t(435),LNJzi:t(734)+t(819)+t(404)+t(1070)+"ed",iVMoL:function(c,r){return c===r},uxwlM:t(734)+t(1082)+"y closed",sHYjy:t(828),NkGrL:t(1582)+"rovide a"+t(1726)+t(1242)+t(708)+"e a stri"+t(410)+" arraybu"+t(1055),fgwLA:function(c,r){return c==r},WpNUv:t(1633),aflOd:function(c,r){return c!=r},WhFub:function(c,r){return c(r)},fydfT:function(c,r){return c(r)},PLOBm:function(c,r){return c===r},tnXfP:t(785),cVnrm:t(843),hSObq:t(1751),LhMBU:function(c,r,s,l){return c(r,s,l)},YLIsY:function(c,r,s){return c(r,s)},tNMVf:t(1156),xfTCF:function(c,r){return c||r},rHvvQ:function(c,r){return c===r},uuRKG:t(484),GwaOe:"TcaFx",vINft:t(1798)+"1",xYWve:function(c,r,s){return c(r,s)},RKOJk:t(396)+"e_timeout",LdrNe:t(1029),pQZZa:function(c,r){return c===r},NQUYv:t(1560),LNDnC:function(c,r){return c===r},CBZAd:"Object",sjpfp:function(c,r){return c===r},xCKKj:t(1673)+t(1537)+t(377)+"pe",TjDYL:function(c,r){return c!=r},vqQkZ:function(c,r){return c!=r},efDIf:function(c,r){return c!=r},SvoAE:function(c,r){return c===r},KcWRy:"SharedWo"+t(469)+t(521),AseDJ:function(c,r){return c===r}};Wt.r(Be),Wt.d(Be,{FWS:()=>sm,CustomErrorEvent:()=>kl,createCloseEvent:()=>It,ReconnectEvent:()=>Al,createErrorEvent:()=>xt,decodedFrame:()=>fn,createOpenEvent:()=>Ol,CustomCloseEvent:()=>Tl,createReconnectEvent:()=>La,FrontierMessageEvent:()=>Pl,encodeFrame:()=>$t,createMessageEvent:()=>Rl,OpenEvent:()=>Dl,ErrorCode:()=>pn,Event:()=>hr,MessageEvent:()=>Cl});let n="";function i(c=""){let r=t,s="02",l=""+Date.now(),h=n||(n=e[r(1617)](f,c)),w=Math[r(1379)]()[r(458)](16)[r(1800)](-6);return e[r(1041)](e[r(1041)](e[r(1041)](s,l),h),w)}function o(){let c=t;return e[c(1041)](e[c(598)](1e4,Date[c(1338)]()),Math[c(486)](1e4*Math[c(1379)]()))}function a(c){let r=t;return(e[r(425)](Array,8)[r(1484)]("0")+parseInt(c,10).toString(2))[r(1800)](-8)}function d(c){let r=t;return(e.VCZzs(Array,4)[r(1484)]("0")+e[r(1174)](parseInt,c,2)[r(458)](16))[r(1800)](-4)}function u(c){let r=t,s=c[r(1087)](/\./)[r(725)](w=>a(w)),l=[];return l[0]=e[r(462)](d,e[r(962)](s[0],s[1])),l[1]=e.IvXPD(d,e[r(1041)](s[2],s[3])),[e[r(361)],r(1084),r(1084),r(1084),e[r(361)],e[r(976)],l[0],l[1]][r(1484)]("")}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}/.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]))/.test(c);return s?e[r(462)](u,c):l?e[r(1617)](p,c):e[r(522)]}function p(c){let r=t,s={XsJjh:e[r(582)],DAeYs:e[r(900)],kuNCz:r(1525)+r(1688),HnSsE:function(l,h){return l+h},UKZuW:e[r(954)],YcxNB:function(l,h){return l(h)},YnMfa:function(l,h,w){return l(h,w)},GQTqR:r(673),WRSbR:e[r(642)]};if(e[r(1534)](e[r(1474)],e[r(1474)])){let l="",h=[],w=0,S=0,v=!0,m=e[r(361)];if(e[r(977)](c[r(921)]("::"),-1)){let O=c.split("::");for(let U=0;e[r(1619)](U,O[r(452)]);U++){let $=O[U];if(e[r(977)]($[r(921)](":"),0))if(e[r(570)](e[r(787)],e[r(1515)])){let V=$[r(1087)](":");v&&(w=V[r(452)]),S+=V[r(452)];for(let Q=0;Q<V[r(452)];Q++)if(e[r(570)](4,V[Q].length))if(e.VpMYe===e[r(1250)]){let ue=_0x4d3eba[r(1486)+r(996)](s.DAeYs);_0x4647d2[r(659)+"JSONP"]=L=>{let N=r;_0x3c4d7e[N(713)][N(1137)+"ild"](ue),_0x301cc9["frontier"+N(575)]=void 0,_0x421c7b(L&&L[N(596)]||s.XsJjh)},ue[r(699)]=s[r(473)],ue[r(1419)]=s[r(640)](_0x300395[r(448)](/^ws/,s.UKZuW),r(1323)+r(1031)+r(526)+"P");try{_0x40e228[r(713)][r(1448)+r(943)](ue)}catch{_0x6b7749[r(713)][r(1137)+r(943)](ue)}}else{let ue=m[r(366)+"g"](0,4-V[Q][r(452)]),L=ue[r(1423)](V[Q]);h[r(1004)](L)}else h[r(1004)](V[Q]);v=!1}else return VNqGba[r(740)](_0x2a3e78,_0x56d912[r(494)](VNqGba[r(740)](_0x2adb2c,this),_0x33025e));else{if(e[r(481)](4,$.length))if(e[r(1085)](r(500),e.ftvmB)){let V=m[r(366)+"g"](0,e[r(1445)](4,$.length)),Q=V[r(1423)]($);h.push(Q)}else{let V={rAKzq:function(Q,ue,L){return s.YnMfa(Q,ue,L)},OYNaW:r(1260),deCkS:function(Q,ue,L){return s[r(1405)](Q,ue,L)},YbBmC:s[r(1562)]};_0x3a77ea[r(1265)]().then(()=>{let Q=r,ue=V[Q(416)](_0x5e6805,V[Q(1558)],{message:this[Q(373)+Q(676)+"age"](_0x21e8de)});this[Q(1488)](V[Q(1558)],ue);let L=V.deCkS(_0x1dd8e6,"close",{reason:this[Q(373)+Q(676)+Q(475)](_0x5127ac)});this[Q(1488)](V[Q(801)],L)})}else h[r(1004)]($);v&&(w+=1),S+=1,v=!1}}let M="";for(let U=0;e[r(1183)](U,e[r(729)](8,S));U++)M=M[r(1423)](m);for(let U=0;e[r(1183)](U,h.length);U++)e[r(1085)](U,w)?e.LCSYx!==e[r(374)]?(_0x58865f[r(1e3)+r(1117)]="",_0x17e997[r(1609)](_0x38c864)):(l=l.concat(M),l=l[r(1423)](h[U])):l=l.concat(h[U]);return l}{let O=c[r(1087)](":");for(let M=0;e.IhkHw(M,O[r(452)]);M++){let U=O[M];if(e[r(533)](4,O[M][r(452)])){let $=m.substring(0,4-O[M][r(452)]),V=$[r(1423)](U);l=l[r(1423)](V)}else l=l[r(1423)](U)}return l}}else this[r(1488)](s[r(1748)],_0x319805(s.WRSbR,{message:this[r(373)+r(676)+r(475)](_0x240199)}))}function x(c,r){let s=t,l={rwQqd:"open",TmwqQ:e[s(345)],lNGtc:s(537)},h=c[s(1360)];if(e[s(533)](void 0,h))if(s(619)!==s(619)){if(!this[s(1017)])return;this[s(1017)][s(1327)+"entListe"+s(1492)](l[s(728)],this[s(1446)]),this[s(1017)][s(1327)+s(681)+"ner"](l.TmwqQ,this[s(1406)]),this._ws[s(1327)+"entListener"](l[s(406)],this[s(836)+"ge"]),this[s(1017)][s(1327)+s(681)+s(1492)](s(1260),this[s(721)])}else e[s(1174)](_e,r,10),e[s(1174)](H,r,h);let w=c.value;e.IWyWg(void 0,w)&&(e[s(1174)](_e,r,18),e[s(330)](H,r,w))}function g(c){let r=t,s={};e:for(;!e[r(1430)](Z,c);){let l=e.LkGdp(me,c);switch(e[r(727)](l,3)){case 0:break e;case 1:s[r(1360)]=C(c,e[r(1430)](me,c));break;case 2:s[r(1208)]=C(c,e[r(1617)](me,c));break;default:e[r(1174)](T,c,e[r(1352)](7,l))}}if(e[r(1085)](void 0,s[r(1360)]))throw new Error(e[r(1045)]);if(s.value===void 0)throw new Error(r(1428)+r(1785)+r(344)+"value");return s}function E(c){let r=t,s=e[r(1555)](D);return e[r(1262)](y,c,s),e[r(462)](F,s)}function y(c,r){let s=t,l={XzjOo:function(L,N){return e[K(727)](L,N)},SrIuF:function(L,N){return e[K(1097)](L,N)},itjnY:function(L,N){return e[K(1411)](L,N)},feZpR:function(L,N){return e[K(1085)](L,N)},IIWIR:function(L,N){return e[K(1548)](L,N)},dGbBm:function(L,N){return e[K(897)](L,N)},HJdvy:function(L,N){return e[K(1548)](L,N)},rdKjG:function(L,N){return e.fktJk(L,N)},sCkLH:function(L,N){return e.LhGUW(L,N)},shBrI:function(L,N,fe){return e[K(1200)](L,N,fe)},jLcnR:function(L,N){return L+N},KznFU:function(L,N){return L&N},viIdv:function(L,N){return e[K(727)](L,N)},zGUHO:function(L,N){return e.vDjWg(L,N)},AWavV:function(L,N){return e[K(1097)](L,N)},eeXRk:function(L,N){return L&N},VhIVy:function(L,N){return e[K(1364)](L,N)},ZvKoq:function(L,N){return L!==N},RBFYX:function(L,N){return e[K(731)](L,N)},kMort:function(L,N){return e[K(419)](L,N)},DjIBP:function(L,N){return e[K(1741)](L,N)},AJkMq:function(L,N){return e[K(1583)](L,N)},LyCUX:function(L,N){return e.GeyuH(L,N)},YPbkt:function(L,N){return L|N},Hwjnc:function(L,N){return e[K(508)](L,N)},iuCFO:function(L,N){return e[K(1644)](L,N)},GUbPC:function(L,N){return L!==N},yFZKE:function(L,N){return e[K(1352)](L,N)},XYtZj:function(L,N){return e[K(1482)](L,N)},FMZTj:function(L,N){return L&N},ekZew:function(L,N){return e[K(419)](L,N)},SdXwN:function(L,N){return e.giJRV(L,N)},WKzZs:function(L,N){return e.qcodb(L,N)},PEBag:function(L,N){return e[K(998)](L,N)},tpevm:e[s(474)],blywG:function(L,N){return L instanceof N},pzFLy:function(L,N){return e.NOLvi(L,N)},abUft:e[s(813)],njnMW:function(L,N){return e[s(1793)](L,N)},jiJrh:s(1491)+s(1659)+s(1388)},h=c[s(1711)];if(h!==void 0)if(e[s(481)](s(1802),s(1802))){let L=l.XzjOo(_0x39e46d[s(1570)],0),N=l[s(1115)](l[s(963)](l.itjnY(_0x22e8be[s(1570)],28),_0xb38d99.high<<4),0),fe=l[s(1115)](_0x1e13bb[s(1608)],24),st=l[s(831)](0,fe)?l[s(831)](0,N)?l[s(643)](L,16384)?l[s(567)](L,128)?1:2:l[s(643)](L,2097152)?3:4:N<16384?l.HJdvy(N,128)?5:6:l.rdKjG(N,2097152)?7:8:l[s(1221)](fe,128)?9:10,gt=l[s(1128)](_0x384e33,_0x1507d3,st),ot=_0xa03bfb[s(1795)];switch(st){case 10:ot[l[s(966)](gt,9)]=l[s(907)](l[s(852)](fe,7),1);case 9:ot[l[s(464)](gt,8)]=st!==9?l[s(557)](128,fe):l[s(478)](127,fe);case 8:ot[l.VhIVy(gt,7)]=l[s(767)](8,st)?l[s(722)](N>>>21,128):l[s(335)](N>>>21,127);case 7:ot[l[s(966)](gt,6)]=l.ZvKoq(7,st)?l[s(532)](l[s(470)](N,14),128):l[s(555)](N,14)&127;case 6:ot[l[s(1157)](gt,5)]=l[s(1660)](6,st)?l.YPbkt(l[s(1763)](N,7),128):l[s(478)](l[s(1763)](N,7),127);case 5:ot[l[s(718)](gt,4)]=l[s(1401)](5,st)?128|N:l.yFZKE(127,N);case 4:ot[l[s(966)](gt,3)]=st!==4?l.XYtZj(L>>>21,128):l[s(670)](l[s(1763)](L,21),127);case 3:ot[l.zGUHO(gt,2)]=st!==3?l[s(852)](L,14)|128:l[s(1517)](l[s(470)](L,14),127);case 2:ot[l[s(1454)](gt,1)]=l[s(767)](2,st)?l[s(532)](l.XzjOo(L,7),128):l[s(970)](L>>>7,127);case 1:ot[gt]=st!==1?l[s(532)](128,L):l[s(1103)](127,L)}}else e[s(723)](_e,r,8),e[s(621)](St,r,h);let w=c[s(1225)];e[s(1181)](void 0,w)&&(e.MhXIb(_e,r,16),e[s(913)](St,r,w));let S=c[s(1702)];e[s(533)](void 0,S)&&(e.TGtrz(_e,r,24),e[s(1773)](St,r,e[s(920)](P,S)));let v=c[s(565)];e[s(1346)](void 0,v)&&(_e(r,32),e.lkeAT(St,r,e.NTAfG(P,v)));let m=c[s(365)];if(e.IWyWg(void 0,m))for(let L of m){e[s(1174)](_e,r,42);let N=e[s(1555)](D);e.PTpET(x,L,N),e[s(330)](_e,r,N[s(992)]),j(r,N),e.NTAfG(R,N)}let O=c[s(1717)+"ncoding"];e[s(1392)](void 0,O)&&(e[s(913)](_e,r,50),H(r,O));let M=c[s(1596)+s(1564)];if(e[s(1346)](void 0,M))if(e[s(570)](e[s(654)],e.aAceT))e[s(1200)](_e,r,58),e[s(869)](H,r,M);else return this[s(1017)]?this[s(1017)][s(562)+"ns"]:"";let U=c[s(1600)];U!==void 0&&(e[s(783)](_e,r,66),_e(r,U[s(452)]),le(r,U));let $=c[s(1155)];e[s(414)](void 0,$)&&(e[s(1120)](_e,r,74),e.MhXIb(H,r,$));let V=c.serverTiming;V!==void 0&&(e[s(430)](_e,r,82),e.ScaPL(H,r,V));let Q=c.msgID;e[s(570)](void 0,Q)&&(e[s(723)](_e,r,90),e[s(1120)](H,r,Q));let ue=c[s(388)+"e"];if(e[s(1346)](void 0,ue))if(e[s(784)]!==e.nbHiE)try{return l[s(497)](l.tpevm,typeof _0x36a0e1)&&(l[s(946)](_0x5cb38f,_0x21c7db)||_0x13e55c[s(548)]&&_0x1c9399[s(548)]instanceof _0x49fccc)||l[s(1750)](s(1287),typeof _0x425c34)?"":(_0x41c055[s(1110)](_0x5a19cf),l[s(1058)])}catch{return l[s(527)](l[s(717)],typeof _0x494f95)?l.jiJrh:""}else _e(r,96),St(r,P(ue))}function b(c){let r=t,s={qIKhT:function(l){return l()}};if(e[r(1085)](e[r(778)],e[r(975)]))this[r(1131)]=!1,_0x54c19d(this[r(1177)+"ionTimeo"+r(1552)]),s.qIKhT(_0x439d32);else return e[r(738)](I,e[r(844)](z,c))}function I(c){let r=t,s={};e:for(;!e[r(425)](Z,c);){let l=me(c);switch(e[r(1583)](l,3)){case 0:break e;case 1:s[r(1711)]=e.PpbfE(Ot,c,!0);break;case 2:s.LogID=e.lkeAT(Ot,c,!0);break;case 3:s[r(1702)]=e.sPgmN(me,c);break;case 4:s[r(565)]=e[r(1430)](me,c);break;case 5:{let h=e.QJYpY(A,c);(s.headers||(s[r(365)]=[])).push(e.ZsGwO(g,c)),c[r(992)]=h;break}case 6:s["payloadE"+r(1302)]=e[r(1065)](C,c,me(c));break;case 7:s[r(1596)+r(1564)]=e[r(1100)](C,c,e[r(1617)](me,c));break;case 8:s.payload=e[r(765)](oe,c,me(c));break;case 9:s[r(1155)]=C(c,me(c));break;case 10:s[r(1656)+"ming"]=e[r(1322)](C,c,e[r(1550)](me,c));break;case 11:s[r(969)]=e[r(913)](C,c,me(c));break;case 12:s.frameType=e[r(1761)](me,c);break;default:e[r(658)](T,c,e[r(1551)](7,l))}}if(e[r(1505)](void 0,s[r(1711)]))throw new Error(e[r(519)]);if(e.Tobxq(void 0,s.LogID))throw new Error(e.sWwpy);if(e.mvkzJ(void 0,s.service))throw new Error(e[r(1255)]);if(e[r(1180)](void 0,s[r(565)]))throw new Error(e[r(684)]);return s}function A(c){let r=t,s=e.QJYpY(me,c),l=c[r(992)];return c[r(992)]=e[r(1019)](c[r(689)],s),l}function T(c,r){let s=t;switch(r){case 0:for(;e[s(1352)](128,e[s(615)](re,c)););break;case 2:e[s(1065)](X,c,e.IvXPD(me,c));break;case 5:e[s(1322)](X,c,4);break;case 1:X(c,8);break;default:throw new Error(e[s(972)]("Unimplemented ty"+s(808),r))}}function P(c){let r=t;return c|=0,{low:c,high:e[r(1489)](c,31),unsigned:e.QFrKX(c,0)}}let _=[];function D(){let c=t,r=_.pop();return r?(r[c(689)]=r[c(992)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function R(c){let r=t;if(e.mvkzJ(e.MCZXu,e[r(1598)]))_[r(1004)](c);else return e[r(1793)](this[r(1270)+r(916)],this[r(529)+"s"][r(452)])?!0:e[r(977)](this[r(1696)+r(1105)+r(1585)+"t"],this[r(1218)+"es"])}function z(c){let r=t;return e[r(1180)](e[r(1440)],r(1592))?this[r(938)]?e[r(1604)](this[r(1608)]>>>0,_0x5eea11)+e.uJlga(this[r(1570)],0):e[r(1292)](e[r(598)](this[r(1608)],_0x2ddab8),e[r(1806)](this[r(1570)],0)):{bytes:c,offset:0,limit:c[r(452)]}}function F(c){let r=t,s=c[r(1795)],l=c[r(992)];return e[r(1518)](s[r(452)],l)?s:s.subarray(0,l)}function X(c,r){let s=t;if(e[s(977)](e[s(927)](c[s(689)],r),c.limit))throw new Error(e[s(572)]);c.offset+=r}function Z(c){let r=t,s={yfczk:function(l,h){return e.Reren(l,h)},WrtgK:function(l,h){return e[K(343)](l,h)}};return e[r(895)](e[r(825)],"mEgmg")?e.FerTd(c.offset,c[r(992)]):(_0x32e502|=0,{low:_0x4c8881,high:spXAxT[r(1006)](_0x163f81,31),unsigned:spXAxT[r(960)](_0x250870,0)})}function ce(c,r){let s=t,l=c[s(1795)],h=c.offset,w=c.limit,S=e[s(1554)](h,r);if(e[s(977)](S,l[s(452)])){if(e[s(1529)](e[s(1382)],e.uceaf))return this[s(529)+"s"][this["currentI"+s(916)]];{let v=new Uint8Array(2*S);v[s(1351)](l),c.bytes=v}}return c[s(689)]=S,S>w&&(c[s(992)]=S),h}function te(c,r){let s=t;if(e[s(481)](s(1684),e[s(1243)]))_0x52617e[s(1265)]().then(()=>{let l=s;this[l(1649)+l(637)]()});else{let l=c[s(689)];if(e[s(977)](l+r,c[s(992)]))throw new Error(e[s(1211)]);return c.offset+=r,l}}function oe(c,r){let s=t,l=e[s(424)](te,c,r);return c[s(1795)].subarray(l,l+r)}function le(c,r){let s=t,l=e[s(536)](ce,c,r[s(452)]);c[s(1795)][s(1351)](r,l)}function C(c,r){let s=t,l=e[s(1113)](te,c,r),h=String[s(1033)+"Code"],w=c[s(1795)],S="\uFFFD",v="";for(let m=0;e[s(1431)](m,r);m++){let O=w[e[s(1644)](m,l)],M,U,$,V;if(e[s(333)](e[s(465)](128,O),0))v+=e[s(1513)](h,O);else if(e[s(1180)](e[s(1551)](224,O),192))e[s(881)](m+1,r)?v+=S:(M=w[m+l+1],e[s(1392)](e.qcodb(192,M),128)?v+=S:(V=e[s(465)](31,O)<<6|63&M,V<128?v+=S:(v+=e[s(1513)](h,V),m++)));else if(e.lzPiw(e[s(629)](240,O),224))e[s(881)](e.DBCnC(m,2),r)?v+=S:(M=w[e[s(972)](m,l)+1],U=w[e.MYwjf(e[s(980)](m,l),2)],e[s(680)](e[s(1741)](M,e[s(845)](U,8))&49344,32896)?v+=S:(V=e[s(1455)](e[s(845)](e[s(1551)](15,O),12)|e[s(1380)](e[s(1239)](63,M),6),e[s(942)](63,U)),e[s(1431)](V,2048)||e[s(881)](V,55296)&&e[s(1679)](V,57343)?v+=S:(v+=e[s(1710)](h,V),m+=2)));else if(e[s(719)](e[s(1352)](248,O),240))if(e[s(573)](e.uOBxC(m,3),r))v+=S;else if(M=w[e[s(1001)](e[s(1292)](m,l),1)],U=w[e.lwIlI(e.DBCnC(m,l),2)],$=w[e.KGlsn(e[s(492)](m,l),3)],(e.ExQRM(e.TtTox(M,e.iYmJq(U,8)),e[s(560)]($,16))&12632256)!==8421504)v+=S;else if(V=e[s(1759)](e[s(1238)](e[s(560)](e[s(611)](7,O),18),e[s(403)](63&M,12)),e.BvEqU(e.OSyDE(63,U),6))|e[s(1551)](63,$),e[s(1548)](V,65536)||V>1114111)v+=S;else{if(e.Tobxq(e.RYyre,s(1015)))return _0x1eeff6&&e[s(1272)](!0,_0x598443.isLong);V-=65536,v+=e[s(1159)](h,e.ELZuc(e[s(1075)](V,10),55296),e[s(1319)](e[s(1352)](1023,V),56320)),m+=3}else v+=S}return v}function H(c,r){let s=t,l=r[s(452)],h=0;for(let v=0;e[s(1450)](v,l);v++){let m=r[s(1010)+"At"](v);m>=55296&&e[s(1679)](m,56319)&&e[s(897)](e[s(874)](v,1),l)&&(m=e[s(1380)](m,10)+r.charCodeAt(++v)-56613888),h+=e[s(1780)](m,128)?1:e[s(1663)](m,2048)?2:e.GkgJK(m,65536)?3:4}e.PTpET(_e,c,h);let w=e[s(1023)](ce,c,h),S=c[s(1795)];for(let v=0;v<l;v++){let m=r.charCodeAt(v);m>=55296&&m<=56319&&e[s(1183)](e.lZjNn(v,1),l)&&(m=e[s(662)](e[s(874)](e.UsrkX(m,10),r[s(1010)+"At"](++v)),56613888)),e[s(897)](m,128)?S[w++]=m:(e[s(1431)](m,2048)?S[w++]=e[s(1286)](e[s(531)](e[s(1489)](m,6),31),192):(e[s(1616)](m,65536)?S[w++]=e[s(531)](e[s(1489)](m,12),15)|224:(S[w++]=e[s(1661)](e[s(856)](e[s(1075)](m,18),7),240),S[w++]=e[s(442)](e[s(1239)](e[s(1075)](m,12),63),128)),S[w++]=e[s(1494)](e[s(465)](e.fJvHb(m,6),63),128)),S[w++]=e[s(1494)](e[s(1239)](63,m),128))}}function j(c,r){let s=t,l=ce(c,r[s(992)]),h=c.bytes,w=r[s(1795)];for(let S=0,v=r.limit;e.yQDsP(S,v);S++)h[e[s(1723)](S,l)]=w[S]}function re(c){return c.bytes[e.hHipW(te,c,1)]}function qe(c,r){let s=t,l=e[s(851)](ce,c,1);c[s(1795)][l]=r}function me(c){let r=t,s=0,l=0,h;do h=e[r(1617)](re,c),e[r(1616)](s,32)&&(l|=e[r(1378)](e[r(1551)](127,h),s)),s+=7;while(128&h);return l}function _e(c,r){let s=t;for(r>>>=0;e.jKofZ(r,128);)e.GHAbB(qe,c,e[s(1238)](e[s(551)](127,r),128)),r>>>=7;e[s(1262)](qe,c,r)}function Ot(c,r){let s=t;if(e[s(1602)](e[s(512)],e.xvUSk)){let l=0,h=0,w=0,S;if(S=e[s(1776)](re,c),l=e.rCFBy(127,S),e.UlMcQ(128,S)&&(S=e.IiBcs(re,c),l|=e[s(560)](e[s(1721)](127,S),7),e[s(714)](128,S)&&(S=e[s(1376)](re,c),l|=e[s(815)](127,S)<<14,e[s(1551)](128,S)))){if(e[s(1257)](e.hblAP,e[s(1018)]))return e[s(1376)](_0x2596fc,e[s(1111)](e[s(1354)](e[s(874)]("index ou"+s(422)+s(957),_0x60a57a)+s(426),e[s(1413)](_0x8a496a,1))+e[s(447)],_0x4e8142));S=e[s(979)](re,c),l|=e[s(370)](127,S)<<21,128&S&&(e[s(1180)](e.YcXjX,s(1059))?_0x45c715(_0x5bfee1(_0x58223a[s(1067)]),_0x1f495e.oldVersion,_0x276493.newVersion,PCjUPB[s(1521)](_0x3387d2,_0x27f794[s(764)+"ion"])):(S=e[s(1761)](re,c),h=127&S,e[s(1352)](128,S)&&(S=e[s(1521)](re,c),h|=e[s(1356)](e[s(1422)](127,S),7),128&S&&(S=re(c),h|=e[s(450)](e[s(531)](127,S),14),e.iIiUs(128,S)&&(S=e[s(1531)](re,c),h|=e[s(845)](e[s(1692)](127,S),21),128&S&&(S=e[s(618)](re,c),w=127&S,128&S&&(S=e.sioQX(re,c),w|=e[s(1380)](e[s(1721)](127,S),7))))))))}return{low:e[s(1694)](l,e[s(1613)](h,28)),high:e[s(1741)](e[s(508)](h,4),w<<24),unsigned:r}}else return!!this[s(503)]}function St(c,r){let s=t;if(e[s(414)](e.zBGuC,e[s(788)]))_0x1cab50[s(1351)](_0x146065,_0x5106c4);else{let l=e[s(1240)](r.low,0),h=e[s(1806)](e.ltsKt(r.low>>>28,e[s(560)](r.high,4)),0),w=e[s(1583)](r.high,24),S=e.ZgtMe(0,w)?h===0?e[s(1274)](l,16384)?e[s(1619)](l,128)?1:2:e[s(1470)](l,2097152)?3:4:e[s(1308)](h,16384)?e[s(1498)](h,128)?5:6:e[s(1523)](h,2097152)?7:8:e[s(467)](w,128)?9:10,v=e[s(604)](ce,c,S),m=c[s(1795)];switch(S){case 10:m[e[s(1744)](v,9)]=e[s(626)](e.JezQA(w,7),1);case 9:m[v+8]=e[s(680)](9,S)?e[s(965)](128,w):e[s(1060)](127,w);case 8:m[v+7]=S!==8?e[s(1453)](e.jDGMc(h,21),128):h>>>21&127;case 7:m[e[s(1354)](v,6)]=S!==7?e.jKuUZ(e.uJlga(h,14),128):e[s(978)](e[s(829)](h,14),127);case 6:m[e[s(614)](v,5)]=S!==6?e.WyZQc(e[s(1035)](h,7),128):e[s(611)](h>>>7,127);case 5:m[e[s(390)](v,4)]=S!==5?e[s(1286)](128,h):e.Kkoyc(127,h);case 4:m[e[s(949)](v,3)]=e.JfOZU(4,S)?e[s(1494)](e.jbdhB(l,21),128):e[s(1807)](e[s(556)](l,21),127);case 3:m[e[s(387)](v,2)]=S!==3?e[s(1453)](e.EmGJO(l,14),128):e[s(611)](l>>>14,127);case 2:m[e[s(390)](v,1)]=S!==2?e[s(442)](e[s(1233)](l,7),128):e[s(617)](l>>>7,127);case 1:m[v]=S!==1?e[s(1062)](128,l):127&l}}}function fn(c){return e[t(1513)](b,c)}function $t(c){return E(c)}let hn=65536,ui=e[t(1627)],ve=hn*hn,Le=ve*ve,fr=Le/2,Ue=String[t(1467)+"e"].charCodeAt;class we{constructor(r,s,l){let h=t,w={ZrWfL:function(S,v){return e[K(1807)](S,v)},BpxQe:function(S,v){return e.PbcaF(S,v)},gbByq:function(S,v){return e[K(794)](S,v)},OGDPE:function(S,v){return e[K(1692)](S,v)}};if(e[h(633)]!==h(964))this[h(950)]=!0,this[h(1570)]=e[h(1453)](0,r),this[h(1608)]=e[h(1494)](0,s),this[h(938)]=!!l;else return _0x568232["fromChar"+h(1715)](w.ZrWfL(255,this[h(1570)]),w[h(1192)](this[h(1570)]>>>8,255),w[h(1192)](w.BpxQe(this.low,16),255),this.low>>>24,w[h(1192)](255,this.high),w.ZrWfL(w[h(1497)](this[h(1608)],8),255),w[h(372)](w[h(772)](this[h(1608)],16),255),this[h(1608)]>>>24)}static isLong(r){return r&&e[t(781)](!0,r.isLong)}static fromBits(r,s,l){return new we(r,s,l)}static[t(1368)+"s"](r,s,l){let h=t;return l?we[h(1368)+h(1678)](r,s):we[h(1368)+h(1788)](r,s)}static["fromByte"+t(1678)](r,s){let l=t;return new we(e[l(1286)](e[l(984)](e.XrGMY(r[0],e[l(450)](r[1],8)),r[2]<<16),r[3]<<24),e[l(501)](e.zYYZr(e[l(1062)](r[4],e[l(560)](r[5],8)),e[l(1378)](r[6],16)),e[l(1645)](r[7],24)),s)}static[t(1368)+t(1788)](r,s){let l=t;return new we(e[l(561)](e[l(516)](e[l(1378)](r[4],24)|e.ZTOWI(r[5],16),e.sWAbW(r[6],8)),r[7]),e[l(984)](e.dRDvi(e[l(1453)](e.iigLd(r[0],24),r[1]<<16),e[l(1645)](r[2],8)),r[3]),s)}static[t(1090)](r){let s=t;return e[s(1195)](r,ui)?Il:new we(e[s(674)](e[s(1482)](e[s(1062)](e[s(1482)](Ue[s(1727)](r,0),e[s(1380)](Ue[s(1727)](r,1),8)),e[s(1380)](Ue[s(1727)](r,2),16)),e[s(1380)](Ue.call(r,3),24)),0),e[s(1005)](e.DKTSM(e[s(984)](Ue[s(1727)](r,4)|e[s(450)](Ue[s(1727)](r,5),8),e[s(1645)](Ue[s(1727)](r,6),16)),e[s(1575)](Ue[s(1727)](r,7),24)),0),!0)}[t(1222)](){let r=t;return String[r(1033)+"Code"](e[r(591)](255,this[r(1570)]),e[r(674)](this[r(1570)],8)&255,e[r(1326)](e[r(839)](this.low,16),255),e[r(1475)](this[r(1570)],24),e[r(1692)](255,this[r(1608)]),e[r(370)](e[r(541)](this.high,8),255),e[r(1559)](this[r(1608)]>>>16,255),e.ACNPG(this[r(1608)],24))}static[t(1104)+"er"](r,s=!0){let l=t;if(e[l(919)](isNaN,r))return s?mg:Il;if(s){if(e[l(881)](r,Le))return yg}else{if(e[l(1393)](r,-fr))return _g;if(e[l(573)](e[l(1607)](r,1),fr))return wg}return we[l(367)](e[l(1755)](r,ve)|0,e[l(997)](r/ve,0),s)}[t(1372)](){let r=t;return this.unsigned?e[r(1424)](e[r(1604)](e.hmTbk(this[r(1608)],0),ve),e[r(1806)](this[r(1570)],0)):e[r(1213)](e[r(1106)](this[r(1608)],ve),e[r(829)](this[r(1570)],0))}isZero(){let r=t;return e[r(1180)](0,this[r(1608)])&&e[r(559)](0,this[r(1570)])}[t(1334)](r){let s=t,l={bqCld:function(h,w){return e.NOLvi(h,w)},OUkmS:e[s(753)],TlzcV:e[s(1766)]};if(e[s(732)](e.DrLlZ,s(379))){we[s(950)](r)||(r=we[s(1104)+"er"](r));let h=this[s(1608)]>>>16,w=65535&this[s(1608)],S=this[s(1570)]>>>16,v=e[s(531)](65535,this.low),m=e[s(794)](r[s(1608)],16),O=e[s(513)](65535,r[s(1608)]),M=e.TzKfU(r[s(1570)],16),U=65535&r[s(1570)],$=0,V=0,Q=0,ue=0;return ue+=e[s(620)](v,U),Q+=ue>>>16,ue&=65535,Q+=e[s(1607)](S,M),V+=e[s(1162)](Q,16),Q&=65535,V+=e[s(1644)](w,O),$+=e[s(1139)](V,16),V&=65535,$+=e.fjrRK(h,m),$&=65535,we[s(367)](Q<<16|ue,e.DKTSM(e[s(560)]($,16),V),this[s(938)])}else sKTMmr.bqCld(sKTMmr[s(1626)],typeof _0x2e4a2f)&&_0x39c9d7["toString"+s(1404)]&&_0xe5c10d[s(1247)+s(1149)](_0x24aee6,_0x4b2496[s(458)+s(1404)],{value:s(1589)}),_0x280125.defineProperty(_0x8164a0,sKTMmr.TlzcV,{value:!0})}[t(1690)](r){let s=t;return we[s(950)](r)||(r=we[s(1104)+"er"](r)),e[s(414)](this[s(938)],r[s(938)])&&this[s(1608)]>>>31===1&&e[s(727)](r[s(1608)],31)===1?!1:e[s(1714)](this[s(1608)],r[s(1608)])&&this[s(1570)]===r[s(1570)]}addOne(){let r=t;return e[r(1573)](-1,this.low)&&this[r(1608)]===-1?we.fromBits(0,0,this[r(938)]):this.low===-1?we[r(367)](0,e[r(1723)](this[r(1608)],1),this[r(938)]):we[r(367)](e[r(492)](this[r(1570)],1),this[r(1608)],this.unsigned)}[t(1463)](r){let s=t;return r?this[s(988)+"E"]():this[s(1794)+"E"]()}toBytesLE(){let r=t,s={JGTLz:e.emIqW};if(e[r(850)](e[r(944)],e[r(944)])){let l=s[r(1775)].split("|"),h=0;for(;;){switch(l[h++]){case"0":this[r(1131)]=!0;continue;case"1":this[r(1072)+"osed"]=!1;continue;case"2":this[r(1205)+r(1459)]?.[r(796)+r(1764)+r(336)]();continue;case"3":this[r(1580)+r(1269)]?.[r(774)+r(885)]();continue;case"4":this[r(1177)]();continue}break}}else{let l=this[r(1608)],h=this[r(1570)];return[e[r(611)](255,h),e[r(839)](h,8)&255,e[r(636)](h>>>16,255),e.kfgEX(h,24),e[r(1239)](255,l),e[r(1807)](e[r(1384)](l,8),255),e[r(591)](e[r(1475)](l,16),255),l>>>24]}}toBytesBE(){let r=t,s=this[r(1608)],l=this.low;return[e.xLvUM(s,24),e[r(1706)](e[r(1557)](s,16),255),e[r(978)](s>>>8,255),e[r(1422)](255,s),e.TxCqn(l,24),e.jbdhB(l,16)&255,e[r(617)](e.YxMEp(l,8),255),e[r(1422)](255,l)]}}let Il=new we(0,0,!1),mg=new we(0,0,!0),wg=we[t(367)](-1,2147483647,!1),yg=we[t(367)](-1,-1,!0),_g=we[t(367)](0,-2147483648,!1);var pn=(function(c){let r=t;return c[c[e[r(454)]]=5001]=e[r(454)],c[c[r(1687)+"NG_ERROR"]=5002]=e[r(1786)],c[c[e.TkDkS]=5003]=e[r(595)],c[c[e[r(1447)]]=5004]=e[r(1447)],c[c[e[r(748)]]=5005]=e[r(748)],c})({});class hr{constructor(r){let s=t;this[s(699)]=r,this.target=null}}class Al extends hr{constructor(r,s){let l=t;super(r),this.message=s&&s[l(537)]||null}}class kl extends hr{constructor(r,s){let l=t,h=e[l(870)][l(1087)]("|"),w=0;for(;;){switch(h[w++]){case"0":this[l(991)]=s&&s.filename||"";continue;case"1":this[l(1553)]=s&&s[l(1553)]||0;continue;case"2":this[l(1260)]=s&&s[l(1260)]||null;continue;case"3":this.code=s&&s[l(1315)]||5001;continue;case"4":this[l(382)]=s&&s[l(382)]||0;continue;case"5":super(r);continue;case"6":this[l(537)]=s&&s[l(537)]||"";continue}break}}}class Tl extends hr{constructor(r,s){let l=t,h=(l(1210)+"4").split("|"),w=0;for(;;){switch(h[w++]){case"0":this[l(1315)]=s&&s[l(1315)]||0;continue;case"1":this[l(569)]=s&&s[l(569)]||"";continue;case"2":super(r);continue;case"3":this[l(661)]=s&&s.wasClean||!1;continue;case"4":this[l(1123)+l(1481)]=s&&s[l(1123)+"nnect"]||!1;continue}break}}}class Cl extends hr{constructor(r,s){let l=t;super(r),this[l(1361)]=s&&s[l(1361)]||null}}class Pl extends Cl{constructor(r,s){let l=t;super(r),this.data=s&&s[l(1361)]||null,this[l(537)]=s&&s.message||null}}class Dl extends hr{constructor(r,s){let l=t;super(r),this[l(1361)]=s&&s[l(1361)]||null}}function xt(c,{message:r,code:s,error:l}){return new kl(c,{message:r,code:s,error:l})}function It(c,{code:r,reason:s,wasClean:l,willReconnect:h}){return new Tl(c,{code:r,reason:s,wasClean:l,willReconnect:h})}function Rl(c,{data:r,message:s}){return new Pl(c,{data:r,message:s})}function Ol(c,{data:r}){return t(1719)!=="sfLOk"?e.vxzik(_0x535385,_0x3c6285):new Dl(c,{data:r})}function La(c,{message:r}){let s=t;if(e.YURrR("ZDJml",e[s(1271)]))try{this._ws&&this[s(1017)][s(673)](_0x169000,_0x242a8a)}catch{}else return new Al(c,{message:r})}class Ll{constructor(r,s){let l=t;this[l(529)+"s"]=r,this[l(1218)+"es"]=s,this[l(1270)+l(916)]=0,this[l(1696)+"ndpointT"+l(1585)+"t"]=0}[t(796)+t(1764)+t(336)](){let r=t;this[r(1270)+r(916)]=0,this[r(1696)+"ndpointTriesCount"]=0}[t(1635)+"es"](){let r=t;if(r(576)!==e.HhQfj)this[r(1696)+r(1105)+r(1585)+"t"]=0;else return!!this[r(503)]}[t(782)+t(1160)+"nt"](){let r=t;return this[r(529)+"s"][this[r(1270)+r(916)]]}[t(782)+"ntEndpoi"+t(578)+t(878)](){let r=t;return this["currentE"+r(1105)+r(1585)+"t"]}[t(758)+"chMaxTries"](){let r=t;return!!(this[r(1270)+r(916)]>=this.endpoints[r(452)]||e.EKqfb(this[r(1270)+r(916)],e[r(1445)](this[r(529)+"s"].length,1))&&e[r(1573)](this[r(1696)+r(1105)+r(1585)+"t"],this.maxRetries))}["checkCur"+t(602)+"ointReac"+t(1237)+"tries"](){let r=t;return e.OHVZJ(this["currentI"+r(916)],this[r(529)+"s"][r(452)])?!0:e[r(1568)](this[r(1696)+r(1105)+r(1585)+"t"],this[r(1218)+"es"])}[t(904)+"ackupEnd"+t(1593)+t(1184)+t(441)](){let r=t;return this[r(1696)+r(1105)+"riesCount"]=1,this[r(1270)+r(916)]++,this[r(529)+"s"][this[r(1270)+r(916)]]}[t(782)+"ntEndpoi"+t(1528)+t(842)](){let r=t;return this[r(1696)+r(1105)+r(1585)+"t"]++,this[r(782)+r(1160)+"nt"]()}}let pr=(e[t(639)](t(525)+"d",typeof globalThis)&&e[t(1263)](e[t(1777)],globalThis[t(1672)+"tor"][t(1565)])||e[t(639)](e[t(753)],typeof window)&&e[t(1429)](e[t(1777)],window[t(1672)+t(1479)][t(1565)]))&&e[t(753)]!=typeof document,Fn=e.aflOd(e[t(753)],typeof globalThis)&&(e.CBZAd===globalThis["construc"+t(1479)][t(1565)]||e[t(1524)](e.xCKKj,globalThis[t(1672)+"tor"].name))&&e[t(1277)](e[t(753)],typeof tt),fi=(e[t(1277)](e[t(753)],typeof globalThis)&&e.NFBwA(e.CBZAd,globalThis[t(1672)+t(1479)][t(1565)])||e[t(1042)](e[t(753)],typeof globalThis)||e[t(1022)](e[t(753)],typeof globalThis)&&!!globalThis[t(985)+t(1628)])&&e[t(1377)](e.yNgSi,typeof wx),hi=e[t(1377)](e[t(753)],typeof globalThis)&&(e[t(1573)](e[t(1024)],globalThis[t(1672)+t(1479)][t(1565)])||e.SvoAE(e.KcWRy,globalThis[t(1672)+t(1479)][t(1565)])||e[t(1731)](t(1512)+t(1298)+t(841),globalThis[t(1672)+t(1479)][t(1565)]))&&e[t(998)](e[t(753)],typeof self),bg=e[t(1377)](e.yNgSi,typeof globalThis)&&e[t(1180)](e[t(651)],globalThis[t(1672)+"tor"][t(1565)])&&e.pwfrD(e[t(753)],typeof global)&&e[t(333)](t(652),global[t(1672)+t(1479)][t(1565)])&&t(525)+"d"!=typeof process&&!!process[t(750)];class Na{constructor(){let r=t;this[r(792)+"rs"]={}}[t(1488)](r,...s){let l=t;if(e[l(1392)](e[l(866)],e[l(866)]))return new _0x3a4955(_0x3f1776);{let h=this[l(792)+"rs"][r];if(h)h[l(1800)]()[l(1129)](w=>w.fn[l(494)](w.ctx,s));else if(e[l(1714)](l(1260),r)&&!this[l(605)]){let w=s[l(452)]&&s[0];if(e[l(613)](w,Error))throw w;let S=new Error(e.lwIlI(e[l(1304)],w?e.VggWE(e[l(961)](" (",w.message),")"):""));throw S[l(1636)]=w,w}return this}}[t(1152)](r,s){let l=t;if(l(1611)!==e[l(483)]){if(e[l(747)](void 0,r))this._listeners={};else if(e[l(559)](void 0,s))this[l(792)+"rs"][r]=null;else if(e.IWyWg(e[l(360)],e[l(1116)])){let h=this[l(792)+"rs"][r];if(h)for(let w=0;w<h[l(452)];)e.hTwgP(h[w].fn,s)?h[l(671)](w,1):++w}else{let h=_0x3c5db5[l(1795)],w=_0x6cbd26.limit;return e[l(781)](h[l(452)],w)?h:h.subarray(0,w)}return this}else{let h=this[l(503)]["getStora"+l(1742)](this[l(1720)]),w=_0xb292c5[l(1110)](e.grgtA(h,"{}"));return w[_0x1f330c]=void 0,this._qosDB[l(1026)+l(1742)](this[l(1720)],_0x37d038[l(1215)+"y"](w))}}on(r,s,l){let h=t;return(this[h(792)+"rs"][r]||(this[h(792)+"rs"][r]=[]))[h(1004)]({fn:s,ctx:l||this}),this}}class Eg extends Na{[t(373)+t(676)+t(475)](r){let s=t;return r[s(1186)]||r[s(761)]?(s(906)+" "+(r[s(1186)]||"")+s(1458)+(r[s(761)]||"")).trim():JSON[s(1215)+"y"](r)}constructor(r,s,l){let h=t;super(),this[h(1068)]=null,fi&&wx[h(495)+"ocket"]&&(this[h(1068)]=wx.connectSocket({url:r,protocols:s,header:l,fail:this["_createS"+h(1532)+h(431)][h(1342)](this),success:this["_createS"+h(1122)+h(1403)+h(982)][h(1342)](this)})),Fn&&tt[h(495)+"ocket"]&&(this[h(1068)]=tt[h(495)+h(603)]({url:r,protocols:s,header:l,fail:this[h(932)+h(1532)+"lHandler"][h(1342)](this),success:this["_createSocketSuc"+h(1403)+h(982)][h(1342)](this)}))}[t(932)+t(1122)+t(1403)+t(982)](){let r=t;Promise[r(1265)]()[r(1266)](()=>{this["_addWsLi"+r(637)]()})}[t(932)+t(1532)+t(431)](r){let s=t;Promise[s(1265)]().then(()=>{let l=s,h=xt(e[l(642)],{message:this[l(373)+l(676)+l(475)](r)});this[l(1488)](e[l(642)],h);let w=e[l(1100)](It,e[l(345)],{reason:this[l(373)+l(676)+l(475)](r)});this[l(1488)](e[l(345)],w)})}_addWsListeners(){let r=t,s={tFBFq:e[r(1078)],WiioM:function(l,h,w){return e[r(1542)](l,h,w)}};this[r(1068)].onOpen(l=>{let h=r;this[h(1488)](s[h(743)],s.WiioM(Ol,s[h(743)],{...l,data:l.errMsg||""}))}),this._socket[r(974)](l=>{let h=r;this[h(1488)](e[h(345)],e[h(1374)](It,h(673),{...l}))}),this[r(1068)][r(408)+"e"](l=>{this[r(1488)](e.DRhqj,e.lkeAT(Rl,"message",{...l}))}),this._socket.onError(l=>{let h=r;this[h(1488)](e.suyJS,e[h(1773)](xt,e[h(642)],{...l,message:l.errMsg||""}))})}[t(1102)](r){let s=t;if(e[s(1201)](r,Uint8Array)){let l=r[s(548)][s(1800)](r[s(1321)+"et"],e.xkVIb(r[s(545)+"th"],r[s(1321)+"et"]));this._socket&&this[s(1068)].send({data:l,fail:h=>{let w=s;this[w(1488)](e[w(642)],e[w(1436)](xt,e.suyJS,{message:this[w(373)+w(676)+w(475)](h)}))}})}else this[s(1068)]&&this[s(1068)].send({data:r,fail:l=>{let h=s;this[h(1488)]("error",e[h(1113)](xt,e.suyJS,{message:this[h(373)+"rrorMessage"](l)}))}})}[t(673)](r,s){let l=t;this[l(1068)]&&this[l(1068)][l(673)]({code:r,reason:s})}["addEvent"+t(1643)](r,s){this.on(r,s)}[t(1327)+t(681)+"ner"](r,s){this[t(1152)](r,s)}get[t(1530)+"te"](){let r=t;return this[r(1068)][r(1530)+"te"]}get[t(1030)+"pe"](){let r=t;return this[r(1068)][r(1030)+"pe"]}set[t(1030)+"pe"](r){}get[t(686)](){let r=t;if(e[r(952)](e[r(589)],e[r(1231)]))return this._socket[r(686)];{let s=_0x16887b[r(366)+"g"](0,e[r(729)](4,_0x4a4d72[r(452)])),l=s[r(1423)](_0x2092cd);_0x258036[r(1004)](l)}}get[t(1249)](){let r=t;return e[r(1683)]===e[r(1061)]?(_0x48f79c+=_0x22c25a&&_0x5c0a7c[r(545)+"th"]||0,_0x245166):this[r(1068)][r(1249)]}get[t(562)+"ns"](){return this[t(1068)].extensions}get["buffered"+t(846)](){return 0}}function vg(c,r){let s=t;if(r)return new r(c.url,c.protocol);if(e[s(1413)](fi,Fn))return new Eg(c.url,c[s(1249)],c.headers);if(e[s(1413)](pr,hi)&&e[s(998)](e.yNgSi,typeof WebSocket)&&WebSocket)return new WebSocket(c[s(686)],c.protocols)}function Sg(c){let r=t,s="3|1|4|2|0"[r(1087)]("|"),l=0;for(;;){switch(s[l++]){case"0":return!1;case"1":if(fi&&wx[r(495)+"ocket"])return!0;continue;case"2":if(e[r(1413)](pr,hi)&&e[r(998)](r(525)+"d",typeof WebSocket)&&WebSocket)return!0;continue;case"3":if(c)return!0;continue;case"4":if(Fn&&tt[r(495)+r(603)])return!0;continue}break}}function Nl(c,r,s){let l=t,h=-1;async function w(S){let v=K,m={xItXj:function(O,M){return e[K(1353)](O,M)},owULs:function(O,M){return e[K(848)](O,M)},UZegS:function(O,M){return e[K(781)](O,M)},PBvSV:function(O,M){return O&M},tTkwb:function(O,M){return e.hTwgP(O,M)},oHXcH:function(O,M){return e.hZszs(O,M)},VEwNu:function(O,M){return e.xkVIb(O,M)}};if(e.mEDXM(e[v(1258)],e[v(1076)])){let O=0,M=0;for(let U=0;m[v(1145)](U,_0x100a13.length);++U)M=_0xf83e3e[v(1010)+"At"](U),m[v(1145)](M,128)?O+=1:m[v(398)](M,2048)?O+=2:m[v(1044)](m[v(1154)](64512,M),55296)&&m[v(1220)](m[v(925)](64512,_0x31acb6.charCodeAt(m.VEwNu(U,1))),56320)?(++U,O+=4):O+=3;return O}else return e[v(1393)](S,h)?Promise[v(1398)](new Error(v(514)+v(504)+v(1597)+v(580)+"process")):(h=S,e[v(1605)](S,s[v(452)])?Promise[v(1265)]():s[S][v(1342)](c)(r,w.bind(null,e[v(1019)](S,1))))}e[l(1176)](w,0)}function Ml(c){let r=t,s=0,l=0;for(let h=0;e[r(797)](h,c[r(452)]);++h)l=c[r(1010)+"At"](h),e[r(1333)](l,128)?s+=1:l<2048?s+=2:e[r(815)](64512,l)===55296&&e[r(1027)](e[r(647)](64512,c[r(1010)+"At"](e[r(967)](h,1))),56320)?(++h,s+=4):s+=3;return s}function Bl(c,r,s){let l=t;if(e[l(1682)](e[l(729)](s,r),1))return"";let h="";for(let w=r;e[l(897)](w,s);){let S=c[w++];if(e[l(341)](S,127))h+=String[l(1033)+"Code"](S);else if(e[l(1288)](S,192)&&e[l(1548)](S,224))h+=String["fromChar"+l(1715)](e[l(1453)](e[l(1239)](31,S)<<6,63&c[w++]));else if(e[l(1410)](S,224)&&e.hHvYT(S,240))h+=String[l(1033)+"Code"](e[l(516)](e[l(893)](e[l(1721)](15,S)<<12,e[l(1645)](63&c[w++],6)),e[l(978)](63,c[w++])));else if(S>=240){let v=e[l(914)](e.gJIgv(e[l(1196)](7,S)<<18|e[l(1380)](63&c[w++],12),e[l(403)](e[l(1721)](63,c[w++]),6))|e.OQpDR(63,c[w++]),65536);h+=String["fromChar"+l(1715)](e[l(1234)](55296,v>>10)),h+=String["fromChar"+l(1715)](e[l(1037)](56320,e[l(1060)](1023,v)))}}return h}function Ma(c,r,s){let l=t,h=s,w,S;for(let v=0;v<c[l(452)];++v)if(e.owIlC(e[l(683)],e.jmKQI))if(w=c[l(1010)+"At"](v),w<128)r[s++]=w;else if(w<2048)r[s++]=e.wClUr(e[l(1075)](w,6),192),r[s++]=e.FrGIy(63&w,128);else if(e.JqUET(e[l(531)](64512,w),55296)&&e.hTwgP(64512&(S=c[l(1010)+"At"](e[l(838)](v,1))),56320)){let m=e.KPOJZ[l(1087)]("|"),O=0;for(;;){switch(m[O++]){case"0":r[s++]=e[l(896)](e[l(816)](63,w),128);continue;case"1":r[s++]=e[l(1494)](w>>18,240);continue;case"2":r[s++]=e[l(1657)](w,6)&63|128;continue;case"3":w=e.saQJr(e[l(972)](65536,e[l(403)](e[l(973)](1023,w),10)),e.GnuSD(1023,S));continue;case"4":r[s++]=e.Reren(w,12)&63|128;continue;case"5":++v;continue}break}}else e[l(544)]===l(1509)?(r[s++]=e[l(1567)](w,12)|224,r[s++]=e[l(1399)](e[l(1572)](e.fJvHb(w,6),63),128),r[s++]=e[l(1590)](63,w)|128):this.on(_0x18a139,_0x43fae6);else return this[l(503)]?.[l(760)](_0xda70af);return s-h}async function Fl(c){let r=t;if(e.EUTCx(r(1287),typeof c)){let s=new Uint8Array(e[r(488)](Ml,c));return e[r(1701)](Ma,c,s,0),s}return c instanceof ArrayBuffer?new Uint8Array(c):new Uint8Array(c[r(548)],c[r(1321)+"et"],c.byteLength)}function Ig(c){let r=t;try{return e[r(998)](e[r(474)],typeof c)&&(e[r(1725)](c,ArrayBuffer)||c[r(548)]&&e[r(393)](c[r(548)],ArrayBuffer))||e[r(998)](e.tuSCr,typeof c)?"":(JSON.parse(c),e[r(813)])}catch{return e.tuSCr==typeof c?e[r(947)]:""}}let Ag=(c,r)=>{let s=t;switch(c){case e[s(672)]:case s(1704):return{["x-use-"+c]:1,"x-tt-env":r};default:return{}}};class kg{constructor(r){let s=t;this[s(1539)+s(878)]=r,this.count=0}addCount(){let r=t;if(e[r(752)](e[r(868)],r(1504)))this[r(1620)]++;else return _0x471130?_0x128c80[r(1368)+"sLE"](_0x3b93c1,_0x3f5a1d):_0x547afa[r(1368)+"sBE"](_0x46100e,_0x3d6f23)}["checkRea"+t(534)+"nt"](){let r=t;return e[r(343)](this[r(1620)],this[r(1539)+"ount"])}[t(774)+"nter"](r=0){let s=t;this[s(1539)+s(878)]=r,this[s(1620)]=0}}async function Tg(c){let r=t,s={QumeH:function(l,h){return e[K(657)](l,h)},lSHxs:r(1357)+"reason"};return new Promise(l=>{let h=r,w={ssrSi:function(S,v){return e.sbatD(S,v)},hxOyS:function(S,v){return S<<v},zVyAB:function(S,v){return e[K(626)](S,v)},RCGRJ:function(S,v){return e[K(1590)](S,v)},eblfY:function(S,v){return e[K(1183)](S,v)}};if(e[h(1733)](e.bkkzL,e[h(1278)])){if(!pr)return l(h(1357)+h(569));try{let S=document[h(1486)+h(996)](e[h(900)]);window["frontier"+h(575)]=v=>{let m=h;document[m(713)][m(1137)+m(943)](S),window[m(659)+m(575)]=void 0,s.QumeH(l,v&&v[m(596)]||s[m(1305)])},S[h(699)]=e.qxZKi,S[h(1419)]=c[h(448)](/^ws/,h(1394))+(h(1323)+"ack=fron"+h(526)+"P");try{document[h(713)][h(1448)+h(943)](S)}catch{e.Tobxq(h(340),h(1187))?(_0x21d759=GdznuA[h(1420)](GdznuA[h(1007)](GdznuA[h(1433)](31,_0xdf0abf),6),GdznuA[h(802)](63,_0x46f6f9)),GdznuA.eblfY(_0x39b00c,128)?_0x14439f+=_0x1ccaf3:(_0x38411b+=_0xa9a3de(_0x2be165),_0x312e20++)):document[h(713)][h(1137)+"ild"](S)}}catch{window[h(659)+h(575)]=void 0,e[h(1485)](l,e[h(582)])}}else return this._qosDB[h(520)]})}function xn(c,r,s){let l=t;return!!c?.[l(1765)](h=>h[l(1360)]===r&&h.value===s)}function xr(c,r){let s=t;return c?.[s(1765)](l=>l[s(1360)]===r)?.[s(1208)]}let Ba=null;async function Cg(){let c=t;return Ba||(Ba=Promise.resolve()[c(1266)](Wt.bind(Wt,"idb"))),Ba}class Pg extends Na{constructor(r,s){let l=t;super(),this[l(476)]=r,this[l(363)]=s,this._qosDB=void 0,this[l(917)+l(1658)]=null}async openDB(){await this[t(901)]()}async[t(901)](){let r=t;if(!this._qosDB){if(this[r(917)+r(1658)])return this["_initPro"+r(1658)];try{let s=this[r(476)],l=this._keyPath;this[r(917)+"mise"]=(async()=>{let h=r,{openDB:w}=await Cg();this[h(503)]=await w("frontier_"+s,1,{upgrade(S){let v=h;S[v(1056)+v(349)+"e"](s,{keyPath:l})}})})(),await this["_initPro"+r(1658)]}catch(s){console[r(1609)](s)}finally{this["_initPro"+r(1658)]=null}}}async[t(760)](r){let s=t;try{return await this[s(901)](),this[s(503)]?.[s(760)](this[s(476)],r)}catch(l){if(e[s(511)](e[s(1207)],e[s(509)]))return new _0x3c4393(_0x35ad16,{data:_0x2a8e2b,message:_0x3cbe52});console[s(1609)](l)}}async[t(1351)](r,s){let l=t;return await this[l(901)](),this[l(503)]?.[l(1046)](this[l(476)],r)}async[t(1417)](r){try{return await this._init(),this._qosDB?.delete(this._dbName,r)}catch(s){console.log(s)}}async clear(){let r=t;try{return await this[r(901)](),this[r(503)]?.[r(1214)](this[r(476)])}catch(s){console[r(1609)](s)}}async[t(1630)](){let r=t;if(e[r(1180)](e[r(471)],r(1307)))return await this[r(901)](),this._qosDB?.[r(1276)+"ys"](this[r(476)]);this[r(503)]?.close(),this[r(503)]=void 0}async[t(1147)](){let r=t;return await this._init(),this[r(503)]?.[r(1147)](this[r(476)])}async[t(1171)](){let r=t;if(e[r(1229)]!==e[r(1653)])try{this._qosDB?.[r(673)](),this[r(503)]=void 0}catch(s){console.log(s)}else _0x1a08c2=e.CwhGG(_0x1749d4,_0x2b0c94),_0x13da49=0}get[t(520)](){let r=t;try{return!!this[r(503)]}catch(s){return console[r(1609)](s),!1}}}class Dg{constructor(r,s){let l=t;this[l(1296)]=r,this[l(1547)]=s,this._qosDB=localStorage}async[t(461)](){}get[t(1720)](){return"frontier_"+this[t(1296)]}async[t(760)](r){let s=t,l=this[s(503)].getItem(this[s(1720)]);return JSON.parse(e[s(910)](l,"{}"))[r]}async[t(1351)](r,s){let l=t,h=this._qosDB[l(1016)](this[l(1720)]),w=JSON[l(1110)](h||"{}");return w[s||r[this._pathKey]]=r,this[l(503)][l(1064)](this._prefix,JSON[l(1215)+"y"](w)),s||r[this._pathKey]}async[t(1417)](r){let s=t,l={fscyI:function(h,w){return h!==w},bIqjG:function(h,w){return e[K(914)](h,w)}};if(e[s(1337)]==="OWPgB"){let h=_0x5712a4[_0x2733a0];if(QVkhyP.fscyI(4,_0x4b46d1[_0x29f9fa][s(452)])){let w=_0x4dce78[s(366)+"g"](0,QVkhyP[s(1264)](4,_0x2cc453[_0x4d4cc9][s(452)])),S=w[s(1423)](h);_0x5c8a7f=_0x3c95ce[s(1423)](S)}else _0x2a4744=_0xb7f9ae[s(1423)](h)}else{let h=this[s(503)][s(1016)](this[s(1720)]),w=JSON[s(1110)](e[s(1413)](h,"{}"));return w[r]=void 0,this[s(503)][s(1064)](this[s(1720)],JSON[s(1215)+"y"](w))}}async[t(1214)](){let r=t;return this._qosDB[r(1214)]()}async keys(){let r=t,s=this._qosDB.getItem(this[r(1720)]),l=JSON.parse(e.HpEVs(s,"{}"));return Object[r(1630)](l)}async[t(1147)](){let r=t,s=this[r(503)].getItem(this[r(1720)]),l=JSON.parse(s||"{}");return Object[r(971)](l)}[t(1171)](){return Promise[t(1265)]()}get[t(520)](){let r=t;if(e[r(1241)](r(538),e.zDpJe))return!!this[r(503)];_0x310960=_0xfd71dc[r(1423)](_0x37c5bc),_0x16a92a=_0x361484[r(1423)](_0x35930b[_0x38985a])}}class Rg{constructor(r,s){let l=t;this[l(1296)]=r,this._pathKey=s,this[l(503)]=Fn?tt:fi?wx:null}async openDB(){}get _prefix(){let r=t;return r(659)+"_"+this[r(1296)]}async[t(760)](r){let s=t,l=this[s(503)][s(1787)+"geSync"](this[s(1720)]);return JSON[s(1110)](e[s(1170)](l,"{}"))[r]}async[t(1351)](r,s){let l=t,h=this[l(503)][l(1787)+l(1742)](this[l(1720)]),w=JSON[l(1110)](e.WdzfS(h,"{}"));return w[s||r[this[l(1547)]]]=r,this[l(503)][l(1026)+"geSync"](this[l(1720)],JSON[l(1215)+"y"](w)),s||r[this[l(1547)]]}async[t(1417)](r){let s=t,l=this[s(503)][s(1787)+s(1742)](this._prefix),h=JSON[s(1110)](l||"{}");return h[r]=void 0,this[s(503)][s(1026)+s(1742)](this[s(1720)],JSON[s(1215)+"y"](h))}async[t(1214)](){let r=t;return this[r(503)]["clearSto"+r(586)]()}async[t(1630)](){let r=t,s=this[r(503)][r(1787)+r(456)+"nc"](this[r(1720)]),l=JSON[r(1110)](e.sapMe(s,"{}"));return Object[r(1630)](l)}async[t(1147)](){let r=t,s=this[r(503)][r(1787)+"geInfoSync"](this[r(1720)]),l=JSON.parse(e[r(820)](s,"{}"));return Object[r(971)](l)}[t(1171)](){return Promise.resolve()}get isReady(){return!!this[t(503)]}}function zl(c,r){let s=t;if(Fn||Fn)return new Rg(c,r);if(e.wEiuX(pr,hi)&&e[s(855)](e.yNgSi,typeof indexedDB))return new Pg(c,r);if(e[s(530)](pr,hi)&&e[s(1427)](e[s(753)],typeof localStorage))return new Dg(c,r);throw new Error(s(1066)+"DB failed")}class Og{constructor(){let r=t;if(e[r(524)](e.zZaci,e[r(1280)])){let{offset:s}=e[r(1224)](_0x308eae,_0x39d0c6,_0x176fc3);_0x106a9b=s;let l={cursor_name:"",cursor:0,service:0},{value:h,offset:w}=e.QdjuS(_0x123c0e,_0x74c03,_0x4b75c9);l[r(1702)]=h,_0x355c64=w;let{value:S,offset:v}=e[r(1542)](_0x48d263,_0x30a7b7,_0x2188e5);_0x393b59=v,l[r(1770)+r(1389)]=e[r(1701)](_0x58afd6,_0x4bf81f,_0x4b8e99,e[r(1424)](_0x4b11e2,S)),_0x3dc37f+=S;let{value:m,offset:O}=_0x255283(_0xe39d57,_0x3b32dc);l[r(701)]=m[r(1372)](),_0x392a37=O,_0x1fdb30[r(1004)](l)}else this[r(1325)+r(1275)+"Id"]=null,this[r(1325)+"l"]=36e5,this[r(503)]=e[r(1436)](zl,r(1173),e[r(411)])}async[t(1325)+t(1646)](){let r=t;e[r(437)](clearInterval,this[r(1325)+r(1275)+"Id"]),this[r(1325)+"lTimeoutId"]=setInterval(()=>{let s=r;this[s(1132)+s(1391)]()},this[r(1325)+"l"])}async[t(461)](){let r=t,s={QInVM:e[r(776)]};await this[r(503)][r(461)]()[r(1266)](()=>{let l=r;s[l(1768)]!==s[l(1768)]?(++_0x4bbe3b,_0x43471b+=4):this[l(1325)+l(1646)]()})}async["flushExp"+t(1391)](){let r=t;(await this[r(503)]?.getAll()||[])[r(418)](({timestamp:h})=>h<Date[r(1338)]())[r(1129)](h=>{let w=r;this._qosDB?.[w(1417)](h.message_id)})}async[t(1417)](r){let s=t,l={woAxD:function(h,w){return e.aiCJn(h,w)},TTHNn:function(h,w){return e.NFluA(h,w)}};if(e[s(781)](e[s(329)],e[s(799)])){if(gpwFVW[s(1544)](4,_0x419db1[s(452)])){let h=_0xb4b5a5.substring(0,gpwFVW[s(482)](4,_0x435b97[s(452)])),w=h.concat(_0x4736f7);_0x552eea[s(1004)](w)}else _0x2cd89c.push(_0x4350f8);_0x96c015&&(_0x238112+=1),_0x46ab6c+=1,_0x316d46=!1}else return this[s(503)]?.del(r)}async[t(1351)](r,s){let l=t;return this[l(503)]?.[l(1351)]({message_id:r,timestamp:s})}async[t(760)](r){let s=t;return this[s(503)]?.[s(760)](r)}async closeDB(){let r=t;e[r(1531)](clearInterval,this["_interva"+r(1275)+"Id"]),await this[r(503)]?.[r(1171)]()}get[t(520)](){let r=t;return this._qosDB?.[r(520)]}}function Fa(c){let r=t,s=!!this[r(457)][r(1757)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(369)](xn,c[r(537)][r(365)],e[r(616)],"2"),h=l&&e.GYsTT(xn,c.message.headers,e[r(528)],"1"),w=l&&e[r(1664)](xn,c.message[r(365)],e[r(1511)],"1"),S=w?e[r(869)](xr,c[r(537)][r(365)],e[r(1340)])?.[r(1087)](",")[r(418)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:w,ackMsgIds:S}}async function Ul(){let c=t;return this._QoSManager||(this[c(824)+c(1293)]=new Og),this["_QoSMana"+c(1293)][c(520)]||await this[c(824)+c(1293)][c(461)](),this[c(824)+c(1293)]}async function Lg(c,r){let s=t,{enableAutoAck:l}=this[s(457)],h=e[s(1666)](xn,c[s(537)][s(365)],s(428),"1"),w=e.iGsdt(xn,c[s(537)][s(365)],s(1095),"1"),S=Fa[s(1727)](this,c);if(e[s(1591)](l,h)){let{SeqID:v,LogID:m,service:O,LogIDNew:M,method:U}=c.message;this._sendAck({SeqID:v,LogID:m,LogIDNew:M,service:O,method:U,headers:[{key:e[s(1588)],value:"1"},{key:e[s(707)],value:e[s(910)](M,"")},{key:s(822),value:"0"}]})}w&&!S.isQoSAck&&this[s(1169)+s(1268)+s(1471)](c),e[s(1555)](r)}async function Ng(c,r){let s=t;this[s(736)](e.YGnnP,c[s(537)]),e[s(929)](r)}async function Mg(c,r){let s=t;if(e[s(511)](e[s(1540)],s(1150))){let l=e[s(1606)](fn,await e[s(1550)](Fl,c[s(1361)]));try{if(e[s(1036)](l[s(1600)],Uint8Array))if(e[s(747)](e[s(1468)],"wlUbQ")){let h=e[s(754)](this[s(457)].payloadEncoding,Object)?{force:!!this[s(457)]["payloadE"+s(1302)].force,encoding:this[s(457)]["payloadE"+s(1302)].encoding?this[s(457)][s(1717)+"ncoding"].encoding[s(448)](/\s/g,"")[s(1758)+s(712)]():""}:{force:!1,encoding:this._options["payloadE"+s(1302)]?this[s(457)]["payloadE"+s(1302)][s(448)](/\s/g,"")[s(1758)+"ase"]():""},w=l[s(1717)+s(1302)]?l[s(1717)+s(1302)].replace(/\s/g,"")[s(1758)+s(712)]():"",S=e.gSsiu(this._options.payloadType,Object)?{force:!!this[s(457)][s(1596)+"ype"][s(1784)],type:this[s(457)][s(1596)+s(1564)][s(699)]?this[s(457)][s(1596)+"ype"].type[s(448)](/\s/g,"")[s(1758)+s(712)]():""}:{force:!1,type:this[s(457)][s(1596)+"ype"]?this._options[s(1596)+s(1564)].replace(/\s/g,"")[s(1758)+s(712)]():""},v=l["payloadT"+s(1564)]?l[s(1596)+"ype"][s(448)](/\s/g,"")[s(1758)+"ase"]():"",m=S.force?S[s(699)]:v||S[s(699)],O=h.force?h[s(1395)]:w||h[s(1395)],M=[e[s(947)],e[s(813)],e[s(1112)],e[s(474)]],U=[e.MEGDk,e[s(631)]];this[s(457)][s(726)+"ansformTextPayload"]&&M[s(926)](m)&&(!O||U[s(926)](O))?l["textPayl"+s(1117)]=e.pHomR(Bl,l.payload,0,l.payload[s(545)+"th"]):l[s(1e3)+s(1117)]=""}else{let h=_0x5d9907(_0x217951,_0x3d081d);return _0x460447[s(1795)][s(853)](h,e[s(1607)](h,_0x21ccfd))}else l[s(1e3)+s(1117)]=""}catch(h){l.textPayload="",console[s(1609)](h)}c.message=l,e[s(929)](r)}else _0x1c9e50(_0x5a1be1,10),_0x344e31(_0x218905,_0x39f58d)}function Bg(c,r,s){let l=t,h=e[l(1686)](s,8192),w=e.gEZdF(h,1),S=null,v=h;return function(m){let O=l;if(e.rZrtN(m,1)||e.UUVpr(m,w))return e[O(1617)](c,m);e[O(599)](e.WpMNB(v,m),h)&&(S=e[O(618)](c,h),v=0);let M=r[O(1727)](S,v,v+=m);return e[O(1335)](7,v)&&(v=e.lZjNn(7|v,1)),M}}let Fg=4294967295;function zg(c,r,s){let l=t;return e[l(493)](RangeError,e[l(890)](e[l(961)](e[l(646)](e.rFmJj(e[l(440)],c),e.vkLCV)+(r||1),e[l(447)]),s))}function Ug(c,r,s){let l=t;if(e[l(342)](e.zMOAa,l(739))){if(s>Fg)throw new Error(e[l(956)]);let h=3;for(;e[l(581)](h,0);){let w=e[l(1048)](255,s);e[l(1362)](Ua,w,c,e[l(1796)](r,h)),s>>>=8,h--}return e[l(949)](r,4)}else e[l(1199)](_0x162804,this,_0x5b9dc0,[_0x5302f6,_0x48a082,_0x4284f3,_0x4624af,_0x5a0d3a,_0x3c2cc4])}function Hg(c,r){let s=t,l=0,h=r,w=e[s(967)](r,4);for(;e[s(1790)](h,w);){let{value:S,offset:v}=e[s(1262)](za,c,h);h=v,l=e[s(1613)](l,8)>>>0,l+=S}return{value:l,offset:w}}function Gg(c,r,s){let l=t,h=e.gJHfr[l(1087)]("|"),w=0;for(;;){switch(h[w++]){case"0":return e[l(805)](e[l(1089)](Ma,c,r,s),s);case"1":if(r[l(1579)])return e.SrSmO(r[l(1579)](c,s),s);continue;case"2":if(e[l(690)](c[l(452)],40))return e[l(1466)](Ma(c,r,s),s);continue;case"3":if(!c)return s;continue;case"4":if(r[l(1303)+"e"])return r[l(1303)+"e"](c,s)+s;continue}break}}function qg(c,r){let s=t,l=new we(e.IFbZX(e[s(1164)](e[s(1759)](c[e[s(837)](r,4)]<<24,c[r+5]<<16),e[s(1575)](c[e[s(432)](r,6)],8)),c[r+7]),e.xNidX(e.TabBA(c[e[s(359)](r,0)],24),c[e[s(1213)](r,1)]<<16)|c[r+2]<<8|c[e.MYwjf(r,3)],!0);return r+=8,{value:l,offset:e[s(1452)](r,8)}}function jg(c,r,s){let l=t,h=c[l(1570)],w=c.high;return r[s]=w>>>24,r[e[l(387)](s,1)]=e[l(1335)](e[l(1806)](w,16),255),r[s+2]=e[l(887)](w>>>8,255),r[e[l(1096)](s,3)]=e.qWoBR(255,w),r[e[l(1111)](s,4)]=e[l(909)](h,24),r[e[l(460)](s,5)]=e[l(636)](e[l(839)](h,16),255),r[e[l(1644)](s,6)]=e[l(1385)](h,8)&255,r[s+7]=e.HZWIf(255,h),s+=8,s}function za(c,r){let s=t;return c[s(1739)+"8"]?{value:c.readUInt8(r),offset:r+1}:{value:e[s(856)](255,c[r]),offset:e[s(1248)](r,1)}}function Ua(c,r,s){let l=t;return r.writeUint8?r[l(1441)+"t8"](c,s):r[s]=e[l(1335)](255,c),s+1}let Wg=function(c){return new Uint8Array(c)},Kg=e.yNgSi!=typeof Buffer?Buffer[t(1230)+t(1125)]:Bg(Wg,Uint8Array[t(1467)+"e"][t(853)]),$g=16,Ha=32;function Vg(c){let r=t,s=0,l={};for(let h=0;e[r(1616)](h,c.length);h++)l[c[h]["cursor_n"+r(1389)]]=e[r(1430)](Ml,c[h][r(1770)+r(1389)]),s+=e.iWcaN(14,l[c[h][r(1770)+r(1389)]]);return[s,l]}function Hl(c,r,s){let l=t,h={qaTKB:e.SCbmo,agXut:l(399),STBvC:function(O,M,U,$){return O(M,U,$)},nrIVu:"service",dxLUZ:function(O,M,U,$){return e[l(1381)](O,M,U,$)},GiBeV:e[l(1667)],elOJV:e[l(793)],mYVkS:function(O,M,U,$){return e.RZTsD(O,M,U,$)},KozLn:e[l(356)]},[w,S]=Vg(c),v=e.CJVeS(Kg,w),m=0;return c[l(1129)](O=>{let M=l;console[M(1609)](h[M(1689)],O,O[M(1702)]),m=Ua(0,v,m),console.log(h[M(768)],m),m=h.STBvC(Ug,v,m,O[M(1702)]||0),console[M(1609)](h.nrIVu,m),m=h[M(472)](Ua,S[O[M(1770)+"ame"]],v,m),console[M(1609)](h[M(1114)],m),m=h[M(466)](Gg,O["cursor_n"+M(1389)],v,m),console.log(h[M(795)],m),m=h.mYVkS(jg,we[M(1104)+"er"](O[M(701)]||r),v,m),console[M(1609)](h[M(376)],m)}),{frameType:Ha,headers:[{key:e[l(1670)],value:s}],payload:v}}function Jg(c){let r=t,s=0,l=[];for(;e[r(1183)](s,c[r(545)+"th"]);){let{offset:h}=za(c,s);s=h;let w={cursor_name:"",cursor:0,service:0},{value:S,offset:v}=Hg(c,s);w.service=S,s=v;let{value:m,offset:O}=e.xPhwB(za,c,s);s=O,w["cursor_n"+r(1389)]=Bl(c,s,e[r(1083)](s,m)),s+=m;let{value:M,offset:U}=e.bOhFd(qg,c,s);w[r(701)]=M[r(1372)](),s=U,l[r(1004)](w)}return l}function Zg(){let c=t;return{frameType:Ha,headers:[{key:c(1535)+c(918),value:e[c(1414)]}],payload:void 0}}class Yg{constructor(r,s,l){let h=t;this[h(1316)+h(1134)]=r,this[h(1642)+h(730)]=s,this[h(1309)+h(666)]=l,this._qosDB=e.xPhwB(zl,this[h(1316)+h(1134)],h(1770)+h(1389))}async[t(461)](){let r=t;await this[r(503)][r(461)]()}async[t(854)+"rs"](){let r=t;if(e[r(804)](e[r(1724)],e.dfiLZ))_0x54e824.o=(s,l)=>_0x38d580[r(1467)+"e"]["hasOwnPr"+r(1149)][r(1727)](s,l);else{if(!this._qosDB[r(520)])return;let s=this[r(1309)+r(666)],l=await this[r(503)][r(1147)]();switch(console[r(1609)](e[r(1804)],l),s){case e[r(1141)]:return l&&l[r(452)]?e[r(939)](Hl,l,0,this["_cursorF"+r(730)]):void 0;case e[r(1705)]:return;case e[r(558)]:return l&&l[r(452)]?e.UunRR(Hl,l,0,this[r(1642)+r(730)]):e[r(1126)](Zg)}}}async[t(1351)](r,s,l){let h=t;return console.log(h(826),r,s,l),this[h(503)].set({cursor_name:r,cursor:s,service:l})}async[t(1216)+"rs"](r){let s=t,l=Jg(r);for(let h of l)console[s(1609)](e[s(697)],l),await this[s(503)][s(1351)](h)}async[t(760)](r){let s=t;return(await this[s(503)][s(760)](r))?.cursor}async closeDB(){await this[t(503)].closeDB()}[t(543)+t(1735)+t(1495)](r){let s=t;this[s(1642)+s(730)]=r}get[t(520)](){let r=t;return this._qosDB[r(520)]}}let Xg=t(628)+t(1254);async function Gl(c){let r=t,s={hdrtF:function(v,m,O){return e[K(765)](v,m,O)}};if(!this[r(457)][r(1757)+"S"])return null;let{aID:l,fpID:h,messageStrategy:w}=this._options,S=e[r(1069)](c,Xg);try{if(e[r(691)](e.eIwLp,"oFVVi"))return this[r(630)+r(627)]?c&&this._cursorManager[r(543)+r(1735)+"Name"](c):this[r(630)+r(627)]=new Yg(h+"_"+l+"_"+S,S,w),this["_cursorM"+r(627)][r(520)]||await this[r(630)+"anager"][r(461)](),this["_cursorM"+r(627)];_0x20603e(_0x5ff265,16),OPKWfp.hdrtF(_0x438c9c,_0x32cd91,_0x1df6f7)}catch{return null}}async function Qg(c,r){let s=t,l=e[s(1089)](xn,c[s(537)][s(365)],s(1315),"-1"),h=xn(c[s(537)][s(365)],s(1095),"1"),w=e[s(658)](xr,c.message.headers,s(1071)+s(665)),S=e[s(1606)](Number,e[s(658)](xr,c[s(537)][s(365)],e[s(334)]))||0,v=Fa.call(this,c),m=xn(c.message.headers,e.XVsGE,"2"),O=e.PTpET(xr,c[s(537)].headers,e[s(937)]),M=e[s(394)](Number,e[s(1740)](xr,c.message[s(365)],e.HIevE));if(v.isQoSAck)return e[s(911)](r);let U=v[s(1188)+"sage"]?await Ul[s(1727)](this):null;if(c.message.service>0&&h&&!l||e[s(599)](c[s(537)][s(1702)],0)){if(w&&v[s(1188)+s(1576)]&&U)return!!!await U[s(760)](w)&&(this[s(1169)+s(1310)+s(763)](c),await U[s(1351)](w,e.jciJU(Date[s(1338)](),S))),e[s(911)](r);if(m){let $=await Gl[s(1727)](this);if(!$)return this[s(1169)+s(1310)+s(763)](c),e[s(1363)](r);let V=await $[s(760)](O)??-1;if(e[s(1148)](V,M))this["_dispatc"+s(1310)+s(763)](c),$.set(O,M,c[s(537)].service);else throw new Error(s(468)+s(1088)+" cursor "+M+(s(597)+s(1781)+s(415)+"r ")+V);return e[s(540)](r)}return this[s(1169)+s(1310)+s(763)](c),e[s(632)](r)}}async function em(c,r){let s=t,l=Fa[s(1727)](this,c);if(!l[s(1188)+s(1576)])return r();let h=await Ul[s(1727)](this);if(l["isAckCle"+s(1503)+s(475)]&&l.ackMsgIds[s(452)])for(let w of l[s(862)+"s"])await h[s(1417)](w);r()}async function tm(c,r){let s=t,l=c[s(537)][s(388)+"e"]===$g,h=c[s(537)].frameType===Ha;if(e[s(1730)](!l,!h))return r();let w=e[s(1053)](xr,c[s(537)][s(365)],s(1535)+s(918));if(!w)return e[s(577)](r);let S=await Gl.call(this,w);if(!S)return e[s(1665)](r);if(l)if(e[s(1573)](e[s(1767)],e.BfOdk)){let v=await S.getCursors(),m={frameType:v?.[s(388)+"e"],SeqID:we[s(1104)+"er"](this._seqId++),LogID:we[s(1104)+"er"](this._options["logIDGen"+s(1300)]()),service:9e3,method:5,headers:v?.headers,payload:v?.[s(1600)]},O=e[s(1710)](E,m);this._ws&&this[s(1017)][s(1530)+"te"]&&this[s(1017)].send(O)}else return _0x8fbe07(_0x1b1ad5);if(h){let v=c[s(537)][s(1600)];v&&S[s(1216)+"rs"](v)}}let nm=async function(c,r){let s=t;this[s(1131)]=!1,clearTimeout(this[s(1177)+"ionTimeo"+s(1552)]),e[s(911)](r)},rm=async function(c,r){let s=t;if(!this[s(1017)]||this[s(1017)].readyState!==this.OPEN)return e.zgGEh(r);let{pingInterval:l}=this._options;this[s(1205)+s(1459)]?.[s(796)+s(1764)+"fig"]();for(let w=0;e.duXFd(w,this._messageQueue[s(452)]);w++){let S=this[s(1309)+s(1561)][w];if(this[s(1017)][s(1530)+"te"]===this[s(1629)]&&S!==null)if(e.kcOZY===e[s(832)]){let v=_0x4f3836[s(537)].payload;v&&_0x518b07[s(1216)+"rs"](v)}else this[s(1017)]&&this[s(1017)][s(1102)](S),this[s(1309)+s(1561)][w]=null;else break}this._messageQueue=this[s(1309)+s(1561)].filter(w=>!!w),this[s(1716)+s(655)+"Id"]=setTimeout(()=>this[s(1680)](),l),this[s(1169)+s(1432)+"nt"](c),this._isBrowser&&this[s(1017)]&&(this[s(1017)].binaryType=this[s(1797)+s(1564)]);let h=this["_endpoin"+s(1459)]?.[s(782)+s(1160)+"nt"]();this[s(736)](s(1142)+h+" success"),e[s(1799)](r)},im=async function(c,r){let s=t,l=this[s(1205)+s(1459)]?.[s(782)+s(1160)+"nt"]();this._debug(s(1142)+l),r()};class sm extends Na{constructor(r){let s=t,l={ZSgoN:function(v,m){return e[K(1792)](v,m)},pmScc:e[s(989)],xSwpQ:function(v,m,O){return e[s(1118)](v,m,O)},CaMge:e.suyJS,TvXsa:e.rVtlv,hldwb:e.svKlk,cJfeG:e.VNOrk,WTBFB:e.mrXPe,HMGyL:function(v,m){return e[s(1027)](v,m)},HnQtd:function(v,m,O){return e[s(663)](v,m,O)},Cgncu:function(v,m){return e[s(1261)](v,m)},dPlNQ:s(884)+s(884)+s(884)+s(884),gzUlt:function(v,m){return e[s(1700)](v,m)},kiTCu:e[s(353)],RhHOH:e[s(1584)],OOtvh:function(v,m,O){return v(m,O)},bIMvJ:function(v,m){return v(m)},FYFQp:function(v,m){return e[s(715)](v,m)},ZOlNj:e[s(709)],fArFU:e[s(345)],sUXSw:function(v,m){return e.dKhkG(v,m)},syRDB:e.NPHRH,IsAPH:e.qjkou,YVDuN:function(v,m,O){return e[s(1358)](v,m,O)},OvINe:e.mmrLb,owJTy:function(v,m,O){return v(m,O)},yxSnL:e[s(833)]};super(),this[s(737)+s(1732)+s(1202)]=!0,this[s(477)+"er"]=pr,this[s(694)]=bg,this._isMiniTT=Fn,this._isMiniWX=fi,this[s(1465)+"r"]=hi,this[s(1309)+s(1561)]=[],this["_endpoin"+s(1459)]=null,this[s(1072)+s(623)]=!1,this[s(1797)+s(1564)]=e[s(1396)],this[s(1177)+s(547)]=!1,this["_connect"+s(1133)+s(1552)]=null,this[s(1161)+s(502)+s(1675)]=null,this[s(1716)+"gTimeoutId"]=null,this._seqId=0,this[s(1131)]=!1,this[s(1235)]="",this["_QoSMana"+s(1293)]=null,this[s(630)+"anager"]=null,this["_pingLos"+s(1269)]=null,this[s(1712)+"ls"]=e.tOCSL,this[s(759)]=3,this.CONNECTING=0,this.OPEN=1,this[s(401)]=2,this[s(1446)]=v=>{let m=s;try{if(l[m(1146)](l[m(1655)],m(1350)))Nl(this,v,[nm,rm,im]);else{let O=_0x426e46[m(668)]();return O?(O[m(689)]=O[m(992)]=0,O):{bytes:new _0x247382(64),offset:0,limit:0}}}catch(O){let M=l.xSwpQ(xt,l.CaMge,{message:O[m(537)],code:pn.OPEN_ERROR,error:O});this[m(1169)+m(368)+m(1009)](M)}},this._onMessage=async v=>{let m=s,{pingInterval:O,pingFrequency:M}=this._options;if((v[m(1361)]==="hi"&&l[m(1146)](l[m(1738)],M)||l.ZSgoN(l[m(749)],M))&&(this[m(1622)+m(798)](),this[m(1488)](l[m(1771)],l[m(1449)]),this[m(1716)+"gTimeoutId"]=l.xSwpQ(setTimeout,this[m(1680)].bind(this),O)),!l[m(1783)]("hi",v[m(1361)]))try{Nl(this,v,[Mg,Lg,em,tm,Qg,Ng])}catch(U){let $=l[m(986)](xt,"error",{message:U.message,code:pn.MESSAGE_ERROR,error:U});this[m(1169)+m(368)+m(1009)]($)}},this[s(721)]=v=>{let m=s,O=this[m(1205)+"tManager"]?.[m(758)+m(385)+"es"](),M=this[m(1205)+m(1459)]?.[m(782)+m(1160)+"nt"]();if(O&&!v.message)if(l[m(667)](l.kiTCu,l[m(1507)])){let U=m(378)+M+(m(539)+m(1073)+m(1754)+"ed");this[m(1169)+m(368)+m(1009)](xt("error",{message:U,code:pn[m(1496)+m(1135)+"R"],error:v}));return}else{let U=/(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}/[m(592)](_0x343c32),$=/(([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]))/[m(592)](_0x173111);return U?HqhLLY[m(1648)](_0x52011a,_0x3657ac):$?HqhLLY[m(1648)](_0x1747be,_0x3cf73d):HqhLLY[m(780)]}this._ws&&l[m(1146)](this._ws[m(1530)+"te"],this[m(1629)])&&this[m(1091)+m(955)](),this[m(1169)+m(368)+m(1009)](l[m(1435)](xt,l[m(789)],{message:v.message,code:pn[m(1426)+m(1697)],error:v}))},this[s(1406)]=async v=>{let m=s,O={OassB:function(U,$){return l[K(389)](U,$)},AcLtL:function(U,$){return l[K(1648)](U,$)}};this[m(449)+m(1638)](),this[m(1622)+m(798)](),this["_removeW"+m(1028)+"rs"](),this._ws=null,this[m(1177)+m(547)]=!1;let M=this[m(1205)+m(1459)]?.["checkRea"+m(385)+"es"]();if(!M&&this[m(990)+"orOnline"]()&&!this[m(1072)+m(623)]){if(l[m(1533)](l[m(381)],"wBySb"))return _0x4e4a69[m(1609)](_0x38e155),!1;{let U=this[m(1205)+m(1459)]?.["getCurre"+m(1160)+"nt"](),$=this[m(457)]["reconnec"+m(542)+m(779)](v[m(1315)],v.reason);this["_dispatchCloseEv"+m(1009)](l[m(1435)](It,l.fArFU,{code:1006,reason:v[m(569)]||m(1191)+m(1708)+"d, unknown reason, hostn"+m(1556)+U,willReconnect:$})),$&&this[m(1177)]();return}}if(l[m(667)](1e3,v[m(1315)])&&this[m(1072)+m(623)])if(l[m(948)](l[m(1366)],l[m(656)])){if(_0x312178>=_0x482c5c)return _0x32abba}else{this["_dispatc"+m(810)+"ent"](l[m(1444)](It,l.fArFU,{code:1e3,reason:l[m(1285)]})),this[m(1205)+m(1459)]?.[m(796)+"pointCon"+m(336)](),this["_pingLos"+m(1269)]?.[m(774)+m(885)]();return}if(l.gzUlt(1e3,v[m(1315)])&&M){let U=this[m(1205)+m(1459)]?.[m(782)+m(1160)+"nt"](),$=v[m(569)];$||($=await l[m(1648)](Tg,this[m(1235)])),$=m(1191)+m(1708)+"d, "+$+(", hostna"+m(594))+U+(", max re"+m(1365)+m(940)),this._dispatchCloseEvent(l[m(1435)](It,l[m(1756)],{code:v.code,reason:$}));let V="connect "+U+(m(539)+m(1073)+m(1754)+"ed");this["_dispatchErrorEv"+m(1009)](l[m(1345)](xt,m(1260),{message:V,code:pn[m(1496)+m(1135)+"R"]})),this[m(1205)+"tManager"]?.["resetEnd"+m(1764)+m(336)](),this[m(1580)+m(1269)]?.[m(774)+"nter"]();return}if(v[m(1315)]!==1e3&&!v.reason)if(l[m(1536)]!==l[m(1536)])KHXDHS[m(498)](_0x522044,KHXDHS[m(1014)](_0x3e99ad,_0xf9230e.result)),_0x566c02();else{let U=this[m(1205)+m(1459)]?.["getCurre"+m(1160)+"nt"]();this[m(1169)+"hCloseEv"+m(1009)](l[m(1435)](It,l[m(1756)],{code:v[m(1315)],reason:m(1191)+m(1708)+"d, unkno"+m(871)+"n, hostname: "+U})),this["_endpoin"+m(1459)]?.[m(796)+m(1764)+m(336)](),this[m(1580)+m(1269)]?.[m(774)+m(885)]();return}this[m(1169)+m(810)+"ent"](v),this[m(1205)+m(1459)]?.["resetEnd"+m(1764)+"fig"](),this[m(1580)+m(1269)]?.[m(774)+"nter"]()},this.onclose=null,this.onerror=null,this[s(706)+"e"]=null,this.onopen=null,this[s(549)+s(711)]=null,this[s(355)+s(859)]=null,this[s(1166)+s(1478)+"yReconnect"]=null,this[s(1439)+s(1623)]=this[s(1439)+s(1623)][s(1342)](this),this[s(1439)+s(1052)]=this["_handleO"+s(1052)][s(1342)](this),this[s(863)+s(1729)]=this["_handleP"+s(1729)][s(1342)](this),this[s(863)+s(930)]=this[s(863)+s(930)].bind(this),this[s(457)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(1408)](1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(891)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(558)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:w}=r,S=Array[s(554)](h)?h:e[s(719)](e.tuSCr,typeof h)?[h]:[];if(!S||e[s(1272)](0,S.length))throw new Error(e[s(677)]);if(!Sg(w))throw new Error("please p"+s(579)+s(1349)+", WebSoc"+s(1209)+s(1671)+"is undef"+s(1245));Object[s(1397)](this[s(457)],r),this[s(1205)+s(1459)]=new Ll(S,this._options[s(1218)+"es"]),this[s(1580)+s(1269)]=new kg(this[s(457)][s(566)+s(650)]),this[s(457)][s(1581)+"cOpen"]&&(this._isInit=!0,this[s(1177)]()),this._options[s(1483)+s(872)+s(1749)]&&(this[s(1499)+"T"]||this._isMiniWX?this[s(685)+s(1569)+"ange"]():this[s(477)+"er"]&&this["_initGlo"+s(716)+s(1643)]())}[t(1439)+t(1623)](){let r=t;this[r(457)][r(564)+"utoRecon"+r(421)]||this[r(1072)+r(623)]||this[r(1442)+"econnect"]()}_handleOffLine(){let r=t;if(e[r(1456)]!==e.kVFnf){this._destroyWebSocket();let s=La(e.looHq,{message:e[r(983)]});this[r(1166)+r(1478)+"yReconnect"]&&this[r(1166)+r(1478)+r(931)+"ct"](s)}else{let s={ARoPr:function(h,w){return e[r(1139)](h,w)},NckLY:function(h,w){return h&w},xQuUO:function(h,w){return h<w},uTnFx:function(h,w){return e[r(1741)](h,w)},etNso:function(h,w){return h|w},IPxMo:function(h,w){return h<<w},WKiep:function(h,w){return e[r(816)](h,w)},uCgzW:function(h,w){return h<w},AXNZO:function(h,w){return h|w}},l=4294967295;return function(h,w,S=!0){let v=r;if(l=s[v(860)](s[v(1312)](127,h[w]),0),s[v(1246)](h[w++],128))return{value:S?l:s.uTnFx(0,l),offset:w};if(l=s[v(660)](l,(127&h[w])<<7)>>>0,s[v(1246)](h[w++],128))return{value:S?l:0|l,offset:w};if(l=(l|(127&h[w])<<14)>>>0,s.xQuUO(h[w++],128))return{value:S?l:s[v(660)](0,l),offset:w};if(l=s[v(860)](s[v(1625)](l,s[v(1223)](s[v(1373)](127,h[w]),21)),0),s[v(625)](h[w++],128))return{value:S?l:0|l,offset:w};if(l=s.ARoPr(s[v(1301)](l,(15&h[w])<<28),0),s[v(625)](h[w++],128))return{value:S?l:0|l,offset:w};if((w+=5)>h.length)throw w=h.length,_0x4ddb31(w,10,h[v(452)]);return{value:S?l:0|l,offset:w}}}}[t(987)+"balEventListener"](){let r=t;this._isBrowser&&window.addEventListener(e[r(1703)],this[r(1439)+r(1623)]),this[r(477)+"er"]&&window[r(584)+r(1643)](e[r(849)],this[r(1439)+r(1052)]),this._isBrowser&&window["addEvent"+r(1643)](e[r(1637)],this[r(863)+"ageHide"]),this[r(477)+"er"]&&window[r(584)+r(1643)](e.DZTCD,this[r(863)+r(930)])}[t(1457)+"balEventListener"](){let r=t;this[r(477)+"er"]&&window[r(1327)+"entListe"+r(1492)](e[r(1703)],this[r(1439)+r(1623)]),this[r(477)+"er"]&&window["removeEv"+r(681)+"ner"](r(1121),this[r(1439)+r(1052)]),this[r(477)+"er"]&&window[r(1327)+"entListener"](e[r(1637)],this["_handleP"+r(1729)]),this._isBrowser&&window[r(1327)+r(681)+"ner"](e.DZTCD,this._handlePageShow)}[t(863)+t(1729)](r){let s=t,l={eEEtP:function(h,w){return e.MXitv(h,w)},kQdzu:function(h,w){return e.iAEKK(h,w)},NniJi:function(h,w){return e.jDGMc(h,w)},NMQMu:function(h,w){return h&w},CuQKc:function(h,w){return h&w}};if(e.TJkpD(e[s(1805)],e[s(1437)]))_0x13616a.d=(h,w)=>{let S=s;for(var v in w)_0x3c646f.o(w,v)&&!_0x25148f.o(h,v)&&_0x2bf678[S(1247)+S(1149)](h,v,{enumerable:!0,get:w[v]})};else{if(!r.persisted)if(e.MYpCS(e[s(338)],"hQOwc")){let h=this[s(1608)],w=this[s(1570)];return[WGbrnD[s(571)](255,w),WGbrnD[s(1203)](w,8)&255,w>>>16&255,WGbrnD.NniJi(w,24),WGbrnD[s(1094)](255,h),WGbrnD[s(1571)](WGbrnD[s(1203)](h,8),255),WGbrnD.eEEtP(WGbrnD[s(1203)](h,16),255),WGbrnD[s(1203)](h,24)]}else this[s(477)+"er"]&&window[s(1327)+s(681)+s(1492)](e.ITiQc,this[s(863)+s(1729)]),this._isBrowser&&window["removeEv"+s(681)+s(1492)]("pageshow",this[s(863)+s(930)]),this[s(673)]();this[s(477)+"er"]&&window["removeEv"+s(681)+"ner"](e[s(1703)],this[s(1439)+s(1623)]),this[s(477)+"er"]&&window[s(1327)+s(681)+s(1492)](e.fGwwz,this[s(1439)+"ffLine"])}}[t(863)+t(930)](r){let s=t;r[s(698)+"d"]&&(this[s(990)+"orOnline"]()&&(!this._ws||e[s(1290)](this[s(1017)][s(1530)+"te"],this[s(1629)])||e.nKdhn(this[s(1017)][s(1530)+"te"],this[s(1687)+"NG"]))&&this[s(1439)+s(1623)](),this._isBrowser&&window["addEvent"+s(1643)](e.VKObm,this["_handleO"+s(1623)]),this[s(477)+"er"]&&window[s(584)+"Listener"](e[s(849)],this["_handleO"+s(1052)]))}async[t(1050)+t(1412)](r){let s=t,{fpID:l,deviceID:h,bddID:w,ttwID:S,accessKey:v,aID:m,customParams:O={},enableAutoAck:M,enableQoS:U,QoSLevel:$,env:V}=this[s(457)],Q,ue,L;this[s(477)+"er"]||this._isMiniWX||this[s(1499)+"T"]?(Q=location&&e.VCyti(e[s(710)],location[s(1249)])?e[s(407)]:e.JyvyG,ue=r[s(448)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),L=/^wss(.*:\/\/)/[s(592)](r)?r:""+Q+ue):(Q=e[s(407)],ue=r[s(448)](/(^http)((?:[s]*:\/\/))/,""),L=/(^ws)((?:[s]*:\/\/))/[s(592)](ue)?ue:""+Q+ue);let N=w?s(744):S?e.AqFad:e[s(1654)],fe=w||S||h;if(e.rszev(!fe,!N))throw new Error(e[s(1143)]);let st=e[s(1042)](e[s(1736)],typeof O)?await e.NyPXh(O):O,gt=V?e[s(1773)](Ag,V.xUseEnv,V[s(1577)]):{},ot=Object.assign({device_platform:e[s(357)],version_code:e[s(1743)],access_key:v,fpid:l,aid:m,[N]:fe,xsack:M?1:0,xaack:M?1:0,xsqos:U?1:0,qos_level:U?$:void 0,qos_sdk_version:2,...gt},st),om=Object[s(1630)](ot)[s(412)]((Ga,qa)=>ot[qa]!==void 0?""+Ga+(Ga?"&":"?")+qa+"="+ot[qa]:Ga,"");return L+s(649)+om}async[t(1177)](){let r=t;if(!(this[r(1177)+"Lock"]||this[r(1072)+r(623)])){this[r(1177)+r(547)]=!0;try{let s=this[r(1205)+r(1459)]?.[r(1369)+r(602)+"ointReachedMaxRe"+r(1460)](),{timeoutInterval:l}=this[r(457)];if(s){let w=this[r(1205)+r(1459)]?.[r(782)+"ntEndpoint"](),S=this[r(1205)+"tManager"]?.["replaceB"+r(590)+"pointAndUpdateCo"+r(441)](),v=this["_endpoin"+r(1459)]?.[r(782)+r(1160)+r(578)+"ount"]();if(S){let m=r(378)+w+(" timeout, max re"+r(1365)+r(777)+r(1634)+r(1769)+r(775))+S+(r(1151)+"y"),O=e[r(489)](xt,r(1260),{message:m,code:pn[r(1496)+"IES_ERROR"]});this[r(736)](m),this["_dispatchErrorEv"+r(1009)](O),this[r(1235)]=await this["_generat"+r(1412)](S),this[r(736)](r(378)+S+" "+v+" times"),this._removeWsListeners()}else{if(e[r(1602)](e.AYwYL,"rxGkN"))return this[r(1696)+"ndpointT"+r(1585)+"t"]=1,this["currentI"+r(916)]++,this[r(529)+"s"][this["currentI"+r(916)]];{let m=r(378)+w+(r(1099)+", max re"+r(1365)+r(940));this[r(736)](m),this[r(1169)+r(368)+r(1009)](e[r(392)](xt,e[r(642)],{message:m,code:pn["MAX_RETR"+r(1135)+"R"]}));return}}}else{let w=this[r(1205)+"tManager"]?.[r(782)+"ntEndpointAndUpdateCount"](),S=this[r(1205)+r(1459)]?.[r(782)+r(1160)+"ntTriesC"+r(878)]();this[r(1235)]=await this["_generat"+r(1412)](e[r(1049)](w,"")),this[r(736)](r(378)+w+" "+S+r(755)),this[r(1232)+r(1028)+"rs"]()}if(this._isInit)this._isInit=!1;else{let w=e[r(869)](La,e[r(1779)],{message:e.VbyUB});this[r(549)+r(711)]&&this[r(549)+r(711)](w)}let h=this[r(1205)+r(1459)]?.[r(782)+"ntEndpoi"+r(578)+"ount"]()||0;e[r(599)](h,1)&&await this._wait(e[r(662)](h,1)),this[r(736)](r(1191)+r(720)+this[r(1235)]+(r(1472)+r(1367))+this[r(1712)+"ls"]),this[r(1017)]=vg({url:this._url,protocols:[this[r(1712)+"ls"]],headers:this[r(457)][r(1599)+r(1330)+"s"][r(1681)+r(1400)]},this[r(457)].ws),(this._isBrowser||this[r(1465)+"r"])&&this[r(1017)]&&(this[r(1017)][r(1030)+"pe"]=this[r(1797)+"ype"]),this["_addWsLi"+r(637)](),this[r(1177)+r(1133)+r(1552)]=setTimeout(this[r(1425)+"ut"][r(1342)](this),l)}catch(s){throw this[r(1177)+"Lock"]=!1,s}}}[t(449)+t(1638)](){let r=t;e.wgdkc(e[r(1227)],e[r(1438)])?(e[r(1550)](clearTimeout,this[r(1177)+r(1133)+r(1552)]),this["_connect"+r(1133)+r(1552)]=null):(this[r(1622)+r(798)](),this[r(1488)](r(396)+r(568)+"s",e[r(741)]),this[r(1716)+r(655)+"Id"]=e[r(1490)](_0x1f8694,this._ping[r(1342)](this),_0x5cf437))}["_clearPi"+t(798)](){let r=t;clearTimeout(this[r(1716)+"gTimeoutId"]),clearTimeout(this[r(1161)+r(502)+r(1675)]),this[r(1716)+r(655)+"Id"]=null,this["_reconne"+r(502)+r(1675)]=null}[t(736)](...r){let s=t;this[s(457)][s(1020)]&&console[s(1609)][s(494)](console,[e[s(1386)],...r])}[t(1618)+t(1508)+"e"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:w}=this[s(457)],S=e.HZAJw(l,Math[s(757)](w,e[s(427)](r,1)));return e.wgtie(S,h)?h:S}[t(1680)](){let r=t;if(this[r(1017)]&&this._ws[r(1530)+"te"]===this[r(1687)+"NG"]){this[r(1622)+r(798)](),this["_pingPon"+r(655)+"Id"]=setTimeout(this[r(1680)][r(1342)](this),this[r(457)]["pingInte"+r(1318)]);return}if(!this[r(1017)]||e[r(1290)](this[r(1017)][r(1530)+"te"],this[r(1629)]))return void this[r(1442)+r(711)]();this[r(1017)]&&this[r(1017)].send("hi"),this[r(1161)+r(502)+"tId"]=e[r(1252)](setTimeout,this[r(1442)+r(711)+r(1707)].bind(this),this._options[r(409)+r(830)+"val"])}[t(1442)+t(711)+t(1707)](){let r=t,s={rKIEz:function(l,h){return e[K(754)](l,h)}};e[r(1789)](e[r(1615)],e[r(1012)])?jGvfoT[r(1595)](_0x3d1b86,_0x1d4b2f)&&_0x45a281[r(1351)](_0x5a9c32,_0x8ff64):(this[r(1580)+"sCounter"]?.[r(704)](),this[r(1488)](r(396)+r(1244)+"t",e[r(1473)]),this["_pingLos"+r(1269)]?.[r(758)+"chMaxCount"]()?this[r(1442)+"econnect"]():this[r(1680)]())}["_navigat"+t(1752)](){let r=t;return this._isMiniTT||this._isMiniWX?this[r(737)+r(1732)+r(1202)]:(this[r(477)+"er"]||this[r(1465)+"r"])&&this[r(457)][r(1483)+"tworkCha"+r(1749)]?navigator[r(1778)]:!0}_handleReconnect(){let r=t;if(e.eaJNo!==e[r(889)]){if(!this["_navigat"+r(1752)]()||this[r(1072)+r(623)])return;this["_endpoin"+r(1459)]?.[r(796)+r(1764)+r(336)](),this["_pingLos"+r(1269)]?.[r(774)+"nter"](),this[r(1017)]?this["_disconn"+r(955)](1001,e[r(347)],!0):this[r(1177)]()}else return null}["_onPageN"+t(1569)+t(705)](){let r=t,s={CqyQM:e[r(1747)],ZcnNo:function(l,h){return e[r(1328)](l,h)},TyCUe:e.shaCp};e.LcoVK(r(1685),e[r(1501)])?this[r(917)+r(1658)]=null:this[r(1499)+"T"]?tt[r(1256)+"kStatusChange"](({isConnected:l})=>{let h=r,w={RbHsU:s.CqyQM};if(s[h(1359)](s.TyCUe,h(535))){let S={AWEhE:function(v,m){return v(m)}};_0x21df00["addEvent"+h(1643)](qQsNzr[h(1253)],v=>{let m=h;_0x2a4899(S[m(451)](_0x412ac7,_0x513411.result),v.oldVersion,v.newVersion,_0x33056e(_0x181950[m(764)+m(1762)]))})}else this[h(737)+"igatorOnline"]=l,l?this["_handleO"+h(1623)]():this[h(1439)+h(1052)]()}):this[r(958)+"X"]&&wx[r(1256)+"kStatusC"+r(880)](({isConnected:l})=>{let h=r;this[h(737)+"igatorOn"+h(1202)]=l,l?this._handleOnLine():this[h(1439)+h(1052)]()})}_wait(r){let s=t,l={dhSEc:function(h,w,S){return e.DJVvX(h,w,S)}};if(s(1746)!==s(1746)){this["_destroy"+s(1032)+"t"]();let h=e[s(1344)](_0x3c8288,"reconnect",{message:e[s(983)]});this[s(1166)+"mediatelyReconnect"]&&this[s(1166)+"mediatelyReconnect"](h)}else return new Promise(h=>{let w=s;l[w(1669)](setTimeout,h,this[w(1618)+w(1508)+"e"](r))})}[t(1091)+t(955)](r=1e3,s="",l=!1){let h=t;this[h(1017)]&&this[h(700)+h(1032)+"t"](r,s,l)}_onTimeout(){let r=t,s=this["_endpoin"+r(1459)]?.[r(782)+"ntEndpoint"]();this._debug(r(378)+s+" timeout"),this[r(1091)+"ect"](1001,r(766)+r(1722)+r(1172)+"g",!0)}[t(695)](r){let s=t,l=e.Jskbq($t,r);this[s(1017)]&&this[s(1017)][s(1530)+"te"]===this[s(1629)]&&(this._ws&&this[s(1017)].send(l),this._debug(s(1538),r))}[t(1232)+"sListeners"](){let r=t;this[r(1017)]&&(this[r(1017)][r(1327)+r(681)+r(1492)](e.xIwKE,this[r(1446)]),this._ws[r(1327)+"entListener"](e.WhqyP,this[r(1406)]),this._ws[r(1327)+r(681)+r(1492)](r(537),this[r(836)+"ge"]),this[r(1017)][r(1327)+r(681)+r(1492)](e.suyJS,this[r(721)]))}[t(1649)+t(637)](){let r=t,s=e[r(735)][r(1087)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1017)][r(584)+"Listener"](r(1549),this[r(1446)]);continue;case"1":this[r(1017)]["addEvent"+r(1643)](e.WhqyP,this[r(1406)]);continue;case"2":this._ws[r(584)+r(1643)]("error",this._onError);continue;case"3":this._ws[r(584)+r(1643)](r(537),this._onMessage);continue;case"4":if(!this[r(1017)])return;continue}break}}_wsInstanceClose(r=1e3,s=""){let l=t;if(e.BFndE(e[l(1480)],e[l(1480)]))return e[l(506)](e[l(474)],typeof _0x241b86)?e.sRDRR:"";try{this[l(1017)]&&this[l(1017)][l(673)](r,s)}catch{}}[t(700)+t(1032)+"t"](r=1e3,s="",l=!1){let h=t;if(this[h(1622)+h(798)](),this[h(449)+h(1638)](),this[h(1232)+"sListeners"](),this[h(692)+"nceClose"](1e3,s),this[h(1177)+h(547)]=!1,l&&this[h(990)+h(1752)]()&&!this[h(1072)+h(623)]){if(this[h(1205)+"tManager"]?.[h(758)+h(385)+"es"]()){let S=this[h(1205)+h(1459)]?.["getCurre"+h(1160)+"nt"]();this[h(1169)+h(810)+h(1009)](It(h(673),{code:1006,reason:h(378)+S+" timeout, max retries reached",wasClean:!0}))}else{let S=this[h(457)]["reconnectInterce"+h(779)](r,s);this[h(1169)+h(810)+h(1009)](e[h(867)](It,e[h(345)],{code:r,reason:s,wasClean:!0,willReconnect:S})),S&&this[h(1177)]()}return}this["_navigat"+h(1752)]()||this[h(1072)+"osed"]?this[h(1169)+"hCloseEv"+h(1009)](e.GcQUE(It,e.WhqyP,{code:r,reason:e[h(1734)]})):this[h(1169)+h(810)+h(1009)](e[h(1023)](It,h(673),{code:1006,reason:e[h(446)]})),this[h(1017)]=null,this[h(1205)+h(1459)]?.[h(796)+h(1764)+h(336)](),this["_pingLos"+h(1269)]?.[h(774)+h(885)]()}["_dispatc"+t(1432)+"nt"](r){let s=t;this[s(1488)](e[s(1078)],r),this[s(1236)]&&this[s(1236)](r)}[t(1169)+t(1310)+t(763)](r){let s=t;this[s(1488)](s(537),r),this.onmessage&&this[s(706)+"e"](r)}[t(1169)+"hAckMess"+t(1471)](r){let s=t;this.emit(e[s(1144)],r),this[s(355)+s(859)]&&this[s(355)+"eAck"](r)}[t(1169)+t(368)+t(1009)](r){let s=t;this.emit(e[s(642)],r),this[s(605)]&&this.onerror(r)}[t(1169)+t(810)+t(1009)](r){let s=t,l={jSDhn:function(h,w){return e[K(669)](h,w)},mfBHe:function(h,w){return h<<w},qFODB:function(h,w){return e.OUzWh(h,w)}};if(e.SCBHv(e[s(380)],"fbnPL"))this[s(1488)](e[s(345)],r),this[s(1140)]&&this[s(1140)](r);else{let h=0,w=0,S;do S=vlUINv[s(1691)](_0x36270b,_0x1c7d89),h<32&&(w|=vlUINv[s(899)](vlUINv[s(1390)](127,S),h)),h+=7;while(vlUINv.qFODB(128,S));return w}}get[t(1030)+"pe"](){let r=t;return this._ws?this[r(1017)][r(1030)+"pe"]:this[r(1797)+r(1564)]}set binaryType(r){let s=t;this["_binaryT"+s(1564)]=r,this._ws&&(this[s(1017)][s(1030)+"pe"]=r)}get retryCount(){let r=t;return this[r(1205)+r(1459)]?.[r(782)+r(1160)+r(578)+"ount"]()||0}get[t(1034)+t(846)](){let r=t,s=this[r(1309)+r(1561)].reduce((l,h)=>(l+=h&&h.byteLength||0,l),0);return e[r(1601)](s,this._ws?this[r(1017)][r(1034)+r(846)]:0)}get[t(562)+"ns"](){let r=t;return this[r(1017)]?this[r(1017)][r(562)+"ns"]:""}get[t(1249)](){let r=t;return this._ws?this[r(1017)][r(1249)]:""}get[t(1530)+"te"](){let r=t;if(r(1194)!==e[r(811)]){let s=e[r(391)](_0x397143,_0x4939ac);this[r(1017)]&&e.mvkzJ(this[r(1017)].readyState,this.OPEN)&&(this[r(1017)]&&this[r(1017)][r(1102)](s),this[r(736)](e[r(999)],_0x731669))}else return this[r(1017)]?this[r(1017)][r(1530)+"te"]:this[r(457)][r(1581)+"cOpen"]?this[r(1687)+"NG"]:this[r(759)]}get[t(686)](){let r=t;return this[r(1017)]?this._ws.url:this[r(1235)]}[t(673)](r=1e3,s){let l=t,h=e[l(745)][l(1087)]("|"),w=0;for(;;){switch(h[w++]){case"0":this[l(700)+"WebSocket"](r,s);continue;case"1":this[l(1072)+l(623)]=!0;continue;case"2":if(!this[l(1017)])return void this[l(736)](e[l(609)]);continue;case"3":this[l(449)+l(1638)]();continue;case"4":this[l(1457)+l(716)+l(1643)]();continue;case"5":this[l(1622)+l(798)]();continue;case"6":if(e[l(517)](this._ws[l(1530)+"te"],this[l(759)])||e[l(1789)](this[l(1017)][l(1530)+"te"],this.CLOSING))return void this[l(736)](e[l(742)]);continue;case"7":this["_QoSMana"+l(1293)]?.[l(1171)]();continue}break}}async send(r,s){let l=t,h={tMgMt:e[l(951)]};if(e[l(348)](null,r))throw new Error(e[l(898)]);e[l(583)](e[l(1313)],typeof r)&&(r=JSON[l(1215)+"y"](r)),e[l(639)](e[l(474)],typeof r)&&!(r instanceof ArrayBuffer)&&!(r[l(548)]&&e[l(641)](r[l(548)],ArrayBuffer))&&(r=JSON[l(1215)+"y"](r));let w=await e[l(1228)](Fl,r),S=e[l(1320)](Ig,r),{method:v=0,service:m=this[l(457)][l(1702)],logID:O=this[l(457)].logIDGenerator(),headers:M=this[l(457)].headers,payloadEncoding:U=this._options[l(1717)+l(1302)],payloadType:$=this._options["payloadT"+l(1564)],logIDNew:V=this[l(457)][l(507)+l(610)][l(1107)+l(827)+l(1371)+"ew"]?i(this[l(457)]["logIDNew"+l(610)][l(1317)]):""}=e[l(1413)](s,{});if(!m)throw new Error("please p"+l(1527)+l(1434)+"ervice");let Q={SeqID:we.fromNumber(this[l(1493)]++),LogID:we[l(1104)+"er"](O),service:m,method:v,headers:M,payloadEncoding:U instanceof Object?U[l(1395)]?U[l(1395)]:"":U,payloadType:$ instanceof Object?$[l(699)]?$[l(699)]:S:$||S,payload:w,LogIDNew:V},ue=e.Jskbq($t,Q);if(this[l(1017)]&&e.PLOBm(this._ws.readyState,this.OPEN))this._ws&&this._ws.send(ue),this[l(736)](e[l(1443)],Q);else if(e[l(1450)](this[l(1309)+l(1561)].length,this._options.maxMessageQueueLength))this[l(1309)+l(1561)][l(1004)](ue),this._debug(e[l(453)],Q);else{if(e.Tobxq("nmWhe",e[l(1077)]))return _0x333343||(_0x6c9f92=_0x1ccc3e[l(1265)]().then(_0xd18e5f[l(1342)](_0x2a3569,QLEfBY[l(413)]))),_0x9c4096;this[l(1309)+"Queue"][l(635)](),this[l(1309)+"Queue"][l(1004)](ue)}return{seqID:this[l(1493)],logID:O,logIDNew:V}}async[t(439)+"t"](r){let s=t;if(e.hTwgP(e[s(1662)],s(817))){let l=!!this[s(457)][s(1757)+"S"];if(!l)return{enabled:l,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let h=_0x5bc6c9(_0x487c9c.message.headers,s(1071)+s(1782),"2"),w=h&&e[s(835)](_0xf972a6,_0x22e61f[s(537)][s(365)],s(1071)+s(490)+"ck","1"),S=h&&_0x9e8670(_0x5dd573[s(537)][s(365)],e[s(1511)],"1"),v=S?e[s(1753)](_0x1a9a98,_0x1caa07[s(537)][s(365)],e[s(1340)])?.[s(1087)](",")[s(418)](_0x6cffd)||[]:[];return{enabled:l,isQoSMessage:h,isQoSAck:w,isAckCleanupMessage:S,ackMsgIds:v}}else{let{url:l}=e.xfTCF(r,{}),h=Array.isArray(l)?l:e[s(1650)](e[s(474)],typeof l)?[l]:[];if(r&&Object[s(1397)](this._options,r),h&&h[s(452)]?this["_endpoin"+s(1459)]=new Ll(h,this[s(457)][s(1218)+"es"]):this[s(1205)+s(1459)]?.[s(796)+"pointConfig"](),this[s(1580)+"sCounter"]?.[s(774)+"nter"](this[s(457)][s(566)+"Count"]),this[s(1072)+s(623)]=!1,this[s(1017)]&&this[s(1017)][s(1530)+"te"]!==this[s(759)])this["_disconn"+s(955)](1e3,s(702)+s(711)+s(383),!0);else{if(e.rHvvQ(e[s(480)],e.GwaOe))return this[s(1068)][s(1030)+"pe"];this[s(1131)]=!0,this[s(1177)]()}}}async connect(){let r=t;if(!this._connectLock){let s=e.vINft.split("|"),l=0;for(;;){switch(s[l++]){case"0":this._readyClosed=!1;continue;case"1":this[r(1177)]();continue;case"2":this[r(1131)]=!0;continue;case"3":this[r(1205)+r(1459)]?.[r(796)+"pointConfig"]();continue;case"4":this[r(1580)+r(1269)]?.[r(774)+"nter"]();continue}break}}}["addEvent"+t(1643)](r,s){this.on(r,s)}[t(1086)+t(763)](r){let s=t,{type:l}=r;this[s(1488)](l,r)}[t(1327)+t(681)+t(1492)](r,s){this.off(r,s)}[t(587)](){let r=t,s={kUtbQ:function(l,h){return e[K(1606)](l,h)},ekGLd:e[r(741)],CTSpB:e.VNOrk,BAcSa:r(396)+r(1244)+"t",wJqIb:"timeout"};return new Promise((l,h)=>{let w=r;this[w(1622)+w(798)](),this[w(1716)+"gTimeoutId"]=e[w(624)](setTimeout,this[w(1680)][w(1342)](this),this[w(457)].pingInterval);let S=()=>{let m=w;s[m(762)](l,s[m(1291)]),this[m(1152)](s.CTSpB,S),this[m(1152)](s[m(675)],v)},v=()=>{let m=w;s[m(762)](h,s[m(769)]),this[m(1152)](s[m(1387)],S),this[m(1152)](s[m(675)],v)};this.on(e[w(397)],S),this.on(e[w(1109)],v),this[w(1680)]()})}}})(),Oe[B(941)+B(496)]=Be[B(941)+B(496)],Oe[B(1175)+"rorEvent"]=Be[B(1175)+B(1676)],Oe.ErrorCode=Be[B(1418)+"e"],Oe[B(763)]=Be[B(763)],Oe.FWS=Be[B(993)],Oe[B(574)+B(1487)+"vent"]=Be[B(574)+B(1487)+"vent"],Oe[B(1487)+B(773)]=Be.MessageEvent,Oe.OpenEvent=Be.OpenEvent,Oe["Reconnec"+B(1204)]=Be[B(812)+B(1204)],Oe[B(648)+B(496)]=Be[B(648)+B(496)],Oe[B(1311)+B(1676)]=Be["createEr"+B(1676)],Oe.createMessageEvent=Be[B(1546)+B(1677)+"nt"],Oe[B(1306)+B(924)]=Be[B(1306)+B(924)],Oe[B(857)+B(1279)+B(773)]=Be[B(857)+B(1279)+"vent"],Oe[B(1283)+B(563)]=Be[B(1283)+B(563)],Oe[B(1039)+B(1389)]=Be[B(1039)+"ame"];for(ua in Be)[B(941)+B(496),"CustomEr"+B(1676),B(1418)+"e",B(763),B(993),B(574)+B(1487)+B(773),"MessageE"+B(773),"OpenEvent",B(812)+B(1204),B(648)+B(496),"createEr"+B(1676),"createMessageEvent",B(1306)+"enEvent","createRe"+B(1279)+B(773),"decodedFrame",B(1039)+"ame"][B(921)](ua)===-1&&(Oe[ua]=Be[ua]);function ma(){let t=["C2v0","z1vmsKW","AeH2wvq","v1PsDeO","zcbLCNjVCI4","veTXq3i","Dw5RBM93BIa","CgndtuW","wMnUtM8","A2v5","zgf0yq","whPkqKK","ufLjruG","C3jxtK4","DhjPzxmGCMu","C3Lsrei","Bhm6ia","zNjVBuj5Dgu","y2HLy2TdDxi","t2vvA0m","DgvmB2Djre4","Dg9oDw1Izxi","v0TPzxa","yvbky0i","zNvUy3rPB24","zxfkD2m","zwzeswy","swLxtKm","CMfUzg9T","AwLNtgq","AuDZzhq","t1L1DM8","mJq3mtmZnNbArunNyW","veTftxq","A2zNrvG","vxD4BKO","q1rtCei","zxq9DxrMltG","yw1L","Cuzprei","AxjLza","r1L2wKK","EuvlEKO","Ahr0Ca","zw5JB2rPBMC","CgjMA0O","yxnZAwDU","CMvQzwn0","D0nSvxi","DhbizwfKzxi","r1vIuem","EefQCxe","y2vZC0HHBMq","vgfN","ww5nzMe","x29Uq2XVC2u","zhzwCK0","zxnwCwu","tuDoDNe","t1fLCfu","EeX2vu0","zvvYBa","z3jNDee","zfbTENO","qNjOve4","y1LuAgW","zgvS","rxjYB3jdB2q","C3jJ","C3nYu2K","Ec1TC2CTCw8","t1n5reu","y29Uy2f0","sLfHEMS","x29UvgLTzw8","tKfusvzfx0u","qvfPuxO","twLZC2LUzYa","te5eBKm","tLrbzKC","zhvyrMq","Ae9Wzw5fDMu","ELz5qui","ihzHBgLKihm","t090DMG","yK9OrMq","rLnbseW","AenNuu8","x2HHBMrSzu8","vM1iuKG","D3jPDgvvAw4","x2HHBMrSzvi","Dg5yzLa","wvzeDu4","qMHMs2m","x29Ut3bLBG","wejewvG","yxbWzw5Kq2G","v1rcrKi","EvfeC1a","mJGYCMrvCKP2","CeTJuKy","v3LAuwm","u2ryD04","zuXKEeK","tNDks1i","x2rYB3bhBg8","ignVzgu6ia","De1HBMfNzxi","DhjPzxm","vxbYswy","CIb0DhDjra","Dg9cExrLCW","DgfIyxnL","x2LZv29YA2u","qKfRBKC","ChjVDg90Exa","u1DNz2i","m3WYFdr8mxW","EgH2vNa","ywDLrxzLBNq","ihbYB3rVy28","q0j1vLG","ueXtvhC","AKrhtwm","q1LotvO","yKDAz2i","BwvKAwf0zwW","Dg9Y","z0LHsK8","BM5Ly3q","whjhtvK","BgLZDgvUtMu","AM9PBG","zujktNy","y3jLyxrLrwW","twvZC2fNzuu","zw1PDa","uMvYzw4","y25nve0","Dgv4Dc9WBge","BMvY","x3nLCuLK","zfjeDMK","tMfTzq","tufyx1jfvfi","z2jcExe","ruPTu0m","x2LZtwLUAvq","ywXPzcb1CMW","rNLxzuO","AeDQtwy","yw51Ce1LC3m","EwXbz04","BMjHBfq","yufbC3y","uMHit0G","CNzHBfzHBhu","BM5AEMm","y0P5uwm","A0vWA2W","u2vYDMLJzvC","teHyEee","qNnMvhG","tfvRzgO","yxKSihrYEsa","zwTAzxC","sNfvrvq","wurOruu","DcbSAw1PDa","wejhvMi","nhWZFdb8mxW","wLD4wvu","C2PWzNa","Dgv4Dc9Qyxy","C29Tzq","CM92AwrLige","BNrbBMrvCgq","BxzREKO","CMvHzhLtDge","wNnhD08","B2nRzxrgywK","rLLguxa","tvLWq1m","y3vYC29Yx2y","ExHtBKW","zfDVCMTLCKC","C2vUzf9Hy2S","Bwf4tg9ZC0m","vKHRDxi","C2nYAxb0","BgTLqvq","y29UDgLUDwu","D29bEeq","wwTYwwC","y3jLyxrLtwu","x3bHDgHlzxK","swHRshC","B3bLBG","C2LVuvG","Cu9otMO","Dxrjza","BgLUzw5V","ruXADwm","zM1eDuK","yw1LoIa","vhHdCw4","t1LoyvC","v2zWsvm","v2LUzg93","uxvLDwu","r1fuCvi","CM92AwrLihy","ExbL","BMfTzq","ywnRx2LK","zKP2sgi","D2D0Awu","zxrxB3jRq2G","Bg93","q3vrs2m","yMrjDNu","Afr3z1a","D3m6lY8","t0H0tLK","C2fNzq","Efrurw52","zxjFywnRx20","D3jPDgu","x3bPBMDmB3m","yxv0B21HDgK","CgXLyxnLiha","Ag1uyMS","DhfmA3a","CMLLC0nVDw4","zMPqEuq","BM9Uzv9UB24","wuLQqNq","tw9KDwXL","quzXCMi","EfbiwMO","Au5MquG","Cg9PBNrbBMq","u2TPCcbWyxm","CKTjrxO","Cgf5Bg9Hzfq","BhrPCgXLihq","tunAwhu","BwLUAvbYB2C","Cgf5Bg9Hza","yMvmDwu","DK9xDfO","B3Pqy1G","Be9hy1e","D0TXswK","zgzxyxO","tvL3AMy","AgLNAa","Bg9N","y3vYC29YlNm","AuHJthi","EMrsrMu","Cvjyz1K","zxbWwxu","zffACNC","r0r1rwS","B0f1ENi","x2DLDeLUDgu","se1Rz0G","y291BNq","z0TOrLC","x2nSzwfYugK","BKXPBMu","quXm","zxroC28","t1vRBvm","tgrYtMu","qNjPzgDL","t1bftG","A2v5CW","mZG2mdbUvu5nBw0","rwHUtgC","BNvTyMvY","AwXSihvZzsa","CMvZzxruCMK","y29UDgv4Da","svrPuwm","BwvY","DxjxChy","z1bgC1e","Bevfv1u","x2n1CNnVCKy","tgLZDgvUzxi","sePoCLi","wLrpv0K","BezSDxnO","tKzcshC","q2DUy3u","x2fKzfDZtgK","vKn5DgK","zgrjrcWGzgu","zxjFDhrS","we5Zs1G","rgPmqLm","Cg1ty2m","C2vYDMvYvgK","ufbSEhe","BwLZzq","Aw47y2HHCNm","thLdvvG","ChrSyM8","De5nvMy","zMT0sMS","C25VswK","rMLHDuS","Ew1oBuu","CNznvKu","zhDLrxy","zgHtrwm","AMHss08","Dhj1y3rVCIa","y29UC3rYDwm","rgvKAwnHDgu","DejfBMu","DeLK","CM9YrxzLBNq","C3nHz2vfDMu","C0Xf","ENDnDLK","x3bPBMC","y3vZDg9Tshq","t05dufa","sMTnu1y","zxLcBei","yvnWyNa","CNn6zxy","q09otKvdveK","yxnJCMLWDa","Cwfus0i","zxf1ywXZ","ALneAg4","AgDqCwO","DNviB3i","reTuu00","yxbWBgLJyxq","y3vYCMvUDeu","uLjpuG","rvjst1i","Ahr0Chm6","yu5pswW","AvD4s2m","C2vYDMLJzq","vKTpyM0","ChbL","AgvjAvy","Dg1tsu0","vgLTzw91Da","BMCGzMfPBgu","uNHzzvi","zuHhq1u","u2vXsuq","x3bYB3rVy28","zvbYAwO","uhP5vgy","q29Kzq","x3bPBMDqB24","Cgf5Bg9Hzeu","B3bLCNr5tMe","C2zmt2S","x3bYzwzPEa","Cg1uBwG","ihrYEsbYzwm","EgTwswi","yxDSDxC","BuXKzfi","ihzHBgLKigq","y2fSBa","yNLL","ywDLsgLKzq","ugPLzhG","qxnLreO","AwDHDg9Yt24","zvPxBNK","Bw1Ytgi","CNnVCKzPBgu","tM1Sv3y","D3Dtsuy","vhzyC2e","CMvHzfvjBNq","twPQB00","ruriy2u","z2vtEw5J","Cu9UvuO","EefTuuG","BgX2v1i","z0XJCxm","B0XMq1C","v1jtyLi","BMDLza","ChPgthK","DML5Dgq","B3jpBMXPBMu","wuXjC1K","zxmGCMvHy2G","DeDyDvy","zKfYrLu","zw5HyMXLuw8","Dg9mB3DLCKm","r1zzzgu","vhnwD0y","rwvsvhu","Aw9U","shDQBMm","Cg9PBNrdB24","zMLUza","uvnzBgm","qMzpzgS","uuLUvK0","yMfJA3vWigu","y3vYC29Yx24","y0PMzuC","teXkyKu","qvL0rvO","qwjVCNrfCNi","sKDuthO","uwLLr08","tLfvwxy","B25mAw5L","Bg9Vshe","zKTmt3i","DgHHBIbSB2m","zxjFCw9Z","se1hEuW","zM9Yy2u","CMvXDwLYzwq","rMrHAKq","z2v0u3rVCMe","C0jf","vePRCeq","z25fweS","zLDVEuu","C2TQCxa","tvrZsNG","Dg9cExrLC0i","yNL0zxm","shrnu00","x2jPBMfYEvq","m3W0Fdb8mNW","tNLqwgG","C2XPy2u","ywnR","ExPzrvy","shHjEfG","EgnHwNi","qw5vvhm","rw1hsK8","wvHSC1m","re9uC1q","veD0CNO","CeP4uMK","t01Yrvq","tKzcD0e","D29prhy","A01VCNq","zMLN","z29PBMCGyxC","DgLNENu","tKDPr0m","BgXyt2G","vfvWvfe","B3DjBem","uuzYs1G","igzPzwXKoIa","v2HXEva","DxbNCMfKzw4","wgfQDNa","t0HwwKO","AMvJDfn0B3i","wwPpr2S","x0vysvnu","Aw9Ul2PZB24","r25Xq2q","mty5ntaWmwnztvfprq","B25szwnLAxy","sgPjt3m","rKHly2y","zgv2AwnLx2K","CKzTsMO","z2vqzuK","AgnRzgi","DLPor28","x2TLEvbHDgG","Ec1TC2CTy3u","AgvHzgvYCW","C3vIC3rYAw4","zNjVBujPDhm","AevYCM9Yrxy","CeHVBvi","vwXny1e","AwTKrge","t0Deueu","x2zVCM1HDeu","tentwxG","yKXmyw8","s296tg4","Bg9IywXty28","y29UBMvJDca","tLjLrKm","qLHRvhq","wK9StMO","y29SBM8","Aw5N","AgfZ","y2HnyxHuCMK","B3jLtMfTzxm","qu9mwva","zNjHBwvuExa","yKLnDKO","s0DSC24","vwzXB0W","D2zbzge","EujiwKi","z2TwBLe","CMvHzhDYAxq","CgLUz19VBMm","vK5pCMS","B3Dvthm","AgvHzgvY","nte0mZHAte1yyNG","q0Xpu0LorW","Aw5KzxGGB3u","vxnYA1G","y2uGBM90igK","ywXSq3vYC28","Be5hDgm","r0j0z2G","B25nzxnZywC","CgLUz1rPBwu","BMCGB3iGyw4","vxjZAhK","CMvKDwnL","De1Ntxq","rvDsBfO","ywWGy3vYC28","CKflENe","BeLdBLO","zMLSDgvY","sfPxswy","rM1WB0W","BMvJDa","DcbVzIbYyw4","y29TCgXLDgu","qu9oru4","vKnAENm","icSG","C21er0i","BMvLzf9Hy2S","tuvtu0fhrv8","AwDuugS","BeHHBMrSzxi","C2fnwNO","Bvbqzeq","o2nOyxjZzxq","n3WYFdz8ma","BwvZC2fNzv8","zxzhDLy","yNnnsgC","CMvJB25Uzwm","vg1nwuC","Dw50","BhrZs3q","qKHTvvC","y2f0y2G","quzYB0C","EMzXs3G","uLrhBMi","CMvWBgfJzq","x2nSzwfYvgK","C2zjDMi","qvDfAeu","BgvUz3rO","y1zUCM0","DfnJB2S","vgD5ywK","z2vjBMzVu3K","x29WDgLVBNm","Dg9tDhjPBMC","yLDJuwK","AMnPsLu","B3bLBKrc","BKTKwe4","zNnuBMm","EKDvse8","CwnVzgi","u1rcDKm","C1nitwu","CMvJzxzPzwq","CMTLCKDSB2i","quPRtxe","C3rZtMe","zhHmvvO","A3voq3O","Dhvtq3i","ywDL","x2rItMfTzq","x2LZqNjVD3m","zwvyuMS","BwXXAei","Dxvss0C","CMrrvw0","vfritM4","AfvNqwW","AKDqvgK","mNWW","zMXVB3i","mZa1nZHjzKrhtvC","yxjiBfC","uK10s1q","zxjFCw9Zx2e","sKrIrLm","BfPQtM4","A1nJs2O","yxbWBhK","y29UBMvJDfm","B3nLrxzLBNq","uevcywC","t2fZC0i","B0vzEMG","DK5KCMe","AKT1vvO","y3ruAw1LB3u","x3fVC0rc","ywXSzwqGBxu","Dvr5req","qLLuEuu","Bg9NsurozxC","zfrOreu","ENLsB3y","Aw50zwDLCIa","wKrxA2S","Ehzvu2S","txDetwi","BMv4DcGPigm","rLrmrLa","rxHruK0","AvznB0W","nhWWFdf8m3W","A3bTu04","AxnszwfKEq","ywXty29Wzq","zxrSuxi","svrMAMi","CMPNzxy","Dw5KzwzPBMu","DgLLCKPtt04","BMPUtvC","rKzAv0e","zw5KCg9PBNq","sgvhDeK","EgHMsK4","rgPjqLa","r2v5DuG","y2HnyxHdB3u","uhfczu8","zerhz1e","BwvZC2fNzq","q2rvz1y","igzHAwWSig0","zfDuyM4","DMXzCuK","DeLUDgvYy2u","DxbKyxrLq3u","A1LJywy","yNL0zuXLBMC","txrezva","tg9JAW","yNvMzMvY","B25tDgfYDfi","zMzMzG","swTIEwm","lcbTyxGGCMu","zwvKzwq","AxnbCNjHEq","AxrQBLK","ugjJyuy","qvDHDLy","sKTlsNq","ruTXzMi","AvLTsNe","y2zizvu","zxH0zw5ZAw8","CMfTzq","zgLZywjSzue","Bwv0Ag9K","CgLUz0XVC3m","zeDIqM0","zv9ZDwnJzxm","CMvHC29U","svD5v2C","zuvfDfa","y1P5C2G","C3jkrfi","rNjVBNrPzxi","sLnptLa","rhzWsvu","qwXgDhG","BNruCMLLC0m","CM92AwrLihC","Aw1LCYbPBIa","A09yzey","CwPnue0","zMD3tee","ywrKrxzLBNq","vKTsA2e","CMfNzvn5BMm","CgLUz09Uy2u","ywjVCNq","EwvKvg0","ywnRDxbfBMq","u25QshO","DgvZDa","ywv0AKy","Bwu6ia","vgTeA1m","BxnN","igXHCMDLCIa","v0HID1u","su5YBMW","s1zNruS","DgTHDeS","CMvUDevUzha","B2nRzxq","zfbxzwe","B25LCNjVCG","s2nTtMK","CLzHBhvLCW","wMXsDgK","te5kEMK","q29UzMLN","vKPLzhm","C3rVCMu","wMnIDxK","AvDJyu4","sM12q3O","DLv4v1u","EMTUy2C","BgfIrKG","z3f1y2K","CLvwCLq","wvbMs1m","qvHNvxC","B3nLza","EfLxDMu","DunNELC","vfnjvNy","yw5Hz2vY","x194x21Zz18","tgnMDve","x2n1CNnVCK0","CuTgvva","BxfHtxi","zw1YrKW","AwDAAhu","C2HPzNq","DMrny1e","C3rLBMvYCW","Au9sCLi","ywzSt2q","sg5tC0u","z1nZAxu","C3v5sLm","suLxsvi","wxP3AvK","C29YDa","uenlEhG","uhr3zuG","y3jLyxrLq2W","l3DZl3yY","q291BNq","q0jAqwq","t2jQzwn0","sgj0Eey","DhL1A3C","z1rPBwvVDxq","sxnbueG","u2rMu0O","q2TvzMG","zNjVBNrPzxi","DvrUrNG","D2fZq2XLyw4","Eg1uCeC","u0Lfr1i","CvLSrNm","zxjFBxnNAwq","u3rYyxrLz3K","z3PvBhq","Cg9W","q0Pwzvm","rK1AvgO","C3bSAwnL","CfzouLC","y2XVC2u","DuPSz2e","qKfJu2e","CNjVCK1LC3m","AerHu0q","z2v0s2v5","C2v0y3vYC28","CvnPqw4","zw50tgLZDgu","DuDMu0W","zKDUt0y","y2ruwvO","x29UugfNzu4","DxjS","B3jRig9MzMW","vffxyKu","B2zMC2v0","CfPwyLy","v0jnwMe","x3DZsw5ZDge","CNnVCL92ywW","x2LZtM9Kzq","x3nLBMrby2S","z1z5Aue","EuvvtLe","CgvYC2LZDgu","DhLWzq","x2rLC3rYB3K","y3vYC29Y","BwfUDwfSihi","DMvY","ywrKq291BNq","yw5Nzq","B25TzxnZywC","vgTkr1K","ysbTDxn0igi","ufPxshi","y01dBee","zwnVBM5Ly3q","yxnL","yM9KEq","tvrXwgy","Cgjbs04","yMfSrxzLBNq","DhbLDM0","AxvdrK8","ChDHDhC","BMCGDxjSoIa","x29UrxjYB3i","uKjgwvG","u2nHueW","Aw5L","BwfW","zw5HyMXLvhi","AMjKAei","CNDrCwq","A09mtge","AwXLtMfTzq","CMXNCgC","vuPpuwe","wwHqCM8","y2XVC2uSihC","sgPYuLK","x2rLyNvN","x21PBMLoyxy","sxzyueq","CK1jyvC","wwn4tKi","Bxjyugu","DxH3Be0","DezcrNe","yMrFzgLK","Ewfvs1e","m3W1Fdf8nhW","rw1eyKe","rez5s3q","AgXKD2i","DMvYC2LVBG","zg9Uzq","AfPnswO","Eu5Nu2K","vLnXDKW","ihrPBwvZ","BKTgqLu","Cg93","y2HLy2Tszwe","q0Xpu0ve","z2v0","zxjYtM8","A1v0yLe","rxzLBNq","DhjHBNnHy3q","AKn1DLy","DgLTzw91DcW","wNzlB3e","ywDyDxq","D0PXswi","zfPcvK0","vKHMy0K","qNb4uwu","DMvUDa","CMvZzxrdB3u","BMrWB2LUDca","C0ztvNq","ywnOzwqSihC","EenlAgu","ChrVCG","zfbStLe","uuftEMu","z2v0q3vYCMu","A1vHuM0","BMjiAuu","C2vUDa","DMfdA2e","DuHWANa","EKjhDum","q2fnz2u","rLjptLrjrvi","zxj2AwnL","x2XPC3rLBMu","qxLLyLK","vhPlzLu","zwXpsLy","CMvZzxrfBMq","ruXcC0K","BMDuAw1LCG","ywTor2m","De5Mvvy","wwjcBum","uKnhuKO","Dg9VigXHCMC","svrus3m","EfPKwuS","zfHoseO","r25VANO","Cgu6ia","yxv0BW","AenSB3nLrxy","vwPprfa","uMvJB25Uzwm","ExzrCKW","BMv3vMvYC2K","BgDssxm","ufb1EfC","y1zZAe4","Dhr3Awq","CYbPBNn0yw4","shbfvNm","wgfLqwq","ywnRx2nVzgu","Chz2u0C","x1fVu01HBMe","qMXMCMm","C2v0zgi","Dg9hzw5LCMe","AwrI","AwrmANq","B3v0sw50zxi","zMvACfi","vefTsxO","s3bIy2q","zxHWB3j0CW","tgHnqLu","x29UtwvZC2e","DwPjz28","wMDNBfa","tufQD3u","A2fqEeG","yMfSu2nVCgu","yxrLq291BNq","zw5XDwv1zq","swLcy3m","qNzfCvu","qw1VDw50","zw5oy1m","sw1yA20","zKD3D3O","t3zRyKq","uwvNrK8","DMLjzhy","C3vIyxjYyxK","z2v0q3vYC28","ChDMCKq","s2TVEwm","y3jLyxrLuMu","ugPiDhO","zufJAW","qvjVuhi","wwDvv3q","ywnRtxnNswq","x2HHBMrSzva","rM14r1q","DMLJzuLeig8","r0DLteG","Eg9oEK8","vK5Kwhe","wKX3z1i","v2reDwm","D24GCMvHC28","DhDVCMTdAge","uw9Xt2y","C1vty1a","B0PlBLq","t0D1AwW","yMXVy2TLza","B3vUDa","z1rLCxK","AgfUz2u","AKTVzLO","Au54u1a","yxb3s0e","mdaWmdaWmda","BNrLCG","vwjKz0q","zK52zxm","C3DZqNy","vfrNAwq","t2nWEMi","C3zlBgS","vfvOALG","z0Pjz3y","yMLUyxj5","qKzUzeu","Bhf5DMC","EwDurwS","tMThCKW","Bwzcsgu","Bhjxv3e","x2LUAxq","y3vYDMfSDwu","CNnVCL9Uyw0","CMvWBgfJzui","sw9lBwS","BwvZC2fNztO","s3PUrLu","yM9L","CMHhzeG","D0vPDvG","vLbvBKK","BeDsEKy","yLj1vgi","z29Vvha","q09oveLovuu","BMrLEa","x2LUAxrqCM8","AwXLx25HBwu","q295zwu","B2Xuq0S","Aw5KzxHpzG","CM1TDgq","zfPbzuO","zw5fDMvUDa","B0Hyy0G","Aw5JBhvKzxm","vevwq3O","C3vJy2vZCW","uuDVB3e","ywDLu2HVDW","EvjLy29UBMu","x2nYzwf0zvm","x19LC01Vzhu","rM5qu3e","nJvJu0vvBwe","A2fbs0q","wKj2ANG","Dw5ZAwDUzwq","C0D1D0m","ywnOzwq","q3vZDg9Tq2W","AuLPvxm","AwXK","rLzxyNa","C0LLquq","yMX5D0C","C1jeuLi","C1vyu3C","zuXoAxC","AxnmB25N","C0HzANK","u0ncshy","DgLUzYbZzxi","DNPqALe","zwn0","r1P2r3e","z2u6ia","x2LZtwLUAvC","CwrMwLC","v3j0z0S","Duz2u1e","DKrQv2C","u3jjDuy","BwTAtLq","quzhB3a","AKXJBLi","veTYwhe","otaZnZa0nhvtrungrq","BxnNsuq","v0T6wNm","DMfSDwvZ","z2LkuLy","DLrdC2y","B25dBg9Zzq","s0TzvwS","tKnkswy","A1vKt1y","C3zjB3u","CgjQzeG","BhDjBeK","tw1wrKq","BgvY","rgfYDNC","t3jSzKy","v2vPEgLUsLm","sg5rDgq","x2LUAxrhBg8","Dg9cExrLC0W","B3j3Bva","x25HDMLNyxq","zMLSzw5HBwu","BgLTAxq","rLDt","v3DxuhC","ywXS","zw1LBNq","suzIwLG","tK9mDMK","A1vyELm","Dgv4DfbHEwW","AxHZt24","D2vI","z0DOBMW","ChvZAa","Auffs0S","EwzJEMS","AhHpEvm","yxDxzMy","zw50","y2HHCKnVzgu","CMvJzwL2zwq","tKnhzwe","CM92AwrLigi","qwnmDeW","B3L2Bxa","z2v0sxrLBq","x3DZ","AgjSqva","Cg1TqKK","zgvIDwC","vw5Oyw5KBgu","DNfrA1O","r2nrvuu","Eenls2O","AhPhtey","C2v0u3rVCMe","wvvsCLi","C0XPC3rLBMu","aaaaaaaaaaa","yMLUyxj5vhK","ywnRpwzYB24","v2vIu29JA2u","zNjVBunOyxi","yNvMzMvYzwq","CuHMueO","tfLyvKO","rxnmAg0","BLvdEMO","zw5JB2rLrNi","C0zKqKW","wuHLEuK","z29cv00","zgvSzxrL","vvPLz1m","txvNCMS","Chv0","Ae9bAva","y1HTANm","y2z2rfm","x2DLBMvYyxq","B2XKvMvYC2K","zMzmAw5L","EwvRzK4","qvbHC0S","zMzLCG","y3jLyxrLt2i","wK5mDLK","ywjvzNq","CMDKrgu","zND2zw4","Agzete8","ELLzwNi","CMvHzg9UBhK","C2v0sxrLBq","z0riDuu","Aw5PDcbrB1m","CMvZDwX0","x3nVy2TLDa","yvHUyuC","BML0AwfSAxO","Ef9MCM9UDgK","x3jLywr5q2W","yxGGCMv0CMK","tKDFrvjst1i","sLfKqMu","wMj0zNu","AfnpyNe","EeL3s0u","D0j5u2i","ywX3yxLZ","mtuWwNLXu3Lh","CYbHBhjLywq","y0zQvMq","mdaWma","Buvewe0","zgLZCgf0y2G","C3bSAxq","ig1LC3nHz2u","r1LZvfq","zNjVBuHHC2G","x2rPC2nVBM4","vKPsr1e","CgfNzwHPzgu","tK1rtxu","AxnFywnR","yMjqEwe","vhruB3G","sLruyw4","ihrPBwvVDxq","B3nKAw4","ChLsyLu","C2vUza","EuzAs0u","zNjVBu51Bwi","BMrWB2LUDfq","B0TnDwe","zw5HyMXLqxu","rg1StuC","uKTpsMS","CgfYC2u","DxrkrKq","BvDHDvy","r0HbyKi","r2Lczvy","whPQt28","vuDrBhG","B2fK","veLjBKC","EK15y1u","twHyswi","B2zMBgLUzq","B2nRzxrtDwm","D2LSBfjLy28","y01AtKG","ywzL","B3PoyKO","CNvWExi","C2HcCKK","zM9YrwfJAa","DhLnD0e","x2LZsw5PDa","zMX1C2HfEha","Aw9UvgLTzw8","yw1Lu3bHy2u","suvtx0vsuK8","CgfNzxnOB3C","CMvTB3zLq2G","zxjFAxnFywm","yMzkzKS","B25JBg9Zzq","D1PSB3m","B3bLBIa","B2rrEei","tvnnA2S","EeL0wgO","wLnNB04","z2v0qwXS","shHotwy","B3bLCNr5","yufQyMO","ihrVihjLDhi","B2zM","veT6Bxm","uej2u1y","tg9NsurozxC","BfbqBgy","vMHjvNK","A3vIA3e","EwHMvwi","BNrfBMrWB2K","x3jLy29UBMu","wxHnrxa","qMDpCwK","rNjhsxK","yNnmu1e","B25tDg9Wsw0","CgLgvNy","q3jeweS","x2rPC3bHDgm","v2r6zLm","y2XVC2veqG","B25Uzwn0Aw4","Cw9Z","rxjfBum","q3vZDg9Trxi","DNH6AwS","x2nVBM5Ly3q","quvbvfK","DMvYC2LVBMm","AwvwrKS","DxnStvi","vKTOuem","ywfqt04","vxbKyxrLq28","z3zPAKe","zxjYtxnN","tvfHyuC","AxnrB1nnzxm","id4G","CeXKtvq","y29UBMvJDgK","wNjxzKW","C2rgsNa","EfrNv3q","wMD0twu","v21YEuu","BhHdDgG","ze54B0K","yMr2BxO","ufrWrvq","rvbuyNy","BgLUzq","A1fKENu","Dev2zw50","x2vUzhbVAw4","zfzZAvG","uKXLCNe","DMfSDwu","A2v0ignVBNm","mNWWFdf8m3W","yNDKAem","ntyYmtqXm3L0rNHzuG","rejdBKm","y2XLyxi","C3rYAw5NAwy","C2v0q3vYC28","B1rcwfq","Bwf4uMv0CMK","uef0r2m","DfrRD2i","C0nRteG","Dg9iyxnO","svb4tw8","uNv0rfa","tg9Nsuq","ywr2yw5Jzq","Cxvir2e","v2HgDwi","CKThB1y","ywXSB2nvBNm","BvPov2q","x3jLBw92zvC","qunoueC","CKXAzMi","x3vYBa","B25VCgvU","AgvKtwf4uMu","C2jHDeq","C2nRwuG","AKrKCNi","BKTKAg4","yxrHlcbKyxq","BhbtD0u","zv90Aw1LB3u","Aw5Lza","Eff1vu8","zgvMAw5Luhi","vwPbuvO","ChjVDg9JB2W","thHVALC","uhjPBwfYEuS","rgfqBui","uMjiC1u","Cw9Zx18","AhrNvNi","B25ozxr3B3i","ywLdsM4","uKLIrhy","zNDZxZeUmc4","zxjYB3i","y1jJCeO","EfbOD0i","CffAwMe","yKLXAKC","CMvZB2X2zq","DgHLBG","u0nVCeW","AefJA01LC3m","C0nVDw50zxi","y3vYCMvUDeK","thnqwue","zeTOA0C","ze1owNq","tgHhvvC","BfrPBwvVDxq","z2v0qwXSs2u","vgPewuW","yMTREKW","y29UBMvJDeu","ELPHy2K","rMvtB0m","uMvHzcbWyxm","zgvJB2rLzey","zwrPyxrLBhK","t3zjtMu","uMjmwxu","C3rYAw5N","DvrZu3q","C3rVCcbPBw0","yMDPCei","zwThtgq","wu54CMW","z2vY","wLvutgK","ntvlBuPlsKq","x0rctMfTzq","Avf6DwK","B3jRzxjhBg8","D3nZoI8V","zxjHDg9Y","qvHowK8","BMnVzgLUzW","DxrMofDYAxq","sfDvAuu","BfniEhm","y3jLyxrLt3a","s3zMvhe","ueHkr2m","x21LC3nHz2u","Ae1LC3nHz2u","y3jLyxrLrxi","tMnRtfK","v3bovxy","B2jQzwn0u3q","y29Kzq","x2n1CNnVCK4","DxnLCKLW","CNzHBa","revgDNe","zNLKzLq","yNL0zu9MzNm","y3zbAgK","jMPZy2fSBgi","r1nev0y","x2LUDgvYDMe","AfPZENm","CMvTB3zLrxy","thvqs0W","v3DvD0u","CMfTugfYyw0","q1Dlz2W","AvDqrK8","y3PmqK0","ywrK","BeXSu2C","AujuEhC","yKLsCum","BM93","yuvmu0m","uePRrxO","B3jL","yMLUza","B25SAw5L","DffVy3e","B3DkvhK","q3jZqvO","qvfOD3O","nxWYFdr8mhW","CYbWyxjHBxm","tNfdwMe"];return ma=function(){return t},ma()}var ua;Object[B(1247)+B(1149)](Oe,B(933)+"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 fl(t=Y()){return Y1(t.libEntry)?t.libEntry:tI(new URL("../index.ts",import.meta.url))}async function Rx(t={}){let e=t.paths??Y(),n=t.entryOverride??fl(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=lt(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[ws]:"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,ws,Ea=at(()=>{"use strict";rn();ie();De();nI=q("spawn-daemon"),ws="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 di(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>${di(n)}</key>
21
- <string>${di(i)}</string>`).join(`
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(`
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 ci,bs,Ta,bl,tg=at(()=>{"use strict";ie();ci=q("supervisor.launchd"),bs="ai.coze.bridge",Ta=aA,bl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
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"?>
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>${bs}</string>
31
+ <string>${ms}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${di(t.nodeBin)}</string>
35
- <string>${di(t.entry)}</string>
34
+ <string>${si(t.nodeBin)}</string>
35
+ <string>${si(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>${di(t.logFile)}</string>
45
+ <string>${si(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${di(t.logFile)}</string>${oA(t.env)}
47
+ <string>${si(t.logFile)}</string>${oA(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return sA(t.homeDir,"Library","LaunchAgents",`${bs}.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"),ci.info("plist written",{plistPath:i,activate:n}),!n)return;await Ta("launchctl",["unload","-w",i]).catch(a=>ci.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Ta("launchctl",["load","-w",i]),ci.info("launchd job loaded",{label:bs});let o=process.getuid?.()??0;await Ta("launchctl",["kickstart","-k",`gui/${o}/${bs}`]),ci.info("launchd job kickstarted",{label:bs,uid:o})},async uninstall(t){let e=this.configPath(t);await Ta("launchctl",["unload","-w",e]).catch(n=>ci.warn("launchctl unload failed (ignored)",{err:String(n)})),await nA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),ci.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 ng}from"node:path";function Pa(t,e){return t.isRoot?e:["--user",...e]}function pA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function Da(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 Ca,li,hA,El,rg=at(()=>{"use strict";ie();Ca=q("supervisor.systemd"),li="coze-bridge.service",hA="/etc/systemd/system";El={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
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]
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
- ${pA(t.env)}
62
+ ${xA(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?ng(hA,li):ng(t.homeDir,".config","systemd","user",li)},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"),Ca.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await Da("systemctl",Pa(t,["daemon-reload"])),await Da("systemctl",Pa(t,n?["enable","--now",li]:["enable",li])),Ca.info("systemd unit enabled",{unitName:li,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await Da("systemctl",Pa(t,["disable","--now",li])).catch(n=>Ca.warn("systemctl disable failed (ignored)",{err:String(n)})),await lA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Da("systemctl",Pa(t,["daemon-reload"])).catch(()=>{}),Ca.info("systemd unit removed",{unitPath:e})}}});import{spawn as xA}from"node:child_process";import{join as gA}from"node:path";function ig(t,e){return new Promise((n,i)=>{let o=xA(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 vl,Ra,Sl,sg=at(()=>{"use strict";ie();vl=q("supervisor.taskscheduler"),Ra="CozeBridge",Sl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
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"?>
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,64 +86,65 @@ 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 ig("schtasks",["/Create","/SC","ONLOGON","/TN",Ra,"/TR",n,"/RU",t.userName,"/F"]),vl.info("task scheduler entry created",{task:Ra,logFile:t.logFile})},async uninstall(t){await ig("schtasks",["/Delete","/TN",Ra,"/F"]).catch(e=>vl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),vl.info("task scheduler entry removed",{task:Ra})}}});var og={};Wa(og,{buildContext:()=>EA,getSupervisor:()=>yA,launchdSupervisor:()=>bl,systemdSupervisor:()=>El,taskSchedulerSupervisor:()=>Sl});import{homedir as mA,userInfo as wA}from"node:os";function yA(t=process.platform){switch(t){case"darwin":return bl;case"linux":return El;case"win32":return Sl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function bA(){let t={};for(let e of _A){let n=process.env[e];n&&(t[e]=n)}return t}function EA(){let t=Y();return{nodeBin:process.execPath,entry:fl(t),logFile:t.logFile,homeDir:mA(),userName:wA().username,isRoot:process.getuid?.()===0,env:bA()}}var _A,ag=at(()=>{"use strict";De();Ea();tg();rg();sg();_A=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ie();gn();var eu=q("acp-installer-warmup"),Om=["claude-code","codex"];async function tu(t={}){let e=t.ensure??_r,i=(await Promise.allSettled(Om.map(async o=>{let a=await e(o);eu.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&eu.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))})}Zt();ie();import{readdir as Jm}from"node:fs/promises";import{mkdir as su,readFile as $m,writeFile as ou}from"node:fs/promises";import{join as Xa}from"node:path";var Vm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function br(t,e,n){await su(t,{recursive:!0});let i=Vm[e],o=Xa(t,i);return await ou(o,n??"","utf8"),o}async function Qa(t,e,n){let i=Xa(t,".claude");await su(i,{recursive:!0});let o=Xa(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 ou(o,JSON.stringify(a,null,2),"utf8"),o}var nt=q("agent-detail-sync"),Zm=6e4,Ym=5*6e4,Os=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await Jm(n)}catch(o){nt.info("agents dir not found, skip detail sync",{root:n,err:String(o)});return}nt.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let a=await ke(o,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){nt.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,a)}catch(d){nt.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),nt.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){nt.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(o){nt.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,n){let i=n??await ke(e,this.opts.paths);if(!i){nt.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){nt.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let p=this.retryQueue.get(e),x=p?Math.min(p.currentDelay*2,Ym):Zm;this.retryQueue.set(e,{dueAt:Date.now()+x,currentDelay:x});return}if(o.agentId&&o.agentId!==e){nt.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"?(nt.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):o.deployType&&nt.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){nt.debug("detail sync: no diff",{agentId:e});return}await je(i,this.opts.paths),nt.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}),nt.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await br(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Ad=Vt(zu(),1);import{createHash as H_}from"node:crypto";import{lstat as wd,mkdir as yd,readFile as Co,readdir as R0,rm as _d,stat as Sd,writeFile as bd}from"node:fs/promises";import{homedir as G_}from"node:os";import{basename as C0,dirname as q_,join as ge,normalize as j_,relative as Id,resolve as Ed,sep as O0}from"node:path";import{Readable as L0}from"node:stream";import{pipeline as N0}from"node:stream/promises";import yw from"events";import dt from"fs";import{EventEmitter as Qc}from"node:events";import Ef from"node:stream";import{StringDecoder as _w}from"node:string_decoder";import If from"node:path";import Or from"node:fs";import{dirname as Ow,parse as Lw}from"path";import{EventEmitter as Gw}from"events";import Lc from"assert";import{Buffer as Zn}from"buffer";import*as ju from"zlib";import qw from"zlib";import{posix as Ar}from"node:path";import{basename as my}from"node:path";import fo from"fs";import Ft from"fs";import Xu from"path";import{win32 as Py}from"node:path";import of from"path";import Uf from"node:fs";import $y from"node:assert";import{randomBytes as Hf}from"node:crypto";import de from"node:fs";import Ge from"node:path";import Gf from"fs";import bo from"node:fs";import Fi from"node:path";import ht from"node:fs";import e_ from"node:fs/promises";import xo from"node:path";import{join as Qf}from"node:path";import ft from"node:fs";import n0 from"node:path";var mw=Object.defineProperty,ww=(t,e)=>{for(var n in e)mw(t,n,{get:e[n],enumerable:!0})},Uu=typeof process=="object"&&process?process:{stdout:null,stderr:null},bw=t=>!!t&&typeof t=="object"&&(t instanceof Qn||t instanceof Ef||Ew(t)||vw(t)),Ew=t=>!!t&&typeof t=="object"&&t instanceof Qc&&typeof t.pipe=="function"&&t.pipe!==Ef.Writable.prototype.pipe,vw=t=>!!t&&typeof t=="object"&&t instanceof Qc&&typeof t.write=="function"&&typeof t.end=="function",Yt=Symbol("EOF"),Xt=Symbol("maybeEmitEnd"),_n=Symbol("emittedEnd"),Fs=Symbol("emittingEnd"),_i=Symbol("emittedError"),zs=Symbol("closed"),Hu=Symbol("read"),Us=Symbol("flush"),Gu=Symbol("flushChunk"),At=Symbol("encoding"),Ir=Symbol("decoder"),We=Symbol("flowing"),bi=Symbol("paused"),Pr=Symbol("resume"),Ke=Symbol("buffer"),rt=Symbol("pipes"),$e=Symbol("bufferLength"),sc=Symbol("bufferPush"),Hs=Symbol("bufferShift"),et=Symbol("objectMode"),Re=Symbol("destroyed"),oc=Symbol("error"),ac=Symbol("emitData"),qu=Symbol("emitEnd"),cc=Symbol("emitEnd2"),Lt=Symbol("async"),dc=Symbol("abort"),Gs=Symbol("aborted"),Ei=Symbol("signal"),Hn=Symbol("dataListeners"),ut=Symbol("discarded"),vi=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),vf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Pr](),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 vf{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,Pw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Qn=class extends Qc{[We]=!1;[bi]=!1;[rt]=[];[Ke]=[];[et];[At];[Lt];[Ir];[Yt]=!1;[_n]=!1;[Fs]=!1;[zs]=!1;[_i]=null;[$e]=0;[Re]=!1;[Ei];[Gs]=!1;[Hn]=0;[ut]=!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[et]=!0,this[At]=null):Pw(e)?(this[At]=e.encoding,this[et]=!1):(this[et]=!1,this[At]=null),this[Lt]=!!e.async,this[Ir]=this[At]?new _w(this[At]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Ke]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[rt]});let{signal:n}=e;n&&(this[Ei]=n,n.aborted?this[dc]():n.addEventListener("abort",()=>this[dc]()))}get bufferLength(){return this[$e]}get encoding(){return this[At]}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[et]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Lt]}set async(t){this[Lt]=this[Lt]||!!t}[dc](){this[Gs]=!0,this.emit("abort",this[Ei]?.reason),this.destroy(this[Ei]?.reason)}get aborted(){return this[Gs]}set aborted(t){}write(t,e,n){if(this[Gs])return!1;if(this[Yt])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[Lt]?vi:Sw;if(!this[et]&&!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[et]?(this[We]&&this[$e]!==0&&this[Us](!0),this[We]?this.emit("data",t):this[sc](t),this[$e]!==0&&this.emit("readable"),n&&i(n),this[We]):t.length?(typeof t=="string"&&!(e===this[At]&&!this[Ir]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[At]&&(t=this[Ir].write(t)),this[We]&&this[$e]!==0&&this[Us](!0),this[We]?this.emit("data",t):this[sc](t),this[$e]!==0&&this.emit("readable"),n&&i(n),this[We]):(this[$e]!==0&&this.emit("readable"),n&&i(n),this[We])}read(t){if(this[Re])return null;if(this[ut]=!1,this[$e]===0||t===0||t&&t>this[$e])return this[Xt](),null;this[et]&&(t=null),this[Ke].length>1&&!this[et]&&(this[Ke]=[this[At]?this[Ke].join(""):Buffer.concat(this[Ke],this[$e])]);let e=this[Hu](t||null,this[Ke][0]);return this[Xt](),e}[Hu](t,e){if(this[et])this[Hs]();else{let n=e;t===n.length||t===null?this[Hs]():typeof n=="string"?(this[Ke][0]=n.slice(t),e=n.slice(0,t),this[$e]-=t):(this[Ke][0]=n.subarray(t),e=n.subarray(0,t),this[$e]-=t)}return this.emit("data",e),!this[Ke].length&&!this[Yt]&&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[Yt]=!0,this.writable=!1,(this[We]||!this[bi])&&this[Xt](),this}[Pr](){this[Re]||(!this[Hn]&&!this[rt].length&&(this[ut]=!0),this[bi]=!1,this[We]=!0,this.emit("resume"),this[Ke].length?this[Us]():this[Yt]?this[Xt]():this.emit("drain"))}resume(){return this[Pr]()}pause(){this[We]=!1,this[bi]=!0,this[ut]=!1}get destroyed(){return this[Re]}get flowing(){return this[We]}get paused(){return this[bi]}[sc](t){this[et]?this[$e]+=1:this[$e]+=t.length,this[Ke].push(t)}[Hs](){return this[et]?this[$e]-=1:this[$e]-=this[Ke][0].length,this[Ke].shift()}[Us](t=!1){do;while(this[Gu](this[Hs]())&&this[Ke].length);!t&&!this[Ke].length&&!this[Yt]&&this.emit("drain")}[Gu](t){return this.emit("data",t),this[We]}pipe(t,e){if(this[Re])return t;this[ut]=!1;let n=this[_n];return e=e||{},t===Uu.stdout||t===Uu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[rt].push(e.proxyErrors?new Tw(this,t,e):new vf(this,t,e)),this[Lt]?vi(()=>this[Pr]()):this[Pr]()),t}unpipe(t){let e=this[rt].find(n=>n.dest===t);e&&(this[rt].length===1?(this[We]&&this[Hn]===0&&(this[We]=!1),this[rt]=[]):this[rt].splice(this[rt].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[ut]=!1,this[Hn]++,!this[rt].length&&!this[We]&&this[Pr]();else if(t==="readable"&&this[$e]!==0)super.emit("readable");else if(Iw(t)&&this[_n])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[_i]){let i=e;this[Lt]?vi(()=>i.call(this,this[_i])):i.call(this,this[_i])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Hn]=this.listeners("data").length,this[Hn]===0&&!this[ut]&&!this[rt].length&&(this[We]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Hn]=0,!this[ut]&&!this[rt].length&&(this[We]=!1)),e}get emittedEnd(){return this[_n]}[Xt](){!this[Fs]&&!this[_n]&&!this[Re]&&this[Ke].length===0&&this[Yt]&&(this[Fs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[zs]&&this.emit("close"),this[Fs]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Re&&this[Re])return!1;if(t==="data")return!this[et]&&!n?!1:this[Lt]?(vi(()=>this[ac](n)),!0):this[ac](n);if(t==="end")return this[qu]();if(t==="close"){if(this[zs]=!0,!this[_n]&&!this[Re])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[_i]=n,super.emit(oc,n);let o=!this[Ei]||this.listeners("error").length?super.emit("error",n):!1;return this[Xt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Xt](),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[Xt](),i}[ac](t){for(let n of this[rt])n.dest.write(t)===!1&&this.pause();let e=this[ut]?!1:super.emit("data",t);return this[Xt](),e}[qu](){return this[_n]?!1:(this[_n]=!0,this.readable=!1,this[Lt]?(vi(()=>this[cc]()),!0):this[cc]())}[cc](){if(this[Ir]){let e=this[Ir].end();if(e){for(let n of this[rt])n.dest.write(e);this[ut]||super.emit("data",e)}}for(let e of this[rt])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[et]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[et]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[et])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[At]?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[ut]=!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[Yt])return e();let i,o,a=p=>{this.off("data",d),this.off("end",u),this.off(Re,f),e(),o(p)},d=p=>{this.off("error",a),this.off("end",u),this.off(Re,f),this.pause(),i({value:p,done:!!this[Yt]})},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((p,x)=>{o=x,i=p,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[ut]=!1;let t=!1,e=()=>(this.pause(),this.off(oc,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(oc,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[ut]=!0,this[Ke].length=0,this[$e]=0;let e=this;return typeof e.close=="function"&&!this[zs]&&e.close(),t?this.emit("error",t):this.emit(Re),this}static get isStream(){return bw}},Dw=dt.writev,Cn=Symbol("_autoClose"),Pt=Symbol("_close"),Si=Symbol("_ended"),xe=Symbol("_fd"),lc=Symbol("_finished"),nn=Symbol("_flags"),uc=Symbol("_flush"),Rc=Symbol("_handleChunk"),Oc=Symbol("_makeBuf"),Mi=Symbol("_mode"),qs=Symbol("_needDrain"),Nr=Symbol("_onerror"),Mr=Symbol("_onopen"),fc=Symbol("_onread"),Dr=Symbol("_onwrite"),Pn=Symbol("_open"),Ct=Symbol("_path"),Sn=Symbol("_pos"),Nt=Symbol("_queue"),Rr=Symbol("_read"),hc=Symbol("_readSize"),tn=Symbol("_reading"),Ii=Symbol("_remain"),pc=Symbol("_size"),Qs=Symbol("_write"),Gn=Symbol("_writing"),eo=Symbol("_defaultFlag"),Jn=Symbol("_errored"),ed=class extends Qn{[Jn]=!1;[xe];[Ct];[hc];[tn]=!1;[pc];[Ii];[Cn];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[Jn]=!1,this[xe]=typeof e.fd=="number"?e.fd:void 0,this[Ct]=t,this[hc]=e.readSize||16*1024*1024,this[tn]=!1,this[pc]=typeof e.size=="number"?e.size:1/0,this[Ii]=this[pc],this[Cn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[xe]=="number"?this[Rr]():this[Pn]()}get fd(){return this[xe]}get path(){return this[Ct]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Pn](){dt.open(this[Ct],"r",(t,e)=>this[Mr](t,e))}[Mr](t,e){t?this[Nr](t):(this[xe]=e,this.emit("open",e),this[Rr]())}[Oc](){return Buffer.allocUnsafe(Math.min(this[hc],this[Ii]))}[Rr](){if(!this[tn]){this[tn]=!0;let t=this[Oc]();if(t.length===0)return process.nextTick(()=>this[fc](null,0,t));dt.read(this[xe],t,0,t.length,null,(e,n,i)=>this[fc](e,n,i))}}[fc](t,e,n){this[tn]=!1,t?this[Nr](t):this[Rc](e,n)&&this[Rr]()}[Pt](){if(this[Cn]&&typeof this[xe]=="number"){let t=this[xe];this[xe]=void 0,dt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Nr](t){this[tn]=!0,this[Pt](),this.emit("error",t)}[Rc](t,e){let n=!1;return this[Ii]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Ii]<=0)&&(n=!1,this[Pt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[xe]=="number"&&this[Rr](),!1;case"error":return this[Jn]?!1:(this[Jn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Rw=class extends ed{[Pn](){let t=!0;try{this[Mr](null,dt.openSync(this[Ct],"r")),t=!1}finally{t&&this[Pt]()}}[Rr](){let t=!0;try{if(!this[tn]){this[tn]=!0;do{let e=this[Oc](),n=e.length===0?0:dt.readSync(this[xe],e,0,e.length,null);if(!this[Rc](n,e))break}while(!0);this[tn]=!1}t=!1}finally{t&&this[Pt]()}}[Pt](){if(this[Cn]&&typeof this[xe]=="number"){let t=this[xe];this[xe]=void 0,dt.closeSync(t),this.emit("close")}}},go=class extends yw{readable=!1;writable=!0;[Jn]=!1;[Gn]=!1;[Si]=!1;[Nt]=[];[qs]=!1;[Ct];[Mi];[Cn];[xe];[eo];[nn];[lc]=!1;[Sn];constructor(t,e){e=e||{},super(e),this[Ct]=t,this[xe]=typeof e.fd=="number"?e.fd:void 0,this[Mi]=e.mode===void 0?438:e.mode,this[Sn]=typeof e.start=="number"?e.start:void 0,this[Cn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Sn]!==void 0?"r+":"w";this[eo]=e.flags===void 0,this[nn]=e.flags===void 0?n:e.flags,this[xe]===void 0&&this[Pn]()}emit(t,...e){if(t==="error"){if(this[Jn])return!1;this[Jn]=!0}return super.emit(t,...e)}get fd(){return this[xe]}get path(){return this[Ct]}[Nr](t){this[Pt](),this[Gn]=!0,this.emit("error",t)}[Pn](){dt.open(this[Ct],this[nn],this[Mi],(t,e)=>this[Mr](t,e))}[Mr](t,e){this[eo]&&this[nn]==="r+"&&t&&t.code==="ENOENT"?(this[nn]="w",this[Pn]()):t?this[Nr](t):(this[xe]=e,this.emit("open",e),this[Gn]||this[uc]())}end(t,e){return t&&this.write(t,e),this[Si]=!0,!this[Gn]&&!this[Nt].length&&typeof this[xe]=="number"&&this[Dr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Si]?(this.emit("error",new Error("write() after end()")),!1):this[xe]===void 0||this[Gn]||this[Nt].length?(this[Nt].push(t),this[qs]=!0,!1):(this[Gn]=!0,this[Qs](t),!0)}[Qs](t){dt.write(this[xe],t,0,t.length,this[Sn],(e,n)=>this[Dr](e,n))}[Dr](t,e){t?this[Nr](t):(this[Sn]!==void 0&&typeof e=="number"&&(this[Sn]+=e),this[Nt].length?this[uc]():(this[Gn]=!1,this[Si]&&!this[lc]?(this[lc]=!0,this[Pt](),this.emit("finish")):this[qs]&&(this[qs]=!1,this.emit("drain"))))}[uc](){if(this[Nt].length===0)this[Si]&&this[Dr](null,0);else if(this[Nt].length===1)this[Qs](this[Nt].pop());else{let t=this[Nt];this[Nt]=[],Dw(this[xe],t,this[Sn],(e,n)=>this[Dr](e,n))}}[Pt](){if(this[Cn]&&typeof this[xe]=="number"){let t=this[xe];this[xe]=void 0,dt.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Sf=class extends go{[Pn](){let t;if(this[eo]&&this[nn]==="r+")try{t=dt.openSync(this[Ct],this[nn],this[Mi])}catch(e){if(e?.code==="ENOENT")return this[nn]="w",this[Pn]();throw e}else t=dt.openSync(this[Ct],this[nn],this[Mi]);this[Mr](null,t)}[Pt](){if(this[Cn]&&typeof this[xe]=="number"){let t=this[xe];this[xe]=void 0,dt.closeSync(t),this.emit("close")}}[Qs](t){let e=!0;try{this[Dr](null,dt.writeSync(this[xe],t,0,t.length,this[Sn])),e=!1}finally{if(e)try{this[Pt]()}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,td=(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},Wi=(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=td(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 p=e(f,d);return u?p.then(()=>u(),u):p}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},Ut=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=Zn.concat,Wu=Object.getOwnPropertyDescriptor(Zn,"concat"),Kw=t=>t,xc=Wu?.writable===!0||Wu?.set!==void 0?t=>{Zn.concat=t?Kw:Ww}:t=>{},Yn=Symbol("_superWrite"),js=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"}},gc=Symbol("flushFlag"),nd=class extends Qn{#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 ju[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new ju[e](t)}catch(n){throw new js(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 js(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Lc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Zn.alloc(0),{[gc]: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}[Yn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Zn.from(t,e)),this.#e)return;Lc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},xc(!0);let d;try{let f=typeof t[gc]=="number"?t[gc]:this.#r;d=this.#t._processChunk(t,f),xc(!1)}catch(f){xc(!1),this.#o(new js(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 js(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[Yn](Zn.from(f));for(let p=1;p<d.length;p++)u=this[Yn](d[p])}else u=this[Yn](Zn.from(d));return n&&n(),u}},Af=class extends nd{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Ut.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ut.Z_FINISH,t.fullFlushFlag=Ut.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(Ut.Z_SYNC_FLUSH),Lc(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 Af{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Yn](t){return this.#e?(this.#e=!1,t[9]=255,super[Yn](t)):super[Yn](t)}},Vw=class extends Af{constructor(t){super(t,"Unzip")}},kf=class extends nd{constructor(t,e){t=t||{},t.flush=t.flush||Ut.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ut.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ut.BROTLI_OPERATION_FLUSH,super(t,e)}},Jw=class extends kf{constructor(t){super(t,"BrotliCompress")}},Zw=class extends kf{constructor(t){super(t,"BrotliDecompress")}},Tf=class extends nd{constructor(t,e){t=t||{},t.flush=t.flush||Ut.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ut.ZSTD_e_end,t.fullFlushFlag=Ut.ZSTD_e_flush,super(t,e)}},Yw=class extends Tf{constructor(t){super(t,"ZstdCompress")}},Xw=class extends Tf{constructor(t){super(t,"ZstdDecompress")}},Qw=(t,e)=>{if(Number.isSafeInteger(t))t<0?ty(t,e):ey(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},ey=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},ty=(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]=Cf(o):o===0?e[i-1]=0:(n=!0,e[i-1]=Pf(o))}},ny=t=>{let e=t[0],n=e===128?iy(t.subarray(1,t.length)):e===255?ry(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},ry=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=Cf(a):a===0?d=a:(i=!0,d=Pf(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},iy=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},Cf=t=>(255^t)&255,Pf=t=>(255^t)+1&255,sy={};ww(sy,{code:()=>rd,isCode:()=>to,isName:()=>oy,name:()=>mo,normalFsTypes:()=>Df});var to=t=>mo.has(t),oy=t=>rd.has(t),Df=new Set(["0","","1","2","3","4","5","6","7","D"]),mo=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"]]),rd=new Map(Array.from(mo).map(t=>[t[1],t[0]])),ay=t=>t===void 0||t<0?void 0:t,Xn=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=qn(t,e+156,1),a=Df.has(o),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??qn(t,e,100),this.mode=d?.mode??u?.mode??In(t,e+100,8),this.uid=d?.uid??u?.uid??In(t,e+108,8),this.gid=d?.gid??u?.gid??In(t,e+116,8),this.size=ay(d?.size??u?.size??In(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??mc(t,e+136,12),this.cksum=In(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),to(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=qn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??qn(t,e+265,32),this.gname=d?.gname??u?.gname??qn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??In(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??In(t,e+337,8)??0,t[e+475]!==0){let p=qn(t,e+345,155);this.path=p+"/"+this.path}else{let p=qn(t,e+345,130);p&&(this.path=p+"/"+this.path),this.atime=n?.atime??i?.atime??mc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??mc(t,e+488,12)}let f=256;for(let p=e;p<e+148;p++)f+=t[p];for(let p=e+156;p<e+512;p++)f+=t[p];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=cy(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=jn(t,e,100,o)||this.needPax,this.needPax=An(t,e+100,8,this.mode)||this.needPax,this.needPax=An(t,e+108,8,this.uid)||this.needPax,this.needPax=An(t,e+116,8,this.gid)||this.needPax,this.needPax=An(t,e+124,12,this.size)||this.needPax,this.needPax=wc(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=jn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=jn(t,e+265,32,this.uname)||this.needPax,this.needPax=jn(t,e+297,32,this.gname)||this.needPax,this.needPax=An(t,e+329,8,this.devmaj)||this.needPax,this.needPax=An(t,e+337,8,this.devmin)||this.needPax,this.needPax=jn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=jn(t,e+345,155,a)||this.needPax:(this.needPax=jn(t,e+345,130,a)||this.needPax,this.needPax=wc(t,e+476,12,this.atime)||this.needPax,this.needPax=wc(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,An(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:mo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(rd.get(t));if(to(e)||e==="Unsupported")this.#e=e;else if(to(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},cy=(t,e)=>{let n=t,i="",o,a=Ar.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Ar.dirname(n),n=Ar.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=Ar.join(Ar.basename(i),n),i=Ar.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},qn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),mc=(t,e,n)=>dy(In(t,e,n)),dy=t=>t===void 0?void 0:new Date(t*1e3),In=(t,e,n)=>Number(t[e])&128?ny(t.subarray(e,e+n)):uy(t,e,n),ly=t=>isNaN(t)?void 0:t,uy=(t,e,n)=>ly(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),fy={12:8589934591,8:2097151},An=(t,e,n,i)=>i===void 0?!1:i>fy[n]||i<0?(Qw(i,t.subarray(e,e+n)),!0):(hy(t,e,n,i),!1),hy=(t,e,n,i)=>t.write(py(i,n),e,n,"ascii"),py=(t,e)=>xy(Math.floor(t).toString(8),e),xy=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",wc=(t,e,n,i)=>i===void 0?!1:An(t,e,n,i.getTime()/1e3),gy=new Array(156).join("\0"),jn=(t,e,n,i)=>i===void 0?!1:(t.write(i+gy,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),uo=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 Xn({path:("PaxHeader/"+my(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(wy(yy(e),n),i)}},wy=(t,e)=>e?Object.assign({},e,t):t,yy=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},by=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ne=by!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),Ey=class extends Qn{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=ne(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?ne(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=ne(t.path)),t.linkpath&&(t.linkpath=ne(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},wo=(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,Nc=Buffer.from([31,139]),Mc=Buffer.from([40,181,47,253]),Sy=Math.max(Nc.length,Mc.length),wt=Symbol("state"),Wn=Symbol("writeEntry"),Qt=Symbol("readEntry"),yc=Symbol("nextEntry"),Ku=Symbol("processEntry"),Mt=Symbol("extendedHeader"),Ai=Symbol("globalExtendedHeader"),bn=Symbol("meta"),$u=Symbol("emitMeta"),be=Symbol("buffer"),en=Symbol("queue"),En=Symbol("ended"),_c=Symbol("emittedEnd"),Kn=Symbol("emit"),Pe=Symbol("unzip"),Ws=Symbol("consumeChunk"),Ks=Symbol("consumeChunkSub"),bc=Symbol("consumeBody"),Vu=Symbol("consumeMeta"),Ju=Symbol("consumeHeader"),ki=Symbol("consuming"),Ec=Symbol("bufferConcat"),$s=Symbol("maybeEnd"),kr=Symbol("writing"),Bt=Symbol("aborted"),Vs=Symbol("onDone"),$n=Symbol("sawValidEntry"),Js=Symbol("sawNullBlock"),Zs=Symbol("sawEOF"),Zu=Symbol("closeStream"),Iy=1e3,Ti=Symbol("compressedBytesRead"),vc=Symbol("decompressedBytesRead"),Yu=Symbol("checkDecompressionRatio"),Ay=()=>!0,ji=class extends Gw{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[en]=[];[be];[Qt];[Wn];[wt]="begin";[bn]="";[Mt];[Ai];[En]=!1;[Pe];[Bt]=!1;[$n];[Js]=!1;[Zs]=!1;[kr]=!1;[ki]=!1;[_c]=!1;[Ti]=0;[vc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Vs,()=>{(this[wt]==="begin"||this[$n]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Vs,t.ondone):this.on(Vs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Iy,this.maxMetaEntrySize=t.maxMetaEntrySize||vy,this.filter=typeof t.filter=="function"?t.filter:Ay;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[Zu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){wo(this,t,e,n)}[Ju](t,e){this[$n]===void 0&&(this[$n]=!1);let n;try{n=new Xn(t,e,this[Mt],this[Ai])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Js]?(this[Zs]=!0,this[wt]==="begin"&&(this[wt]="header"),this[Kn]("eof")):(this[Js]=!0,this[Kn]("nullBlock"));else if(this[Js]=!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[Wn]=new Ey(n,this[Mt],this[Ai]);if(!this[$n])if(o.remain){let a=()=>{o.invalid||(this[$n]=!0)};o.on("end",a)}else this[$n]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Kn]("ignoredEntry",o),this[wt]="ignore",o.resume()):o.size>0&&(this[bn]="",o.on("data",a=>this[bn]+=a),this[wt]="meta"):(this[Mt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Kn]("ignoredEntry",o),this[wt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[wt]="body":(this[wt]="header",o.end()),this[Qt]?this[en].push(o):(this[en].push(o),this[yc]())))}}}[Zu](){queueMicrotask(()=>this.emit("close"))}[Ku](t){let e=!0;if(!t)this[Qt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[Qt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[yc]()),e=!1);return e}[yc](){do;while(this[Ku](this[en].shift()));if(this[en].length===0){let t=this[Qt];!t||t.flowing||t.size===t.remain?this[kr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[bc](t,e){let n=this[Wn];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[wt]="header",this[Wn]=void 0,n.end()),o.length}[Vu](t,e){let n=this[Wn],i=this[bc](t,e);return!this[Wn]&&n&&this[$u](n),i}[Kn](t,e,n){this[en].length===0&&!this[Qt]?this.emit(t,e,n):this[en].push([t,e,n])}[$u](t){switch(this[Kn]("meta",this[bn]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Mt]=uo.parse(this[bn],this[Mt],!1);break;case"GlobalExtendedHeader":this[Ai]=uo.parse(this[bn],this[Ai],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Mt]??Object.create(null);this[Mt]=e,e.path=this[bn].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Mt]||Object.create(null);this[Mt]=e,e.linkpath=this[bn].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Bt]){if(this[Pe]){let e=this[Pe];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Bt]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[Yu](t){this[vc]+=t.length;let e=this[vc]/this[Ti];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[Bt])return n?.(),!1;if((this[Pe]===void 0||this.brotli===void 0&&this[Pe]===!1)&&t){if(this[be]&&(t=Buffer.concat([this[be],t]),this[be]=void 0),t.length<Sy)return this[be]=t,n?.(),!0;for(let d=0;this[Pe]===void 0&&d<Nc.length;d++)t[d]!==Nc[d]&&(this[Pe]=!1);let o=!1;if(this[Pe]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Mc.length;d++)if(t[d]!==Mc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Pe]===!1&&a)if(t.length<512)if(this[En])this.brotli=!0;else return this[be]=t,n?.(),!0;else try{new Xn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Pe]===void 0||this[Pe]===!1&&(this.brotli||o)){let d=this[En];this[En]=!1,this[Pe]=this[Pe]===void 0?new Vw({}):o?new Xw({}):new Zw({}),this[Pe].on("data",f=>{this[Yu](f)&&this[Ws](f)}),this[Pe].on("error",f=>{this[Bt]||this.abort(f)}),this[Pe].on("end",()=>{this[En]=!0,this[Ws]()}),this[kr]=!0,this[Ti]+=t.length;let u=!!this[Pe][d?"end":"write"](t);return this[kr]=!1,n?.(),u}}this[kr]=!0,this[Pe]?(this[Ti]+=t.length,this[Pe].write(t)):this[Ws](t),this[kr]=!1;let i=this[en].length>0?!1:this[Qt]?this[Qt].flowing:!0;return!i&&this[en].length===0&&this[Qt]?.once("drain",()=>this.emit("drain")),n?.(),i}[Ec](t){t&&!this[Bt]&&(this[be]=this[be]?Buffer.concat([this[be],t]):t)}[$s](){if(this[En]&&!this[_c]&&!this[Bt]&&!this[ki]){this[_c]=!0;let t=this[Wn];if(t?.blockRemain){let e=this[be]?this[be].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[be]&&t.write(this[be]),t.end()}this[Kn](Vs)}}[Ws](t){if(this[ki]&&t)this[Ec](t);else if(!t&&!this[be])this[$s]();else if(t){if(this[ki]=!0,this[be]){this[Ec](t);let e=this[be];this[be]=void 0,this[Ks](e)}else this[Ks](t);for(;this[be]&&this[be]?.length>=512&&!this[Bt]&&!this[Zs];){let e=this[be];this[be]=void 0,this[Ks](e)}this[ki]=!1}(!this[be]||this[En])&&this[$s]()}[Ks](t){let e=0,n=t.length;for(;e+512<=n&&!this[Bt]&&!this[Zs];)switch(this[wt]){case"begin":case"header":this[Ju](t,e),e+=512;break;case"ignore":case"body":e+=this[bc](t,e);break;case"meta":e+=this[Vu](t,e);break;default:throw new Error("invalid state: "+this[wt])}e<n&&(this[be]=this[be]?Buffer.concat([t.subarray(e),this[be]]):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[Bt]||(this[Pe]?(t&&(this[Ti]+=t.length,this[Pe].write(t)),this[Pe].end()):(this[En]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[$s]())),this}},Bi=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)},ky=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Of=(t,e)=>{let n=new Map(e.map(d=>[Bi(d),!0])),i=t.filter,o=100,a=(d,u="",f=0)=>{if(f>=o)return n.set(d,!1),!1;let p=u||Lw(d).root||".",x;if(d===p)x=!1;else{let g=n.get(d);x=g!==void 0?g:a(Ow(d),p,f+1)}return n.set(d,x),x};t.filter=i?(d,u)=>i(d,u)&&a(Bi(d)):d=>a(Bi(d))},Ty=t=>{let e=new ji(t),n=t.file,i;try{i=Or.openSync(n,"r");let o=Or.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),u=Or.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=Or.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{Or.closeSync(i)}catch{}}},Cy=(t,e)=>{let n=new ji(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Or.stat(o,(u,f)=>{if(u)d(u);else{let p=new ed(o,{readSize:i,size:f.size});p.on("error",d),p.pipe(n)}})})},Br=Wi(Ty,Cy,t=>new ji(t),t=>new ji(t),(t,e)=>{e?.length&&Of(t,e),t.noResume||ky(t)}),Lf=(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:Dy,parse:Qu}=Py,id=t=>{let e="",n=Qu(t);for(;Dy(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=Qu(t)}return[e,t]},yo=["|","<",">","?",":"],sd=yo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Ry=new Map(yo.map((t,e)=>[t,sd[e]])),Oy=new Map(sd.map((t,e)=>[t,yo[e]])),ef=t=>yo.reduce((e,n)=>e.split(n).join(Ry.get(n)),t),Ly=t=>sd.reduce((e,n)=>e.split(n).join(Oy.get(n)),t),Nf=(t,e)=>e?(t=ne(t).replace(/^\.(\/|$)/,""),Bi(e)+"/"+t):ne(t),Ny=16*1024*1024,tf=Symbol("process"),nf=Symbol("file"),rf=Symbol("directory"),Bc=Symbol("symlink"),sf=Symbol("hardlink"),Ci=Symbol("header"),no=Symbol("read"),Fc=Symbol("lstat"),ro=Symbol("onlstat"),zc=Symbol("onread"),Uc=Symbol("onreadlink"),Hc=Symbol("openfile"),Gc=Symbol("onopenfile"),kn=Symbol("close"),ho=Symbol("mode"),qc=Symbol("awaitDrain"),Sc=Symbol("ondrain"),zt=Symbol("prefix"),Mf=class extends Qn{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=td(e);super(),this.path=ne(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||Ny,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=ne(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?ne(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]=id(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=Ly(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=ne(n.absolute||Xu.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[ro](o):this[Fc]()}warn(t,e,n={}){return wo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Fc](){Ft.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ro](e)})}[ro](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Fy(t),this.emit("stat",t),this[tf]()}[tf](){switch(this.type){case"File":return this[nf]();case"Directory":return this[rf]();case"SymbolicLink":return this[Bc]();default:return this.end()}}[ho](t){return Lf(t,this.type==="Directory",this.portable)}[zt](t){return Nf(t,this.prefix)}[Ci](){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 Xn({path:this[zt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[zt](this.linkpath):this.linkpath,mode:this[ho](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 uo({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[zt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[zt](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)}[rf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ci](),this.end()}[Bc](){Ft.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Uc](e)})}[Uc](t){this.linkpath=ne(t),this[Ci](),this.end()}[sf](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=ne(Xu.relative(this.cwd,t)),this.stat.size=0,this[Ci](),this.end()}[nf](){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[sf](e);this.linkCache.set(t,this.absolute)}if(this[Ci](),this.stat.size===0)return this.end();this[Hc]()}[Hc](){Ft.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Gc](e)})}[Gc](t){if(this.fd=t,this.#e)return this[kn]();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[no]()}[no](){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");Ft.read(t,e,n,i,o,(a,d)=>{if(a)return this[kn](()=>this.emit("error",a));this[zc](d)})}[kn](t=()=>{}){this.fd!==void 0&&Ft.close(this.fd,t)}[zc](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[kn](()=>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[kn](()=>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[Sc]():this[qc](()=>this[Sc]())}[qc](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)}[Sc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[kn](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[no]()}},My=class extends Mf{sync=!0;[Fc](){this[ro](Ft.lstatSync(this.absolute))}[Bc](){this[Uc](Ft.readlinkSync(this.absolute))}[Hc](){this[Gc](Ft.openSync(this.absolute,"r"))}[no](){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=Ft.readSync(e,n,i,o,a);this[zc](d),t=!1}finally{if(t)try{this[kn](()=>{})}catch{}}}[qc](t){t()}[kn](t=()=>{}){this.fd!==void 0&&Ft.closeSync(this.fd),t()}},By=class extends Qn{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 wo(this,t,e,n)}constructor(t,e={}){let n=td(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=ne(t.path),this.mode=t.mode!==void 0?this[ho](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?ne(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=id(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 Xn({path:this[zt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[zt](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 uo({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[zt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[zt](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)}[zt](t){return Nf(t,this.prefix)}[ho](t){return Lf(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}},Fy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",zy=class Lr{tail;head;length=0;static create(e=[]){return new Lr(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++)Hy(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)Gy(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 Lr;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 Lr;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 Lr;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 Lr;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=Uy(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 Uy(t,e,n){let i=e,o=e?e.next:t.head,a=new od(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function Hy(t,e){t.tail=new od(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Gy(t,e){t.head=new od(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var od=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}},af=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},cf=Buffer.alloc(1024),io=Symbol("onStat"),Pi=Symbol("ended"),kt=Symbol("queue"),Di=Symbol("pendingLinks"),vn=Symbol("current"),Vn=Symbol("process"),Ri=Symbol("processing"),Ys=Symbol("processJob"),Tt=Symbol("jobs"),Ic=Symbol("jobDone"),so=Symbol("addFSEntry"),df=Symbol("addTarEntry"),jc=Symbol("stat"),Wc=Symbol("readdir"),oo=Symbol("onreaddir"),ao=Symbol("pipe"),lf=Symbol("entry"),Ac=Symbol("entryOpt"),co=Symbol("writeEntryClass"),Bf=Symbol("write"),kc=Symbol("ondrain"),_o=class extends Qn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[co];onWriteEntry;[kt];[Di]=new Map;[Tt]=0;[Ri]=!1;[Pi]=!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=ne(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[co]=Mf,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 Jw(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[kc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[kc]);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[kt]=new zy,this[Tt]=0,this.jobs=Number(t.jobs)||4,this[Ri]=!1,this[Pi]=!1}[Bf](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[Pi]=!0,this[Vn](),n&&n(),this}write(t){if(this[Pi])throw new Error("write after end");return typeof t=="string"?this[so](t):this[df](t),this.flowing}[df](t){let e=ne(of.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new af(t.path,e);n.entry=new By(t,this[Ac](n)),n.entry.on("end",()=>this[Ic](n)),this[Tt]+=1,this[kt].push(n)}this[Vn]()}[so](t){let e=ne(of.resolve(this.cwd,t));this[kt].push(new af(t,e)),this[Vn]()}[jc](t){t.pending=!0,this[Tt]+=1;let e=this.follow?"stat":"lstat";fo[e](t.absolute,(n,i)=>{t.pending=!1,this[Tt]-=1,n?this.emit("error",n):this[io](t,i)})}[io](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[vn])this[Ys](t);else{let n=`${e.dev}:${e.ino}`,i=this[Di].get(n);i?i.push(t):this[Di].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Vn]()}[Wc](t){t.pending=!0,this[Tt]+=1,fo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Tt]-=1,e)return this.emit("error",e);this[oo](t,n)})}[oo](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Vn]()}[Vn](){if(!this[Ri]){this[Ri]=!0;for(let t=this[kt].head;t&&this[Tt]<this.jobs;t=t.next)if(this[Ys](t.value),t.value.ignore){let e=t.next;this[kt].removeNode(t),t.next=e}this[Ri]=!1,this[Pi]&&this[kt].length===0&&this[Tt]===0&&(this.zip?this.zip.end(cf):(super.write(cf),super.end()))}}get[vn](){return this[kt]&&this[kt].head&&this[kt].head.value}[Ic](t){this[kt].shift(),this[Tt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Di].get(n);if(i){this[Di].delete(n);for(let o of i)o.pending=!1,this[Ys](o)}}this[Vn]()}[Ys](t){if(t.pending&&t.pendingLink&&t===this[vn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[vn]&&!t.piped&&this[ao](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[io](t,e):this[jc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[oo](t,e):this[Wc](t),!t.readdir)return}if(t.entry=this[lf](t),!t.entry){t.ignore=!0;return}t===this[vn]&&!t.piped&&this[ao](t)}}}[Ac](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}}[lf](t){this[Tt]+=1;try{return new this[co](t.path,this[Ac](t)).on("end",()=>this[Ic](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[kc](){this[vn]&&this[vn].entry&&this[vn].entry.resume()}[ao](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[so](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={}){wo(this,t,e,n)}},ad=class extends _o{sync=!0;constructor(t){super(t),this[co]=My}pause(){}resume(){}[jc](t){let e=this.follow?"statSync":"lstatSync";this[io](t,fo[e](t.absolute))}[Wc](t){this[oo](t,fo.readdirSync(t.absolute))}[ao](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[so](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Bf](i)})}},qy=(t,e)=>{let n=new ad(t),i=new Sf(t.file,{mode:t.mode||438});n.pipe(i),Ff(n,e)},jy=(t,e)=>{let n=new _o(t),i=new go(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 zf(n,e).catch(a=>n.emit("error",a)),o},Ff=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Br({file:If.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},zf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Br({file:If.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},Wy=(t,e)=>{let n=new ad(t);return Ff(n,e),n},Ky=(t,e)=>{let n=new _o(t);return zf(n,e).catch(i=>n.emit("error",i)),n},iT=Wi(qy,jy,Wy,Ky,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),Vy=process.env.__FAKE_PLATFORM__||process.platform,qf=Vy==="win32",{O_CREAT:jf,O_NOFOLLOW:uf,O_TRUNC:Wf,O_WRONLY:Kf}=Gf.constants,$f=Number(process.env.__FAKE_FS_O_FILENAME__)||Gf.constants.UV_FS_O_FILEMAP||0,Jy=qf&&!!$f,Zy=512*1024,Yy=$f|Wf|jf|Kf,ff=!qf&&typeof uf=="number"?uf|Wf|jf|Kf:null,Vf=ff!==null?()=>ff:Jy?t=>t<Zy?Yy:"w":()=>"w",Kc=(t,e,n)=>{try{return bo.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},po=(t,e,n,i)=>{bo.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},Xy=(t,e,n,i,o)=>{if(e.isDirectory())Jf(Fi.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=Fi.resolve(t,e.name);po(d,n,i,o)});else{let a=Fi.resolve(t,e.name);po(a,n,i,o)}},Jf=(t,e,n,i)=>{bo.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 po(t,e,n,i);let d=a.length,u=null,f=p=>{if(!u){if(p)return i(u=p);if(--d===0)return po(t,e,n,i)}};for(let p of a)Xy(t,p,e,n,f)})},Qy=(t,e,n,i)=>{e.isDirectory()&&Zf(Fi.resolve(t,e.name),n,i),Kc(Fi.resolve(t,e.name),n,i)},Zf=(t,e,n)=>{let i;try{i=bo.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Kc(t,e,n);throw a}for(let o of i)Qy(t,o,e,n);return Kc(t,e,n)},Yf=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"}},Eo=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"}},t_=(t,e)=>{ht.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new Yf(t,n?.code||"ENOTDIR")),e(n)})},n_=(t,e,n)=>{t=ne(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),p=e.preserve,x=e.unlink,g=ne(e.cwd),E=(b,I)=>{b?n(b):I&&f?Jf(I,d,u,A=>E(A)):a?ht.chmod(t,o,n):n()};if(t===g)return t_(t,E);if(p)return e_.mkdir(t,{mode:o,recursive:!0}).then(b=>E(null,b??void 0),E);let y=ne(xo.relative(g,t)).split("/");$c(g,y,o,x,g,void 0,E)},$c=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),f=ne(xo.resolve(t+"/"+u));ht.mkdir(f,n,Xf(f,e,n,i,o,a,d))},Xf=(t,e,n,i,o,a,d)=>u=>{u?ht.lstat(t,(f,p)=>{if(f)f.path=f.path&&ne(f.path),d(f);else if(p.isDirectory())$c(t,e,n,i,o,a,d);else if(i)ht.unlink(t,x=>{if(x)return d(x);ht.mkdir(t,n,Xf(t,e,n,i,o,a,d))});else{if(p.isSymbolicLink())return d(new Eo(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,$c(t,e,n,i,o,a,d))},r_=t=>{let e=!1,n;try{e=ht.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new Yf(t,n??"ENOTDIR")}},i_=(t,e)=>{t=ne(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,p=e.unlink,x=ne(e.cwd),g=b=>{b&&u&&Zf(b,a,d),o&&ht.chmodSync(t,i)};if(t===x)return r_(x),g();if(f)return g(ht.mkdirSync(t,{mode:i,recursive:!0})??void 0);let E=ne(xo.relative(x,t)).split("/"),y;for(let b=E.shift(),I=x;b&&(I+="/"+b);b=E.shift()){I=ne(xo.resolve(I));try{ht.mkdirSync(I,i),y=y||I}catch{let A=ht.lstatSync(I);if(A.isDirectory())continue;if(p){ht.unlinkSync(I),ht.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new Eo(I,I+"/"+E.join("/"))}}return g(y)},Tc=Object.create(null),hf=1e4,Tr=new Set,s_=t=>{Tr.has(t)?Tr.delete(t):Tc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Tr.add(t);let e=Tc[t],n=Tr.size-hf;if(n>hf/10){for(let i of Tr)if(Tr.delete(i),delete Tc[i],--n<=0)break}return e},o_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,a_=o_==="win32",c_=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=Qf(i,n)),e.push(n||"/"),e},[]),d_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=a_?["win32 parallelization disabled"]:t.map(i=>Bi(Qf(s_(i))));let n=new Set(t.map(i=>c_(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}},l_=()=>process.umask(),pf=Symbol("onEntry"),Vc=Symbol("checkFs"),xf=Symbol("checkFs2"),Jc=Symbol("isReusable"),yt=Symbol("makeFs"),Zc=Symbol("file"),Yc=Symbol("directory"),lo=Symbol("link"),gf=Symbol("symlink"),mf=Symbol("hardlink"),Ni=Symbol("ensureNoSymlink"),wf=Symbol("unsupported"),yf=Symbol("checkPath"),Cc=Symbol("stripAbsolutePath"),Tn=Symbol("mkdir"),Ve=Symbol("onError"),Xs=Symbol("pending"),_f=Symbol("pend"),Cr=Symbol("unpend"),Pc=Symbol("ended"),Dc=Symbol("maybeClose"),Xc=Symbol("skip"),zi=Symbol("doChown"),Ui=Symbol("uid"),Hi=Symbol("gid"),Gi=Symbol("checkedCwd"),u_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,qi=u_==="win32",f_=1024,h_=(t,e)=>{if(!qi)return de.unlink(t,e);let n=t+".DELETE."+Hf(16).toString("hex");de.rename(t,n,i=>{if(i)return e(i);de.unlink(n,e)})},p_=t=>{if(!qi)return de.unlinkSync(t);let e=t+".DELETE."+Hf(16).toString("hex");de.renameSync(t,e),de.unlinkSync(e)},bf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,cd=class extends ji{[Pc]=!1;[Gi]=!1;[Xs]=0;reservations=new d_;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[Pc]=!0,this[Dc]()},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:f_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||qi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=ne(Ge.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:l_():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[pf](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Dc](){this[Pc]&&this[Xs]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Cc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=id(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||qi&&/^[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=Ge.posix.dirname(t.path),f=Ge.posix.normalize(Ge.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}[yf](t){let e=ne(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=ne(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[Cc](t,"path")||!this[Cc](t,"linkpath"))return!1;if(t.absolute=Ge.isAbsolute(t.path)?ne(Ge.resolve(t.path)):ne(Ge.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:ne(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}=Ge.win32.parse(String(t.absolute));t.absolute=i+ef(String(t.absolute).slice(i.length));let{root:o}=Ge.win32.parse(t.path);t.path=o+ef(t.path.slice(o.length))}return!0}[pf](t){if(!this[yf](t))return t.resume();switch($y.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[Vc](t);default:return this[wf](t)}}[Ve](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Cr](),e.resume())}[Tn](t,e,n){n_(ne(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)}[zi](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}[Ui](t){return bf(this.uid,t.uid,this.processUid)}[Hi](t){return bf(this.gid,t.gid,this.processGid)}[Zc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new go(String(t.absolute),{flags:Vf(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&de.close(i.fd,()=>{}),i.write=()=>!0,this[Ve](u,t),e()});let o=1,a=u=>{if(u){i.fd&&de.close(i.fd,()=>{}),this[Ve](u,t),e();return}--o===0&&i.fd!==void 0&&de.close(i.fd,f=>{f?this[Ve](f,t):this[Cr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let p=t.atime||new Date,x=t.mtime;de.futimes(f,p,x,g=>g?de.utimes(u,p,x,E=>a(E&&g)):a())}if(typeof f=="number"&&this[zi](t)){o++;let p=this[Ui](t),x=this[Hi](t);typeof p=="number"&&typeof x=="number"&&de.fchown(f,p,x,g=>g?de.chown(u,p,x,E=>a(E&&g)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[Ve](u,t),e()}),t.pipe(d)),d.pipe(i)}[Yc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Tn](String(t.absolute),n,i=>{if(i){this[Ve](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Cr](),t.resume())};t.mtime&&!this.noMtime&&(o++,de.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[zi](t)&&(o++,de.chown(String(t.absolute),Number(this[Ui](t)),Number(this[Hi](t)),a)),a()})}[wf](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[gf](t,e){let n=ne(Ge.relative(this.cwd,Ge.resolve(Ge.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Ni](t,this.cwd,n,()=>this[lo](t,String(t.linkpath),"symlink",e),i=>{this[Ve](i,t),e()})}[mf](t,e){let n=ne(Ge.resolve(this.cwd,String(t.linkpath))),i=ne(String(t.linkpath)).split("/");this[Ni](t,this.cwd,i,()=>this[lo](t,n,"link",e),o=>{this[Ve](o,t),e()})}[Ni](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Ge.resolve(e,a);de.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new Eo(d,Ge.resolve(d,n.join("/"))));this[Ni](t,d,n,i,o)})}[_f](){this[Xs]++}[Cr](){this[Xs]--,this[Dc]()}[Xc](t){this[Cr](),t.resume()}[Jc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!qi}[Vc](t){this[_f]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[xf](t,n))}[xf](t,e){let n=d=>{e(d)},i=()=>{this[Tn](this.cwd,this.dmode,d=>{if(d){this[Ve](d,t),n();return}this[Gi]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=ne(Ge.dirname(String(t.absolute)));if(d!==this.cwd)return this[Tn](d,this.dmode,u=>{if(u){this[Ve](u,t),n();return}a()})}a()},a=()=>{de.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Xc](t),n();return}if(d||this[Jc](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,p=x=>this[yt](x??null,t,n);return f?de.chmod(String(t.absolute),Number(t.mode),p):p()}if(t.absolute!==this.cwd)return de.rmdir(String(t.absolute),f=>this[yt](f??null,t,n))}if(t.absolute===this.cwd)return this[yt](null,t,n);h_(String(t.absolute),f=>this[yt](f??null,t,n))})};this[Gi]?o():i()}[yt](t,e,n){if(t){this[Ve](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Zc](e,n);case"Link":return this[mf](e,n);case"SymbolicLink":return this[gf](e,n);case"Directory":case"GNUDumpDir":return this[Yc](e,n)}}[lo](t,e,n,i){de[n](e,String(t.absolute),o=>{o?this[Ve](o,t):(this[Cr](),t.resume()),i()})}},Oi=t=>{try{return[null,t()]}catch(e){return[e,null]}},e0=class extends cd{sync=!0;[yt](t,e){return super[yt](t,e,()=>{})}[Vc](t){if(!this[Gi]){let o=this[Tn](this.cwd,this.dmode);if(o)return this[Ve](o,t);this[Gi]=!0}if(t.absolute!==this.cwd){let o=ne(Ge.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[Tn](o,this.dmode);if(a)return this[Ve](a,t)}}let[e,n]=Oi(()=>de.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Xc](t);if(e||this[Jc](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?Oi(()=>{de.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[yt](d,t)}let[o]=Oi(()=>de.rmdirSync(String(t.absolute)));this[yt](o,t)}let[i]=t.absolute===this.cwd?[]:Oi(()=>p_(String(t.absolute)));this[yt](i,t)}[Zc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{de.closeSync(o)}catch(f){u=f}(d||u)&&this[Ve](d||u,t),e()},o;try{o=de.openSync(String(t.absolute),Vf(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[Ve](d,t)),t.pipe(a)),a.on("data",d=>{try{de.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{de.futimesSync(o,u,f)}catch(p){try{de.utimesSync(String(t.absolute),u,f)}catch{d=p}}}if(this[zi](t)){let u=this[Ui](t),f=this[Hi](t);try{de.fchownSync(o,Number(u),Number(f))}catch(p){try{de.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||p}}}i(d)})}[Yc](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Tn](String(t.absolute),n);if(i){this[Ve](i,t),e();return}if(t.mtime&&!this.noMtime)try{de.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[zi](t))try{de.chownSync(String(t.absolute),Number(this[Ui](t)),Number(this[Hi](t)))}catch{}e(),t.resume()}[Tn](t,e){try{return i_(ne(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}}[Ni](t,e,n,i,o){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Ge.resolve(a,d);let[u,f]=Oi(()=>de.lstatSync(a));if(u)return i();if(f.isSymbolicLink())return o(new Eo(a,Ge.resolve(e,n.join("/"))))}i()}[lo](t,e,n,i){let o=`${n}Sync`;try{de[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[Ve](a,t)}}},x_=t=>{let e=new e0(t),n=t.file,i=Uf.statSync(n),o=t.maxReadSize||16*1024*1024;new Rw(n,{readSize:o,size:i.size}).pipe(e)},g_=(t,e)=>{let n=new cd(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Uf.stat(o,(u,f)=>{if(u)d(u);else{let p=new ed(o,{readSize:i,size:f.size});p.on("error",d),p.pipe(n)}})})},t0=Wi(x_,g_,t=>new e0(t),t=>new cd(t),(t,e)=>{e?.length&&Of(t,e)}),m_=(t,e)=>{let n=new ad(t),i=!0,o,a;try{try{o=ft.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=ft.openSync(t.file,"w+");else throw f}let d=ft.fstatSync(o),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let x=0,g=0;x<512;x+=g){if(g=ft.readSync(o,u,x,u.length-x,a+x),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!g)break e}let f=new Xn(u);if(!f.cksumValid)break;let p=512*Math.ceil((f.size||0)/512);if(a+p+512>d.size)break;a+=p,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,w_(t,n,a,o,e)}finally{if(i)try{ft.closeSync(o)}catch{}}},w_=(t,e,n,i,o)=>{let a=new Sf(t.file,{fd:i,start:n});e.pipe(a),__(e,o)},y_=(t,e)=>{e=Array.from(e);let n=new _o(t),i=(o,a,d)=>{let u=(E,y)=>{E?ft.close(o,b=>d(E)):d(null,y)},f=0;if(a===0)return u(null,0);let p=0,x=Buffer.alloc(512),g=(E,y)=>{if(E||y===void 0)return u(E);if(p+=y,p<512&&y)return ft.read(o,x,p,x.length-p,f+p,g);if(f===0&&x[0]===31&&x[1]===139)return u(new Error("cannot append to compressed archives"));if(p<512)return u(null,f);let b=new Xn(x);if(!b.cksumValid)return u(null,f);let I=512*Math.ceil((b.size??0)/512);if(f+I+512>a||(f+=I+512,f>=a))return u(null,f);t.mtimeCache&&b.mtime&&t.mtimeCache.set(String(b.path),b.mtime),p=0,ft.read(o,x,0,512,f,g)};ft.read(o,x,0,512,f,g)};return new Promise((o,a)=>{n.on("error",a);let d="r+",u=(f,p)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",ft.open(t.file,d,u);if(f||!p)return a(f);ft.fstat(p,(x,g)=>{if(x)return ft.close(p,()=>a(x));i(p,g.size,(E,y)=>{if(E)return a(E);let b=new go(t.file,{fd:p,start:y});n.pipe(b),b.on("error",a),b.on("close",o),b_(n,e)})})};ft.open(t.file,d,u)})},__=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Br({file:n0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},b_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Br({file:n0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Li=Wi(m_,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")}),yT=Wi(Li.syncFile,Li.asyncFile,Li.syncNoFile,Li.asyncNoFile,(t,e=[])=>{Li.validate?.(t,e),E_(t)}),E_=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))};Zt();var _t={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 vo(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function r0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function So(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function i0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function s0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function o0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function er(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}rn();Ye();ie();De();Ye();function Fr(t,e){if(vo(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ki(t){return t.startsWith("http://")||t.startsWith("https://")}function zr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as l2}from"node:fs";import{dirname as f2,join as h2}from"node:path";import{fileURLToPath as x2}from"node:url";var Ht="0.3.1";import{mkdir as z_,rm as S0}from"node:fs/promises";import{join as Zi}from"node:path";Jt();import{readFileSync as P_}from"node:fs";var D_=384;async function dd(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await wn(t.agentEnvFile,n,{mode:D_})}function tr(t){try{let e=JSON.parse(P_(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Io(t,e,n={},i=o=>o){return{...i({...t,...tr(e)}),...n}}Jt();function $i(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(R_(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
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(`
92
92
  `)}
93
- `}function R_(t){if(t.includes(`
94
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ie();De();import{homedir as N_}from"node:os";import{join as M_}from"node:path";Ye();ie();var Ao="1008033",l0="1289";var u0="pbbp2",f0="https://www.coze.cn",h0="/api/coze_claw/resource/get_frontier_key",O_="https://www.coze.cn",L_="wss://frontier.coze.cn";function Ur(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??O_}function p0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??L_}function Dn(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 Ji(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Vi=q("handshake");async function ld(t){let e=Ur(t.endpoint),n=t.timeoutMs??1e4,i=`${zr(e)}${h0}?aid=${encodeURIComponent(Ao)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Dn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);Vi.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")??"",p=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let b=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${b.slice(0,200)}`)}let x=await u.json();if(x.code!==void 0&&x.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${x.code} msg=${x.msg??"-"} logid=${f}`);let g=x.data??{},E=typeof g.access_key=="string"&&g.access_key||typeof g.accessKey=="string"&&g.accessKey||void 0,y=typeof g.device_id=="string"&&g.device_id||typeof g.deviceId=="string"&&g.deviceId||void 0;if(!E||!y){let b=JSON.stringify(x).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${b}`)}return Vi.info("handshake ok",{remoteDeviceId:y,logid:f,traceId:p}),{accessKey:E,deviceId:y}}catch(u){if(u instanceof k)throw Vi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Vi.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let f=u.cause;throw Vi.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 ko=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Dt="auto",ud=19e4,x0=32e3;function m0(t){return{model:fd(t.model)??Dt,...t.modelToken?{modelToken:t.modelToken}:{}}}function w0(t){return!t||t===Dt}var B_=new Set(["auto","\u81EA\u52A8"]);function fd(t){let e=t?.trim();if(e)return B_.has(e.toLowerCase())?Dt:e}function y0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=ko,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Dt;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 w0(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function _0(t,e,n,i){let o={};if(t.modelToken?o.model=t.model||Dt:w0(t.model)||(o.model=t.model),t.modelToken){let a={name:"coze",base_url:`${ko}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=To(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),o.model_providers={coze:a},o.model_context_window=t.modelInfo?.contextWindow??ud}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function b0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function To(t,e,n){let{ttEnv:i,usePpe:o}=Ji(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 E0(t,e,n,i){if(!t.modelToken)return{};let o=To(e,n,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,u])=>`${d}:${u}`).join(`
95
- `)}}function hd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function pd(t){return t.model||Dt}function g0(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 v0(t,e,n,i,o){if(!t.modelToken)return null;let a=pd(t),d=To(e,n,o),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let f=[g0(a,u,t.modelInfo?.contextWindow??ud,t.modelInfo?.maxOutput??x0)],p=new Set([a]);for(let g of i??[])!g||p.has(g)||(p.add(g),f.push(g0(g,["text"],ud,x0)));let x={baseUrl:`${ko}/v1`,api:"openai-completions",apiKey:t.modelToken,models:f};return Object.keys(d).length>0&&(x.headers=d),x}function F_(t){if(t!==void 0)return t?"auto":"text"}function xd(t,e,n){let i=To(e,n),o=t.model||Dt,a=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${ko}/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=F_(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(` - ${M_(N_(),".hermes","skills")}`),`${a.join(`
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(`
96
96
  `)}
97
- `}var nr=q("hermes-config"),I0="dont_ask",A0="default";function rr(t,e){return Zi(Me(t,e).root,"hermes-home")}async function U_(t){let e=rr(t.agentId,t.paths);await z_(e,{recursive:!0,mode:448});let n=$i({...process.env,...tr(t.paths.agentEnvFile)});await mt(Zi(e,".env"),n,{mode:384});let i=xd(t.modelConfig,t.cozeEnv,t.mockScenario);await mt(Zi(e,"config.yaml"),i,{mode:384}),nr.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function k0(t){let e=rr(t.agentId,t.paths),n=Zi(e,"state.db"),i=Zi(e,"config.yaml");nr.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 S0(n,{force:!0}).catch(a=>nr.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let o=xd({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await mt(i,o,{mode:384}).catch(a=>nr.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),nr.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function md(t,e){let n=rr(t,e);nr.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 S0(n,{recursive:!0,force:!0}).catch(i=>nr.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var gd=new Map;function T0(t){let e=gd.get(t.agentId);if(e)return e;let n=U_(t).finally(()=>gd.delete(t.agentId));return gd.set(t.agentId,n),n}var ae=q("agent-handlers"),P0=5*1024*1024,W_=1,K_=6,$_=new Set(["node_modules",".git",".coze","dist","build",".next"]),V_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,J_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Z_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Y_(t){let e=t?.trim();return e?Z_.test(e)||J_.test(e)?e:(ae.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function X_(t){return new Promise((e,n)=>{let i=lt("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 Q_(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var Po=class{constructor(e){this.opts=e}opts;get paths(){return this.opts.paths??Y()}async listSkills(e){e._meta;let n=er(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Me(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Gr(a,n,o,this.paths),f=[],p=new Set;for(let g of d){let E=ge(u,g.relPath,"SKILL.md");await Sd(E).then(b=>b.isFile()).catch(()=>!1)&&(f.push(ib(g)),p.add(g.relPath))}if(e.scanLocal){let g=await H0(n,o,a,this.paths),E=await G0(n,a);for(let y of[...g,...E])p.has(y.relPath)||(p.add(y.relPath),f.push(y.skill))}return{skills:a==="hermes"?f.filter(g=>g.skillName!=="yuanbao"):f}}async addSkills(e){e._meta;let n=er(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((f,p)=>[f.skillId,p])),u=[];for(let f of o){let p=await Do({agentId:n,workspace:i.workspace,framework:i.framework,skill:f,paths:this.paths});Ro(a,d,p),u.push(f)}return await wi(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=er(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Gr(i.framework,n,i.workspace,this.paths);for(let f of a){if(!o.has(f.skillId)){d.push(f);continue}let p=ge(u,f.relPath);ae.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:f.skillId,relPath:f.relPath,skillBase:u,absDir:p}),await _d(p,{recursive:!0,force:!0}),ae.info("skill removed",{agentId:n,skillId:f.skillId,relPath:f.relPath})}return await wi(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=er(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");ae.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??Me(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 P=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${P}: ${e.skillName}`)}let{absDir:f,relPath:p,dirName:x}=u,g=ge(f,"SKILL.md"),E=new Ad.default;E.addLocalFolder(f,x);let y=E.toBuffer();if(y.length>D0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${D0}`);let b=await Co(g,{encoding:"utf8"}).then(P=>z0(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...b?{description:b}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):ae.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??F0(n,p);if(i&&!d){let P=i.skills??[],_=P.find(D=>D.relPath===p);_?(_.version=A,_.skillId=T):P.push({skillId:T,skillName:e.skillName,relPath:p,version:A,installedAt:Date.now(),...b?{description:b}:{}}),await wi(n,P)}return ae.info("skill published",{agentId:n,skillName:e.skillName,relPath:p,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[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,ae.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,ae.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(n).catch(p=>ae.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:o,err:String(p)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return ae.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await ke(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return ae.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await br(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw ae.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await je(i),ae.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 ke(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&Ki(e.registry)&&o.push(`--registry=${e.registry}`);let a=Y_(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&V_.test(d)&&o.push("--env",d);let u=await X_(o);return ae.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 ke(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await je(i),ae.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}):(ae.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",`${_t.DELETE}: missing agentId`);ae.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 ke(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=Me(n);return a==="cloud"?(ae.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 _d(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await je(i)),ae.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(Fr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=fd(e.model)??Dt,i=await ke(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 je(i),ae.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return ae.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(p=>ae.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(p)}));let u=o.framework==="hermes"&&Q_(d,o.modelInfo);if(o.framework==="hermes"&&!u){let p=[];for(let[x,g]of o.allSessionQueues())p.push(g.enqueue(async()=>{let E=o.sessions.get(x);if(!(!E?.downstream||!E.acpSessionId))try{await E.downstream.setSessionModel?.({sessionId:E.acpSessionId,modelId:n})}catch(y){ae.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:x,acpId:E.acpSessionId,err:String(y)})}}));return await Promise.all(p),ae.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:p.length}),{ok:!0}}let f=[];for(let[p,x]of o.allSessionQueues())f.push(x.enqueue(async()=>{let g=o.sessions.get(p);g?.downstream&&(await g.downstream.stop(`switchModel: ${n}`).catch(()=>{}),g.downstream=void 0)}));return await Promise.all(f),ae.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(Fr(e._meta,_t.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${_t.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,_t.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>ae.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,_t.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),ae.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 mi(e,o)}async clearPersistedAcpSessionIds(e){let n=await ke(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 je(n)}async repairAgent(e){if(Fr(e._meta,_t.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${_t.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${_t.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){ae.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,_t.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){ae.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){ae.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Fr(e._meta,"_agent/getFileTree");let n=e._meta,i=er(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),u=await wd(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 gi(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let f=gb(e.depth);return u.isDirectory()?{tree:await xb(o,d,a,f)}:{tree:[{name:mb(a),path:W0(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Fr(e._meta,"_agent/getFileContent");let n=er(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),a=await wd(o).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 gi(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>P0)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${P0})`);let d=await Co(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 ke(e).catch(()=>null))?.workspace??Me(e).workspace}safeJoin(e,n){let i=Ed(e,n||"."),o=Id(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${O0}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return ke(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 M0(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 Gr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:ge(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:ge(".agents","skills")};case"hermes":return{base:rr(e,i??Y()),subdir:"skills"}}}function B0(t){let e=G_();if(t==="claude-code")return[ge(e,".claude","skills")];if(t==="codex")return[ge(e,".agents","skills"),ge(e,".codex","skills")];if(t==="openclaw")return[ge(e,".agents","skills"),ge(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||ge(e,"AppData","Local");return[ge(n,"hermes","skills"),ge(e,".hermes","skills")]}return[ge(e,".hermes","skills")]}return[]}async function eb(t,e,n,i,o,a){let d=async u=>Sd(ge(u,"SKILL.md")).then(f=>f.isFile()).catch(()=>!1);if(!o){let{base:u,subdir:f}=Gr(n,t,e,a),p=ge(f,i),x=ge(u,p);return await d(x)?{absDir:x,relPath:p}:null}for(let u of B0(n)){let f=ge(u,i);if(await d(f))return{absDir:f,relPath:f}}return null}async function tb(t,e,n,i,o,a){let d=M0(i),u=await eb(t,e,n,d,o,a);if(u)return{...u,dirName:d};let p=(o?await G0(t,n):await H0(t,e,n,a)).filter(E=>E.skill.skillName===i);if(p.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${p.map(E=>C0(E.relPath)).join(", ")} \u2014 rename or remove duplicates`);let x=p[0];return x?{absDir:o?x.relPath:ge(e,x.relPath),relPath:x.relPath,dirName:C0(x.relPath)}:null}function F0(t,e){return(H_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function z0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
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
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 U0(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 Sd(ge(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let f=d.name,p=ge(n,f),x=ge(e,f,"SKILL.md"),g=await Co(x,{encoding:"utf8"}).catch(()=>null);if(g===null)continue;let E=z0(g);a.push({relPath:p,skill:{skillId:F0(t,p),skillName:E.name||f,...E.description?{description:E.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function H0(t,e,n,i){let{base:o,subdir:a}=Gr(n,t,e,i);return U0(t,ge(o,a),a,!1)}async function G0(t,e){let n=[],i=new Set;for(let o of B0(e)){let a=await U0(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,D0=10*1024*1024,Hr=3e4;async function Do(t){let{agentId:e,workspace:n,framework:i,skill:o,paths:a}=t;if(!o.skillName)throw new k("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 k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let f=M0(o.skillName),{base:p,subdir:x}=Gr(i,e,n,a),g=ge(x,f),E=ge(p,g);if(await yd(E,{recursive:!0}),d){let b=Buffer.from(o.content,"utf8");Yi(b.length),await bd(ge(E,"SKILL.md"),b,"utf8")}else{let b=await ob(o.downloadUrl);cb(b)?await fb(b,E):db(b)?await lb(b,E):await bd(ge(E,"SKILL.md"),b.toString("utf8"),"utf8")}let y={skillId:o.skillId,skillName:o.skillName,relPath:g,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 ae.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:g,source:d?"content":"downloadUrl"}),y}function Ro(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 q0(t,e){let n=await ke(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Ht,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await je(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((g,E)=>[g.skillId,E])),u=a.filter(g=>g.builtin===!0&&!!g.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await je(n,e),{status:"noop",count:0};let f=0,p=0,{base:x}=Gr(n.framework,t,n.workspace,e);ae.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:x,builtinCount:u.length,builtinRelPaths:u.map(g=>g.relPath)});for(let g of u)try{let E=ge(x,g.relPath);ae.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:g.skillId,relPath:g.relPath,rmTarget:E}),await _d(E,{recursive:!0,force:!0});let y=await Do({agentId:t,workspace:n.workspace,framework:n.framework,skill:sb(g),...e?{paths:e}:{}});Ro(a,d,y),f+=1}catch(E){p+=1,ae.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:g.skillId,skillName:g.skillName,err:String(E)})}return n.skills=a,p===0&&(n.skillsRefreshedForVersion=i),await je(n,e),ae.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:p}),{status:"refreshed",count:f}}async function ob(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Yi(e);let n=ab(t);return Yi(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Co(e);return Yi(n.length),n}if(Ki(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),nb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Yi(o.byteLength),Buffer.from(o)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Yi(t){if(t>rb)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function ab(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 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 vd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function lb(t,e){let n,i;try{n=new Ad.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||vd(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(p=>p===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=ub(i),a=Ed(e);for(let d of i){if(vd(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Ed(e,u),p=Id(a,f);if(p.startsWith("..")||p==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await yd(f,{recursive:!0});continue}await yd(q_(f),{recursive:!0});let x;try{x=d.getData()}catch(g){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${g.message}`,{cause:g})}await bd(f,x)}}function ub(t){let e;for(let n of t){let i=n.entryName;if(!i||vd(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=t0({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Hr}ms)`))},Hr);try{await N0(L0.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Hr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function hb(t){let e=[],n=Br({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(p=>p==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Hr}ms)`))},Hr);try{await N0(L0.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Hr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var pb=5e3;async function xb(t,e,n,i){return j0(t,e,n,i,{count:0})}async function j0(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($_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=pb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=ge(e,u.name),p=j_(ge(n,u.name)),x=null;try{x=await wd(f)}catch{continue}if(x.isSymbolicLink())continue;o.count++;let g={name:u.name,path:W0(Id(t,f)),isDir:x.isDirectory(),size:x.size,modifiedAt:Math.floor(x.mtimeMs)};x.isDirectory()&&i>1&&(g.children=await j0(t,f,p,i-1,o)),d.push(g)}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?W_:Math.min(t,K_)}function mb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function W0(t){return t.split(O0).join("/")}ie();var Rn=q("agent-health-reporter"),wb=1e4,yb=3,Xi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??wb,this.livenessFailureThreshold=e.livenessFailureThreshold??yb}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()}),Rn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Rn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Rn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Rn.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=_b(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:Ht,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Rn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(Rn.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){Rn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Rn.warn("onTickEnd hook failed",{err:String(n)})}}};function _b(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Zt();import{copyFile as BE,cp as FE,mkdir as jo,readFile as zE,rm as UE,stat as Ld,writeFile as HE}from"node:fs/promises";import{homedir as Th}from"node:os";import{basename as GE,join as on}from"node:path";gn();import{existsSync as Db}from"node:fs";import{release as Rb}from"node:os";import{basename as Ob,isAbsolute as Lb}from"node:path";function Qi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function qr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function jr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function On(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ye();var Oo=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)}},ee={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function K0(t){return"method"in t&&"id"in t&&t.id!==void 0}function $0(t){return"method"in t&&!("id"in t)}function Lo(t){return!("method"in t)&&"id"in t}var bb={AGENT_NOT_FOUND:ee.AGENT_NOT_FOUND,AGENT_BUSY:ee.AGENT_BUSY,AGENT_DISCONNECTED:ee.AGENT_DISCONNECTED,AGENT_TIMEOUT:ee.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:ee.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:ee.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:ee.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:ee.INTERNAL_ERROR,BRIDGE_INTERNAL:ee.INTERNAL_ERROR,IPC_AUTH_FAILED:ee.INTERNAL_ERROR,IPC_BAD_REQUEST:ee.INVALID_REQUEST,METHOD_NOT_FOUND:ee.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:ee.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:ee.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:ee.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:ee.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:ee.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:ee.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:ee.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:ee.FILE_TOO_LARGE,UNSUPPORTED_MIME:ee.UNSUPPORTED_MIME,UPLOAD_FAILED:ee.UPLOAD_FAILED,UPSTREAM_NOT_READY:ee.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:ee.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:ee.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:ee.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:ee.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:ee.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:ee.SKILL_ZIP_TOO_LARGE};function Eb(t){if(t!=null)return t instanceof Error?{name:t.name,message:es(t.message)}:typeof t=="string"?es(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 es(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]=es(i):e[n]=i;return e}function ts(t){if(t instanceof k){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]??ee.INTERNAL_ERROR,message:es(t.message),data:n}}return{code:ee.INTERNAL_ERROR,message:es(t instanceof Error?t.message:String(t))}}function V0(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 k(n,o,{retriable:e?.retriable??!1,cause:a})}function Z0(t){return`${JSON.stringify(t)}
103
- `}var J0=10*1024*1024,No=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>J0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${J0} 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 X0={"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(X0).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:[]},Wr=class{seq=0;next(e,n){this.seq+=1;let i=X0[e]??Ab(e),o=Ib[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>Y0(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=>Y0(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function Ab(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Y0(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)}rn();gr();Ye();ie();De();import{execFileSync as Tb,spawnSync as Cb}from"node:child_process";function ns(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function rs(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 kd=new Set;function Q0(t){typeof t=="number"&&t>0&&kd.add(t)}function eh(t){typeof t=="number"&&kd.delete(t)}function th(){for(let t of kd)rs(t,"SIGKILL")}var Kr="coze-bridge-daemon";function nh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Tb("pgrep",["-U",String(o),"-f",Kr],{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 rh(t,e){if(t.length===0)return;let n=e?.killFn??rs,i=e?.isAliveFn??ns,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 Pb=[{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 Pb)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function sh(t,e){return ih(t,e)}function oh(t,e){return ih(t,e)}function $r(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 ah(t,e,n){let o=n-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let p=t.suspendedMs+o,x=n-t.startedAt-p;return{action:"suspend",suspendedDeltaMs:o,rearmMs:$r(x,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:$r(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:$r(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:$r(a,!1,e)}}var ch=Qe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Nb=200,Mb=40,Bb=Qe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fb=Qe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zb=Qe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Ub=Qe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Hb=Qe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Gb=Qe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),dh=500;function qb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=dh?t:`${e.slice(0,dh)}...<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 lh(t){try{return Db(t)}catch{return}}function Wb(t,e){return{platform:process.platform,osRelease:Rb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Lb(e.command)?lh(e.command):void 0,cwd:e.cwd,cwdExists:lh(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 bt=class{constructor(e){this.opts=e;this.log=q(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new No({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Wr;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=Io(process.env,this.opts.agentEnvFile??Y().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=lt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Q0(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,eh(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 k("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()));rs(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||rs(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,ch,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(qr("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(jr(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(On(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,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=Qi(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,p)=>{let x={resolve:f,reject:p,timer:null,method:e,promptTimeout:null};if(o){let g=this.now(),E={cfg:o,startedAt:g,lastActivityAt:g,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:g,expectedIntervalMs:$r(0,!1,o),sessionId:u};x.promptTimeout=E;let y=()=>{let b={startedAt:E.startedAt,lastActivityAt:E.lastActivityAt,firstFrameSeen:E.firstFrameSeen,hasActiveTool:E.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:E.suspendedMs,armedAt:E.armedAt,expectedIntervalMs:E.expectedIntervalMs},I=this.now(),A=ah(b,E.cfg,I),T=P=>{E.armedAt=I,E.expectedIntervalMs=P,x.timer=setTimeout(y,P)};if(A.action==="suspend"){E.suspendedMs+=A.suspendedDeltaMs,E.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:E.suspendedMs,...E.sessionId?{sessionId:E.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,...E.sessionId?{sessionId:E.sessionId}:{}}),p(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${E.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${E.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...E.sessionId?{sessionId:E.sessionId}:{}}),p(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${E.cfg.livenessWindowMs}ms`)))};x.timer=setTimeout(y,E.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(x.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),p(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,x);try{this.writeFrame(d)}catch(g){x.timer&&clearTimeout(x.timer),this.pending.delete(a),p(g)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Z0(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Lo(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:qb(e.result)}),n.resolve(e.result));return}if($0(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(K0(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(On(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(On(e.id,ts(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=V0(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=oh(this.framework,jb(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(Mb).join(`
106
- `),o=sh(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.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 $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 Mo=class extends bt{framework="claude-code";constructor(e){let{command:n,args:i}=xi("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)}};gn();import{spawn as Vb}from"node:child_process";import{closeSync as Jb,existsSync as Pd,mkdirSync as Zb,mkdtempSync as Yb,openSync as Xb,readFileSync as mh,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 Vr}from"node:path";var uh=["default","acceptEdits","plan","auto","bypassPermissions"],fh=["read-only","auto","full-access"];var hh=["default","accept_edits","dont_ask"];function Gt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return uh.includes(e);case"codex":return fh.includes(e);case"hermes":return hh.includes(e);case"openclaw":return!1}}function Bo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function ph(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Td(t){switch(t){case"claude-code":return uh.join("/");case"codex":return fh.join("/");case"hermes":return hh.join("/");case"openclaw":return""}}De();var Dd=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?Dd: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?Dd: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 xh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:Dd};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 Cd(t){if(Array.isArray(t))return t.flatMap(i=>Cd(i));if(!t||typeof t!="object"){let i=xh(t);return i?[i]:[]}let e=t;if(e.hooks)return Cd(e.hooks);let n=xh(e);return n?[n]:[]}function lE(t){let e=Vr(t,"hooks.json");if(!Pd(e))return[];let n=JSON.parse(mh(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return Cd(o.Stop??o.stop)}function uE(t,e){let n=Vr(t,"sessions");if(!Pd(n))return;let i=[],o=a=>{let d;try{d=eE(a,{withFileTypes:!0})}catch{return}for(let u of d){let f=Vr(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{Jb(n)}catch{}}}function hE(t){return tr(t??Y().agentEnvFile)}function pE(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 xE(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]=pE(o.slice(a+1)))}return e}function gE(t){let e=Vr(t,"cozeloop.env");return Pd(e)?xE(mh(e,"utf8")):{}}function gh(t){let e=t?.trim();return e||void 0}function mE(t){let e=hE(t.agentEnvFile),n=gh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=gh(t.env?.HOME??e.HOME??process.env.HOME)??rE();return Vr(i,".codex")}var Fo=class extends bt{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:a}=xi("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Yb(Vr(iE(),"coze-bridge-codex-home-")):mE(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Zb(d,{recursive:!0});let f=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,p={command:o,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...f?{env:f}:{}};super(p),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=Gt("codex",e.modeId)?Bo(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=Io(process.env,this.opts.agentEnvFile??Y().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"]}),p="",x=setTimeout(()=>{f.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);f.stderr?.setEncoding("utf8"),f.stderr?.on("data",g=>{p+=g,p.length>4e3&&(p=p.slice(-4e3))}),f.on("error",g=>{clearTimeout(x),o(g)}),f.on("close",(g,E)=>{if(clearTimeout(x),g===0){i();return}o(new Error(`hook exited code=${g} signal=${E} stderr=${p.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=ph(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ie();var yE=q("hermes-downstream"),zo=class extends bt{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){yE.warn("hermes session/set_model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}};Ye();var _E=3e4,Jr=class extends bt{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}`}]},_E))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Jt();Ye();ie();De();function Rd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}gn();var Ln=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 Uo=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 Ln,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)Zr(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 Zr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function sn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}rn();ie();import{constants as wh}from"node:fs";import{access as bE,readFile as EE}from"node:fs/promises";import{delimiter as vE,dirname as SE,join as yh}from"node:path";var it=q("framework-detector"),_h={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},IE=[".exe",".cmd",".bat",".ps1"],ir=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??lt,access:e.access??bE,readFile:e.readFile??EE}}async detect(e){let n=_h[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return it.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(_h).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=yh(o,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?wh.F_OK:wh.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 it.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 it.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=yh(SE(o),"hermes-acp");return await this.isExecutable(a)?(it.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(it.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 it.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return it.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 it.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 it.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?(it.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}:(it.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return it.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 it.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||it.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){it.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",p=>{o+=p.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",p=>u({code:p,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 Eh}from"node:os";import{join as Go}from"node:path";Jt();rn();gr();Ye();ie();async function vh(){let t=Go(Eh(),".openclaw/openclaw.json");return mn(t)}async function Sh(){return(await vh())?.gateway?.auth?.token??""}var sr=q("openclaw.config"),TE=[0,5e3,5e3],CE=Qe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),bh="models.providers.",Ho="agents.defaults.models",PE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function Yr(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 qo=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Ln;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??Go(Eh(),".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,sr.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let o=lt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=p=>{d||(d=!0,clearTimeout(f),p())};o.stderr?.on("data",p=>{a+=p.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",p=>u(()=>i(p))),o.on("close",p=>u(()=>{p===0?n():i(new Error(`exit ${p}: ${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){sr.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",`${bh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${bh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ho}[${e}]`,()=>this.runCli(["config","set",Ho,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ho}[${e}]`,`${Ho}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await vh())?.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=Go(this.openclawDir,"identity","device.json"),i=(await mn(e))?.deviceId?.trim();if(!i)return sr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Go(this.openclawDir,"devices","paired.json"),a=await mn(o),d=a?.[i];if(!a||!d)return sr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,f=Yr(Yr(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(b=>b.startsWith("operator.")),p=Yr([...PE],f),x=Yr(d.scopes,p),g=Yr(d.approvedScopes,p),E=u?Yr(u.scopes,p):void 0;return x.length!==(d.scopes?.length??0)||g.length!==(d.approvedScopes?.length??0)||u!==void 0&&E?.length!==(u.scopes?.length??0)?(d.scopes=x,d.approvedScopes=g,u&&E&&(u.scopes=E),await wn(o,a,{mode:384}),sr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:p}),!0):(sr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return sr.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 DE,writeFile as RE}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(`
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
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
110
  `);function ME(t){return t.length===0?t:`${(t.endsWith(`
111
111
  `)?t.slice(0,-1):t).split(`
112
112
  `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
113
113
  `)}
114
- `}async function Ih(t){let e=OE(t,"HEARTBEAT.md"),n=await DE(e,"utf8");return ME(n)!==LE?!1:(await RE(e,NE),!0)}var se=q("agent-manager"),qE=["hooks.json","cozeloop.env"],jE=["hooks"];async function WE(t,e){let n=on(Me(t,e).root,"codex-home"),i=on(Th(),".codex");if(n!==i){await jo(n,{recursive:!0});for(let o of jE){let a=on(i,o),d=on(n,o);try{await Ld(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")}}),se.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&se.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}for(let o of qE){let a=on(i,o),d=on(n,o);try{await Ld(d);continue}catch{}try{if(o==="cozeloop.env"){let f=(await zE(a,"utf8")).split(/\r?\n/).filter(p=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(p)).join(`
115
- `);await HE(d,f,{mode:384})}else await BE(a,d);se.info("migrated legacy Codex state",{agentId:t,name:o})}catch(u){u.code!=="ENOENT"&&se.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(u)})}}}}var Nd="acceptEdits",Ch="full-access",Ph="read-only";function KE(t){return{INITIAL_AGENT_MODE:Bo(t)}}var $E=(t,e,n,i,o,a,d,u,f,p,x,g)=>{switch(t){case"claude-code":{let E={...o?{...y0(o),...E0(o,d,u,g)}:{},...f??{},IS_SANDBOX:"1"};return new Mo({cwd:n,env:E,agentId:i})}case"codex":{let E=Ch;p!==void 0&&(Gt("codex",p)?E=p:se.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:p}));let y={...o?{...b0(o),..._0(o,d,u,g)}:{},...KE(E),...o?{NO_BROWSER:"1"}:{},...f??{},...o?{COZELAB_ONBOARD_CLOUD:"true"}:{}},b=!!o;return new Fo({cwd:n,agentId:i,...Object.keys(y).length>0?{env:y}:{},...b?{authMethodId:"api-key",isolateCodexHome:!0,...x?{codexHomeDir:x}:{}}:{}})}case"openclaw":return new Jr({command:e,cwd:n,agentId:i,...a?{sessionName:Rd(a)}:{}});case"hermes":return new zo({command:e,cwd:n,agentId:i,...f&&Object.keys(f).length>0?{env:{...f}}:{},...o?.model?{modelId:o.model}:{}})}};function Od(t){return t==="claude-code"||t==="codex"}var VE={path:"",version:"cloud-deployed"},Ah="openclaw_gateway_unavailable",JE="openclaw_default_agent_missing";function kh(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 ZE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},YE=6e4,Wo=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 ir),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new qo({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??on(Th(),".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=>{se.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=on(e,".env");if(await Ld(n).then(a=>a.isFile()).catch(()=>!1)){se.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=$i({...process.env,...tr(this.paths.agentEnvFile)});await mt(n,o,{mode:384}),se.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),se.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 ke(e.agentId,this.paths).catch(()=>null),o=vo(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")se.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>se.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")se.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>se.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){se.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await ke(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await je(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){se.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await ke(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await je(T,this.paths))}return se.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework]){let P=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${P}`)}let u=Me(e.agentId,this.paths),f=o?"cloud":"local",p=e.framework==="openclaw"&&f==="local",x;p&&!n?.revive&&(x=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let g=x??(p?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),E=e.workspace??g??u.workspace,y=new AbortController,b=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&Od(e.framework)&&await _r(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 jo(u.root,{recursive:!0}),await jo(E,{recursive:!0}),await jo(u.logs,{recursive:!0}),T(),p||await br(E,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Qa(E,"cloud"):await Qa(E,"local",Nd)),T();let P=i,_=m0({model:e.model??P?.model}),D=r0(e._meta)??P?.accountId,R=e.patToken??P?.patToken,z=f==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new Uo({agentId:e.agentId,framework:e.framework,workspace:E,model:_.model??Dt,deployType:f,...D?{accountId:D}:{},...R?{patToken:R}:{},...z?{modelInfo:z}:{}}),I.status="ok",P?.sessions){let Z=e.framework==="hermes"||f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[te,oe]of Object.entries(P.sessions)){let le={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};Z?oe.permissionMode===void 0?(le.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",se.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:te,framework:e.framework,fallback:le.permissionMode})):Gt(e.framework,oe.permissionMode)?le.permissionMode=oe.permissionMode:se.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:te,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&se.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:te,framework:e.framework,deployType:f}),oe.cozeGroupId&&(le.cozeGroupId=oe.cozeGroupId),oe.tokenGroupId&&(le.tokenGroupId=oe.tokenGroupId),oe.requestScene&&(le.requestScene=oe.requestScene),I.sessions.set(te,le)}let ce=Object.keys(P.sessions).length;ce>0&&se.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ce})}this.registry.register(I),A=!0;let F={agentId:e.agentId,framework:e.framework,workspace:E,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:_.model};if(f==="cloud"&&(F.deployType="cloud"),D&&(F.accountId=D),R&&(F.patToken=R),z&&(F.modelInfo=z),P?.skills&&(F.skills=P.skills),P?.agentName&&(F.agentName=P.agentName),P?.description&&(F.description=P.description),F.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??Ht,e.framework==="openclaw"&&f==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,E)):se.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Ih(E)&&se.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:E})}catch(Z){se.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:E,err:String(Z)})}}let X=e.initialSkills??[];if(X.length>0){let Z=[...F.skills??[]],ce=new Map(Z.map((le,C)=>[le.skillId,C])),te=await Promise.allSettled(X.map(le=>Do({agentId:e.agentId,workspace:E,framework:e.framework,skill:le,paths:this.paths}))),oe=0;for(let[le,C]of te.entries()){let H=X[le];H&&(C.status==="fulfilled"?(Ro(Z,ce,C.value),oe++):se.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:H.skillId,skillName:H.skillName,err:String(C.reason)}))}oe>0&&(F.skills=Z,se.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:X.length}))}return await je(F,this.paths),se.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:E,framework:e.framework}}catch(T){throw se.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),se.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:u.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await UE(u.root,{recursive:!0,force:!0}).catch(P=>se.warn("rm agent dir failed (ignored)",{err:String(P)})),T instanceof k?T:new k("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"&&Od(e.framework))f=VE;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`);Od(e.framework)&&!Cs(e.framework)&&(se.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await _r(e.framework));let p=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:p,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:f.path});else if(e.framework==="hermes"){let g={...this.buildBinShimPathEnv()};p&&(await T0({paths:this.paths,agentId:e.agentId,modelConfig:p,cozeEnv:o,mockScenario:a}),g.HERMES_HOME=rr(e.agentId,this.paths)),x=this.factory(e.framework,f.path,e.workspace,e.agentId,p,i,o,a,g)}else{let g=e.sessions.get(i),E=sn(e)?g?.permissionMode??Ch:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await WE(e.agentId,this.paths),x=this.factory(e.framework,f.path,e.workspace,e.agentId,p,i,o,a,this.buildBinShimPathEnv(),E,e.framework==="codex"&&e.deployType==="cloud"?on(Me(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await x.start(),await x.initialize(ZE),x}catch(g){let E=x instanceof bt?x.getStderrTail():[];throw E.length>0&&se.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:g instanceof k?g.code:"unknown",recentStderr:E}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,f.path,g)}}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 k("AGENT_ENV_NOT_READY",kh(o),{cause:{reason:Ah}})}catch(o){se.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};se.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 se.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:JE}})}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",kh(n),{cause:{reason:Ah}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:u,command:f}=e,p=Rd(o);if(n.deployType==="local"){let E=await this.ensureOpenclawDefaultAgent();return new Jr({command:f,cwd:E.workspace,agentId:E.id,sessionName:p})}let x=await Sh();try{let E=this.getOpenclawConfig();await E.ensureAcpDeviceScopes()&&await E.restartGateway()}catch(E){se.warn("acp device scope ensure failed (ignored)",{err:String(E)})}let g;if(i?.modelToken){let E=hd(o),y=pd(i),b=`${E}/${y}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(b)!==I){let A=this.getOpenclawConfig(),T=await A.getAllowlistModelsForProvider(E),P=v0(i,a,d,T,u);P&&(await A.ensureProvider(E,P),await A.addModelToAllowlist(b),this.ensuredProviders.set(b,I))}g=b}return new Jr({command:f,cwd:n.workspace,agentId:n.agentId,sessionName:p,...x?{gatewayToken:x}:{},...g?{slashModelOnStart:g}:{}})}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=hd(a),u=`${d}/${o}`,f=!0;try{await i.removeProvider(d)}catch(p){f=!1,se.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(p)})}try{await i.removeModelFromAllowlist(u)}catch(p){f=!1,se.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(p)})}f&&this.ensuredProviders.delete(u)}}};import{randomUUID as Nh}from"node:crypto";import{promises as iv}from"node:fs";import{basename as Mh}from"node:path";Ye();ie();import{promises as XE}from"node:fs";import{basename as QE}from"node:path";var Dh=q("file-upload"),ev="/api/coze_claw/file/agent_upload",tv=6e4;async function Rh(t,e={}){let i=`${zr(Ur(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",...Dn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,p=setTimeout(()=>f.abort(),o);Dh.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let x=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),g=x.headers.get("x-tt-logid")??"";if(!x.ok){let b=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${x.status} logid=${g}: ${b.slice(0,200)}`)}let E=await x.json();if(E.code!==void 0&&E.code!==0)throw new k("UPLOAD_FAILED",`upload code=${E.code} msg=${E.msg??"-"} logid=${g}`);let y=E.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${g}: ${JSON.stringify(E).slice(0,200)}`);return Dh.info("file upload ok",{uri:y,logid:g}),{uri:y}}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${QE(t.path)}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(p)}}Ye();ie();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 Oh(t){let e=nv(t).toLowerCase();return rv[e]??"application/octet-stream"}De();var Ko=q("agent-send"),Lh=50*1024*1024;function Bh(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 o=i.sessions.get(n);if(!o)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:o}}async function Fh(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(p){u=p,f<2&&(Ko.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(p)}),await new Promise(x=>setTimeout(x,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function zh(t,e){let{session:n,runtime:i}=Bh(e.core,t.agentId,t.sessionId);if(!await gi(t.path,n.workspace))throw new k("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 k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>Lh)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${Lh}`);let a=await Oh(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??Mh(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(p){throw Ko.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:p instanceof k?p.code:"UNKNOWN",message:p instanceof Error?p.message:String(p)}),p}let f={sessionUpdate:"agent_file",messageId:Nh(),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 Fh(e,n,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Ko.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 Uh(t,e){let{session:n,runtime:i}=Bh(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??Mh(t.path),a={sessionUpdate:"group_file",messageId:Nh(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Fh(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Ko.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 Hh(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}rn();ie();gn();var qt=q("coze-cli-installer"),Gh="@coze/cli@latest",sv="coze",qh="0.1.8",ov=5e3,av=5e3,cv=9e4,jh=1e4,is=null,$o=!1;async function Bd(t,e={}){if($o)return;if(is)return is;let n=e.exec??d0;return is=(async()=>{try{let i=await dv(sv,n),o=!1;if(i){let d=await lv(n);if(d===void 0)qt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(Hh(d,qh))qt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:qh}),o=!0;else{qt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),$o=!0;return}}let a=o?"upgrade-only":"full";qt.info("coze-cli install start",{package:Gh,mode:a});try{await n("npm",["i","-g","--prefer-online",Gh],{timeout:cv,maxBuffer:10*1024*1024}),qt.info("coze-cli install ok")}catch(d){qt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){$o=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:jh}),qt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){qt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:jh}),qt.info("coze auth login ok")}catch(d){qt.warn("coze auth login failed",{err:String(d)});return}$o=!0}finally{is=null}})(),is}async function dv(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:ov});return Ya(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}}Zt();Jt();De();var uv=10*6e4;function Wh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?uv:e}function Vo(t){return mn(t??Y().configFile)}function ss(t,e){return wn(e??Y().configFile,t)}import{randomBytes as Dv}from"node:crypto";gr();Ye();ie();import{createReadStream as fv}from"node:fs";import{mkdir as hv,readFile as pv,realpath as xv,stat as gv,writeFile as mv}from"node:fs/promises";import{basename as wv,dirname as Fd,isAbsolute as yv,join as _v,relative as bv,resolve as Kh,sep as Ev}from"node:path";import{createInterface as vv}from"node:readline";var Vh=q("fs-rpc"),os=Qe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Jh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>os)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${os} bytes`);let i=await Yh(t.path,e);return await hv(Fd(i),{recursive:!0}),await mv(i,t.content,"utf8"),Vh.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Zh(t,e){let n=await Yh(t.path,e),i=await gv(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>os&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${os} bytes`);let a;if(o&&i.size>os)a=await Sv(n,t.line??1,t.limit);else{let d=await pv(n,"utf8");if(o){let u=d.split(`
116
- `),f=Math.max(0,(t.line??1)-1),p=typeof t.limit=="number"?f+t.limit:void 0;a=u.slice(f,p).join(`
117
- `)}else a=d}return Vh.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(`
118
- `)}async function Yh(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([$h(Kh(e)),$h(Kh(t))]),o=bv(n,i);if(Iv(o,Ev,yv(o)))throw new k("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 $h(t){let e=[],n=t;for(;n!==Fd(n);)try{let i=await xv(n);return e.length?_v(i,...e.reverse()):i}catch{e.push(wv(n)),n=Fd(n)}return t}ie();var Xh=q("prompt-multimodal"),Qh=10*1024*1024,Av=15e3,kv=6;async function ep(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 tp(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||!Ki(e.uri))return t;try{let{buf:n,contentType:i}=await Pv(e.uri),o=e.mimeType||Cv(i)||"application/octet-stream";return Xh.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 Xh.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 Pv(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>Qh)throw new Error(`image too large: ${o.byteLength} bytes (max ${Qh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Zt();Ye();ie();var J=q("core"),Rv=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,Jo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Wr;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=Wh(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(),J.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){J.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),J.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){J.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)&&J.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)=>{J.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),Zr(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){J.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(On(o,{code:ee.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>J.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:ee.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){J.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:ee.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(Lo(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&&J.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=i0(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),J.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),J.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,ee.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):J.warn("drop notification: extension not registered",{method:e.method});return}let f=await u(e,this);n!==null&&await this.upstream.send(jr(n,f));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(jr(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(jr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,ee.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):J.warn("drop unknown notification",{method:e.method})}catch(u){J.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(On(n,ts(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 o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let 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 p=n._meta?.cozeTriggerMsgId,x=So(n._meta);return J.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,f,a,Lv,p,x)}}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{J.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}=o0(i);switch(n){case"session/new":{let a=Bv();return J.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return J.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 k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=sn(e)?s0(i._meta):void 0;if(u!==void 0&&!Gt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Td(e.framework)}`);let f=So(i._meta),p=this.requestSceneBySession.get(d),x=await this.ensureRuntime(e,d,f,p);if(u!==void 0&&x.permissionMode===void 0&&(x.permissionMode=u,await this.persistSessionMapping(e)),x.replySeq=0,await this.ensureDownstream(e,d,x),!x.downstream||!x.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&x.permissionMode!==void 0&&x.permissionMode!==u){let y=x.permissionMode;x.permissionMode=u,await this.persistSessionMapping(e);try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(b){throw x.permissionMode=y,await this.persistSessionMapping(e).catch(()=>{}),b}}let g=i._meta?.cozeTriggerMsgId;if(g?e.activeTriggers.set(x.acpSessionId,g):e.activeTriggers.delete(x.acpSessionId),f?e.activeGroupIds.set(x.acpSessionId,f):e.activeGroupIds.delete(x.acpSessionId),f&&x.cozeGroupId!==f&&(x.cozeGroupId=f,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&tp(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let E=await ep(a.prompt);try{let y=await x.downstream.sessionPrompt({...a,sessionId:x.acpSessionId,prompt:E});return x.lastActiveAt=Date.now(),y}catch(y){if(y instanceof k&&y.code==="AGENT_APPROVAL_TIMEOUT"){let b=x.pendingPermission;b&&(b.downstream.respondAgentRequest(b.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(b.upstreamId),x.pendingPermission=void 0);let I=x.acpSessionId,A=I?e.activeTriggers.get(I):void 0,T=I?e.activeGroupIds.get(I):void 0;return J.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,x,d,Nv,A,T)}throw y}finally{if(e.activeTriggers.delete(x.acpSessionId),e.activeGroupIds.delete(x.acpSessionId),x.pendingPermission=void 0,x.reloadAfterTurn){x.reloadAfterTurn=!1;let y=x.downstream;y&&(x.downstream=void 0,J.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:x.acpSessionId}),y.stop("reload-after-turn").catch(b=>J.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(b)})))}else x.downstream?.isAlive()&&this.armIdleTimer(e,d,x)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new 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&&(J.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=o,d=a.sessionId,u=a.modeId,f=So(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!sn(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(!Gt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Td(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let p=e.sessions.get(d)??await this.ensureRuntime(e,d);if(p.permissionMode===u)return{};let x=p.permissionMode;if(p.permissionMode=u,await this.persistSessionMapping(e),p.downstream?.isAlive()&&p.acpSessionId)try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(g){throw p.permissionMode=x,await this.persistSessionMapping(e).catch(()=>{}),g}else J.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 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 J.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};J.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,p=e.deployType==="cloud"&&a.tokenGroupId!==i,x=a.requestScene!==o;if(p&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),p||x){Zr(a);let g=a.downstream;a.downstream=void 0,g&&await g.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(f||p||x)&&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 sn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?I0:A0:u.permissionMode=e.framework==="claude-code"?Nd:Ph),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(_t.GEN_MODEL_TOKEN,o,Mv);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(Zr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&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 p=this.requestSceneBySession.get(n);p&&J.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:p}),f=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,p)}catch(p){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(J.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),p}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}),J.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId})}catch(p){J.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(p)}),i.acpSessionId=void 0;let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,await this.persistSessionMapping(e)}}catch(p){throw J.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(p)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,p}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),sn(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(p){J.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(p)})}}armIdleTimer(e,n,i){if(Zr(i),this.isRuntimeBusy(e,i)){J.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)){J.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}J.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=>J.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(qr("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(qr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>J.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){J.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){J.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Uv(n)){J.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"&&sn(e)){let x=d.currentModeId;Gt(e.framework,x)&&a.permissionMode!==x?(a.permissionMode=x,this.persistSessionMapping(e).catch(g=>J.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(g)}))):typeof x=="string"&&!Gt(e.framework,x)&&J.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:x})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let p=e.activeGroupIds.get(i);p&&(u.cozeGroupId=p),this.upstream.send(qr("session/update",{...n,sessionId:o,_meta:u})).catch(x=>J.warn("forward update failed",{agentId:e.agentId,err:String(x)}))}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}J.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:ee.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 Jh(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Zh(a,o);n.respondAgentRequest(i.id,d)}}catch(o){J.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,ts(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,p={cozeAgentId:e.agentId};f&&(p.cozeTriggerMsgId=f);let x=u?e.activeGroupIds.get(u):void 0;x&&(p.cozeGroupId=x);let g=u?this.reverseSessionId(e,u):void 0,E=g?e.sessions.get(g):void 0;E&&(E.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let y={...a,...g?{sessionId:g}:{},_meta:p};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:g}),J.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:g,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(b=>({optionId:b.optionId,kind:b.kind,name:b.name}))}),this.upstream.send(Qi(o,"session/request_permission",y)).catch(b=>{this.pendingUpstream.delete(o),J.error("forward permission request failed",{agentId:e.agentId,err:String(b)}),n.respondAgentRequestError(i.id,{code:ee.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?(J.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),J.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 Oo(e.error)):i.value.resolve(e.result);return}J.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 J.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=Rv){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(Qi(o,e,n)).catch(f=>{let p=this.pendingBridge.get(o);p&&(clearTimeout(p.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&&sn(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 mi(e.agentId,n,this.paths)}catch(n){J.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(On(e,{code:n,message:i,data:{bridgeVersion:Ht}}))}};function Bv(){return Dv(16).toString("hex")}function Fv(t,e){if(!t||typeof t!="object"){J.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){J.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"){J.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")&&J.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."],np="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(np)?i.text.slice(np.length):i.text;return zv.some(a=>o.startsWith(a))}Jt();ie();De();import{randomBytes as Hv}from"node:crypto";import{createServer as Gv}from"node:http";var qv=1e6,rp=q("ipc"),Zo=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??Y()}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(),rp.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 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}`){as(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){as(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await jv(e)}catch(u){as(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);as(n,200,u??{ok:!0})}catch(u){rp.error("IPC handler failed",{key:o,err:String(u)}),as(n,500,{error:u instanceof Error?u.message:String(u)})}}};function as(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=Vt(Xp(),1),u1=Vt(sa(),1),f1=Vt(ei(),1),h1=Vt(Jd(),1),p1=Vt(Xd(),1),x1=Vt(il(),1),ax=Vt(da(),1),g1=Vt(ox(),1);var cx=ax.default;Ye();ie();var{FWS:R1}=_x(),Fe=q("upstream.frontier"),Ex="application/json",vx="none",O1=15e3;function L1(t){class e extends cx{constructor(i){super(i,u0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Fe.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($l("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");Fe.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Fe.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var gs=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){Fe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:f0,...Dn(this.opts.ppeOverride)},n=L1(e),i=p0(this.opts.urlOverride),o={url:i,ws:n,fpID:l0,aID:Ao,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Ex,force:!0},payloadEncoding:{encoding:vx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new R1(o),d=!1,u=null,f,p,x=new Promise((y,b)=>{f=y,p=b}),g=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?p(y):f())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Fe.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&g();for(let b of this.connectHandlers)Promise.resolve(b({initial:y})).catch(I=>Fe.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=y=>{this.opened=!1,Fe.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},a.onerror=y=>{Fe.warn("frontier error",{code:y.code,msg:y.message}),g(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 E=this.opts.openTimeoutMs??O1;u=setTimeout(()=>{g(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${E}ms (handshake or upgrade slow)`))},E),await a.connect();try{await x}catch(y){try{a.close(1e3,"open failed")}catch(b){Fe.warn("fws close during start failure threw (ignored)",{err:String(b)})}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){Fe.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Fe.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?(Fe.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 o=JSON.stringify(e),a=e;Sx(a)||Fe.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:Ex,payloadEncoding:vx})}catch(u){throw Fe.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 o=n(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Fe.debug("drop non-adapter frontier frame",{service:n});return}let i=B1(e);if(!i){Fe.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Fe.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Fe.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;Sx(a)||Fe.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=>Fe.warn("frontier frame handler threw",{err:String(d)}))}};function Sx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Ix=2e3;function N1(t){return t.length<=Ix?t:`${t.slice(0,Ix)}...<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}}Ye();ie();var cl=q("skill-publish"),F1="/api/marketplace/product/skill/publish_with_assets",z1=15e4;async function Ax(t,e={}){let i=`${zr(Ur(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",...Dn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);cl.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let p=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),x=p.headers.get("x-tt-logid")??"";if(!p.ok){let y=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${p.status} logid=${x}: ${y.slice(0,200)}`)}let g=await p.json();if(cl.info("skill publish response",{logid:x,httpStatus:p.status,code:g.code,msg:g.msg,dataSkillId:g.data?.skill_id??"",dataVersion:g.data?.version??""}),g.code!==void 0&&g.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${g.code} msg=${g.msg??"-"} logid=${x}`);let E={};return g.data?.skill_id!==void 0&&g.data.skill_id!==""&&(E.skillId=String(g.data.skill_id)),g.data?.version&&(E.version=g.data.version),cl.info("skill publish ok",{logid:x,skillId:E.skillId??"",version:E.version??""}),E}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(f)}}ie();var dl=q("upstream.switchable"),wa=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;dl.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 dl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>dl.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()}};ie();var ll=q("upstream"),oi=class{handler=null;async start(){ll.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){ll.info("NoopUpstream stopped",{reason:e})}async send(e){ll.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)}};Ye();ie();Jt();ie();De();import{promises as U1}from"node:fs";var kx=q("pat-token-store");async function ya(t=Y()){try{let n=(await U1.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(kx.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"&&kx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ms(t,e=Y()){if(!t)throw new Error("writePatToken: empty patToken");await mt(e.patTokenFile,t,{mode:384})}De();De();import{promises as _a}from"node:fs";import{join as H1}from"node:path";function G1(t,e){return`#!/bin/sh
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(`
117
+ `),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
119
120
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
120
121
  `}function q1(t,e){return`@echo off\r
121
122
  "${e}" "${t}" %*\r
122
- `}async function Tx(t,e=Y()){let n=e.binDir;await _a.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 _a.readFile(i,"utf8").catch(()=>null)===a||(await _a.writeFile(i,a,"utf8"),process.platform!=="win32"&&await _a.chmod(i,493)),n}ie();De();import{execSync as Cx}from"node:child_process";import{readFileSync as Px,unlinkSync as j1}from"node:fs";import{mkdir as W1,open as K1,readFile as Dx,unlink as ul,writeFile as $1}from"node:fs/promises";import{dirname as V1}from"node:path";var J1=q("single-instance"),Z1=t=>new Promise(e=>setTimeout(e,t)),ba=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Y().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>ns(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&&J1.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 Dx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await ul(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 Dx(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 Z1(this.claimLockIntervalMs);continue}await ul(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await ul(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=Px(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Kr)||n.includes("lib/index.js"))}catch{}try{let n=Cx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Kr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Cx(`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{Px(this.pidFile,"utf8").trim()===String(this.selfPid)&&j1(this.pidFile)}catch{}})}};Ea();ie();var ur=q("daemon.upstream-watchdog"),iI=12e4,sI=9e5,oI=3e4;function hl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var va=class{constructor(e){this.opts=e;this.softMs=e.softMs??hl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",iI),this.hardMs=e.hardMs??hl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",sI),this.intervalMs=e.intervalMs??hl("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?.(),ur.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&&ur.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&&ur.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,ur.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){ur.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,ur.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>ur.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var W=q("daemon");async function Lx(){let t=Y();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Wl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>Me(C,t).logs,listAgentIds:()=>Ps(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
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
123
124
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
124
125
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
125
- `)}catch{}}let e=new ba({processTitle:Kr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Vo(),o=i??{};As({pid:process.pid}),W.info(i?"loaded bridge config":"initialized bridge config");let a=new wa(new oi),d=null,u=new Jo({upstream:a,paths:t,bridgeConfig:o,sessionSpawner:async(C,H,j,re,qe,me)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(C,H,j,re,qe,me)}}),f=new Wo({paths:t,config:o,registry:u});d=f;let p,x,g=null,E={},y,b=null,I=null,A=null,T=new Ln;function P(C,H){return T.enqueue(()=>D(C,H))}function _(){I||(I=new va({isConnected:()=>a.isConnected()&&!(b?.isLivenessLost()??!1),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:C=>{if(process.env[ws]==="1"){W.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}W.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),I.start()}async function D(C,H){let j=C,re=j?.privatecode;if(!re)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let qe=Ji(j.env),me=j.handshake_url,_e=j.frontier_url,Ot=Ox(j.env,me,_e);if(A=j,!H?.force&&p===re&&x===Ot){let ve=await aI(t);return u.agents.size===0&&ve?(W.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ia(t,f).catch(Le=>W.warn("connect-noop auto-revive error (ignored)",{err:String(Le)}))):W.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let St=!!p&&p!==re,fn=x!==void 0&&x!==Ot,$t=St||fn,hn=await ld({privatecode:re,...me?{endpoint:me}:{},ppeOverride:qe});if($t){W.warn("connect config switched, resetting agents",{pcChanged:St,envChanged:fn,previousPc:p?Sa(p):"",nextPc:Sa(re)});for(let ve of[...u.agents.values()])await ve.dispose("connect config switch").catch(()=>{}),u.agents.delete(ve.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new oi,"connect switch").catch(()=>{})}g=hn.deviceId,As({deviceId:g,pid:process.pid}),Bd({patToken:re,env:j.env}).catch(ve=>W.warn("coze-cli setup error (ignored)",{err:String(ve)}));let ui=new gs({handshake:hn,privatecode:re,..._e?{urlOverride:_e}:{},ppeOverride:qe,getPatTokenForAgent:ve=>u.agents.get(ve)?.patToken});return await a.swap(ui,"connect"),p=re,x=Ot,E=qe,y=me,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),W.info("mock scenario set",{scenario:j.mock_scenario})),b||(b=new Xi({core:u,getDeviceId:()=>g??"",onTickEnd:()=>F.retryPending().catch(ve=>W.warn("detailSync.retryPending failed (ignored)",{err:String(ve)})),onAuthFailures:X})),b.start(),_(),$t&&Ia(t,f).catch(ve=>W.warn("post-connect-switch auto-revive error (ignored)",{err:String(ve)})),ms(re,t).catch(ve=>W.warn("writePatToken after /connect failed (ignored)",{err:String(ve)})),W.info("/connect: WS established",{deviceId:g}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async C=>f.createAgent(C.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let R={},z=new Po({agents:u.agents,paths:t,publishSkillToMarketplace:async C=>{let H=u.agents.get(C.agentId)?.patToken??p;if(!H)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Ax({patToken:H,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:y,ppeOverride:E})},disposeAndMarkDisconnected:async(C,H)=>{let j=u.agents.get(C);if(j){await f.cleanupOpenclawSessionProviders(j).catch(qe=>W.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(qe)})),j.framework==="hermes"&&j.deployType==="cloud"&&await md(C,t).catch(qe=>W.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(qe)}));let re=!0;try{await j.dispose(`disconnect: ${H}`)}catch(qe){re=!1,W.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(qe)}),j.status="error"}re&&(j.status="disconnected",u.unregister(C),u.disconnectedAgents.add(C))}else u.disconnectedAgents.add(C)},disposeForDelete:async(C,H)=>{let j=u.agents.get(C);j&&(await f.cleanupOpenclawSessionProviders(j).catch(re=>W.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(re)})),j.framework==="hermes"&&j.deployType==="cloud"&&await md(C,t).catch(re=>W.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(re)})),await j.dispose(`delete: ${H}`).catch(re=>W.warn("dispose during delete failed (ignored)",{agentId:C,err:String(re)})),u.unregister(C)),u.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!R.ref)throw new Error("agent-detail-sync not initialized yet");await R.ref.syncOne(C)},cleanupOpenclawProviders:async(C,H)=>{await f.cleanupOpenclawSessionProviders(C,H)},openclawRepair:async(C,H)=>{await f.openclawRepair(C,H)},hermesReset:async(C,H)=>{let j=await ke(C).catch(()=>null);!j||j.framework!=="hermes"||j.deployType!=="cloud"||await k0({paths:t,agentId:C,model:j.model,modelInfo:j.modelInfo,cozeEnv:H,mockScenario:u.getMockScenario()})},isRuntimePendingPermission:C=>u.hasPendingPermissionFor(C)});u.registerExtension("_agent/listSkills",C=>z.listSkills(C.params)),u.registerExtension("_agent/addSkills",C=>z.addSkills(C.params)),u.registerExtension("_agent/removeSkills",C=>z.removeSkills(C.params)),u.registerExtension("_agent/publishSkill",C=>z.publishSkill(C.params)),u.registerExtension("_agent/getFileTree",C=>z.getFileTree(C.params)),u.registerExtension("_agent/getFileContent",C=>z.getFileContent(C.params)),u.registerExtension("_agent/update",C=>z.updateAgent(C.params)),u.registerExtension("_agent/disconnect",C=>z.disconnectAgent(C.params)),u.registerExtension("_agent/switchModel",C=>z.switchModel(C.params)),u.registerExtension("_agent/reset",C=>z.resetAgent(C.params)),u.registerExtension("_agent/repair",C=>z.repairAgent(C.params)),u.registerExtension("_agent/delete",C=>z.deleteAgent(C.params)),u.registerExtension("_agent/upgrade",C=>z.upgradeBridge(C.params));let F=new Os({paths:t,handlers:z,agentManager:f,sendDetail:C=>u.sendRequest("_agent/detail",C)});R.ref=F;let X=async C=>{await Promise.allSettled(C.map(async H=>{try{await z.disconnectAgent({agentId:H.agentId,reason:`auth_failure: code=${H.code} ${H.message}`}),W.info("agent disconnected due to auth failure from heartbeat response",{agentId:H.agentId,code:H.code,message:H.message})}catch(j){W.warn("disconnect during authFailure handling failed (ignored)",{agentId:H.agentId,err:String(j)})}}))};a.onConnect(({initial:C})=>{W.info("frontier upstream connected, triggering detail sync",{initial:C}),F.syncAll(C?"initial-connect":"reconnect").catch(H=>W.warn("detail sync top-level error (ignored)",{err:String(H)}))});let Z=new Zo({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[ws]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:g??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let H=C,j=H?.privatecode,re=H?.pairing_code;if(!j||!re)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let qe=Ji(H.env),me=H.handshake_url,_e=H.frontier_url,Ot=Ox(H.env,me,_e),St=!!p&&p!==j,fn=x!==void 0&&x!==Ot,$t=St||fn,hn=await ld({privatecode:j,...me?{endpoint:me}:{},ppeOverride:qe});if($t){W.warn("pair config switched, resetting agents",{pcChanged:St,envChanged:fn,previousPc:p?Sa(p):"",nextPc:Sa(j),previousEnvKey:x??"",nextEnvKey:Ot});for(let Le of[...u.agents.values()])await Le.dispose("pair config switch").catch(()=>{}),u.agents.delete(Le.agentId);u.disconnectedAgents.size>0&&(W.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await a.swap(new oi,"pair switch").catch(()=>{})}g=hn.deviceId,As({deviceId:g,pid:process.pid}),Bd({patToken:j,env:H.env}).catch(Le=>W.warn("coze-cli setup error (ignored)",{err:String(Le)}));let ui=new gs({handshake:hn,privatecode:j,..._e?{urlOverride:_e}:{},ppeOverride:qe,getPatTokenForAgent:Le=>u.agents.get(Le)?.patToken});await a.swap(ui,"pair");try{let Le=new ir;o.frameworksCache=await Le.detectAll(),await ss(o),W.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Le){W.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Le)})}let ve=Object.keys(o.frameworksCache??{});try{let Le=await u.sendRequest("_agent/pair",{pairCode:re,patToken:j,frameworks:ve,_meta:{cozeDeviceId:g}});W.info("_agent/pair ok",{pairResult:Le}),p=j,x=Ot,E=qe,y=me,H.mock_scenario!==void 0&&(u.setMockScenario(H.mock_scenario),W.info("mock scenario set",{scenario:H.mock_scenario})),ms(j,t).catch(Ue=>W.warn("writePatToken after /pair failed (ignored)",{err:String(Ue)})),b||(b=new Xi({core:u,getDeviceId:()=>g??"",onTickEnd:()=>F.retryPending().catch(Ue=>W.warn("detailSync.retryPending failed (ignored)",{err:String(Ue)})),onAuthFailures:X})),b.start(),_(),$t&&Ia(t,f).catch(Ue=>W.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ue)}));let fr;return H.agent_id&&(fr=await dI(H.agent_id,t,f,Ue=>u.sendRequest("_agent/detail",Ue),j).catch(Ue=>(W.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(Ue)}),{ok:!1,agentId:H.agent_id??"",note:String(Ue)}))),{ok:!0,note:"paired with cloud",...fr?{agent:fr}:{}}}catch(Le){return W.error("_agent/pair failed",{err:String(Le)}),{ok:!1,note:`pair failed: ${String(Le)}`}}}},{method:"POST",path:"/connect",handler:C=>P(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let H=C;return{ok:!0,result:await f.createAgent(H)}}},{method:"POST",path:"/agent/send",handler:async C=>{let H=C;if(!H?.agentId||!H?.sessionId||!H?.kind||!H?.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 j=H;return await(j.groupFile?Uh:zh)(j,{core:u,patToken:p,handshakeBase:y,ppeOverride:E})}catch(j){if(j instanceof k)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async C=>{let H=C?.agent_id,j=await u.reloadAgents(H);return W.info("IPC /reload: recycled agent subprocesses",{agentId:H??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(W.info("IPC /shutdown received"),setImmediate(()=>{le.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ce,token:te}=await Z.start();try{await Tx(t.libEntry,t)}catch(C){W.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 ir().detectAll(),await ss(o),o.frameworksCache)}).catch(C=>W.warn("startup warmup error (ignored)",{err:String(C)})),tu().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(gn(),Ql));for(let H of["claude-code","codex"]){let j=await C(H);j&&W.info("acp wrapper version",{framework:H,version:j})}}).catch(C=>W.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let oe=null,le={port:ce,token:te,core:u,ipc:Z,shutdown(C){return oe||(W.info("daemon shutdown",{reason:C}),oe=(async()=>{b?.stop(),I?.stop(),await u.stop(C),await Z.stop(),await e.release()})(),oe)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{le.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>th()),process.on("unhandledRejection",C=>{W.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{W.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)}),W.info("daemon ready",{port:ce,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),fI({cliSpawned:process.env[ws]==="1",readPatToken:()=>ya(t),connect:P}).catch(C=>W.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),le}async function aI(t){return Ps(t).length>0}function Sa(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Ox(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function cI(t,e){let n=Ps(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(Zt(),Rs));for(let a of n){await o(a,t).catch(d=>W.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),W.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),W.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){W.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(()=>(Zt(),Rs)),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`);W.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let x=Nx(d),g={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...x?{_meta:x}:{}};return await n.createAgent(g),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}W.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let 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 p=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:p?"cloud agent acknowledged":"created from cloud detail"}}async function lI(t){let e=t.logger??W;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 Ia(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 Ia(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(()=>(Zt(),Rs));W.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(p){W.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(p)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){W.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){W.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{W.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let p=Nx(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...p?{_meta:p}:{}},{revive:!0}),a+=1}catch(p){W.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(p)}),d+=1}}return W.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 q0(o,t)).status==="refreshed"&&(i+=1)}catch(a){W.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(a)})}return i>0&&W.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??W;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 Nx(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Ea();De();import{readFile as Mx}from"node:fs/promises";var un=class{paths;constructor(e){this.paths=e??Y()}async probe(e=1e3){let n=await Aa(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:pI(i)}}}async request(e){let n=await Aa(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 Aa(t){try{let[e,n]=await Promise.all([Mx(t.portFile,"utf8"),Mx(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 pI(t){return t instanceof Error?t.message:String(t)}rn();ie();gr();import{spawn as xI}from"node:child_process";import{userInfo as Fx}from"node:os";var pl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",gI=new Set(["bash","zsh","sh","dash","ksh"]),Bx=Qe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),mI=2e3;function wI(t,e=pl){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(`
127
- `)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function yI(){let t=(process.env.SHELL??"").trim()||(Fx().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return gI.has(e)?t:null}function _I(t){return new Promise(e=>{let n=`printf '%s' '${pl}'; env; printf '%s' '${pl}'`,i;try{i=xI(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Fx().homedir}})}catch{e(null);return}let o="",a=!1,d=x=>{try{i.pid&&process.kill(-i.pid,x)}catch{}},u=x=>{a||(a=!0,clearTimeout(f),clearTimeout(p),e(x))};i.stdout?.on("data",x=>{o+=x.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),Bx),p=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},Bx+mI)})}async function xl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=yI();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??_I)(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}}De();function Bn(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}}gn();import{chmod as bI,copyFile as zx,mkdir as Hx,readFile as _s,rename as Ux,rm as wl,stat as Gx,writeFile as EI}from"node:fs/promises";import{homedir as aL}from"node:os";import{dirname as vI,join as ze,resolve as yl,sep as ys}from"node:path";import{fileURLToPath as SI}from"node:url";rn();ie();De();function ai(t,e,n,i){ct(t.bridgeLogsDir,e,"dist-install",n,i)}function qx(){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:ze("vendor","aarch64-apple-darwin","bin","codex"),x64:ze("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:ze("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:ze("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:ze("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:ze("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function AI(t){let e=SI(t),n=vI(e),i=`${ys}src${ys}`;if(n.includes(i)||n.endsWith(`${ys}src${ys}cli`))return null;let o=yl(n,"index.js"),a=yl(n,"..","package.json");return{dist:o,pkgJson:a}}async function _l(t={}){let e=t.paths??Y(),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 _s(o,"utf8"));a=b.version??"unknown",d=b.dependencies??{}}catch(b){throw ai(e,"error","cannot read source package.json",{err:String(b)}),new Error(`cannot read source package.json: ${String(b)}`,{cause:b})}let u=Ts.map(b=>({name:b,spec:d[b]??"latest"})),f=u.map(({name:b,spec:I})=>`${b}@${I}`),p=await Vo(e.configFile)??{},x=p.libVersion,g=await _s(e.libEntry).then(()=>!0).catch(()=>!1),E=x===a,y=await jx(e,u);if(E&&g&&y)return{kind:"already-current",libVersion:a};if(!E||!g){await Hx(e.libDir,{recursive:!0}),await zx(i,e.libEntry),await zx(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let b=yl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
128
- `;await _s(b,"utf8").catch(()=>null)!==I&&await EI(b,I)}return y||(t.installWrappers?await t.installWrappers(e,f):await CI(e,f,u)),p.libVersion=a,await ss(p,e.configFile),ai(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:x,toVersion:a}),E&&g?{kind:"already-current",libVersion:a}:x?{kind:"version-changed",fromVersion:x,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function jx(t,e){for(let n of e){let i=ze(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await _s(i,"utf8"))}catch(d){return ai(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 ai(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!kI(a,n.spec))return ai(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await Wx(ze(t.libDir,"node_modules"))}function kI(t,e){let n=gl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=gl(i.slice(1));if(!a)return!0;if(ml(n,a)<0)return!1;let d=TI(a);return ml(n,d)<0}let o=gl(i);return o?ml(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 gl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function ml(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 RI(t.installLock,async()=>{if(await jx(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ys}.staging-${process.pid}-${i}`,a=ze(o,"node_modules"),d=ze(t.libDir,"node_modules");try{await Hx(o,{recursive:!0}),await PI(e,o),await DI(a);let u=`${d}.trash-${i}`;await Ux(d,u).catch(()=>{}),await Ux(a,d),await wl(u,{recursive:!0,force:!0}).catch(()=>{}),ai(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await wl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function PI(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=lt("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 DI(t){for(let e of Ts){let n=ze(t,...e.split("/")),i=JSON.parse(await _s(ze(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=ze(t,".bin",o),d=await Gx(a);process.platform!=="win32"&&!(d.mode&73)&&await bI(a,d.mode|73).catch(()=>{})}if(!await Wx(t)){let e=qx()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function Wx(t){let e=qx(),n=II();if(!e||!n)return!0;let i=ze(t,"@openai","codex"),o=ze(t,...e.split("/")),a=[ze(i,"package.json"),ze(i,"bin","codex.js"),ze(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),ze(o,"package.json"),ze(o,n)];return(await Promise.all(a.map(u=>Gx(u).then(f=>f.isFile()).catch(()=>!1)))).every(Boolean)}async function RI(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 wl(t,{force:!0}).catch(()=>{})}}$a();ie();De();import{closeSync as $x,fstatSync as Vx,openSync as Jx,readFileSync as OI,readSync as LI,readdirSync as NI,statSync as MI}from"node:fs";import{join as ka}from"node:path";var BI=new Set(["debug","info","warn","error"]);function Zx(t){let e=t,n=Bn(e,"--agent-id");e=n.rest;let i=Bn(e,"--date");e=i.rest;let o=Bn(e,"-n","--lines");e=o.rest;let a=Bn(e,"--level");e=a.rest;let d=Bn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,p=a.value&&BI.has(a.value)?a.value:void 0,x={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(x.agentId=n.value),i.value&&(x.date=i.value),p&&(x.level=p),d.value&&(x.grep=d.value),x}function FI(t,e){return t.agentId?ka(Me(t.agentId,e).logs,mr("agent",t.date)):ka(e.bridgeLogsDir,mr("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=Ka(o,e);if(!a)continue;let d=0;try{d=MI(ka(t,o)).size}catch{}i.push({file:ka(t,o),date:a,size:d})}return i.sort((o,a)=>a.date.localeCompare(o.date)),i}function Yx(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"&&!Vl(n,e.level))return!1}return!0}var Kx={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 Xx(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&&Kx[o]&&(a=`\x1B[${Kx[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(([p])=>!HI.has(p)).map(([p,x])=>` ${p}=${typeof x=="string"?x:JSON.stringify(x)}`).join("");return`${i} ${a} ${d} ${u}${f}`}function qI(t,e,n){let a=OI(t,"utf8").split(`
129
- `).filter(d=>d.length>0).filter(d=>Yx(d,{level:e.level,grep:e.grep}));for(let d of zI(a,e.lines))process.stdout.write(`${Xx(d,{raw:e.raw,color:n})}
130
- `)}async function Qx(t,e){let n=e.paths??Y(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Me(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}
131
- `),1;for(let p of f)process.stdout.write(`${p.date} ${(p.size/1024).toFixed(1)}KB ${p.file}
132
- `);return 0}let o=t.date??zn(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}
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}
132
+ `),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}
133
134
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
134
135
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
135
- `),1}return t.follow&&await KI(a,t,i),0}var jI=500;function WI(t){try{let e=Jx(t,"r");try{return Vx(e).size}finally{$x(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=Jx(t,"r");try{let p=Vx(f).size;if(p>i){let x=Buffer.allocUnsafe(p-i),g=LI(f,x,0,x.length,i);u=x.subarray(0,g).toString("utf8"),i+=g}}finally{$x(f)}}catch{}if(u){let f=(o+u).split(`
136
- `);o=f.pop()??"";for(let p of f)p.length>0&&Yx(p,{level:e.level,grep:e.grep})&&process.stdout.write(`${Xx(p,{raw:e.raw,color:n})}
137
- `)}await new Promise(f=>setTimeout(f,jI))}}finally{process.off("SIGINT",d)}}import{basename as $I,resolve as VI}from"node:path";De();var JI=9e4,ZI={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 ZI[t]??1}async function eg(t,e={}){let n=e.paths??Y();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>
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>
138
139
  `),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.
139
- `),3;let i=await Aa(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 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,JI)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
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)}
141
142
  `),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
142
143
  `),YI(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
143
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})
144
145
  `)}else process.stdout.write(`Sent ${t.kind} ${d} (${QI(a.bytes)})
145
- `)}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 lg=q("cli");function Ze(t,e){let{value:n,rest:i}=Bn(t,e);return{value:n,rest:i}}function Oa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
146
- `)}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:P}=Ze(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return SA(e.slice(1));if(e[0]==="log")return{mode:"log",...Zx(e.slice(1))};if(e[0]==="connect")return IA(e.slice(1));if(e.includes("--status"))return Oa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Oa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Oa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Oa("--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:p,rest:x}=Ze(n,"--handshake-url");n=x;let{value:g,rest:E}=Ze(n,"--frontier-url");n=E;let{value:y,rest:b}=Ze(n,"--mock-scenario");n=b;let{value:I}=Ze(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),p&&(T.handshakeUrl=p),g&&(T.frontierUrl=g),y&&(T.mockScenario=y),I&&(T.agentId=I),A&&(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:p}=Ze(i,"--agent-id");i=p;let{value:x,rest:g}=Ze(i,"--session-id");i=g;let{value:E,rest:y}=Ze(i,"--mime");i=y;let b=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return o&&(A.caption=o),d&&(A.name=d),f&&(A.agentId=f),x&&(A.sessionId=x),b&&(A.groupFile=!0),E&&(A.mimeType=E),A}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:p}=Ze(e,"--frontier-url");e=p;let{value:x,rest:g}=Ze(e,"--mock-scenario");e=g;let E=e.includes("--skip-rebuild-env"),y={mode:"connect"};return n&&(y.privatecode=n),o&&(y.env=o),d&&(y.handshakeUrl=d),f&&(y.frontierUrl=f),x&&(y.mockScenario=x),E&&(y.skipRebuildEnv=!0),y}var AA=`
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=`
147
148
  coze-bridge - local bridge daemon for cloud Agent Service
148
149
 
149
150
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -224,52 +225,52 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
224
225
 
225
226
  Internal:
226
227
  <node> <entry> --daemon daemon mode (OS supervisor only)
227
- `.trimStart();async function ug(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(`${Ht}
228
- `),0;case"daemon":{try{await Lx()}catch(i){return lg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return kA(e);case"stop":return hg(e);case"reload":return PA(n.agentId,e);case"log":return Qx(n,e);case"update":return TA(e);case"purge":return RA(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 eg({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 fg(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??Y(),n=new un(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 fg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
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)
230
231
  `),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
231
232
  ${JSON.stringify(o.body,null,2)}
232
- `),0}async function hg(t){let e=t.paths??Y(),n=new un(e),i=t.daemonSweep??(async()=>{let f=nh();return await rh(f),f}),o=async()=>{t.skipProcessKill||await i(e)},a=await Es(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
+ `),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)}
233
234
  `)}let u=await n.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
234
235
  `:`coze-bridge: not running
235
- `),0;if(u.kind==="stale")return await fg(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
236
+ `),0;if(u.kind==="stale")return await lg(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
236
237
  `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
237
238
  `),0}catch(f){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
238
239
  `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
239
- `),1)}}async function TA(t){return await hg(t),(t.spawnNpx??CA)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function CA(t){return new Promise(e=>{let n=lt("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 PA(t,e){let n=new un(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
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)
241
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)
242
243
  `):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
243
244
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
244
245
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
245
- `),1}}async function Es(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(()=>(ag(),og)),i=e(),o=n();return{platform:i.platform,install:a=>i.install(o,a),uninstall:()=>i.uninstall(o)}}async function pg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??BA,a=t.paths??Y();if(n.kind==="connected"){if(!DA(n.body))return n;ct(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=>ct(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(f)})),await dg(a.pidFile,o)}let d=t.spawnDaemon??Rx,u=await Es(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await cg(e,i,o);if(f.kind==="connected")return f;ct(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){ct(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}ct(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,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)}
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)}
246
247
  `));return process.stdout.write(`coze-bridge: starting daemon...
247
- `),await d({paths:t.paths}),cg(e,i,o)}function DA(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.nodeExecPath!="string"||typeof e.nodeArch!="string"?!1:e.nodeExecPath!==process.execPath||e.nodeArch!==process.arch}async function RA(t){let e=new un(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping 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...
248
249
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
249
- `)}await new Promise(d=>setTimeout(d,500))}let i=await Es(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
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
250
251
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
251
- `)}let o=t.paths??Y(),{rm:a}=await import("node:fs/promises");try{await a(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
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}
252
253
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
253
254
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
254
- `),0}async function OA(t){let e=await Es(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
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...
255
256
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
256
257
  `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
257
- `),1}}async function LA(t){let e=await Es(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
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
258
259
  `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
259
- `),1}}async function xg(t,e,n){if(e)return ct(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(ct(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(ct(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
260
- `),ct(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 un(n.paths),u=n.paths??Y(),f=await xg(u,a,n.reconstructEnv??xl);if(await dd(u,f).catch(g=>ct(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(g)})),!n.skipDistInstall){let g=await _l({paths:n.paths});g.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${g.fromVersion} \u2192 ${g.toVersion}
261
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):g.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${g.libVersion}
262
- `)}let p=await pg(n,d);if(p.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${p.kind}
263
- `),1;let x={privatecode:t,pairing_code:e};i.env&&(x.env=i.env),i.handshakeUrl&&(x.handshake_url=i.handshakeUrl),i.frontierUrl&&(x.frontier_url=i.frontierUrl),i.mockScenario&&(x.mock_scenario=i.mockScenario),o&&(x.agent_id=o);try{let g=await d.request({method:"POST",path:"/pair",body:x,timeoutMs:35e3});if(g.status===200&&g.body?.ok){let E=g.body.agent;return E&&!E.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${E.agentId}): ${E.note}
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}
264
265
  `),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"
265
- `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(g.body)}
266
- `),1}catch(g){return process.stderr.write(`coze-bridge: pair failed: ${String(g)}
267
- `),1}}async function MA(t,e,n={},i){let o=e.paths??Y(),a=t??await ya(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 un(e.paths),u=await xg(o,i,e.reconstructEnv??xl);if(await dd(o,u).catch(x=>ct(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(x)})),!e.skipDistInstall){let x=await _l({paths:e.paths});x.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${x.fromVersion} \u2192 ${x.toVersion}
268
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(E=>setTimeout(E,500)))):x.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${x.libVersion}
269
- `)}let f=await pg(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
270
- `),1;let p={privatecode:a};n.env&&(p.env=n.env),n.handshakeUrl&&(p.handshake_url=n.handshakeUrl),n.frontierUrl&&(p.frontier_url=n.frontierUrl),n.mockScenario&&(p.mock_scenario=n.mockScenario);try{let x=await d.request({method:"POST",path:"/connect",body:p,timeoutMs:35e3});return x.status===200&&x.body?.ok?(process.stdout.write(`coze-bridge: connected (${x.body.note??"ok"})
271
- `),t!==void 0&&await ms(a,o).catch(g=>lg.warn("writePatToken after connect failed (ignored)",{err:String(g)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(x.body)}
272
- `),1)}catch(x){return process.stderr.write(`coze-bridge: connect failed: ${String(x)}
273
- `),1}}async function cg(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 dg(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||!ns(u))return;await e(i)}}function BA(t){return new Promise(e=>setTimeout(e,t))}ie();function FA(t){let e=/^v?(\d+)/.exec(t.trim());return e&&Number(e[1])<22?"fatal":"ok"}function gg(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
274
- `),n(1)}gg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Kl("warn");ug(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
266
+ `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(m.body)}
267
+ `),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}
271
+ `),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)}
273
+ `),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)}
275
276
  `),process.exit(1)});