coze-bridge 0.3.2-alpha.105 → 0.3.2-alpha.106

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 +98 -98
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var Rm=Object.create;var Ja=Object.defineProperty;var Om=Object.getOwnPropertyDescriptor;var Lm=Object.getOwnPropertyNames;var Mm=Object.getPrototypeOf,Nm=Object.prototype.hasOwnProperty;var xe=(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 ot=(t,e)=>()=>(t&&(e=t(t=0)),e);var le=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Za=(t,e)=>{for(var n in e)Ja(t,n,{get:e[n],enumerable:!0})},Bm=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lm(e))!Nm.call(t,s)&&s!==n&&Ja(t,s,{get:()=>e[s],enumerable:!(i=Om(e,s))||i.enumerable});return t};var Xt=(t,e,n)=>(n=t!=null?Rm(Mm(t)):{},Bm(e||!t||!t.__esModule?Ja(n,"default",{value:t,enumerable:!0}):n,t));function $e(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var _r=ot(()=>{"use strict"});import{createWriteStream as Fm,mkdirSync as zm,readdirSync as Um,unlinkSync as Hm}from"node:fs";import{join as Zl}from"node:path";function Hn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function yr(t,e){return`${t}-${e}.log`}function Ya(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Gm(t,e,n){let i=a=>{let[d,u,h]=a.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,h??1)};return Math.floor((i(e)-i(t))/864e5)>n}function As(t,e,n,i){let s;try{s=Um(t)}catch{return}for(let a of s){let d=Ya(a,e);if(d&&Gm(d,n,i))try{Hm(Zl(t,a))}catch{}}}var gi,Xa=ot(()=>{"use strict";gi=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>Hn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let n=this.clock();n!==this.currentDate&&this.rotate(n),this.stream?.write(e)}rotate(e){this.stream?.end();try{zm(this.dir,{recursive:!0});let n=Fm(Zl(this.dir,yr(this.prefix,e)),{flags:"a"});n.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var Mm=Object.create;var ec=Object.defineProperty;var Nm=Object.getOwnPropertyDescriptor;var Fm=Object.getOwnPropertyNames;var Bm=Object.getPrototypeOf,zm=Object.prototype.hasOwnProperty;var ge=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var ot=(t,e)=>()=>(t&&(e=t(t=0)),e);var fe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),tc=(t,e)=>{for(var n in e)ec(t,n,{get:e[n],enumerable:!0})},Um=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fm(e))!zm.call(t,o)&&o!==n&&ec(t,o,{get:()=>e[o],enumerable:!(i=Nm(e,o))||i.enumerable});return t};var en=(t,e,n)=>(n=t!=null?Mm(Bm(t)):{},Um(e||!t||!t.__esModule?ec(n,"default",{value:t,enumerable:!0}):n,t));function Je(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var vr=ot(()=>{"use strict"});import{createWriteStream as Hm,mkdirSync as qm,readdirSync as Gm,unlinkSync as jm}from"node:fs";import{join as tf}from"node:path";function jn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function Sr(t,e){return`${t}-${e}.log`}function nc(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Wm(t,e,n){let i=a=>{let[d,f,u]=a.split("-").map(Number);return Date.UTC(d??0,(f??1)-1,u??1)};return Math.floor((i(e)-i(t))/864e5)>n}function Ps(t,e,n,i){let o;try{o=Gm(t)}catch{return}for(let a of o){let d=nc(a,e);if(d&&Wm(d,n,i))try{jm(tf(t,a))}catch{}}}var Ei,rc=ot(()=>{"use strict";Ei=class{constructor(e,n,i){this.dir=e;this.prefix=n;this.opts=i;this.clock=i.clock??(()=>jn(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{qm(this.dir,{recursive:!0});let n=Hm(tf(this.dir,Sr(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&&As(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as qm,mkdirSync as jm}from"node:fs";import{join as Wm}from"node:path";function Xl(t){let e=t.retentionDays??Vm,n=t.clock??(()=>Hn(new Date));Cs={bridgeSink:new gi(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:s=>new gi(t.agentLogsDir(s),"agent",{retentionDays:e,clock:n})};let i=n();As(t.bridgeLogsDir,"bridge",i,e);for(let s of t.listAgentIds?.()??[])As(t.agentLogsDir(s),"agent",i,e)}function Jm(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Ql(t){Qa=t}function eu(t){return br[Qa]<=br[t]}function tu(t,e){let n=br[t];return n===void 0?!0:n>=br[e]}function Ts(t){Yl={...t}}function nu(t){let e=(u,h=2)=>String(u).padStart(h,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",s=Math.abs(n),a=e(Math.floor(s/60)),d=e(s%60);return`${Hn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function at(t,e,n,i,s){try{let a=`${JSON.stringify({ts:nu(new Date),level:e,module:n,msg:i,...s})}
11
- `;jm(t,{recursive:!0}),qm(Wm(t,yr("bridge",Hn(new Date))),a)}catch{}}function Zm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function ks(t,e,n,i,s){if(br[t]<br[Qa])return;let a=`${JSON.stringify({ts:nu(new Date),level:t,module:e,msg:n,...Yl,...i})}
12
- `;if(Cs){let d=Zm(s,i),u=d?Jm(Cs,d):Cs.bridgeSink;try{u.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?$m.write(a):Km.write(a)}function G(t,e){return{debug:(n,i)=>ks("debug",t,n,i,e),info:(n,i)=>ks("info",t,n,i,e),warn:(n,i)=>ks("warn",t,n,i,e),error:(n,i)=>ks("error",t,n,i,e),child:n=>G(`${t}.${n}`,e),forAgent:n=>G(t,n)}}var br,Qa,Km,$m,Yl,Vm,Cs,ne=ot(()=>{"use strict";_r();Xa();br={debug:10,info:20,warn:30,error:40},Qa=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Km=process.stdout,$m=process.stderr,Yl={},Vm=$e("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Cs=null});var k,Ve=ot(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,n,i){super(n),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var ou={};Za(ou,{ACP_WRAPPER_NPM_PACKAGES:()=>Ds,_resetAcpInstallerForTests:()=>nw,_setBinaryPathCacheForTests:()=>rw,buildAcpSpawn:()=>mi,ensureAcpInstalled:()=>Er,getAcpBinaryPath:()=>Rs,pickWhichLine:()=>nc,probeAcpVersion:()=>tw,resolveAcpCommand:()=>su});import{readFileSync as ru}from"node:fs";import{createRequire as Ym}from"node:module";import{dirname as Xm,resolve as Qm}from"node:path";function tc(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function nc(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=i=>e.find(s=>s.toLowerCase().endsWith(i));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}function ew(t){let e=iu.resolve(`${t.npmPackage}/package.json`),n=Xm(e),i=JSON.parse(ru(e,"utf8")),s=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!s)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return Qm(n,s)}async function Er(t,e){let n=ec[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=vr.get(t);if(i)return i;let s=tc(t);if(s)return vr.set(t,s),Ps.info("acp wrapper overridden by env",{framework:t,path:s}),s;try{let a=ew(n);return vr.set(t,a),Ps.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw Ps.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:n.npmPackage,err:String(a)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${n.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
- `),{cause:a})}}async function tw(t){let e=ec[t];if(e)try{let n=iu.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(ru(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Ps.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Rs(t){return vr.get(t)}function su(t,e){if(e)return e;let n=tc(t);if(n)return n;let i=Rs(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 mi(t,e,n){if(e)return{command:e,args:[...n]};let i=tc(t);if(i)return{command:i,args:[...n]};let s=su(t);return{command:process.execPath,args:[s,...n]}}function nw(){vr.clear()}function rw(t,e){vr.set(t,e)}var Ps,ec,Ds,iu,vr,yn=ot(()=>{"use strict";Ve();ne();Ps=G("agents.acp-installer"),ec={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Ds=Object.values(ec).filter(t=>t!==void 0).map(t=>t.npmPackage),iu=Ym(import.meta.url),vr=new Map});import{chmod as sw,mkdir as ow,readFile as aw,rename as cw,rm as dw,writeFile as lw}from"node:fs/promises";import{dirname as uw}from"node:path";async function Ze(t){try{let e=await aw(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function _t(t,e,n){await ow(uw(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await lw(i,e,{encoding:"utf8",mode:n?.mode}),await cw(i,t),n?.mode!==void 0&&await sw(t,n.mode)}catch(s){throw await dw(i,{force:!0}).catch(()=>{}),s}}async function ft(t,e,n){await _t(t,`${JSON.stringify(e,null,2)}
14
- `,n)}var Ct=ot(()=>{"use strict"});import{promises as du,readdirSync as fw}from"node:fs";import{homedir as hw}from"node:os";import{sep as xw,join as ke,resolve as lu}from"node:path";function Z(t){let e=t??hw(),n=ke(e,".coze"),i=ke(n,"bridge"),s=ke(i,"lib"),a=ke(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:s,libEntry:ke(s,"index.js"),binDir:ke(i,"bin"),pidFile:ke(i,"bridge.pid"),portFile:ke(i,"bridge.port"),tokenFile:ke(i,"bridge.token"),patTokenFile:ke(i,"pat-token"),agentEnvFile:ke(i,"agent-env.json"),logFile:ke(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:ke(a,"daemon-stdio.log"),installLock:ke(i,"install.lock"),configFile:ke(i,"config.json"),modelCacheFile:ke(i,"model-cache.json"),agentsRoot:ke(n,"agents")}}function De(t,e=Z()){let n=ke(e.agentsRoot,t);return{root:n,config:ke(n,"config.json"),workspace:ke(n,"workspace"),logs:ke(n,"logs")}}function Os(t=Z()){try{return fw(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function wi(t,e){let n=await du.realpath(lu(t)).catch(()=>null);if(!n)return!1;let i=await du.realpath(lu(e)).catch(()=>null);if(!i)return!1;let s=process.platform==="win32"?n.toLowerCase():n,a=process.platform==="win32"?i.toLowerCase():i;return s===a||s.startsWith(a+xw)}var Ce=ot(()=>{"use strict"});var Ms={};Za(Ms,{AGENT_CONFIG_FILE_MODE:()=>Ls,enforceAgentConfigMode:()=>mw,loadAgentConfig:()=>ge,persistAgentSessions:()=>_i,persistAgentSkills:()=>yi,saveAgentConfig:()=>Re});import{chmod as pw,stat as gw}from"node:fs/promises";function ge(t,e){return Ze(De(t,e).config)}function Re(t,e){return ft(De(t.agentId,e).config,t,{mode:Ls})}async function mw(t,e){if(process.platform==="win32")return;let n=De(t,e).config;try{let i=await gw(n);if(!i.isFile())return;let s=i.mode&511;s!==Ls&&(await pw(n,Ls),uu.warn("agent config mode auto-corrected to 0600",{path:n,from:s.toString(8)}))}catch(i){if(i.code==="ENOENT")return;uu.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function _i(t,e,n){let i=await ge(t,n);i&&(i.sessions=Object.fromEntries(e),await Re(i,n))}async function yi(t,e,n){let i=await ge(t,n);i&&(i.skills=e,await Re(i,n))}var uu,Ls,Qt=ot(()=>{"use strict";Ct();ne();Ce();uu=G("agent-config"),Ls=384});var sc=le((ck,xu)=>{xu.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Bs=le(gu=>{var pu={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Ew(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(pu))gu[t]=Ew(pu[t])});var bu=le((lk,yu)=>{var Sw=xe("fs"),Be=xe("path"),mu=sc(),Iw=Bs(),Aw=typeof process=="object"&&process.platform==="win32",wu=t=>typeof t=="object"&&t!==null,_u=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 Se(t){this.sep=Be.sep,this.fs=Sw,wu(t)&&wu(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}yu.exports=Se;Se.prototype.makeDir=function(t){let e=this;function n(i){let s=i.split(e.sep)[0];i.split(e.sep).forEach(function(a){if(!(!a||a.substr(-1,1)===":")){s+=e.sep+a;var d;try{d=e.fs.statSync(s)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw u}if(d&&d.isFile())throw Iw.FILE_IN_THE_WAY(`"${s}"`)}})}n(t)};Se.prototype.writeFileTo=function(t,e,n,i){let s=this;if(s.fs.existsSync(t)){if(!n)return!1;var a=s.fs.statSync(t);if(a.isDirectory())return!1}var d=Be.dirname(t);s.fs.existsSync(d)||s.makeDir(d);var u;try{u=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),u=s.fs.openSync(t,"w",438)}if(u)try{s.fs.writeSync(u,e,0,e.length,0)}finally{s.fs.closeSync(u)}return s.fs.chmodSync(t,i||438),!0};Se.prototype.writeFileToAsync=function(t,e,n,i,s){typeof i=="function"&&(s=i,i=void 0);let a=this;a.fs.exists(t,function(d){if(d&&!n)return s(!1);a.fs.stat(t,function(u,h){if(d&&h.isDirectory())return s(!1);var x=Be.dirname(t);a.fs.exists(x,function(p){p||a.makeDir(x),a.fs.open(t,"w",438,function(w,b){w?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(y,v){a.fs.write(v,e,0,e.length,0,function(){a.fs.close(v,function(){a.fs.chmod(t,i||438,function(){s(!0)})})})})}):b?a.fs.write(b,e,0,e.length,0,function(){a.fs.close(b,function(){a.fs.chmod(t,i||438,function(){s(!0)})})}):a.fs.chmod(t,i||438,function(){s(!0)})})})})})};Se.prototype.findFiles=function(t){let e=this;function n(i,s,a){typeof s=="boolean"&&(a=s,s=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let h=Be.join(i,u),x=e.fs.statSync(h);(!s||s.test(h))&&d.push(Be.normalize(h)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(h,s,a)))}),d}return n(t,void 0,!0)};Se.prototype.findFilesAsync=function(t,e){let n=this,i=[];n.fs.readdir(t,function(s,a){if(s)return e(s);let d=a.length;if(!d)return e(null,i);a.forEach(function(u){u=Be.join(t,u),n.fs.stat(u,function(h,x){if(h)return e(h);x&&(i.push(Be.normalize(u)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(u,function(p,w){if(p)return e(p);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};Se.prototype.getAttributes=function(){};Se.prototype.setAttributes=function(){};Se.crc32update=function(t,e){return _u[(t^e)&255]^t>>>8};Se.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=Se.crc32update(n,t[i++]);return~n>>>0};Se.methodToString=function(t){switch(t){case mu.STORED:return"STORED ("+t+")";case mu.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Se.canonical=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.join(".",e)};Se.zipnamefix=function(t){if(!t)return"";let e=Be.posix.normalize("/"+t.split("\\").join("/"));return Be.posix.join(".",e)};Se.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]};Se.sanitize=function(t,e){t=Be.resolve(Be.normalize(t));for(var n=e.split("/"),i=0,s=n.length;i<s;i++){var a=Be.normalize(Be.join(t,n.slice(i,s).join(Be.sep)));if(a.indexOf(t)===0)return a}return Be.normalize(Be.join(t,Be.basename(e)))};Se.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};Se.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};Se.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Se.fromDate2DOS=function(t){let e=0,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};Se.isWin=Aw;Se.crcTable=_u});var Eu=le((uk,vu)=>{var kw=xe("path");vu.exports=function(t,{fs:e}){var n=t||"",i=a(),s=null;function a(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(s=e.statSync(n),i.directory=s.isDirectory(),i.mtime=s.mtime,i.atime=s.atime,i.executable=(73&s.mode)!==0,i.readonly=(128&s.mode)===0,i.hidden=kw.basename(n)[0]==="."):console.warn("Invalid path: "+n),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:n,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Iu=le((fk,Su)=>{Su.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Ar=le((hk,Ir)=>{Ir.exports=bu();Ir.exports.Constants=sc();Ir.exports.Errors=Bs();Ir.exports.FileAttr=Eu();Ir.exports.decoder=Iu()});var ku=le((xk,Au)=>{var bn=Ar(),z=bn.Constants;Au.exports=function(){var t=20,e=10,n=0,i=0,s=0,a=0,d=0,u=0,h=0,x=0,p=0,w=0,b=0,y=0,v=0;t|=bn.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,C=E=>Math.max(0,E)&65535,P=E=>Math.max(0,E)&255;return s=bn.fromDate2DOS(new Date),{get made(){return t},set made(E){t=E},get version(){return e},set version(E){e=E},get flags(){return n},set flags(E){n=E},get flags_efs(){return(n&z.FLG_EFS)>0},set flags_efs(E){E?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(E){E?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(E){switch(E){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=E},get time(){return bn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=bn.fromDate2DOS(E)},get timeval(){return s},set timeval(E){s=A(E)},get timeHighByte(){return P(s>>>8)},get crc(){return a},set crc(E){a=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return u},set size(E){u=A(E)},get fileNameLength(){return h},set fileNameLength(E){h=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return p},set commentLength(E){p=E},get diskNumStart(){return w},set diskNumStart(E){w=A(E)},get inAttr(){return b},set inAttr(E){b=A(E)},get attr(){return y},set attr(E){y=A(E)},get fileAttr(){return(y||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+h+x+p},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var D=E.slice(v,v+z.LOCHDR);if(D.readUInt32LE(0)!==z.LOCSIG)throw bn.Errors.INVALID_LOC();I.version=D.readUInt16LE(z.LOCVER),I.flags=D.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=D.readUInt16LE(z.LOCHOW),I.time=D.readUInt32LE(z.LOCTIM),I.crc=D.readUInt32LE(z.LOCCRC),I.compressedSize=D.readUInt32LE(z.LOCSIZ),I.size=D.readUInt32LE(z.LOCLEN),I.fnameLen=D.readUInt16LE(z.LOCNAM),I.extraLen=D.readUInt16LE(z.LOCEXT);let O=v+z.LOCHDR+I.fnameLen,U=O+I.extraLen;return E.slice(O,U)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw bn.Errors.INVALID_CEN();t=E.readUInt16LE(z.CENVEM),e=E.readUInt16LE(z.CENVER),n=E.readUInt16LE(z.CENFLG),i=E.readUInt16LE(z.CENHOW),s=E.readUInt32LE(z.CENTIM),a=E.readUInt32LE(z.CENCRC),d=E.readUInt32LE(z.CENSIZ),u=E.readUInt32LE(z.CENLEN),h=E.readUInt16LE(z.CENNAM),x=E.readUInt16LE(z.CENEXT),p=E.readUInt16LE(z.CENCOM),w=E.readUInt16LE(z.CENDSK),b=E.readUInt16LE(z.CENATT),y=E.readUInt32LE(z.CENATX),v=E.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(z.LOCHDR);return E.writeUInt32LE(z.LOCSIG,0),E.writeUInt16LE(e,z.LOCVER),E.writeUInt16LE(n,z.LOCFLG),E.writeUInt16LE(i,z.LOCHOW),E.writeUInt32LE(s,z.LOCTIM),E.writeUInt32LE(a,z.LOCCRC),E.writeUInt32LE(d,z.LOCSIZ),E.writeUInt32LE(u,z.LOCLEN),E.writeUInt16LE(h,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+h+x+p);return E.writeUInt32LE(z.CENSIG,0),E.writeUInt16LE(t,z.CENVEM),E.writeUInt16LE(e,z.CENVER),E.writeUInt16LE(n,z.CENFLG),E.writeUInt16LE(i,z.CENHOW),E.writeUInt32LE(s,z.CENTIM),E.writeUInt32LE(a,z.CENCRC),E.writeUInt32LE(d,z.CENSIZ),E.writeUInt32LE(u,z.CENLEN),E.writeUInt16LE(h,z.CENNAM),E.writeUInt16LE(x,z.CENEXT),E.writeUInt16LE(p,z.CENCOM),E.writeUInt16LE(w,z.CENDSK),E.writeUInt16LE(b,z.CENATT),E.writeUInt32LE(y,z.CENATX),E.writeUInt32LE(v,z.CENOFF),E},toJSON:function(){let E=function(D){return D+" bytes"};return{made:t,version:e,flags:n,method:bn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(u),fileNameLength:E(h),extraLength:E(x),commentLength:E(p),diskNumStart:w,inAttr:b,attr:y,offset:v,centralHeaderSize:E(z.CENHDR+h+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Tu=le((pk,Cu)=>{var kr=Ar(),be=kr.Constants;Cu.exports=function(){var t=0,e=0,n=0,i=0,s=0;return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return n},set size(a){n=a},get offset(){return i},set offset(a){i=a},get commentLength(){return s},set commentLength(a){s=a},get mainHeaderSize(){return be.ENDHDR+s},loadFromBinary:function(a){if((a.length!==be.ENDHDR||a.readUInt32LE(0)!==be.ENDSIG)&&(a.length<be.ZIP64HDR||a.readUInt32LE(0)!==be.ZIP64SIG))throw kr.Errors.INVALID_END();a.readUInt32LE(0)===be.ENDSIG?(t=a.readUInt16LE(be.ENDSUB),e=a.readUInt16LE(be.ENDTOT),n=a.readUInt32LE(be.ENDSIZ),i=a.readUInt32LE(be.ENDOFF),s=a.readUInt16LE(be.ENDCOM)):(t=kr.readBigUInt64LE(a,be.ZIP64SUB),e=kr.readBigUInt64LE(a,be.ZIP64TOT),n=kr.readBigUInt64LE(a,be.ZIP64SIZE),i=kr.readBigUInt64LE(a,be.ZIP64OFF),s=0)},toBinary:function(){var a=Buffer.alloc(be.ENDHDR+s);return a.writeUInt32LE(be.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,be.ENDSUB),a.writeUInt16LE(e,be.ENDTOT),a.writeUInt32LE(n,be.ENDSIZ),a.writeUInt32LE(i,be.ENDOFF),a.writeUInt16LE(s,be.ENDCOM),a.fill(" ",be.ENDHDR),a},toJSON:function(){let a=function(d,u){let h=d.toString(16).toUpperCase();for(;h.length<u;)h="0"+h;return"0x"+h};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:a(i,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ac=le(oc=>{oc.EntryHeader=ku();oc.MainHeader=Tu()});var Du=le((mk,Pu)=>{Pu.exports=function(t){var e=xe("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var s=e.createDeflateRaw(n),a=[],d=0;s.on("data",function(u){a.push(u),d+=u.length}),s.on("end",function(){var u=Buffer.alloc(d),h=0;u.fill(0);for(var x=0;x<a.length;x++){var p=a[x];p.copy(u,h),h+=p.length}i&&i(u)}),s.end(t)}}}});var Ou=le((wk,Ru)=>{var Cw=+(process.versions?process.versions.node:"").split(".")[0]||0;Ru.exports=function(t,e){var n=xe("zlib");let i=Cw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(s){var a=n.createInflateRaw(i),d=[],u=0;a.on("data",function(h){d.push(h),u+=h.length}),a.on("end",function(){var h=Buffer.alloc(u),x=0;h.fill(0);for(var p=0;p<d.length;p++){var w=d[p];w.copy(h,x),x+=w.length}s&&s(h)}),a.end(t)}}}});var Fu=le((_k,Bu)=>{"use strict";var{randomFillSync:Lu}=xe("crypto"),Tw=Bs(),Pw=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Nu=(t,e)=>Math.imul(t,e)>>>0,Mu=(t,e)=>Pw[(t^e)&255]^t>>>8,bi=()=>typeof Lu=="function"?Lu(Buffer.alloc(12)):bi.node();bi.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 Fs={genSalt:bi};function zs(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])}zs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Mu(e[0],t),e[1]+=e[0]&255,e[1]=Nu(e[1],134775813)+1,e[2]=Mu(e[2],e[1]>>>24),t};zs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Nu(t,t^1)>>8&255};function Dw(t){let e=new zs(t);return function(n){let i=Buffer.alloc(n.length),s=0;for(let a of n)i[s++]=e.updateKeys(a^e.next());return i}}function Rw(t){let e=new zs(t);return function(n,i,s=0){i||(i=Buffer.alloc(n.length));for(let a of n){let d=e.next();i[s++]=a^d,e.updateKeys(a)}return i}}function Ow(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Dw(n),s=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==a)throw Tw.WRONG_PASSWORD();return i(t.slice(12))}function Lw(t){Buffer.isBuffer(t)&&t.length>=12?Fs.genSalt=function(){return t.slice(0,12)}:t==="node"?Fs.genSalt=bi.node:Fs.genSalt=bi}function Mw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=Rw(n),a=Fs.genSalt();a[11]=e.crc>>>24&255,i&&(a[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return s(a,d),s(t,d,12)}Bu.exports={decrypt:Ow,encrypt:Mw,_salter:Lw}});var zu=le(Us=>{Us.Deflater=Du();Us.Inflater=Ou();Us.ZipCrypto=Fu()});var dc=le((bk,Uu)=>{var ue=Ar(),Nw=ac(),Ie=ue.Constants,cc=zu();Uu.exports=function(t,e){var n=new Nw.EntryHeader,i=Buffer.alloc(0),s=Buffer.alloc(0),a=!1,d=null,u=Buffer.alloc(0),h=Buffer.alloc(0),x=!0;let p=t,w=typeof p.decoder=="object"?p.decoder:ue.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function b(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(h=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function y(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ue.crc32(E)!==n.localHeader.crc)return!1}else{let D={},O=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(O)==Ie.LOCSIG||e.readUInt32LE(O)==Ie.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==Ie.EXTSIG)D.crc=e.readUInt32LE(O+Ie.EXTCRC),D.compressedSize=e.readUInt32LE(O+Ie.EXTSIZ),D.size=e.readUInt32LE(O+Ie.EXTLEN);else if(e.readUInt16LE(O+12)===19280)D.crc=e.readUInt32LE(O+Ie.EXTCRC-4),D.compressedSize=e.readUInt32LE(O+Ie.EXTSIZ-4),D.size=e.readUInt32LE(O+Ie.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(D.compressedSize!==n.compressedSize||D.size!==n.size||D.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(E)!==D.crc)return!1}return!0}function v(E,D,O){if(typeof D>"u"&&typeof E=="string"&&(O=E,E=void 0),a)return E&&D&&D(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var U=b();if(U.length===0)return E&&D&&D(U),U;if(n.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ue.Errors.INVALID_PASS_PARAM();U=cc.ZipCrypto.decrypt(U,n,O)}var M=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(U.copy(M),y(M))return E&&D&&D(M),M;throw E&&D&&D(M,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var K=new cc.Inflater(U,n.size);if(E)K.inflateAsync(function(V){V.copy(V,0),D&&(y(V)?D(V):D(V,ue.Errors.BAD_CRC()))});else{if(K.inflate(M).copy(M,0),!y(M))throw ue.Errors.BAD_CRC(`"${w.decode(i)}"`);return M}break;default:throw E&&D&&D(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(E,D){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&D&&D(b()),b();if(d.length&&!a){var O;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,O=Buffer.alloc(d.length),d.copy(O),E&&D&&D(O),O;default:case ue.Constants.DEFLATED:var U=new cc.Deflater(d);if(E)U.deflateAsync(function(K){O=Buffer.alloc(K.length),n.compressedSize=K.length,K.copy(O),D&&D(O)});else{var M=U.deflate();return n.compressedSize=M.length,M}U=null;break}}else if(E&&D)D(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,D){return ue.readBigUInt64LE(E,D)}function C(E){try{for(var D=0,O,U,M;D+4<E.length;)O=E.readUInt16LE(D),D+=2,U=E.readUInt16LE(D),D+=2,M=E.slice(D,D+U),D+=U,Ie.ID_ZIP64===O&&P(M)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(E){var D,O,U,M;E.length>=Ie.EF_ZIP64_SCOMP&&(D=A(E,Ie.EF_ZIP64_SUNCOMP),n.size===Ie.EF_ZIP64_OR_32&&(n.size=D)),E.length>=Ie.EF_ZIP64_RHO&&(O=A(E,Ie.EF_ZIP64_SCOMP),n.compressedSize===Ie.EF_ZIP64_OR_32&&(n.compressedSize=O)),E.length>=Ie.EF_ZIP64_DSN&&(U=A(E,Ie.EF_ZIP64_RHO),n.offset===Ie.EF_ZIP64_OR_32&&(n.offset=U)),E.length>=Ie.EF_ZIP64_DSN+4&&(M=E.readUInt32LE(Ie.EF_ZIP64_DSN),n.diskNumStart===Ie.EF_ZIP64_OR_16&&(n.diskNumStart=M))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(E){i=ue.toBuffer(E,w.encode);var D=i[i.length-1];a=D===47||D===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,C(E)},get comment(){return w.decode(s)},set comment(E){if(s=ue.toBuffer(E,w.encode),n.commentLength=s.length,s.length>65535)throw ue.Errors.COMMENT_TOO_LONG()},get name(){var E=w.decode(i);return a?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=ue.toBuffer(E,ue.decoder.encode),!a&&d.length?(n.size=d.length,n.method=ue.Constants.DEFLATED,n.crc=ue.crc32(E),n.changed=!0):n.method=ue.Constants.STORED},getData:function(E){return n.changed?d:v(!1,null,E)},getDataAsync:function(E,D){n.changed?E(d):v(!0,E,D)},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(),D=ue.Constants.CENHDR;return i.copy(E,D),D+=i.length,u.copy(E,D),D+=n.extraLength,s.copy(E,D),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=h.length;let D=n.localHeaderToBinary(),O=Buffer.alloc(D.length+i.length+n.extraLocalLength);return D.copy(O,E),E+=D.length,i.copy(O,E),E+=i.length,h.copy(O,E),E+=h.length,O},toJSON:function(){let E=function(D){return"<"+(D&&D.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:E(e),data:E(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var qu=le((vk,Gu)=>{var Hu=dc(),Bw=ac(),Je=Ar();Gu.exports=function(t,e){var n=[],i={},s=Buffer.alloc(0),a=new Bw.MainHeader,d=!1,u=null;let h=new Set,x=e,{noSort:p,decoder:w}=x;t?v(x.readEntries):d=!0;function b(){let A=new Set;for(let C of Object.keys(i)){let P=C.split("/");if(P.pop(),!!P.length)for(let E=0;E<P.length;E++){let D=P.slice(0,E+1).join("/")+"/";A.add(D)}}for(let C of A)if(!(C in i)){let P=new Hu(x);P.entryName=C,P.attr=16,P.temporary=!0,n.push(P),i[P.entryName]=P,h.add(P)}}function y(){if(d=!0,i={},a.diskEntries>(t.length-a.offset)/Je.Constants.CENHDR)throw Je.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(a.diskEntries);for(var A=a.offset,C=0;C<n.length;C++){var P=A,E=new Hu(x,t);E.header=t.slice(P,P+=Je.Constants.CENHDR),E.entryName=t.slice(P,P+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(P,P+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(P,P+E.header.commentLength)),A+=E.header.centralHeaderSize,n[C]=E,i[E.entryName]=E}h.clear(),b()}function v(A){var C=t.length-Je.Constants.ENDHDR,P=Math.max(0,C-65535),E=P,D=t.length,O=-1,U=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(P=0),C;C>=E;C--)if(t[C]===80){if(t.readUInt32LE(C)===Je.Constants.ENDSIG){O=C,U=C,D=C+Je.Constants.ENDHDR,E=C-Je.Constants.END64HDR;continue}if(t.readUInt32LE(C)===Je.Constants.END64SIG){E=P;continue}if(t.readUInt32LE(C)===Je.Constants.ZIP64SIG){O=C,D=C+Je.readBigUInt64LE(t,C+Je.Constants.ZIP64SIZE)+Je.Constants.ZIP64LEAD;break}}if(O==-1)throw Je.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(O,D)),a.commentLength&&(s=t.slice(U+Je.Constants.ENDHDR)),A&&y()}function I(){n.length>1&&!p&&n.sort((A,C)=>A.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return d||y(),n.filter(A=>!h.has(A))},get comment(){return w.decode(s)},set comment(A){s=Je.toBuffer(A,w.encode),a.commentLength=s.length},getEntryCount:function(){return d?n.length:a.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||y(),i[A]||null},setEntry:function(A){d||y(),n.push(A),i[A.entryName]=A,a.totalEntries=n.length},deleteFile:function(A,C=!0){d||y();let P=i[A];this.getEntryChildren(P,C).map(D=>D.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||y();let C=i[A],P=n.indexOf(C);P>=0&&(n.splice(P,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,C=!0){if(d||y(),typeof A=="object")if(A.isDirectory&&C){let P=[],E=A.entryName;for(let D of n)D.entryName.startsWith(E)&&P.push(D);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let C=this.getEntryChildren(A);return C.includes(A)?C.length-1:C.length}return 0},compressToBuffer:function(){d||y(),I();let A=[],C=[],P=0,E=0;a.size=0,a.offset=0;let D=0;for(let M of this.entries){let K=M.getCompressedData();M.header.offset=E;let V=M.packLocalHeader(),ie=V.length+K.length;E+=ie,A.push(V),A.push(K);let X=M.packCentralHeader();C.push(X),a.size+=X.length,P+=ie+X.length,D++}P+=a.mainHeaderSize,a.offset=E,a.totalEntries=D,E=0;let O=Buffer.alloc(P);for(let M of A)M.copy(O,E),E+=M.length;for(let M of C)M.copy(O,E),E+=M.length;let U=a.toBinary();return s&&s.copy(U,Je.Constants.ENDHDR),U.copy(O,E),t=O,d=!1,O},toAsyncBuffer:function(A,C,P,E){try{d||y(),I();let D=[],O=[],U=0,M=0,K=0;a.size=0,a.offset=0;let V=function(ie){if(ie.length>0){let X=ie.shift(),oe=X.entryName+X.extra.toString();P&&P(oe),X.getCompressedDataAsync(function(de){E&&E(oe),X.header.offset=M;let ye=X.packLocalHeader(),ze=ye.length+de.length;M+=ze,D.push(ye),D.push(de);let T=X.packCentralHeader();O.push(T),a.size+=T.length,U+=ze+T.length,K++,V(ie)})}else{U+=a.mainHeaderSize,a.offset=M,a.totalEntries=K,M=0;let X=Buffer.alloc(U);D.forEach(function(de){de.copy(X,M),M+=de.length}),O.forEach(function(de){de.copy(X,M),M+=de.length});let oe=a.toBinary();s&&s.copy(oe,Je.Constants.ENDHDR),oe.copy(X,M),t=X,d=!1,A(X)}};V(Array.from(this.entries))}catch(D){C(D)}}}}});var Ku=le((Ek,Wu)=>{var Ee=Ar(),ve=xe("path"),Fw=dc(),zw=qu(),Gn=(...t)=>Ee.findLast(t,e=>typeof e=="boolean"),ju=(...t)=>Ee.findLast(t,e=>typeof e=="string"),Uw=(...t)=>Ee.findLast(t,e=>typeof e=="function"),Hw={noSort:!1,readEntries:!1,method:Ee.Constants.NONE,fs:null};Wu.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),Hw);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(n=t,i.method=Ee.Constants.BUFFER,t=void 0)),Object.assign(i,e);let s=new Ee(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ee.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))i.method=Ee.Constants.FILE,i.filename=t,n=s.fs.readFileSync(t);else throw Ee.Errors.INVALID_FILENAME();let a=new zw(n,i),{canonical:d,sanitize:u,zipnamefix:h}=Ee;function x(y){if(y&&a){var v;if(typeof y=="string"&&(v=a.getEntry(ve.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(v=a.getEntry(y.entryName)),v)return v}return null}function p(y){let{join:v,normalize:I,sep:A}=ve.posix;return v(ve.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function w(y){return y instanceof RegExp?(function(v){return function(I){return v.test(I)}})(y):typeof y!="function"?()=>!0:y}let b=(y,v)=>{let I=v.slice(-1);return I=I===s.sep?s.sep:"",ve.relative(y,v)+I};return{readFile:function(y,v){var I=x(y);return I&&I.getData(v)||null},childCount:function(y){let v=x(y);if(v)return a.getChildCount(v)},readFileAsync:function(y,v){var I=x(y);I?I.getDataAsync(v):v(null,"getEntry failed for:"+y)},readAsText:function(y,v){var I=x(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(y,v,I){var A=x(y);A?A.getDataAsync(function(C,P){if(P){v(C,P);return}C&&C.length?v(C.toString(I||"utf8")):v("")}):v("")},deleteFile:function(y,v=!0){var I=x(y);I&&a.deleteFile(I.entryName,v)},deleteEntry:function(y){var v=x(y);v&&a.deleteEntry(v.entryName)},addZipComment:function(y){a.comment=y},getZipComment:function(){return a.comment||""},addZipEntryComment:function(y,v){var I=x(y);I&&(I.comment=v)},getZipEntryComment:function(y){var v=x(y);return v&&v.comment||""},updateFile:function(y,v){var I=x(y);I&&I.setData(v)},addLocalFile:function(y,v,I,A){if(s.fs.existsSync(y)){v=v?p(v):"";let C=ve.win32.basename(ve.win32.normalize(y));v+=I||C;let P=s.fs.statSync(y),E=P.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);P.isDirectory()&&(v+=s.sep),this.addFile(v,E,A,P)}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,v){y=typeof y=="object"?y:{localPath:y};let I=ve.resolve(y.localPath),{comment:A}=y,{zipPath:C,zipName:P}=y,E=this;s.fs.stat(I,function(D,O){if(D)return v(D,!1);C=C?p(C):"";let U=ve.win32.basename(ve.win32.normalize(I));if(C+=P||U,O.isFile())s.fs.readFile(I,function(M,K){return M?v(M,!1):(E.addFile(C,K,A,O),setImmediate(v,void 0,!0))});else if(O.isDirectory())return C+=s.sep,E.addFile(C,Buffer.alloc(0),A,O),setImmediate(v,void 0,!0)})},addLocalFolder:function(y,v,I){if(I=w(I),v=v?p(v):"",y=ve.normalize(y),s.fs.existsSync(y)){let A=s.findFiles(y),C=this;if(A.length)for(let P of A){let E=ve.join(v,b(y,P));I(E)&&C.addLocalFile(P,ve.dirname(E))}}else throw Ee.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,v,I,A){A=w(A),I=I?p(I):"",y=ve.normalize(y);var C=this;s.fs.open(y,"r",function(P){if(P&&P.code==="ENOENT")v(void 0,Ee.Errors.FILE_NOT_FOUND(y));else if(P)v(void 0,P);else{var E=s.findFiles(y),D=-1,O=function(){if(D+=1,D<E.length){var U=E[D],M=b(y,U).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?s.fs.stat(U,function(K,V){K&&v(void 0,K),V.isFile()?s.fs.readFile(U,function(ie,X){ie?v(void 0,ie):(C.addFile(I+M,X,"",V),O())}):(C.addFile(I+M+"/",Buffer.alloc(0),"",V),O())}):process.nextTick(()=>{O()})}else v(!0,void 0)};O()}})},addLocalFolderAsync2:function(y,v){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=ve.resolve(p(y.localPath));let{zipPath:A,filter:C,namefix:P}=y;C instanceof RegExp?C=(function(O){return function(U){return O.test(U)}})(C):typeof C!="function"&&(C=function(){return!0}),A=A?p(A):"",P=="latin1"&&(P=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=O=>O);let E=O=>ve.join(A,P(b(localPath,O))),D=O=>ve.win32.basename(ve.win32.normalize(P(O)));s.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?v(void 0,Ee.Errors.FILE_NOT_FOUND(localPath)):O?v(void 0,O):s.findFilesAsync(localPath,function(U,M){if(U)return v(U);M=M.filter(K=>C(E(K))),M.length||v(void 0,!1),setImmediate(M.reverse().reduce(function(K,V){return function(ie,X){if(ie||X===!1)return setImmediate(K,ie,!1);I.addLocalFileAsync({localPath:V,zipPath:ve.dirname(E(V)),zipName:D(V)},K)}},v))})})},addLocalFolderPromise:function(y,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},v),(C,P)=>{C&&A(C),P&&I(this)})})},addFile:function(y,v,I,A){y=h(y);let C=x(y),P=C!=null;P||(C=new Fw(i),C.entryName=y),C.comment=I||"";let E=typeof A=="object"&&A instanceof s.fs.Stats;E&&(C.header.time=A.mtime);var D=C.isDirectory?16:0;let O=C.isDirectory?16384:32768;return E?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=C.isDirectory?493:420,D=(D|O<<16)>>>0,C.attr=D,C.setData(v),P||a.setEntry(C),C},getEntries:function(y){return a.password=y,a?a.entries:[]},getEntry:function(y){return x(y)},getEntryCount:function(){return a.getEntryCount()},forEach:function(y){return a.forEach(y)},extractEntryTo:function(y,v,I,A,C,P){A=Gn(!1,A),C=Gn(!1,C),I=Gn(!0,I),P=ju(C,P);var E=x(y);if(!E)throw Ee.Errors.NO_ENTRY();var D=d(E.entryName),O=u(v,P&&!E.isDirectory?P:I?D:ve.basename(D));if(E.isDirectory){var U=a.getEntryChildren(E);return U.forEach(function(V){if(V.isDirectory)return;var ie=V.getData();if(!ie)throw Ee.Errors.CANT_EXTRACT_FILE();var X=d(V.entryName),oe=u(v,I?X:ve.basename(X));let de=C?V.header.fileAttr:void 0;s.writeFileTo(oe,ie,A,de)}),!0}var M=E.getData(a.password);if(!M)throw Ee.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(O)&&!A)throw Ee.Errors.CANT_OVERRIDE();let K=C?y.header.fileAttr:void 0;return s.writeFileTo(O,M,A,K),!0},test:function(y){if(!a)return!1;for(var v in a.entries)try{if(v.isDirectory)continue;var I=a.entries[v].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,v,I,A){if(I=Gn(!1,I),A=ju(I,A),v=Gn(!1,v),!a)throw Ee.Errors.NO_ZIP();a.entries.forEach(function(C){var P=u(y,d(C.entryName));if(C.isDirectory){s.makeDir(P);return}var E=C.getData(A);if(!E)throw Ee.Errors.CANT_EXTRACT_FILE();let D=I?C.header.fileAttr:void 0;s.writeFileTo(P,E,v,D);try{s.fs.utimesSync(P,C.header.time,C.header.time)}catch{throw Ee.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,v,I,A){if(A=Uw(v,I,A),I=Gn(!1,I),v=Gn(!1,v),!A)return new Promise((O,U)=>{this.extractAllToAsync(y,v,I,function(M){M?U(M):O(this)})});if(!a){A(Ee.Errors.NO_ZIP());return}y=ve.resolve(y);let C=O=>u(y,ve.normalize(d(O.entryName))),P=(O,U)=>new Error(O+': "'+U+'"'),E=[],D=[];a.entries.forEach(O=>{O.isDirectory?E.push(O):D.push(O)});for(let O of E){let U=C(O),M=I?O.header.fileAttr:void 0;try{s.makeDir(U),M&&s.fs.chmodSync(U,M),s.fs.utimesSync(U,O.header.time,O.header.time)}catch{A(P("Unable to create folder",U))}}D.reverse().reduce(function(O,U){return function(M){if(M)O(M);else{let K=ve.normalize(d(U.entryName)),V=u(y,K);U.getDataAsync(function(ie,X){if(X)O(X);else if(!ie)O(Ee.Errors.CANT_EXTRACT_FILE());else{let oe=I?U.header.fileAttr:void 0;s.writeFileToAsync(V,ie,v,oe,function(de){de||O(P("Unable to write file",V)),s.fs.utimes(V,U.header.time,U.header.time,function(ye){ye?O(P("Unable to set times",V)):O()})})}})}}},A)()},writeZip:function(y,v){if(arguments.length===1&&typeof y=="function"&&(v=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=a.compressToBuffer();if(I){var A=s.writeFileTo(y,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);return new Promise((C,P)=>{!y&&i.filename&&(y=i.filename),y||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(E=>{let D=O=>O?C(O):P("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(y,E,I,A,D)},P)})},toBufferPromise:function(){return new Promise((y,v)=>{a.toAsyncBuffer(y,v)})},toBuffer:function(y,v,I,A){return typeof y=="function"?(a.toAsyncBuffer(y,v,I,A),null):a.compressToBuffer()}}}});import{execFile as Zy,spawn as Yy,spawnSync as WC}from"node:child_process";import{promisify as Xy}from"node:util";function eb(t){if(process.platform!=="win32")return!1;if(b0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(b0,"").toLowerCase();return Qy.has(n)}function v0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return eb(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function dt(t,e=[],n={}){return Yy(t,e,v0(t,n))}function E0(t,e=[],n={}){return tb(t,e,v0(t,n))}var Qy,b0,tb,an=ot(()=>{"use strict";Qy=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),b0=/\.(cmd|bat|ps1)$/i;tb=Xy(Zy)});var un=le((_O,Px)=>{"use strict";var Cx=["nodebuffer","arraybuffer","fragments"],Tx=typeof Blob<"u";Tx&&Cx.push("blob");Px.exports={BINARY_TYPES:Cx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Tx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var us=le((yO,ta)=>{"use strict";var{EMPTY_BUFFER:PS}=un(),$d=Buffer[Symbol.species];function DS(t,e){if(t.length===0)return PS;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),i=0;for(let s=0;s<t.length;s++){let a=t[s];n.set(a,i),i+=a.length}return i<e?new $d(n.buffer,n.byteOffset,i):n}function Dx(t,e,n,i,s){for(let a=0;a<s;a++)n[i+a]=t[a]^e[a&3]}function Rx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function RS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Vd(t){if(Vd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new $d(t):ArrayBuffer.isView(t)?e=new $d(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Vd.readOnly=!1),e}ta.exports={concat:DS,mask:Dx,toArrayBuffer:RS,toBuffer:Vd,unmask:Rx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=xe("bufferutil");ta.exports.mask=function(e,n,i,s,a){a<48?Dx(e,n,i,s,a):t.mask(e,n,i,s,a)},ta.exports.unmask=function(e,n){e.length<32?Rx(e,n):t.unmask(e,n)}}catch{}});var Mx=le((bO,Lx)=>{"use strict";var Ox=Symbol("kDone"),Jd=Symbol("kRun"),Zd=class{constructor(e){this[Ox]=()=>{this.pending--,this[Jd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Jd]()}[Jd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ox])}}};Lx.exports=Zd});var ri=le((vO,zx)=>{"use strict";var fs=xe("zlib"),Nx=us(),OS=Mx(),{kStatusCode:Bx}=un(),LS=Buffer[Symbol.species],MS=Buffer.from([0,0,255,255]),ra=Symbol("permessage-deflate"),fn=Symbol("total-length"),ti=Symbol("callback"),Nn=Symbol("buffers"),ni=Symbol("error"),na,Yd=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!na){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;na=new OS(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[ti];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,i=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(i=>{let s=n[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let a=+s;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=a}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=s})}),e}decompress(e,n,i){na.add(s=>{this._decompress(e,n,(a,d)=>{s(),i(a,d)})})}compress(e,n,i){na.add(s=>{this._compress(e,n,(a,d)=>{s(),i(a,d)})})}_decompress(e,n,i){let s=this._isServer?"client":"server";if(!this._inflate){let a=`${s}_max_window_bits`,d=typeof this.params[a]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[ra]=this,this._inflate[fn]=0,this._inflate[Nn]=[],this._inflate.on("error",BS),this._inflate.on("data",Fx)}this._inflate[ti]=i,this._inflate.write(e),n&&this._inflate.write(MS),this._inflate.flush(()=>{let a=this._inflate[ni];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Nx.concat(this._inflate[Nn],this._inflate[fn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fn]=0,this._inflate[Nn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,n,i){let s=this._isServer?"server":"client";if(!this._deflate){let a=`${s}_max_window_bits`,d=typeof this.params[a]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[fn]=0,this._deflate[Nn]=[],this._deflate.on("data",NS)}this._deflate[ti]=i,this._deflate.write(e),this._deflate.flush(fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Nx.concat(this._deflate[Nn],this._deflate[fn]);n&&(a=new LS(a.buffer,a.byteOffset,a.length-4)),this._deflate[ti]=null,this._deflate[fn]=0,this._deflate[Nn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};zx.exports=Yd;function NS(t){this[Nn].push(t),this[fn]+=t.length}function Fx(t){if(this[fn]+=t.length,this[ra]._maxPayload<1||this[fn]<=this[ra]._maxPayload){this[Nn].push(t);return}this[ni]=new RangeError("Max payload size exceeded"),this[ni].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ni][Bx]=1009,this.removeListener("data",Fx),this.reset()}function BS(t){if(this[ra]._inflate=null,this[ni]){this[ti](this[ni]);return}t[Bx]=1007,this[ti](t)}});var ii=le((EO,ia)=>{"use strict";var{isUtf8:Ux}=xe("buffer"),{hasBlob:FS}=un(),zS=[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 US(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Xd(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 HS(t){return FS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ia.exports={isBlob:HS,isValidStatusCode:US,isValidUTF8:Xd,tokenChars:zS};if(Ux)ia.exports.isValidUTF8=function(t){return t.length<24?Xd(t):Ux(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=xe("utf-8-validate");ia.exports.isValidUTF8=function(e){return e.length<32?Xd(e):t(e)}}catch{}});var rl=le((SO,$x)=>{"use strict";var{Writable:GS}=xe("stream"),Hx=ri(),{BINARY_TYPES:qS,EMPTY_BUFFER:Gx,kStatusCode:jS,kWebSocket:WS}=un(),{concat:Qd,toArrayBuffer:KS,unmask:$S}=us(),{isValidStatusCode:VS,isValidUTF8:qx}=ii(),sa=Buffer[Symbol.species],It=0,jx=1,Wx=2,Kx=3,el=4,tl=5,oa=6,nl=class extends GS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||qS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[WS]=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=It}_write(e,n,i){if(this._opcode===8&&this._state==It)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new sa(i.buffer,i.byteOffset+e,i.length-e),new sa(i.buffer,i.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=n.length-e;e>=i.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new sa(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case It:this.getInfo(e);break;case jx:this.getPayloadLength16(e);break;case Wx:this.getPayloadLength64(e);break;case Kx:this.getMask();break;case el:this.getData(e);break;case tl:case oa:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let i=(n[0]&64)===64;if(i&&!this._extensions[Hx.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=jx:this._payloadLength===127?this._state=Wx:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Kx:this._state=el}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=el}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&&$S(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=tl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hx.extensionName].decompress(e,this._fin,(s,a)=>{if(s)return n(s);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(d);return}this._fragments.push(a)}this.dataMessage(n),this._state===It&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=It;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Qd(i,n):this._binaryType==="arraybuffer"?s=KS(Qd(i,n)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=It):(this._state=oa,setImmediate(()=>{this.emit("message",s,!0),this._state=It,this.startLoop(e)}))}else{let s=Qd(i,n);if(!this._skipUTF8Validation&&!qx(s)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===tl||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=It):(this._state=oa,setImmediate(()=>{this.emit("message",s,!1),this._state=It,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(!VS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let s=new sa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!qx(s)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(a);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=oa,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(n)}))}createError(e,n,i,s,a){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(d,this.createError),d.code=a,d[jS]=s,d}};$x.exports=nl});var ol=le((AO,Zx)=>{"use strict";var{Duplex:IO}=xe("stream"),{randomFillSync:JS}=xe("crypto"),Vx=ri(),{EMPTY_BUFFER:ZS,kWebSocket:YS,NOOP:XS}=un(),{isBlob:si,isValidStatusCode:QS}=ii(),{mask:Jx,toBuffer:dr}=us(),At=Symbol("kByteLength"),eI=Buffer.alloc(4),aa=8*1024,lr,oi=aa,Mt=0,tI=1,nI=2,il=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=Mt,this.onerror=XS,this[YS]=void 0}static frame(e,n){let i,s=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||eI,n.generateMask?n.generateMask(i):(oi===aa&&(lr===void 0&&(lr=Buffer.alloc(aa)),JS(lr,0,aa),oi=0),i[0]=lr[oi++],i[1]=lr[oi++],i[2]=lr[oi++],i[3]=lr[oi++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let u;typeof e=="string"?(!n.mask||d)&&n[At]!==void 0?u=n[At]:(e=Buffer.from(e),u=e.length):(u=e.length,s=n.mask&&n.readOnly&&!d);let h=u;u>=65536?(a+=8,h=127):u>125&&(a+=2,h=126);let x=Buffer.allocUnsafe(s?u+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=h,h===126?x.writeUInt16BE(u,2):h===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),n.mask?(x[1]|=128,x[a-4]=i[0],x[a-3]=i[1],x[a-2]=i[2],x[a-1]=i[3],d?[x,e]:s?(Jx(e,i,x,a,u),[x]):(Jx(e,i,e,0,u),[x,e])):[x,e]}close(e,n,i,s){let a;if(e===void 0)a=ZS;else{if(typeof e!="number"||!QS(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={[At]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Mt?this.enqueue([this.dispatch,a,!1,d,s]):this.sendFrame(t.frame(a,d),s)}ping(e,n,i){let s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):si(e)?(s=e.size,a=!1):(e=dr(e),s=e.length,a=dr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[At]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};si(e)?this._state!==Mt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Mt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,n,i){let s,a;if(typeof e=="string"?(s=Buffer.byteLength(e),a=!1):si(e)?(s=e.size,a=!1):(e=dr(e),s=e.length,a=dr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[At]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};si(e)?this._state!==Mt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Mt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let s=this._extensions[Vx.extensionName],a=n.binary?2:1,d=n.compress,u,h;typeof e=="string"?(u=Buffer.byteLength(e),h=!1):si(e)?(u=e.size,h=!1):(e=dr(e),u=e.length,h=dr.readOnly),this._firstFragment?(this._firstFragment=!1,d&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=s._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[At]:u,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:h,rsv1:d};si(e)?this._state!==Mt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Mt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,s){this._bufferedBytes+=i[At],this._state=nI,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(sl,this,u,s);return}this._bufferedBytes-=i[At];let d=dr(a);n?this.dispatch(d,n,i,s):(this._state=Mt,this.sendFrame(t.frame(d,i),s),this.dequeue())}).catch(a=>{process.nextTick(rI,this,a,s)})}dispatch(e,n,i,s){if(!n){this.sendFrame(t.frame(e,i),s);return}let a=this._extensions[Vx.extensionName];this._bufferedBytes+=i[At],this._state=tI,a.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let h=new Error("The socket was closed while data was being compressed");sl(this,h,s);return}this._bufferedBytes-=i[At],this._state=Mt,i.readOnly=!1,this.sendFrame(t.frame(u,i),s),this.dequeue()})}dequeue(){for(;this._state===Mt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][At],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][At],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)}};Zx.exports=il;function sl(t,e,n){typeof n=="function"&&n(e);for(let i=0;i<t._queue.length;i++){let s=t._queue[i],a=s[s.length-1];typeof a=="function"&&a(e)}}function rI(t,e,n){sl(t,e,n),t.onerror(e)}});var sp=le((kO,ip)=>{"use strict";var{kForOnEventAttribute:hs,kListener:al}=un(),Yx=Symbol("kCode"),Xx=Symbol("kData"),Qx=Symbol("kError"),ep=Symbol("kMessage"),tp=Symbol("kReason"),ai=Symbol("kTarget"),np=Symbol("kType"),rp=Symbol("kWasClean"),hn=class{constructor(e){this[ai]=null,this[np]=e}get target(){return this[ai]}get type(){return this[np]}};Object.defineProperty(hn.prototype,"target",{enumerable:!0});Object.defineProperty(hn.prototype,"type",{enumerable:!0});var ur=class extends hn{constructor(e,n={}){super(e),this[Yx]=n.code===void 0?0:n.code,this[tp]=n.reason===void 0?"":n.reason,this[rp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Yx]}get reason(){return this[tp]}get wasClean(){return this[rp]}};Object.defineProperty(ur.prototype,"code",{enumerable:!0});Object.defineProperty(ur.prototype,"reason",{enumerable:!0});Object.defineProperty(ur.prototype,"wasClean",{enumerable:!0});var ci=class extends hn{constructor(e,n={}){super(e),this[Qx]=n.error===void 0?null:n.error,this[ep]=n.message===void 0?"":n.message}get error(){return this[Qx]}get message(){return this[ep]}};Object.defineProperty(ci.prototype,"error",{enumerable:!0});Object.defineProperty(ci.prototype,"message",{enumerable:!0});var xs=class extends hn{constructor(e,n={}){super(e),this[Xx]=n.data===void 0?null:n.data}get data(){return this[Xx]}};Object.defineProperty(xs.prototype,"data",{enumerable:!0});var iI={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[hs]&&s[al]===e&&!s[hs])return;let i;if(t==="message")i=function(a,d){let u=new xs("message",{data:d?a:a.toString()});u[ai]=this,ca(e,this,u)};else if(t==="close")i=function(a,d){let u=new ur("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[ai]=this,ca(e,this,u)};else if(t==="error")i=function(a){let d=new ci("error",{error:a,message:a.message});d[ai]=this,ca(e,this,d)};else if(t==="open")i=function(){let a=new hn("open");a[ai]=this,ca(e,this,a)};else return;i[hs]=!!n[hs],i[al]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[al]===e&&!n[hs]){this.removeListener(t,n);break}}};ip.exports={CloseEvent:ur,ErrorEvent:ci,Event:hn,EventTarget:iI,MessageEvent:xs};function ca(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var da=le((CO,op)=>{"use strict";var{tokenChars:ps}=ii();function Vt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function sI(t){let e=Object.create(null),n=Object.create(null),i=!1,s=!1,a=!1,d,u,h=-1,x=-1,p=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(p===-1&&ps[x]===1)h===-1&&(h=w);else if(w!==0&&(x===32||x===9))p===-1&&h!==-1&&(p=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let y=t.slice(h,p);x===44?(Vt(e,y,n),n=Object.create(null)):d=y,h=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(u===void 0)if(p===-1&&ps[x]===1)h===-1&&(h=w);else if(x===32||x===9)p===-1&&h!==-1&&(p=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w),Vt(n,t.slice(h,p),!0),x===44&&(Vt(e,d,n),n=Object.create(null),d=void 0),h=p=-1}else if(x===61&&h!==-1&&p===-1)u=t.slice(h,w),h=p=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(s){if(ps[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);h===-1?h=w:i||(i=!0),s=!1}else if(a)if(ps[x]===1)h===-1&&(h=w);else if(x===34&&h!==-1)a=!1,p=w;else if(x===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)a=!0;else if(p===-1&&ps[x]===1)h===-1&&(h=w);else if(h!==-1&&(x===32||x===9))p===-1&&(p=w);else if(x===59||x===44){if(h===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let y=t.slice(h,p);i&&(y=y.replace(/\\/g,""),i=!1),Vt(n,u,y),x===44&&(Vt(e,d,n),n=Object.create(null),d=void 0),u=void 0,h=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(h===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=w);let b=t.slice(h,p);return d===void 0?Vt(e,b,n):(u===void 0?Vt(n,b,!0):i?Vt(n,u,b.replace(/\\/g,"")):Vt(n,u,b),Vt(e,d,n)),e}function oI(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(i=>[e].concat(Object.keys(i).map(s=>{let a=i[s];return Array.isArray(a)||(a=[a]),a.map(d=>d===!0?s:`${s}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}op.exports={format:oI,parse:sI}});var ha=le((DO,wp)=>{"use strict";var aI=xe("events"),cI=xe("https"),dI=xe("http"),dp=xe("net"),lI=xe("tls"),{randomBytes:uI,createHash:fI}=xe("crypto"),{Duplex:TO,Readable:PO}=xe("stream"),{URL:cl}=xe("url"),Bn=ri(),hI=rl(),xI=ol(),{isBlob:pI}=ii(),{BINARY_TYPES:ap,CLOSE_TIMEOUT:gI,EMPTY_BUFFER:la,GUID:mI,kForOnEventAttribute:dl,kListener:wI,kStatusCode:_I,kWebSocket:je,NOOP:lp}=un(),{EventTarget:{addEventListener:yI,removeEventListener:bI}}=sp(),{format:vI,parse:EI}=da(),{toBuffer:SI}=us(),up=Symbol("kAborted"),ll=[8,13],xn=["CONNECTING","OPEN","CLOSING","CLOSED"],II=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_e=class t extends aI{constructor(e,n,i){super(),this._binaryType=ap[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=la,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),fp(this,e,n,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ap.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,i){let s=new hI({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new xI(e,this._extensions,i.generateMask);this._receiver=s,this._sender=a,this._socket=e,s[je]=this,a[je]=this,e[je]=this,s.on("conclude",CI),s.on("drain",TI),s.on("error",PI),s.on("message",DI),s.on("ping",RI),s.on("pong",OI),a.onerror=LI,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",pp),e.on("data",fa),e.on("end",gp),e.on("error",mp),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Bn.extensionName]&&this._extensions[Bn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){gt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),xp(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ul(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||la,n,i)}pong(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ul(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||la,n,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ul(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Bn.extensionName]||(s.compress=!1),this._sender.send(e||la,s,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){gt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_e,"CONNECTING",{enumerable:!0,value:xn.indexOf("CONNECTING")});Object.defineProperty(_e.prototype,"CONNECTING",{enumerable:!0,value:xn.indexOf("CONNECTING")});Object.defineProperty(_e,"OPEN",{enumerable:!0,value:xn.indexOf("OPEN")});Object.defineProperty(_e.prototype,"OPEN",{enumerable:!0,value:xn.indexOf("OPEN")});Object.defineProperty(_e,"CLOSING",{enumerable:!0,value:xn.indexOf("CLOSING")});Object.defineProperty(_e.prototype,"CLOSING",{enumerable:!0,value:xn.indexOf("CLOSING")});Object.defineProperty(_e,"CLOSED",{enumerable:!0,value:xn.indexOf("CLOSED")});Object.defineProperty(_e.prototype,"CLOSED",{enumerable:!0,value:xn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_e.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_e.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[dl])return e[wI];return null},set(e){for(let n of this.listeners(t))if(n[dl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[dl]:!0})}})});_e.prototype.addEventListener=yI;_e.prototype.removeEventListener=bI;wp.exports=_e;function fp(t,e,n,i){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:gI,protocolVersion:ll[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!ll.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ll.join(", ")})`);let a;if(e instanceof cl)a=e;else try{a=new cl(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:",h;if(a.protocol!=="ws:"&&!d&&!u?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!a.pathname?h="The URL's pathname is empty":a.hash&&(h="The URL contains a fragment identifier"),h){let I=new SyntaxError(h);if(t._redirects===0)throw I;ua(t,I);return}let x=d?443:80,p=uI(16).toString("base64"),w=d?cI.request:dI.request,b=new Set,y;if(s.createConnection=s.createConnection||(d?kI:AI),s.defaultPort=s.defaultPort||x,s.port=a.port||x,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(y=new Bn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=vI({[Bn.extensionName]:y.offer()})),n.length){for(let I of n){if(typeof I!="string"||!II.test(I)||b.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(I)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),u){let I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let v;if(s.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?s.socketPath:a.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,C]of Object.entries(I))i.headers[A.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:a.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),v=t._req=w(s),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=w(s);s.timeout&&v.on("timeout",()=>{gt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[up]||(v=t._req=null,ua(t,I))}),v.on("response",I=>{let A=I.headers.location,C=I.statusCode;if(A&&s.followRedirects&&C>=300&&C<400){if(++t._redirects>s.maxRedirects){gt(t,v,"Maximum redirects exceeded");return}v.abort();let P;try{P=new cl(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);ua(t,D);return}fp(t,P,n,i)}else t.emit("unexpected-response",v,I)||gt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,C)=>{if(t.emit("upgrade",I),t.readyState!==_e.CONNECTING)return;v=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){gt(t,A,"Invalid Upgrade header");return}let E=fI("sha1").update(p+mI).digest("base64");if(I.headers["sec-websocket-accept"]!==E){gt(t,A,"Invalid Sec-WebSocket-Accept header");return}let D=I.headers["sec-websocket-protocol"],O;if(D!==void 0?b.size?b.has(D)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":b.size&&(O="Server sent no subprotocol"),O){gt(t,A,O);return}D&&(t._protocol=D);let U=I.headers["sec-websocket-extensions"];if(U!==void 0){if(!y){gt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=EI(U)}catch{gt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(M);if(K.length!==1||K[0]!==Bn.extensionName){gt(t,A,"Server indicated an extension that was not requested");return}try{y.accept(M[Bn.extensionName])}catch{gt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Bn.extensionName]=y}t.setSocket(A,C,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(v,t):v.end()}function ua(t,e){t._readyState=_e.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function AI(t){return t.path=t.socketPath,dp.connect(t)}function kI(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=dp.isIP(t.host)?"":t.host),lI.connect(t)}function gt(t,e,n){t._readyState=_e.CLOSING;let i=new Error(n);Error.captureStackTrace(i,gt),e.setHeader?(e[up]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ua,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ul(t,e,n){if(e){let i=pI(e)?e.size:SI(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${xn[t.readyState]})`);process.nextTick(n,i)}}function CI(t,e){let n=this[je];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[je]!==void 0&&(n._socket.removeListener("data",fa),process.nextTick(hp,n._socket),t===1005?n.close():n.close(t,e))}function TI(){let t=this[je];t.isPaused||t._socket.resume()}function PI(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",fa),process.nextTick(hp,e._socket),e.close(t[_I])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function cp(){this[je].emitClose()}function DI(t,e){this[je].emit("message",t,e)}function RI(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,lp),e.emit("ping",t)}function OI(t){this[je].emit("pong",t)}function hp(t){t.resume()}function LI(t){let e=this[je];e.readyState!==_e.CLOSED&&(e.readyState===_e.OPEN&&(e._readyState=_e.CLOSING,xp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function pp(){let t=this[je];if(this.removeListener("close",pp),this.removeListener("data",fa),this.removeListener("end",gp),t._readyState=_e.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",cp),t._receiver.on("finish",cp))}function fa(t){this[je]._receiver.write(t)||this.pause()}function gp(){let t=this[je];t._readyState=_e.CLOSING,t._receiver.end(),this.end()}function mp(){let t=this[je];this.removeListener("error",mp),this.on("error",lp),t&&(t._readyState=_e.CLOSING,this.destroy())}});var vp=le((OO,bp)=>{"use strict";var RO=ha(),{Duplex:MI}=xe("stream");function _p(t){t.emit("close")}function NI(){!this.destroyed&&this._writableState.finished&&this.destroy()}function yp(t){this.removeListener("error",yp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function BI(t,e){let n=!0,i=new MI({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let u=!d&&i._readableState.objectMode?a.toString():a;i.push(u)||t.pause()}),t.once("error",function(a){i.destroyed||(n=!1,i.destroy(a))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,a){if(t.readyState===t.CLOSED){a(s),process.nextTick(_p,i);return}let d=!1;t.once("error",function(h){d=!0,a(h)}),t.once("close",function(){d||a(s),process.nextTick(_p,i)}),n&&t.terminate()},i._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(s,a,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(s,a,d)});return}t.send(s,d)},i.on("end",NI),i.on("error",yp),i}bp.exports=BI});var fl=le((LO,Ep)=>{"use strict";var{tokenChars:FI}=ii();function zI(t){let e=new Set,n=-1,i=-1,s=0;for(s;s<t.length;s++){let d=t.charCodeAt(s);if(i===-1&&FI[d]===1)n===-1&&(n=s);else if(s!==0&&(d===32||d===9))i===-1&&n!==-1&&(i=s);else if(d===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let u=t.slice(n,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return e.add(a),e}Ep.exports={parse:zI}});var Pp=le((NO,Tp)=>{"use strict";var UI=xe("events"),xa=xe("http"),{Duplex:MO}=xe("stream"),{createHash:HI}=xe("crypto"),Sp=da(),fr=ri(),GI=fl(),qI=ha(),{CLOSE_TIMEOUT:jI,GUID:WI,kWebSocket:KI}=un(),$I=/^[+/0-9A-Za-z]{22}==$/,Ip=0,Ap=1,Cp=2,hl=class extends UI{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:jI,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:qI,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=xa.createServer((i,s)=>{let a=xa.STATUS_CODES[426];s.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),s.end(a)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=VI(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,a,d)=>{this.handleUpgrade(s,a,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ip}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Cp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(gs,this);return}if(e&&this.once("close",e),this._state!==Ap)if(this._state=Ap,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(gs,this):process.nextTick(gs,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{gs(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,i,s){n.on("error",kp);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){hr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){hr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!$I.test(a)){hr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){hr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ms(n,400);return}let h=e.headers["sec-websocket-protocol"],x=new Set;if(h!==void 0)try{x=GI.parse(h)}catch{hr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&p!==void 0){let b=new fr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Sp.parse(p);y[fr.extensionName]&&(b.accept(y[fr.extensionName]),w[fr.extensionName]=b)}catch{hr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(y,v,I,A)=>{if(!y)return ms(n,v||401,I,A);this.completeUpgrade(w,a,x,e,n,i,s)});return}if(!this.options.verifyClient(b))return ms(n,401)}this.completeUpgrade(w,a,x,e,n,i,s)}completeUpgrade(e,n,i,s,a,d,u){if(!a.readable||!a.writable)return a.destroy();if(a[KI])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ip)return ms(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${HI("sha1").update(n+WI).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),p._protocol=w)}if(e[fr.extensionName]){let w=e[fr.extensionName].params,b=Sp.format({[fr.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",x,s),a.write(x.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&Ps(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Km,mkdirSync as $m}from"node:fs";import{join as Vm}from"node:path";function rf(t){let e=t.retentionDays??Xm,n=t.clock??(()=>jn(new Date));Os={bridgeSink:new Ei(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:o=>new Ei(t.agentLogsDir(o),"agent",{retentionDays:e,clock:n})};let i=n();Ps(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])Ps(t.agentLogsDir(o),"agent",i,e)}function Ym(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function sf(t){ic=t}function of(t){return Ir[ic]<=Ir[t]}function af(t,e){let n=Ir[t];return n===void 0?!0:n>=Ir[e]}function Ls(t){nf={...t}}function cf(t){let e=(f,u=2)=>String(f).padStart(u,"0"),n=-t.getTimezoneOffset(),i=n>=0?"+":"-",o=Math.abs(n),a=e(Math.floor(o/60)),d=e(o%60);return`${jn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${a}:${d}`}function at(t,e,n,i,o){try{let a=`${JSON.stringify({ts:cf(new Date),level:e,module:n,msg:i,...o})}
11
+ `;$m(t,{recursive:!0}),Km(Vm(t,Sr("bridge",jn(new Date))),a)}catch{}}function Qm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function Ds(t,e,n,i,o){if(Ir[t]<Ir[ic])return;let a=`${JSON.stringify({ts:cf(new Date),level:t,module:e,msg:n,...nf,...i})}
12
+ `;if(Os){let d=Qm(o,i),f=d?Ym(Os,d):Os.bridgeSink;try{f.write(a)}catch{process.stderr.write(a)}return}t==="error"||t==="warn"?Zm.write(a):Jm.write(a)}function q(t,e){return{debug:(n,i)=>Ds("debug",t,n,i,e),info:(n,i)=>Ds("info",t,n,i,e),warn:(n,i)=>Ds("warn",t,n,i,e),error:(n,i)=>Ds("error",t,n,i,e),child:n=>q(`${t}.${n}`,e),forAgent:n=>q(t,n)}}var Ir,ic,Jm,Zm,nf,Xm,Os,ne=ot(()=>{"use strict";vr();rc();Ir={debug:10,info:20,warn:30,error:40},ic=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Jm=process.stdout,Zm=process.stderr,nf={},Xm=Je("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Os=null});var k,Ze=ot(()=>{"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 uf={};tc(uf,{ACP_WRAPPER_NPM_PACKAGES:()=>Ns,_resetAcpInstallerForTests:()=>sw,_setBinaryPathCacheForTests:()=>ow,buildAcpSpawn:()=>bi,ensureAcpInstalled:()=>kr,getAcpBinaryPath:()=>Fs,pickWhichLine:()=>ac,probeAcpVersion:()=>iw,resolveAcpCommand:()=>ff});import{readFileSync as df}from"node:fs";import{createRequire as ew}from"node:module";import{dirname as tw,resolve as nw}from"node:path";function oc(t){if(t!=="codex")return;let e=process.env.COZE_BRIDGE_CODEX_ACP_BIN?.trim();return e||void 0}function ac(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 rw(t){let e=lf.resolve(`${t.npmPackage}/package.json`),n=tw(e),i=JSON.parse(df(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 nw(n,o)}async function kr(t,e){let n=sc[t];if(!n)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=Ar.get(t);if(i)return i;let o=oc(t);if(o)return Ar.set(t,o),Ms.info("acp wrapper overridden by env",{framework:t,path:o}),o;try{let a=rw(n);return Ar.set(t,a),Ms.info("acp wrapper resolved",{framework:t,binary:n.binary,path:a}),a}catch(a){throw Ms.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 iw(t){let e=sc[t];if(e)try{let n=lf.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(df(n,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(n){Ms.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(n)});return}}function Fs(t){return Ar.get(t)}function ff(t,e){if(e)return e;let n=oc(t);if(n)return n;let i=Fs(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 bi(t,e,n){if(e)return{command:e,args:[...n]};let i=oc(t);if(i)return{command:i,args:[...n]};let o=ff(t);return{command:process.execPath,args:[o,...n]}}function sw(){Ar.clear()}function ow(t,e){Ar.set(t,e)}var Ms,sc,Ns,lf,Ar,vn=ot(()=>{"use strict";Ze();ne();Ms=q("agents.acp-installer"),sc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Ns=Object.values(sc).filter(t=>t!==void 0).map(t=>t.npmPackage),lf=ew(import.meta.url),Ar=new Map});import{chmod as cw,mkdir as dw,readFile as lw,rename as fw,rm as uw,writeFile as hw}from"node:fs/promises";import{dirname as xw}from"node:path";async function Ye(t){try{let e=await lw(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function _t(t,e,n){await dw(xw(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await hw(i,e,{encoding:"utf8",mode:n?.mode}),await fw(i,t),n?.mode!==void 0&&await cw(t,n.mode)}catch(o){throw await uw(i,{force:!0}).catch(()=>{}),o}}async function ut(t,e,n){await _t(t,`${JSON.stringify(e,null,2)}
14
+ `,n)}var Ct=ot(()=>{"use strict"});import{promises as pf,readdirSync as pw}from"node:fs";import{homedir as gw}from"node:os";import{sep as mw,join as Re,resolve as gf}from"node:path";function Z(t){let e=t??gw(),n=Re(e,".coze"),i=Re(n,"bridge"),o=Re(i,"lib"),a=Re(i,"logs");return{cozeRoot:n,bridgeRoot:i,libDir:o,libEntry:Re(o,"index.js"),binDir:Re(i,"bin"),pidFile:Re(i,"bridge.pid"),portFile:Re(i,"bridge.port"),tokenFile:Re(i,"bridge.token"),patTokenFile:Re(i,"pat-token"),agentEnvFile:Re(i,"agent-env.json"),logFile:Re(i,"bridge.log"),bridgeLogsDir:a,daemonStdioLog:Re(a,"daemon-stdio.log"),installLock:Re(i,"install.lock"),configFile:Re(i,"config.json"),modelCacheFile:Re(i,"model-cache.json"),agentsRoot:Re(n,"agents")}}function Oe(t,e=Z()){let n=Re(e.agentsRoot,t);return{root:n,config:Re(n,"config.json"),workspace:Re(n,"workspace"),logs:Re(n,"logs")}}function Bs(t=Z()){try{return pw(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function vi(t,e){let n=await pf.realpath(gf(t)).catch(()=>null);if(!n)return!1;let i=await pf.realpath(gf(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+mw)}var Pe=ot(()=>{"use strict"});var Us={};tc(Us,{AGENT_CONFIG_FILE_MODE:()=>zs,enforceAgentConfigMode:()=>yw,loadAgentConfig:()=>we,persistAgentSessions:()=>Si,persistAgentSkills:()=>Ii,saveAgentConfig:()=>Le});import{chmod as ww,stat as _w}from"node:fs/promises";function we(t,e){return Ye(Oe(t,e).config)}function Le(t,e){return ut(Oe(t.agentId,e).config,t,{mode:zs})}async function yw(t,e){if(process.platform==="win32")return;let n=Oe(t,e).config;try{let i=await _w(n);if(!i.isFile())return;let o=i.mode&511;o!==zs&&(await ww(n,zs),mf.warn("agent config mode auto-corrected to 0600",{path:n,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;mf.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(i)})}}async function Si(t,e,n){let i=await we(t,n);i&&(i.sessions=Object.fromEntries(e),await Le(i,n))}async function Ii(t,e,n){let i=await we(t,n);i&&(i.skills=e,await Le(i,n))}var mf,zs,tn=ot(()=>{"use strict";Ct();ne();Pe();mf=q("agent-config"),zs=384});var lc=fe((cT,yf)=>{yf.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 qs=fe(bf=>{var Ef={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 Aw(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(Ef))bf[t]=Aw(Ef[t])});var kf=fe((lT,Af)=>{var kw=ge("fs"),ze=ge("path"),vf=lc(),Tw=qs(),Cw=typeof process=="object"&&process.platform==="win32",Sf=t=>typeof t=="object"&&t!==null,If=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 ke(t){this.sep=ze.sep,this.fs=kw,Sf(t)&&Sf(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Af.exports=ke;ke.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(f){if(f.message&&f.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw f}if(d&&d.isFile())throw Tw.FILE_IN_THE_WAY(`"${o}"`)}})}n(t)};ke.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 f;try{f=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),f=o.fs.openSync(t,"w",438)}if(f)try{o.fs.writeSync(f,e,0,e.length,0)}finally{o.fs.closeSync(f)}return o.fs.chmodSync(t,i||438),!0};ke.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(f,u){if(d&&u.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(w,b){w?a.fs.chmod(t,438,function(){a.fs.open(t,"w",438,function(_,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)})})})})}):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)})})}):a.fs.chmod(t,i||438,function(){o(!0)})})})})})};ke.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(f){let u=ze.join(i,f),x=e.fs.statSync(u);(!o||o.test(u))&&d.push(ze.normalize(u)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&a&&(d=d.concat(n(u,o,a)))}),d}return n(t,void 0,!0)};ke.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(f){f=ze.join(t,f),n.fs.stat(f,function(u,x){if(u)return e(u);x&&(i.push(ze.normalize(f)+(x.isDirectory()?n.sep:"")),x.isDirectory()?n.findFilesAsync(f,function(p,w){if(p)return e(p);i=i.concat(w),--d||e(null,i)}):--d||e(null,i))})})})};ke.prototype.getAttributes=function(){};ke.prototype.setAttributes=function(){};ke.crc32update=function(t,e){return If[(t^e)&255]^t>>>8};ke.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let i=0;i<e;)n=ke.crc32update(n,t[i++]);return~n>>>0};ke.methodToString=function(t){switch(t){case vf.STORED:return"STORED ("+t+")";case vf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ke.canonical=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.join(".",e)};ke.zipnamefix=function(t){if(!t)return"";let e=ze.posix.normalize("/"+t.split("\\").join("/"));return ze.posix.join(".",e)};ke.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]};ke.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)))};ke.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};ke.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};ke.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)};ke.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};ke.isWin=Cw;ke.crcTable=If});var Cf=fe((fT,Tf)=>{var Rw=ge("path");Tf.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=Rw.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 Pf=fe((uT,Rf)=>{Rf.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Rr=fe((hT,Cr)=>{Cr.exports=kf();Cr.exports.Constants=lc();Cr.exports.Errors=qs();Cr.exports.FileAttr=Cf();Cr.exports.decoder=Pf()});var Of=fe((xT,Df)=>{var Sn=Rr(),z=Sn.Constants;Df.exports=function(){var t=20,e=10,n=0,i=0,o=0,a=0,d=0,f=0,u=0,x=0,p=0,w=0,b=0,_=0,v=0;t|=Sn.isWin?2560:768,n|=z.FLG_EFS;let I={extraLen:0},A=E=>Math.max(0,E)>>>0,T=E=>Math.max(0,E)&65535,R=E=>Math.max(0,E)&255;return o=Sn.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&z.FLG_EFS)>0},set flags_efs(E){E?n|=z.FLG_EFS:n&=~z.FLG_EFS},get flags_desc(){return(n&z.FLG_DESC)>0},set flags_desc(E){E?n|=z.FLG_DESC:n&=~z.FLG_DESC},get method(){return i},set method(E){switch(E){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=E},get time(){return Sn.fromDOS2Date(this.timeval)},set time(E){E=new Date(E),this.timeval=Sn.fromDate2DOS(E)},get timeval(){return o},set timeval(E){o=A(E)},get timeHighByte(){return R(o>>>8)},get crc(){return a},set crc(E){a=A(E)},get compressedSize(){return d},set compressedSize(E){d=A(E)},get size(){return f},set size(E){f=A(E)},get fileNameLength(){return u},set fileNameLength(E){u=E},get extraLength(){return x},set extraLength(E){x=E},get extraLocalLength(){return I.extraLen},set extraLocalLength(E){I.extraLen=E},get commentLength(){return p},set commentLength(E){p=E},get diskNumStart(){return w},set diskNumStart(E){w=A(E)},get inAttr(){return b},set inAttr(E){b=A(E)},get attr(){return _},set attr(E){_=A(E)},get fileAttr(){return(_||0)>>16&4095},get offset(){return v},set offset(E){v=A(E)},get encrypted(){return(n&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+u+x+p},get realDataOffset(){return v+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(E){var P=E.slice(v,v+z.LOCHDR);if(P.readUInt32LE(0)!==z.LOCSIG)throw Sn.Errors.INVALID_LOC();I.version=P.readUInt16LE(z.LOCVER),I.flags=P.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=P.readUInt16LE(z.LOCHOW),I.time=P.readUInt32LE(z.LOCTIM),I.crc=P.readUInt32LE(z.LOCCRC),I.compressedSize=P.readUInt32LE(z.LOCSIZ),I.size=P.readUInt32LE(z.LOCLEN),I.fnameLen=P.readUInt16LE(z.LOCNAM),I.extraLen=P.readUInt16LE(z.LOCEXT);let D=v+z.LOCHDR+I.fnameLen,U=D+I.extraLen;return E.slice(D,U)},loadFromBinary:function(E){if(E.length!==z.CENHDR||E.readUInt32LE(0)!==z.CENSIG)throw Sn.Errors.INVALID_CEN();t=E.readUInt16LE(z.CENVEM),e=E.readUInt16LE(z.CENVER),n=E.readUInt16LE(z.CENFLG),i=E.readUInt16LE(z.CENHOW),o=E.readUInt32LE(z.CENTIM),a=E.readUInt32LE(z.CENCRC),d=E.readUInt32LE(z.CENSIZ),f=E.readUInt32LE(z.CENLEN),u=E.readUInt16LE(z.CENNAM),x=E.readUInt16LE(z.CENEXT),p=E.readUInt16LE(z.CENCOM),w=E.readUInt16LE(z.CENDSK),b=E.readUInt16LE(z.CENATT),_=E.readUInt32LE(z.CENATX),v=E.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var E=Buffer.alloc(z.LOCHDR);return E.writeUInt32LE(z.LOCSIG,0),E.writeUInt16LE(e,z.LOCVER),E.writeUInt16LE(n,z.LOCFLG),E.writeUInt16LE(i,z.LOCHOW),E.writeUInt32LE(o,z.LOCTIM),E.writeUInt32LE(a,z.LOCCRC),E.writeUInt32LE(d,z.LOCSIZ),E.writeUInt32LE(f,z.LOCLEN),E.writeUInt16LE(u,z.LOCNAM),E.writeUInt16LE(I.extraLen,z.LOCEXT),E},centralHeaderToBinary:function(){var E=Buffer.alloc(z.CENHDR+u+x+p);return E.writeUInt32LE(z.CENSIG,0),E.writeUInt16LE(t,z.CENVEM),E.writeUInt16LE(e,z.CENVER),E.writeUInt16LE(n,z.CENFLG),E.writeUInt16LE(i,z.CENHOW),E.writeUInt32LE(o,z.CENTIM),E.writeUInt32LE(a,z.CENCRC),E.writeUInt32LE(d,z.CENSIZ),E.writeUInt32LE(f,z.CENLEN),E.writeUInt16LE(u,z.CENNAM),E.writeUInt16LE(x,z.CENEXT),E.writeUInt16LE(p,z.CENCOM),E.writeUInt16LE(w,z.CENDSK),E.writeUInt16LE(b,z.CENATT),E.writeUInt32LE(_,z.CENATX),E.writeUInt32LE(v,z.CENOFF),E},toJSON:function(){let E=function(P){return P+" bytes"};return{made:t,version:e,flags:n,method:Sn.methodToString(i),time:this.time,crc:"0x"+a.toString(16).toUpperCase(),compressedSize:E(d),size:E(f),fileNameLength:E(u),extraLength:E(x),commentLength:E(p),diskNumStart:w,inAttr:b,attr:_,offset:v,centralHeaderSize:E(z.CENHDR+u+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Mf=fe((pT,Lf)=>{var Pr=Rr(),ve=Pr.Constants;Lf.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 ve.ENDHDR+o},loadFromBinary:function(a){if((a.length!==ve.ENDHDR||a.readUInt32LE(0)!==ve.ENDSIG)&&(a.length<ve.ZIP64HDR||a.readUInt32LE(0)!==ve.ZIP64SIG))throw Pr.Errors.INVALID_END();a.readUInt32LE(0)===ve.ENDSIG?(t=a.readUInt16LE(ve.ENDSUB),e=a.readUInt16LE(ve.ENDTOT),n=a.readUInt32LE(ve.ENDSIZ),i=a.readUInt32LE(ve.ENDOFF),o=a.readUInt16LE(ve.ENDCOM)):(t=Pr.readBigUInt64LE(a,ve.ZIP64SUB),e=Pr.readBigUInt64LE(a,ve.ZIP64TOT),n=Pr.readBigUInt64LE(a,ve.ZIP64SIZE),i=Pr.readBigUInt64LE(a,ve.ZIP64OFF),o=0)},toBinary:function(){var a=Buffer.alloc(ve.ENDHDR+o);return a.writeUInt32LE(ve.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,ve.ENDSUB),a.writeUInt16LE(e,ve.ENDTOT),a.writeUInt32LE(n,ve.ENDSIZ),a.writeUInt32LE(i,ve.ENDOFF),a.writeUInt16LE(o,ve.ENDCOM),a.fill(" ",ve.ENDHDR),a},toJSON:function(){let a=function(d,f){let u=d.toString(16).toUpperCase();for(;u.length<f;)u="0"+u;return"0x"+u};return{diskEntries:t,totalEntries:e,size:n+" bytes",offset:a(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var uc=fe(fc=>{fc.EntryHeader=Of();fc.MainHeader=Mf()});var Ff=fe((mT,Nf)=>{Nf.exports=function(t){var e=ge("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(i){var o=e.createDeflateRaw(n),a=[],d=0;o.on("data",function(f){a.push(f),d+=f.length}),o.on("end",function(){var f=Buffer.alloc(d),u=0;f.fill(0);for(var x=0;x<a.length;x++){var p=a[x];p.copy(f,u),u+=p.length}i&&i(f)}),o.end(t)}}}});var zf=fe((wT,Bf)=>{var Pw=+(process.versions?process.versions.node:"").split(".")[0]||0;Bf.exports=function(t,e){var n=ge("zlib");let i=Pw>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,i)},inflateAsync:function(o){var a=n.createInflateRaw(i),d=[],f=0;a.on("data",function(u){d.push(u),f+=u.length}),a.on("end",function(){var u=Buffer.alloc(f),x=0;u.fill(0);for(var p=0;p<d.length;p++){var w=d[p];w.copy(u,x),x+=w.length}o&&o(u)}),a.end(t)}}}});var jf=fe((_T,Gf)=>{"use strict";var{randomFillSync:Uf}=ge("crypto"),Dw=qs(),Ow=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}),qf=(t,e)=>Math.imul(t,e)>>>0,Hf=(t,e)=>Ow[(t^e)&255]^t>>>8,Ai=()=>typeof Uf=="function"?Uf(Buffer.alloc(12)):Ai.node();Ai.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 Gs={genSalt:Ai};function js(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])}js.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Hf(e[0],t),e[1]+=e[0]&255,e[1]=qf(e[1],134775813)+1,e[2]=Hf(e[2],e[1]>>>24),t};js.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return qf(t,t^1)>>8&255};function Lw(t){let e=new js(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 Mw(t){let e=new js(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 Nw(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Lw(n),o=i(t.slice(0,12)),a=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==a)throw Dw.WRONG_PASSWORD();return i(t.slice(12))}function Fw(t){Buffer.isBuffer(t)&&t.length>=12?Gs.genSalt=function(){return t.slice(0,12)}:t==="node"?Gs.genSalt=Ai.node:Gs.genSalt=Ai}function Bw(t,e,n,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=Mw(n),a=Gs.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)}Gf.exports={decrypt:Nw,encrypt:Bw,_salter:Fw}});var Wf=fe(Ws=>{Ws.Deflater=Ff();Ws.Inflater=zf();Ws.ZipCrypto=jf()});var xc=fe((ET,Kf)=>{var ue=Rr(),zw=uc(),Te=ue.Constants,hc=Wf();Kf.exports=function(t,e){var n=new zw.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),a=!1,d=null,f=Buffer.alloc(0),u=Buffer.alloc(0),x=!0;let p=t,w=typeof p.decoder=="object"?p.decoder:ue.decoder;x=w.hasOwnProperty("efs")?w.efs:!1;function b(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(u=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function _(E){if(!n.flags_desc&&!n.localHeader.flags_desc){if(ue.crc32(E)!==n.localHeader.crc)return!1}else{let P={},D=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(D)==Te.LOCSIG||e.readUInt32LE(D)==Te.CENSIG)throw ue.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==Te.EXTSIG)P.crc=e.readUInt32LE(D+Te.EXTCRC),P.compressedSize=e.readUInt32LE(D+Te.EXTSIZ),P.size=e.readUInt32LE(D+Te.EXTLEN);else if(e.readUInt16LE(D+12)===19280)P.crc=e.readUInt32LE(D+Te.EXTCRC-4),P.compressedSize=e.readUInt32LE(D+Te.EXTSIZ-4),P.size=e.readUInt32LE(D+Te.EXTLEN-4);else throw ue.Errors.DESCRIPTOR_UNKNOWN();if(P.compressedSize!==n.compressedSize||P.size!==n.size||P.crc!==n.crc)throw ue.Errors.DESCRIPTOR_FAULTY();if(ue.crc32(E)!==P.crc)return!1}return!0}function v(E,P,D){if(typeof P>"u"&&typeof E=="string"&&(D=E,E=void 0),a)return E&&P&&P(Buffer.alloc(0),ue.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var U=b();if(U.length===0)return E&&P&&P(U),U;if(n.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw ue.Errors.INVALID_PASS_PARAM();U=hc.ZipCrypto.decrypt(U,n,D)}var N=Buffer.alloc(n.size);switch(n.method){case ue.Constants.STORED:if(U.copy(N),_(N))return E&&P&&P(N),N;throw E&&P&&P(N,ue.Errors.BAD_CRC()),ue.Errors.BAD_CRC();case ue.Constants.DEFLATED:var K=new hc.Inflater(U,n.size);if(E)K.inflateAsync(function(J){J.copy(J,0),P&&(_(J)?P(J):P(J,ue.Errors.BAD_CRC()))});else{if(K.inflate(N).copy(N,0),!_(N))throw ue.Errors.BAD_CRC(`"${w.decode(i)}"`);return N}break;default:throw E&&P&&P(Buffer.alloc(0),ue.Errors.UNKNOWN_METHOD()),ue.Errors.UNKNOWN_METHOD()}}function I(E,P){if((!d||!d.length)&&Buffer.isBuffer(e))return E&&P&&P(b()),b();if(d.length&&!a){var D;switch(n.method){case ue.Constants.STORED:return n.compressedSize=n.size,D=Buffer.alloc(d.length),d.copy(D),E&&P&&P(D),D;default:case ue.Constants.DEFLATED:var U=new hc.Deflater(d);if(E)U.deflateAsync(function(K){D=Buffer.alloc(K.length),n.compressedSize=K.length,K.copy(D),P&&P(D)});else{var N=U.deflate();return n.compressedSize=N.length,N}U=null;break}}else if(E&&P)P(Buffer.alloc(0));else return Buffer.alloc(0)}function A(E,P){return ue.readBigUInt64LE(E,P)}function T(E){try{for(var P=0,D,U,N;P+4<E.length;)D=E.readUInt16LE(P),P+=2,U=E.readUInt16LE(P),P+=2,N=E.slice(P,P+U),P+=U,Te.ID_ZIP64===D&&R(N)}catch{throw ue.Errors.EXTRA_FIELD_PARSE_ERROR()}}function R(E){var P,D,U,N;E.length>=Te.EF_ZIP64_SCOMP&&(P=A(E,Te.EF_ZIP64_SUNCOMP),n.size===Te.EF_ZIP64_OR_32&&(n.size=P)),E.length>=Te.EF_ZIP64_RHO&&(D=A(E,Te.EF_ZIP64_SCOMP),n.compressedSize===Te.EF_ZIP64_OR_32&&(n.compressedSize=D)),E.length>=Te.EF_ZIP64_DSN&&(U=A(E,Te.EF_ZIP64_RHO),n.offset===Te.EF_ZIP64_OR_32&&(n.offset=U)),E.length>=Te.EF_ZIP64_DSN+4&&(N=E.readUInt32LE(Te.EF_ZIP64_DSN),n.diskNumStart===Te.EF_ZIP64_OR_16&&(n.diskNumStart=N))}return{get entryName(){return w.decode(i)},get rawEntryName(){return i},set entryName(E){i=ue.toBuffer(E,w.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 f},set extra(E){f=E,n.extraLength=E.length,T(E)},get comment(){return w.decode(o)},set comment(E){if(o=ue.toBuffer(E,w.encode),n.commentLength=o.length,o.length>65535)throw ue.Errors.COMMENT_TOO_LONG()},get name(){var E=w.decode(i);return a?E.substr(E.length-1).split("/").pop():E.split("/").pop()},get isDirectory(){return a},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(E){I(!0,E)},setData:function(E){d=ue.toBuffer(E,ue.decoder.encode),!a&&d.length?(n.size=d.length,n.method=ue.Constants.DEFLATED,n.crc=ue.crc32(E),n.changed=!0):n.method=ue.Constants.STORED},getData:function(E){return n.changed?d:v(!1,null,E)},getDataAsync:function(E,P){n.changed?E(d):v(!0,E,P)},set attr(E){n.attr=E},get attr(){return n.attr},set header(E){n.loadFromBinary(E)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=f.length;var E=n.centralHeaderToBinary(),P=ue.Constants.CENHDR;return i.copy(E,P),P+=i.length,f.copy(E,P),P+=n.extraLength,o.copy(E,P),E},packLocalHeader:function(){let E=0;n.flags_efs=this.efs,n.extraLocalLength=u.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,u.copy(D,E),E+=u.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 Jf=fe((bT,Vf)=>{var $f=xc(),Uw=uc(),Xe=Rr();Vf.exports=function(t,e){var n=[],i={},o=Buffer.alloc(0),a=new Uw.MainHeader,d=!1,f=null;let u=new Set,x=e,{noSort:p,decoder:w}=x;t?v(x.readEntries):d=!0;function b(){let A=new Set;for(let T of Object.keys(i)){let R=T.split("/");if(R.pop(),!!R.length)for(let E=0;E<R.length;E++){let P=R.slice(0,E+1).join("/")+"/";A.add(P)}}for(let T of A)if(!(T in i)){let R=new $f(x);R.entryName=T,R.attr=16,R.temporary=!0,n.push(R),i[R.entryName]=R,u.add(R)}}function _(){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 R=A,E=new $f(x,t);E.header=t.slice(R,R+=Xe.Constants.CENHDR),E.entryName=t.slice(R,R+=E.header.fileNameLength),E.header.extraLength&&(E.extra=t.slice(R,R+=E.header.extraLength)),E.header.commentLength&&(E.comment=t.slice(R,R+E.header.commentLength)),A+=E.header.centralHeaderSize,n[T]=E,i[E.entryName]=E}u.clear(),b()}function v(A){var T=t.length-Xe.Constants.ENDHDR,R=Math.max(0,T-65535),E=R,P=t.length,D=-1,U=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(R=0),T;T>=E;T--)if(t[T]===80){if(t.readUInt32LE(T)===Xe.Constants.ENDSIG){D=T,U=T,P=T+Xe.Constants.ENDHDR,E=T-Xe.Constants.END64HDR;continue}if(t.readUInt32LE(T)===Xe.Constants.END64SIG){E=R;continue}if(t.readUInt32LE(T)===Xe.Constants.ZIP64SIG){D=T,P=T+Xe.readBigUInt64LE(t,T+Xe.Constants.ZIP64SIZE)+Xe.Constants.ZIP64LEAD;break}}if(D==-1)throw Xe.Errors.INVALID_FORMAT();a.loadFromBinary(t.slice(D,P)),a.commentLength&&(o=t.slice(U+Xe.Constants.ENDHDR)),A&&_()}function I(){n.length>1&&!p&&n.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||_(),n.filter(A=>!u.has(A))},get comment(){return w.decode(o)},set comment(A){o=Xe.toBuffer(A,w.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||_(),i[A]||null},setEntry:function(A){d||_(),n.push(A),i[A.entryName]=A,a.totalEntries=n.length},deleteFile:function(A,T=!0){d||_();let R=i[A];this.getEntryChildren(R,T).map(P=>P.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||_();let T=i[A],R=n.indexOf(T);R>=0&&(n.splice(R,1),delete i[A],a.totalEntries=n.length)},getEntryChildren:function(A,T=!0){if(d||_(),typeof A=="object")if(A.isDirectory&&T){let R=[],E=A.entryName;for(let P of n)P.entryName.startsWith(E)&&R.push(P);return R}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||_(),I();let A=[],T=[],R=0,E=0;a.size=0,a.offset=0;let P=0;for(let N of this.entries){let K=N.getCompressedData();N.header.offset=E;let J=N.packLocalHeader(),ie=J.length+K.length;E+=ie,A.push(J),A.push(K);let Y=N.packCentralHeader();T.push(Y),a.size+=Y.length,R+=ie+Y.length,P++}R+=a.mainHeaderSize,a.offset=E,a.totalEntries=P,E=0;let D=Buffer.alloc(R);for(let N of A)N.copy(D,E),E+=N.length;for(let N of T)N.copy(D,E),E+=N.length;let U=a.toBinary();return o&&o.copy(U,Xe.Constants.ENDHDR),U.copy(D,E),t=D,d=!1,D},toAsyncBuffer:function(A,T,R,E){try{d||_(),I();let P=[],D=[],U=0,N=0,K=0;a.size=0,a.offset=0;let J=function(ie){if(ie.length>0){let Y=ie.shift(),oe=Y.entryName+Y.extra.toString();R&&R(oe),Y.getCompressedDataAsync(function(le){E&&E(oe),Y.header.offset=N;let Ee=Y.packLocalHeader(),qe=Ee.length+le.length;N+=qe,P.push(Ee),P.push(le);let C=Y.packCentralHeader();D.push(C),a.size+=C.length,U+=qe+C.length,K++,J(ie)})}else{U+=a.mainHeaderSize,a.offset=N,a.totalEntries=K,N=0;let Y=Buffer.alloc(U);P.forEach(function(le){le.copy(Y,N),N+=le.length}),D.forEach(function(le){le.copy(Y,N),N+=le.length});let oe=a.toBinary();o&&o.copy(oe,Xe.Constants.ENDHDR),oe.copy(Y,N),t=Y,d=!1,A(Y)}};J(Array.from(this.entries))}catch(P){T(P)}}}}});var Yf=fe((vT,Xf)=>{var Ie=Rr(),Se=ge("path"),Hw=xc(),qw=Jf(),Wn=(...t)=>Ie.findLast(t,e=>typeof e=="boolean"),Zf=(...t)=>Ie.findLast(t,e=>typeof e=="string"),Gw=(...t)=>Ie.findLast(t,e=>typeof e=="function"),jw={noSort:!1,readEntries:!1,method:Ie.Constants.NONE,fs:null};Xf.exports=function(t,e){let n=null,i=Object.assign(Object.create(null),jw);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=Ie.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new Ie(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=Ie.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=Ie.Constants.FILE,i.filename=t,n=o.fs.readFileSync(t);else throw Ie.Errors.INVALID_FILENAME();let a=new qw(n,i),{canonical:d,sanitize:f,zipnamefix:u}=Ie;function x(_){if(_&&a){var v;if(typeof _=="string"&&(v=a.getEntry(Se.posix.normalize(_))),typeof _=="object"&&typeof _.entryName<"u"&&typeof _.header<"u"&&(v=a.getEntry(_.entryName)),v)return v}return null}function p(_){let{join:v,normalize:I,sep:A}=Se.posix;return v(Se.isAbsolute(_)?"/":".",I(A+_.split("\\").join(A)+A))}function w(_){return _ instanceof RegExp?(function(v){return function(I){return v.test(I)}})(_):typeof _!="function"?()=>!0:_}let b=(_,v)=>{let I=v.slice(-1);return I=I===o.sep?o.sep:"",Se.relative(_,v)+I};return{readFile:function(_,v){var I=x(_);return I&&I.getData(v)||null},childCount:function(_){let v=x(_);if(v)return a.getChildCount(v)},readFileAsync:function(_,v){var I=x(_);I?I.getDataAsync(v):v(null,"getEntry failed for:"+_)},readAsText:function(_,v){var I=x(_);if(I){var A=I.getData();if(A&&A.length)return A.toString(v||"utf8")}return""},readAsTextAsync:function(_,v,I){var A=x(_);A?A.getDataAsync(function(T,R){if(R){v(T,R);return}T&&T.length?v(T.toString(I||"utf8")):v("")}):v("")},deleteFile:function(_,v=!0){var I=x(_);I&&a.deleteFile(I.entryName,v)},deleteEntry:function(_){var v=x(_);v&&a.deleteEntry(v.entryName)},addZipComment:function(_){a.comment=_},getZipComment:function(){return a.comment||""},addZipEntryComment:function(_,v){var I=x(_);I&&(I.comment=v)},getZipEntryComment:function(_){var v=x(_);return v&&v.comment||""},updateFile:function(_,v){var I=x(_);I&&I.setData(v)},addLocalFile:function(_,v,I,A){if(o.fs.existsSync(_)){v=v?p(v):"";let T=Se.win32.basename(Se.win32.normalize(_));v+=I||T;let R=o.fs.statSync(_),E=R.isFile()?o.fs.readFileSync(_):Buffer.alloc(0);R.isDirectory()&&(v+=o.sep),this.addFile(v,E,A,R)}else throw Ie.Errors.FILE_NOT_FOUND(_)},addLocalFileAsync:function(_,v){_=typeof _=="object"?_:{localPath:_};let I=Se.resolve(_.localPath),{comment:A}=_,{zipPath:T,zipName:R}=_,E=this;o.fs.stat(I,function(P,D){if(P)return v(P,!1);T=T?p(T):"";let U=Se.win32.basename(Se.win32.normalize(I));if(T+=R||U,D.isFile())o.fs.readFile(I,function(N,K){return N?v(N,!1):(E.addFile(T,K,A,D),setImmediate(v,void 0,!0))});else if(D.isDirectory())return T+=o.sep,E.addFile(T,Buffer.alloc(0),A,D),setImmediate(v,void 0,!0)})},addLocalFolder:function(_,v,I){if(I=w(I),v=v?p(v):"",_=Se.normalize(_),o.fs.existsSync(_)){let A=o.findFiles(_),T=this;if(A.length)for(let R of A){let E=Se.join(v,b(_,R));I(E)&&T.addLocalFile(R,Se.dirname(E))}}else throw Ie.Errors.FILE_NOT_FOUND(_)},addLocalFolderAsync:function(_,v,I,A){A=w(A),I=I?p(I):"",_=Se.normalize(_);var T=this;o.fs.open(_,"r",function(R){if(R&&R.code==="ENOENT")v(void 0,Ie.Errors.FILE_NOT_FOUND(_));else if(R)v(void 0,R);else{var E=o.findFiles(_),P=-1,D=function(){if(P+=1,P<E.length){var U=E[P],N=b(_,U).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(N)?o.fs.stat(U,function(K,J){K&&v(void 0,K),J.isFile()?o.fs.readFile(U,function(ie,Y){ie?v(void 0,ie):(T.addFile(I+N,Y,"",J),D())}):(T.addFile(I+N+"/",Buffer.alloc(0),"",J),D())}):process.nextTick(()=>{D()})}else v(!0,void 0)};D()}})},addLocalFolderAsync2:function(_,v){let I=this;_=typeof _=="object"?_:{localPath:_},localPath=Se.resolve(p(_.localPath));let{zipPath:A,filter:T,namefix:R}=_;T instanceof RegExp?T=(function(D){return function(U){return D.test(U)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?p(A):"",R=="latin1"&&(R=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof R!="function"&&(R=D=>D);let E=D=>Se.join(A,R(b(localPath,D))),P=D=>Se.win32.basename(Se.win32.normalize(R(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?v(void 0,Ie.Errors.FILE_NOT_FOUND(localPath)):D?v(void 0,D):o.findFilesAsync(localPath,function(U,N){if(U)return v(U);N=N.filter(K=>T(E(K))),N.length||v(void 0,!1),setImmediate(N.reverse().reduce(function(K,J){return function(ie,Y){if(ie||Y===!1)return setImmediate(K,ie,!1);I.addLocalFileAsync({localPath:J,zipPath:Se.dirname(E(J)),zipName:P(J)},K)}},v))})})},addLocalFolderPromise:function(_,v){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:_},v),(T,R)=>{T&&A(T),R&&I(this)})})},addFile:function(_,v,I,A){_=u(_);let T=x(_),R=T!=null;R||(T=new Hw(i),T.entryName=_),T.comment=I||"";let E=typeof A=="object"&&A instanceof o.fs.Stats;E&&(T.header.time=A.mtime);var P=T.isDirectory?16:0;let D=T.isDirectory?16384:32768;return E?D|=4095&A.mode:typeof A=="number"?D|=4095&A:D|=T.isDirectory?493:420,P=(P|D<<16)>>>0,T.attr=P,T.setData(v),R||a.setEntry(T),T},getEntries:function(_){return a.password=_,a?a.entries:[]},getEntry:function(_){return x(_)},getEntryCount:function(){return a.getEntryCount()},forEach:function(_){return a.forEach(_)},extractEntryTo:function(_,v,I,A,T,R){A=Wn(!1,A),T=Wn(!1,T),I=Wn(!0,I),R=Zf(T,R);var E=x(_);if(!E)throw Ie.Errors.NO_ENTRY();var P=d(E.entryName),D=f(v,R&&!E.isDirectory?R:I?P:Se.basename(P));if(E.isDirectory){var U=a.getEntryChildren(E);return U.forEach(function(J){if(J.isDirectory)return;var ie=J.getData();if(!ie)throw Ie.Errors.CANT_EXTRACT_FILE();var Y=d(J.entryName),oe=f(v,I?Y:Se.basename(Y));let le=T?J.header.fileAttr:void 0;o.writeFileTo(oe,ie,A,le)}),!0}var N=E.getData(a.password);if(!N)throw Ie.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!A)throw Ie.Errors.CANT_OVERRIDE();let K=T?_.header.fileAttr:void 0;return o.writeFileTo(D,N,A,K),!0},test:function(_){if(!a)return!1;for(var v in a.entries)try{if(v.isDirectory)continue;var I=a.entries[v].getData(_);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(_,v,I,A){if(I=Wn(!1,I),A=Zf(I,A),v=Wn(!1,v),!a)throw Ie.Errors.NO_ZIP();a.entries.forEach(function(T){var R=f(_,d(T.entryName));if(T.isDirectory){o.makeDir(R);return}var E=T.getData(A);if(!E)throw Ie.Errors.CANT_EXTRACT_FILE();let P=I?T.header.fileAttr:void 0;o.writeFileTo(R,E,v,P);try{o.fs.utimesSync(R,T.header.time,T.header.time)}catch{throw Ie.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(_,v,I,A){if(A=Gw(v,I,A),I=Wn(!1,I),v=Wn(!1,v),!A)return new Promise((D,U)=>{this.extractAllToAsync(_,v,I,function(N){N?U(N):D(this)})});if(!a){A(Ie.Errors.NO_ZIP());return}_=Se.resolve(_);let T=D=>f(_,Se.normalize(d(D.entryName))),R=(D,U)=>new Error(D+': "'+U+'"'),E=[],P=[];a.entries.forEach(D=>{D.isDirectory?E.push(D):P.push(D)});for(let D of E){let U=T(D),N=I?D.header.fileAttr:void 0;try{o.makeDir(U),N&&o.fs.chmodSync(U,N),o.fs.utimesSync(U,D.header.time,D.header.time)}catch{A(R("Unable to create folder",U))}}P.reverse().reduce(function(D,U){return function(N){if(N)D(N);else{let K=Se.normalize(d(U.entryName)),J=f(_,K);U.getDataAsync(function(ie,Y){if(Y)D(Y);else if(!ie)D(Ie.Errors.CANT_EXTRACT_FILE());else{let oe=I?U.header.fileAttr:void 0;o.writeFileToAsync(J,ie,v,oe,function(le){le||D(R("Unable to write file",J)),o.fs.utimes(J,U.header.time,U.header.time,function(Ee){Ee?D(R("Unable to set times",J)):D()})})}})}}},A)()},writeZip:function(_,v){if(arguments.length===1&&typeof _=="function"&&(v=_,_=""),!_&&i.filename&&(_=i.filename),!!_){var I=a.compressToBuffer();if(I){var A=o.writeFileTo(_,I,!0);typeof v=="function"&&v(A?null:new Error("failed"),"")}}},writeZipPromise:function(_,v){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},v);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,I,A,P)},R)})},toBufferPromise:function(){return new Promise((_,v)=>{a.toAsyncBuffer(_,v)})},toBuffer:function(_,v,I,A){return typeof _=="function"?(a.toAsyncBuffer(_,v,I,A),null):a.compressToBuffer()}}}});import{execFile as Qy,spawn as eE,spawnSync as WC}from"node:child_process";import{promisify as tE}from"node:util";function rE(t){if(process.platform!=="win32")return!1;if(A0.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(A0,"").toLowerCase();return nE.has(n)}function k0(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return rE(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function dt(t,e=[],n={}){return eE(t,e,k0(t,n))}function Oo(t,e=[],n={}){return iE(t,e,k0(t,n))}var nE,A0,iE,Wt=ot(()=>{"use strict";nE=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),A0=/\.(cmd|bat|ps1)$/i;iE=tE(Qy)});var un=fe((wO,Lx)=>{"use strict";var Dx=["nodebuffer","arraybuffer","fragments"],Ox=typeof Blob<"u";Ox&&Dx.push("blob");Lx.exports={BINARY_TYPES:Dx,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ox,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var gs=fe((_O,aa)=>{"use strict";var{EMPTY_BUFFER:RS}=un(),Yd=Buffer[Symbol.species];function PS(t,e){if(t.length===0)return RS;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 Yd(n.buffer,n.byteOffset,i):n}function Mx(t,e,n,i,o){for(let a=0;a<o;a++)n[i+a]=t[a]^e[a&3]}function Nx(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function DS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Qd(t){if(Qd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Yd(t):ArrayBuffer.isView(t)?e=new Yd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Qd.readOnly=!1),e}aa.exports={concat:PS,mask:Mx,toArrayBuffer:DS,toBuffer:Qd,unmask:Nx};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ge("bufferutil");aa.exports.mask=function(e,n,i,o,a){a<48?Mx(e,n,i,o,a):t.mask(e,n,i,o,a)},aa.exports.unmask=function(e,n){e.length<32?Nx(e,n):t.unmask(e,n)}}catch{}});var zx=fe((yO,Bx)=>{"use strict";var Fx=Symbol("kDone"),el=Symbol("kRun"),tl=class{constructor(e){this[Fx]=()=>{this.pending--,this[el]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[el]()}[el](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fx])}}};Bx.exports=tl});var ai=fe((EO,Gx)=>{"use strict";var ms=ge("zlib"),Ux=gs(),OS=zx(),{kStatusCode:Hx}=un(),LS=Buffer[Symbol.species],MS=Buffer.from([0,0,255,255]),da=Symbol("permessage-deflate"),hn=Symbol("total-length"),si=Symbol("callback"),zn=Symbol("buffers"),oi=Symbol("error"),ca,nl=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,!ca){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ca=new OS(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[si];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){ca.add(o=>{this._decompress(e,n,(a,d)=>{o(),i(a,d)})})}compress(e,n,i){ca.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"?ms.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=ms.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[da]=this,this._inflate[hn]=0,this._inflate[zn]=[],this._inflate.on("error",FS),this._inflate.on("data",qx)}this._inflate[si]=i,this._inflate.write(e),n&&this._inflate.write(MS),this._inflate.flush(()=>{let a=this._inflate[oi];if(a){this._inflate.close(),this._inflate=null,i(a);return}let d=Ux.concat(this._inflate[zn],this._inflate[hn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[hn]=0,this._inflate[zn]=[],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"?ms.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=ms.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[hn]=0,this._deflate[zn]=[],this._deflate.on("data",NS)}this._deflate[si]=i,this._deflate.write(e),this._deflate.flush(ms.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Ux.concat(this._deflate[zn],this._deflate[hn]);n&&(a=new LS(a.buffer,a.byteOffset,a.length-4)),this._deflate[si]=null,this._deflate[hn]=0,this._deflate[zn]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,a)})}};Gx.exports=nl;function NS(t){this[zn].push(t),this[hn]+=t.length}function qx(t){if(this[hn]+=t.length,this[da]._maxPayload<1||this[hn]<=this[da]._maxPayload){this[zn].push(t);return}this[oi]=new RangeError("Max payload size exceeded"),this[oi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[oi][Hx]=1009,this.removeListener("data",qx),this.reset()}function FS(t){if(this[da]._inflate=null,this[oi]){this[si](this[oi]);return}t[Hx]=1007,this[si](t)}});var ci=fe((bO,la)=>{"use strict";var{isUtf8:jx}=ge("buffer"),{hasBlob:BS}=un(),zS=[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 US(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function rl(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 HS(t){return BS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}la.exports={isBlob:HS,isValidStatusCode:US,isValidUTF8:rl,tokenChars:zS};if(jx)la.exports.isValidUTF8=function(t){return t.length<24?rl(t):jx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ge("utf-8-validate");la.exports.isValidUTF8=function(e){return e.length<32?rl(e):t(e)}}catch{}});var cl=fe((vO,Xx)=>{"use strict";var{Writable:qS}=ge("stream"),Wx=ai(),{BINARY_TYPES:GS,EMPTY_BUFFER:Kx,kStatusCode:jS,kWebSocket:WS}=un(),{concat:il,toArrayBuffer:KS,unmask:$S}=gs(),{isValidStatusCode:VS,isValidUTF8:$x}=ci(),fa=Buffer[Symbol.species],It=0,Vx=1,Jx=2,Zx=3,sl=4,ol=5,ua=6,al=class extends qS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||GS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[WS]=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=It}_write(e,n,i){if(this._opcode===8&&this._state==It)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 fa(i.buffer,i.byteOffset+e,i.length-e),new fa(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 fa(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 It:this.getInfo(e);break;case Vx:this.getPayloadLength16(e);break;case Jx:this.getPayloadLength64(e);break;case Zx:this.getMask();break;case sl:this.getData(e);break;case ol:case ua: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[Wx.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=Vx:this._payloadLength===127?this._state=Jx: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=Zx:this._state=sl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=sl}getData(e){let n=Kx;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&&$S(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ol,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Wx.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===It&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=It;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=il(i,n):this._binaryType==="arraybuffer"?o=KS(il(i,n)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=It):(this._state=ua,setImmediate(()=>{this.emit("message",o,!0),this._state=It,this.startLoop(e)}))}else{let o=il(i,n);if(!this._skipUTF8Validation&&!$x(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(a);return}this._state===ol||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=It):(this._state=ua,setImmediate(()=>{this.emit("message",o,!1),this._state=It,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Kx),this.end();else{let i=e.readUInt16BE(0);if(!VS(i)){let a=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(a);return}let o=new fa(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$x(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=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=ua,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,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[jS]=o,d}};Xx.exports=al});var fl=fe((IO,ep)=>{"use strict";var{Duplex:SO}=ge("stream"),{randomFillSync:JS}=ge("crypto"),Yx=ai(),{EMPTY_BUFFER:ZS,kWebSocket:XS,NOOP:YS}=un(),{isBlob:di,isValidStatusCode:QS}=ci(),{mask:Qx,toBuffer:ur}=gs(),At=Symbol("kByteLength"),e1=Buffer.alloc(4),ha=8*1024,hr,li=ha,Nt=0,t1=1,n1=2,dl=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=Nt,this.onerror=YS,this[XS]=void 0}static frame(e,n){let i,o=!1,a=2,d=!1;n.mask&&(i=n.maskBuffer||e1,n.generateMask?n.generateMask(i):(li===ha&&(hr===void 0&&(hr=Buffer.alloc(ha)),JS(hr,0,ha),li=0),i[0]=hr[li++],i[1]=hr[li++],i[2]=hr[li++],i[3]=hr[li++]),d=(i[0]|i[1]|i[2]|i[3])===0,a=6);let f;typeof e=="string"?(!n.mask||d)&&n[At]!==void 0?f=n[At]:(e=Buffer.from(e),f=e.length):(f=e.length,o=n.mask&&n.readOnly&&!d);let u=f;f>=65536?(a+=8,u=127):f>125&&(a+=2,u=126);let x=Buffer.allocUnsafe(o?f+a:a);return x[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(x[0]|=64),x[1]=u,u===126?x.writeUInt16BE(f,2):u===127&&(x[2]=x[3]=0,x.writeUIntBE(f,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?(Qx(e,i,x,a,f),[x]):(Qx(e,i,e,0,f),[x,e])):[x,e]}close(e,n,i,o){let a;if(e===void 0)a=ZS;else{if(typeof e!="number"||!QS(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 f=Buffer.byteLength(n);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+f),a.writeUInt16BE(e,0),typeof n=="string"?a.write(n,2):a.set(n,2)}}let d={[At]:a.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Nt?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):di(e)?(o=e.size,a=!1):(e=ur(e),o=e.length,a=ur.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[At]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};di(e)?this._state!==Nt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Nt?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):di(e)?(o=e.size,a=!1):(e=ur(e),o=e.length,a=ur.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[At]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};di(e)?this._state!==Nt?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==Nt?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,n,i){let o=this._extensions[Yx.extensionName],a=n.binary?2:1,d=n.compress,f,u;typeof e=="string"?(f=Buffer.byteLength(e),u=!1):di(e)?(f=e.size,u=!1):(e=ur(e),f=e.length,u=ur.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=f>=o._threshold),this._compress=d):(d=!1,a=0),n.fin&&(this._firstFragment=!0);let x={[At]:f,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:u,rsv1:d};di(e)?this._state!==Nt?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==Nt?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,n,i,o){this._bufferedBytes+=i[At],this._state=n1,e.arrayBuffer().then(a=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(ll,this,f,o);return}this._bufferedBytes-=i[At];let d=ur(a);n?this.dispatch(d,n,i,o):(this._state=Nt,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(a=>{process.nextTick(r1,this,a,o)})}dispatch(e,n,i,o){if(!n){this.sendFrame(t.frame(e,i),o);return}let a=this._extensions[Yx.extensionName];this._bufferedBytes+=i[At],this._state=t1,a.compress(e,i.fin,(d,f)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");ll(this,u,o);return}this._bufferedBytes-=i[At],this._state=Nt,i.readOnly=!1,this.sendFrame(t.frame(f,i),o),this.dequeue()})}dequeue(){for(;this._state===Nt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][At],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][At],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)}};ep.exports=dl;function ll(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 r1(t,e,n){ll(t,e,n),t.onerror(e)}});var dp=fe((AO,cp)=>{"use strict";var{kForOnEventAttribute:ws,kListener:ul}=un(),tp=Symbol("kCode"),np=Symbol("kData"),rp=Symbol("kError"),ip=Symbol("kMessage"),sp=Symbol("kReason"),fi=Symbol("kTarget"),op=Symbol("kType"),ap=Symbol("kWasClean"),xn=class{constructor(e){this[fi]=null,this[op]=e}get target(){return this[fi]}get type(){return this[op]}};Object.defineProperty(xn.prototype,"target",{enumerable:!0});Object.defineProperty(xn.prototype,"type",{enumerable:!0});var xr=class extends xn{constructor(e,n={}){super(e),this[tp]=n.code===void 0?0:n.code,this[sp]=n.reason===void 0?"":n.reason,this[ap]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[tp]}get reason(){return this[sp]}get wasClean(){return this[ap]}};Object.defineProperty(xr.prototype,"code",{enumerable:!0});Object.defineProperty(xr.prototype,"reason",{enumerable:!0});Object.defineProperty(xr.prototype,"wasClean",{enumerable:!0});var ui=class extends xn{constructor(e,n={}){super(e),this[rp]=n.error===void 0?null:n.error,this[ip]=n.message===void 0?"":n.message}get error(){return this[rp]}get message(){return this[ip]}};Object.defineProperty(ui.prototype,"error",{enumerable:!0});Object.defineProperty(ui.prototype,"message",{enumerable:!0});var _s=class extends xn{constructor(e,n={}){super(e),this[np]=n.data===void 0?null:n.data}get data(){return this[np]}};Object.defineProperty(_s.prototype,"data",{enumerable:!0});var i1={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[ws]&&o[ul]===e&&!o[ws])return;let i;if(t==="message")i=function(a,d){let f=new _s("message",{data:d?a:a.toString()});f[fi]=this,xa(e,this,f)};else if(t==="close")i=function(a,d){let f=new xr("close",{code:a,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[fi]=this,xa(e,this,f)};else if(t==="error")i=function(a){let d=new ui("error",{error:a,message:a.message});d[fi]=this,xa(e,this,d)};else if(t==="open")i=function(){let a=new xn("open");a[fi]=this,xa(e,this,a)};else return;i[ws]=!!n[ws],i[ul]=e,n.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ul]===e&&!n[ws]){this.removeListener(t,n);break}}};cp.exports={CloseEvent:xr,ErrorEvent:ui,Event:xn,EventTarget:i1,MessageEvent:_s};function xa(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var pa=fe((kO,lp)=>{"use strict";var{tokenChars:ys}=ci();function Zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function s1(t){let e=Object.create(null),n=Object.create(null),i=!1,o=!1,a=!1,d,f,u=-1,x=-1,p=-1,w=0;for(;w<t.length;w++)if(x=t.charCodeAt(w),d===void 0)if(p===-1&&ys[x]===1)u===-1&&(u=w);else if(w!==0&&(x===32||x===9))p===-1&&u!==-1&&(p=w);else if(x===59||x===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let _=t.slice(u,p);x===44?(Zt(e,_,n),n=Object.create(null)):d=_,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(f===void 0)if(p===-1&&ys[x]===1)u===-1&&(u=w);else if(x===32||x===9)p===-1&&u!==-1&&(p=w);else if(x===59||x===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w),Zt(n,t.slice(u,p),!0),x===44&&(Zt(e,d,n),n=Object.create(null),d=void 0),u=p=-1}else if(x===61&&u!==-1&&p===-1)f=t.slice(u,w),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(o){if(ys[x]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);u===-1?u=w:i||(i=!0),o=!1}else if(a)if(ys[x]===1)u===-1&&(u=w);else if(x===34&&u!==-1)a=!1,p=w;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x===34&&t.charCodeAt(w-1)===61)a=!0;else if(p===-1&&ys[x]===1)u===-1&&(u=w);else if(u!==-1&&(x===32||x===9))p===-1&&(p=w);else if(x===59||x===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1&&(p=w);let _=t.slice(u,p);i&&(_=_.replace(/\\/g,""),i=!1),Zt(n,f,_),x===44&&(Zt(e,d,n),n=Object.create(null),d=void 0),f=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(u===-1||a||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=w);let b=t.slice(u,p);return d===void 0?Zt(e,b,n):(f===void 0?Zt(n,b,!0):i?Zt(n,f,b.replace(/\\/g,"")):Zt(n,f,b),Zt(e,d,n)),e}function o1(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(", ")}lp.exports={format:o1,parse:s1}});var _a=fe((RO,bp)=>{"use strict";var a1=ge("events"),c1=ge("https"),d1=ge("http"),hp=ge("net"),l1=ge("tls"),{randomBytes:f1,createHash:u1}=ge("crypto"),{Duplex:TO,Readable:CO}=ge("stream"),{URL:hl}=ge("url"),Un=ai(),h1=cl(),x1=fl(),{isBlob:p1}=ci(),{BINARY_TYPES:fp,CLOSE_TIMEOUT:g1,EMPTY_BUFFER:ga,GUID:m1,kForOnEventAttribute:xl,kListener:w1,kStatusCode:_1,kWebSocket:$e,NOOP:xp}=un(),{EventTarget:{addEventListener:y1,removeEventListener:E1}}=dp(),{format:b1,parse:v1}=pa(),{toBuffer:S1}=gs(),pp=Symbol("kAborted"),pl=[8,13],pn=["CONNECTING","OPEN","CLOSING","CLOSED"],I1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends a1{constructor(e,n,i){super(),this._binaryType=fp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ga,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){fp.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 h1({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),a=new x1(e,this._extensions,i.generateMask);this._receiver=o,this._sender=a,this._socket=e,o[$e]=this,a[$e]=this,e[$e]=this,o.on("conclude",T1),o.on("drain",C1),o.on("error",R1),o.on("message",P1),o.on("ping",D1),o.on("pong",O1),a.onerror=L1,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",_p),e.on("data",wa),e.on("end",yp),e.on("error",Ep),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[Un.extensionName]&&this._extensions[Un.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){gt(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())}),wp(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){gl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ga,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){gl(this,e,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ga,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){gl(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Un.extensionName]||(o.compress=!1),this._sender.send(e||ga,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){gt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ye,"CONNECTING",{enumerable:!0,value:pn.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:pn.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:pn.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:pn.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:pn.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:pn.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:pn.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:pn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[xl])return e[w1];return null},set(e){for(let n of this.listeners(t))if(n[xl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[xl]:!0})}})});ye.prototype.addEventListener=y1;ye.prototype.removeEventListener=E1;bp.exports=ye;function gp(t,e,n,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:g1,protocolVersion:pl[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,!pl.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${pl.join(", ")})`);let a;if(e instanceof hl)a=e;else try{a=new hl(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:",f=a.protocol==="ws+unix:",u;if(a.protocol!=="ws:"&&!d&&!f?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!a.pathname?u="The URL's pathname is empty":a.hash&&(u="The URL contains a fragment identifier"),u){let I=new SyntaxError(u);if(t._redirects===0)throw I;ma(t,I);return}let x=d?443:80,p=f1(16).toString("base64"),w=d?c1.request:d1.request,b=new Set,_;if(o.createConnection=o.createConnection||(d?k1:A1),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 Un({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=b1({[Un.extensionName]:_.offer()})),n.length){for(let I of n){if(typeof I!="string"||!I1.test(I)||b.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.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}`),f){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let v;if(o.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=d,t._originalHostOrSocketPath=f?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=f?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")),v=t._req=w(o),t._redirects&&t.emit("redirect",t.url,v)}else v=t._req=w(o);o.timeout&&v.on("timeout",()=>{gt(t,v,"Opening handshake has timed out")}),v.on("error",I=>{v===null||v[pp]||(v=t._req=null,ma(t,I))}),v.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){gt(t,v,"Maximum redirects exceeded");return}v.abort();let R;try{R=new hl(A,e)}catch{let P=new SyntaxError(`Invalid URL: ${A}`);ma(t,P);return}gp(t,R,n,i)}else t.emit("unexpected-response",v,I)||gt(t,v,`Unexpected server response: ${I.statusCode}`)}),v.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;v=t._req=null;let R=I.headers.upgrade;if(R===void 0||R.toLowerCase()!=="websocket"){gt(t,A,"Invalid Upgrade header");return}let E=u1("sha1").update(p+m1).digest("base64");if(I.headers["sec-websocket-accept"]!==E){gt(t,A,"Invalid Sec-WebSocket-Accept header");return}let P=I.headers["sec-websocket-protocol"],D;if(P!==void 0?b.size?b.has(P)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":b.size&&(D="Server sent no subprotocol"),D){gt(t,A,D);return}P&&(t._protocol=P);let U=I.headers["sec-websocket-extensions"];if(U!==void 0){if(!_){gt(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=v1(U)}catch{gt(t,A,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(N);if(K.length!==1||K[0]!==Un.extensionName){gt(t,A,"Server indicated an extension that was not requested");return}try{_.accept(N[Un.extensionName])}catch{gt(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Un.extensionName]=_}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(v,t):v.end()}function ma(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function A1(t){return t.path=t.socketPath,hp.connect(t)}function k1(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hp.isIP(t.host)?"":t.host),l1.connect(t)}function gt(t,e,n){t._readyState=ye.CLOSING;let i=new Error(n);Error.captureStackTrace(i,gt),e.setHeader?(e[pp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ma,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function gl(t,e,n){if(e){let i=p1(e)?e.size:S1(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${pn[t.readyState]})`);process.nextTick(n,i)}}function T1(t,e){let n=this[$e];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[$e]!==void 0&&(n._socket.removeListener("data",wa),process.nextTick(mp,n._socket),t===1005?n.close():n.close(t,e))}function C1(){let t=this[$e];t.isPaused||t._socket.resume()}function R1(t){let e=this[$e];e._socket[$e]!==void 0&&(e._socket.removeListener("data",wa),process.nextTick(mp,e._socket),e.close(t[_1])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function up(){this[$e].emitClose()}function P1(t,e){this[$e].emit("message",t,e)}function D1(t){let e=this[$e];e._autoPong&&e.pong(t,!this._isServer,xp),e.emit("ping",t)}function O1(t){this[$e].emit("pong",t)}function mp(t){t.resume()}function L1(t){let e=this[$e];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,wp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function wp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function _p(){let t=this[$e];if(this.removeListener("close",_p),this.removeListener("data",wa),this.removeListener("end",yp),t._readyState=ye.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[$e]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",up),t._receiver.on("finish",up))}function wa(t){this[$e]._receiver.write(t)||this.pause()}function yp(){let t=this[$e];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function Ep(){let t=this[$e];this.removeListener("error",Ep),this.on("error",xp),t&&(t._readyState=ye.CLOSING,this.destroy())}});var Ap=fe((DO,Ip)=>{"use strict";var PO=_a(),{Duplex:M1}=ge("stream");function vp(t){t.emit("close")}function N1(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Sp(t){this.removeListener("error",Sp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function F1(t,e){let n=!0,i=new M1({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(a,d){let f=!d&&i._readableState.objectMode?a.toString():a;i.push(f)||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(vp,i);return}let d=!1;t.once("error",function(u){d=!0,a(u)}),t.once("close",function(){d||a(o),process.nextTick(vp,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",N1),i.on("error",Sp),i}Ip.exports=F1});var ml=fe((OO,kp)=>{"use strict";var{tokenChars:B1}=ci();function z1(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&&B1[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 f=t.slice(n,i);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),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}kp.exports={parse:z1}});var Lp=fe((MO,Op)=>{"use strict";var U1=ge("events"),ya=ge("http"),{Duplex:LO}=ge("stream"),{createHash:H1}=ge("crypto"),Tp=pa(),pr=ai(),q1=ml(),G1=_a(),{CLOSE_TIMEOUT:j1,GUID:W1,kWebSocket:K1}=un(),$1=/^[+/0-9A-Za-z]{22}==$/,Cp=0,Rp=1,Dp=2,wl=class extends U1{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:j1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:G1,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ya.createServer((i,o)=>{let a=ya.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=V1(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=Cp}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===Dp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Es,this);return}if(e&&this.once("close",e),this._state!==Rp)if(this._state=Rp,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(Es,this):process.nextTick(Es,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Es(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",Pp);let a=e.headers["sec-websocket-key"],d=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){gr(this,e,n,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){gr(this,e,n,400,"Invalid Upgrade header");return}if(a===void 0||!$1.test(a)){gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){bs(n,400);return}let u=e.headers["sec-websocket-protocol"],x=new Set;if(u!==void 0)try{x=q1.parse(u)}catch{gr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&p!==void 0){let b=new pr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let _=Tp.parse(p);_[pr.extensionName]&&(b.accept(_[pr.extensionName]),w[pr.extensionName]=b)}catch{gr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(_,v,I,A)=>{if(!_)return bs(n,v||401,I,A);this.completeUpgrade(w,a,x,e,n,i,o)});return}if(!this.options.verifyClient(b))return bs(n,401)}this.completeUpgrade(w,a,x,e,n,i,o)}completeUpgrade(e,n,i,o,a,d,f){if(!a.readable||!a.writable)return a.destroy();if(a[K1])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Cp)return bs(a,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${H1("sha1").update(n+W1).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let w=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;w&&(x.push(`Sec-WebSocket-Protocol: ${w}`),p._protocol=w)}if(e[pr.extensionName]){let w=e[pr.extensionName].params,b=Tp.format({[pr.extensionName]:[w]});x.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",x,o),a.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),a.removeListener("error",kp),p.setSocket(a,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(gs,this)})),u(p,s)}};Tp.exports=hl;function VI(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 gs(t){t._state=Cp,t.emit("close")}function kp(){this.destroy()}function ms(t,e,n,i){n=n||xa.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${xa.STATUS_CODES[e]}\r
17
- `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
16
+ `)),a.removeListener("error",Pp),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(Es,this)})),f(p,o)}};Op.exports=wl;function V1(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 Es(t){t._state=Dp,t.emit("close")}function Pp(){this.destroy()}function bs(t,e,n,i){n=n||ya.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} ${ya.STATUS_CODES[e]}\r
17
+ `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+n)}function hr(t,e,n,i,s,a){if(t.listenerCount("wsClientError")){let d=new Error(s);Error.captureStackTrace(d,hr),t.emit("wsClientError",d,n,e)}else ms(n,i,s,a)}});var qp=le(Pe=>{"use strict";var N=F;(function(t,e){let n=F,i=t();for(;;)try{if(-parseInt(n(881))/1+parseInt(n(1059))/2*(parseInt(n(534))/3)+parseInt(n(612))/4*(parseInt(n(707))/5)+-parseInt(n(1372))/6+parseInt(n(1934))/7+parseInt(n(1713))/8*(parseInt(n(1079))/9)+parseInt(n(571))/10===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ba,512933);var nA=Object[N(939)+N(1384)],rA=Object[N(1695)+"opertyNa"+N(1102)],Fp=(t,e)=>function(){return t&&(e=(0,t[{QSGyb:function(a,d){return a(d)}}[N(977)](rA,t)[0]])(t=0)),e},iA=(t,e)=>{for(var n in e)nA(t,n,{get:e[n],enumerable:!0})};function sA(){return Op||(Op=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function oA(){let t=N;return Lp||(Lp=[IDBCursor[t(946)+"e"][t(907)],IDBCursor.prototype[t(490)],IDBCursor[t(946)+"e"][t(490)+t(1258)+"ey"]])}function aA(t){let e=N,n={Eifhw:function(s,a){return s!==a},zwuFg:e(1364),meVWo:function(s,a){return s(a)},SJktA:function(s){return s()},uqgbs:e(796),afBlm:function(s,a){return s(a)},MQATk:function(s){return s()},NCHgR:e(720),ZXWvi:function(s,a){return s instanceof a}},i=new Promise((s,a)=>{let d=e,u={wUnSV:n[d(1827)],DPTcc:function(w,b){return n[d(840)](w,b)},hUOHX:function(w){return n.MQATk(w)}},h=()=>{let w=d;t[w(1213)+w(1200)+w(698)](u.wUnSV,x),t[w(1213)+w(1200)+"ner"](w(720),p)},x=()=>{let w=d;u[w(1120)](s,Zt(t[w(564)])),u[w(569)](h)},p=()=>{let w=d;if(n.Eifhw(n[w(805)],n[w(805)]))return new _0x2f8d12(_0x5af78b,{message:_0x1ee666});n[w(1764)](a,t[w(720)]),n[w(1677)](h)};t[d(1766)+d(436)](d(796),x),t[d(1766)+d(436)](n[d(1323)],p)});return i.then(s=>{let a=e;n[a(1946)](s,IDBCursor)&&pl[a(624)](s,t)})[e(1871)](()=>{}),_a[e(624)](i,t),i}function cA(t){let e=N,n={mQpUW:e(515),mFssq:e(720),vFZRs:e(1407),qONOl:function(s,a){return s(a)},olMeM:function(s,a){return s+a},kdSUJ:e(733),OqjDd:function(s){return s()},JzEyM:function(s){return s()},Vobvc:e(512)+"or"};if(wa[e(1836)](t))return;let i=new Promise((s,a)=>{let d=e,u={JkiwW:n[d(711)],KAbov:n[d(955)],VLwCg:n[d(1900)],JqTsS:function(w,b){return n[d(1965)](w,b)},PKCWd:function(w,b){return n.olMeM(w,b)},mpSzA:function(w,b){return w===b},YlPOK:n[d(1447)],vSlic:function(w){return n[d(1179)](w)},pYUtk:function(w){return n[d(1564)](w)},Yllml:function(w,b){return w(b)},sFunp:n.Vobvc},h=()=>{let w=d;t[w(1213)+w(1200)+w(698)](u[w(1742)],x),t[w(1213)+w(1200)+w(698)](u[w(924)],p),t["removeEv"+w(1200)+w(698)](u[w(1473)],p)},x=()=>{let w=d,b={TmXMk:function(y,v){return u[F(1738)](y,v)},Eroay:function(y,v){return u[F(517)](y,v)}};if(u[w(1422)](u[w(997)],u[w(997)]))u.vSlic(s),u.pYUtk(h);else{let v=""+_0x5cb406[w(1313)](),I=_0x1d7cc6||(_0x19a010=b[w(1614)](_0xc3f9ac,_0x493000)),A=_0x2a4e8c.random()[w(497)](16)[w(446)](-6);return b[w(557)](b[w(557)]("02"+v,I),A)}},p=()=>{let w=d;u.Yllml(a,t[w(720)]||new DOMException(u[w(1855)],w(512)+"or")),u[w(1788)](h)};t[d(1766)+d(436)](n[d(711)],x),t.addEventListener(n[d(955)],p),t[d(1766)+d(436)](n[d(1900)],p)});wa.set(t,i)}function dA(t){ya={uZyFh:function(n,i){return n(i)}}.uZyFh(t,ya)}function lA(t){let e=N,n={OBvQv:function(i,s){return i(s)},XrLBf:"7|2|6|0|1|10|8|9"+e(931),uOjEJ:function(i,s,a,d){return i(s,a,d)},WOpjP:function(i,s,a,d){return i(s,a,d)},pgcHm:e(906),TLxJP:e(1653),PHUab:e(1822),kMOdE:"service-name",kBWRD:e(1379),arQkE:function(i,s){return i(s)},HcBMG:function(i,s){return i(s)},GPjet:function(i,s){return i===s},kHDOV:function(i,s){return i in s},xRdJy:e(1033)+"oreNames",yrPry:function(i){return i()}};return n[e(1099)](t,IDBDatabase.prototype["transact"+e(1135)])&&!n.kHDOV(n.xRdJy,IDBTransaction.prototype)?function(i,...s){let a=e,d=t[a(1399)](n[a(1103)](ws,this),i,...s);return xl[a(624)](d,i[a(579)]?i[a(579)]():[i]),n[a(1103)](Zt,d)}:n[e(1243)](oA)[e(1499)](t)?function(...i){let s=e;if(n[s(1021)]!==n[s(1021)]){let a=n[s(987)][s(1559)]("|"),d=0;for(;;){switch(a[d++]){case"0":_0x45ac59=_0xdb251b(_0x1dcd52,_0x2e422a,_0x5739ad[s(1553)]||0);continue;case"1":_0x42e50b[s(553)]("service",_0x1d133b);continue;case"2":_0x414856=n[s(1446)](_0xb6364b,0,_0x43411a,_0x32cc48);continue;case"3":_0x50c7ff=n[s(702)](_0x2fc9ae,_0x1f1475[s(1797)+"er"](_0x1a0da8.cursor||_0x281e86),_0x4cfd09,_0x3e52d1);continue;case"4":_0x1b2560.log(n[s(477)],_0x563c8e);continue;case"5":_0x5e6594[s(553)](n[s(1893)],_0x196a67);continue;case"6":_0xa64cb9[s(553)](n[s(1789)],_0x532fc8);continue;case"7":_0x4983ec[s(553)]("cursor.service",_0x3532d3,_0x222096[s(1553)]);continue;case"8":_0x4b1e5e[s(553)](n.kMOdE,_0x5683f9);continue;case"9":_0x4cddb7=_0x41d7e0(_0xe2e811[s(1454)+s(1628)],_0x68d34f,_0x408b62);continue;case"10":_0x4ecb76=_0xa6ca22(_0x288bd2[_0x3f3021[s(1454)+s(1628)]],_0x3941de,_0x5b1582);continue}break}}else return t.apply(ws(this),i),Zt(pl[s(492)](this))}:function(...i){let s=e;return n.arQkE(Zt,t[s(692)](n[s(1444)](ws,this),i))}}function uA(t){let e=N,n={MEyDL:function(i,s){return i===s},jQwuu:e(1643),naUxU:function(i,s){return i(s)},FEGrd:function(i,s,a){return i(s,a)},AZqXs:function(i){return i()}};return n[e(1717)](typeof t,n[e(1334)])?n.naUxU(lA,t):(t instanceof IDBTransaction&&n[e(639)](cA,t),n[e(572)](zp,t,n[e(1761)](sA))?new Proxy(t,ya):t)}function Zt(t){let e=N,n={GuJxq:function(s,a){return s instanceof a},hOEdr:function(s,a){return s!==a}};if(n.GuJxq(t,IDBRequest))return aA(t);if(ga[e(1836)](t))return ga[e(492)](t);let i=uA(t);return n.hOEdr(i,t)&&(ga.set(t,i),_a.set(i,t)),i}var zp,Op,Lp,pl,wa,xl,ga,_a,ya,ws,Mp=Fp({"node_modules/idb/build/wrap-idb-value.js"(){let t=N,e={imuaF:function(n,i){return n!==i},wSAaZ:function(n,i){return n-i},CLbBo:function(n,i,s){return n(i,s)},nLrHY:function(n,i){return n!==i},dtLfx:t(1681),rXHhn:function(n,i){return n instanceof i},DXZsp:function(n,i){return n===i},iqMKn:"TctcD",TTwSh:t(880),tHTkT:t(467),grovs:function(n,i){return n===i},pxoAf:t(1033)+t(908),yyCZq:"store",TfmzT:function(n,i){return n===i},awUxG:function(n,i){return n===i},gvbrE:function(n,i){return n in i}};zp=(n,i)=>i[t(981)](s=>n instanceof s),pl=new WeakMap,wa=new WeakMap,xl=new WeakMap,ga=new WeakMap,_a=new WeakMap,ya={get(n,i,s){let a=t,d={dtoYD:function(u,h){return e[F(895)](u,h)},wgXeD:function(u,h){return e[F(835)](u,h)},uWhVQ:function(u,h,x){return e[F(1691)](u,h,x)}};if(e[a(533)](e.dtLfx,a(1902))){if(e[a(1175)](n,IDBTransaction)){if(e[a(1963)](e[a(739)],e.TTwSh))return _0x5498fe[_0x1da63c]=_0x180fb3,!0;if(e[a(1963)](i,e[a(521)]))return wa[a(492)](n);if(e[a(1034)](i,e[a(1588)]))return n[a(1033)+"oreNames"]||xl[a(492)](n);if(e.grovs(i,e[a(732)]))return s["objectSt"+a(908)][1]?void 0:s[a(1033)+a(690)](s[a(1033)+"oreNames"][0])}return Zt(n[i])}else d[a(1067)](_0x9e61e5,_0x56b573,16),d[a(1067)](_0x4514cc,_0x5cd41f,_0x535b46)},set(n,i,s){return n[i]=s,!0},has(n,i){let s=t;return e[s(1175)](n,IDBTransaction)&&(e[s(1670)](i,e[s(521)])||e[s(452)](i,e[s(732)]))?!0:e[s(449)](i,n)}},ws=n=>_a.get(n)}}),Up={};iA(Up,{deleteDB:()=>hA,openDB:()=>fA,unwrap:()=>ws,wrap:()=>Zt});function fA(t,e,{blocked:n,upgrade:i,blocking:s,terminated:a}={}){let d=N,u={qEeay:function(p,w,b,y,v){return p(w,b,y,v)},AjbGb:d(1912)+d(1076),gnNSB:d(1533)+d(1571)},h=indexedDB[d(957)](t,e),x=Zt(h);return i&&h["addEvent"+d(436)](u[d(1945)],p=>{let w=d;u.qEeay(i,Zt(h[w(564)]),p[w(975)+"on"],p.newVersion,Zt(h["transact"+w(1135)]))}),n&&h[d(1766)+d(436)](d(498),()=>n()),x[d(864)](p=>{let w=d;a&&p[w(1766)+w(436)](w(1029),()=>a()),s&&p[w(1766)+w(436)](u[w(1144)],()=>s())})[d(1871)](()=>{}),x}function hA(t,{blocked:e}={}){let n=N,i={cFFfb:"blocked",mqhrM:function(a,d){return a(d)}},s=indexedDB[n(1869)+n(1616)](t);return e&&s[n(1766)+n(436)](i.cFFfb,()=>e()),i[n(1087)](Zt,s).then(()=>{})}function Np(t,e){let n=N,i={TXmHz:n(1578)+"e",ReOCh:n(540),RWNDs:function(h,x){return h instanceof x},DidYC:n(1739),ifOcq:n(1530)};if(!(i[n(1324)](t,IDBDatabase)&&!(e in t)&&typeof e===i[n(851)]))return;if(ma.get(e))return ma[n(492)](e);let s=e.replace(/FromIndex$/,""),a=e!==s,d=Gp[n(1499)](s);if(!(s in(a?IDBIndex:IDBObjectStore)[n(946)+"e"])||!(d||Hp[n(1499)](s)))return i[n(959)]!=="GMutp"?this._qosDB[n(1730)+n(509)]():void 0;let u=async function(h,...x){let p=n,w=this.transaction(h,d?i.TXmHz:i[p(1458)]),b=w.store;return a&&(b=b[p(1078)](x[p(562)]())),(await Promise[p(686)]([b[s](...x),d&&w[p(467)]]))[0]};return ma[n(624)](e,u),u}var Hp,Gp,ma,xA=Fp({"node_modules/idb/build/index.js"(){let t=N,e={mfPuf:function(n){return n()},DkzHb:function(n){return n()},OGdch:t(492),coaTC:t(976),mTSwH:t(1229)+"ys",miqig:t(1359),lRkSn:t(965),iYnaF:t(1343),BZunv:function(n,i){return n(i)}};e[t(1535)](Mp),e.DkzHb(Mp),Hp=[e.OGdch,"getKey",e[t(1462)],e.mTSwH,e.miqig],Gp=[e[t(717)],"add","delete",e[t(1489)]],ma=new Map,e[t(844)](dA,n=>({...n,get:(i,s,a)=>Np(i,s)||n[t(492)](i,s,a),has:(i,s)=>!!Np(i,s)||n.has(i,s)}))}}),pA={idb:function(t){let e=N;t[e(1410)]=Promise[e(747)]().then(()=>(xA(),Up))[e(864)](function(n){return n})}},Bp={};function Jt(t){let e=N,n={mIjcd:function(a,d){return a!==d}};var i=Bp[t];if(n[e(1959)](void 0,i))return i[e(1410)];var s=Bp[t]={exports:{}};return pA[t](s,s[e(1410)],Jt),s[e(1410)]}Jt.d=(t,e)=>{let n=F;for(var i in e)Jt.o(e,i)&&!Jt.o(t,i)&&Object[n(939)+n(1384)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=N;Jt.o=(e,n)=>Object.prototype[t(506)+"operty"][t(1399)](e,n)})(),(()=>{let t=N,e={OppgI:function(n,i){return n!=i},vhXgY:t(1807),prjed:"__esModule"};Jt.r=n=>{let i=t;e[i(623)]("undefined",typeof Symbol)&&Symbol["toString"+i(1950)]&&Object["definePr"+i(1384)](n,Symbol["toString"+i(1950)],{value:e.vhXgY}),Object[i(939)+"operty"](n,e[i(941)],{value:!0})}})();var Oe={};function ba(){let t=["CMvUDevUzha","BfrPBwvVDxq","B0TlqNi","ywXSzwqGBxu","CMvHzhDYAxq","vhLWv28","sLzKCvq","x2LZsw5PDa","D2HZCMi","z05LAK8","Cxn6C0m","B2jYrM0","BLHUAKq","DvDNrNu","ChHVqwy","DgvZDa","reiGzMfPBgu","r25uyvK","y0z1tKK","ENz6BNi","vunHrfO","v0vRwKS","s2rHzKO","sLbouhO","yvjpBwC","CNzHBfzHBhu","Aw5KzxHpzG","q1vezLi","uKv5DxG","sMrfv1i","DKjMA3u","CgLUz1rPBwu","C3nHz2vfDMu","v0Hct1e","ywnOzwq","zxf1ywXZ","AxnrB1nby2S","x2HHBMrSzu8","BwLZzq","y2XVC2veqG","vg1ytwS","ANPoAwi","DgfIyxnL","wvzkAuG","ruPfueq","B2LUDfjLywm","zLn4CKO","wxP6wwC","B3jRig9MzMW","Cg9W","DxnLCKLW","x3jLywr5q2W","y29UDgv4Da","DMDPz2i","yw1L","su5tvefova","zgfwswm","zfnwBwS","DgLTzw91DcW","zgvIDwC","vMrWvwC","r2zktfe","v1DpD2G","B25nzxnZywC","Efrurw52","y2zQs24","zwnVBM5Ly3q","B25tDgfYDfi","BMDuAw1LCG","zNvUy3rPB24","DvrKBwq","y3LqtMO","wvLJCK4","y2uGBM90igK","D2rWr0i","Bw5ezuK","r2n5r2C","wvLyuvq","AunuuKO","y3vYDMfSDwu","wejdBuS","v2vPEgLUsLm","AwrI","AvvhAgW","DhjPzxmGCMu","x2LZtwLUAvC","t2jIyum","v2vfwKq","AxnAzxjV","y3bIvxC","seDztum","wNvWCKe","y2HLy2Tszwe","u1vYrLK","zcWGDw5RBM8","AvbQsuK","vgzTELq","yNLL","rLjqy2q","A29bCxq","A0X1yLO","CxfKB2e","sfnvDvm","u0PRDee","AgXvuxq","uhnitfC","AMvJDfn0B3i","ANfJq0m","CLrRzKq","AwXSihvZzsa","Fdv8nNW4Fdq","x2nVBM5Ly3q","CgfYC2u","zxrSveC","vej3DvO","vunKDwm","uwjLuey","q0XIqM8","BgHSu2m","DKfKt2O","DuvYBuW","z2v0t3DUuhi","qKn0C1K","DefjquG","C0juvLK","zMLSzw5HBwu","qxfvBhy","Dw5ZAwDUzwq","z3vhC00","Ef9MCM9UDgK","weXLC2S","y29UBMvJDca","EfrKtei","D0fxs2G","t25Zyuu","AwXK","DfPVsK4","qNDewwK","zNvfDKi","nJy0qxrZv3v6","yKPcA2O","wKTntK0","z05ktvC","tuv5reW","BLb5sgu","DcbSAw1PDa","zxmGCMvHy2G","nxWXFdj8mhW","ywnRtxnNswq","B3nLza","CfDOz2S","BezSDxnO","ywXPzcb1CMW","x29UrxjYB3i","DunQA0e","CNnVCL92ywW","y2XLyxjtDg8","zeHlyKC","BKXPBMu","nhWWFdf8m3W","t01gtgy","x2HHBMrSzva","EuPbt2m","BfDdDvC","sNfuC1m","C3rYAw5N","BgvUz3rO","yLvVDe4","sMTPD1C","BuHHAMi","tenntfm","r0jhs3O","u3LmuKi","CMvWBgfJzq","CgfNzwHPzgu","ALLQBLe","sfjPsLq","Cgu6ia","qNnZB2y","Axnby2TdBgu","CMTLCKDSB2i","u2jQzLO","Ew9Uz3C","ywfgs1y","CMvJzwL2zwq","Dhj1y3rVCIa","s0r6tuy","qvPXwhm","ugn0uvq","sMjIywu","Bwvwv28","DufoB3a","ywrKrxzLBNq","wxPPsem","y3vYCMvUDeK","x3bPBMDmB3m","zufJAW","tg9NsurozxC","u0fPzMq","tMHOCKW","z0fPq2S","x3vYBa","ELbWENi","wgLxveO","EvjLy29UBMu","vhjvsgi","rLbpsxi","zM9YrwfJAa","CLDNzvC","B25fCNjVCG","vhbtwNu","wMLbqum","Dhfez0m","swjssu4","DLnSAwm","ueHvywi","lcbTyxGGCMu","rxzLBNq","y3jLyxrLuMu","yxKSig5LDhC","B2nRzxrgywK","DLzfv1u","x3bYB3rVy28","zNjVBu51Bwi","zxjFCw9Zx2e","AMDysvy","D2LSBfjLy28","uhf0B2e","C3bvBMq","u2XbvNy","EejeEue","sMX1BMq","A3DfuKi","tw9KDwXL","tg1xzNi","CKHisxO","DerYAvq","De9hrK4","zM9Yy2u","C2fNzq","vhbowue","vw1Oqwe","ywzL","BMCGDxjSoIa","we5dCxa","BKLeDLC","C2vYDMvYvgK","u1DnC1q","AgvHzgvY","Bwu6ia","wgDRDMy","AhnMCxG","qKr5Cvy","DxfNyNm","tM5Ywuu","ChjVDg9JB2W","D0vzDLK","CNr2CLa","vujftvK","thvvrwi","t3HuDwq","y2vZC0HHBMq","AgfZ","CM9YrxzLBNq","z2v0u3rVCMe","sgDjD08","B0vUuu4","zw5JB2rLrNi","A0rqANC","qKvKzxa","DMvUDa","zxjFAxnFywm","r3fQs3G","zNzOBxi","qNDLruC","sKPkwK8","wvznBfO","sw1yBe0","D01cwgC","ExzbrK0","x2LZqNjVD3m","C0z1BNa","vgLTzw91Da","Dg9cExrLC0W","BLjgrKG","ywrK","y3ruAw1LB3u","uwDku0y","tgrjEuW","y29UBMvJDgK","x2LUAxrqCM8","yKDZELe","yw51Ce1LC3m","q3D6Dhq","CMvXDwLYzwq","zgvSzxrLrge","x2nSzwfYugK","y2f0y2G","zuvrEeG","C3vIyxjYyxK","AenSB3nLrxy","CvvHtxO","vxvTzeW","t29fuKO","BMnLq2XVC2u","y29Kzq","B3bLBIa","ANbRDwi","D0DvDMy","D0v4ALq","zMLSDgvY","reXQuvO","vw5Oyw5KBgu","DgLUzYbZzxi","t0fQBNK","zMzjt1G","C25IwMK","B25VCgvU","AwPrAKO","veX4sLa","Fdb8mxWY","zKTguuu","C3rLBMvYCW","r1L3y3G","zMzRr1m","qNjPzgDL","DKzAuNm","zw5KCg9PBNq","whrVBKO","svjIqwq","BMzgA3O","Aw47y2HHCNm","BvPkB2y","DNHiuxy","s3vRtu0","BNvbzNy","q3vZDg9Tq2W","zxrxB3jRq2G","DMvYC2LVBMm","DNzisM0","wvvWs3y","DMLPyuK","r2nLtwu","vxvPuvK","wvP3u0e","ueXHrfK","yxnZAwDU","v21lvgq","qvjbse4","CNHzr2q","shfPv0G","v053uxy","u1blufK","C2D6AwK","wKvVsuW","wgPqELy","DMvzAeO","sxfkEfK","D3Pwugu","C0nVDw50zxi","ndmWmtaXmhrirxfzBW","wg5iv3C","u01OwvO","tuvtu0fhrv8","C3bSAwnL","C0XPC3rLBMu","CMH3CeG","q2rtre4","BhHAAge","AxnFywnR","Ae9HD0G","z25ou0i","wLHxDMK","ExbL","zejZy3m","BgLZDgvUtMu","vgfN","qMj5uw8","jMPZy2fSBgi","ywDL","zMzMzG","rhzRD1q","Aw5L","tfzuu1G","CgXLyxnLiha","BuLQy2q","vw5HAK0","DLvNvxq","CNjVCK1LC3m","rfHAC3a","Dw5KzwzPBMu","Cu9ot2W","te1oreS","Aw5N","BeXfyKe","EwTMtLC","BwfW","q09oveLovuu","ChflwK0","s21cEfu","tgLZDgvUzxi","x3nLBMrby2S","yujizfm","EvHAz2y","BLjkweq","sxPjB2i","Dgv4Dc9WBge","yxKSihrYEsa","Bhj4Avy","yw1LoIa","C2XPy2u","BMXRC1m","ywrKq291BNq","z3zICKu","yLfit0y","uuPlEK0","yxDvEeC","vKnrvNe","x2DLDeLUDgu","Ehbgq28","vgDkt2C","Ehf1vuS","uurHq00","wujgshe","mdaWmdaWmda","zxj2AwnL","DvvysNu","Bg9NsurozxC","wfvpAwW","Bwv0Ag9K","tuDcrLK","zg9Uzq","Ber2vNK","vLzHB1a","BwvZC2fNzv8","vvn4rxO","s0vUu0y","qw1VDw50","lcbOB3n0BMe","zw5NDgG","BMCGzMfPBgu","CgDJsg0","CIb0DhDjra","CxrpzNm","DxvIB1q","AhLYEwO","DgHYzKq","Dgv4DfbHEwW","DvDPte4","whrPsxq","x29UvgLTzw8","wu12t3q","qvHlrxm","Bg5HEeK","y29UDgLUDwu","svzowLC","z2v0","ywDLrxzLBNq","ug5YtLq","CgTWv1q","yw5ZzM9YBvq","Dg9tDhjPBMC","yMXVy2TLza","s0Dozgq","twLZC2LUzYa","t1bftG","Chf0wgi","veTYz3O","DNbiu2W","C1HZwNO","AgfZt3DUuhi","zw1PDa","BMHvqw0","CMfNzvn5BMm","y29UC3rYDwm","zxjFCw9Z","qwjVCNrfCNi","x2n1CNnVCKy","x2rLC3rYB3K","y29TCgXLDgu","AwXLx25HBwu","ueTdv2q","AxzPshi","t1nPA0W","igzHAwWSig0","DeHuA1q","Dw50","x3fVC0rc","v2vIu29JA2u","Bhzwq2O","ww16CLe","C3rVCcbPBw0","AvvZDuC","v1vkzuS","qKPJt2e","B0nMtfy","qur2uNO","BKXYsfK","nde5odjlv0fNC0i","yvn2tLa","zgPZwKi","z2v0q3vYC28","ywnOzwqSihC","x2n1CNnVCK0","CMvHzg9UBhK","wM5fzvi","yMLUyxj5vhK","vefIwuq","igzPzwXKoIa","u0z2v0u","q0vbAgC","zevMA1G","DgLLCKPtt04","x2rLyNvN","EKTxquG","AfDAr3C","CMvTB3zLq2G","Bg9N","B3vUDa","BMrLEa","vMvvuKm","rxjVyxK","AgvHzgvYCW","Dfz6sMu","sengq1K","suvtx0vsuK8","C2HPzNq","tKLrEKC","CMvZDwX0","D21Tu0K","vhzwu0O","uNPXwxa","BNj4vuO","AfvpsfG","thnqsg8","mJy0mZa3mhrgsvDXuG","rKvhCMq","B25szwnLAxy","AefJA01LC3m","zgjzB2K","igXHCMDLCIa","v0vQENG","EMXdthm","C29YDa","ign1CNnVCIa","AhfvquG","zw5XDwv1zq","ihrPBwvVDxq","q1jVB2u","C2vUDa","t2TzsfK","yw5Nzq","qwfgtKC","u1DWtee","CLD2t1i","x3DHAxq","BwrsB2S","zu5Msvi","t2rJwMi","vM9vsfK","DfDqCee","Au5AwMC","B2nZvvm","zg9LAvO","y0zlvve","y3r4","DxjS","D2vhy20","AM9Qv24","y2HnyxHuCMK","Dxrjza","vLvytfC","uhDurgy","s1fcBum","twvZC2fNzuu","y0DKCeW","nfveBhbgDW","BwLUzW","yuHNugu","ywX3yxLZ","Agzys24","sMzJwg0","DLHevMG","yxjYyxLIDwy","CM5dvui","BgLTAxq","CMfTzq","t3bWz0K","C2v0","BM9Uzv9UB24","C0nMqwe","Ae9Wzw5fDMu","suDrtKG","EgHIyMG","z3LlrMK","t2XoDvy","CYbHBhjLywq","v091tKi","ELjJtgi","BwXyt0y","D3jPDgvvAw4","wxfttvy","y2DuwKG","BMfvEfu","z1rPBwvVDxq","BwfUDwfSihi","tg9JAW","zgf0yq","DgvVq3y","B1zSvhi","D1DJwfa","zgvS","u2vXsuq","CfDwufq","o2nOyxjZzxq","y29SBM8","Bu1cDvm","ihjLy29UBMu","BxHLtKK","z0LyvLi","zMzZBgi","vfHREum","EKD1Cvq","BwvZC2fNzq","qMrgExi","BhnJA3O","zfnduKi","yurXDgO","x3DZ","quXm","zvj5CLK","EfjdA0S","uK1AsMu","z3bvzwC","x3bPBMC","Bwf4tg9ZC0m","BNrbBMrvCgq","D0ndvxm","sgDTuvm","rxbsAM4","BxnNsuq","AhzYzLy","C1DxCvC","CwztAg0","AgLNAa","z0rOBeS","CYbWyxjHBxm","CNnVCL9Uyw0","DgfYz2v0","ENHZs24","ywXS","BLjfs1m","x3jLy29UBMu","qwPjEhm","B3jL","DeLK","yxbWBhK","rvjst1i","ihzHBgLKigq","A2fLtgW","D1Lkv1u","C1POsMC","BMvY","BuHyy1e","wMPvqM0","D3nZoI8V","v09WALa","ywnRpwzYB24","wevisfG","wefMqwK","DMfSDwvZ","mJa5ntu2nuDws09ZzG","B25JBg9Zzq","C2vUza","BLjfAhm","BvfWvvC","q0nbz1O","x3bYzwzPEa","DvnMswi","ALfdwwW","ze1oAMG","BfjRu24","ihrPBwvZ","ENPUrhi","zxjYB3i","y1HmvKC","wfL5s08","C0jf","A0XXthy","Bwf4uMv0CMK","yxbWBgLJyxq","BMrWB2LUDca","CKnJuNC","yKfQDei","wfHMC0i","yNnWuMO","ExLdwNe","uwjsBNO","EM5Ur0i","x29WDgLVBNm","uwzkEeC","yxrHlcbKyxq","uLjpuG","Axfns24","ywDLu2HVDW","Bg9IywXty28","zgXvAeq","ug5Or28","BMvJDa","t2jQzwn0","DuvgCKe","CMvZB2X2zq","BwXhs2O","y2XYy0q","EMvoweq","yxv0BW","qKj3Cey","x2DLBMvYyxq","EgPxD0e","x2zVCM1HDeu","y0vszeO","Bhm6ia","zsbHihn0CMK","s1b3t1C","u0jHt3a","ExDLuwW","B1jmtgy","sKfvDM0","x2LZtwLUAvq","reniDeS","zNr1D24","BwvZC2fNztO","BxrHCLy","z2vrDwv1zuW","ugviBvm","D1PUwuC","DhjPzxm","ELLVBeu","yw1Lu3bHy2u","wuDfCfm","CMLLC0nVDw4","ExfrtLu","rerStKm","r3HQse0","CMfUzg9T","nhWZ","BKTgALC","qLfyvMW","wNn5wwW","Ahr0Chm6","B1vMq2m","BgvY","B3nLrxzLBNq","ihrYEsbYzwm","x2TLEvbHDgG","m3WWFdj8nhW","ALzRvgu","wevQC0u","u0fluhe","C3vIC3rYAw4","C3vJy2vZCW","vuLryum","y29UBMvJDeu","AxnbCNjHEq","BM9SENm","y3vZDg9Tshq","Dg5ls2q","x19LC01Vzhu","DMvYC2LVBG","END1rMC","D29XzNy","x2jPBMfYEvq","zfDVCMTLCKC","wwPqAwm","zMvtAe0","BNrfBMrWB2K","y3vYCMvUDeu","B2zMBgLUzq","tej0yxm","y3jLyxrLtwu","Cg9cA1O","CKjttMi","AfHnDw0","CYbPBNn0yw4","pxv0zI04","z0rnzfu","CM92AwrLige","C3rYAw5NAwy","yxrLq291BNq","BwHIsKC","r0Hvugu","D2vI","ywrKt25L","Ahr0Ca","DwDyBuu","yujSCvC","r29rv2G","Ae1LC3nHz2u","zKTZww4","D1nbyvO","surOwMi","CMvHzfvjBNq","BgLUzq","B2zMC2v0","ywzcBg0","BMrWB2LUDfq","yM9KEq","zMzzzxC","qLP1BNy","vKrgyK4","DxrMofDYAxq","y29UBMvJDfm","A3zduuC","se1ou0W","sMjxEKi","rgLKwum","sK9QyNy","ChjVy2vZCW","Aw5PDcbrB1m","D09Vrve","Bwf4twvZC2e","Evnuy3a","zNjHBwvuExa","vxbJuMG","z2vjBMzVu3K","ywXty29Wzq","sgPbshK","weTcshG","DgHLBG","A1zAu3a","C2v0y3vYC28","u1fkAwC","yuXYrwi","BNrLCG","yNvMzMvYzwq","thfTDNO","s2XrwMW","A0TYDLm","DMfSDwu","v1fUtwm","vw9tC0O","x2rPC3bHDgm","x29Ut3bLBG","vfn5Aei","y0zotNa","nZCZmdy5B1HozM9W","yMfSrxzLBNq","vfPkAue","BhvWBg4","zw5HyMXLvhi","Ec1TC2CTy3u","y3vYC29Yx2y","C3vbyM8","Aw9Ul2PZB24","x2nSzwfYvgK","qNHXDha","ywnRx2nVzgu","s01mBhu","CMXIqwe","Aw11yuy","seT6veK","BhDPCfG","se5jBu4","q0Xpu0LorW","BurPBwu","sK5My0G","yxnL","zv90Aw1LB3u","y3vYC29Y","twjszvC","BMfTzq","ywr2yw5Jzq","B3jLtMfTzxm","tgTRvKO","twLUwNi","ELPouM0","u2TPCcbWyxm","ig1LC3nHz2u","yNL0zxm","tKDFrvjst1i","ENfPy3C","zwn0","yvnpENC","vMTIDvO","s2HoBLe","zK5Yu1m","zgzRwwO","s2LPuwG","s0fIB3y","Cg9PBNrdB24","ELfjt1y","zLzWzeG","zxjkwKi","zxH0ugf5Bg8","svvsBxG","Fdr8m3W1","t2PusLG","tvPjqLC","x2LZtM9Kzq","uwLuCLu","DKzvt0S","Bg9Nsurhzw4","q29UzMLN","zgvMAw5Luhi","wLjkC28","ChjQzwq","txftrgW","AwT6tLm","C2v0q3vYC28","rNjVBNrPzxi","ChjVDg90Exa","DgLlAfa","BgLUzw5V","Exf2Ee4","C3fhuha","CwHIzgm","r0nirgy","q09otKvdveK","q25UvgS","BuzZC3e","Cgf5Bg9Hza","B3bLBG","Chv5z3G","Awzpy3e","yvfZyuS","tvvqvxG","tg9Nsuq","AgnkDxy","y29Uy2f0","Chv0","yxGGCMv0CMK","teTqtvu","mhW0","BMvLzf9Hy2S","veXWExu","Cg93","Dgv4Dc9Qyxy","y3jLyxrLrxi","B3jpBMXPBMu","B2XKvMvYC2K","z2v0qwXS","uvnhEwi","x2LUAxq","CNnVCKzPBgu","vxjXvwO","C29Tzq","EhLTrhK","y2HHCKnVzgu","tufyx1jfvfi","Cvbduvy","zMX1C2HfEha","whjmqMy","BM5cr0C","vw5PBxbSzw0","ANffuhG","r0TwvfO","wM9KzMO","AxbAtKm","twjWv3O","B09OvK8","rgvlvxu","wwXqt0S","ChvZAa","BMCGB3iGyw4","qKPYB2q","vKLsweG","qwvJqvK","B25LCNjVCG","vxHlA2C","EvbyEK8","x2XPC3rLBMu","yMLQu2S","wgDcCwq","wxrSAeG","z2TuwgO","B1jxCeK","qMvnDem","yMLUyxj5","yMLUza","Dev2zw50","zhbZwuy","u2zhvg8","uK1YDLO","AxnrB1nnzxm","DMvY","A0jxuKq","zNjVBunOyxi","DeLUDgvYy2u","zM1Kq3u","zw5JB2rPBMC","s2zzDKu","D2Dyzuq","qK1pvfK","y2XVC2u","DwjPzKq","x2nYzwf0zvm","Dg9Y","B2jQzwn0u3q","z3jVDNm","sLbcvLq","x3nLCuLK","ALDSwwK","De1HBMfNzxi","vevpD3i","ywnRx2LK","CgLUz0LUDgu","AgvKtwf4uMu","vwjMuvu","zw50zwqGDhK","DxrVuMvJB24","sfbPuK4","vgzTD3G","BxHxr08","BM5uyMq","CMvZzxrfBMq","D1Hms3q","qKHmqNa","DwfSBhK","zxjYtM8","zw5HyMXLuw8","zw13vha","Durizg8","u0zfvgK","mZzzy3LtvxG","Bg93","ChfmCve","zNjVBujPDhm","zNjVBuj5Dgu","BLb6Ave","AgLLzNG","CfDet2q","DvDOvLe","Dw1brxO","A2v5CW","vNzIvgq","x2n1CNnVCK4","CgLUz0XVC3m","vKXeufm","x2rPC2nVBM4","y3jLyxrLt3a","AgfUz2u","v3fgvwy","Aw5KzxG","ndaWntbWD2LkCvy","z3bkDLG","txD2s3O","v0P6zhu","wLbAzLm","CKDmufe","uxb2Cge","zMzLCG","BxfOCK0","Axv6Dw4","x29Uq2XVC2u","C2vUzf9Hy2S","D0zpsMC","DgDKuvK","q3vZDg9Trxi","BM5Ly3q","rxb2z2e","ihn1y2nLC3m","x2rYB3bhBg8","CxzVv00","r1bQzxq","t2HlC0W","B25TzxnZywC","BwvZ","t0j2uxy","y3jLyxrLq2W","y3jLyxrLt2i","x194x21Zz18","uKDVq3K","rgvKAwnHDgu","B3bLBKrc","zgvHBeq","sfn1wMm","CgjUEeS","CwrAB0q","rxjYB3jdB2q","uMvHzcbWyxm","EwvTDgy","ChbL","zuPnt2e","B25tDg9Wsw0","rfbuy2m","vLnUt04","zxq9DxrMltG","wvvTuuu","u3rYyxrLz3K","t2HXAKO","yxv0B21HDgK","EK1os2u","ENvcvwK","wNHotee","zMvY","uhzizKO","Dw5RBM93BIa","v2vezfy","wu1MA2m","Aw9U","u0zyy3C","tw1AEMe","uNb0sgW","C2v0zgi","yxbWzw5Kq2G","x25HDMLNyxq","wwLWvNe","BNruCMLLC0m","qwPIr2i","x3nVy2TLDa","sK5LveK","yNL0zu9MzNm","tNjvDfy","CfnPyw8","nxWYFdn8mxW","zKLOs2e","suX2BNO","qvDHA2W","CM92AwrLigi","DuD1wxK","x0vysvnu","sfPgEMy","B2fcsNi","A1n0yxr1C0m","Aw9UvgLTzw8","B3v0sw50zxi","tNbwuve","zvviufy","x2LZv29YA2u","BNzmvLy","zuXNweC","yNHZCfa","AuXOwee","yKnctxu","C1jcwNC","DhDVCMTdAge","C0zIBvK","AMTOwgW","Buz6t2y","CLHiAg4","z29PBMCGyxC","t2rIswe","x21PBMLoyxy","t3fQrgq","CM92AwrLihC","v2TWA3u","rLjowxa","qNL6DKe","q0Xpu0ve","yMfJA3vWigu","z0DnzuG","C1HnqMS","AgfcCxC","zvvYBa","z0rOyxG","t0HfCwm","t2vxvLy","CLvNBLC","tvDWq2i","x3bHDgHlzxK","EK11uNq","zNDZxZeUmc4","zxH0zw5ZAw8","AwXXCwq","zw50tgLZDgu","vK9HzMK","EvrJDuC","AwXLtMfTzq","BwvY","Cgf5Bg9Hzfq","vvDswLi","qK5Htge","uMvJB25Uzwm","ywXSq3vYC28","DfHKvuC","BeHHBMrSzxi","BMnVzgLUzW","CMvTB3zLrxy","C3DZyva","AxrdtLK","CeDZCKC","qLjTBeC","AevYCM9Yrxy","CfbXr0C","x0rctMfTzq","icSG","wg1ryxq","B25pCgvU","Cg9PBNrbBMq","CMvKDwnL","CwzxBKi","rfn3v3G","vfzgBem","z2v0qwXSs2u","sMvfBLm","sw1cC1e","u2n4C3u","re1kr3K","z0jOB2G","ChH0wwu","uurnBgG","y3zIAwu","z2vtEw5J","DuL4y2G","z2vY","q29Kzq","ww9yExe","ExjqCNK","yNvMzMvY","Cxrhs0G","yxjuCg0","zgrjrcWGzgu","s1zNrLK","vvj2wue","C0PYy1G","y2HLy2TdDxi","nhWYFdb8m3W","sLnUDg0","sKrzuvm","CNzHBa","uKLisu4","AxmGDw5Kzwy","uhjPBwfYEuS","sufksNa","wwDWrxG","q3H5wNK","rM9ft1G","Aw5xzeu","vMTiuLe","yKrjuuy","vMHdyNi","x2HHBMrSzvi","s3joqMO","Cgf5Bg9Hzeu","A2v5","mhWYFdr8mxW","y2LVCeu","CNHdvwC","Cw9Zx18","v1fWCvy","z2PeAfK","EfvZzuvUDG","x2rItMfTzq","x3bPBMDqB24","AwvPEvy","v2LUzg93","ALbkqLG","DxjOChy","vKHKtuK","qMXNBfe","tejtzNa","y2zIr1y","CgfNzxnOB3C","uLzkqMe","y2H3Du0","zfjdz28","B3jRzxjhBg8","z2v0q3vYCMu","r1vnD04","BMDLza","CgjICdi","B25ozxr3B3i","zxjFBxnNAwq","yMzqv3O","C3jJ","CgvYC2LZDgu","tffcy2K","AM9PBG","B2fK","sLzPsfi","zgz5sgG","nhW1Fdj8mxW","A25hsKu","y29jDfe","rujjDLq","q0jMy2u","sKjhBMm","BM93","twLfyKq","z3Dbtve","DgvmB2Djre4","B0zYB3O","vuTqr3a","rLDt","z2Diz0m","Aufdwhi","zv9ZDwnJzxm","tKniz1i","uLDorhm","r29ADgy","r2zSrwm","sLHVB0S","r1zXAee","EwDXCuK","ELnbzxG","C0zWwNu","rLjptLrjrvi","CLHmEfq","ALf3Dxu","D2fZq2XLyw4","DMXnB1a","rKLmrv9ot1q","EuXtufC","EhbUC2W","zxjHDg9Y","BxnN","wMLnC3G","y2XLyxi","zMLN","DgH0zgi","zxjFDhrS","uvviBwi","B2nRzxrtDwm","zMLUza","yNL0zuXLBMC","B29hsMe","ywDLsgLKzq","wLb3v24","Cg5UuLC","vufiu20","BvD5zKq","zgvJB2rLzey","CMvZzxrdB3u","y291BNq","DKLdqLe","zuLmyKe","C0DPu2y","wgfjBK0","ANfVCLi","AeDPuNK","q0Doug0","sLblCxq","C1P4sgm","AMPvugC","AwDHDg9Yt24","AxnszwfKEq","mZC5odu0mfvWtufLAq","whDiAgu","D2PwENy","vMzZEM8","id4G","nhWWFdn8mNW","CeXyDKK","BMfPqNO","AfzdCw4","rLnbtLe","r2TOCfy","EhzNu2q","B3bLCNr5","CMrJuvm","vxLwtNa","CLzHBhvLCW","zw50","q2XkvLi","zw5fDMvUDa","sfvTC0u","C3rHCNq","ELPjz0i","BLfLBxu","x29UtwvZC2e","vfnNseS","x3jLBw92zvC","wNvRv04","y2fSBa","vMnMzum","BxDTA1C","ywPmvum","ENnmrKu","zNjVBNrPzxi","AMLpr0G","zuT4AxK","ywjVCNq","x1fVu01HBMe","zK9mtfe","zxHWB3j0CW","zg5kCxK","x21LC3nHz2u","BgXeyuK","C2v0u3rVCMe","rvrAs0K","Ee1Nt1G","zNnYEgW","v0PNzvu","r0XLD3u","BhrPCgXLihq","qLnuBhm","BxbtEKe","teTbELi","CMvWBgfJzui","x2vUzhbVAw4","wurzsNq","suvSrLe","Cu1kyMm","vw9gAKq","y2HnyxHdB3u","DMDcs24","wgv5zuW","Dg9cExrLC0i","rxrSBuG","s1LeAuu","AxjLza","tKfusvzfx0u","u2vYDMLJzvC","renbEKC","x2LUDgvYDMe","CgvuEKq","mxW1","y3jLyxrLrwW","sgnctuC","zwrVr3i","Du9QruO","A2rtvuO","ysbTDxn0igi","DgLTzw91Da","DhLWzq","ywnRDxbfBMq","DvnpzfO","seHJzeS","y3vYC29Yx24","Ec1TC2CTCw8","B2nRzxq","su5MyNi","uMvpq2G","D1zQAuq","AfDvANy","yMfSu2nVCgu","y29Hvem","DM5ztvq","AxnmB25N","x2fKzfDZtgK","rK5Nsey","qvvODfC","AKDgvg4","quXArey","C3rVCMu","x29UugfNzu4","DMPnu0K","vKX3q2C","q0rNq2q","DxPNv1u","D2nfuvG","EgvPAuW","zMTRqvG","EerJELC","z2v0sxrLBq","s2TLqMq","zwz6zNe","CMvHzhLtDge","Cfjfrfm","v2P2wNC","Evfmy2G","vLnlsMS","yKTdwva","AvLUyuy","Dg9cExrLCW","zMzmAw5L","rvj5D1q","vfn4s1C","vLDOy1K","weX4zMq","sLnptLa","t05KuMS","s1reqKe","Aw5JBhvKzxm","yw5Hz2vY","D24GCMvHC28","BvnjDu8","A0rpqMe","DxbKyxrLq3u","x2LUAxrhBg8","BNfVueO","vxbKyxrLq28","zgnluKO","De9ps1K","zw1LBNq","yM9L","Dhz1DNm","CMvJB25Uzwm","qNDQAuu","BIWGAg9ZDg4","zLPtvKq","B2zM","vLbTvMS","CMvJzxzPzwq","qMnpqwi","ywnR","q05jqw0","Agznshm","z2u6ia","y3ffrMW","CMvHC29U","tMfTzq","Chj4D1G","tLzKBvC","r011Dha","zxjYtxnN","EwLhtg8","DxbNCMfKzw4","yNrWugG","BwzqDwy","y09Wzw4","AwHoDfa","AezOzKS","q3nws0u","Dg9hzw5LCMe","CgLUz19VBMm","ChrVCG","zwrPyxrLBhK","tMLfrKK","t1bftL9fuLi","C3zJEKG","r0DID3G","Eg5yDKq","BNvTyMvY","uxvLDwu","EwTmywS","A3rADge","C2vYDMLJzq","BwvKAwf0zwW","sNrlzw4","s055tLq","vhH5wMy","u2HHCMvKv28","C3bSAxq","wufdDhy","DhjPBq","C2vYDMLJzs0","CMvZzxruCMK","sNPfEu0","zNv5zNG","yK11twO","s0ryywq","sfjry0W","t3bLBKv2zw4","AejOBfm","zwvKzwq","Dg9mB3DLCKm","zenQEM0"];return ba=function(){return t},ba()}(()=>{let t=N,e={JSntm:function(c,r){return c(r)},vpHSl:function(c,r){return c===r},iPjII:t(1479),yongw:function(c,r){return c(r)},qMJbc:function(c,r){return c+r},qPCQV:function(c,r){return c+r},IDhZb:function(c,r){return c*r},DSwWx:function(c,r){return c*r},pbnxK:function(c,r){return c+r},YDYJt:function(c,r){return c(r)},aROmg:function(c,r,o){return c(r,o)},nrxUJ:function(c,r){return c!=r},cGdpL:t(1964)+"d",YoXyq:t(1807),MbpWz:t(803)+"le",uzgWU:function(c,r){return c!==r},dlUhD:t(1731),coycp:t(1639),ZjUBm:function(c,r){return c+r},uSOdZ:"0000",BdFyr:t(1954),bUotN:function(c,r){return c(r)},ipZNC:t(460)+t(460)+"0000000000000000",pnnRW:function(c,r){return c instanceof r},bKCYP:function(c,r){return c instanceof r},BweEG:t(442)+t(1905)+t(1122),JJJZO:"applicat"+t(889),NIQzG:t(726)+t(889)+t(650)+t(820),FoEOX:"string",RMZJe:function(c,r,o,l){return c(r,o,l)},hvrfV:t(720),BRmlG:function(c,r,o){return c(r,o)},QUHmb:t(1029),yweQl:function(c,r){return c!==r},gNejO:"WEjzx",AXKEs:function(c,r){return c>r},xvgSd:function(c,r){return c<r},erJZB:function(c,r){return c>r},yemtf:function(c,r){return c<r},ubifD:function(c,r){return c!==r},rxYGd:function(c,r){return c-r},LBtas:function(c,r){return c<r},GHUPe:function(c,r){return c<r},uTdmd:function(c,r){return c===r},GfJLQ:function(c,r){return c===r},UKPGp:t(489),fuyfx:t(1002),mtarV:function(c,r){return c>>>r},OdbIa:function(c,r,o){return c(r,o)},ffIOX:function(c,r,o){return c(r,o)},FRPcd:function(c,r){return c&r},feShM:"Missing "+t(1868)+t(544)+"key",CGNPm:function(c){return c()},UyVNp:function(c,r){return c(r)},uCjkA:function(c,r){return c&r},CnnTk:function(c,r){return c<r},PnrNT:function(c,r){return c===r},YipVq:function(c,r){return c+r},KDzMF:function(c,r){return c||r},WJgeU:function(c,r){return c!==r},Cwztt:function(c,r,o){return c(r,o)},btpPh:function(c,r){return c!==r},LsPHo:function(c,r,o){return c(r,o)},UBEMY:function(c,r){return c!==r},HZFzf:function(c,r,o){return c(r,o)},Wkpku:function(c,r){return c(r)},ijQjJ:function(c,r,o){return c(r,o)},iUGhl:function(c){return c()},KfYvE:function(c,r,o){return c(r,o)},oCfLV:function(c,r){return c===r},elIIM:t(1128),wEYvY:t(1961),jojWn:function(c,r){return c!==r},hGiRy:function(c,r,o){return c(r,o)},eEQxH:function(c,r,o){return c(r,o)},wsCYU:function(c,r){return c!==r},umAEz:function(c,r,o){return c(r,o)},xPpmy:function(c,r){return c!==r},oRLLf:"bcXMq",rDvzq:t(1773),zKWAH:function(c,r){return c!==r},LKAzR:function(c,r){return c!==r},Xgkvf:t(654),agRcb:function(c,r){return c(r)},FTRRL:function(c,r){return c(r)},yiGLo:function(c,r){return c>>>r},XXfsB:function(c,r,o){return c(r,o)},tDriT:function(c,r){return c(r)},gkTXj:function(c,r){return c(r)},ZsyYl:function(c,r){return c(r)},mwmkW:function(c,r){return c(r)},ygqqI:function(c,r,o){return c(r,o)},rfaQx:function(c,r,o){return c(r,o)},ffYew:function(c,r){return c&r},URvYA:function(c,r){return c===r},RGoCy:function(c,r){return c===r},mwCCi:t(500)+t(1868)+" field: method",ySTcp:function(c,r){return c(r)},jgXIV:function(c,r){return c(r)},AWakl:function(c,r,o){return c(r,o)},dpsYF:function(c,r){return c+r},PpJVQ:t(989)+t(1044)+t(1751),qbalW:function(c,r){return c>>r},yXZgf:t(1821),ClJVR:function(c,r){return c+r},MbReW:function(c,r){return c<r},ftuwn:function(c,r){return c>>r},IGQNH:function(c,r){return c+r},Pqtoa:t(1150)+t(968),AUhtW:function(c,r){return c|r},xnXvD:function(c,r){return c<<r},lxZha:function(c,r){return c!==r},vlMoP:t(1734),mdRok:function(c,r){return c+r},USxEz:function(c,r){return c===r},Ewwam:"EArPt",sXMBk:t(679),mxWGO:function(c,r){return c>r},pvjVS:function(c,r){return c+r},UCduc:t(1115)+t(1719),WHBOQ:function(c,r){return c===r},ffslb:t(715),vvHJm:function(c,r){return c(r)},LVTSX:function(c,r){return c===r},ZKMNM:function(c,r){return c&r},dealD:function(c,r){return c+r},zMNKe:function(c,r){return c+r},QDaCM:function(c,r){return c&r},dEfkX:function(c,r){return c<r},ykLak:function(c,r){return c<<r},kDPjw:function(c,r){return c&r},CVUNS:function(c,r){return c>=r},TVFlC:function(c,r){return c<=r},UbfQU:function(c,r){return c==r},MUPUx:function(c,r){return c>=r},qvoWM:function(c,r){return c+r},RVJBa:function(c,r){return c+r},XUOil:function(c,r){return c+r},TKrgz:function(c,r){return c!==r},vFUOK:function(c,r){return c|r},pWDOd:function(c,r){return c<<r},BCtsY:function(c,r){return c<r},zGuqT:function(c,r,o){return c(r,o)},XtiIt:function(c,r){return c>>r},WUJeK:function(c,r){return c>=r},ajLUC:function(c,r){return c<r},IeTCh:function(c,r){return c<r},qhbdc:function(c,r){return c<r},dbYoi:function(c,r){return c<r},znCOj:function(c,r){return c+r},kVZSp:function(c,r){return c<r},suAbo:function(c,r){return c&r},CDgCd:function(c,r){return c>>r},gBhoh:function(c,r){return c|r},HBWiA:function(c,r){return c&r},RMrvZ:function(c,r){return c>>r},wcEQX:function(c,r){return c>>r},tqDgC:function(c,r){return c<r},xymDy:function(c,r){return c(r)},jjUPg:function(c,r){return c<r},HqiWH:"RyMAF",eNfIR:t(1546),RptHl:function(c,r){return c>=r},rhwpH:function(c,r){return c&r},LKPMU:function(c,r){return c&r},YVJiH:function(c,r){return c&r},EJEPD:function(c,r){return c(r)},xMgOX:function(c,r){return c&r},bDIQF:function(c,r){return c&r},REyux:function(c,r){return c===r},aLrEb:t(567),SFETi:function(c,r){return c(r)},guGsM:function(c,r){return c&r},nnBGG:function(c,r){return c<<r},PeHmS:function(c,r){return c&r},dcKRJ:function(c,r){return c&r},HgIwO:function(c,r){return c(r)},fIhKa:function(c,r){return c<<r},dSCRB:function(c,r){return c(r)},ZsWgf:function(c,r){return c(r)},VkbuZ:function(c,r){return c&r},nQemu:function(c,r){return c|r},SfGTo:function(c,r){return c|r},haBqw:function(c,r){return c<<r},xpnsl:function(c,r){return c>>>r},bCBMu:function(c,r){return c<<r},bfPWz:function(c,r){return c===r},nlksS:function(c,r){return c<r},OCvCP:function(c,r){return c<r},zznDr:function(c,r){return c<r},KlQZl:function(c,r){return c+r},DvkwT:function(c,r){return c>>>r},ually:function(c,r){return c|r},UrqUj:function(c,r){return c&r},bMuMj:function(c,r){return c+r},UAHSm:function(c,r){return c|r},tXdUG:function(c,r){return c+r},BMOTY:function(c,r){return c&r},SCXMP:function(c,r){return c>>>r},dXLPd:function(c,r){return c+r},IdogB:function(c,r){return c!==r},yvAFM:function(c,r){return c&r},WQpqV:function(c,r){return c>>>r},ZxNLA:function(c,r){return c&r},mZJof:function(c,r){return c>>>r},GxjHM:function(c,r){return c+r},cgTZH:function(c,r){return c|r},TSxKW:function(c,r){return c>>>r},LmWfr:function(c,r){return c>>>r},YjPic:function(c,r){return c>>>r},zoXPj:function(c,r){return c>>>r},lwipX:function(c,r){return c!==r},GflEc:function(c,r){return c===r},yLSPW:"yPXzO",TXkyC:function(c,r){return c|r},vHorO:t(1173),bAjtB:function(c,r){return c|r},XjPzV:function(c,r){return c|r},dfyHh:function(c,r){return c<<r},KdafJ:function(c,r){return c|r},Zodfj:function(c,r){return c|r},ObbaC:function(c,r){return c<<r},ZPZfS:function(c,r){return c|r},rTkfD:function(c,r){return c|r},etlTG:function(c,r){return c|r},ImBsQ:function(c,r){return c<<r},kvCQG:function(c,r){return c|r},uuboT:function(c,r){return c<<r},HUmsE:function(c,r){return c&r},tVzJe:function(c,r){return c&r},myfoC:function(c,r){return c>>>r},lDvVy:function(c,r){return c&r},SAifd:function(c,r){return c>>>r},VHdMI:function(c,r){return c>>>r},ZPwWn:function(c,r){return c(r)},obrFm:function(c,r){return c>=r},KMLlu:function(c,r){return c|r},TypWo:function(c,r){return c%r},HNImN:function(c,r){return c|r},jVkTe:function(c,r){return c/r},qtOfs:function(c,r){return c*r},wYJWU:function(c,r){return c>>>r},GKvgG:function(c,r){return c*r},KrNBj:function(c,r){return c>>>r},MwvKz:function(c,r){return c&r},bGszQ:function(c,r){return c&r},hhjTS:function(c,r){return c&r},doeiZ:function(c,r){return c+r},HgmQS:function(c,r){return c|r},JbWzB:function(c,r){return c!==r},edoGr:function(c,r){return c>>>r},SUrFY:function(c,r){return c===r},xRCkK:function(c,r){return c>r},YGEpS:t(457),TxyZf:t(1597),Lqmvz:function(c,r){return c|r},Hvrdn:function(c,r){return c|r},aaFKV:function(c,r){return c<<r},KGNdd:function(c,r){return c<<r},IElFQ:function(c,r){return c>r},rXLxT:t(1236),YgpEx:function(c,r){return c&r},nRFFH:function(c,r){return c&r},kKrvS:function(c,r){return c>>>r},XnHWw:function(c,r){return c&r},gIXVR:function(c,r){return c>>>r},IAJJp:function(c,r){return c&r},wzVPe:function(c,r){return c&r},tOOKY:function(c,r){return c>>>r},vBfku:function(c,r){return c>>>r},BHLBp:function(c,r){return c>>>r},PLaDY:function(c,r){return c&r},jpkub:t(1721)+t(781),hsfqx:t(1937)+t(693),xBDyA:t(953)+t(915),JOjbv:t(984)+t(561)+"R",MmZza:function(c,r){return c===r},JVgHh:"veYhJ",Scxsu:function(c,r){return c+r},AqUlv:function(c,r){return c*r},CrRKX:function(c,r){return c>>>r},GqkIj:"znnGB",RIHIN:t(933),OeWVV:t(1001),GoQWh:t(1587),wCCUs:"done",TLPHF:function(c,r){return c===r},INEla:t(1033)+t(908),nhUAm:t(1470),ERywT:function(c,r){return c===r},VCQVq:t(1168),HSUuS:t(1886)+"d error.",XBCmK:function(c,r){return c===r},GCHDf:function(c,r){return c<r},pGsrG:t(800),hcJuv:function(c,r,o){return c(r,o)},KukMM:"open",CxyZy:function(c,r,o){return c(r,o)},rtvrP:function(c,r,o){return c(r,o)},koAqt:function(c,r,o){return c(r,o)},zeNXD:function(c,r,o){return c(r,o)},dnJqy:function(c,r){return c instanceof r},nPziQ:"ping_onc"+t(903)+"t",GBGKz:t(1449),GVqhA:"WRUiz",JdEWR:t(1568),AaFNG:t(1733)+"2",TetQt:t(1746),DLjQZ:function(c,r){return c!==r},sFpZu:"xLKyj",HSuZc:t(1525),yTcuG:function(c,r){return c<r},peTzD:function(c,r){return c-r},nYiNz:function(c,r){return c<r},RkmUJ:function(c,r){return c===r},VkHRQ:t(825),kaeLl:function(c,r){return c<=r},FzcOy:function(c,r){return c>=r},hqUAH:function(c,r){return c<r},SKMkD:function(c,r){return c|r},YUpKv:function(c,r){return c&r},fmdCu:function(c,r){return c&r},vVEWU:function(c,r){return c>=r},fAKKr:function(c,r){return c<<r},nfFkz:function(c,r){return c<<r},jYjnQ:function(c,r){return c&r},NrUtV:function(c,r){return c|r},NiEFI:function(c,r){return c|r},WQnMc:function(c,r){return c&r},gMWnZ:function(c,r){return c&r},zZNRm:function(c,r){return c&r},teoCv:function(c,r){return c>>r},lWCuW:function(c,r){return c!=r},TLpyu:function(c,r){return c===r},UCaDZ:t(596),lvVCj:function(c,r){return c<r},cFKUQ:function(c,r){return c|r},HGYMC:function(c,r){return c&r},Bxqtp:function(c,r){return c&r},rxCUg:function(c,r){return c+r},cvbie:t(791)+t(1442),rdcQS:function(c,r){return c&r},mHajb:function(c,r){return c|r},HRiJT:function(c,r){return c>>r},uDHdo:function(c,r){return c&r},ocsUS:function(c,r){return c&r},qszsC:function(c,r){return c|r},GYwcx:function(c,r){return c|r},aBHdS:function(c,r){return c>>r},TAbYD:function(c,r){return c|r},QgJSF:function(c,r){return c&r},Bbqpr:function(c,r){return c-r},QbePF:function(c,r){return c==r},UxKkg:function(c,r){return c===r},OhqjJ:t(1847),GGbwx:function(c,r){return c(r)},NnrYE:function(c,r,o,l){return c(r,o,l)},OoERJ:function(c,r,o){return c(r,o)},afQGF:function(c,r){return c!==r},SMhYZ:function(c,r,o){return c(r,o)},TgJOg:function(c,r,o){return c(r,o)},Skkvp:function(c,r){return c!=r},UpcRh:function(c,r){return c===r},lpwVW:t(958),RUirE:t(1431),UumdL:function(c,r){return c==r},SbjfZ:function(c,r){return c===r},ikqeY:"SmeTb",WeDdV:t(1511),sVTlZ:t(1117),cXLVG:function(c,r,o){return c(r,o)},PEMWi:function(c,r){return c!==r},bxspP:t(1545)+"OR",llDaI:t(1437)+t(738),wAWKh:t(519),KVgFY:t(1132)+"reason",DTcpa:"script",oEhqx:t(829),wdpGB:t(1952)+t(703)+t(548)+"P",rWgeW:t(995),chwuM:function(c,r){return c(r)},WEkZK:function(c,r){return c!==r},KPwOW:"EfVpG",GoZtf:function(c,r){return c(r)},LBSfp:t(1767),JIrrE:t(1163),zPpzr:t(1656),GUMwN:function(c,r,o){return c(r,o)},PnhGo:t(821),swsaP:function(c,r,o,l){return c(r,o,l)},aSvNP:t(751),sRBZw:t(1541)+t(1322)+"s",rBSNb:t(796),YmzrQ:function(c,r,o){return c(r,o)},rGLPQ:function(c,r,o){return c(r,o)},ZiAAC:"zRcLb",sgzii:function(c,r){return c+r},ftGOr:t(1556),TZJiA:t(1380),JAUvm:function(c,r){return c===r},spUnd:t(712),UoFjD:function(c,r){return c<=r},pREDS:function(c,r){return c|r},DCHtK:function(c,r){return c&r},bijSk:function(c,r){return c|r},AQbTl:function(c,r){return c|r},KkeBd:"omgjU",wXLKt:function(c,r){return c||r},nvLVV:function(c,r){return c==r},jJlIE:t(940),Wdwlm:"Mzvkz",WNwQv:function(c,r){return c||r},TrUHb:function(c,r){return c!==r},lhlSc:t(1708),XEjsE:function(c,r){return c||r},YYXQT:function(c,r){return c||r},FPOIr:function(c,r,o){return c(r,o)},MiEbD:function(c,r){return c||r},eLgXG:function(c,r){return c===r},XNCqp:t(637),ZukWN:"AmTvh",LMNDK:function(c,r){return c||r},HPiRN:function(c,r){return c||r},lsckz:function(c,r){return c||r},GLewu:function(c,r){return c!=r},nPyHe:t(854)+t(1590)+"d",SBaOp:"qos",fZSVD:t(1330),ZBqbW:function(c,r){return c(r)},CdSDN:function(c,r){return c(r)},XiWTJ:function(c,r){return c!==r},arTpm:t(617),iCTRJ:t(1308),TpSZu:t(1833),tgdQY:function(c,r){return c(r)},TpNYA:t(1916),WWOwh:"wnWrm",cfbGV:"x_fronti"+t(511),hWZGw:function(c,r,o,l){return c(r,o,l)},bspRj:t(1703)+t(1845)+"k",hiefx:t(969),gVsBI:function(c,r,o,l){return c(r,o,l)},VVaoP:t(1943),BJrod:function(c,r){return c||r},HjAHy:t(892),xTdLB:function(c){return c()},URhka:function(c,r){return c===r},oFroz:function(c,r){return c instanceof r},pGrZp:function(c,r){return c instanceof r},mHXcQ:t(1013),IVNZW:function(c,r,o,l){return c(r,o,l)},UfrIi:function(c,r){return c(r)},pLXvI:function(c,r){return c|r},tvuvs:function(c,r){return c&&r},VoUHY:function(c,r){return c||r},eRyrY:function(c,r){return c!==r},DNLta:t(1011),PtjPr:"jKAVV",pkpWT:function(c,r){return c||r},sCfAa:function(c,r){return c(r)},tZoJN:function(c,r){return c+r},SKKsH:function(c,r){return c+r},SbDCv:"index out of ran"+t(1524),uANop:t(1221),BlglQ:function(c,r){return c||r},mwCRj:t(1376),clrcD:"integer too large",hyryj:function(c,r){return c>=r},kgarz:function(c,r){return c&r},gNJMW:function(c,r){return c+r},VSKJk:function(c,r){return c+r},LkkVJ:function(c,r,o){return c(r,o)},JNeTI:function(c,r){return c<<r},BBwpF:t(1377)+"1",wVjiD:function(c,r,o,l){return c(r,o,l)},wrAJe:function(c,r){return c+r},XLxfd:function(c,r){return c+r},FRNYp:function(c,r){return c<<r},PvHfJ:function(c,r){return c+r},wdvVg:function(c,r){return c|r},AYfIM:function(c,r){return c+r},jPJBX:function(c,r){return c+r},dSVmk:function(c,r){return c+r},BrHkH:t(1646),vjMSI:function(c,r){return c+r},qqdoa:function(c,r){return c>>>r},BJcOa:function(c,r){return c>>>r},tiKhP:function(c,r){return c+r},rRjia:function(c,r){return c+r},SWpLA:function(c,r){return c>>>r},OhKsL:function(c,r){return c+r},KiiQh:function(c,r){return c&r},XAfAi:function(c,r){return c&r},XYyKO:function(c,r){return c&r},thrfD:function(c,r){return c+r},pqLqQ:function(c,r){return c|r},WOuNB:t(1367),WqFUf:function(c,r,o,l){return c(r,o,l)},mjXFb:function(c,r){return c!==r},wExjT:function(c,r){return c<<r},YZwSA:t(687),UahXx:"fWlvO",YgoZl:function(c,r){return c(r)},pxtYe:function(c,r){return c+r},gDhlK:t(1653),JBGnc:function(c,r,o,l){return c(r,o,l)},Qpvpa:function(c,r,o,l){return c(r,o,l)},MWpCb:t(1553),qdZoD:function(c,r,o,l){return c(r,o,l)},sZhJg:"cursor.s"+t(461),tAIAH:t(1562)+t(906),sFbmY:function(c,r,o,l){return c(r,o,l)},qtGKH:t(1822),itCNY:t(927),aQsaK:function(c,r,o){return c(r,o)},oaBJr:t(1621),yWzLq:t(1337)+t(1156),PctQT:t(1454)+t(1628),YtlhH:t(1209)+t(1387),jqEPx:t(665),INfbr:t(1629),IbRIN:t(1971),dBscs:function(c){return c()},EIKck:t(1139),JNfcH:t(1632)+t(789)+"onnecting",XmQat:function(c,r){return c!==r},kDWBo:t(1586),whsrb:t(866)+"r",ciopE:function(c,r){return c===r},wmmSI:"StZmF",UIQaC:function(c,r){return c||r},OdcZb:t(1468),Laiii:function(c,r,o){return c(r,o)},MqSDl:t(515),bJBkj:function(c,r){return c(r)},eQfur:t(512)+"or",tOGFN:function(c){return c()},JtKen:function(c){return c()},UWRZR:t(1407),fKsYn:"Kkchr",njEmV:t(630),yqvxN:t(1879),CNIAm:t(1703)+t(1298),Jlund:function(c,r){return c(r)},UWJZr:"x_fronti"+t(1346),mMBuS:t(1455)+"s",GcyGg:t(886)+t(683)+"e",BEdep:function(c,r){return c(r)},gOoLY:function(c,r,o){return c(r,o)},TknLV:t(886)+t(1729)+"ue",JvolI:function(c,r){return c>r},nREhs:function(c,r){return c+r},WmKTd:function(c){return c()},lLElY:t(782),PwTDf:function(c){return c()},hFhfK:t(450),FygXN:t(794),ykfNW:function(c,r){return c&&r},ihNtP:function(c,r,o){return c(r,o)},VhCbr:function(c){return c()},xeiiL:t(1186),EtlmH:function(c,r){return c(r)},pWVPT:function(c,r){return c!==r},IRbAd:function(c){return c()},Vfszo:function(c,r){return c!==r},BQXVl:function(c){return c()},SGufm:function(c,r){return c instanceof r},sXsZz:function(c,r){return c===r},qUaMz:t(1850),SPKPY:t(615),DeKUu:function(c,r){return c===r},IxALo:function(c,r){return c===r},zZIgB:t(1351),kLubZ:function(c,r,o){return c(r,o)},mDime:function(c,r,o){return c(r,o)},iUsuG:function(c,r){return c===r},efzfq:t(1909),IqJxY:function(c,r,o){return c(r,o)},oKKBr:function(c,r){return c(r)},fkkAX:t(619)+t(1130),TjiIw:function(c,r){return c/r},CEAhg:t(1958)+"rovide v"+t(1726),thtdb:t(1201),OLNfl:t(1095),NpVQQ:t(1321),TvVSJ:t(663),CBfce:t(1840),CYpxc:t(1513)+"t",vSMWJ:t(527)+t(1543)+t(653)+"ct",mWyfD:t(1748),sJrcX:t(1288),ZiMsx:"online",hlUQt:function(c,r){return c!==r},rlbAa:"offline",nQKui:t(785),JPBVT:t(701),ozOzd:"ws://",hWUjv:t(1283),OHEqc:"bd_did",xpFCo:"ttwid",dRCgo:"device_id",HHcdK:function(c,r){return c||r},JDYQS:t(1958)+t(1154)+t(1247)+"viceID o"+t(478),EBIvT:function(c){return c()},gAiCk:t(1197)+"0",GqXfX:function(c,r){return c+r},kDOBa:function(c,r){return c(r)},uWiLN:function(c,r){return c===r},wGUvf:t(675),daVIc:t(1392),lRzJP:function(c,r){return c>r},OlNuV:function(c,r){return c-r},nIDvW:function(c,r,o){return c(r,o)},MinZr:function(c,r){return c(r)},yVilt:t(1332)+">",BSTls:function(c,r){return c*r},gDhax:function(c,r){return c!==r},aZrbA:"going aw"+t(443)+t(1513)+t(1887)+t(1020),YACtv:function(c,r){return c===r},PsHLW:t(1090),GKVTZ:t(1271)+"3",ilqqd:t(659),KQBmC:t(1252)+"1",TSyhB:t(1951),OxTud:t(1671),IGTOj:t(1176)+t(1793)+t(1622)+t(1956),vgigb:function(c,r){return c||r},UmhAa:function(c,r){return c===r},DMZui:t(1552),VLDPS:t(1601),DMJGy:t(1898),pSiao:t(459),zFAcD:function(c,r){return c===r},hXMum:t(1958)+t(822)+t(694)+t(737)+t(1448)+t(758)+t(999)+" arraybu"+t(1086),QDdBg:function(c,r){return c==r},hfMHs:function(c,r){return c!=r},ptQqK:function(c,r){return c instanceof r},ByzvA:function(c,r){return c(r)},BNaLa:t(1958)+t(822)+" valid s"+t(461),UkvcZ:function(c,r){return c(r)},HAxtP:function(c,r){return c===r},aSOzw:t(585),aHgPe:t(582),ujeMl:function(c,r){return c&r},JViHR:function(c,r){return c(r)},coItQ:function(c,r){return c*r},VWQWo:function(c,r){return c/r},eKxiy:function(c,r){return c!=r},CShEi:function(c,r){return c===r},ZEoIL:t(1281),vnYMT:function(c,r){return c!=r},pWhgk:t(1108)+t(808)+t(741)+"pe",yqQNU:function(c,r){return c!=r},FFtjv:t(1558)+t(1754)+t(861),YEOUi:t(1438)+t(1292)+t(1461),ImXlM:function(c,r){return c!=r},mlXOF:function(c,r){return c===r},KEnSF:"Object",wjVzv:function(c,r){return c!=r},AjIxs:function(c,r){return c===r},KOpTk:function(c,r){return c!=r},iJXNX:function(c,r,o){return c(r,o)},uErmL:t(1106)+t(1274)};Jt.r(Oe),Jt.d(Oe,{FWS:()=>Cm,CustomErrorEvent:()=>Ll,createCloseEvent:()=>kt,ReconnectEvent:()=>Ol,createErrorEvent:()=>wt,decodedFrame:()=>Nt,createOpenEvent:()=>Ul,CustomCloseEvent:()=>Ml,createReconnectEvent:()=>Fa,FrontierMessageEvent:()=>Bl,encodeFrame:()=>Yt,createMessageEvent:()=>zl,OpenEvent:()=>Fl,ErrorCode:()=>mn,Event:()=>gr,MessageEvent:()=>Nl});let n="";function i(c=""){let r=t,o={pqKZM:function(l,f){return e[F(1253)](l,f)},rnCUB:function(l){return l()}};if(e[r(504)](r(802),e[r(1669)]))PHGYve[r(434)](_0x236666,_0x52e811[r(720)]),PHGYve[r(620)](_0x5afc24);else{let f=""+Date.now(),m=n||(n=e[r(1756)](h,c)),_=Math[r(780)]()[r(497)](16).slice(-6);return e[r(1428)](e.qPCQV("02",f)+m,_)}}function s(){let c=t;return e[c(1428)](e[c(836)](1e4,Date.now()),Math.floor(e[c(1227)](1e4,Math[c(780)]())))}function a(c){let r=t;return e[r(1112)](e.YDYJt(Array,8).join("0"),e[r(1598)](parseInt,c,10)[r(497)](2))[r(446)](-8)}function d(c){let r=t,o={yKNjM:function(l,f){return e.nrxUJ(l,f)},VWhcY:e[r(611)],wOoEQ:e[r(1242)],Kgyan:e[r(994)]};if(e.uzgWU(e[r(742)],e.coycp))return e.qPCQV(e[r(1426)](Array,4)[r(1303)]("0"),parseInt(c,2)[r(497)](16))[r(446)](-4);cpYrbZ.yKNjM(cpYrbZ[r(1494)],typeof _0x2f3655)&&_0x510a6b.toStringTag&&_0xe27031[r(939)+r(1384)](_0x3f460d,_0xd6d00c[r(497)+r(1950)],{value:cpYrbZ[r(855)]}),_0x2a1385[r(939)+"operty"](_0x2d5426,cpYrbZ.Kgyan,{value:!0})}function u(c){let r=t,o=c[r(1559)](/\./)[r(1970)](m=>a(m)),l=[];return l[0]=e[r(1253)](d,e[r(700)](o[0],o[1])),l[1]=e[r(1426)](d,e[r(985)](o[2],o[3])),[e.uSOdZ,e.uSOdZ,e[r(1452)],e[r(1452)],e[r(1452)],e[r(660)],l[0],l[1]][r(1303)]("")}function h(c){let r=t,o=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[r(1589)](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(1589)](c);return o?e[r(1253)](u,c):l?e.bUotN(x,c):e[r(993)]}function x(c){let r=t;if(e[r(761)](e[r(1583)],r(577))){let o=e[r(1354)](this._options[r(1269)+r(1212)],_0x44672b)?{force:!!this[r(735)][r(1269)+r(1212)][r(1812)],encoding:this[r(735)][r(1269)+"ncoding"].encoding?this[r(735)][r(1269)+r(1212)][r(1025)].replace(/\s/g,"")[r(1572)+r(902)]():""}:{force:!1,encoding:this[r(735)]["payloadE"+r(1212)]?this[r(735)][r(1269)+"ncoding"][r(1747)](/\s/g,"")[r(1572)+r(902)]():""},l=_0x1b92f0[r(1269)+"ncoding"]?_0x380035[r(1269)+r(1212)][r(1747)](/\s/g,"")[r(1572)+r(902)]():"",f=e.bKCYP(this[r(735)].payloadType,_0x303b31)?{force:!!this[r(735)][r(1205)+r(1947)].force,type:this[r(735)][r(1205)+"ype"][r(1450)]?this[r(735)][r(1205)+r(1947)][r(1450)][r(1747)](/\s/g,"")[r(1572)+r(902)]():""}:{force:!1,type:this[r(735)][r(1205)+r(1947)]?this._options[r(1205)+r(1947)][r(1747)](/\s/g,"")[r(1572)+r(902)]():""},m=_0x40f63d[r(1205)+r(1947)]?_0x24ba6f[r(1205)+r(1947)][r(1747)](/\s/g,"")[r(1572)+r(902)]():"",_=f[r(1812)]?f.type:m||f.type,S=o[r(1812)]?o[r(1025)]:l||o[r(1025)],g=[e[r(1848)],e[r(1849)],e[r(563)],e.FoEOX],R=[r(625)+"e",r(1013)];this[r(735)][r(885)+"ansformTextPayload"]&&g[r(1499)](_)&&(!S||R[r(1499)](S))?_0x35ceca[r(483)+r(1304)]=e[r(668)](_0x2ea4b2,_0x173cb7[r(956)],0,_0x566721[r(956)][r(1350)+"th"]):_0x221997["textPayl"+r(1304)]=""}else{let o="",l=[],f=0,m=0,_=!0,S=e[r(1452)];if(e[r(488)](c.indexOf("::"),-1)){let g=c[r(1559)]("::");for(let L=0;e[r(1383)](L,g[r(1740)]);L++){let B=g[L];if(e[r(928)](B[r(1600)](":"),0)){let J=B[r(1559)](":");_&&(f=J[r(1740)]),m+=J.length;for(let $=0;e[r(1116)]($,J[r(1740)]);$++)if(e[r(1030)](4,J[$].length)){let me=S[r(795)+"g"](0,e.rxYGd(4,J[$].length)),Ke=me.concat(J[$]);l[r(998)](Ke)}else l.push(J[$]);_=!1}else{if(e[r(1475)](4,B.length)){let J=S[r(795)+"g"](0,e[r(1923)](4,B[r(1740)])),$=J[r(964)](B);l[r(998)]($)}else l.push(B);_&&(f+=1),m+=1,_=!1}}let R="";for(let L=0;e[r(814)](L,8-m);L++)R=R[r(964)](S);for(let L=0;e[r(826)](L,l.length);L++)e.uTdmd(L,f)?(o=o[r(964)](R),o=o[r(964)](l[L])):o=o.concat(l[L]);return o}if(e.GfJLQ(e[r(1318)],r(1302))){let g=e[r(1598)](_0x1d1004,e[r(677)],{message:this[r(755)+r(1962)+"age"](_0x3ccaeb)});this[r(507)](e[r(677)],g);let R=e.BRmlG(_0x46556c,e[r(1347)],{reason:this[r(755)+r(1962)+r(1953)](_0x523f4b)});this[r(507)](e.QUHmb,R)}else{let g=c.split(":");for(let R=0;e[r(826)](R,g[r(1740)]);R++){let L=g[R];if(e[r(761)](4,g[R][r(1740)])){let B=S[r(795)+"g"](0,e.rxYGd(4,g[R].length)),J=B[r(964)](L);o=o[r(964)](J)}else o=o[r(964)](L)}return o}}}function p(c,r){let o=t,l=c[o(1270)];l!==void 0&&(e[o(1217)](ae,r,10),e[o(1217)](ze,r,l));let f=c[o(874)];e[o(761)](void 0,f)&&(e[o(1598)](ae,r,18),e[o(1217)](ze,r,f))}function w(c){let r=t;if(e[r(1030)](e[r(1565)],e[r(1565)]))return r(1404)+"_"+this[r(1220)];{let o={};e:for(;!e.JSntm(V,c);){let l=e[r(1253)](ee,c);switch(e.mtarV(l,3)){case 0:break e;case 1:o[r(1270)]=e.OdbIa(ye,c,e.yongw(ee,c));break;case 2:o[r(874)]=e[r(1889)](ye,c,e[r(1426)](ee,c));break;default:e[r(1177)](C,c,e[r(1672)](7,l))}}if(e[r(1635)](void 0,o[r(1270)]))throw new Error(e[r(810)]);if(o[r(874)]===void 0)throw new Error(r(500)+r(1868)+r(544)+r(874));return o}}function b(c){let r=t,o=e[r(1366)](D);return y(c,o),e[r(1386)](M,o)}function y(c,r){let o=t,l={vkQVe:function(f,m){return e.KDzMF(f,m)},rUgnW:"going aw"+o(443)+"reconnec"+o(1887)+o(1020)};if(o(1327)===o(1497))_0x211903=_0x1341dd[o(983)+"At"](_0x4b8d56),e[o(1383)](_0x165d26,128)?_0x160aa1+=1:_0x1d03c1<2048?_0x2b0957+=2:(64512&_0x2d3725)===55296&&e[o(1728)](64512,_0x405670.charCodeAt(e[o(700)](_0x2000fb,1)))===56320?(++_0x5b89de,_0x245c1f+=4):_0x5c1c11+=3;else{let f=c[o(648)];e[o(1418)](void 0,f)&&(e[o(1177)](ae,r,8),e[o(1867)](lt,r,f));let m=c[o(962)];e[o(1534)](void 0,m)&&(e.LsPHo(ae,r,16),lt(r,m));let _=c[o(1553)];e[o(1030)](void 0,_)&&(ae(r,24),e[o(1889)](lt,r,e[o(1741)](P,_)));let S=c.method;e[o(1832)](void 0,S)&&(e[o(1157)](ae,r,32),e[o(1177)](lt,r,e[o(1181)](P,S)));let g=c[o(558)];if(e[o(1418)](void 0,g))for(let Xe of g){e.ijQjJ(ae,r,42);let st=e[o(1657)](D);e[o(1026)](p,Xe,st),ae(r,st[o(621)]),T(r,st),e[o(1741)](O,st)}let R=c[o(1269)+o(1212)];if(R!==void 0)if(e[o(531)](e.elIIM,e[o(1830)])){let Xe=this[o(523)][o(1480)](this[o(713)]),st=_0x45eace.parse(l.vkQVe(Xe,"{}"));return _0xb4f4a8.keys(st)}else ae(r,50),e.KfYvE(ze,r,R);let L=c["payloadT"+o(1947)];e.jojWn(void 0,L)&&(e[o(1217)](ae,r,58),e[o(1365)](ze,r,L));let B=c.payload;B!==void 0&&(e[o(1177)](ae,r,66),e[o(1872)](ae,r,B.length),e[o(1157)](de,r,B));let J=c[o(1771)];e.wsCYU(void 0,J)&&(e[o(1872)](ae,r,74),e[o(1068)](ze,r,J));let $=c[o(1820)+"ming"];if(e.xPpmy(void 0,$))if(e[o(494)](e[o(762)],e.rDvzq)){if(!this._navigatorOnline()||this[o(1625)+o(1723)])return;this[o(1425)+o(1038)]?.[o(1050)+"pointCon"+o(1344)](),this[o(1769)+o(1933)]?.[o(1358)+o(869)](),this[o(664)]?this[o(1074)+o(917)](1001,l[o(1193)],!0):this[o(1685)]()}else e[o(1177)](ae,r,82),e[o(1365)](ze,r,$);let me=c[o(676)];e[o(550)](void 0,me)&&(e[o(1177)](ae,r,90),ze(r,me));let Ke=c[o(858)+"e"];if(e.uzgWU(void 0,Ke))if(e[o(1423)](e[o(1824)],e.Xgkvf)){let Xe=0,st=0;for(let _n=0;e[o(954)](_n,_0x12731f[o(1740)]);++_n)st=_0x49c945[o(983)+"At"](_n),st<128?Xe+=1:e[o(1116)](st,2048)?Xe+=2:e[o(1635)](e[o(1728)](64512,st),55296)&&e[o(494)](64512&_0x20c88e[o(983)+"At"](e[o(1142)](_n,1)),56320)?(++_n,Xe+=4):Xe+=3;return Xe}else ae(r,96),lt(r,e.yongw(P,Ke))}}function v(c){return e[t(1253)](I,e.agRcb(U,c))}function I(c){let r=t,o={};e:for(;!V(c);){let l=e.FTRRL(ee,c);switch(e[r(1532)](l,3)){case 0:break e;case 1:o[r(648)]=e[r(730)](it,c,!0);break;case 2:o[r(962)]=e[r(1026)](it,c,!0);break;case 3:o[r(1553)]=e[r(1810)](ee,c);break;case 4:o[r(465)]=e.gkTXj(ee,c);break;case 5:{let f=e.ZsyYl(A,c);(o[r(558)]||(o.headers=[]))[r(998)](e[r(1010)](w,c)),c[r(621)]=f;break}case 6:o[r(1269)+r(1212)]=e.HZFzf(ye,c,e[r(1401)](ee,c));break;case 7:o[r(1205)+r(1947)]=e[r(1157)](ye,c,ee(c));break;case 8:o[r(956)]=e[r(1889)](oe,c,e[r(1181)](ee,c));break;case 9:o[r(1771)]=e[r(1329)](ye,c,e[r(784)](ee,c));break;case 10:o[r(1820)+r(613)]=ye(c,e.JSntm(ee,c));break;case 11:o[r(676)]=e.rfaQx(ye,c,e[r(1741)](ee,c));break;case 12:o.frameType=e[r(1253)](ee,c);break;default:e.BRmlG(C,c,e[r(843)](7,l))}}if(e[r(494)](void 0,o.SeqID))throw new Error("Missing "+r(1868)+" field: SeqID");if(e[r(494)](void 0,o[r(962)]))throw new Error("Missing required"+r(544)+"LogID");if(e[r(1249)](void 0,o[r(1553)]))throw new Error(r(500)+r(1868)+r(544)+"service");if(e[r(1107)](void 0,o[r(465)]))throw new Error(e.mwCCi);return o}function A(c){let r=t,o=e[r(857)](ee,c),l=c.limit;return c[r(621)]=c[r(839)]+o,l}function C(c,r){let o=t;switch(r){case 0:for(;e[o(1672)](128,e[o(1799)](H,c)););break;case 2:e.HZFzf(K,c,e.UyVNp(ee,c));break;case 5:e[o(730)](K,c,4);break;case 1:e[o(1153)](K,c,8);break;default:throw new Error(e[o(1016)](e.PpJVQ,r))}}function P(c){return c|=0,{low:c,high:e.qbalW(c,31),unsigned:c>=0}}let E=[];function D(){let c=t,r=E[c(1623)]();return r?(r.offset=r[c(621)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(c){E[t(998)](c)}function U(c){let r=t;return e[r(504)](e[r(439)],e[r(439)])?{bytes:c,offset:0,limit:c[r(1740)]}:!!this._qosDB}function M(c){let r=t;if(r(1506)!=="nqoPJ"){let o=this[r(1412)+r(1550)][r(1225)]((l,f)=>(l+=f&&f[r(1350)+"th"]||0,l),0);return e.YipVq(o,this._ws?this._ws[r(870)+r(473)]:0)}else{let o=c[r(914)],l=c[r(621)];return e[r(494)](o.length,l)?o:o[r(1873)](0,l)}}function K(c,r){let o=t;if(e[o(1389)](c.offset,r)>c[o(621)])throw new Error(o(912)+o(1719));c[o(839)]+=r}function V(c){let r=t;return c[r(839)]>=c[r(621)]}function ie(c,r){let o=t,l={poBkZ:function(f,m){return e[F(905)](f,m)},OAjny:function(f,m){return f|m},jiOGH:function(f,m){return e[F(766)](f,m)},BwDYi:function(f,m){return f|m},ggHgC:function(f,m){return f&m},iNZZg:function(f,m){return e.GfJLQ(f,m)},KmBxU:function(f,m){return f===m},OkYHY:function(f,m){return e[F(628)](f,m)},uIxch:e[o(1801)],sZxHc:function(f,m){return e[o(766)](f,m)},EymXm:function(f,m){return e.FRPcd(f,m)},yQLch:function(f,m){return e.AUhtW(f,m)},NVdmW:function(f,m){return e[o(1728)](f,m)},IURmx:function(f,m){return e[o(1548)](f,m)},rWvOR:function(f,m){return e[o(1672)](f,m)},CRooe:function(f,m){return e.AUhtW(f,m)},XEhZo:function(f,m){return e[o(1467)](f,m)},UuiQY:function(f,m){return e[o(843)](f,m)},WjWfc:function(f,m){return e[o(1467)](f,m)}};if(e[o(1942)](e[o(1336)],o(1734)))this._isMiniTT?_0x5007c5["onNetwor"+o(1159)+o(1076)](({isConnected:f})=>{let m=o;this[m(1178)+m(1370)+m(838)]=f,f?this[m(1611)+m(1732)]():this[m(1611)+m(1491)]()}):this._isMiniWX&&_0xb21926[o(1297)+"kStatusC"+o(1076)](({isConnected:f})=>{let m=o;this[m(1178)+m(1370)+"line"]=f,f?this[m(1611)+"nLine"]():this[m(1611)+"ffLine"]()});else{let f=c[o(914)],m=c[o(839)],_=c[o(621)],S=e[o(592)](m,r);if(S>f.length)if(e[o(471)](e.Ewwam,e[o(1187)]))if(_0x198e56=_0x553f3b[o(983)+"At"](_0x9447c8),l[o(816)](_0x4f7896,128))_0x22fca5[_0x4e5a14++]=_0x3c4565;else if(l.poBkZ(_0x20f58f,2048))_0x2a770b[_0x58ee33++]=l[o(1888)](l[o(1405)](_0x1a2bb1,6),192),_0x322ed6[_0x5d8dc5++]=l[o(1711)](l[o(1320)](63,_0x56ae61),128);else if(l[o(597)](l[o(1320)](64512,_0xb6e930),55296)&&l[o(435)](l[o(1320)](64512,_0x2a4a16=_0x57f714[o(983)+"At"](l[o(586)](_0x172c82,1))),56320)){let g=l[o(1239)][o(1559)]("|"),R=0;for(;;){switch(g[R++]){case"0":_0xb5f986[_0x49ef58++]=l[o(1888)](l[o(1320)](l[o(1368)](_0x3fee05,6),63),128);continue;case"1":_0x4a530b[_0x5c0ac1++]=l[o(1711)](l.EymXm(_0x274104>>12,63),128);continue;case"2":++_0x130374;continue;case"3":_0x44bb56[_0x301b31++]=l[o(1888)](_0x1f05fb>>18,240);continue;case"4":_0x2142a1[_0x321f66++]=l[o(1486)](l[o(1529)](63,_0x430b63),128);continue;case"5":_0x3727f2=l[o(586)](l[o(586)](65536,l[o(930)](1023&_0x5917b7,10)),l[o(590)](1023,_0x591a32));continue}break}}else _0x3706cf[_0x3faee0++]=l[o(584)](_0x467cab>>12,224),_0x2122e2[_0x2f49cb++]=l.XEhZo(l[o(1917)](l[o(1405)](_0x1a9bfe,6),63),128),_0xa78cbc[_0x20fcd2++]=l.WjWfc(63&_0x28ed4b,128);else{let g=new Uint8Array(e[o(1227)](2,S));g.set(f),c[o(914)]=g}return c.offset=S,e[o(928)](S,_)&&(c[o(621)]=S),m}}function X(c,r){let o=t,l=c[o(839)];if(e[o(1048)](e.pvjVS(l,r),c.limit))throw new Error(e[o(1689)]);return c.offset+=r,l}function oe(c,r){let o=t,l=e[o(1598)](X,c,r);return c[o(914)][o(1873)](l,e[o(628)](l,r))}function de(c,r){let o=t,l=ie(c,r.length);c[o(914)][o(624)](r,l)}function ye(c,r){let o=t;if(e[o(494)](e[o(656)],"jQCYl")){let l=e[o(1329)](X,c,r),f=String[o(1022)+o(1241)],m=c.bytes,_="\uFFFD",S="";for(let g=0;e[o(905)](g,r);g++){let R=m[g+l],L,B,J,$;e[o(1249)](e[o(1728)](128,R),0)?S+=e[o(1913)](f,R):e[o(1957)](e[o(1715)](224,R),192)?e[o(1110)](g,1)>=r?S+=_:(L=m[e[o(1127)](g,l)+1],e.QDaCM(192,L)!==128?S+=_:($=e[o(843)](31,R)<<6|e.QDaCM(63,L),e[o(547)]($,128)?S+=_:(S+=e[o(1253)](f,$),g++))):e[o(1715)](240,R)==224?e[o(1016)](g,2)>=r?S+=_:(L=m[g+l+1],B=m[e[o(1142)](e[o(1389)](g,l),2)],e[o(1030)](e[o(1467)](L,e[o(1548)](B,8))&49344,32896)?S+=_:($=e.AUhtW(e[o(1467)](e[o(1548)](e[o(1715)](15,R),12),e[o(1551)](e[o(458)](63,L),6)),e[o(1842)](63,B)),e[o(954)]($,2048)||e.CVUNS($,55296)&&e[o(1228)]($,57343)?S+=_:(S+=f($),g+=2))):e[o(1043)](248&R,240)?e.MUPUx(e[o(1098)](g,3),r)?S+=_:(L=m[e[o(1289)](e[o(1098)](g,l),1)],B=m[e.IGQNH(e[o(464)](g,l),2)],J=m[e.zMNKe(g+l,3)],e[o(503)](e[o(1728)](e.vFUOK(L,e[o(1548)](B,8))|e[o(1548)](J,16),12632256),8421504)?S+=_:($=e[o(936)](e[o(936)](e.xnXvD(7&R,18)|(63&L)<<12,e[o(1066)](e[o(1715)](63,B),6)),e[o(1715)](63,J)),e[o(1696)]($,65536)||e[o(1048)]($,1114111)?S+=_:($-=65536,S+=e.zGuqT(f,e[o(1389)](e[o(485)]($,10),55296),e[o(1110)](e.ffYew(1023,$),56320)),g+=3))):S+=_}return S}else return _0x415aad&&e[o(1607)](!0,_0x15b6d1.isLong)}function ze(c,r){let o=t,l=r[o(1740)],f=0;for(let S=0;e[o(905)](S,l);S++){let g=r[o(983)+"At"](S);e[o(529)](g,55296)&&g<=56319&&e.ajLUC(S+1,l)&&(g=e[o(1923)](e[o(1289)](g<<10,r[o(983)+"At"](++S)),56613888)),f+=e.IeTCh(g,128)?1:e[o(951)](g,2048)?2:g<65536?3:4}e[o(1867)](ae,c,f);let m=e[o(1068)](ie,c,f),_=c[o(914)];for(let S=0;e[o(1402)](S,l);S++){let g=r[o(983)+"At"](S);g>=55296&&e.TVFlC(g,56319)&&e[o(575)](e.znCOj(S,1),l)&&(g=e.rxYGd(e[o(1066)](g,10)+r[o(983)+"At"](++S),56613888)),e[o(865)](g,128)?_[m++]=g:(e.MbReW(g,2048)?_[m++]=e[o(766)](g,6)&31|192:(e[o(954)](g,65536)?_[m++]=e.AUhtW(e[o(888)](e[o(1474)](g,12),15),224):(_[m++]=e[o(1234)](e.CDgCd(g,18)&7,240),_[m++]=e.HBWiA(e[o(1018)](g,12),63)|128),_[m++]=e[o(458)](e[o(1476)](g,6),63)|128),_[m++]=63&g|128)}}function T(c,r){let o=t,l=e.LsPHo(ie,c,r[o(621)]),f=c[o(914)],m=r[o(914)];for(let _=0,S=r.limit;e.tqDgC(_,S);_++)f[e[o(700)](_,l)]=m[_]}function H(c){return c[t(914)][X(c,1)]}function j(c,r){let o=t,l=e.zGuqT(ie,c,1);c[o(914)][l]=r}function ee(c){let r=t,o=0,l=0,f;do f=e[r(982)](H,c),e[r(1369)](o,32)&&(l|=e[r(1551)](e[r(843)](127,f),o)),o+=7;while(e[r(1672)](128,f));return l}function ae(c,r){let o=t;if(e[o(1644)](e[o(1924)],e[o(593)]))return this[o(1901)+"s"][this[o(1768)+o(555)]];for(r>>>=0;e[o(1138)](r,128);)e[o(1889)](j,c,e[o(1940)](127,r)|128),r>>>=7;e[o(658)](j,c,r)}function it(c,r){let o=t,l=0,f=0,m=0,_;return _=e.yongw(H,c),l=e[o(967)](127,_),e[o(1617)](128,_)&&(_=e[o(1618)](H,c),l|=e[o(1066)](e.QDaCM(127,_),7),e[o(1940)](128,_)&&(_=H(c),l|=e[o(1066)](e.YVJiH(127,_),14),e[o(1842)](128,_)&&(_=H(c),l|=e[o(1551)](e[o(1416)](127,_),21),e[o(1265)](128,_)&&(e[o(1602)](e[o(868)],e.aLrEb)?(_=e[o(1058)](H,c),f=e[o(1728)](127,_),e[o(1702)](128,_)&&(_=e[o(1913)](H,c),f|=e[o(1551)](e[o(967)](127,_),7),e[o(458)](128,_)&&(_=H(c),f|=e[o(988)](e[o(770)](127,_),14),e[o(1508)](128,_)&&(_=e[o(1839)](H,c),f|=e[o(1151)](127&_,21),e.HBWiA(128,_)&&(_=e.dSCRB(H,c),m=e.uCjkA(127,_),e[o(1508)](128,_)&&(_=e.ZsWgf(H,c),m|=e.VkbuZ(127,_)<<7)))))):(this["_message"+o(1550)][o(562)](),this[o(1412)+o(1550)].push(_0x5d047)))))),{low:e[o(1394)](l,f<<28),high:e.SfGTo(f>>>4,e[o(1188)](m,24)),unsigned:r}}function lt(c,r){let o=t,l=e[o(1532)](r[o(1060)],0),f=e[o(1339)](e[o(768)](r[o(1060)],28)|e[o(1169)](r.high,4),0),m=e.yiGLo(r[o(680)],24),_=m===0?e.bfPWz(0,f)?l<16384?e[o(826)](l,128)?1:2:e[o(447)](l,2097152)?3:4:f<16384?f<128?5:6:e.OCvCP(f,2097152)?7:8:e[o(719)](m,128)?9:10,S=e.Cwztt(ie,c,_),g=c[o(914)];switch(_){case 10:g[e[o(872)](S,9)]=e[o(1955)](m,7)&1;case 9:g[e.znCOj(S,8)]=e.wsCYU(9,_)?e[o(1053)](128,m):e[o(980)](127,m);case 8:g[e[o(1566)](S,7)]=_!==8?e[o(1355)](e[o(1955)](f,21),128):f>>>21&127;case 7:g[e[o(1210)](S,6)]=e[o(1423)](7,_)?e[o(1532)](f,14)|128:e[o(1028)](e[o(1955)](f,14),127);case 6:g[S+5]=e[o(604)](6,_)?e[o(1394)](e[o(1339)](f,7),128):e[o(980)](e.SCXMP(f,7),127);case 5:g[e.dXLPd(S,4)]=e.IdogB(5,_)?e[o(1355)](128,f):e[o(1853)](127,f);case 4:g[e[o(872)](S,3)]=e[o(1418)](4,_)?e[o(1275)](l,21)|128:e[o(1129)](e[o(1906)](l,21),127);case 3:g[e[o(779)](S,2)]=_!==3?e[o(638)](e[o(1493)](l,14),128):e[o(1842)](e[o(1808)](l,14),127);case 2:g[e[o(985)](S,1)]=e[o(1423)](2,_)?e[o(1234)](e[o(809)](l,7),128):e.zoXPj(l,7)&127;case 1:g[S]=e[o(897)](1,_)?e[o(1467)](128,l):e[o(1129)](127,l)}}function Nt(c){return v(c)}function Yt(c){let r=t;return e[r(1326)](r(1005),e[r(1338)])?e[r(662)](b,c):this._socket.readyState}let gn=65536,zn="\0\0\0\0\0\0\0\0",mt=e[t(1309)](gn,gn),pr=e[t(1421)](mt,mt),Ne=e.VWQWo(pr,2),pe=String[t(946)+"e"].charCodeAt;class ce{constructor(r,o,l){let f=t;this[f(1464)]=!0,this.low=e[f(657)](0,r),this.high=e[f(1394)](0,o),this[f(1701)]=!!l}static[t(1464)](r){return r&&r.isLong===!0}static[t(1062)](r,o,l){let f=t;if(e.vHorO!==f(1173)){let m=_0x246383(f(720),{message:_0x4d72ae[f(659)],code:_0x3409b4[f(1545)+"OR"],error:_0x5a9f52});this[f(877)+f(1218)+f(1388)](m)}else return new ce(r,o,l)}static[t(1063)+"s"](r,o,l){let f=t;return l?ce[f(1063)+"sLE"](r,o):ce[f(1063)+"sBE"](r,o)}static[t(1063)+"sLE"](r,o){let l=t;return new ce(e[l(1355)](e[l(729)](r[0],e[l(1551)](r[1],8)),e[l(988)](r[2],16))|e[l(1551)](r[3],24),e[l(657)](e[l(1929)](r[4],r[5]<<8)|e[l(1306)](r[6],16),e.bCBMu(r[7],24)),o)}static[t(1063)+t(723)](r,o){let l=t;return new ce(e[l(1929)](e[l(1596)](e[l(992)](e[l(1660)](r[4],24),r[5]<<16),r[6]<<8),r[7]),e[l(1394)](e[l(1083)](e[l(1467)](e[l(1548)](r[0],24),e[l(1151)](r[1],16)),r[2]<<8),r[3]),o)}static fromHash(r){let o=t;return e[o(1602)](r,zn)?ut:new ce(e[o(1682)](e.gBhoh(e[o(1687)](pe.call(r,0),pe[o(1399)](r,1)<<8),pe[o(1399)](r,2)<<16),e[o(1231)](pe[o(1399)](r,3),24))>>>0,e[o(848)](e[o(1053)](e[o(1083)](pe[o(1399)](r,4),e[o(480)](pe.call(r,5),8)),pe[o(1399)](r,6)<<16),pe[o(1399)](r,7)<<24)>>>0,!0)}toHash(){let r=t;return String[r(1022)+r(1241)](e[r(1391)](255,this[r(1060)]),e[r(559)](this[r(1060)]>>>8,255),e.yvAFM(this.low>>>16,255),e.myfoC(this[r(1060)],24),e.FRPcd(255,this.high),e[r(468)](e[r(1955)](this.high,8),255),e[r(919)](e[r(1772)](this[r(680)],16),255),e[r(1284)](this[r(680)],24))}static fromNumber(r,o=!0){let l=t;if(e[l(1353)](isNaN,r))return o?Ug:ut;if(o){if(e[l(1585)](r,pr))return Gg}else{if(r<=-Ne)return qg;if(r+1>=Ne)return Hg}return ce.fromBits(e[l(893)](e[l(1579)](r,mt),0),e[l(898)](e[l(792)](r,mt),0),o)}toNumber(){let r=t;return this[r(1701)]?e[r(1142)](e[r(479)](e[r(696)](this[r(680)],0),mt),this.low>>>0):e[r(1389)](e.GKvgG(this[r(680)],mt),this[r(1060)]>>>0)}[t(1662)](){let r=t;return e[r(1107)](0,this[r(680)])&&e[r(1635)](0,this[r(1060)])}[t(1859)](r){let o=t;ce[o(1464)](r)||(r=ce[o(1797)+"er"](r));let l=e.KrNBj(this.high,16),f=65535&this[o(680)],m=this.low>>>16,_=e[o(1081)](65535,this[o(1060)]),S=r[o(680)]>>>16,g=e[o(1865)](65535,r[o(680)]),R=e.yiGLo(r[o(1060)],16),L=e.hhjTS(65535,r[o(1060)]),B=0,J=0,$=0,me=0;return me+=_+L,$+=e[o(1268)](me,16),me&=65535,$+=m+R,J+=$>>>16,$&=65535,J+=f+g,B+=J>>>16,J&=65535,B+=e[o(599)](l,S),B&=65535,ce[o(1062)](e[o(1017)](e[o(1151)]($,16),me),e[o(674)](B<<16,J),this.unsigned)}[t(1609)](r){let o=t;return ce.isLong(r)||(r=ce[o(1797)+"er"](r)),e[o(850)](this[o(1701)],r[o(1701)])&&this[o(680)]>>>31===1&&e[o(1107)](e[o(1445)](r[o(680)],31),1)?!1:e[o(1667)](this[o(680)],r[o(680)])&&e[o(504)](this[o(1060)],r.low)}[t(828)](){let r=t,o={ZnEeR:function(l,f){return e.IDhZb(l,f)},VDFbN:function(l,f){return e[F(667)](l,f)}};if(e[r(775)]!==e[r(1557)])return this.low===-1&&e[r(1607)](-1,this[r(680)])?ce[r(1062)](0,0,this[r(1701)]):e[r(1644)](-1,this[r(1060)])?ce[r(1062)](0,e[r(1110)](this[r(680)],1),this[r(1701)]):ce[r(1062)](e[r(464)](this[r(1060)],1),this[r(680)],this[r(1701)]);{let{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:m}=this[r(735)],_=o[r(541)](l,_0x5d5c55[r(971)](m,_0x2d5768-1));return o[r(845)](_,f)?f:_}}[t(1490)](r){let o=t;return r?this[o(1857)+"E"]():this[o(1433)+"E"]()}[t(1857)+"E"](){let r=t,o={FNgHF:function(l,f){return e[F(871)](l,f)},BeMtC:function(l,f){return e.Hvrdn(l,f)},djsZB:function(l,f){return l|f},sBTVY:function(l,f){return e[F(1757)](l,f)},CsVKE:function(l,f){return e[F(499)](l,f)},KhNnQ:function(l,f){return l&f},BcOAb:function(l,f){return e[F(1786)](l,f)},zQIOV:function(l,f){return e[F(1427)](l,f)},nnTbd:function(l,f,m){return e[F(1892)](l,f,m)},pPqGG:function(l,f){return l+f},QfJxG:function(l,f){return l>>f}};if(e.lwipX(e[r(1333)],"DtEJq")){let l=this[r(680)],f=this[r(1060)];return[e[r(1865)](255,f),e[r(1842)](e[r(1284)](f,8),255),e[r(1260)](e[r(1906)](f,16),255),e.YjPic(f,24),e[r(1858)](255,l),e.nRFFH(e[r(873)](l,8),255),e[r(1935)](e[r(655)](l,16),255),l>>>24]}else _0x508342=zzvwds[r(1466)](zzvwds[r(1012)](zzvwds[r(536)](zzvwds[r(1698)](7&_0x4931c9,18),zzvwds[r(1539)](63&_0x2e72ad,12)),(63&_0x6756a8)<<6),zzvwds[r(920)](63,_0x285687)),zzvwds[r(1520)](_0x2a24f4,65536)||zzvwds[r(926)](_0x34a698,1114111)?_0x366b95+=_0x441521:(_0x4db9b4-=65536,_0x3d8781+=zzvwds[r(1049)](_0x4ff0e9,zzvwds[r(1219)](zzvwds[r(736)](_0x2750e5,10),55296),zzvwds[r(1219)](1023&_0x12305f,56320)),_0x24e398+=3)}[t(1433)+"E"](){let r=t,o=this.high,l=this[r(1060)];return[o>>>24,e[r(1259)](e[r(768)](o,16),255),e[r(1932)](e[r(1509)](o,8),255),e[r(1842)](255,o),e[r(1604)](l,24),e[r(1052)](l,16)&255,e[r(1919)](e[r(1955)](l,8),255),e[r(1935)](255,l)]}}let ut=new ce(0,0,!1),Ug=new ce(0,0,!0),Hg=ce[t(1062)](-1,2147483647,!1),Gg=ce.fromBits(-1,-1,!0),qg=ce[t(1062)](0,-2147483648,!1);var mn=(function(c){let r=t,o=e[r(1881)][r(1559)]("|"),l=0;for(;;){switch(o[l++]){case"0":c[c[e[r(1825)]]=5004]=e[r(1825)];continue;case"1":c[c[e[r(1804)]]=5002]=e[r(1804)];continue;case"2":c[c[e[r(852)]]=5003]=e.JOjbv;continue;case"3":return c;case"4":c[c.OPEN_ERROR=5005]="OPEN_ERROR";continue;case"5":c[c["NATIVE_E"+r(738)]=5001]=r(1437)+r(738);continue}break}})({});class gr{constructor(r){let o=t;this[o(1450)]=r,this[o(684)]=null}}class Ol extends gr{constructor(r,o){let l=t;super(r),this.message=o&&o[l(659)]||null}}class Ll extends gr{constructor(r,o){let l=t;super(r),this[l(720)]=o&&o[l(720)]||null,this[l(651)]=o&&o[l(651)]||0,this.filename=o&&o[l(1699)]||"",this[l(948)]=o&&o[l(948)]||0,this[l(659)]=o&&o.message||"",this[l(1879)]=o&&o[l(1879)]||5001}}class Ml extends gr{constructor(r,o){let l=t;super(r),this[l(1879)]=o&&o[l(1879)]||0,this[l(1526)]=o&&o.reason||"",this[l(1335)]=o&&o[l(1335)]||!1,this["willReco"+l(1094)]=o&&o[l(1800)+l(1094)]||!1}}class Nl extends gr{constructor(r,o){let l=t;super(r),this[l(643)]=o&&o[l(643)]||null}}class Bl extends Nl{constructor(r,o){let l=t;super(r),this[l(643)]=o&&o[l(643)]||null,this.message=o&&o[l(659)]||null}}class Fl extends gr{constructor(r,o){let l=t;if(e[l(1137)](l(1930),e.JVgHh))super(r),this.data=o&&o[l(643)]||null;else return this._qosDB?.[l(647)](_0x410841)}}function wt(c,{message:r,code:o,error:l}){return new Ll(c,{message:r,code:o,error:l})}function kt(c,{code:r,reason:o,wasClean:l,willReconnect:f}){return new Ml(c,{code:r,reason:o,wasClean:l,willReconnect:f})}function zl(c,{data:r,message:o}){return new Bl(c,{data:r,message:o})}function Ul(c,{data:r}){let o=t;return o(734)===e.GqkIj?new Fl(c,{data:r}):this[o(1701)]?e.Scxsu(e[o(768)](this[o(680)],0)*_0x51ccd7,e[o(1268)](this[o(1060)],0)):e[o(1232)](e[o(1700)](this.high,_0x3d6ff0),e.CrRKX(this[o(1060)],0))}function Fa(c,{message:r}){return new Ol(c,{message:r})}class Hl{constructor(r,o){let l=t;this[l(1901)+"s"]=r,this[l(725)+"es"]=o,this[l(1768)+l(555)]=0,this["currentE"+l(841)+l(776)+"t"]=0}["resetEnd"+t(925)+t(1344)](){let r=t;if(e[r(503)](e[r(1256)],e[r(1192)]))this[r(1768)+r(555)]=0,this["currentE"+r(841)+"riesCount"]=0;else try{this[r(523)]?.close(),this._qosDB=void 0}catch(o){_0x35345a.log(o)}}[t(1563)+"es"](){let r=t;this[r(812)+r(841)+r(776)+"t"]=0}[t(1293)+"ntEndpoint"](){let r=t;return this[r(1901)+"s"][this[r(1768)+"ndex"]]}[t(1293)+t(811)+t(1143)+"ount"](){return this["currentEndpointT"+t(776)+"t"]}[t(1666)+t(605)+"es"](){let r=t;if(e.GoQWh===e[r(832)])return!!(this["currentI"+r(555)]>=this[r(1901)+"s"][r(1740)]||this["currentI"+r(555)]===this.endpoints[r(1740)]-1&&e.uTdmd(this["currentE"+r(841)+"riesCount"],this[r(725)+"es"]));{let{offset:o}=_0x3c2381(_0x58ce2f,_0x2e36b6);_0x19e270=o;let l={cursor_name:"",cursor:0,service:0},{value:f,offset:m}=_0x357d33(_0xf5c04a,_0x2a379e);l[r(1553)]=f,_0x360484=m;let{value:_,offset:S}=e[r(1329)](_0x2d0ce2,_0x4ae0a4,_0x9e3f8f);_0x3b71e2=S,l[r(1454)+r(1628)]=e.RMZJe(_0x5c12b1,_0x3cabae,_0x343831,_0x1b619f+_),_0x41ab55+=_;let{value:g,offset:R}=_0x1122a9(_0x68696a,_0x1ed7a0);l[r(904)]=g.toNumber(),_0x5016eb=R,_0x4000a5.push(l)}}[t(1251)+t(1574)+t(1619)+t(1042)+t(772)](){let r=t;return this[r(1768)+r(555)]==this[r(1901)+"s"].length?!0:this["currentE"+r(841)+r(776)+"t"]>this[r(725)+"es"]}[t(1424)+t(1451)+t(1224)+t(1507)+"unt"](){let r=t;return this[r(812)+r(841)+r(776)+"t"]=1,this[r(1768)+"ndex"]++,this[r(1901)+"s"][this[r(1768)+r(555)]]}["getCurre"+t(811)+t(672)+"ateCount"](){let r=t;return this[r(812)+r(841)+r(776)+"t"]++,this[r(1293)+r(811)+"nt"]()}}let mr=(e.eKxiy(e[t(611)],typeof globalThis)&&e.CShEi(e[t(1928)],globalThis[t(510)+t(1032)][t(906)])||t(1964)+"d"!=typeof window&&e[t(531)](e.ZEoIL,window[t(510)+t(1032)][t(906)]))&&e[t(1463)](e[t(611)],typeof document),Un=e.vnYMT(e[t(611)],typeof globalThis)&&(e[t(1654)](t(745),globalThis[t(510)+"tor"][t(906)])||e[t(1724)]===globalThis[t(510)+t(1032)][t(906)])&&e[t(611)]!=typeof tt,xi=(e[t(777)](e[t(611)],typeof globalThis)&&e.TLPHF(t(745),globalThis[t(510)+t(1032)][t(906)])||t(1964)+"d"==typeof globalThis||e[t(1406)](e[t(611)],typeof globalThis)&&!!globalThis[t(1655)+t(1899)])&&e[t(1523)](e[t(611)],typeof wx),pi=e[t(777)](t(1964)+"d",typeof globalThis)&&(e[t(1560)](e[t(1724)],globalThis[t(510)+"tor"][t(906)])||e.RGoCy(e.FFtjv,globalThis[t(510)+t(1032)].name)||e.uTdmd(e.YEOUi,globalThis.constructor[t(906)]))&&e[t(1523)](e.cGdpL,typeof self),jg=e[t(1851)](e[t(611)],typeof globalThis)&&e[t(635)](e[t(472)],globalThis[t(510)+t(1032)][t(906)])&&e[t(1374)](e[t(611)],typeof global)&&e[t(689)](e[t(472)],global[t(510)+t(1032)].name)&&e.KOpTk(e[t(611)],typeof process)&&!!process[t(804)];class za{constructor(){let r=t;this[r(1006)+"rs"]={}}emit(r,...o){let l=t,f=this._listeners[r];if(f)f[l(446)]()[l(1781)](m=>m.fn[l(692)](m[l(601)],o));else if(e[l(1492)]("error",r)&&!this[l(1003)])if(e[l(453)]!==e[l(453)]){if(ZwLAUW.RGoCy(_0x169162,ZwLAUW[l(673)]))return _0x1f8d57[l(492)](_0x5b60b5);if(ZwLAUW.TLPHF(_0x52d130,ZwLAUW.INEla))return _0xf66415[l(1033)+"oreNames"]||_0x4b0fc5.get(_0xbaf382);if(_0x3bfdae===ZwLAUW[l(508)])return _0x1bea4b["objectSt"+l(908)][1]?void 0:_0x4cbb73[l(1033)+l(690)](_0x2ba1ae["objectSt"+l(908)][0])}else{let m=o[l(1740)]&&o[0];if(e[l(1354)](m,Error))throw m;let _=new Error(e[l(700)](e[l(1676)],m?e.IGQNH(e[l(1142)](" (",m.message),")"):""));throw _[l(1626)]=m,m}return this}off(r,o){let l=t;if(e.XBCmK(void 0,r))this._listeners={};else if(o===void 0)this[l(1006)+"rs"][r]=null;else{let f=this[l(1006)+"rs"][r];if(f)for(let m=0;e[l(952)](m,f[l(1740)]);)e.WHBOQ(f[m].fn,o)?f[l(1938)](m,1):++m}return this}on(r,o,l){let f=t;return(this._listeners[r]||(this[f(1006)+"rs"][r]=[]))[f(998)]({fn:o,ctx:l||this}),this}}class Wg extends za{[t(755)+"rrorMess"+t(1953)](r){let o=t;return r.errMsg||r.errNo?(o(767)+" "+(r.errMsg||"")+" code: "+(r[o(1054)]||""))[o(1561)]():JSON[o(823)+"y"](r)}constructor(r,o,l){let f=t;super(),this._socket=null,xi&&wx["connectS"+f(1456)]&&(this[f(1145)]=wx[f(847)+f(1456)]({url:r,protocols:o,header:l,fail:this[f(1031)+f(1794)+f(1211)].bind(this),success:this[f(1031)+"ocketSuc"+f(1835)+"ler"][f(1014)](this)})),Un&&tt[f(847)+f(1456)]&&(this[f(1145)]=tt.connectSocket({url:r,protocols:o,header:l,fail:this[f(1031)+f(1794)+"lHandler"].bind(this),success:this[f(1031)+f(1348)+"cessHand"+f(787)][f(1014)](this)}))}[t(1031)+t(1348)+t(1835)+t(787)](){let r=t;if(e[r(494)](e.pGsrG,e[r(1216)]))Promise[r(747)]()[r(864)](()=>{let o=r;this[o(1465)+o(1896)]()});else return new _0x53d01f(_0x51af6c,{code:_0x3e1fcb,reason:_0xb04fa3,wasClean:_0x5860f2,willReconnect:_0x34a97c})}["_createS"+t(1794)+t(1211)](r){let o=t,l={SFXcw:function(f,m,_){return e[F(963)](f,m,_)},McNbI:e[o(677)],Jbbae:o(1029)};Promise.resolve()[o(864)](()=>{let f=o,m=l[f(1136)](wt,f(720),{message:this[f(755)+f(1962)+"age"](r)});this[f(507)](l.McNbI,m);let _=l[f(1136)](kt,l[f(1763)],{reason:this[f(755)+f(1962)+f(1953)](r)});this[f(507)](f(1029),_)})}[t(1465)+"steners"](){let r=t,o={WjvZw:e[r(1347)],cyPNj:r(659),SQJig:function(l,f,m){return e[r(1831)](l,f,m)},VPmVk:e[r(677)],fOLLQ:function(l,f,m){return e[r(1673)](l,f,m)}};this._socket[r(1223)](l=>{let f=r;this.emit(e.KukMM,e[f(1261)](Ul,e[f(1908)],{...l,data:l[f(1531)]||""}))}),this[r(1145)].onClose(l=>{let f=r;this[f(507)](f(1029),kt(o[f(1485)],{...l}))}),this._socket[r(1637)+"e"](l=>{let f=r;this[f(507)](o[f(1645)],o[f(867)](zl,o[f(1645)],{...l}))}),this._socket[r(1783)](l=>{let f=r;this.emit(o[f(1518)],o[f(1409)](wt,o[f(1518)],{...l,message:l[f(1531)]||""}))})}send(r){let o=t,l={JVdqT:e.hvrfV,jzNib:function(f,m,_){return e[F(1872)](f,m,_)}};if(e[o(1411)](r,Uint8Array)){let f=r.buffer[o(446)](r[o(1147)+"et"],e.RVJBa(r[o(1350)+"th"],r[o(1147)+"et"]));this[o(1145)]&&this._socket[o(709)]({data:f,fail:m=>{let _=o;this[_(507)](e[_(677)],e[_(750)](wt,e[_(677)],{message:this[_(755)+_(1962)+_(1953)](m)}))}})}else this[o(1145)]&&this[o(1145)][o(709)]({data:r,fail:f=>{let m=o;this[m(507)](l[m(1580)],l[m(1615)](wt,l[m(1580)],{message:this[m(755)+m(1962)+m(1953)](f)}))}})}close(r,o){let l=t;this[l(1145)]&&this[l(1145)][l(1029)]({code:r,reason:o})}[t(1766)+"Listener"](r,o){this.on(r,o)}[t(1213)+t(1200)+"ner"](r,o){this.off(r,o)}get[t(1483)+"te"](){let r=t,o={cERdJ:e.nPziQ,AJwXX:e[r(1745)]};if(e[r(503)](e[r(1328)],"BECdB"))return this._socket[r(1483)+"te"];this[r(1769)+r(1933)]?.[r(448)](),this.emit(o[r(756)],o.AJwXX),this["_pingLos"+r(1933)]?.[r(1666)+"chMaxCount"]()?this[r(1267)+r(1640)]():this[r(670)]()}get[t(542)+"pe"](){return this[t(1145)].binaryType}set[t(542)+"pe"](r){}get[t(602)](){let r=t;return this[r(1145)][r(602)]}get protocol(){let r=t;return this[r(1145)][r(1829)]}get extensions(){let r=t;return this[r(1145)][r(1198)+"ns"]}get[t(870)+"Amount"](){return 0}}function Kg(c,r){let o=t;if(o(1514)!==e[o(1603)]){if(r)return new r(c[o(602)],c.protocol);if(xi||Un)return new Wg(c[o(602)],c.protocol,c.headers);if((mr||pi)&&e[o(611)]!=typeof WebSocket&&WebSocket)return new WebSocket(c[o(602)],c[o(1829)+"s"])}else this["maxLossC"+o(554)]=_0x3daa79,this[o(1359)]=0}function $g(c){let r=t,o=e[r(588)][r(1559)]("|"),l=0;for(;;){switch(o[l++]){case"0":if(xi&&wx[r(847)+r(1456)])return!0;continue;case"1":if(Un&&tt["connectS"+r(1456)])return!0;continue;case"2":return!1;case"3":if((mr||pi)&&e[r(568)]("undefined",typeof WebSocket)&&WebSocket)return!0;continue;case"4":if(c)return!0;continue}break}}function Gl(c,r,o){let l=t,f={KYDiE:function(m,_){return e[F(479)](m,_)},inWdE:function(m,_){return e[F(1418)](m,_)},KTDBA:e.TetQt,tuncb:function(m,_){return e[F(1228)](m,_)},XwHhe:"next() c"+l(1577)+l(1420)+"imes in "+l(853),dfkYj:function(m,_){return e[l(471)](m,_)},KDXad:function(m,_){return e[l(464)](m,_)}};if(e[l(1885)](e[l(1331)],e[l(1111)])){let m=-1;async function _(S){let g=l,R={mFzOf:function(L,B){return f[F(1435)](L,B)}};if(f[g(1263)](f[g(1498)],f.KTDBA)){let L=new _0x4ee459(cUTEWo[g(1174)](2,_0x1a1c3b));L[g(624)](_0x4325aa),_0x26cc39[g(914)]=L}else return f.tuncb(S,m)?Promise.reject(new Error(f[g(1373)])):(m=S,f[g(922)](S,o[g(1740)])?Promise[g(747)]():o[S][g(1014)](c)(r,_.bind(null,f[g(1567)](S,1))))}e[l(1618)](_,0)}else return this["currentE"+l(841)+l(776)+"t"]=1,this["currentI"+l(555)]++,this[l(1901)+"s"][this[l(1768)+l(555)]]}function ql(c){let r=t,o=0,l=0;for(let f=0;e[r(547)](f,c[r(1740)]);++f)l=c[r(983)+"At"](f),e[r(1786)](l,128)?o+=1:l<2048?o+=2:e[r(1935)](64512,l)===55296&&e[r(1667)](64512&c[r(983)+"At"](e[r(1142)](f,1)),56320)?(++f,o+=4):o+=3;return o}function jl(c,r,o){let l=t,f={IzIob:function(_,S){return _|S}};if(e[l(1202)](e[l(1441)](o,r),1))return"";let m="";for(let _=r;e.nYiNz(_,o);)if(e.RkmUJ(e[l(1264)],"mhbJG")){let S=c[_++];if(e[l(695)](S,127))m+=String[l(1022)+l(1241)](S);else if(e.FzcOy(S,192)&&e[l(581)](S,224))m+=String[l(1022)+l(1241)](e.SKMkD(e[l(1914)](31,S)<<6,e[l(1024)](63,c[_++])));else if(e[l(1795)](S,224)&&e.qhbdc(S,240))m+=String[l(1022)+l(1241)](e[l(1234)](e[l(936)](e.fAKKr(15&S,12),e[l(1904)](e[l(1749)](63,c[_++]),6)),63&c[_++]));else if(e[l(961)](S,240)){let g=e[l(1441)](e[l(1148)](e[l(1544)](e[l(1066)](e[l(875)](7,S),18),e[l(468)](63,c[_++])<<12),e.gMWnZ(63,c[_++])<<6)|e[l(911)](63,c[_++]),65536);m+=String[l(1022)+"Code"](55296+e[l(644)](g,10)),m+=String[l(1022)+l(1241)](e[l(1428)](56320,1023&g))}}else this[l(1464)]=!0,this[l(1060)]=0|_0x131fc8,this[l(680)]=JWfAOo[l(441)](0,_0x41e5fa),this.unsigned=!!_0x325382;return m}function Ua(c,r,o){let l=t,f={BNhNX:function(m,_){return e[F(1760)](m,_)},vAdOj:function(m,_){return e[F(1737)](m,_)},Bssof:e[l(611)],uUXJu:function(m,_){return m||_},gjDhY:function(m,_){return m!=_},VdpUg:l(854)+l(1590)+"d"};if(l(724)!=="LNREu"){let m=o,_,S;for(let g=0;e[l(865)](g,c[l(1740)]);++g)if(e[l(970)](e[l(1594)],e[l(1594)]))if(_=c[l(983)+"At"](g),e[l(525)](_,128))r[o++]=_;else if(_<2048)r[o++]=e[l(893)](e.qbalW(_,6),192),r[o++]=e[l(600)](e[l(1664)](63,_),128);else if(e[l(1137)](e[l(891)](64512,_),55296)&&e.RGoCy(e.FRPcd(64512,S=c[l(983)+"At"](e[l(1273)](g,1))),56320)){let R=e[l(1237)][l(1559)]("|"),L=0;for(;;){switch(R[L++]){case"0":++g;continue;case"1":r[o++]=e.XjPzV(e[l(1385)](_>>6,63),128);continue;case"2":r[o++]=e[l(1743)](e[l(1750)](_,18),240);continue;case"3":_=e[l(1112)](65536+(e[l(1057)](1023,_)<<10),e[l(598)](1023,S));continue;case"4":r[o++]=e[l(1083)](e[l(1391)](e.XtiIt(_,12),63),128);continue;case"5":r[o++]=e[l(1584)](e[l(1842)](63,_),128);continue}break}}else r[o++]=e[l(1148)](e[l(1476)](_,12),224),r[o++]=e[l(1897)](e[l(1914)](e[l(438)](_,6),63),128),r[o++]=e[l(543)](e[l(1861)](63,_),128);else return _0x3059df[l(914)][_0x5b81ac(_0x107a1a,1)];return e.Bbqpr(o,m)}else{if(_0x26441c||_0x3bbd46)return new _0x20302a(_0x43f2b2,_0x326907);if(f.BNhNX(_0x5b5b42,_0x18d63f)&&f[l(1693)](f.Bssof,typeof _0x3ec888))return new _0x428378(_0x3591f8,_0x420db8);if(f[l(462)](_0xecd997,_0x1b0f8c)&&f[l(1276)](f[l(1752)],typeof _0x5cc3d9))return new _0x373687(_0x397389,_0x54446d);throw new _0x354e31(f[l(1634)])}}async function Wl(c){let r=t;if(e[r(1690)](r(1739),typeof c))if(e[r(1004)](e[r(1125)],e[r(1125)])){let o=new Uint8Array(e[r(1547)](ql,c));return e[r(1828)](Ua,c,o,0),o}else{let o=this._endpointManager?.["getCurre"+r(811)+"nt"](),l=this._options["reconnec"+r(1023)+r(1542)](_0x4fec39.code,_0x4b500e.reason);this[r(877)+r(1874)+"ent"](e[r(730)](_0x4cb59e,e[r(1347)],{code:1006,reason:_0xbd4002[r(1526)]||"connecting failed, unkno"+r(1501)+r(1515)+r(445)+o,willReconnect:l})),l&&this._connect();return}return c instanceof ArrayBuffer?new Uint8Array(c):new Uint8Array(c[r(1244)],c[r(1147)+"et"],c[r(1350)+"th"])}function Vg(c){let r=t;try{return r(1739)!=typeof c&&(e[r(1488)](c,ArrayBuffer)||c[r(1244)]&&e[r(1488)](c.buffer,ArrayBuffer))||e.Skkvp(e[r(1262)],typeof c)?"":(JSON[r(1686)](c),r(726)+"ion/json")}catch{if(e[r(859)](e.lpwVW,e.RUirE)){let o=_0x4d33cc[r(1270)];o!==void 0&&(e.ijQjJ(_0x2f0fbc,_0x18cdba,10),e[r(1877)](_0xcdca28,_0x420ac3,o));let l=_0x3ecab2[r(874)];e.afQGF(void 0,l)&&(e[r(1936)](_0x3c8975,_0xc7b3ab,18),e[r(456)](_0x3dbbe3,_0x446054,l))}else return e[r(1876)](r(1739),typeof c)?e[r(1848)]:""}}let Jg=(c,r)=>{let o=t;if(e[o(1755)](o(466),e.ikqeY))Pe[o(664)]&&Pe[o(664)].close(_0x5981ef,_0x32c5a6);else switch(c){case e[o(1133)]:case e.sVTlZ:return{["x-use-"+c]:1,"x-tt-env":r};default:return{}}};class Zg{constructor(r){let o=t;this.maxLossCount=r,this[o(1359)]=0}addCount(){this.count++}[t(1666)+t(1430)+"nt"](){let r=t;return e[r(1585)](this[r(1359)],this["maxLossC"+r(554)])}["resetCou"+t(869)](r=0){let o=t,l={qfWnB:function(f,m,_){return e[F(721)](f,m,_)}};e.PEMWi("BJrdr",o(806))?(this[o(671)+"ount"]=r,this.count=0):(lvVEWx[o(1226)](_0x474941,_0x4c2098,58),_0x5a925b(_0x722f33,_0x3f34ed))}}async function Yg(c){let r=t,o={XaInM:r(1307)+"3|0",rGtJR:e[r(1825)],cpbUw:r(984)+r(561)+"R",uEFrA:e[r(1167)],DmVUM:e[r(1413)],UoSsJ:e[r(1804)],SFvWE:function(l,f){return l(f)},QJKzM:function(l,f){return l!==f},ieiyV:e[r(1707)],zlCLs:function(l,f){return e[r(784)](l,f)},iuzun:e[r(1248)],rCcRw:e.DTcpa,QiTrU:r(972)+"ascript",prxwX:function(l,f){return e[r(985)](l,f)},ugXmE:e.oEhqx,hOawH:e[r(1648)],sWWqW:e[r(1782)],tlFkL:function(l,f){return e[r(1290)](l,f)}};return new Promise(l=>{let f=r,m={pRpvc:f(1132)+"reason",YUmQE:o[f(1363)],uSfIb:o.rGtJR,GvQbG:o[f(1663)],XLesk:o[f(746)],fNrSS:o.DmVUM,YIfxl:o[f(876)],GkhpV:function(_,S){return o[f(545)](_,S)},iviHr:function(_,S){return o[f(451)](_,S)}};if(f(1661)!==o[f(1280)]){if(!mr)return o[f(578)](l,o[f(1088)]);try{let _=document[f(1443)+f(1510)](o[f(728)]);window["frontier"+f(1496)]=S=>{let g=f;document[g(842)][g(552)+"ild"](_),window["frontier"+g(1496)]=void 0,l(S&&S[g(1341)]||m.pRpvc)},_[f(1450)]=o[f(935)],_[f(1300)]=o[f(1528)](c.replace(/^ws/,o[f(830)]),o[f(1944)]);try{document[f(842)][f(1140)+f(1709)](_)}catch{document[f(842)][f(552)+f(1709)](_)}}catch{if(o[f(678)]!==f(995)){let _=m[f(1123)].split("|"),S=0;for(;;){switch(_[S++]){case"0":return _0x13c2f8;case"1":_0x14e8f2[_0xedef24[PnLiyP[f(714)]]=5004]=f(1937)+f(693);continue;case"2":_0x43c0b3[_0x465abc[PnLiyP.GvQbG]=5003]=PnLiyP.GvQbG;continue;case"3":_0x40bb69[_0x2d1181[PnLiyP[f(1704)]]=5005]=PnLiyP[f(1704)];continue;case"4":_0x634c2c[_0x3a7622[PnLiyP.fNrSS]=5001]=PnLiyP[f(921)];continue;case"5":_0x38fa68[_0x32b3bc[PnLiyP.YIfxl]=5002]=f(953)+f(915);continue}break}}else window["frontier"+f(1496)]=void 0,o.tlFkL(l,"unknown reason")}}else{if(_0x2bbf81 instanceof _0x13181f)return PnLiyP.GkhpV(_0xe6f198,_0x3bfdb0);if(_0x2a2bcd[f(1836)](_0x534b95))return _0x40cffe[f(492)](_0x196bfb);let _=PnLiyP[f(1382)](_0x168309,_0x131bae);return PnLiyP[f(518)](_,_0x41f645)&&(_0x5cdd5e.set(_0x4a7870,_),_0xaa5b8d[f(624)](_,_0x8f867f)),_}})}function wn(c,r,o){let l=t;return!!c?.[l(1349)](f=>f[l(1270)]===r&&f[l(874)]===o)}function wr(c,r){let o=t;if(e[o(1595)](e[o(759)],o(773)))return c?.[o(1349)](l=>l[o(1270)]===r)?.[o(874)];{let l=this[o(523)].getItem(this._prefix);return _0x3d32ed[o(1686)](e[o(1760)](l,"{}"))[_0x10b8b4]}}let Ha=null;async function Xg(){let c=t,r={wMBXg:function(o,l){return e[F(1325)](o,l)},lLEbA:e[c(993)]};if(e[c(1286)]===e.JIrrE){let o=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[c(1589)](_0x24d184),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]))/[c(1589)](_0x5ac009);return o?TpTcdS[c(1852)](_0x278c2a,_0x416395):l?TpTcdS[c(1852)](_0xf89696,_0x5da8b3):TpTcdS[c(1968)]}else return Ha||(Ha=Promise[c(747)]()[c(864)](Jt[c(1014)](Jt,e[c(1776)]))),Ha}class Qg extends za{constructor(r,o){let l=t;super(),this[l(1278)]=r,this._keyPath=o,this[l(523)]=void 0,this[l(1864)+l(1612)]=null}async[t(1109)](){let r=t;e[r(743)]!=="EzoKZ"?await this[r(978)]():(e[r(1294)](_0x4fe184,_0x5175c0,96),_0x2a67d8(_0x3a9eb4,e[r(1810)](_0x5813aa,_0x1098a5)))}async[t(978)](){let r=t;if(!this[r(523)]){if(this[r(1864)+r(1612)])return this[r(1864)+"mise"];try{let o=this._dbName,l=this[r(790)];this[r(1864)+r(1612)]=(async()=>{let f=r,{openDB:m}=await Xg();this[f(523)]=await e[f(1214)](m,f(1404)+"_"+o,1,{upgrade(_){let S=f;_[S(1105)+S(1680)+"e"](o,{keyPath:l})}})})(),await this[r(1864)+r(1612)]}catch(o){if(e[r(1832)](e[r(1785)],r(634))){let{pingInterval:l,pingFrequency:f}=this._options;if((_0x244520.data==="hi"&&r(615)===f||e[r(535)]===f)&&(this[r(1870)+r(1642)](),this.emit(e[r(1170)],e[r(817)]),this[r(1279)+r(640)+"Id"]=e[r(526)](_0x745a90,this._ping[r(1014)](this),l)),e.bfPWz("hi",_0x2f366a[r(643)]))return;try{_0x332cf5(this,_0x88fe96,[_0x2ef484,_0x1d0aa0,_0x23a8ed,_0x6a4f1b,_0x10fc6c,_0x42e3f4])}catch(m){let _=e.rGLPQ(_0x5821a8,e[r(677)],{message:m[r(659)],code:_0x44527c["MESSAGE_"+r(693)],error:m});this["_dispatchErrorEv"+r(1388)](_)}}else console[r(553)](o)}finally{this[r(1864)+r(1612)]=null}}}async[t(492)](r){let o=t;try{return await this._init(),this[o(523)]?.[o(492)](this[o(1278)],r)}catch(l){console[o(553)](l)}}async[t(624)](r,o){let l=t;return await this[l(978)](),this[l(523)]?.[l(965)](this[l(1278)],r)}async[t(647)](r){let o=t;try{return await this[o(978)](),this._qosDB?.delete(this[o(1278)],r)}catch(l){console[o(553)](l)}}async[t(1343)](){let r=t;try{return await this[r(978)](),this._qosDB?.clear(this._dbName)}catch(o){if(e[r(1030)](e.ftGOr,e[r(883)]))console.log(o);else{let l=_0x3757d8[r(1740)]&&_0x73bce9[0];if(e[r(1411)](l,_0x53727d))throw l;let f=new _0x2de331(e[r(1927)](e.HSUuS,l?e[r(628)](" (",l[r(659)])+")":""));throw f.context=l,l}}}async keys(){let r=t;return await this[r(978)](),this[r(523)]?.getAllKeys(this._dbName)}async[t(976)](){let r=t;return await this._init(),this[r(523)]?.[r(976)](this[r(1278)])}async[t(1613)](){let r=t;try{if(e[r(763)](r(712),e[r(1802)]))this[r(523)]?.[r(1029)](),this[r(523)]=void 0;else return this._socket[r(602)]}catch(o){console[r(553)](o)}}get[t(1371)](){let r=t,o={XjWPd:function(l,f){return e[F(1429)](l,f)},zqicw:function(l,f){return e[F(1786)](l,f)},lrxiV:function(l,f){return e[F(464)](l,f)},moAzd:function(l,f){return e[F(1441)](l,f)},sqGPp:function(l,f){return e.IGQNH(l,f)},VvbTd:function(l,f){return e[F(1757)](l,f)},fuEvB:function(l,f){return e[F(1484)](l,f)},GnTaY:function(l,f){return e[F(447)](l,f)},VeURC:function(l,f){return e[F(1750)](l,f)},Tfmwx:function(l,f){return e[F(1508)](l,f)},jWlYi:function(l,f){return e[F(765)](l,f)},zsLFE:function(l,f){return e[F(1007)](l,f)},hBhlS:function(l,f){return l>>f},dMNjh:function(l,f){return e.AQbTl(l,f)}};try{return!!this[r(523)]}catch(l){if(e[r(1481)]!==e.KkeBd){let f=_0x255b7c[r(983)+"At"](_0x65c28d);f>=55296&&KvsgLO.XjWPd(f,56319)&&KvsgLO[r(916)](KvsgLO[r(444)](_0x4522ac,1),_0x257c2f)&&(f=KvsgLO.moAzd(KvsgLO[r(950)](KvsgLO[r(1070)](f,10),_0xc85abe.charCodeAt(++_0x188764)),56613888)),KvsgLO[r(916)](f,128)?_0x2f1987[_0x4e61a5++]=f:(KvsgLO[r(916)](f,2048)?_0x28502a[_0x3690f0++]=KvsgLO[r(1712)](f>>6&31,192):(KvsgLO[r(1591)](f,65536)?_0x86b716[_0x4933a3++]=KvsgLO[r(556)](f,12)&15|224:(_0x3a9011[_0x593595++]=KvsgLO.fuEvB(KvsgLO[r(1047)](KvsgLO[r(556)](f,18),7),240),_0x98fbd4[_0x4a0d8b++]=KvsgLO[r(1712)](KvsgLO.jWlYi(KvsgLO[r(556)](f,12),63),128)),_0x50682e[_0xee42d5++]=KvsgLO[r(1403)](KvsgLO[r(1047)](KvsgLO[r(1570)](f,6),63),128)),_0x14385b[_0x9d1d22++]=KvsgLO[r(716)](KvsgLO[r(1037)](63,f),128))}else return console.log(l),!1}}}class em{constructor(r,o){let l=t;this[l(1220)]=r,this[l(1195)]=o,this[l(523)]=localStorage}async openDB(){}get _prefix(){return t(1404)+"_"+this._DBName}async get(r){let o=t,l=this._qosDB[o(1480)](this._prefix);return JSON.parse(e.wXLKt(l,"{}"))[r]}async[t(624)](r,o){let l=t,f=this[l(523)][l(1480)](this[l(713)]),m=JSON[l(1686)](e[l(1051)](f,"{}"));return m[o||r[this[l(1195)]]]=r,this[l(523)].setItem(this[l(713)],JSON.stringify(m)),o||r[this[l(1195)]]}async del(r){let o=t,l={oVlTr:function(f,m){return e[F(1165)](f,m)},aBlqW:"text/plain;chars"+o(1122)};if(e.jJlIE===e.Wdwlm)return NsiLvp[o(645)](o(1739),typeof _0x2a1697)?NsiLvp[o(831)]:"";{let f=this._qosDB[o(1480)](this[o(713)]),m=JSON[o(1686)](e[o(1925)](f,"{}"));return m[r]=void 0,this._qosDB.setItem(this[o(713)],JSON[o(823)+"y"](m))}}async[t(1343)](){let r=t;return this[r(523)][r(1343)]()}async[t(1069)](){let r=t;if(e[r(1779)](e.lhlSc,e[r(1692)]))throw this["_connect"+r(642)]=!1,_0x56cbd8;{let o=this[r(523)][r(1480)](this[r(713)]),l=JSON[r(1686)](e[r(793)](o,"{}"));return Object[r(1069)](l)}}async[t(976)](){let r=t,o=this._qosDB[r(1480)](this._prefix),l=JSON[r(1686)](e[r(1651)](o,"{}"));return Object[r(706)](l)}[t(1613)](){return Promise.resolve()}get isReady(){let r=t,o={dWGmF:function(l,f,m){return e[F(1780)](l,f,m)}};if(e[r(1299)]("rHHIz",r(1809)))return!!this[r(523)];{let l=RabtMg.dWGmF(_0x1af54e,_0x233619,_0xbc465c.length);_0x1f3b3e[r(914)][r(624)](_0x3d9748,l)}}}class tm{constructor(r,o){let l=t;this[l(1220)]=r,this[l(1195)]=o,this[l(523)]=Un?tt:xi?wx:null}async[t(1109)](){}get _prefix(){return"frontier_"+this[t(1220)]}async get(r){let o=t,l=this._qosDB[o(1838)+o(1238)](this[o(713)]);return JSON[o(1686)](e[o(1651)](l,"{}"))[r]}async set(r,o){let l=t,f=this[l(523)][l(1838)+l(1238)](this[l(713)]),m=JSON[l(1686)](e[l(1314)](f,"{}"));return m[o||r[this._pathKey]]=r,this[l(523)][l(1414)+l(1238)](this[l(713)],JSON[l(823)+"y"](m)),o||r[this[l(1195)]]}async del(r){let o=t,l=this[o(523)][o(1838)+"geSync"](this[o(713)]),f=JSON[o(1686)](l||"{}");return f[r]=void 0,this[o(523)][o(1414)+"geSync"](this[o(713)],JSON[o(823)+"y"](f))}async[t(1343)](){let r=t;return this[r(523)][r(1730)+r(509)]()}async[t(1069)](){let r=t;if(e[r(1166)](e[r(1818)],e[r(1398)]))this[r(807)+"ype"]=_0x49012e,this._ws&&(this[r(664)][r(542)+"pe"]=_0x2e7d03);else{let o=this[r(523)][r(1838)+r(860)+"nc"](this[r(713)]),l=JSON.parse(e[r(1966)](o,"{}"));return Object.keys(l)}}async[t(976)](){let r=t,o=this[r(523)][r(1838)+r(860)+"nc"](this[r(713)]),l=JSON[r(1686)](e[r(1046)](o,"{}"));return Object[r(706)](l)}[t(1613)](){return Promise.resolve()}get[t(1371)](){return!!this[t(523)]}}function Kl(c,r){let o=t;if(e[o(661)](Un,Un))return new tm(c,r);if(e[o(661)](mr,pi)&&e[o(1419)](e[o(611)],typeof indexedDB))return new Qg(c,r);if(e[o(1046)](mr,pi)&&e[o(1737)](e[o(611)],typeof localStorage))return new em(c,r);throw new Error(e[o(1718)])}class nm{constructor(){let r=t;this["_interva"+r(1575)+"Id"]=null,this._interval=36e5,this._qosDB=Kl(e[r(760)],r(470)+"id")}async["_interva"+t(1725)](){let r=t;if(e[r(1137)](r(748),e[r(1516)]))for(var o in _0x4068a4)_0x2f924b.o(_0x4a72ae,o)&&!_0x7575cc.o(_0x35b190,o)&&_0x392a6f[r(939)+r(1384)](_0x392ec0,o,{enumerable:!0,get:_0x13103f[o]});else e.ZBqbW(clearInterval,this["_interva"+r(1575)+"Id"]),this[r(1440)+r(1575)+"Id"]=e[r(1936)](setInterval,()=>{let l=r;this[l(986)+l(1436)]()},this._interval)}async[t(1109)](){let r=t;await this._qosDB[r(1109)]()[r(864)](()=>{this._intervalFlush()})}async[t(986)+t(1436)](){let r=t;(await this[r(523)]?.[r(976)]()||[]).filter(({timestamp:f})=>f<Date[r(1313)]())[r(1781)](f=>{let m=r;this[m(523)]?.[m(647)](f[m(470)+"id"])})}async[t(647)](r){let o=t,l={zvznr:function(f,m,_){return f(m,_)},kwERB:function(f,m){return e[F(1941)](f,m)}};if(e[o(1777)](e[o(1246)],e.arTpm))_0x1ae222(_0x280309,32),IWqDyV[o(1593)](_0x4a65fe,_0x1f6249,IWqDyV[o(1806)](_0x1bf951,_0x441bd5));else return this._qosDB?.[o(647)](r)}async[t(624)](r,o){let l=t;return e.ERywT(e[l(1652)],e[l(1784)])?_0x1706e1?this.toBytesLE():this[l(1433)+"E"]():this._qosDB?.set({message_id:r,timestamp:o})}async get(r){let o=t;return this[o(523)]?.[o(492)](r)}async[t(1613)](){let r=t;e[r(1092)](clearInterval,this[r(1440)+r(1575)+"Id"]),await this._qosDB?.[r(1613)]()}get isReady(){if(e[t(1814)]!=="GceMe")this.on(_0x655196,_0x2c8d91);else return this._qosDB?.isReady}}function Ga(c){let r=t,o={yJAOc:function(l,f){return e[F(1737)](l,f)},oKIWp:e[r(1242)]};if(e[r(494)](r(943),e[r(1636)]))_0x2e7ff8.r=l=>{let f=r;RMufAn[f(1736)]("undefined",typeof _0x560d26)&&_0x3a8949["toString"+f(1950)]&&_0x27c0eb.defineProperty(l,_0x5bd382["toString"+f(1950)],{value:RMufAn.oKIWp}),_0x4d2a02[f(939)+f(1384)](l,f(803)+"le",{value:!0})};else{let l=!!this[r(735)][r(1055)+"S"];if(!l)return{enabled:l,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let f=e[r(1214)](wn,c[r(659)][r(558)],e[r(1287)],"2"),m=f&&e[r(1214)](wn,c[r(659)][r(558)],r(1703)+r(1798)+"ck","1"),_=f&&e.hWZGw(wn,c[r(659)].headers,e[r(731)],"1"),S=_?wr(c[r(659)][r(558)],r(1703)+"er_ack_msgid")?.[r(1559)](",")[r(1884)](Boolean)||[]:[];return{enabled:l,isQoSMessage:f,isQoSAck:m,isAckCleanupMessage:_,ackMsgIds:S}}}async function $l(){let c=t;return this["_QoSMana"+c(1240)]||(this[c(1408)+c(1240)]=new nm),this[c(1408)+"ger"][c(1371)]||await this[c(1408)+c(1240)][c(1109)](),this[c(1408)+c(1240)]}async function rm(c,r){let o=t,{enableAutoAck:l}=this[o(735)],f=e[o(1214)](wn,c.message[o(558)],e[o(1065)],"1"),m=e.gVsBI(wn,c[o(659)][o(558)],e[o(469)],"1"),_=Ga[o(1399)](this,c);if(l&&f){let{SeqID:S,LogID:g,service:R,LogIDNew:L,method:B}=c[o(659)];this[o(437)]({SeqID:S,LogID:g,LogIDNew:L,service:R,method:B,headers:[{key:e[o(469)],value:"1"},{key:o(1040),value:e[o(1e3)](L,"")},{key:e[o(862)],value:"0"}]})}m&&!_[o(1610)]&&this[o(877)+o(574)+o(493)](c),r()}async function im(c,r){let o=t;this[o(549)](o(1758),c[o(659)]),e[o(1706)](r)}async function sm(c,r){let o=t,l={GqjKx:function(m,_,S){return m(_,S)},oSQYP:o(1029)},f=e[o(1618)](Nt,await e[o(982)](Wl,c.data));try{if(e.bKCYP(f[o(956)],Uint8Array))if(e.URhka("qtxBq","gZKIW")){let m=this[o(735)]["reconnec"+o(1023)+o(1542)](_0x41cbfc,_0x45c249);this[o(877)+o(1874)+o(1388)](l[o(1846)](_0x5cca21,l.oSQYP,{code:_0x280c0e,reason:_0xc221c4,wasClean:!0,willReconnect:m})),m&&this[o(1685)]()}else{let m=e[o(1317)](this[o(735)][o(1269)+o(1212)],Object)?{force:!!this[o(735)][o(1269)+o(1212)][o(1812)],encoding:this[o(735)][o(1269)+o(1212)].encoding?this[o(735)][o(1269)+o(1212)][o(1025)][o(1747)](/\s/g,"")[o(1572)+o(902)]():""}:{force:!1,encoding:this[o(735)][o(1269)+"ncoding"]?this[o(735)]["payloadE"+o(1212)][o(1747)](/\s/g,"")[o(1572)+"ase"]():""},_=f[o(1269)+"ncoding"]?f[o(1269)+"ncoding"][o(1747)](/\s/g,"")[o(1572)+o(902)]():"",S=e.pGrZp(this[o(735)][o(1205)+o(1947)],Object)?{force:!!this._options["payloadT"+o(1947)][o(1812)],type:this[o(735)][o(1205)+o(1947)].type?this[o(735)][o(1205)+o(1947)][o(1450)][o(1747)](/\s/g,"")["toLowerC"+o(902)]():""}:{force:!1,type:this[o(735)][o(1205)+"ype"]?this[o(735)][o(1205)+"ype"][o(1747)](/\s/g,"")["toLowerC"+o(902)]():""},g=f[o(1205)+o(1947)]?f[o(1205)+o(1947)][o(1747)](/\s/g,"")[o(1572)+o(902)]():"",R=S[o(1812)]?S[o(1450)]:g||S[o(1450)],L=m[o(1812)]?m.encoding:_||m[o(1025)],B=[e[o(1848)],e[o(1849)],e[o(563)],o(1739)],J=[o(625)+"e",e[o(699)]];this[o(735)][o(885)+o(496)+o(929)+"ad"]&&B[o(1499)](R)&&(!L||J[o(1499)](L))?f["textPayl"+o(1304)]=e[o(491)](jl,f.payload,0,f[o(956)][o(1350)+"th"]):f[o(483)+o(1304)]=""}else f["textPayl"+o(1304)]=""}catch(m){f[o(483)+"oad"]="",console[o(553)](m)}c.message=f,r()}function om(c,r,o){let l=t,f={BDyqV:function(m,_){return e[F(525)](m,_)},JeEnS:function(m,_){return e.UfrIi(m,_)},QMRgb:function(m,_){return e[F(1325)](m,_)},eZwri:function(m,_){return e.kDPjw(m,_)},ZuprA:function(m,_){return e[F(599)](m,_)},uSoGo:function(m,_){return e[F(1378)](m,_)},FSANQ:function(m,_,S,g){return m(_,S,g)},zxsKn:function(m,_){return e[F(1512)](m,_)},rooRP:e.VVaoP,FoNyU:function(m,_){return e[F(595)](m,_)},gwAMQ:l(892),emwTp:function(m){return e[l(1706)](m)}};if(e[l(666)](e.DNLta,e.PtjPr)){let m=e[l(495)](o,8192),_=m>>>1,S=null,g=m;return function(R){let L=l;if(f[L(1826)](R,1)||R>_)return f[L(1230)](c,R);g+R>m&&(S=f.QMRgb(c,m),g=0);let B=r[L(1399)](S,g,g+=R);return f.eZwri(7,g)&&(g=f[L(1665)](f.uSoGo(7,g),1)),B}}else{let{enableAutoAck:m}=this[l(735)],_=TiOeoS.FSANQ(_0x15533c,_0x5a8e79[l(659)][l(558)],l(969),"1"),S=TiOeoS[l(1381)](_0x47910b,_0x2fa748[l(659)][l(558)],l(1943),"1"),g=_0x172557[l(1399)](this,_0xaf0145);if(TiOeoS[l(685)](m,_)){let{SeqID:R,LogID:L,service:B,LogIDNew:J,method:$}=_0xa7d01e[l(659)];this[l(437)]({SeqID:R,LogID:L,LogIDNew:J,service:B,method:$,headers:[{key:TiOeoS.rooRP,value:"1"},{key:l(1040),value:TiOeoS.FoNyU(J,"")},{key:TiOeoS[l(1315)],value:"0"}]})}S&&!g[l(1610)]&&this["_dispatc"+l(574)+"ageEvent"](_0x4ffc60),TiOeoS[l(1056)](_0x399330)}}let am=4294967295;function cm(c,r,o){let l=t;return e[l(626)](RangeError,e[l(1710)](e.SKKsH(e[l(1232)](e.SbDCv+c,e[l(1765)]),e[l(1285)](r,1))+e.mwCRj,o))}function dm(c,r,o){let l=t;if(o>am)throw new Error(e[l(749)]);let f=3;for(;e[l(481)](f,0);){let m=e.kgarz(255,o);e[l(668)](ja,m,c,r+f),o>>>=8,f--}return e[l(1716)](r,4)}function lm(c,r){let o=t,l=0,f=r,m=e[o(1487)](r,4);for(;f<m;){let{value:_,offset:S}=e[o(909)](qa,c,f);f=S,l=e[o(1146)](l,8)>>>0,l+=_}return{value:l,offset:m}}function um(c,r,o){let l=t,f=e[l(752)][l(1559)]("|"),m=0;for(;;){switch(f[m++]){case"0":if(e[l(865)](c[l(1740)],40))return e[l(1112)](e[l(551)](Ua,c,r,o),o);continue;case"1":return e.dpsYF(e[l(1459)](Ua,c,r,o),o);case"2":if(r.write)return e.wrAJe(r.write(c,o),o);continue;case"3":if(r.utf8Write)return e[l(1495)](r[l(846)+"e"](c,o),o);continue;case"4":if(!c)return o;continue}break}}function fm(c,r){let o=t,l=new ce(e.GYwcx(e.pREDS(e[o(1182)](c[r+4],24),c[r+5]<<16)|e.fAKKr(c[e[o(1131)](r,6)],8),c[r+7]),e.wdvVg(e[o(1083)](e[o(1484)](c[e[o(1210)](r,0)]<<24,c[e.AYfIM(r,1)]<<16),c[e[o(1282)](r,2)]<<8),c[e[o(1631)](r,3)]),!0);return r+=8,{value:l,offset:r+8}}function hm(c,r,o){let l=t,f={pserm:function(m,_,S){return e.LsPHo(m,_,S)},IUYUM:e.QUHmb};if(e[l(1667)](e.BrHkH,l(1646))){let m=c.low,_=c.high;return r[o]=_>>>24,r[e[l(1472)](o,1)]=e.rdcQS(e[l(1675)](_,16),255),r[o+2]=e.hhjTS(e[l(530)](_,8),255),r[e[l(947)](o,3)]=e[l(1391)](255,_),r[e.rRjia(o,4)]=e[l(589)](m,24),r[o+5]=m>>>16&255,r[e[l(1100)](o,6)]=e[l(1858)](e.TSxKW(m,8),255),r[e[l(1110)](o,7)]=e[l(923)](255,m),o+=8,o}else{let m=this[l(1425)+l(1038)]?.[l(1293)+"ntEndpoint"]();this["_dispatchCloseEv"+l(1388)](f.pserm(_0x592f5f,f.IUYUM,{code:_0x575457[l(1879)],reason:l(1863)+l(476)+"d, unknown reaso"+l(1515)+l(445)+m})),this[l(1425)+"tManager"]?.[l(1050)+l(925)+"fig"](),this[l(1769)+l(1933)]?.[l(1358)+l(869)]();return}}function qa(c,r){let o=t;return c[o(837)+"8"]?{value:c[o(837)+"8"](r),offset:r+1}:{value:e[o(705)](255,c[r]),offset:e[o(1100)](r,1)}}function ja(c,r,o){let l=t;return r[l(636)+"t8"]?r[l(636)+"t8"](c,o):r[o]=e.XYyKO(255,c),e[l(482)](o,1)}let xm=function(c){return new Uint8Array(c)},pm=e[t(1374)](e[t(611)],typeof Buffer)?Buffer["allocUns"+t(1816)]:e.iJXNX(om,xm,Uint8Array[t(946)+"e"][t(1873)]);(()=>{let c=t,r={YMfkc:function(l,f){return e[F(1810)](l,f)},vxHQv:function(l,f){return e.DCHtK(l,f)},fsrxl:function(l,f){return e[F(719)](l,f)},OjTJX:function(l,f){return e[F(1061)](l,f)},gpJvX:function(l,f){return l>>>f},WJzdu:function(l,f){return e[F(674)](l,f)},DCAzG:function(l,f){return e.aaFKV(l,f)},mnDeI:function(l,f){return e[F(1202)](l,f)},VcfeC:function(l,f){return e[F(722)](l,f)},HKzTI:function(l,f){return e[F(814)](l,f)},YIixC:function(l,f){return e[F(1475)](l,f)},ILvnz:e[c(633)],xjWwA:function(l,f,m,_){return e[c(1077)](l,f,m,_)}},o=4294967295;return function(l,f,m=!0){let _=c,S={LCMLS:function(g,R){return r.YMfkc(g,R)},XEHHX:function(g,R){return g&R},nrmQp:function(g,R){return r[F(1134)](g,R)},uDScz:function(g,R){return g<<R},zMuRt:function(g,R){return r[F(1907)](g,R)}};if(o=(127&l[f])>>>0,r[_(1417)](l[f++],128))return{value:m?o:r[_(932)](0,o),offset:f};if(o=r[_(1080)](r.WJzdu(o,r[_(1439)](127&l[f],7)),0),l[f++]<128)return{value:m?o:r[_(1082)](0,o),offset:f};if(o=r[_(1080)](o|r[_(1439)](r.vxHQv(127,l[f]),14),0),r.mnDeI(l[f++],128))return{value:m?o:r.WJzdu(0,o),offset:f};if(o=r[_(1080)](r[_(932)](o,r[_(1400)](127,l[f])<<21),0),r[_(1649)](l[f++],128))return{value:m?o:0|o,offset:f};if(o=r.gpJvX(o|r[_(1439)](15&l[f],28),0),r[_(896)](l[f++],128))return{value:m?o:r[_(1082)](0,o),offset:f};if((f+=5)>l[_(1740)]){if(r.YIixC(_(849),r[_(1152)]))throw f=l[_(1740)],r[_(754)](cm,f,10,l.length);_0x331754=IcBBgS[_(1744)](_0x5b4ceb,_0x498237),_0x3fc4a1=127&_0x3bb459,IcBBgS[_(704)](128,_0x55c258)&&(_0x1716ca=IcBBgS.nrmQp(_0x2fab63,_0x47b83b),_0x37f85d|=IcBBgS.uDScz(IcBBgS[_(1196)](127,_0x475464),7))}return{value:m?o:r[_(932)](0,o),offset:f}}})();let gm=16,Wa=32;function mm(c){let r=t,o={eJMOa:function(m,_){return e[F(1495)](m,_)},sGiSf:function(m,_){return e.mjXFb(m,_)},TBwuZ:function(m,_){return m&_},wWcXP:function(m,_){return e[F(992)](m,_)},TEOwr:function(m,_){return e[F(1883)](m,_)},hfXKn:function(m,_){return m&_},uGuYy:function(m,_){return e[F(1383)](m,_)}},l=0,f={};for(let m=0;e[r(826)](m,c[r(1740)]);m++)e[r(1918)]!==e.UahXx?(f[c[m][r(1454)+r(1628)]]=e.YgoZl(ql,c[m][r(1454)+r(1628)]),l+=e[r(1235)](14,f[c[m][r(1454)+r(1628)]])):(_0x568cab=_0x2e1ae7[XJfJeG[r(1118)](_0x398b77,_0x4fc144)+1],XJfJeG[r(1362)](XJfJeG[r(1688)](192,_0x492223),128)?_0x4da075+=_0x4c3493:(_0xf86343=XJfJeG[r(646)](XJfJeG[r(1039)](XJfJeG[r(1688)](31,_0xeb335e),6),XJfJeG[r(616)](63,_0x53c6e9)),XJfJeG[r(1155)](_0x3fca87,128)?_0x3d9045+=_0x5c3327:(_0x53344e+=_0x4f8286(_0x1ececc),_0xa85f41++)));return[l,f]}function Vl(c,r,o){let l=t;if(e[l(850)](e[l(1215)],e[l(1215)]))return _0x57d6f4?.[l(1349)](f=>f[l(1270)]===_0x25737c)?.[l(874)];{let[f,m]=mm(c),_=pm(f),S=0;return c[l(1781)](g=>{let R=l,L=("7|9|10|3"+R(1684)+R(1894))[R(1559)]("|"),B=0;for(;;){switch(L[B++]){case"0":console[R(553)](R(906),S);continue;case"1":S=e.IVNZW(hm,ce[R(1797)+"er"](g[R(904)]||r),_,S);continue;case"2":console.log(e[R(681)],S);continue;case"3":S=e[R(1312)](dm,_,S,g[R(1553)]||0);continue;case"4":S=e[R(1085)](um,g[R(1454)+R(1628)],_,S);continue;case"5":console.log(e[R(1194)],S);continue;case"6":S=e[R(1113)](ja,m[g[R(1454)+R(1628)]],_,S);continue;case"7":console[R(553)](e[R(697)],g,g.service);continue;case"8":console[R(553)](e[R(1697)],S);continue;case"9":S=e[R(1172)](ja,0,_,S);continue;case"10":console.log(e[R(1245)],S);continue}break}}),{frameType:Wa,headers:[{key:l(887)+l(516),value:o}],payload:_}}}function wm(c){let r=t,o=0,l=[];for(;e[r(814)](o,c.byteLength);){let{offset:f}=e[r(960)](qa,c,o);o=f;let m={cursor_name:"",cursor:0,service:0},{value:_,offset:S}=e[r(1872)](lm,c,o);m[r(1553)]=_,o=S;let{value:g,offset:R}=qa(c,o);o=R,m["cursor_n"+r(1628)]=jl(c,o,o+g),o+=g;let{value:L,offset:B}=e.rtvrP(fm,c,o);m[r(904)]=L.toNumber(),o=B,l[r(998)](m)}return l}function _m(){let c=t;if(e[c(1137)](c(1621),e[c(1158)]))return{frameType:Wa,headers:[{key:c(887)+"ile_name",value:e.yWzLq}],payload:void 0};this._qosDB?.[c(647)](_0x12e0e7[c(470)+"id"])}class ym{constructor(r,o,l){let f=t;this[f(1071)+f(774)]=r,this[f(513)+f(1203)]=o,this[f(1412)+f(1124)]=l,this[f(523)]=e[f(1217)](Kl,this[f(1071)+f(774)],e[f(1762)])}async openDB(){let r=t;await this[r(523)][r(1109)]()}async[t(537)+"rs"](){let r=t;if(!this[r(523)].isReady)return;let o=this[r(1412)+r(1124)],l=await this._qosDB.getAll();switch(console[r(553)](e[r(1009)],l),o){case e[r(990)]:return l&&l[r(1740)]?e[r(1085)](Vl,l,0,this[r(513)+r(1203)]):void 0;case e[r(1457)]:return;case e[r(1787)]:return l&&l[r(1740)]?e[r(1312)](Vl,l,0,this[r(513)+r(1203)]):e[r(1948)](_m)}}async[t(624)](r,o,l){let f=t;return console[f(553)](e.EIKck,r,o,l),this[f(523)].set({cursor_name:r,cursor:o,service:l})}async setCursors(r){let o=t,l={lupln:e[o(901)]};if(e[o(1222)](e.kDWBo,"jDKkQ")){let f=e.dSCRB(wm,r);for(let m of f)console[o(553)](e[o(1582)],f),await this[o(523)].set(m)}else{let f=this[o(1425)+o(1038)]?.[o(1293)+"ntEndpoint"]();this[o(549)](o(1705)+f+o(583)),this["_disconn"+o(917)](1001,l[o(884)],!0)}}async[t(492)](r){let o=t;return(await this[o(523)][o(492)](r))?.[o(904)]}async[t(1613)](){let r=t;await this[r(523)][r(1613)]()}[t(1504)+t(979)+t(1527)](r){let o=t;if(e[o(1272)](e[o(565)],e[o(565)]))this[o(513)+"ileName"]=r;else return this[o(1145)][o(542)+"pe"]}get[t(1371)](){return this[t(523)].isReady}}let bm=e[t(1694)];async function Jl(c){let r=t,o={eILbA:function(S,g){return e.WUJeK(S,g)},RMjSz:function(S,g){return S===g},TSgHK:function(S,g){return e.GflEc(S,g)}};if(!this._options.enableQoS)return null;let{aID:l,fpID:f,messageStrategy:m}=this[r(735)],_=e[r(797)](c,bm);try{if(this[r(539)+r(1500)]){if(e[r(1654)]("PmgQv",e[r(594)]))return!!(SkYfQS[r(1361)](this[r(1768)+r(555)],this[r(1901)+"s"][r(1740)])||SkYfQS.RMjSz(this["currentI"+r(555)],this[r(1901)+"s"].length-1)&&SkYfQS[r(1396)](this[r(812)+r(841)+r(776)+"t"],this.maxRetries));c&&this[r(539)+"anager"][r(1504)+"rsorFile"+r(1527)](c)}else this["_cursorM"+r(1500)]=new ym(f+"_"+l+"_"+_,_,m);return this["_cursorM"+r(1500)][r(1371)]||await this[r(539)+r(1500)][r(1109)](),this[r(539)+r(1500)]}catch{return null}}async function vm(c,r){let o=t,l={byVFn:e[o(942)],UzXUB:e[o(677)],ZYAiR:function(f,m){return e[o(1714)](f,m)},XgBqd:e.eQfur,DDlNC:function(f){return e[o(1811)](f)},XeyeL:function(f){return e[o(1555)](f)},mSIuO:e[o(1206)]};if(e[o(834)]===e.njEmV){let f={ARAHN:function(g){let R=o;return eMcPAp[R(1432)](g)}},m=()=>{let g=o;_0x45203d["removeEv"+g(1200)+g(698)](eMcPAp.byVFn,_),_0x1dc3aa[g(1213)+g(1200)+g(698)](eMcPAp.UzXUB,S),_0x540f8a[g(1213)+g(1200)+g(698)](g(1407),S)},_=()=>{f[o(1922)](_0x212d31),m()},S=()=>{let g=o;eMcPAp.ZYAiR(_0x35bac5,_0x4216aa[g(720)]||new _0x300676(eMcPAp[g(1008)],eMcPAp[g(1008)])),eMcPAp[g(778)](m)};_0x57c699[o(1766)+o(436)](o(515),_),_0x30e63a[o(1766)+"Listener"](eMcPAp.UzXUB,S),_0x32a198[o(1766)+o(436)](eMcPAp[o(1502)],S)}else{let f=wn(c[o(659)][o(558)],e[o(949)],"-1"),m=wn(c[o(659)][o(558)],"is_ack","1"),_=wr(c.message[o(558)],e[o(1522)]),S=e[o(1805)](Number,wr(c[o(659)].headers,e.UWJZr))||0,g=Ga[o(1399)](this,c),R=e[o(1113)](wn,c.message[o(558)],e[o(652)],"2"),L=e[o(1877)](wr,c.message[o(558)],e[o(1650)]),B=e[o(1843)](Number,e.gOoLY(wr,c[o(659)][o(558)],e.TknLV));if(g[o(1610)])return r();let J=g["isQoSMes"+o(1813)]?await $l[o(1399)](this):null;if(e[o(488)](c.message[o(1553)],0)&&m&&!f||e.JvolI(c.message[o(1553)],0)){if(_&&g[o(1019)+o(1813)]&&J)return!!!await J[o(492)](_)&&(this["_dispatc"+o(833)+o(1791)](c),await J[o(624)](_,e[o(710)](Date[o(1313)](),S))),e[o(1921)](r);if(R)if(e.LVTSX(e.lLElY,o(1360))){let $={vXDVh:function(me,Ke,Xe){return e.Laiii(me,Ke,Xe)}};return new _0x575f19(me=>{let Ke=o;$[Ke(618)](_0x6f1a,me,this[Ke(454)+Ke(1599)+"e"](_0x4708ca))})}else{let $=await Jl.call(this);if(!$)return this[o(877)+o(833)+o(1791)](c),e.tOGFN(r);let me=await $[o(492)](L)??-1;if(e.nlksS(me,B))this["_dispatchMessage"+o(1791)](c),$.set(L,B,c[o(659)][o(1553)]);else throw new Error(o(1519)+o(913)+o(580)+B+(o(576)+"than local cursor ")+me);return r()}return this[o(877)+o(833)+o(1791)](c),e.PwTDf(r)}}}async function Em(c,r){let o=t;if(e[o(850)](e[o(1538)],e.FygXN)){let l=Ga[o(1399)](this,c);if(!l[o(1019)+o(1813)])return e[o(1706)](r);let f=await $l[o(1399)](this);if(l[o(1753)+o(1866)+o(1953)]&&l[o(1722)+"s"][o(1740)])for(let m of l[o(1722)+"s"])await f[o(647)](m);e.CGNPm(r)}else return this[o(877)+"hMessage"+o(1791)](_0x11e9f6),_0x26fdeb()}async function Sm(c,r){let o=t,l=c.message[o(858)+"e"]===gm,f=e[o(494)](c[o(659)][o(858)+"e"],Wa);if(e[o(1969)](!l,!f))return e[o(608)](r);let m=e[o(1537)](wr,c.message[o(558)],o(887)+o(516));if(!m)return e[o(1266)](r);let _=await Jl[o(1399)](this,m);if(!_)return r();if(l)if(e.oCfLV(e[o(1477)],e[o(1477)])){let S=await _[o(537)+"rs"](),g={frameType:S?.[o(858)+"e"],SeqID:ce.fromNumber(this[o(1036)]++),LogID:ce[o(1797)+"er"](this[o(735)]["logIDGen"+o(1340)]()),service:9e3,method:5,headers:S?.[o(558)],payload:S?.[o(956)]},R=b(g);this[o(664)]&&this[o(664)][o(1483)+"te"]&&this[o(664)][o(709)](R)}else this[o(1517)](_0x1de0a6,_0x1b3c59);if(f){let S=c.message[o(956)];S&&_.setCursors(S)}}let Im=async function(c,r){let o=t;this[o(1581)]=!1,e[o(1434)](clearTimeout,this["_connect"+o(1160)+o(606)]),e[o(1921)](r)},Am=async function(c,r){let o=t;if(!this[o(664)]||e[o(649)](this[o(664)][o(1483)+"te"],this[o(501)]))return e[o(1903)](r);let{pingInterval:l}=this[o(735)];this["_endpoin"+o(1038)]?.[o(1050)+o(925)+o(1344)]();for(let m=0;m<this[o(1412)+o(1550)][o(1740)];m++){let _=this[o(1412)+o(1550)][m];if(e.PnrNT(this[o(664)][o(1483)+"te"],this[o(501)])&&e[o(1375)](null,_))this._ws&&this[o(664)][o(709)](_),this[o(1412)+"Queue"][m]=null;else break}this["_message"+o(1550)]=this["_message"+o(1550)][o(1884)](m=>!!m),this[o(1279)+o(640)+"Id"]=e[o(909)](setTimeout,()=>this[o(670)](),l),this[o(877)+o(627)+"nt"](c),this[o(1854)+"er"]&&this[o(664)]&&(this[o(664)].binaryType=this[o(807)+o(1947)]);let f=this["_endpoin"+o(1038)]?.[o(1293)+o(811)+"nt"]();this[o(549)](o(1880)+f+o(1096)),e[o(783)](r)},km=async function(c,r){let o=t,l=this[o(1425)+"tManager"]?.[o(1293)+o(811)+"nt"]();this[o(549)](o(1880)+l),e.WmKTd(r)};class Cm extends za{constructor(r){let o=t,l={oUfCc:function(S,g){return e[F(1030)](S,g)},wFOJg:e[o(1482)],viiaI:function(S,g,R){return e[o(1867)](S,g,R)},fSxrJ:e[o(677)],ADvRz:function(S,g,R){return S(g,R)},cFuNI:e[o(1347)],nRJXD:function(S,g){return S!==g},apLBt:function(S,g,R){return e[o(1931)](S,g,R)},fSmFc:function(S,g){return e[o(503)](S,g)},ISnLC:function(S,g){return e.Jlund(S,g)},dCjzm:function(S,g,R){return e[o(1217)](S,g,R)},YMvOt:function(S,g){return e[o(1576)](S,g)}};super(),this["_miniNav"+o(1370)+o(838)]=!0,this[o(1854)+"er"]=mr,this[o(934)]=jg,this[o(764)+"T"]=Un,this[o(1659)+"X"]=xi,this._isWorker=pi,this[o(1412)+o(1550)]=[],this[o(1425)+o(1038)]=null,this[o(1625)+o(1723)]=!1,this[o(807)+o(1947)]=e[o(1478)],this[o(1685)+o(642)]=!1,this[o(1685)+o(1160)+"utId"]=null,this[o(688)+o(1860)+"tId"]=null,this["_pingPon"+o(640)+"Id"]=null,this[o(1036)]=0,this[o(1581)]=!1,this[o(1775)]="",this[o(1408)+o(1240)]=null,this[o(539)+o(1500)]=null,this._pingLossCounter=null,this[o(1796)+"ls"]=o(1296),this[o(1184)]=3,this[o(953)+"NG"]=0,this[o(501)]=1,this[o(899)]=2,this[o(878)]=S=>{let g=o;try{Gl(this,S,[Im,Am,km])}catch(R){if(l[g(786)](g(1909),l[g(1091)])){let L=_0x2476af.message[g(956)];L&&_0x3813af[g(944)+"rs"](L)}else{let L=l[g(1915)](wt,l[g(1620)],{message:R.message,code:mn.OPEN_ERROR,error:R});this[g(877)+g(1218)+g(1388)](L)}}},this[o(1395)+"ge"]=async S=>{let g=o,R={fKFQE:function(L,B){return L(B)},VUXLW:function(L,B){return e.SGufm(L,B)},HCFCY:function(L,B){return e.URvYA(L,B)},fsEyx:function(L,B){return e.WHBOQ(L,B)}};if(e[g(505)](e[g(1875)],e.qUaMz)){let{pingInterval:L,pingFrequency:B}=this[g(735)];if((S[g(643)]==="hi"&&e[g(1926)]===B||e[g(535)]===B)&&(this["_clearPi"+g(1642)](),this[g(507)](e[g(1170)],"success"),this[g(1279)+"gTimeoutId"]=e.YmzrQ(setTimeout,this[g(670)].bind(this),L)),e[g(996)]("hi",S[g(643)]))return;try{e.IxALo(e[g(1393)],e[g(1393)])?e.IVNZW(Gl,this,S,[sm,rm,Em,Sm,vm,im]):(R[g(1895)](_0x1ecac5,this["_pingPon"+g(640)+"Id"]),R.fKFQE(_0x308b3a,this[g(688)+g(1860)+g(691)]),this[g(1279)+g(640)+"Id"]=null,this[g(688)+"ctTimeou"+g(691)]=null)}catch(J){let $=e[g(1674)](wt,e.hvrfV,{message:J[g(659)],code:mn[g(1937)+g(693)],error:J});this[g(877)+g(1218)+g(1388)]($)}}else{if(qzzYRO[g(607)](_0x52159e,_0x24f913)){if(qzzYRO[g(560)](_0x998fee,"done"))return _0x34221e.get(_0x36af28);if(qzzYRO[g(560)](_0x37f29b,g(1033)+"oreNames"))return _0x399307[g(1033)+"oreNames"]||_0x4bd9a3[g(492)](_0x3f11b4);if(qzzYRO.fsEyx(_0x5e3554,g(1470)))return _0x2565c0["objectSt"+g(908)][1]?void 0:_0x353089[g(1033)+g(690)](_0x563183[g(1033)+g(908)][0])}return qzzYRO[g(1895)](_0x11795c,_0x11bc88[_0x4fdaa6])}},this._onError=S=>{let g=o,R=this[g(1425)+g(1038)]?.[g(1666)+g(605)+"es"](),L=this[g(1425)+"tManager"]?.[g(1293)+"ntEndpoint"]();if(R&&!S.message){let B=g(1705)+L+(g(520)+g(966)+g(1720)+"ed");this[g(877)+g(1218)+g(1388)](e[g(900)](wt,e[g(677)],{message:B,code:mn[g(984)+"IES_ERROR"],error:S}));return}this[g(664)]&&e[g(528)](this[g(664)][g(1483)+"te"],this[g(501)])&&this[g(1074)+g(917)](),this["_dispatc"+g(1218)+g(1388)](e.eEQxH(wt,e[g(677)],{message:S.message,code:mn[g(1437)+g(738)],error:S}))},this[o(1089)]=async S=>{let g=o;this[g(890)+g(1204)](),this[g(1870)+g(1642)](),this[g(1397)+"sListeners"](),this._ws=null,this[g(1685)+g(642)]=!1;let R=this[g(1425)+g(1038)]?.[g(1666)+g(605)+"es"]();if(!R&&this[g(1141)+g(974)]()&&!this[g(1625)+g(1723)]){let L=this[g(1425)+g(1038)]?.[g(1293)+g(811)+"nt"](),B=this[g(735)]["reconnec"+g(1023)+"ptor"](S[g(1879)],S[g(1526)]);this[g(877)+g(1874)+g(1388)](l[g(532)](kt,l[g(1592)],{code:1006,reason:S[g(1526)]||"connecti"+g(476)+"d, unkno"+g(1501)+g(1515)+g(445)+L,willReconnect:B})),B&&this[g(1685)]();return}if(l[g(440)](1e3,S[g(1879)])&&this[g(1625)+g(1723)]){this[g(877)+"hCloseEv"+g(1388)](l.apLBt(kt,l[g(1592)],{code:1e3,reason:g(1671)})),this[g(1425)+"tManager"]?.[g(1050)+g(925)+g(1344)](),this[g(1769)+g(1933)]?.["resetCou"+g(869)]();return}if(l.fSmFc(1e3,S[g(1879)])&&R){let L=this["_endpoin"+g(1038)]?.[g(1293)+g(811)+"nt"](),B=S.reason;B||(B=await l.ISnLC(Yg,this[g(1775)])),B=g(1863)+g(476)+"d, "+B+(g(474)+g(1823))+L+(g(1790)+g(1658)+g(1608)),this[g(877)+g(1874)+g(1388)](l[g(532)](kt,l[g(1592)],{code:S[g(1879)],reason:B}));let J=g(1705)+L+(g(520)+g(966)+g(1720)+"ed");this[g(877)+g(1218)+"ent"](l[g(1573)](wt,l[g(1620)],{message:J,code:mn[g(984)+g(561)+"R"]})),this[g(1425)+"tManager"]?.[g(1050)+g(925)+g(1344)](),this[g(1769)+g(1933)]?.resetCounter();return}if(S.code!==1e3&&!S[g(1526)]){let L=this[g(1425)+g(1038)]?.["getCurre"+g(811)+"nt"]();this["_dispatchCloseEv"+g(1388)](l[g(1573)](kt,l.cFuNI,{code:S.code,reason:g(1863)+g(476)+g(1668)+g(1501)+"n, hostn"+g(445)+L})),this[g(1425)+g(1038)]?.["resetEnd"+g(925)+g(1344)](),this["_pingLos"+g(1933)]?.[g(1358)+g(869)]();return}this["_dispatc"+g(1874)+g(1388)](S),this[g(1425)+g(1038)]?.[g(1050)+"pointConfig"](),this[g(1769)+g(1933)]?.["resetCou"+g(869)]()},this.onclose=null,this[o(1003)]=null,this[o(1101)+"e"]=null,this[o(1891)]=null,this[o(1641)+o(1640)]=null,this[o(573)+o(1770)]=null,this[o(1119)+o(1554)+o(1778)+"ct"]=null,this[o(1611)+"nLine"]=this[o(1611)+o(1732)].bind(this),this[o(1611)+o(1491)]=this[o(1611)+"ffLine"][o(1014)](this),this["_handleP"+o(1352)]=this[o(1735)+"ageHide"][o(1014)](this),this["_handleP"+o(740)]=this[o(1735)+o(740)].bind(this),this[o(735)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e.TjiIw(1,0),service:0,logIDGenerator:s,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:o(751),pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:o(1971),env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:m}=r,_=Array.isArray(f)?f:e[o(1043)](e[o(1262)],typeof f)?[f]:[];if(!_||e.UpcRh(0,_.length))throw new Error(e[o(546)]);if(!e[o(1325)]($g,m))throw new Error("please p"+o(1180)+o(682)+", WebSocket cons"+o(1759)+o(1257)+"ined");if(Object[o(1920)](this[o(735)],r),this[o(1425)+o(1038)]=new Hl(_,this._options[o(725)+"es"]),this[o(1769)+o(1933)]=new Zg(this._options[o(1072)+"Count"]),this._options[o(1126)+o(1536)]&&(this[o(1581)]=!0,this[o(1685)]()),this[o(735)][o(1949)+o(1171)+"nged"])if(e[o(1345)]!==e.OLNfl)this[o(764)+"T"]||this._isMiniWX?this[o(1471)+o(1911)+o(587)]():this[o(1854)+"er"]&&this[o(1505)+o(882)+o(436)]();else return _0x4e7b75[o(692)](_0x38e8dd(this),_0x237bee),Jccmgb[o(487)](_0x55aaf0,_0x116e23[o(492)](this))}[t(1611)+t(1732)](){let r=t;if(e[r(1162)]===e[r(566)])return _0x5bea4f+=_0x219366&&_0x47f9e4[r(1350)+"th"]||0,_0x372ea3;if(this[r(735)]["disableA"+r(1045)+r(744)]||this[r(1625)+r(1723)])return;this[r(1267)+r(1640)]()}[t(1611)+t(1491)](){let r=t;if(e[r(1311)]!==e[r(1311)])return new _0x1da768(_0x5b13eb,{message:_0x384fb2,code:_0x3aaf48,error:_0x13076f});{this[r(514)+r(524)+"t"]();let o=e[r(1084)](Fa,e.CYpxc,{message:e.vSMWJ});this[r(1119)+r(1554)+r(1778)+"ct"]&&this[r(1119)+"mediatel"+r(1778)+"ct"](o)}}["_initGlobalEvent"+t(436)](){let r=t;this[r(1854)+"er"]&&window["addEvent"+r(436)]("online",this._handleOnLine),this._isBrowser&&window[r(1766)+r(436)](r(813),this[r(1611)+r(1491)]),this._isBrowser&&window["addEvent"+r(436)](e[r(1356)],this[r(1735)+r(1352)]),this._isBrowser&&window[r(1766)+r(436)](e.sJrcX,this["_handleP"+r(740)])}[t(1097)+t(882)+t(436)](){let r=t;this._isBrowser&&window[r(1213)+r(1200)+r(698)](e.ZiMsx,this[r(1611)+r(1732)]),this._isBrowser&&window["removeEventListe"+r(698)](r(813),this[r(1611)+r(1491)]),this[r(1854)+"er"]&&window[r(1213)+"entListe"+r(698)](e.mWyfD,this[r(1735)+r(1352)]),this[r(1854)+"er"]&&window["removeEv"+r(1200)+"ner"](e[r(1250)],this[r(1735)+"ageShow"])}[t(1735)+t(1352)](r){let o=t;!r[o(1301)+"d"]&&(this[o(1854)+"er"]&&window[o(1213)+o(1200)+"ner"](o(1748),this["_handleP"+o(1352)]),this._isBrowser&&window[o(1213)+o(1200)+o(698)]("pageshow",this["_handleP"+o(740)]),this[o(1029)]()),this[o(1854)+"er"]&&window["removeEv"+o(1200)+"ner"](e[o(1342)],this[o(1611)+o(1732)]),this[o(1854)+"er"]&&window[o(1213)+o(1200)+o(698)](o(813),this[o(1611)+o(1491)])}["_handleP"+t(740)](r){let o=t;r[o(1301)+"d"]&&(this[o(1141)+o(974)]()&&(!this._ws||e[o(1678)](this[o(664)].readyState,this.OPEN)||this._ws[o(1483)+"te"]!==this[o(953)+"NG"])&&this[o(1611)+o(1732)](),this[o(1854)+"er"]&&window[o(1766)+"Listener"](e[o(1342)],this["_handleO"+o(1732)]),this[o(1854)+"er"]&&window["addEvent"+o(436)](e[o(894)],this[o(1611)+o(1491)]))}async[t(753)+t(1189)](r){let o=t,{fpID:l,deviceID:f,bddID:m,ttwID:_,accessKey:S,aID:g,customParams:R={},enableAutoAck:L,enableQoS:B,QoSLevel:J,env:$}=this[o(735)],me,Ke,Xe;if(this[o(1854)+"er"]||this[o(1659)+"X"]||this[o(764)+"T"])me=location&&e[o(1690)](e.nQKui,location[o(1829)])?e[o(1035)]:e.ozOzd,Ke=r.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),Xe=/^wss(.*:\/\/)/[o(1589)](r)?r:""+me+Ke;else{if(e[o(1460)]===o(629))return new _0x36948d(_0x3b35dc,{data:_0x251146,message:_0x3c004c});me=e[o(1035)],Ke=r.replace(/(^http)((?:[s]*:\/\/))/,""),Xe=/(^ws)((?:[s]*:\/\/))/[o(1589)](Ke)?Ke:""+me+Ke}let st=m?e[o(1191)]:_?e[o(455)]:e[o(1291)],_n=m||_||f;if(e[o(1453)](!_n,!st))throw new Error(e[o(1254)]);let Tm=e.UumdL(o(1643),typeof R)?await e[o(1310)](R):R,Pm=$?e[o(570)](Jg,$[o(1277)],$[o(1638)]):{},Ka=Object[o(1920)]({device_platform:o(827),version_code:e[o(1774)],access_key:S,fpid:l,aid:g,[st]:_n,xsack:L?1:0,xaack:L?1:0,xsqos:B?1:0,qos_level:B?J:void 0,qos_sdk_version:2,...Pm},Tm),Dm=Object[o(1069)](Ka)[o(1225)](($a,Va)=>Ka[Va]!==void 0?""+$a+($a?"&":"?")+Va+"="+Ka[Va]:$a,"");return Xe+"/ws/v2"+Dm}async[t(1685)](){let r=t;if(e[r(484)](e[r(1882)],e[r(1882)])){if(this[r(1685)+r(642)]||this[r(1625)+r(1723)])return;this[r(1685)+"Lock"]=!0;try{let o=this[r(1425)+r(1038)]?.[r(1251)+"rentEndp"+r(1619)+r(1042)+r(772)](),{timeoutInterval:l}=this[r(735)];if(o){let m=this[r(1425)+"tManager"]?.[r(1293)+r(811)+"nt"](),_=this[r(1425)+r(1038)]?.[r(1424)+r(1451)+r(1224)+"UpdateCo"+r(522)](),S=this[r(1425)+r(1038)]?.["getCurrentEndpoi"+r(1143)+r(554)]();if(_){let g=r(1705)+m+(" timeout, max re"+r(1658)+r(538)+r(1683)+r(1185)+r(727))+_+" to retry",R=wt(e[r(677)],{message:g,code:mn[r(984)+r(561)+"R"]});this[r(549)](g),this[r(877)+r(1218)+"ent"](R),this._url=await this["_generat"+r(1189)](_),this[r(549)](r(1705)+_+" "+S+" times"),this._removeWsListeners()}else{let g=r(1705)+m+(r(583)+r(1790)+"tries re"+r(1608));this._debug(g),this["_dispatc"+r(1218)+r(1388)](e.ffIOX(wt,e[r(677)],{message:g,code:mn["MAX_RETR"+r(561)+"R"]}));return}}else{let m=this[r(1425)+r(1038)]?.[r(1293)+r(811)+r(672)+r(824)](),_=this[r(1425)+r(1038)]?.[r(1293)+r(811)+r(1143)+r(554)]();this._url=await this[r(753)+r(1189)](m||""),this[r(549)]("connect "+m+" "+_+r(718)),this[r(1397)+r(1939)+"rs"]()}if(this[r(1581)])this[r(1581)]=!1;else{let m=Fa(e.CYpxc,{message:e[r(1630)]});this[r(1641)+r(1640)]&&this[r(1641)+r(1640)](m)}let f=this[r(1425)+r(1038)]?.[r(1293)+r(811)+r(1143)+"ount"]()||0;e.lRzJP(f,1)&&await this[r(591)](e[r(631)](f,1)),this[r(549)](r(1863)+r(1817)+this._url+(" protoco"+r(757))+this[r(1796)+"ls"]),this[r(664)]=e[r(1819)](Kg,{url:this[r(1775)],protocols:[this[r(1796)+"ls"]],headers:this._options.miniProgramParams[r(801)+"tpHeader"]},this[r(735)].ws),(this[r(1854)+"er"]||this[r(1164)+"r"])&&this[r(664)]&&(this[r(664)][r(542)+"pe"]=this[r(807)+"ype"]),this[r(1465)+r(1896)](),this[r(1685)+r(1160)+r(606)]=e[r(1026)](setTimeout,this._onTimeout.bind(this),l)}catch(o){throw this._connectLock=!1,o}}else return e.GqXfX(e[r(1503)](_0x258824,8).join("0"),e[r(900)](_0x9ee352,_0x521652,10)[r(497)](2)).slice(-8)}[t(890)+t(1204)](){let r=t;clearTimeout(this[r(1685)+r(1160)+r(606)]),this[r(1685)+r(1160)+r(606)]=null}["_clearPi"+t(1642)](){let r=t;e[r(910)](clearTimeout,this[r(1279)+r(640)+"Id"]),clearTimeout(this[r(688)+r(1860)+r(691)]),this[r(1279)+r(640)+"Id"]=null,this[r(688)+r(1860)+r(691)]=null}[t(549)](...r){let o=t;this[o(735)][o(1633)]&&console[o(553)][o(692)](console,[e.yVilt,...r])}[t(454)+"rvalValue"](r){let o=t,{initReconnectInterval:l,maxReconnectInterval:f,reconnectIntervalGrowFactor:m}=this[o(735)],_=e[o(1421)](l,Math[o(971)](m,e.peTzD(r,1)));return _>f?f:_}[t(670)](){let r=t;if(this[r(664)]&&e[r(1607)](this[r(664)].readyState,this.CONNECTING)){this["_clearPi"+r(1642)](),this[r(1279)+"gTimeoutId"]=e[r(1157)](setTimeout,this[r(670)].bind(this),this[r(735)][r(1041)+r(1255)]);return}if(!this[r(664)]||e[r(1190)](this[r(664)].readyState,this[r(501)]))return void this[r(1267)+"econnect"]();this[r(664)]&&this[r(664)][r(709)]("hi"),this[r(688)+r(1860)+r(691)]=e[r(1936)](setTimeout,this[r(1267)+r(1640)+r(1856)][r(1014)](this),this[r(735)][r(1605)+r(1161)+"val"])}["_handleR"+t(1640)+t(1856)](){let r=t;this[r(1769)+r(1933)]?.addCount(),this[r(507)](r(1541)+r(903)+"t",r(1449)),this[r(1769)+r(1933)]?.[r(1666)+"chMaxCount"]()?this[r(1267)+r(1640)]():this._ping()}[t(1141)+t(974)](){let r=t;return this[r(764)+"T"]||this._isMiniWX?this[r(1178)+r(1370)+r(838)]:(this[r(1854)+"er"]||this[r(1164)+"r"])&&this[r(735)][r(1949)+r(1171)+r(1295)]?navigator.onLine:!0}[t(1267)+"econnect"](){let r=t;!this["_navigat"+r(974)]()||this[r(1625)+"osed"]||(this[r(1425)+"tManager"]?.[r(1050)+r(925)+r(1344)](),this[r(1769)+r(1933)]?.["resetCou"+r(869)](),this._ws?this[r(1074)+"ect"](1001,e.aZrbA,!0):this[r(1685)]())}[t(1471)+"etWorkCh"+t(587)](){let r=t;this[r(764)+"T"]?tt["onNetwor"+r(1159)+r(1076)](({isConnected:o})=>{let l=r;this[l(1178)+l(1370)+l(838)]=o,o?this[l(1611)+l(1732)]():this[l(1611)+l(1491)]()}):this[r(1659)+"X"]&&wx[r(1297)+r(1159)+r(1076)](({isConnected:o})=>{let l=r;this[l(1178)+l(1370)+l(838)]=o,o?this["_handleO"+l(1732)]():this[l(1611)+l(1491)]()})}[t(591)](r){let o={snbZi:function(l,f,m){return l(f,m)}};return new Promise(l=>{let f=F;o[f(1890)](setTimeout,l,this[f(454)+f(1599)+"e"](r))})}[t(1074)+t(917)](r=1e3,o="",l=!1){let f=t;this[f(664)]&&this[f(514)+f(524)+"t"](r,o,l)}[t(486)+"ut"](){let r=t,o=this[r(1425)+r(1038)]?.["getCurre"+r(811)+"nt"]();this[r(549)](r(1705)+o+r(583)),this["_disconn"+r(917)](1001,e[r(901)],!0)}[t(437)](r){let o=t,l=e[o(784)](Yt,r);this._ws&&e[o(1560)](this._ws[o(1483)+"te"],this[o(501)])&&(this[o(664)]&&this[o(664)][o(709)](l),this._debug(e[o(1679)],r))}[t(1397)+"sListeners"](){let r=t,o=e[r(991)][r(1559)]("|"),l=0;for(;;){switch(o[l++]){case"0":if(!this[r(664)])return;continue;case"1":this[r(664)][r(1213)+"entListener"](e[r(1199)],this[r(1395)+"ge"]);continue;case"2":this[r(664)][r(1213)+"entListe"+r(698)](e.KukMM,this[r(878)]);continue;case"3":this[r(664)][r(1213)+r(1200)+r(698)](r(720),this[r(1727)]);continue;case"4":this._ws[r(1213)+r(1200)+r(698)](r(1029),this[r(1089)]);continue}break}}[t(1465)+t(1896)](){let r=t,o=e[r(609)][r(1559)]("|"),l=0;for(;;){switch(o[l++]){case"0":this[r(664)][r(1766)+r(436)](r(1029),this[r(1089)]);continue;case"1":this[r(664)][r(1766)+r(436)](e[r(677)],this[r(1727)]);continue;case"2":this._ws[r(1766)+"Listener"](e[r(1908)],this._onOpen);continue;case"3":this._ws[r(1766)+"Listener"](e[r(1199)],this[r(1395)+"ge"]);continue;case"4":if(!this[r(664)])return;continue}break}}["_wsInsta"+t(1878)](r=1e3,o=""){let l=t;try{this[l(664)]&&this[l(664)][l(1029)](r,o)}catch{}}[t(514)+t(524)+"t"](r=1e3,o="",l=!1){let f=t;if(this[f(1870)+f(1642)](),this[f(890)+"mer"](),this["_removeW"+f(1939)+"rs"](),this["_wsInsta"+f(1878)](1e3,o),this[f(1685)+f(642)]=!1,l&&this[f(1141)+f(974)]()&&!this["_readyCl"+f(1723)])if(f(1862)!==e[f(879)]){if(this["_endpoin"+f(1038)]?.[f(1666)+"chMaxTries"]()){let _=this[f(1425)+f(1038)]?.[f(1293)+f(811)+"nt"]();this[f(877)+f(1874)+f(1388)](kt("close",{code:1006,reason:f(1705)+_+(f(583)+f(1790)+f(1658)+f(1608)),wasClean:!0}))}else{let _=this._options[f(1513)+f(1023)+f(1542)](r,o);this[f(877)+f(1874)+f(1388)](e[f(1153)](kt,e[f(1347)],{code:r,reason:o,wasClean:!0,willReconnect:_})),_&&this[f(1685)]()}return}else return _0x1fec64.log(_0xecaa60),!1;this[f(1141)+"orOnline"]()||this[f(1625)+f(1723)]?this[f(877)+f(1874)+"ent"](e.Laiii(kt,e[f(1347)],{code:r,reason:e[f(1834)]})):this["_dispatc"+f(1874)+f(1388)](e[f(1329)](kt,e.QUHmb,{code:1006,reason:e.IGTOj})),this[f(664)]=null,this[f(1425)+"tManager"]?.[f(1050)+f(925)+f(1344)](),this["_pingLos"+f(1933)]?.[f(1358)+f(869)]()}[t(877)+"hOpenEvent"](r){let o=t;this[o(507)](e[o(1908)],r),this[o(1891)]&&this[o(1891)](r)}["_dispatc"+t(833)+t(1791)](r){let o=t;this[o(507)](e[o(1199)],r),this.onmessage&&this[o(1101)+"e"](r)}[t(877)+"hAckMess"+t(493)](r){let o=t;this[o(507)](o(1521),r),this["onReceiv"+o(1770)]&&this[o(573)+o(1770)](r)}["_dispatc"+t(1218)+t(1388)](r){let o=t;this[o(507)](e.hvrfV,r),this.onerror&&this[o(1003)](r)}[t(877)+t(1874)+t(1388)](r){let o=t;this[o(507)](e.QUHmb,r),this[o(708)]&&this.onclose(r)}get[t(542)+"pe"](){let r=t,o={weGcm:r(1040),ETZKI:function(l,f){return e[r(1627)](l,f)},SlAVv:e[r(862)]};if(e[r(1815)](e.DMZui,e.DMZui))return this._ws?this[r(664)][r(542)+"pe"]:this[r(807)+r(1947)];{let{SeqID:l,LogID:f,service:m,LogIDNew:_,method:S}=_0x1fd9d2[r(659)];this[r(437)]({SeqID:l,LogID:f,LogIDNew:_,service:m,method:S,headers:[{key:"is_ack",value:"1"},{key:EXNAjK[r(603)],value:EXNAjK[r(1415)](_,"")},{key:EXNAjK[r(1803)],value:"0"}]})}}set[t(542)+"pe"](r){let o=t;this[o(807)+o(1947)]=r,this[o(664)]&&(this[o(664)][o(542)+"pe"]=r)}get retryCount(){let r=t;return this[r(1425)+r(1038)]?.[r(1293)+r(811)+r(1143)+r(554)]()||0}get[t(870)+t(473)](){let r=t;return this[r(1412)+r(1550)][r(1225)]((l,f)=>(l+=f&&f[r(1350)+"th"]||0,l),0)+(this[r(664)]?this[r(664)][r(870)+r(473)]:0)}get[t(1198)+"ns"](){let r=t;return this[r(664)]?this[r(664)][r(1198)+"ns"]:""}get[t(1829)](){let r=t;return this[r(664)]?this[r(664)].protocol:""}get[t(1483)+"te"](){let r=t;if(e[r(1073)]!==e[r(1233)])return this[r(664)]?this[r(664)][r(1483)+"te"]:this._options[r(1126)+r(1536)]?this[r(953)+"NG"]:this[r(1184)];_0x355290[r(624)](_0x552eeb,_0x5df481),_0x2c73c9[r(624)](_0x2671d4,_0x27e741)}get[t(602)](){let r=t;return this[r(664)]?this[r(664)][r(602)]:this[r(1775)]}[t(1029)](r=1e3,o){let l=t;if(e[l(1149)]!==e[l(1149)])return this[l(523)]?.[l(1371)];if(this[l(1625)+l(1723)]=!0,this[l(890)+l(1204)](),this[l(1870)+l(1642)](),this[l(1097)+"balEvent"+l(436)](),this[l(1408)+"ger"]?.closeDB(),!this[l(664)])return void this[l(549)]("close, w"+l(819)+l(1647)+"nitialized");if(e[l(1667)](this._ws[l(1483)+"te"],this[l(1184)])||e.zFAcD(this[l(664)].readyState,this[l(899)]))return void this[l(549)]("close, w"+l(632)+"y closed");this[l(514)+l(524)+"t"](r,o)}async[t(709)](r,o){let l=t;if(r==null)throw new Error(e[l(818)]);e.QDdBg(l(1549),typeof r)&&(r=JSON[l(823)+"y"](r)),e[l(1523)](e[l(1262)],typeof r)&&!e.ptQqK(r,ArrayBuffer)&&!(r[l(1244)]&&e[l(1411)](r.buffer,ArrayBuffer))&&(r=JSON[l(823)+"y"](r));let f=await e[l(1183)](Wl,r),m=Vg(r),{method:_=0,service:S=this._options.service,logID:g=this[l(735)][l(937)+l(1340)](),headers:R=this[l(735)][l(558)],payloadEncoding:L=this[l(735)][l(1269)+"ncoding"],payloadType:B=this[l(735)][l(1205)+l(1947)],logIDNew:J=this[l(735)][l(463)+l(938)]["enableAu"+l(1540)+l(1316)+"ew"]?i(this[l(735)][l(463)+"Config"][l(1624)]):""}=o||{};if(!S)throw new Error(e[l(1207)]);let $={SeqID:ce.fromNumber(this[l(1036)]++),LogID:ce.fromNumber(g),service:S,method:_,headers:R,payloadEncoding:L instanceof Object?L.encoding?L.encoding:"":L,payloadType:e.pGrZp(B,Object)?B[l(1450)]?B.type:m:B||m,payload:f,LogIDNew:J},me=e.UkvcZ(Yt,$);return this._ws&&e.HAxtP(this[l(664)][l(1483)+"te"],this[l(501)])?(this._ws&&this[l(664)].send(me),this[l(549)](e[l(918)],$)):e[l(951)](this[l(1412)+l(1550)][l(1740)],this[l(735)][l(856)+l(769)+l(475)])?(this[l(1412)+l(1550)].push(me),this._debug(e[l(614)],$)):(this[l(1412)+"Queue"][l(562)](),this[l(1412)+l(1550)].push(me)),{seqID:this._seqId,logID:g,logIDNew:J}}async[t(1513)+"t"](r){let o=t,{url:l}=e[o(1314)](r,{}),f=Array[o(799)](l)?l:e[o(1262)]==typeof l?[l]:[];r&&Object.assign(this[o(735)],r),f&&f[o(1740)]?this["_endpoin"+o(1038)]=new Hl(f,this[o(735)].maxRetries):this[o(1425)+"tManager"]?.[o(1050)+o(925)+o(1344)](),this["_pingLos"+o(1933)]?.["resetCou"+o(869)](this._options[o(1072)+"Count"]),this[o(1625)+o(1723)]=!1,this[o(664)]&&e[o(550)](this._ws[o(1483)+"te"],this[o(1184)])?this._disconnect(1e3,o(641)+o(1640)+o(1967),!0):(this[o(1581)]=!0,this[o(1685)]())}async connect(){let r=t;!this["_connect"+r(642)]&&(this[r(1425)+r(1038)]?.[r(1050)+"pointCon"+r(1344)](),this[r(1769)+r(1933)]?.["resetCou"+r(869)](),this[r(1625)+r(1723)]=!1,this._isInit=!0,this[r(1685)]())}[t(1766)+t(436)](r,o){this.on(r,o)}["dispatch"+t(1791)](r){let o=t,{type:l}=r;this[o(507)](l,r)}[t(1213)+t(1200)+"ner"](r,o){this.off(r,o)}pingOnce(){let r=t,o={wZnYG:function(l,f){return e.ujeMl(l,f)},UAPJE:function(l,f){return e.USxEz(l,f)},XKBHx:r(1960),VSnON:function(l,f){return e[r(1305)](l,f)},gpUeg:r(796),ALZDF:e[r(1064)]};return new Promise((l,f)=>{let m=r,_={VrxyE:e[m(1064)]};this[m(1870)+"ngTimer"](),this["_pingPon"+m(640)+"Id"]=e[m(1819)](setTimeout,this._ping[m(1014)](this),this._options[m(1041)+"rval"]);let S=()=>{let R=m,L={pqtXb:function(B,J){return o[F(771)](B,J)}};o.UAPJE(R(1960),o[R(863)])?(o[R(1121)](l,o[R(669)]),this.off(R(1541)+R(1322)+"s",S),this.off(o[R(1469)],g)):(_0x125c3f=_0x3009bd(_0x425bb7),_0x1145ae|=MsjbCi[R(502)](127,_0x1e2246)<<7)},g=()=>{let R=m;f("timeout"),this[R(1517)](R(1541)+"e_success",S),this[R(1517)](_.VrxyE,g)};this.on(e[m(1170)],S),this.on(m(1541)+m(903)+"t",g),this[m(670)]()})}}})(),Pe[N(1910)+N(788)]=Oe[N(1910)+N(788)],Pe[N(1093)+N(1837)]=Oe["CustomEr"+N(1837)],Pe[N(1114)+"e"]=Oe.ErrorCode,Pe.Event=Oe.Event,Pe[N(1319)]=Oe.FWS,Pe.FrontierMessageEvent=Oe[N(945)+N(610)+N(1844)],Pe["MessageE"+N(1844)]=Oe[N(610)+N(1844)],Pe[N(1569)+"t"]=Oe[N(1569)+"t"],Pe[N(1208)+N(1015)]=Oe.ReconnectEvent,Pe[N(1104)+N(788)]=Oe[N(1104)+N(788)],Pe[N(973)+"rorEvent"]=Oe[N(973)+N(1837)],Pe[N(815)+"ssageEvent"]=Oe[N(815)+N(1606)+"nt"],Pe[N(1075)+N(1390)]=Oe[N(1075)+N(1390)],Pe[N(1792)+N(798)+"vent"]=Oe["createRe"+N(798)+N(1844)],Pe[N(1357)+N(622)]=Oe["decodedF"+N(622)],Pe[N(1841)+N(1628)]=Oe[N(1841)+"ame"];for(pa in Oe)[N(1910)+N(788),N(1093)+"rorEvent",N(1114)+"e","Event",N(1319),"Frontier"+N(610)+N(1844),N(610)+N(1844),N(1569)+"t",N(1208)+N(1015),"createCloseEvent",N(973)+N(1837),N(815)+N(1606)+"nt","createOp"+N(1390),"createReconnectE"+N(1844),N(1357)+N(622),"encodeFr"+N(1628)].indexOf(pa)===-1&&(Pe[pa]=Oe[pa]);var pa;function F(t,e){t=t-434;let n=ba(),i=n[t];if(F.yGsNkS===void 0){var s=function(h){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",w="";for(let b=0,y,v,I=0;v=h.charAt(I++);~v&&(y=b%4?y*64+v:v,b++%4)?p+=String.fromCharCode(255&y>>(-2*b&6)):0)v=x.indexOf(v);for(let b=0,y=p.length;b<y;b++)w+="%"+("00"+p.charCodeAt(b).toString(16)).slice(-2);return decodeURIComponent(w)};F.gTjGjO=s,F.zLkmZq={},F.yGsNkS=!0}let a=n[0],d=t+a,u=F.zLkmZq[d];return u?i=u:(i=F.gTjGjO(i),F.zLkmZq[d]=i),i}Object["definePr"+N(1384)](Pe,N(803)+"le",{value:!0})});import{existsSync as NA,openSync as BA}from"node:fs";import{mkdir as FA}from"node:fs/promises";import{dirname as zA}from"node:path";import{fileURLToPath as UA}from"node:url";function GA(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function yl(t=Z()){return NA(t.libEntry)?t.libEntry:UA(new URL("../index.ts",import.meta.url))}async function tg(t={}){let e=t.paths??Z(),n=t.entryOverride??yl(e),i=GA(e,process.env.COZE_BRIDGE_LOG_MODE);await FA(zA(i),{recursive:!0});let s=BA(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],u=dt(process.execPath,d,{detached:!0,stdio:["ignore",s,s],env:{...process.env,[bs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return HA.info("daemon spawned",{pid:u.pid,entry:n}),{pid:u.pid,entry:n}}var HA,bs,Aa=ot(()=>{"use strict";an();ne();Ce();HA=G("spawn-daemon"),bs="COZE_BRIDGE_DAEMON"});import{spawn as z2}from"node:child_process";import{mkdir as U2,unlink as H2,writeFile as G2}from"node:fs/promises";import{dirname as q2,join as j2}from"node:path";function fi(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function W2(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${fi(n)}</key>
21
- <string>${fi(i)}</string>`).join(`
20
+ `+n)}function gr(t,e,n,i,o,a){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,gr),t.emit("wsClientError",d,n,e)}else bs(n,i,o,a)}});var $p=fe(He=>{"use strict";var M=V;(function(t,e){let n=V,i=t();for(;;)try{if(parseInt(n(1289))/1+parseInt(n(764))/2+parseInt(n(1585))/3*(parseInt(n(1098))/4)+parseInt(n(380))/5+-parseInt(n(1089))/6+parseInt(n(477))/7+-parseInt(n(523))/8*(parseInt(n(1727))/9)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(ka,163224);var nI=Object["definePr"+M(1266)],rI=Object[M(937)+"opertyNa"+M(1110)],qp=(t,e)=>function(){return t&&(e=(0,t[{maphO:function(o,a){return o(a)}}.maphO(rI,t)[0]])(t=0)),e},iI=(t,e)=>{let n=M,i={oSpBI:function(a,d,f,u){return a(d,f,u)}};for(var o in e)i[n(818)](nI,t,o,{get:e[o],enumerable:!0})};function sI(){return Fp||(Fp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function oI(){let t=M;return Bp||(Bp=[IDBCursor.prototype[t(1749)],IDBCursor[t(501)+"e"][t(1678)],IDBCursor[t(501)+"e"][t(1678)+t(368)+"ey"]])}function aI(t){let e=M,n={HYlJb:function(o,a){return o(a)},liXeu:function(o){return o()},NVxXl:e(468),vKtIA:function(o,a){return o instanceof a}},i=new Promise((o,a)=>{let d=e,f={WfXZD:d(1746),gspET:function(w,b){return n.HYlJb(w,b)},zEOEo:function(w){return n.liXeu(w)}},u=()=>{let w=d;t[w(963)+w(1331)+w(441)](w(468),x),t[w(963)+"entListe"+w(441)](f[w(1605)],p)},x=()=>{let w=d;f[w(1257)](o,f[w(1257)](Yt,t[w(836)])),f.zEOEo(u)},p=()=>{f[d(1257)](a,t.error),u()};t[d(1107)+d(984)](n[d(418)],x),t[d(1107)+"Listener"](d(1746),p)});return i[e(1094)](o=>{let a=e;n[a(349)](o,IDBCursor)&&yl[a(1753)](o,t)})[e(765)](()=>{}),Ia[e(1753)](i,t),i}function cI(t){let e=M,n={gGERD:function(o){return o()},wMlKq:"QKyGT",azswV:e(452),gpHJU:e(1699),QUVlH:e(1746),PvivS:e(1108)+"or",IZlEF:e(1479)};if(Sa[e(1197)](t))return;let i=new Promise((o,a)=>{let d=e,f={lIJLY:function(w,b){return w!==b},EMveZ:n.wMlKq,sxgaJ:n[d(1676)],kdwZB:n[d(922)],cfyzT:n[d(1831)],nlpEg:"abort",zPqEk:n[d(420)]},u=()=>{let w=d;if(f.lIJLY(f.EMveZ,f[w(1796)]))t[w(963)+w(1331)+w(441)](f[w(787)],x),t[w(963)+w(1331)+w(441)](f[w(979)],p),t[w(963)+w(1331)+w(441)](f[w(1590)],p);else return!!_0x588837?.[w(526)](b=>b[w(1683)]===_0x19510b&&b[w(1595)]===_0x36bae7)},x=()=>{n[d(1647)](o),n.gGERD(u)},p=()=>{let w=d;a(t[w(1746)]||new DOMException(f[w(709)],f[w(709)])),u()};t[d(1107)+d(984)](n.gpHJU,x),t[d(1107)+"Listener"](n.QUVlH,p),t[d(1107)+d(984)](n[d(944)],p)});Sa.set(t,i)}function dI(t){Aa={QBjDQ:function(n,i){return n(i)}}.QBjDQ(t,Aa)}function lI(t){let e=M,n={Hhjnw:function(i,o,a){return i(o,a)},EMemT:function(i,o){return i===o},DJEXt:e(467),zyDfv:function(i,o){return i(o)},EuCQI:e(583),WzZvL:"ArkMC",ENpqi:function(i,o){return i(o)},emFDR:function(i,o){return i in o},WxXzD:e(891)+"oreNames",KaIUn:function(i){return i()}};return n.EMemT(t,IDBDatabase[e(501)+"e"]["transact"+e(817)])&&!n.emFDR(n[e(1083)],IDBTransaction[e(501)+"e"])?function(i,...o){let a=e,d={NPXfw:function(f,u,x){return n[V(1443)](f,u,x)},QMvEx:function(f,u,x){return n[V(1443)](f,u,x)}};if(n[a(713)](a(467),n[a(1147)])){let f=t[a(1603)](vs(this),i,...o);return _l[a(1753)](f,i.sort?i[a(1645)]():[i]),n[a(1521)](Yt,f)}else d[a(1180)](_0x24c5f7,_0x4cdff8,50),d[a(600)](_0x2a43c8,_0x375ace,_0x4b438c)}:n[e(1743)](oI)[e(632)](t)?function(...i){let o=e;return t[o(939)](vs(this),i),n[o(1521)](Yt,yl.get(this))}:function(...i){let o=e,a={OYuOv:n[o(1119)]};return o(885)===n[o(481)]?n[o(1521)](Yt,t[o(939)](n[o(996)](vs,this),i)):(_0x1e7d27||(_0x4d0ad9=_0x18e339.resolve()[o(1094)](_0x5d80fd[o(1305)](_0x3f0e8c,a[o(1003)]))),_0x1b99cf)}}function fI(t){let e=M,n={DUlgE:function(i,o){return i===o},nIOMi:"function",Oikns:function(i,o){return i(o)},pwbxt:function(i,o){return i instanceof o},VWFpM:function(i,o){return i(o)},eCPyQ:function(i,o,a){return i(o,a)}};return n.DUlgE(typeof t,n[e(1084)])?n[e(373)](lI,t):(n[e(1335)](t,IDBTransaction)&&n[e(1546)](cI,t),n.eCPyQ(Gp,t,sI())?new Proxy(t,Aa):t)}function Yt(t){let e=M,n={peSWA:function(o,a){return o instanceof a},Yfwwk:function(o,a){return o(a)},VviPc:function(o,a){return o!==a}};if(n[e(1349)](t,IDBRequest))return aI(t);if(ba[e(1197)](t))return ba[e(1326)](t);let i=n[e(639)](fI,t);return n.VviPc(i,t)&&(ba[e(1753)](t,i),Ia.set(i,t)),i}var Gp,Fp,Bp,yl,Sa,_l,ba,Ia,Aa,vs,zp=qp({"node_modules/idb/build/wrap-idb-value.js"(){let t=M,e={MsnoL:function(n){return n()},Hojii:function(n,i,o){return n(i,o)},qLAnA:function(n,i){return n(i)},hhcLG:function(n,i){return n instanceof i},ylXXD:function(n,i){return n!==i},xOMCu:"uMOBR",xhXNi:"OSfHo",jgxHX:"done",dKNCA:function(n,i){return n===i},mpvaX:t(365),ypvDK:function(n,i){return n===i},TRrWz:t(320),IVoYd:function(n,i){return n|i},hoBln:function(n,i){return n&i},TuuTh:function(n,i){return n>>i},TuhRI:function(n,i){return n|i},sFrlv:t(1659),qmjTb:function(n,i){return n in i}};Gp=(n,i)=>i[t(1181)](o=>n instanceof o),yl=new WeakMap,Sa=new WeakMap,_l=new WeakMap,ba=new WeakMap,Ia=new WeakMap,Aa={get(n,i,o){let a=t;if(e.hhcLG(n,IDBTransaction))if(e[a(840)](e[a(434)],e[a(656)])){if(i===e.jgxHX)return Sa[a(1326)](n);if(e[a(1324)](i,a(891)+a(329)))return e[a(1199)]===e[a(1199)]?n["objectSt"+a(329)]||_l[a(1326)](n):this[a(1167)+a(758)+a(610)+"t"];if(e.ypvDK(i,e[a(775)]))return o[a(891)+a(329)][1]?void 0:o[a(891)+a(538)](o["objectSt"+a(329)][0])}else{let d=e[a(1376)](_0x2832a5);return e[a(1509)](_0x4c2e05,_0x58f72f,d),e[a(1264)](_0x2f5cff,d)}return e.qLAnA(Yt,n[i])},set(n,i,o){let a=t;if(e[a(840)](e[a(563)],e[a(563)]))_0x27b80f[_0x423817++]=e[a(611)](e[a(1451)](e.TuuTh(_0x22585e,18),7),240),_0x1a9bec[_0x18f3f5++]=e[a(459)](e[a(1451)](e[a(748)](_0x2fc6a6,12),63),128);else return n[i]=o,!0},has(n,i){let o=t;return e[o(569)](n,IDBTransaction)&&(i===e.jgxHX||i===e[o(775)])?!0:e.qmjTb(i,n)}},vs=n=>Ia[t(1326)](n)}}),jp={};iI(jp,{deleteDB:()=>hI,openDB:()=>uI,unwrap:()=>vs,wrap:()=>Yt});function uI(t,e,{blocked:n,upgrade:i,blocking:o,terminated:a}={}){let d=M,f={oEdBa:function(p,w,b,_,v){return p(w,b,_,v)},CjvAI:function(p,w){return p(w)},mrTeT:d(1175),ltmhD:d(1639)+d(1824),AqNjD:"upgraden"+d(487),rLJhx:"blocked"},u=indexedDB[d(841)](t,e),x=Yt(u);return i&&u["addEvent"+d(984)](f.AqNjD,p=>{let w=d;f.oEdBa(i,f[w(874)](Yt,u[w(836)]),p[w(1610)+"on"],p[w(1420)+"on"],f[w(874)](Yt,u[w(1567)+w(817)]))}),n&&u[d(1107)+d(984)](f.rLJhx,()=>n()),x[d(1094)](p=>{let w=d;a&&p[w(1107)+w(984)](f.mrTeT,()=>a()),o&&p[w(1107)+w(984)](f[w(1310)],()=>o())})[d(765)](()=>{}),x}function hI(t,{blocked:e}={}){let n=M,i={sENnQ:n(1754)},o=indexedDB[n(808)+n(628)](t);return e&&o[n(1107)+n(984)](i[n(1170)],()=>e()),Yt(o).then(()=>{})}function Up(t,e){let n=M,i={WMjOJ:n(1658)+"e",HAIfk:n(1436),BBFcO:function(u,x){return u instanceof x},IbDgY:function(u,x){return u in x},ShSdI:function(u,x){return u===x}};if(!(i[n(1100)](t,IDBDatabase)&&!i[n(321)](e,t)&&i[n(1508)](typeof e,n(1397))))return;if(va[n(1326)](e))return va[n(1326)](e);let o=e[n(1631)](/FromIndex$/,""),a=e!==o,d=Kp.includes(o);if(!(o in(a?IDBIndex:IDBObjectStore).prototype)||!(d||Wp.includes(o)))return;let f=async function(u,...x){let p=n,w=this[p(1567)+p(817)](u,d?i[p(1762)]:i[p(1265)]),b=w[p(320)];return a&&(b=b[p(794)](x[p(1031)]())),(await Promise[p(499)]([b[o](...x),d&&w[p(579)]]))[0]};return va[n(1753)](e,f),f}var Wp,Kp,va,xI=qp({"node_modules/idb/build/index.js"(){let t=M,e={yahke:function(n){return n()},mtHAB:t(915),RYLEA:t(1302),vgsSI:t(1434),PMWAS:t(1686),bNsPO:t(1433),eaqxO:function(n,i){return n(i)}};e[t(1092)](zp),e[t(1092)](zp),Wp=[t(1326),e[t(785)],e[t(1262)],t(693)+"ys",t(1215)],Kp=[e.vgsSI,e.PMWAS,t(1258),e[t(1126)]],va=new Map,e[t(822)](dI,n=>({...n,get:(i,o,a)=>Up(i,o)||n.get(i,o,a),has:(i,o)=>!!Up(i,o)||n[t(1197)](i,o)}))}}),pI={idb:function(t){let e=M;t.exports=Promise[e(1078)]()[e(1094)](()=>(xI(),jp))[e(1094)](function(n){return n})}},Hp={};function Xt(t){let e=M,n={ekBmv:function(a,d){return a!==d}};var i=Hp[t];if(n[e(1696)](void 0,i))return i[e(1468)];var o=Hp[t]={exports:{}};return pI[t](o,o[e(1468)],Xt),o[e(1468)]}function V(t,e){t=t-319;let n=ka(),i=n[t];if(V.KXTQAw===void 0){var o=function(u){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",w="";for(let b=0,_,v,I=0;v=u.charAt(I++);~v&&(_=b%4?_*64+v:v,b++%4)?p+=String.fromCharCode(255&_>>(-2*b&6)):0)v=x.indexOf(v);for(let b=0,_=p.length;b<_;b++)w+="%"+("00"+p.charCodeAt(b).toString(16)).slice(-2);return decodeURIComponent(w)};V.yptjtC=o,V.reXAuj={},V.KXTQAw=!0}let a=n[0],d=t+a,f=V.reXAuj[d];return f?i=f:(i=V.yptjtC(i),V.reXAuj[d]=i),i}Xt.d=(t,e)=>{let n=V;for(var i in e)Xt.o(e,i)&&!Xt.o(t,i)&&Object["definePr"+n(1266)](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=M;Xt.o=(e,n)=>Object.prototype[t(1062)+t(1266)][t(1603)](e,n)})(),(()=>{let t=M,e={APSxH:t(1583)+"d",eKwOg:t(605)};Xt.r=n=>{let i=t;e[i(1562)]!=typeof Symbol&&Symbol["toString"+i(800)]&&Object[i(824)+i(1266)](n,Symbol[i(1518)+"Tag"],{value:e[i(527)]}),Object[i(824)+"operty"](n,"__esModule",{value:!0})}})();var Me={};(()=>{let t=M,e={LPvCo:function(c,r){return c(r)},UXOZa:function(c,r){return c+r},tbDLh:function(c,r){return c+r},hFeZC:function(c,r){return c*r},iyqHg:function(c,r){return c(r)},SfwGr:function(c,r){return c+r},HFhKP:function(c,r){return c(r)},KXfEh:function(c,r,s){return c(r,s)},qZggh:t(998),iFcQf:"ffff",JICGu:function(c,r){return c===r},DWnGD:t(1105),YxvtE:function(c,r){return c(r)},MkepB:function(c,r){return c>r},uiZPl:function(c,r){return c>r},HaQGH:function(c,r){return c<r},ybSjd:function(c,r){return c!==r},LnUec:t(1704),YVNva:t(544),ODaRh:function(c,r){return c-r},uMtbh:function(c,r){return c!==r},qYROV:function(c,r){return c<r},IVxdh:function(c,r){return c-r},SyMKf:function(c,r){return c-r},nUGWb:function(c,r,s){return c(r,s)},hDEwf:function(c,r,s){return c(r,s)},ccHtF:function(c,r){return c!==r},zbvlG:function(c,r){return c(r)},htkdE:function(c,r,s){return c(r,s)},EBahx:function(c,r){return c&r},FGZNe:function(c,r){return c===r},uAUVH:t(1179)+t(1786)+" field: value",tSYcb:function(c){return c()},Xazae:function(c,r,s){return c(r,s)},pfiIB:function(c,r){return c(r)},CXvNh:function(c,r){return c>r},fZkSw:function(c,r){return c!==r},UYXhv:function(c,r,s){return c(r,s)},jOVsr:function(c,r,s){return c(r,s)},reSpa:function(c,r,s){return c(r,s)},pTAjl:function(c,r){return c(r)},RpXMX:function(c,r){return c(r)},wUrVY:function(c,r){return c===r},AVZCR:t(404),fIpuk:t(697),mZHKQ:function(c,r,s){return c(r,s)},aSqEL:function(c,r,s){return c(r,s)},mtimn:function(c,r){return c!==r},qSZMp:function(c,r,s){return c(r,s)},vpgrz:t(1782),GnLHy:t(848),GQAYm:function(c,r,s){return c(r,s)},aQJUJ:function(c,r){return c!==r},uDFIW:function(c,r,s){return c(r,s)},RByfH:function(c,r,s){return c(r,s)},obKTT:t(1685),hRrEk:t(506),nDjWd:function(c,r){return c!==r},FOtsu:t(1675),DcDqz:function(c,r,s){return c(r,s)},kHBbT:"VrvRQ",gkRfF:"XChDr",hvNku:function(c,r){return c(r)},MeyjV:function(c,r){return c===r},mjEeL:t(1561),FifNC:t(631),XQjHw:function(c,r){return c>>>r},uBSld:function(c,r){return c(r)},IFczQ:function(c,r){return c(r)},CSQlY:function(c,r){return c!==r},yWgrQ:t(1805),uekSd:t(529),SoKKJ:function(c,r,s){return c(r,s)},lDoRT:function(c,r,s){return c(r,s)},RjUBh:function(c,r){return c(r)},tBZps:function(c,r,s){return c(r,s)},BRtiA:function(c,r,s){return c(r,s)},NeXAE:function(c,r){return c&r},ghIyt:function(c,r){return c===r},IgWvq:t(1179)+t(1786)+" field: SeqID",edMXh:t(1179)+t(1786)+t(432)+t(1572),NShpV:t(1179)+t(1786)+" field: method",ObIhR:function(c,r){return c(r)},BXkla:function(c,r){return c&r},firXH:function(c,r){return c(r)},ALmfR:function(c,r){return c+r},QKeKZ:function(c,r,s){return c(r,s)},HKAeK:function(c,r){return c!==r},SKOGT:t(1840),VbfrB:function(c,r){return c>>r},OupQH:function(c,r){return c>=r},puFDu:function(c,r){return c>r},PIMlJ:t(430)+"t limit",uVZFl:function(c,r){return c>=r},pqIbI:t(1565),jSOyi:function(c,r){return c+r},VddIs:"QiAmZ",kIEVC:"Read pas"+t(723),bCqgi:function(c,r){return c===r},jkUDy:t(579),xoSnC:function(c,r){return c!==r},oOocw:function(c,r,s){return c(r,s)},xSJog:t(797),wEMxT:"AZPSJ",iMJdb:function(c,r){return c instanceof r},ANiey:function(c,r){return c instanceof r},IINBX:t(1296)+t(688)+"et=utf-8",WNtXc:"applicat"+t(825)+t(856)+t(1472),RFBpU:"none_none",hLcdr:t(1184),ypDeM:function(c,r){return c<r},ZmcXn:function(c,r){return c&r},kTNMC:function(c,r){return c(r)},YRPIf:function(c,r){return c+r},UTKnG:function(c,r){return c!==r},urxkp:function(c,r){return c<<r},qGgWn:function(c,r){return c&r},cnwRh:function(c,r){return c<r},uKIGa:function(c,r){return c==r},IEavZ:function(c,r){return c===r},xdgAw:t(1384),TSmQg:t(650),HMRdw:function(c,r){return c+r},clNsE:function(c,r){return c&r},TKGXF:function(c,r){return c|r},cZBQv:function(c,r){return c<<r},xZlPS:function(c,r){return c|r},awMeu:function(c,r){return c<<r},ecfzz:function(c,r){return c&r},HBfZW:function(c,r){return c<<r},AaQJw:function(c,r){return c&r},fPTkz:function(c,r){return c<=r},ENfEl:function(c,r){return c>=r},cStor:function(c,r){return c+r},jSBfW:function(c,r){return c+r},dRgYR:function(c,r){return c&r},cDAcE:function(c,r){return c|r},QMcMz:function(c,r){return c+r},BxCRp:function(c,r){return c+r},mDZJz:function(c,r){return c&r},EnZVE:function(c,r){return c||r},SyYEb:function(c,r){return c>=r},JUfqC:function(c,r){return c-r},IrpXn:function(c,r){return c<<r},ZoWKd:function(c,r){return c<=r},iwKBp:function(c,r){return c<r},hIiDm:function(c,r){return c+r},BGRKN:function(c,r){return c+r},gPivP:function(c,r){return c<r},ldEuw:t(1235),APwVZ:t(770),qGCiM:function(c,r){return c<r},ulYvQ:function(c,r){return c|r},KHPpx:function(c,r){return c&r},otUCf:function(c,r){return c>>r},OwNfn:function(c,r){return c===r},CHzol:t(346),GyEXa:t(1149),ZCmLY:function(c,r){return c|r},sjxuT:function(c,r){return c&r},lnOeP:function(c,r){return c|r},wBBmq:function(c,r){return c>>r},CxfYQ:function(c,r){return c&r},abEYg:function(c,r){return c&r},pfCzD:function(c,r){return c<r},LvBPT:"KfUss",NHRCb:function(c,r,s){return c(r,s)},sXprw:function(c,r){return c&r},sGjLB:function(c,r){return c===r},Synht:"vzRuu",bHdRg:t(1717),EqYRJ:function(c,r){return c(r)},qIsnR:function(c,r){return c&r},xcJfo:function(c,r){return c(r)},Xftyi:function(c,r){return c<<r},yXoON:function(c,r){return c&r},RZXXc:function(c,r){return c(r)},Jsauq:function(c,r){return c&r},hVyiC:function(c,r){return c&r},jkiXd:function(c,r){return c(r)},TTirx:function(c,r){return c(r)},IaERq:function(c,r){return c(r)},IWAan:function(c,r){return c&r},czqRE:function(c,r){return c|r},WXLtp:function(c,r){return c|r},waoSH:function(c,r){return c>>>r},JDGGU:function(c,r){return c<<r},zniFR:function(c,r){return c>>>r},hOaLv:function(c,r){return c===r},ZJJwH:function(c,r){return c===r},UWHGU:function(c,r){return c<r},ipMUz:function(c,r){return c<r},tdcEO:function(c,r){return c<r},IiTmi:function(c,r){return c<r},FgaKH:function(c,r){return c>>>r},yPora:function(c,r){return c+r},XeLaC:function(c,r){return c!==r},OPwUG:function(c,r){return c|r},yGMSe:function(c,r){return c&r},eLLLF:function(c,r){return c+r},lDZRu:function(c,r){return c&r},fleJX:function(c,r){return c>>>r},ZEXca:function(c,r){return c|r},kekIR:function(c,r){return c>>>r},BDmaw:function(c,r){return c>>>r},XbkgK:function(c,r){return c!==r},tKumJ:function(c,r){return c|r},uElUM:function(c,r){return c>>>r},PIaED:function(c,r){return c&r},ZvImf:function(c,r){return c>>>r},gBucD:function(c,r){return c|r},VuncQ:function(c,r){return c!==r},yhJDA:function(c,r){return c&r},Vjjsk:function(c,r){return c>>>r},nITFW:function(c,r){return c|r},Gwofq:function(c,r){return c|r},IVVrd:function(c,r){return c&r},NCAuK:function(c,r){return c!==r},fpTuR:function(c,r){return c|r},Ssmzl:function(c,r){return c&r},lxdOh:function(c,r){return c(r)},OkVrb:function(c,r){return c|r},pDVOj:function(c,r){return c<<r},gLuWV:function(c,r){return c|r},ENaxR:function(c,r){return c<<r},hbGtG:function(c,r){return c|r},MPhQo:function(c,r){return c|r},pniNM:function(c,r){return c&r},iEXSA:function(c,r){return c&r},sJbui:function(c,r){return c>>>r},UqQLu:function(c,r){return c&r},Pwdjm:function(c,r){return c>>>r},SxMVL:function(c,r){return c!==r},nuNLl:t(1815),bGoDa:function(c,r){return c>>>r},gRbMG:function(c,r){return c|r},uAMER:function(c,r){return c<<r},Vzlwk:function(c,r){return c|r},griOq:function(c,r){return c<<r},rHhXt:function(c,r){return c&r},tOQNb:function(c,r){return c>>>r},wJEgy:function(c,r){return c|r},LMIed:function(c,r){return c/r},BgnZN:function(c,r){return c+r},PRBhl:function(c,r){return c+r},cSMQK:function(c,r){return c===r},nwxWX:function(c,r){return c>>>r},vxJQr:function(c,r){return c&r},UiUPE:function(c,r){return c&r},xEKip:function(c,r){return c+r},JrReb:function(c,r){return c+r},LMqGY:function(c,r){return c>>>r},qdrnM:function(c,r){return c>>>r},uiNRC:function(c,r){return c|r},hTOUG:function(c,r){return c<<r},vjLEp:function(c,r){return c|r},UGVYx:function(c,r){return c>>>r},VaWtC:function(c,r){return c===r},BXlgB:function(c,r){return c<r},KvTlD:function(c,r){return c===r},ZipmR:t(1352),SLRQL:function(c,r){return c===r},UvVBc:function(c,r){return c+r},fzvGv:function(c,r){return c&r},DMCFY:function(c,r){return c&r},aketg:function(c,r){return c>>>r},aGkTb:function(c,r){return c>>>r},qNQiQ:function(c,r){return c>>>r},Zmogx:function(c,r){return c>>>r},DKbIF:function(c,r){return c&r},nEaBd:function(c,r){return c>>>r},MQXbh:function(c,r){return c>>>r},xWvlE:function(c,r){return c>>>r},vlODd:function(c,r){return c&r},TMByS:function(c,r){return c|r},axwih:function(c,r){return c&r},HmcsJ:function(c,r){return c!==r},RZqQB:t(1131),EevvV:t(586)+"4|5",Uzihf:t(1601)+t(1336),VYhdC:"CONNECTI"+t(1804),ZuxTy:t(618)+t(943)+"R",PFjqB:t(1157)+"OR",gCHaQ:t(1564)+"0",TiDMR:function(c,r){return c>=r},xdLxY:function(c,r){return c===r},CHovI:function(c,r){return c-r},yeRMM:function(c,r){return c==r},MrTce:"send_ack",wOaIZ:t(468),edSbv:function(c,r,s){return c(r,s)},sxYnD:t(1369)+t(590)+"t",DALlo:function(c,r){return c===r},qfPuA:t(712),zyGMJ:t(1734),wMPJr:t(678),Cwbqv:t(1247),IrlNJ:function(c,r){return c!==r},iJnNQ:t(1203),pazKF:t(1746),DeTlc:t(1175),VIJsT:function(c,r,s){return c(r,s)},PLgri:"open",bkQCK:function(c,r){return c===r},JUOVw:function(c,r){return c+r},JNAsE:t(1581),yfDjV:t(1500),egadl:t(645),gixvg:function(c,r,s){return c(r,s)},OzFfV:function(c,r){return c+r},ynElw:function(c,r){return c>>r},zMIqq:function(c,r){return c|r},VaERx:function(c,r){return c|r},FOBQB:function(c,r){return c&r},bighX:function(c,r){return c instanceof r},yBWqB:"LaGrg",FIkfE:function(c,r){return c!=r},xLJTq:function(c,r){return c*r},dFARF:function(c,r){return c===r},mIbZJ:"mfrUh",gGmpV:t(1144),nxLRQ:t(1583)+"d",ngdnO:"qNsXT",LnzFc:t(486)+t(1503)+t(1703)+"imes in "+t(905),VMbur:function(c,r){return c+r},dgoKi:function(c,r){return c(r)},ovTiG:function(c,r){return c&r},XcZNa:function(c,r){return c&r},Elxhy:function(c,r){return c(r)},egNtn:function(c,r){return c&r},ccCjK:function(c,r){return c(r)},NPvhv:"MDCFf",jFcQl:function(c,r){return c<r},MODao:function(c,r){return c===r},WFkpQ:function(c,r){return c===r},Dhzkc:function(c,r){return c<r},OvEYn:function(c,r){return c<=r},schMr:function(c,r){return c>=r},Nkfpa:function(c,r){return c<r},xUelg:function(c,r){return c|r},rfMEp:function(c,r){return c<<r},szUCA:function(c,r){return c&r},PPIxN:function(c,r){return c|r},XALOa:function(c,r){return c|r},jqZyi:function(c,r){return c<<r},CPIcI:function(c,r){return c<<r},WIdyY:function(c,r){return c!==r},AgbFU:t(725),Vcgjt:function(c,r){return c-r},JWsTb:function(c,r){return c|r},SetiF:function(c,r){return c&r},YRuqz:function(c,r){return c+r},MKKDS:function(c,r){return c<r},mkzVT:function(c,r){return c|r},NjnpC:function(c,r){return c&r},jhpkX:function(c,r){return c===r},EQclM:function(c,r){return c&r},EjuLn:function(c,r){return c+r},YVLJW:function(c,r){return c&r},bVmHI:function(c,r){return c&r},QeBbx:function(c,r){return c|r},TrIjw:function(c,r){return c&r},pdCHD:function(c,r){return c&r},XLJxZ:function(c,r){return c|r},cJnSv:function(c,r){return c&r},vzBdG:function(c,r){return c&r},MsLAa:function(c,r){return c|r},lduSY:function(c,r){return c>>r},GiWmN:t(1784),ASApT:t(1397),cuGjB:function(c,r){return c(r)},VKzqk:function(c,r,s,l){return c(r,s,l)},lGVbw:function(c,r){return c!=r},AzmRU:t(776)+t(825),QTJgX:function(c,r){return c==r},FHpqL:"boe",XPKUN:t(1439),bdOQn:t(1277)+t(828),ViKxF:"script",CeMFI:t(1140)+t(993),laxJv:function(c,r){return c+r},IEGri:t(1271),egbjM:"&jscallback=fron"+t(551)+"P",UbmQq:t(460),GtxHI:function(c,r){return c<r},mOxQP:function(c,r){return c<<r},SRwwl:function(c,r){return c|r},UdMDy:"idb",mRvCT:t(1404),JUACX:t(1643)+t(327),YdQtf:"dyExr",omHpa:"uwVnD",bMDnI:t(1623),oELRj:t(1814),NUNyj:t(1785),aaIje:"zeLoe",hKtLi:function(c,r,s){return c(r,s)},daRcd:t(895),HmCoA:function(c,r){return c||r},WLLRf:t(1517),gIryo:function(c,r){return c||r},tEWcg:function(c,r){return c||r},SDuRP:"BbDdF",padRW:function(c,r){return c||r},VvGXy:function(c,r){return c||r},rBMDR:function(c,r){return c||r},SnGYO:t(1432)+"00000000"+t(1432)+"00000000",skSGO:function(c,r){return c||r},gOHhp:"LfNMH",UdVIl:t(1672),VimIj:function(c,r){return c||r},Vvtxe:t(1735)+t(1374)+"d",AFKFm:t(348),kAbRc:t(1256)+"id",ngBzC:function(c,r,s){return c(r,s)},SmoTz:function(c,r,s,l){return c(r,s,l)},LXvWr:t(1693),AJVvN:function(c,r){return c(r)},LijqS:function(c,r,s){return c(r,s)},QcgRi:function(c,r){return c==r},JXdVP:function(c,r){return c instanceof r},MEiBH:t(742),WLdec:function(c,r){return c===r},supaQ:t(372),ZrPcf:t(1744),PcNBr:"ack",DTQJg:function(c,r){return c===r},gaXLT:t(1413),kHaAc:t(509),rNeKC:t(959),CofPZ:t(395)+t(987),ACLQQ:function(c,r,s,l){return c(r,s,l)},HlPae:t(395)+t(774)+"ck",XrhJk:t(395)+t(453)+"k",WUTJW:"x_fronti"+t(1530)+t(791),UuOgF:"suQiy",EKTmn:function(c,r,s,l){return c(r,s,l)},voTct:"need_ack",FWGWC:t(1809),CVVES:function(c,r){return c&&r},RzhKT:t(1669),ncPPo:"ack_id",FfUDv:function(c,r){return c||r},aQdkH:function(c){return c()},ZWZKD:function(c,r,s){return c(r,s)},ieOUx:function(c,r){return c+r},zEfIu:function(c,r,s){return c(r,s)},edzYj:t(657),eOmtB:function(c,r){return c(r)},jiEsO:function(c,r){return c===r},PauFv:"esBCQ",xOBLA:function(c,r){return c instanceof r},flmWo:function(c,r,s,l){return c(r,s,l)},MfaCw:function(c,r){return c(r)},UTJqU:function(c,r){return c|r},TuXgN:function(c,r){return c(r)},FMWGd:function(c,r){return c+r},rTWdU:function(c,r){return c+r},LMZwy:function(c,r){return c+r},LkhjI:t(615)+t(1315)+"ge: ",cWkYQ:t(762),VADBX:t(1388),dmfrG:function(c,r){return c>r},MDPaz:t(601)+t(720)+"e",ceEhE:"JbPKx",usXGM:function(c,r,s){return c(r,s)},hvOvH:function(c,r){return c>>>r},DhPED:function(c,r){return c===r},sLBZO:t(320),QztgY:function(c,r){return c in r},nSevT:t(507),zWrXo:t(1619)+"2",xqoNt:function(c,r){return c+r},ILrrY:function(c,r){return c+r},FCwpF:function(c,r,s,l){return c(r,s,l)},Cihvs:function(c,r){return c<<r},ikhDv:function(c,r){return c+r},HEuSu:function(c,r){return c<<r},lgdtF:function(c,r){return c+r},Ecwql:function(c,r){return c+r},MQJDw:function(c,r){return c+r},pbCPw:function(c,r){return c<<r},SRiHe:function(c,r){return c+r},gFMeO:function(c,r){return c+r},eFLOU:function(c,r){return c&r},eKtDn:function(c,r){return c+r},BylQA:function(c,r){return c>>>r},WwKRq:function(c,r){return c+r},EspTs:function(c,r){return c&r},fAQHQ:function(c,r){return c>>>r},iOHud:function(c,r){return c&r},rVUdT:function(c,r){return c>>>r},yTcwZ:function(c,r){return c&r},tCpuN:function(c,r){return c&r},YyAiR:function(c,r){return c+r},UNifh:function(c,r){return c&r},vcIsH:function(c,r){return c===r},DfwrG:"Akpxx",wlgXc:function(c,r){return c<r},IQbps:function(c,r){return c|r},EEotC:function(c,r){return c<<r},cpSFh:function(c,r){return c&r},FWKfk:function(c,r){return c|r},EqqCe:function(c,r){return c&r},YKaod:function(c,r){return c<r},UuWrS:function(c,r){return c|r},DnAeq:function(c,r){return c>>>r},FdEWL:function(c,r){return c&r},AhgAt:function(c,r){return c&r},QHeKQ:function(c,r){return c<r},fNyci:function(c,r){return c+r},wbtkf:t(438)+"10|1|2|7"+t(515),yqqcI:t(338)+t(732),FHRtK:t(1341)+t(913),lNlby:"curvalue",TSHAC:t(1768),kzhSy:t(798),lrWPe:t(655),nDDfB:t(540)+t(323),nRpNk:function(c,r){return c(r)},QKRIm:"JIfIU",KnNkR:t(1495),luFvg:function(c,r,s){return c(r,s)},DGvif:function(c,r){return c+r},qRysC:function(c,r,s){return c(r,s)},mOdIZ:t(719)+t(389),ACPmy:t(1195)+"ame",GDHuG:t(603)+t(1543),cpQsh:"ALL",nKCfx:"INSTANT",xitIL:t(1200),rXLsW:function(c,r,s,l){return c(r,s,l)},LiLzM:function(c,r){return c(r)},cTIqg:t(1116),mBORv:function(c,r){return c+r},eUPLx:function(c,r){return c!==r},BVghF:"MBljr",KNIvX:t(1467),ofBTp:function(c,r){return c||r},NFuAF:t(1026),PDhRO:function(c,r){return c(r)},aJMIi:t(1373),dbaUo:function(c,r,s,l){return c(r,s,l)},yaLav:t(395)+"er_msgid",fiTkl:function(c,r){return c(r)},bDHVP:t(395)+"er_ttl",wjLwu:t(741)+"s",tOhov:t(613)+t(938)+"e",ZdFoq:function(c,r){return c(r)},qFKHW:function(c,r,s){return c(r,s)},oikLk:function(c,r){return c!==r},clZiP:"ctyRi",fQUyr:function(c){return c()},GeOuU:function(c){return c()},zqbvw:function(c,r){return c===r},rEana:function(c,r,s){return c(r,s)},kmfPm:function(c){return c()},zXDtY:"bNzJC",hNkNI:function(c){return c()},eJBZN:function(c,r,s){return c(r,s)},Feiad:function(c){return c()},XTtTI:function(c,r){return c===r},WlEHi:t(1726),nNtHA:t(682),TpZho:function(c){return c()},Xyluw:t(1479),jJIcQ:function(c,r,s){return c(r,s)},ptHrL:t(1060),JiDue:function(c,r,s){return c(r,s)},IGHCk:function(c,r){return c===r},kisAL:function(c,r){return c+r},oAKsi:"always",FxbwE:t(1405),WTImg:function(c,r){return c!=r},ReTLj:function(c,r){return c!==r},meUqJ:"jvFQr",tJgdU:function(c,r,s){return c(r,s)},jnZgE:t(1347)+t(606),ZjLQp:t(1791),SmJQk:function(c,r){return c===r},PRGUR:t(1117)+"rovide v"+t(1794),ktHWA:function(c,r){return c(r)},fARMf:t(1117)+t(761)+"s params"+t(1114)+"ket cons"+t(749)+"is undef"+t(619),KAeGC:t(528)+"t",LuXys:t(958)+t(371)+" reconnect",ftcVx:"online",ZaINm:t(1783),GhpYy:"pagehide",zJaqZ:t(1206),eUZAL:function(c,r,s){return c(r,s)},uPgKP:t(921),HgcUd:function(c,r){return c!==r},PBygh:function(c,r,s,l){return c(r,s,l)},oGnoo:"upgraden"+t(487),WRxwo:t(1819),gnYEn:function(c,r){return c==r},TTzgF:t(1828),gkUJF:t(648),pJCFh:function(c,r){return c!==r},sXDQp:t(989),eTWbD:t(425),LlISD:t(608),AnzQz:function(c,r){return c||r},xfvFF:t(1117)+t(1802)+t(1835)+t(1666)+t(1268),UGXQj:t(379),kPZuz:t(1807),uudAd:t(510)+"0",pgsay:function(c,r){return c-r},aDwfu:t(630),RNVgr:t(753),mNOFk:"QKHsg",gMuio:function(c,r){return c!==r},IzCIt:t(595),QiwoG:function(c,r){return c||r},AZVUy:function(c,r,s){return c(r,s)},NMTMV:function(c,r,s){return c(r,s)},StfKX:function(c,r){return c(r)},BNEka:function(c,r){return c(r)},meoqG:"FRONTIER>",KGxEv:function(c,r){return c*r},LtVoq:function(c,r){return c>r},Fxhsi:function(c,r,s){return c(r,s)},dgiod:function(c,r,s){return c(r,s)},YVPrM:t(1118),Apcma:t(907)+t(1021)+t(528)+t(1731)+t(1682),DkfbC:function(c,r,s){return c(r,s)},RvpVR:t(1632),SjVsf:t(582),HzFyM:function(c,r){return c!==r},RXiyq:"gZTWT",TActL:t(1254)+t(1636)+"onnecting",gPLnk:"0|2|4|3|1",wuacK:t(1718)+"2",UfIYd:function(c,r,s){return c(r,s)},fdnQD:t(1586),vpgoQ:function(c,r){return c!==r},Bmlca:t(951),vwwCX:t(661),gNFKQ:t(1176),cWFrJ:t(621)+t(1469),Tuxuc:t(581)+t(1677)+t(1811),cURCE:t(1117)+t(403)+t(1395)+t(1017)+t(356)+t(1093)+t(1526)+t(1137)+t(1476),bLRCO:function(c,r){return c==r},bqjMm:t(1343),RGVlw:function(c,r){return c!=r},GXwHe:function(c,r){return c instanceof r},OXKYj:function(c,r){return c instanceof r},idfbv:function(c,r){return c(r)},fOAvy:function(c,r){return c(r)},gaSTq:function(c,r){return c||r},hftLs:"please provide a"+t(1101)+t(732),VmRqW:function(c,r){return c instanceof r},QWrVf:function(c,r){return c instanceof r},TNdrO:function(c,r){return c(r)},rVzia:t(1091),nqIDv:t(482),BszbC:function(c,r){return c==r},lMOgL:t(1450)+t(1260)+t(1287),ccgKL:function(c,r){return c===r},Xnkpa:t(1096),ynFJz:t(1369)+t(1150)+"s",ZRomp:t(1151),QHHNE:function(c,r){return c/r},ZASEl:function(c,r){return c!=r},IljXo:t(1837),EjswH:function(c,r){return c!=r},CHkCM:function(c,r){return c===r},QaVPB:t(1243)+t(1024)+t(638)+"pe",zXzlD:function(c,r){return c===r},PLcqJ:"Object",mQZTm:function(c,r){return c!=r},zPlny:function(c,r){return c!=r},OmClq:t(1043)+t(1556)+t(1366),kJiwF:function(c,r){return c===r},OIggd:t(1591)+t(1438)+t(422),ThcbG:function(c,r){return c!=r},hjJcw:t(573)+t(1334)};Xt.r(Me),Xt.d(Me,{FWS:()=>Dm,CustomErrorEvent:()=>zl,createCloseEvent:()=>kt,ReconnectEvent:()=>Bl,createErrorEvent:()=>wt,decodedFrame:()=>Ft,createOpenEvent:()=>Wl,CustomCloseEvent:()=>Ul,createReconnectEvent:()=>ja,FrontierMessageEvent:()=>ql,encodeFrame:()=>Qt,createMessageEvent:()=>jl,OpenEvent:()=>Gl,ErrorCode:()=>wn,Event:()=>_r,MessageEvent:()=>Hl});let n="";function i(c=""){let r=t,s="02",l=""+Date[r(559)](),h=n||(n=e[r(347)](u,c)),m=Math[r(1e3)]()[r(1518)](16)[r(899)](-6);return e.UXOZa(e.UXOZa(e[r(680)](s,l),h),m)}function o(){let c=t;return e.tbDLh(e[c(1463)](1e4,Date[c(559)]()),Math[c(1280)](1e4*Math.random()))}function a(c){let r=t;return(e[r(795)](Array,8)[r(1770)]("0")+parseInt(c,10)[r(1518)](2))[r(899)](-8)}function d(c){let r=t;return e[r(635)](e[r(367)](Array,4)[r(1770)]("0"),e[r(564)](parseInt,c,2)[r(1518)](16)).slice(-4)}function f(c){let r=t,s=c[r(1622)](/\./)[r(424)](m=>a(m)),l=[];return l[0]=e[r(367)](d,s[0]+s[1]),l[1]=e[r(795)](d,e[r(635)](s[2],s[3])),[e[r(990)],e[r(990)],e.qZggh,e.qZggh,e[r(990)],e[r(336)],l[0],l[1]][r(1770)]("")}function u(c){let r=t;if(e[r(330)](e.DWnGD,e[r(448)])){let s=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.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(347)](f,c):l?e[r(1637)](x,c):r(1432)+r(1432)+r(1432)+r(1432)}else this[r(1776)]=!1,_0x17b20c(this[r(1378)+"ionTimeo"+r(1051)]),_0x1a01c3()}function x(c){let r=t,s="",l=[],h=0,m=0,y=!0,S=e[r(990)];if(e[r(1004)](c[r(1611)]("::"),-1)){let g=c.split("::");for(let O=0;O<g.length;O++){let B=g[O];if(e.uiZPl(B[r(1611)](":"),0)){let F=B[r(1622)](":");y&&(h=F[r(1511)]),m+=F[r(1511)];for(let $=0;e[r(1435)]($,F.length);$++)if(e[r(1654)](4,F[$][r(1511)])){if(e[r(330)](e[r(1713)],e[r(1494)]))return this._qosDB[r(1599)];{let pe=S.substring(0,e[r(1263)](4,F[$].length)),de=pe[r(1408)](F[$]);l[r(567)](de)}}else l[r(567)](F[$]);y=!1}else{if(e[r(624)](4,B.length)){let F=S.substring(0,e.ODaRh(4,B[r(1511)])),$=F.concat(B);l[r(567)]($)}else l[r(567)](B);y&&(h+=1),m+=1,y=!1}}let L="";for(let O=0;e.qYROV(O,e.IVxdh(8,m));O++)L=L[r(1408)](S);for(let O=0;O<l[r(1511)];O++)e.JICGu(O,h)&&(s=s[r(1408)](L)),s=s.concat(l[O]);return s}{let g=c[r(1622)](":");for(let L=0;L<g[r(1511)];L++){let O=g[L];if(e[r(624)](4,g[L][r(1511)])){let B=S.substring(0,e[r(1723)](4,g[L][r(1511)])),F=B[r(1408)](O);s=s[r(1408)](F)}else s=s.concat(O)}return s}}function p(c,r){let s=t,l=c.key;e[s(1654)](void 0,l)&&(e[s(1161)](ae,r,10),e[s(1226)](qe,r,l));let h=c[s(1595)];e[s(470)](void 0,h)&&(ae(r,18),qe(r,h))}function w(c){let r=t,s={};e:for(;!e[r(795)](J,c);){let l=e[r(367)](ee,c);switch(l>>>3){case 0:break e;case 1:s[r(1683)]=e[r(564)](Ee,c,e[r(842)](ee,c));break;case 2:s[r(1595)]=e[r(1161)](Ee,c,e[r(842)](ee,c));break;default:e[r(1833)](T,c,e[r(677)](7,l))}}if(e.JICGu(void 0,s[r(1683)]))throw new Error("Missing "+r(1786)+" field: key");if(e[r(1460)](void 0,s[r(1595)]))throw new Error(e[r(1068)]);return s}function b(c){let r=t,s=e[r(1148)](P);return e[r(1515)](_,c,s),N(s)}function _(c,r){let s=t,l={gtaBJ:function(be,Ae){return be+Ae},QVXba:function(be,Ae){return e[V(1020)](be,Ae)},iKBwQ:function(be,Ae){return be*Ae},XafaC:function(be,Ae){return e[V(1039)](be,Ae)}},h=c[s(812)];e.fZkSw(void 0,h)&&(ae(r,8),e[s(1132)](lt,r,h));let m=c[s(1572)];m!==void 0&&(e.jOVsr(ae,r,16),lt(r,m));let y=c.service;e[s(1654)](void 0,y)&&(e[s(970)](ae,r,24),e[s(1515)](lt,r,e[s(1214)](R,y)));let S=c.method;e[s(1654)](void 0,S)&&(e[s(1833)](ae,r,32),e[s(970)](lt,r,e.RpXMX(R,S)));let g=c[s(497)];if(g!==void 0)for(let be of g){if(e[s(1174)](e.AVZCR,e.fIpuk))return _0x41223d?this.toBytesLE():this[s(1320)+"E"]();{e[s(1461)](ae,r,42);let Ae=e.tSYcb(P);e[s(1358)](p,be,Ae),e.aSqEL(ae,r,Ae.limit),C(r,Ae),e.LPvCo(D,Ae)}}let L=c[s(391)+"ncoding"];e.mtimn(void 0,L)&&(e[s(1461)](ae,r,50),e[s(1229)](qe,r,L));let O=c.payloadType;if(O!==void 0)if(e[s(330)](e[s(851)],e.GnLHy)){let be=_0x4862de.bytes,Ae=_0x1faf9a[s(417)],yn=_0x397529[s(975)],Tt=l[s(1308)](Ae,_0x3bfefa);if(l[s(1456)](Tt,be[s(1511)])){let br=new _0x27debe(l[s(332)](2,Tt));br[s(1753)](be),_0x13bd3f[s(604)]=br}return _0x36d75e.offset=Tt,l[s(385)](Tt,yn)&&(_0x1ffc93[s(975)]=Tt),Ae}else e[s(652)](ae,r,58),e.KXfEh(qe,r,O);let B=c[s(1177)];e[s(810)](void 0,B)&&(e[s(1080)](ae,r,66),e[s(1461)](ae,r,B[s(1511)]),e[s(1391)](le,r,B));let F=c[s(1325)];if(F!==void 0)if(e.FGZNe(e[s(1580)],e[s(690)])){if(this._options[s(767)+"utoRecon"+s(378)]||this[s(402)+s(554)])return;this["_handleR"+s(1260)]()}else e[s(1358)](ae,r,74),e[s(1833)](qe,r,F);let $=c[s(1410)+s(433)];e[s(1654)](void 0,$)&&(e[s(652)](ae,r,82),e[s(1226)](qe,r,$));let pe=c[s(701)];if(e[s(1654)](void 0,pe)){if(e[s(1633)](e[s(617)],e[s(617)]))return rxVpOu[s(1568)](_0x48992f,_0x576712[s(939)](rxVpOu[s(795)](_0x2385d3,this),_0xf252d3));e[s(1833)](ae,r,90),qe(r,pe)}let de=c[s(1205)+"e"];de!==void 0&&(e[s(1524)](ae,r,96),lt(r,e[s(1568)](R,de)))}function v(c){let r=t,s={IFjPG:function(l,h,m){return l(h,m)}};if(e[r(1174)](e.kHBbT,e[r(633)]))CKRkbC.IFjPG(_0x40468e,_0x42ad3a,90),CKRkbC[r(1001)](_0x150b4a,_0x48815a,_0x4cd33e);else return e[r(795)](I,e[r(1836)](U,c))}function I(c){let r=t,s={JQmob:function(l,h,m){return l(h,m)}};if(e[r(1050)](e[r(1038)],e[r(1702)]))JmHaBN[r(985)](_0x2851eb,_0x3309f5,96),JmHaBN[r(985)](_0x536310,_0x5326c3,_0xf93d1(_0x39bd62));else{let l={};e:for(;!e[r(1214)](J,c);){let h=e[r(842)](ee,c);switch(e[r(589)](h,3)){case 0:break e;case 1:l.SeqID=st(c,!0);break;case 2:l[r(1572)]=e.Xazae(st,c,!0);break;case 3:l.service=e[r(1330)](ee,c);break;case 4:l[r(1803)]=e[r(409)](ee,c);break;case 5:if(e.CSQlY(e[r(512)],e[r(1592)])){let m=A(c);(l[r(497)]||(l.headers=[]))[r(567)](w(c)),c[r(975)]=m;break}else _0x36ca07(_0x49b9be,16),_0x120504(_0x11d255,_0x14bf70);case 6:l[r(391)+r(1143)]=e[r(1515)](Ee,c,ee(c));break;case 7:l["payloadT"+r(1624)]=Ee(c,e.iyqHg(ee,c));break;case 8:l[r(1177)]=e[r(322)](oe,c,e[r(1637)](ee,c));break;case 9:l[r(1325)]=e[r(1348)](Ee,c,e[r(731)](ee,c));break;case 10:l.serverTiming=e[r(872)](Ee,c,ee(c));break;case 11:l[r(701)]=e.tBZps(Ee,c,ee(c));break;case 12:l[r(1205)+"e"]=e[r(409)](ee,c);break;default:e[r(1764)](T,c,e[r(1766)](7,h))}}if(e[r(1300)](void 0,l[r(812)]))throw new Error(e[r(692)]);if(e[r(330)](void 0,l[r(1572)]))throw new Error(e.edMXh);if(e[r(1460)](void 0,l[r(1566)]))throw new Error("Missing "+r(1786)+r(432)+r(1566));if(l[r(1803)]===void 0)throw new Error(e[r(698)]);return l}}function A(c){let r=t,s=e.ObIhR(ee,c),l=c.limit;return c[r(975)]=e.tbDLh(c[r(417)],s),l}function T(c,r){let s=t;switch(r){case 0:for(;e[s(489)](128,e.iyqHg(H,c)););break;case 2:e[s(1348)](K,c,e[s(1286)](ee,c));break;case 5:e[s(970)](K,c,4);break;case 1:e[s(383)](K,c,8);break;default:throw new Error(e[s(1798)](s(597)+s(1232)+s(629),r))}}function R(c){let r=t,s={WtmFg:function(l,h,m){return e[V(399)](l,h,m)},qiavG:function(l){return l()},YLbKr:function(l,h,m){return e[V(1461)](l,h,m)},wCjYP:function(l,h){return l(h)}};if(e[r(881)](e.SKOGT,"fUdav")){oQvkUu[r(1383)](_0xdf6368,_0x4ad20d,42);let l=oQvkUu[r(1485)](_0x39343c);_0x387e7e(_0x4cdca7,l),_0x1b3fc7(_0x5025e5,l.limit),oQvkUu[r(1569)](_0x57738a,_0x48f022,l),oQvkUu[r(1559)](_0xdc5804,l)}else return c|=0,{low:c,high:e[r(1075)](c,31),unsigned:e[r(1412)](c,0)}}let E=[];function P(){let c=t,r=E[c(1523)]();return r?(r[c(417)]=r[c(975)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(c){E[t(567)](c)}function U(c){return{bytes:c,offset:0,limit:c[t(1511)]}}function N(c){let r=t,s=c[r(604)],l=c[r(975)];return s[r(1511)]===l?s:s[r(1104)](0,l)}function K(c,r){let s=t;if(e[s(1380)](c[s(417)]+r,c[s(975)]))throw new Error(e[s(335)]);c[s(417)]+=r}function J(c){let r=t;return e[r(923)](c[r(417)],c[r(975)])}function ie(c,r){let s=t;if(e[s(624)](e.pqIbI,e[s(591)]))this[s(845)]=_0x4c4093,this[s(884)]=_0x4a57c9,this._qosDB=_0x86cfe4;else{let l=c[s(604)],h=c[s(417)],m=c.limit,y=e[s(1602)](h,r);if(e[s(1004)](y,l[s(1511)])){let S=new Uint8Array(e.hFeZC(2,y));S[s(1753)](l),c[s(604)]=S}return c[s(417)]=y,e[s(1004)](y,m)&&(c[s(975)]=y),h}}function Y(c,r){let s=t;if(e[s(1337)]!==s(1710)){let l=c.offset;if(e[s(1004)](e[s(680)](l,r),c[s(975)]))throw new Error(e[s(1548)]);return c[s(417)]+=r,l}else _0x2b1cb1.d=(l,h)=>{for(var m in h)_0x45601f.o(h,m)&&!_0x4ab0a6.o(l,m)&&_0x2a1aec.defineProperty(l,m,{enumerable:!0,get:h[m]})}}function oe(c,r){let s=t,l={VOjYV:function(h,m){return e[V(803)](h,m)},EAHzh:e[s(908)],opRTe:s(891)+s(329),IAbRL:function(h,m){return e[s(330)](h,m)},upubn:s(320)};if(e[s(1053)](s(1571),"aSQxW")){if(KHeKeU[s(466)](_0x382fd6,KHeKeU.EAHzh))return _0x45688c.get(_0x5b4226);if(KHeKeU[s(466)](_0x12fddd,KHeKeU[s(1066)]))return _0x5d521b[s(891)+"oreNames"]||_0x1f1ca4[s(1326)](_0x5dcb47);if(KHeKeU[s(1491)](_0x480044,KHeKeU[s(928)]))return _0x55ffef["objectSt"+s(329)][1]?void 0:_0x5da4f2[s(891)+s(538)](_0x316120[s(891)+s(329)][0])}else{let h=e.oOocw(Y,c,r);return c[s(604)][s(1104)](h,e[s(1602)](h,r))}}function le(c,r){let s=t;if(e[s(852)]===e[s(953)])this["maxLossC"+s(883)]=_0x17846f,this[s(1215)]=0;else{let l=e[s(1764)](ie,c,r[s(1511)]);c[s(604)][s(1753)](r,l)}}function Ee(c,r){let s=t,l=e[s(1764)](Y,c,r),h=String[s(339)+s(710)],m=c[s(604)],y="\uFFFD",S="";for(let g=0;e[s(1319)](g,r);g++){let L=m[e[s(680)](g,l)],O,B,F,$;if(e[s(1377)](128,L)===0)S+=e.kTNMC(h,L);else if(e[s(330)](e.EBahx(224,L),192))e.OupQH(e[s(1602)](g,1),r)?S+=y:(O=m[e[s(1191)](e.UXOZa(g,l),1)],e.UTKnG(e[s(677)](192,O),128)?S+=y:($=e[s(1019)](e[s(489)](31,L),6)|e[s(1823)](63,O),e.cnwRh($,128)?S+=y:(S+=h($),g++)));else if(e[s(916)](240&L,224))if(g+2>=r)S+=y;else if(e[s(771)](e.xdgAw,e[s(525)]))if(e[s(1537)](_0x1ec4e1[s(1177)],_0x386f2b)){let pe=this[s(415)][s(391)+"ncoding"]instanceof _0x51fc3d?{force:!!this[s(415)].payloadEncoding.force,encoding:this._options[s(391)+s(1143)].encoding?this[s(415)][s(391)+s(1143)][s(806)][s(1631)](/\s/g,"")[s(850)+s(1774)]():""}:{force:!1,encoding:this._options[s(391)+s(1143)]?this[s(415)][s(391)+"ncoding"][s(1631)](/\s/g,"")[s(850)+s(1774)]():""},de=_0x307c17[s(391)+s(1143)]?_0x235a02["payloadE"+s(1143)][s(1631)](/\s/g,"")[s(850)+"ase"]():"",be=e[s(779)](this[s(415)]["payloadT"+s(1624)],_0x15628e)?{force:!!this[s(415)][s(1009)+s(1624)][s(831)],type:this[s(415)][s(1009)+s(1624)][s(1097)]?this[s(415)][s(1009)+"ype"][s(1097)].replace(/\s/g,"")[s(850)+s(1774)]():""}:{force:!1,type:this[s(415)][s(1009)+"ype"]?this[s(415)][s(1009)+s(1624)].replace(/\s/g,"").toLowerCase():""},Ae=_0x51c374[s(1009)+s(1624)]?_0x40a75a["payloadT"+s(1624)].replace(/\s/g,"")[s(850)+s(1774)]():"",yn=be[s(831)]?be[s(1097)]:Ae||be[s(1097)],Tt=pe.force?pe[s(806)]:de||pe[s(806)],br=[e[s(1291)],s(776)+s(825),e[s(1788)],"string"],Ya=[e[s(1489)],e.hLcdr];this._options["enableTr"+s(707)+s(1156)+"ad"]&&br[s(632)](yn)&&(!Tt||Ya[s(632)](Tt))?_0x13b99c[s(1234)+"oad"]=_0x47fe1b(_0x1be1f2[s(1177)],0,_0x4fbd3d[s(1177)][s(1826)+"th"]):_0x371a64[s(1234)+s(789)]=""}else _0x40b856[s(1234)+"oad"]="";else O=m[e[s(1191)](e[s(1602)](g,l),1)],B=m[e[s(786)](g+l,2)],e[s(624)](e[s(1490)](e.TKGXF(O,e.cZBQv(B,8)),49344),32896)?S+=y:($=e.xZlPS(e[s(479)](e.awMeu(e[s(666)](15,L),12),e[s(733)](63&O,6)),e[s(735)](63,B)),e.ypDeM($,2048)||e[s(923)]($,55296)&&e[s(696)]($,57343)?S+=y:(S+=h($),g+=2));else e.uKIGa(248&L,240)?e[s(1416)](e[s(1626)](g,3),r)?S+=y:(O=m[e[s(1346)](g+l,1)],B=m[e[s(635)](g,l)+2],F=m[e.YRPIf(e[s(1602)](g,l),3)],e.dRgYR(e[s(1241)](e[s(1241)](O,B<<8),e[s(1129)](F,16)),12632256)!==8421504?S+=y:($=e[s(1241)](e[s(479)](e[s(677)](7,L)<<18,(63&O)<<12),e[s(733)](63&B,6))|e.NeXAE(63,F),e[s(1319)]($,65536)||e[s(1020)]($,1114111)?S+=y:($-=65536,S+=e[s(1080)](h,e[s(1125)](e.VbfrB($,10),55296),e.BxCRp(e.mDZJz(1023,$),56320)),g+=3))):S+=y}return S}function qe(c,r){let s=t,l=r[s(1511)],h=0;for(let S=0;e.qYROV(S,l);S++){let g=r[s(1535)+"At"](S);e[s(1152)](g,55296)&&e[s(696)](g,56319)&&e.cnwRh(S+1,l)&&(g=e[s(1217)](e[s(1125)](e[s(394)](g,10),r[s(1535)+"At"](++S)),56613888)),h+=e[s(1435)](g,128)?1:e[s(503)](g,2048)?2:e[s(1435)](g,65536)?3:4}e[s(1229)](ae,c,h);let m=e[s(1358)](ie,c,h),y=c.bytes;for(let S=0;e[s(503)](S,l);S++){let g=r[s(1535)+"At"](S);if(e[s(1416)](g,55296)&&e[s(1839)](g,56319)&&e.iwKBp(e[s(406)](S,1),l)&&(g=e.SyMKf(e[s(1208)](e.cZBQv(g,10),r.charCodeAt(++S)),56613888)),e[s(1253)](g,128))y[m++]=g;else if(e.bCqgi(e.ldEuw,e[s(1621)])){let L=this[s(1022)][s(1598)](this[s(1142)]),O=_0x58319d.parse(e[s(903)](L,"{}"));return _0x499996[s(440)](O)}else{if(e[s(1529)](g,2048))y[m++]=e[s(1279)](e.KHPpx(e[s(1421)](g,6),31),192);else{if(e[s(930)](e[s(858)],e[s(524)]))return!0;g<65536?y[m++]=e[s(508)](e.sjxuT(e.VbfrB(g,12),15),224):(y[m++]=e.lnOeP(e.wBBmq(g,18)&7,240),y[m++]=e[s(1241)](e[s(1789)](g,12)&63,128)),y[m++]=e.CxfYQ(e.wBBmq(g,6),63)|128}y[m++]=e[s(1071)](e[s(1488)](63,g),128)}}}function C(c,r){let s=t,l=ie(c,r[s(975)]),h=c.bytes,m=r[s(604)];for(let y=0,S=r[s(975)];e[s(813)](y,S);y++)h[e[s(1626)](y,l)]=m[y]}function H(c){let r=t;if(e[r(330)](r(668),e[r(350)]))this["_miniNavigatorOn"+r(1769)]=_0x209f4c,_0x5f0f5c?this[r(1582)+r(870)]():this[r(1582)+"ffLine"]();else return c[r(604)][e[r(1161)](Y,c,1)]}function j(c,r){let s=t,l=e.hDEwf(ie,c,1);c[s(604)][l]=r}function ee(c){let r=t;if(e.sGjLB(e[r(426)],e.bHdRg))_0x54a07d-=65536,_0x36a2cc+=e[r(1239)](_0x13d3d8,e[r(1789)](_0x4c80e6,10)+55296,e[r(1346)](e.sXprw(1023,_0x8cbe10),56320)),_0x40bd6b+=3;else{let s=0,l=0,h;do h=e[r(556)](H,c),e.gPivP(s,32)&&(l|=e[r(1019)](127&h,s)),s+=7;while(e[r(1377)](128,h));return l}}function ae(c,r){let s=t;for(r>>>=0;e[s(1152)](r,128);)j(c,e[s(666)](127,r)|128),r>>>=7;e[s(1515)](j,c,r)}function st(c,r){let s=t,l=0,h=0,m=0,y;return y=e[s(1637)](H,c),l=e[s(550)](127,y),128&y&&(y=e[s(1273)](H,c),l|=e[s(1019)](e.mDZJz(127,y),7),128&y&&(y=H(c),l|=e[s(1578)](e[s(363)](127,y),14),128&y&&(y=e[s(974)](H,c),l|=e[s(733)](e[s(1377)](127,y),21),128&y&&(y=e[s(842)](H,c),h=e[s(1484)](127,y),128&y&&(y=H(c),h|=e[s(866)](127,y)<<7,e.KHPpx(128,y)&&(y=e[s(782)](H,c),h|=e[s(1129)](127&y,14),e.AaQJw(128,y)&&(y=e.TTirx(H,c),h|=e.ecfzz(127,y)<<21,e.mDZJz(128,y)&&(y=H(c),m=127&y,128&y&&(y=e[s(1058)](H,c),m|=e[s(1578)](e[s(995)](127,y),7)))))))))),{low:e.czqRE(l,h<<28),high:e[s(479)](e[s(589)](h,4),m<<24),unsigned:r}}function lt(c,r){let s=t,l=r[s(1272)]>>>0,h=e[s(361)](e[s(1482)](r[s(1272)],28),e.JDGGU(r.high,4))>>>0,m=e[s(537)](r[s(837)],24),y=e[s(1670)](0,m)?e[s(1544)](0,h)?e[s(1687)](l,16384)?e[s(756)](l,128)?1:2:e[s(1426)](l,2097152)?3:4:e[s(1529)](h,16384)?e[s(813)](h,128)?5:6:e[s(1202)](h,2097152)?7:8:e[s(1202)](m,128)?9:10,S=e[s(1391)](ie,c,y),g=c[s(604)];switch(y){case 10:g[S+9]=e[s(1766)](e[s(1146)](m,7),1);case 9:g[e[s(495)](S,8)]=e[s(868)](9,y)?e[s(936)](128,m):e[s(1228)](127,m);case 8:g[e[s(1223)](S,7)]=e[s(1633)](8,y)?e[s(1241)](e[s(1482)](h,21),128):e[s(1415)](e.fleJX(h,21),127);case 7:g[e[s(786)](S,6)]=e.mtimn(7,y)?e.ZEXca(e[s(1011)](h,14),128):e[s(667)](h,14)&127;case 6:g[e[s(1486)](S,5)]=e[s(683)](6,y)?e[s(416)](e[s(412)](h,7),128):e[s(1285)](e.ZvImf(h,7),127);case 5:g[S+4]=y!==5?e[s(558)](128,h):e[s(671)](127,h);case 4:g[e[s(635)](S,3)]=e[s(1574)](4,y)?e.OPwUG(l>>>21,128):e[s(511)](e.Vjjsk(l,21),127);case 3:g[e[s(1486)](S,2)]=y!==3?e[s(778)](l>>>14,128):l>>>14&127;case 2:g[e.SfwGr(S,1)]=e[s(1053)](2,y)?e[s(1240)](l>>>7,128):e.IVVrd(l>>>7,127);case 1:g[S]=e.NCAuK(1,y)?e[s(410)](128,l):e[s(1742)](127,l)}}function Ft(c){return e[t(842)](v,c)}function Qt(c){return e[t(1589)](b,c)}let mn=65536,qn=e[t(463)],mt=e.xLJTq(mn,mn),wr=e.xLJTq(mt,mt),Be=e[t(1311)](wr,2),me=String[t(501)+"e"][t(1535)+"At"];class ce{constructor(r,s,l){let h=t;this[h(413)]=!0,this[h(1272)]=e[h(746)](0,r),this[h(837)]=0|s,this[h(340)]=!!l}static[t(413)](r){return r&&e[t(930)](!0,r.isLong)}static[t(1015)](r,s,l){return new ce(r,s,l)}static[t(1138)+"s"](r,s,l){let h=t;return l?ce[h(1138)+h(909)](r,s):ce[h(1138)+h(1122)](r,s)}static[t(1138)+t(909)](r,s){let l=t;return new ce(e[l(479)](e[l(461)](e[l(1241)](r[0],e[l(1284)](r[1],8)),r[2]<<16),r[3]<<24),e[l(746)](e[l(557)](r[4],r[5]<<8),r[6]<<16)|e[l(1082)](r[7],24),s)}static[t(1138)+t(1122)](r,s){let l=t;return new ce(e[l(479)](e.hbGtG(e[l(1042)](r[4]<<24,e[l(1082)](r[5],16)),e[l(1129)](r[6],8)),r[7]),e[l(410)](e[l(1042)](e[l(508)](r[0]<<24,r[1]<<16),e[l(1284)](r[2],8)),r[3]),s)}static[t(860)](r){let s=t;if(e[s(1398)]("XEJOA",e[s(892)])){let l=this[s(837)],h=this[s(1272)];return[e[s(550)](255,h),e.pniNM(e[s(537)](h,8),255),e[s(708)](h>>>16,255),h>>>24,e[s(677)](255,l),e[s(443)](e.sJbui(l,8),255),e[s(1063)](e.Pwdjm(l,16),255),l>>>24]}else return r===qn?ft:new ce(e.bGoDa(e[s(1073)](e[s(1240)](e[s(361)](me[s(1603)](r,0),e.Xftyi(me[s(1603)](r,1),8)),e[s(1019)](me[s(1603)](r,2),16)),e[s(1016)](me[s(1603)](r,3),24)),0),(e[s(747)](me[s(1603)](r,4),e[s(672)](me.call(r,5),8))|e[s(1792)](me.call(r,6),16)|e[s(1578)](me.call(r,7),24))>>>0,!0)}[t(480)](){let r=t;return String[r(339)+"Code"](e[r(549)](255,this[r(1272)]),e[r(912)](e[r(412)](this[r(1272)],8),255),e.PIaED(e[r(1482)](this[r(1272)],16),255),e[r(689)](this[r(1272)],24),255&this[r(837)],e[r(783)](this[r(837)],8)&255,this.high>>>16&255,e[r(783)](this[r(837)],24))}static[t(686)+"er"](r,s=!0){let l=t;if(e[l(1058)](isNaN,r))return s?jg:ft;if(s){if(e[l(1416)](r,wr))return Kg}else{if(e.ZoWKd(r,-Be))return $g;if(e.BxCRp(r,1)>=Be)return Wg}return ce.fromBits(r%mt|0,e[l(716)](e[l(1186)](r,mt),0),s)}[t(1691)](){let r=t;return this[r(340)]?e[r(934)](e[r(1778)](this[r(837)],0)*mt,e.tOQNb(this.low,0)):e[r(1644)](this.high*mt,this[r(1272)]>>>0)}[t(1692)](){let r=t;return e[r(1475)](0,this[r(837)])&&e[r(771)](0,this[r(1272)])}add(r){let s=t;ce[s(413)](r)||(r=ce.fromNumber(r));let l=this.high>>>16,h=e[s(780)](65535,this[s(837)]),m=e[s(1816)](this[s(1272)],16),y=e[s(978)](65535,this[s(1272)]),S=e[s(1011)](r.high,16),g=65535&r[s(837)],L=e[s(997)](r[s(1272)],16),O=e.UiUPE(65535,r.low),B=0,F=0,$=0,pe=0;return pe+=e[s(1779)](y,O),$+=pe>>>16,pe&=65535,$+=e.JrReb(m,L),F+=e[s(1034)]($,16),$&=65535,F+=e[s(495)](h,g),B+=e.qdrnM(F,16),F&=65535,B+=l+S,B&=65535,ce.fromBits(e[s(1560)](e[s(370)]($,16),pe),e.vjLEp(B<<16,F),this[s(340)])}[t(1655)](r){let s=t;return ce[s(413)](r)||(r=ce[s(686)+"er"](r)),e[s(1633)](this.unsigned,r[s(340)])&&e[s(1174)](e[s(659)](this[s(837)],31),1)&&e[s(412)](r[s(837)],31)===1?!1:e[s(803)](this[s(837)],r.high)&&e[s(596)](this[s(1272)],r[s(1272)])}[t(1671)](){let r=t;if(e.KvTlD(e[r(1759)],e[r(1759)]))return e.SLRQL(-1,this[r(1272)])&&this[r(837)]===-1?ce.fromBits(0,0,this.unsigned):e.bCqgi(-1,this[r(1272)])?ce[r(1015)](0,e[r(1159)](this[r(837)],1),this.unsigned):ce[r(1015)](this[r(1272)]+1,this[r(837)],this[r(340)]);{let s=0,l={};for(let h=0;e[r(1573)](h,_0x365f04[r(1511)]);h++)l[_0x4d6abe[h][r(1195)+r(887)]]=e[r(1589)](_0x5b1a57,_0x30dfa1[h][r(1195)+r(887)]),s+=e[r(1208)](14,l[_0x2135ef[h]["cursor_n"+r(887)]]);return[s,l]}}[t(1386)](r){return r?this.toBytesLE():this.toBytesBE()}toBytesLE(){let r=t,s=this.high,l=this.low;return[e.rHhXt(255,l),e.fzvGv(l>>>8,255),e[r(1231)](e[r(1213)](l,16),255),l>>>24,e[r(1823)](255,s),e[r(511)](e[r(344)](s,8),255),e[r(1742)](e.qNQiQ(s,16),255),e[r(412)](s,24)]}[t(1320)+"E"](){let r=t,s=this[r(837)],l=this[r(1272)];return[e[r(562)](s,24),e[r(1414)](e[r(726)](s,16),255),e[r(735)](e.MQXbh(s,8),255),e[r(1056)](255,s),e[r(886)](l,24),e[r(838)](e[r(997)](l,16),255),e[r(667)](l,8)&255,e.vlODd(255,l)]}}let ft=new ce(0,0,!1),jg=new ce(0,0,!0),Wg=ce[t(1015)](-1,2147483647,!1),Kg=ce[t(1015)](-1,-1,!0),$g=ce[t(1015)](0,-2147483648,!1);var wn=(function(c){let r=t;if(e[r(1606)](e[r(861)],e[r(861)]))_0x38704a[_0x3fed59++]=e[r(1531)](_0x10b85d>>12,224),_0x235d79[_0x5b3c08++]=e[r(1241)](e.axwih(_0x103138>>6,63),128),_0x35176f[_0x85af31++]=e[r(778)](e.vlODd(63,_0x4d950e),128);else{let s=e[r(1364)][r(1622)]("|"),l=0;for(;;){switch(s[l++]){case"0":c[c[r(1643)+r(327)]=5004]=r(1643)+r(327);continue;case"1":c[c[e.Uzihf]=5001]=e[r(1498)];continue;case"2":c[c[e[r(1629)]]=5002]=e.VYhdC;continue;case"3":c[c[e.ZuxTy]=5003]=r(618)+r(943)+"R";continue;case"4":c[c[e.PFjqB]=5005]=e[r(914)];continue;case"5":return c}break}}})({});class _r{constructor(r){let s=t;this.type=r,this[s(1055)]=null}}class Bl extends _r{constructor(r,s){let l=t;super(r),this[l(1500)]=s&&s.message||null}}class zl extends _r{constructor(r,s){let l=t;super(r),this.error=s&&s[l(1746)]||null,this[l(988)]=s&&s.colno||0,this[l(829)]=s&&s.filename||"",this[l(965)]=s&&s[l(965)]||0,this[l(1500)]=s&&s[l(1500)]||"",this[l(1373)]=s&&s[l(1373)]||5001}}class Ul extends _r{constructor(r,s){let l=t,h=e[l(1356)][l(1622)]("|"),m=0;for(;;){switch(h[m++]){case"0":this[l(1061)+l(1755)]=s&&s[l(1061)+l(1755)]||!1;continue;case"1":this[l(828)]=s&&s.reason||"";continue;case"2":this[l(1373)]=s&&s[l(1373)]||0;continue;case"3":this[l(375)]=s&&s[l(375)]||!1;continue;case"4":super(r);continue}break}}}class Hl extends _r{constructor(r,s){let l=t;super(r),this[l(960)]=s&&s.data||null}}class ql extends Hl{constructor(r,s){let l=t;super(r),this.data=s&&s[l(960)]||null,this[l(1500)]=s&&s[l(1500)]||null}}class Gl extends _r{constructor(r,s){let l=t;super(r),this[l(960)]=s&&s[l(960)]||null}}function wt(c,{message:r,code:s,error:l}){return new zl(c,{message:r,code:s,error:l})}function kt(c,{code:r,reason:s,wasClean:l,willReconnect:h}){return new Ul(c,{code:r,reason:s,wasClean:l,willReconnect:h})}function jl(c,{data:r,message:s}){return new ql(c,{data:r,message:s})}function Wl(c,{data:r}){return new Gl(c,{data:r})}function ja(c,{message:r}){return new Bl(c,{message:r})}class Kl{constructor(r,s){let l=t;this[l(1155)+"s"]=r,this.maxRetries=s,this[l(1736)+l(901)]=0,this[l(1167)+l(758)+l(610)+"t"]=0}[t(1248)+t(902)+"fig"](){let r=t;this[r(1736)+r(901)]=0,this[r(1167)+r(758)+r(610)+"t"]=0}resetTries(){let r=t;this[r(1167)+r(758)+r(610)+"t"]=0}[t(478)+t(1025)+"nt"](){let r=t;return this[r(1155)+"s"][this[r(1736)+r(901)]]}[t(478)+t(1025)+t(1134)+t(883)](){let r=t;return this[r(1167)+r(758)+r(610)+"t"]}[t(882)+"chMaxTries"](){let r=t;return!!(e.TiDMR(this[r(1736)+r(901)],this[r(1155)+"s"][r(1511)])||e[r(1563)](this[r(1736)+r(901)],e[r(1219)](this.endpoints[r(1511)],1))&&this[r(1167)+r(758)+r(610)+"t"]===this[r(1634)+"es"])}[t(1594)+t(750)+t(401)+t(1550)+t(1664)](){let r=t;return e[r(1371)](this[r(1736)+r(901)],this[r(1155)+"s"][r(1511)])?!0:this[r(1167)+"ndpointT"+r(610)+"t"]>this[r(1634)+"es"]}[t(641)+t(1607)+"pointAnd"+t(1838)+t(502)](){let r=t;return this["currentE"+r(758)+"riesCount"]=1,this[r(1736)+r(901)]++,this[r(1155)+"s"][this["currentI"+r(901)]]}[t(478)+t(1025)+t(1697)+"ateCount"](){let r=t;if(r(1103)!==r(1365))return this[r(1167)+r(758)+r(610)+"t"]++,this[r(478)+r(1025)+"nt"]();{let s=e.TTirx(_0x17d6b8,_0x23e9de);this[r(1545)]&&e[r(596)](this[r(1545)][r(1558)+"te"],this[r(1547)])&&(this[r(1545)]&&this[r(1545)].send(s),this[r(1270)](e[r(1318)],_0x228564))}}}let yr=(e.lGVbw(e.nxLRQ,typeof globalThis)&&e.vcIsH(t(1837),globalThis[t(1447)+t(1628)][t(913)])||e[t(547)](t(1583)+"d",typeof window)&&e[t(1740)]===window[t(1447)+t(1628)][t(913)])&&e[t(777)](e[t(1733)],typeof document),Gn=e.nxLRQ!=typeof globalThis&&(e[t(1393)](t(1189),globalThis[t(1447)+"tor"].name)||e[t(1690)](e.QaVPB,globalThis.constructor[t(913)]))&&e[t(1342)](e[t(1733)],typeof tt),wi=(t(1583)+"d"!=typeof globalThis&&e.zXzlD(e.PLcqJ,globalThis[t(1447)+"tor"][t(913)])||e[t(916)](e.nxLRQ,typeof globalThis)||e[t(1367)](e[t(1733)],typeof globalThis)&&!!globalThis[t(387)+t(1787)])&&e.WTImg(e.nxLRQ,typeof wx),_i=e.zPlny("undefined",typeof globalThis)&&(e[t(1359)](t(1243)+t(1024)+"lobalScope",globalThis["construc"+t(1628)][t(913)])||e[t(857)](e.OmClq,globalThis[t(1447)+t(1628)][t(913)])||e.kJiwF(e.OIggd,globalThis["construc"+t(1628)].name))&&e[t(494)]("undefined",typeof self),Vg=e[t(1342)]("undefined",typeof globalThis)&&t(1189)===globalThis[t(1447)+"tor"][t(913)]&&e[t(679)](e.nxLRQ,typeof global)&&e.PLcqJ===global[t(1447)+t(1628)][t(913)]&&e[t(547)](e[t(1733)],typeof process)&&!!process[t(1465)];class Wa{constructor(){let r=t;this[r(833)+"rs"]={}}[t(910)](r,...s){let l=t;if(l(429)!==l(429)){let{type:h}=_0x44bcc1;this.emit(h,_0x593336)}else{let h=this._listeners[r];if(h)h[l(899)]().forEach(m=>m.fn[l(939)](m[l(1362)],s));else if(e[l(1054)]("error",r)&&!this[l(1577)])if(e[l(1606)](e[l(1812)],e[l(580)])){let m=s.length&&s[0];if(e[l(1537)](m,Error))throw m;let y=new Error(e[l(1722)](l(1282)+"d error.",m?e[l(811)](" ("+m.message,")"):""));throw y[l(1190)]=m,m}else{let m={wzNPW:e[l(1178)],owxYM:l(1369)+l(1150)+"s",GHasV:l(1118),ATNal:function(y,S,g){return e[l(1182)](y,S,g)},LCHzt:e[l(390)]};return new _0x2e25c5((y,S)=>{let g=l,L={nmOZq:function(F,$){return F($)},cMTHW:m[g(634)],KuSzW:m.owxYM,FpKup:function(F,$){return F($)},vhUWf:m[g(1005)]};this[g(1400)+g(490)](),this[g(435)+g(1576)+"Id"]=m[g(942)](_0x3b905f,this._ping[g(1305)](this),this[g(415)][g(1106)+g(859)]);let O=()=>{let F=g;L[F(1662)](y,L.cMTHW),this[F(670)](L[F(932)],O),this[F(670)](F(1369)+F(590)+"t",B)},B=()=>{let F=g;L[F(1737)](S,L.vhUWf),this[F(670)](L[F(932)],O),this.off("ping_onc"+F(590)+"t",B)};this.on(g(1369)+g(1150)+"s",O),this.on(m[g(627)],B),this[g(669)]()})}return this}}[t(670)](r,s){let l=t;if(e[l(1300)](e[l(1725)],e[l(1725)])){if(e[l(1174)](void 0,r))this._listeners={};else if(s===void 0)this[l(833)+"rs"][r]=null;else{let h=this._listeners[r];if(h)for(let m=0;e[l(1435)](m,h[l(1511)]);)e.VaWtC(h[m].fn,s)?h[l(1625)](m,1):++m}return this}else{this[l(1775)+l(1613)+l(927)](e.lDoRT(_0x5796a1,l(1175),{code:1e3,reason:e[l(948)]})),this._endpointManager?.[l(1248)+l(902)+l(1822)](),this[l(1252)+l(815)]?.["resetCou"+l(585)]();return}}on(r,s,l){let h=t;return(this[h(833)+"rs"][r]||(this[h(833)+"rs"][r]=[]))[h(567)]({fn:s,ctx:l||this}),this}}class Jg extends Wa{["_formatE"+t(1801)+"age"](r){let s=t;return e[s(1719)](e[s(1185)],"xuGkU")?r[s(843)]||r[s(1233)]?(s(578)+" "+(r[s(843)]||"")+s(644)+(r.errNo||""))[s(906)]():JSON[s(1353)+"y"](r):(this["currentE"+s(758)+s(610)+"t"]=1,this["currentI"+s(901)]++,this[s(1155)+"s"][this[s(1736)+s(901)]])}constructor(r,s,l){let h=t;super(),this[h(1227)]=null,wi&&wx[h(637)+h(358)]&&(this[h(1227)]=wx[h(637)+"ocket"]({url:r,protocols:s,header:l,fail:this["_createS"+h(1706)+"lHandler"][h(1305)](this),success:this[h(1721)+h(1506)+h(587)+h(1618)][h(1305)](this)})),Gn&&tt["connectS"+h(358)]&&(this._socket=tt[h(637)+h(358)]({url:r,protocols:s,header:l,fail:this[h(1721)+"ocketFailHandler"][h(1305)](this),success:this[h(1721)+h(1506)+h(587)+"ler"][h(1305)](this)}))}[t(1721)+t(1506)+"cessHand"+t(1618)](){let r=t;Promise.resolve()[r(1094)](()=>{this["_addWsLi"+r(956)]()})}[t(1721)+t(1706)+t(1165)](r){let s=t;Promise[s(1078)]()[s(1094)](()=>{let l=s,h=e[l(1239)](wt,e[l(360)],{message:this[l(1483)+l(1801)+l(568)](r)});this[l(910)](e[l(360)],h);let m=e.mZHKQ(kt,e.DeTlc,{reason:this[l(1483)+l(1801)+l(568)](r)});this.emit(l(1175),m)})}[t(1781)+"steners"](){let r=t,s={GsTDS:function(l,h){return l<=h},fZswD:function(l,h){return e[V(457)](l,h)},xrOaY:function(l,h){return e.JUOVw(l,h)},kfKgY:e.JNAsE,dLdfS:e.DeTlc,BsCAt:e.yfDjV,hEATR:function(l,h,m){return e[V(522)](l,h,m)},zxKzn:e[r(360)]};this._socket.onOpen(l=>{let h=r;this[h(910)](h(841),e[h(1444)](Wl,e[h(408)],{...l,data:l.errMsg||""}))}),this[r(1227)][r(744)](l=>{let h=r;if(s.kfKgY==="oEUiQ")this.emit(s.dLdfS,kt(s[h(642)],{...l}));else return s.GsTDS(_0x59f953,_0x1bbdda)?_0x2ee25e[h(869)](new _0x41ee08("next() c"+h(1503)+h(1703)+h(1555)+h(905))):(_0x45b7b9=_0x3e668d,s[h(1070)](_0x25beeb,_0x5391fd.length)?_0x51f014[h(1078)]():_0x558947[_0x4dcb14].bind(_0x17e55a)(_0x22fc59,_0x4f8244.bind(null,s[h(986)](_0xa751b7,1))))}),this[r(1227)][r(946)+"e"](l=>{let h=r;this.emit(s[h(1086)],s[h(1411)](jl,s[h(1086)],{...l}))}),this[r(1227)][r(1584)](l=>{let h=r;this.emit(s[h(969)],wt(s.zxKzn,{...l,message:l[h(843)]||""}))})}[t(933)](r){let s=t,l={JDMna:e[s(1653)],POTFw:s(458),gdaAr:e[s(360)],aybEv:function(h,m,y){return e[s(1035)](h,m,y)},TlmLd:function(h,m){return e[s(1573)](h,m)},EHnLh:function(h,m){return h|m},rUJpQ:function(h,m){return e.VbfrB(h,m)},aeVKd:function(h,m){return h===m},IaWyF:function(h,m){return e.OzFfV(h,m)},oHUFP:function(h,m){return e[s(1082)](h,m)},uJJBO:function(h,m){return h&m},rALTW:function(h,m){return h&m},AzMtb:function(h,m){return e.ynElw(h,m)},UuKad:function(h,m){return e[s(1303)](h,m)},fXknd:function(h,m){return h&m},Qfmvb:function(h,m){return e[s(890)](h,m)},jZJXE:function(h,m){return e.VaERx(h,m)},ATfyj:function(h,m){return h&m},jFOyg:function(h,m){return h>>m},JdXpZ:function(h,m){return e[s(354)](h,m)}};if(e[s(334)](r,Uint8Array))if(e.wUrVY(e[s(1502)],s(643))){let h=r.buffer[s(899)](r[s(1748)+"et"],r.byteLength+r.byteOffset);this[s(1227)]&&this._socket[s(933)]({data:h,fail:m=>{let y=s;if(l[y(1250)]===l[y(1158)])return{bytes:_0x32ab50,offset:0,limit:_0x43f017[y(1511)]};this[y(910)](l[y(471)],l[y(1557)](wt,l.gdaAr,{message:this[y(1483)+"rrorMess"+y(568)](m)}))}})}else _0x4fe2df=_0x1477b7[s(1535)+"At"](_0x51cf39),l[s(781)](_0x2af273,128)?_0x5eb70f[_0x47f4b4++]=_0x2739b4:l[s(781)](_0x16e4c1,2048)?(_0x4c3a78[_0x28c95e++]=l[s(423)](l[s(877)](_0x108776,6),192),_0x28242e[_0x5d4dd0++]=l.EHnLh(63&_0xd427a5,128)):(64512&_0x1cf26d)===55296&&l[s(436)](64512&(_0x3be645=_0x8ea60a.charCodeAt(_0x4329fc+1)),56320)?(_0x5138e0=l[s(730)](l[s(730)](65536,l.oHUFP(l[s(1701)](1023,_0x170401),10)),l.rALTW(1023,_0x161c85)),++_0x3cc4f2,_0x1a29c9[_0x2644e0++]=l[s(423)](l[s(520)](_0x5eae49,18),240),_0x15db48[_0x5df08e++]=l[s(1218)](l[s(475)](l.Qfmvb(_0x3008ca,12),63),128),_0xbd6d14[_0x4aa281++]=l[s(423)](_0x3781a4>>6&63,128),_0x36fa9d[_0x2a70e5++]=l[s(1612)](l[s(1040)](63,_0x42799f),128)):(_0x3e770d[_0x4edc39++]=l[s(1612)](l[s(520)](_0x13c91c,12),224),_0x5a8d91[_0x18b52a++]=l.UuKad(l[s(1673)](_0x58b497,6)&63,128),_0x48bdc8[_0x552ab1++]=l.JdXpZ(63,_0x157857)|128);else this[s(1227)]&&this[s(1227)][s(933)]({data:r,fail:h=>{let m=s;this[m(910)](e[m(360)],wt(e.pazKF,{message:this[m(1483)+"rrorMess"+m(568)](h)}))}})}close(r,s){let l=t;this[l(1227)]&&this[l(1227)][l(1175)]({code:r,reason:s})}[t(1107)+t(984)](r,s){this.on(r,s)}["removeEv"+t(1331)+t(441)](r,s){this[t(670)](r,s)}get[t(1558)+"te"](){return this[t(1227)].readyState}get[t(572)+"pe"](){return this._socket.binaryType}set[t(572)+"pe"](r){}get[t(397)](){return this._socket.url}get protocol(){let r=t;return this._socket[r(1449)]}get[t(521)+"ns"](){let r=t;return this._socket[r(521)+"ns"]}get[t(1648)+t(736)](){return 0}}function Zg(c,r){let s=t;if(r)return new r(c[s(397)],c[s(1449)]);if(wi||Gn)return new Jg(c[s(397)],c[s(1449)],c[s(497)]);if((yr||_i)&&e.FIkfE(s(1583)+"d",typeof WebSocket)&&WebSocket)return new WebSocket(c[s(397)],c[s(1449)+"s"])}function Xg(c){let r=t;if(e.dFARF(e.mIbZJ,e[r(1799)])){let s=new _0x310de8(e[r(1139)](2,_0x442f49));s[r(1753)](_0x48e846),_0x26ae06.bytes=s}else return!!(c||wi&&wx[r(637)+r(358)]||Gn&&tt["connectS"+r(358)]||e.EnZVE(yr,_i)&&e[r(1733)]!=typeof WebSocket&&WebSocket)}function $l(c,r,s){let l={SJSYV:function(y,S){return e[V(457)](y,S)},hGVaP:e.ngdnO,twkOH:e.LnzFc,VvSlR:function(y,S){return e[V(1663)](y,S)}},h=-1;async function m(y){let S=V;return l.SJSYV(S(855),l.hGVaP)?!!this._qosDB:y<=h?Promise[S(869)](new Error(l[S(518)])):(h=y,l.SJSYV(y,s[S(1511)])?Promise[S(1078)]():s[y].bind(c)(r,m[S(1305)](null,l.VvSlR(y,1))))}m(0)}function Vl(c){let r=t;if(r(1609)===e[r(660)]){let s=0,l=0;for(let h=0;e[r(1529)](h,c[r(1511)]);++h)l=c[r(1535)+"At"](h),e[r(879)](l,128)?s+=1:l<2048?s+=2:e.MODao(e[r(1231)](64512,l),55296)&&e.WFkpQ(e[r(1488)](64512,c[r(1535)+"At"](e[r(1159)](h,1))),56320)?(++h,s+=4):s+=3;return s}else _0x38e1ca=e[r(351)](_0x3e3ebd,_0x17902c),_0x23bca6|=e[r(888)](127,_0xc6fde9)<<14,e[r(1821)](128,_0x347a26)&&(_0x18b12b=e.Elxhy(_0x464767,_0x54aaf2),_0x20bb1f|=(127&_0x4802a9)<<21,e[r(728)](128,_0x48ea73)&&(_0x36d727=e[r(1273)](_0xba2b28,_0x45af46),_0x1aa475=127&_0x210b54,e[r(489)](128,_0x54632d)&&(_0x5b29ae=e[r(1072)](_0x44be48,_0x296c8d),_0x70c934|=e[r(505)](127,_0x3a17fc)<<7)))}function Jl(c,r,s){let l=t,h={HVyXr:function(y,S,g){return y(S,g)},CbIoi:function(y,S,g){return e.UYXhv(y,S,g)},LJxTM:function(y,S){return y(S)}};if(e[l(1198)](s-r,1))return"";let m="";for(let y=r;y<s;){let S=c[y++];if(e[l(1396)](S,127))m+=String[l(339)+l(710)](S);else if(e[l(1616)](S,192)&&e[l(343)](S,224))m+=String["fromChar"+l(710)](e[l(1192)](e.rfMEp(e[l(489)](31,S),6),e[l(1808)](63,c[y++])));else if(e[l(1616)](S,224)&&S<240)m+=String[l(339)+l(710)](e[l(1049)](e.XALOa(e[l(760)](15&S,12),e.CPIcI(63&c[y++],6)),e[l(354)](63,c[y++])));else if(S>=240)if(e[l(398)]("aNphJ",e.AgbFU))lznxOx[l(1187)](_0x16674d,_0x161740,24),lznxOx[l(388)](_0x29eb9f,_0x2695d2,lznxOx[l(1288)](_0x27ddbb,_0x5de5dd));else{let g=e[l(1650)](e[l(1560)](e.JWsTb(e.xZlPS(e[l(1284)](e[l(1488)](7,S),18),e[l(718)](63,c[y++])<<12),e.IrpXn(e.IWAan(63,c[y++]),6)),e[l(456)](63,c[y++])),65536);m+=String[l(339)+l(710)](e[l(1720)](55296,e[l(890)](g,10))),m+=String[l(339)+"Code"](56320+e[l(549)](1023,g))}}return m}function Ka(c,r,s){let l=t,h=s,m,y;for(let S=0;e[l(1573)](S,c[l(1511)]);++S)m=c[l(1535)+"At"](S),e[l(1435)](m,128)?r[s++]=m:e.MKKDS(m,2048)?(r[s++]=e[l(1042)](e[l(1075)](m,6),192),r[s++]=e[l(1314)](63&m,128)):e[l(1032)](64512,m)===55296&&e.jhpkX(e.EQclM(64512,y=c.charCodeAt(e[l(1159)](S,1))),56320)?(m=e.BGRKN(e.EjuLn(65536,e[l(1048)](e[l(1488)](1023,m),10)),e[l(1228)](1023,y)),++S,r[s++]=m>>18|240,r[s++]=e[l(361)](e[l(1075)](m,12)&63,128),r[s++]=e.Vzlwk(e[l(444)](e[l(1075)](m,6),63),128),r[s++]=e.bVmHI(63,m)|128):(r[s++]=e.tKumJ(e[l(1789)](m,12),224),r[s++]=e[l(1193)](e[l(366)](e[l(1075)](m,6),63),128),r[s++]=e[l(671)](63,m)|128);return s-h}async function Zl(c){let r=t;if(e[r(1054)](e[r(445)],e[r(445)])){if(e.uKIGa(e.ASApT,typeof c)){let s=new Uint8Array(e[r(1522)](Vl,c));return e[r(957)](Ka,c,s,0),s}return e.bighX(c,ArrayBuffer)?new Uint8Array(c):new Uint8Array(c.buffer,c[r(1748)+"et"],c[r(1826)+"th"])}else _0x16dba9<65536?_0x107b68[_0x2615f0++]=e[r(1160)](_0x1f224e>>12,15)|224:(_0x68d290[_0x954a47++]=e.XLJxZ(e.cJnSv(e[r(890)](_0x4e440f,18),7),240),_0x31f896[_0x2e03de++]=e[r(647)](_0x39a276>>12,63)|128),_0x33b8d2[_0x170a67++]=e[r(651)](e.yGMSe(e[r(1834)](_0x25f1bc,6),63),128)}function Yg(c){let r=t;try{return e[r(1473)](e.ASApT,typeof c)&&(e[r(779)](c,ArrayBuffer)||c[r(476)]&&c.buffer instanceof ArrayBuffer)||e[r(1473)](e[r(1533)],typeof c)?"":(JSON[r(1471)](c),e[r(570)])}catch{return e.QTJgX("string",typeof c)?e[r(1291)]:""}}let Qg=(c,r)=>{let s=t;switch(c){case e[s(699)]:case e[s(823)]:return{[s(1306)+c]:1,"x-tt-env":r};default:return{}}};class em{constructor(r){let s=t;this[s(941)+s(883)]=r,this[s(1215)]=0}addCount(){let r=t;this[r(1215)]++}["checkRea"+t(328)+"nt"](){let r=t;return this[r(1215)]>=this[r(941)+"ount"]}[t(553)+t(585)](r=0){let s=t;this[s(941)+s(883)]=r,this[s(1215)]=0}}async function tm(c){let r={mJZvu:function(s,l){return s>=l},OQioa:function(s,l){return e[V(1396)](s,l)},rWLTm:function(s,l){return e[V(900)](s,l)},MenhZ:function(s,l){return e[V(1705)](s,l)},fMogO:function(s,l){return e[V(1219)](s,l)},sZwMi:function(s,l){return e[V(1316)](s,l)},ckYAX:function(s,l){return e[V(1071)](s,l)},kInzc:function(s,l){return s&l},QgZwb:function(s,l){return s>>l},fgznZ:function(s,l){return e[V(508)](s,l)},KAMeV:function(s,l){return e.DKbIF(s,l)},qxgOO:function(s,l){return e[V(1635)](s,l)},PLRLe:function(s,l){return s&l},SQNXi:function(s,l){return e[V(1049)](s,l)},wdWHz:function(s,l){return e[V(888)](s,l)},gXDDE:function(s,l){return e.YVLJW(s,l)}};return new Promise(s=>{let l=V,h={bwzUQ:function(m,y){return e[V(485)](m,y)}};if(!yr)return e.RZXXc(s,e[l(1497)]);try{let m=document[l(1067)+"ement"](e[l(1076)]);window["frontier"+l(1712)]=y=>{let S=l;document[S(1660)].removeChild(m),window["frontier"+S(1712)]=void 0,h[S(449)](s,y&&y[S(1641)]||S(1277)+"reason")},m[l(1097)]=e[l(926)],m[l(1153)]=e.laxJv(c.replace(/^ws/,e[l(1640)]),e[l(925)]);try{if(e.MeyjV(e[l(854)],"bHYzT"))document.body[l(729)+"ild"](m);else{let y=_0x1f2955[l(1535)+"At"](_0x278f08);TqTFFQ[l(1679)](y,55296)&&TqTFFQ.OQioa(y,56319)&&TqTFFQ[l(1446)](TqTFFQ[l(904)](_0x682e95,1),_0x5a5274)&&(y=TqTFFQ[l(1210)](TqTFFQ.MenhZ(TqTFFQ[l(1327)](y,10),_0x41cc27.charCodeAt(++_0x10cba1)),56613888)),TqTFFQ.rWLTm(y,128)?_0x30d876[_0x30625c++]=y:(y<2048?_0x443941[_0x562237++]=TqTFFQ[l(740)](TqTFFQ[l(1269)](TqTFFQ[l(1088)](y,6),31),192):(TqTFFQ[l(1446)](y,65536)?_0x25b65f[_0x5175c2++]=TqTFFQ[l(929)](TqTFFQ[l(1246)](y>>12,15),224):(_0x400884[_0x3faa2f++]=TqTFFQ[l(1328)](TqTFFQ[l(1422)](TqTFFQ[l(1088)](y,18),7),240),_0x3b9130[_0x5b49ed++]=TqTFFQ[l(1237)](TqTFFQ[l(807)](y>>12,63),128)),_0x1da705[_0x5c170e++]=TqTFFQ[l(807)](y>>6,63)|128),_0x260f50[_0x1ff680++]=TqTFFQ[l(1328)](TqTFFQ[l(594)](63,y),128))}}catch{document.body[l(966)+"ild"](m)}}catch{window[l(757)+l(1712)]=void 0,e[l(1286)](s,l(1277)+"reason")}})}function _n(c,r,s){let l=t;return!!c?.[l(526)](h=>h[l(1683)]===r&&h[l(1595)]===s)}function Er(c,r){let s=t;return c?.find(l=>l[s(1683)]===r)?.value}let $a=null;async function nm(){let c=t;return $a||($a=Promise[c(1078)]()[c(1094)](Xt[c(1305)](Xt,e[c(607)]))),$a}class rm extends Wa{constructor(r,s){let l=t;super(),this._dbName=r,this[l(973)]=s,this[l(1022)]=void 0,this[l(1688)+"mise"]=null}async[t(876)](){await this[t(534)]()}async _init(){let r=t,s={xVdmo:e[r(1527)],lDhIq:function(l){return l()},Ldpte:e[r(1372)],iSbno:e[r(1498)],iLiCb:r(1135)+"NG_ERROR",gUFBs:e[r(914)],RYELQ:e.JUACX};if(e[r(868)](e.YdQtf,e[r(1099)])){if(this[r(1022)])return;if(this[r(1688)+r(991)])return this["_initPro"+r(991)];try{let l=this[r(1667)],h=this[r(973)];this[r(1688)+r(991)]=(async()=>{let m=r;if(s[m(864)]===m(1404)){let{openDB:y}=await s[m(1538)](nm);this[m(1022)]=await y(m(757)+"_"+l,1,{upgrade(S){let g=m;S[g(1112)+g(565)+"e"](l,{keyPath:h})}})}else this._ws&&this[m(1545)][m(1175)](_0x4c41d3,_0x2fe200)})(),await this._initPromise}catch(l){console[r(1492)](l)}finally{this[r(1688)+r(991)]=null}}else{let l=(r(1698)+r(345))[r(1622)]("|"),h=0;for(;;){switch(l[h++]){case"0":_0x546ee8[_0xd36d6b["MAX_RETR"+r(943)+"R"]=5003]=MYploE[r(1171)];continue;case"1":_0xcb43d5[_0x217cb9[MYploE[r(1322)]]=5001]=MYploE[r(1322)];continue;case"2":return _0x371d54;case"3":_0x460208[_0x8ab6b[r(1135)+"NG_ERROR"]=5002]=MYploE.iLiCb;continue;case"4":_0xb0317e[_0x3d4b07.OPEN_ERROR=5005]=MYploE.gUFBs;continue;case"5":_0x8a2d3a[_0x4d34ed[MYploE[r(820)]]=5004]=MYploE[r(820)];continue}break}}}async get(r){let s=t;if(e[s(1354)]!==e[s(439)])try{return await this._init(),this[s(1022)]?.get(this[s(1667)],r)}catch(l){console.log(l)}else{let l=s(1079)+_0x3d89f6+(s(1059)+s(1597)+s(1399)+s(455));this[s(1270)](l),this["_dispatc"+s(863)+s(927)](e[s(383)](_0x587d2e,e[s(360)],{message:l,code:_0x3af225[s(618)+s(943)+"R"]}));return}}async[t(1753)](r,s){let l=t;return await this._init(),this[l(1022)]?.[l(1434)](this._dbName,r)}async[t(714)](r){let s=t,l={PtiBS:s(1369)+s(1150)+"s",zVEFc:e[s(1178)],qvHMD:function(h,m,y){return e[s(1348)](h,m,y)}};if(e[s(1145)]!==e[s(1363)])try{return await this[s(534)](),this[s(1022)]?.[s(1258)](this._dbName,r)}catch(h){console[s(1492)](h)}else this["_clearPi"+s(490)](),this[s(910)](l[s(419)],l[s(920)]),this[s(435)+"gTimeoutId"]=l.qvHMD(_0x4d0f5c,this._ping[s(1305)](this),_0x58ba6f)}async[t(1433)](){let r=t;try{return await this[r(534)](),this[r(1022)]?.[r(1433)](this[r(1667)])}catch(s){console.log(s)}}async[t(440)](){let r=t;return await this[r(534)](),this[r(1022)]?.[r(693)+"ys"](this[r(1667)])}async[t(1302)](){let r=t;return await this[r(534)](),this[r(1022)]?.[r(1302)](this[r(1667)])}async[t(796)](){let r=t;try{this[r(1022)]?.[r(1175)](),this[r(1022)]=void 0}catch(s){console[r(1492)](s)}}get[t(1599)](){let r=t;try{return!!this[r(1022)]}catch(s){return console[r(1492)](s),!1}}}class im{constructor(r,s){let l=t;this[l(845)]=r,this[l(884)]=s,this._qosDB=localStorage}async openDB(){}get[t(1142)](){return"frontier_"+this[t(845)]}async get(r){let s=t;if(e.DALlo(s(1409),e[s(623)])){let l=_0x4acdd1(e[s(360)],{message:this[s(1483)+s(1801)+"age"](_0x2ba7d)});this[s(910)](e[s(360)],l);let h=e.hKtLi(_0x5d3bc7,e.DeTlc,{reason:this[s(1483)+s(1801)+s(568)](_0x3bf29b)});this[s(910)](e[s(1455)],h)}else{let l=this[s(1022)][s(1598)](this[s(1142)]);return JSON[s(1471)](e[s(609)](l,"{}"))[r]}}async[t(1753)](r,s){let l=t,h={zBSsg:l(648)};if(l(1517)===e.WLLRf){let m=this[l(1022)][l(1598)](this[l(1142)]),y=JSON[l(1471)](e[l(331)](m,"{}"));return y[s||r[this._pathKey]]=r,this[l(1022)][l(1057)](this[l(1142)],JSON[l(1353)+"y"](y)),s||r[this[l(884)]]}else _0xbd4868=h[l(1646)],_0x386045=_0x2a294a[l(1631)](/(^http)((?:[s]*:\/\/))/,""),_0x536254=/(^ws)((?:[s]*:\/\/))/.test(_0x52e7da)?_0x4fe21f:""+_0x270088+_0x12ecaf}async del(r){let s=t,l=this[s(1022)][s(1598)](this[s(1142)]),h=JSON[s(1471)](e.tEWcg(l,"{}"));return h[r]=void 0,this._qosDB.setItem(this[s(1142)],JSON.stringify(h))}async[t(1433)](){let r=t;return this._qosDB[r(1433)]()}async keys(){let r=t;if(e[r(330)](e.SDuRP,e[r(752)])){let s=this[r(1022)].getItem(this[r(1142)]),l=JSON[r(1471)](e[r(331)](s,"{}"));return Object[r(440)](l)}else return}async[t(1302)](){let r=t,s=this._qosDB[r(1598)](this[r(1142)]),l=JSON.parse(e.padRW(s,"{}"));return Object.values(l)}[t(796)](){return Promise[t(1078)]()}get[t(1599)](){return!!this._qosDB}}class sm{constructor(r,s){let l=t;this[l(845)]=r,this[l(884)]=s,this[l(1022)]=Gn?tt:wi?wx:null}async[t(876)](){}get[t(1142)](){let r=t;return r(757)+"_"+this[r(845)]}async[t(1326)](r){let s=t,l=this[s(1022)][s(1299)+s(1714)](this[s(1142)]);return JSON[s(1471)](e[s(428)](l,"{}"))[r]}async[t(1753)](r,s){let l=t,h=this[l(1022)][l(1299)+"geSync"](this[l(1142)]),m=JSON[l(1471)](e[l(1620)](h,"{}"));return m[s||r[this[l(884)]]]=r,this._qosDB[l(1230)+l(1714)](this[l(1142)],JSON[l(1353)+"y"](m)),s||r[this[l(884)]]}async[t(714)](r){let s=t,l=this[s(1022)][s(1299)+s(1714)](this[s(1142)]),h=JSON[s(1471)](l||"{}");return h[r]=void 0,this[s(1022)][s(1230)+s(1714)](this[s(1142)],JSON[s(1353)+"y"](h))}async[t(1433)](){let r=t,s={ygkmD:function(l,h){return e[V(1836)](l,h)},AEWum:e[r(1820)]};if(r(1758)!=="UnrlV"){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}/.test(_0x31c03e),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(945)](_0x36daf5);return l?_0x1dc900(_0x372b8d):h?uBoESo[r(536)](_0x4ab117,_0x2f9040):uBoESo.AEWum}else return this[r(1022)][r(935)+r(751)]()}async[t(440)](){let r=t,s=this[r(1022)][r(1299)+r(1006)+"nc"](this[r(1142)]),l=JSON.parse(e[r(1832)](s,"{}"));return Object[r(440)](l)}async getAll(){let r=t,s=this[r(1022)][r(1299)+r(1006)+"nc"](this[r(1142)]),l=JSON[r(1471)](e[r(1046)](s,"{}"));return Object[r(1290)](l)}[t(796)](){return Promise[t(1078)]()}get[t(1599)](){return!!this[t(1022)]}}function Xl(c,r){let s=t;if(e[s(950)]!==e[s(532)]){if(Gn||Gn)return new sm(c,r);if(e[s(1201)](yr,_i)&&e[s(1473)](s(1583)+"d",typeof indexedDB))return new rm(c,r);if(e[s(428)](yr,_i)&&e[s(679)](e[s(1733)],typeof localStorage))return new im(c,r);throw new Error(e.Vvtxe)}else this.on(_0x473c04,_0x42bc72)}class om{constructor(){let r=t;this._intervalTimeoutId=null,this[r(616)+"l"]=36e5,this[r(1022)]=e[r(1226)](Xl,e[r(1487)],e[r(1452)])}async[t(616)+t(1115)](){let r=t,s={xVHgw:function(l,h,m){return e[V(1695)](l,h,m)},idtwm:function(l,h,m){return e[V(1695)](l,h,m)},YzqwA:function(l,h,m,y){return e[V(576)](l,h,m,y)},GDFNd:function(l,h){return e[V(1602)](l,h)}};if(e[r(1606)](e.LXvWr,r(516)))e.AJVvN(clearInterval,this[r(616)+r(700)+"Id"]),this["_interva"+r(700)+"Id"]=e[r(1507)](setInterval,()=>{let l=r;this[l(1283)+l(1387)]()},this[r(616)+"l"]);else{let{offset:l}=s[r(814)](_0x4e8ad0,_0x39a30d,_0xac8aed);_0x4df0af=l;let h={cursor_name:"",cursor:0,service:0},{value:m,offset:y}=s[r(675)](_0x13ad97,_0x5b8ed2,_0x5203ff);h[r(1566)]=m,_0x1a4e88=y;let{value:S,offset:g}=s[r(675)](_0x470926,_0x8a44ef,_0x9f3fdf);_0x2dc62b=g,h[r(1195)+r(887)]=s[r(454)](_0x1dbf53,_0x4e3f46,_0x57f090,s.GDFNd(_0x1548f5,S)),_0x32cf8e+=S;let{value:L,offset:O}=_0x3dbd49(_0x4c9a06,_0x4b58e5);h[r(658)]=L[r(1691)](),_0x4515fa=O,_0x398797[r(567)](h)}}async openDB(){let r=t;e[r(1222)](e[r(1760)],e.ZrPcf)?this[r(833)+"rs"]={}:await this[r(1022)][r(876)]()[r(1094)](()=>{let s=r,l={eZeuu:function(h,m){return e.QcgRi(h,m)},KIjee:e[s(1533)],ILnOl:function(h,m,y,S){return e[s(957)](h,m,y,S)},WcrtB:function(h,m){return e[s(1757)](h,m)}};if(e[s(1670)](e[s(1739)],e[s(1739)]))this._intervalFlush();else{if(QJCZyb.eZeuu(QJCZyb[s(1018)],typeof _0xde2df4)){let h=new _0x326d1d(_0x55f16d(_0x17f6aa));return QJCZyb.ILnOl(_0x2e8b1d,_0x4e1899,h,0),h}return QJCZyb[s(1166)](_0x571b87,_0x598132)?new _0x432e2e(_0x439d8b):new _0x3e6611(_0x55d736[s(476)],_0x10da62[s(1748)+"et"],_0x18d314.byteLength)}})}async[t(1283)+t(1387)](){let r=t;(await this[r(1022)]?.getAll()||[])[r(653)](({timestamp:h})=>h<Date[r(559)]()).forEach(h=>{let m=r,y={ptRaH:e[m(835)]};e[m(1593)](e[m(1344)],e[m(1344)])?this[m(1022)]?.del(h[m(1256)+"id"]):(this[m(910)](y.ptRaH,_0x3456c1),this[m(1716)+"eAck"]&&this[m(1716)+m(1827)](_0xbe19d0))})}async[t(714)](r){let s=t;return this._qosDB?.[s(714)](r)}async[t(1753)](r,s){let l=t;return this[l(1022)]?.[l(1753)]({message_id:r,timestamp:s})}async[t(1326)](r){let s=t;return e.kHaAc===s(1298)?this._ws?this[s(1545)].extensions:"":this[s(1022)]?.get(r)}async[t(796)](){let r=t;e.RZXXc(clearInterval,this[r(616)+"lTimeoutId"]),await this[r(1022)]?.[r(796)]()}get[t(1599)](){let r=t;return this[r(1022)]?.[r(1599)]}}function Va(c){let r=t;if(e[r(622)]===r(959)){let s=!!this[r(415)][r(396)+"S"];if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=e[r(957)](_n,c[r(1500)][r(497)],e.CofPZ,"2"),h=l&&e[r(1445)](_n,c[r(1500)][r(497)],e[r(759)],"1"),m=l&&e[r(957)](_n,c[r(1500)].headers,e.XrhJk,"1"),y=m?Er(c[r(1500)][r(497)],e.WUTJW)?.[r(1622)](",")[r(653)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:m,ackMsgIds:y}}else this[r(1545)]&&this[r(1545)][r(933)](_0x523bc9),this._debug(e.MrTce,_0x489cdc)}async function Yl(){let c=t,r={FsMkz:function(s,l){return e.pfiIB(s,l)},DrmLe:function(s){return e[V(1148)](s)}};if(e.ybSjd(e[c(681)],e[c(681)]))aVAvti[c(702)](_0x48e337,_0x2c146f[c(1746)]),aVAvti[c(737)](_0x4d5bc4);else return this[c(1793)+"ger"]||(this[c(1793)+c(1128)]=new om),this[c(1793)+c(1128)][c(1599)]||await this[c(1793)+c(1128)].openDB(),this["_QoSMana"+c(1128)]}async function am(c,r){let s=t,{enableAutoAck:l}=this._options,h=e.EKTmn(_n,c[s(1500)][s(497)],e.voTct,"1"),m=e[s(576)](_n,c[s(1500)][s(497)],e[s(755)],"1"),y=Va[s(1603)](this,c);if(e[s(981)](l,h))if(s(1669)===e.RzhKT){let{SeqID:S,LogID:g,service:L,LogIDNew:O,method:B}=c.message;this[s(1220)]({SeqID:S,LogID:g,LogIDNew:O,service:L,method:B,headers:[{key:e[s(755)],value:"1"},{key:e[s(1608)],value:e[s(1747)](O,"")},{key:s(873),value:"0"}]})}else{let S=_0x47aef1[s(1523)]();return S?(S[s(417)]=S[s(975)]=0,S):{bytes:new _0x4667d6(64),offset:0,limit:0}}m&&!y[s(734)]&&this["_dispatc"+s(382)+s(1570)](c),e[s(1505)](r)}async function cm(c,r){let s=t;this._debug(s(717),c.message),r()}async function dm(c,r){let s=t,l={tUqhy:function(h,m){return h!=m},JAACJ:e[s(1733)],Ydrnp:function(h,m,y){return e.ZWZKD(h,m,y)},xjpIn:function(h,m,y,S){return h(m,y,S)},UQpDW:function(h,m){return e.ieOUx(h,m)},jvixC:function(h,m,y){return e[s(571)](h,m,y)}};if(s(722)!==e[s(1249)]){let h=e[s(1023)](Ft,await e.eOmtB(Zl,c[s(960)]));try{if(e[s(983)](s(809),e[s(1281)]))return!!(_0xa96d34||_0x40ecc2&&_0x3d9ecb[s(637)+"ocket"]||_0x4b7bed&&_0x1be3ef[s(637)+s(358)]||(_0x3d93f0||_0x5044b5)&&mzKLzw[s(1464)](mzKLzw[s(1711)],typeof _0x57866e)&&_0x176384);if(e[s(334)](h[s(1177)],Uint8Array)){let m=e.bighX(this[s(415)][s(391)+s(1143)],Object)?{force:!!this[s(415)][s(391)+s(1143)][s(831)],encoding:this[s(415)].payloadEncoding[s(806)]?this[s(415)][s(391)+s(1143)][s(806)][s(1631)](/\s/g,"")[s(850)+"ase"]():""}:{force:!1,encoding:this[s(415)][s(391)+s(1143)]?this._options[s(391)+s(1143)][s(1631)](/\s/g,"")[s(850)+s(1774)]():""},y=h[s(391)+s(1143)]?h[s(391)+s(1143)][s(1631)](/\s/g,"").toLowerCase():"",S=e[s(1767)](this[s(415)][s(1009)+"ype"],Object)?{force:!!this._options[s(1009)+"ype"][s(831)],type:this[s(415)][s(1009)+s(1624)].type?this[s(415)].payloadType[s(1097)][s(1631)](/\s/g,"")[s(850)+s(1774)]():""}:{force:!1,type:this[s(415)]["payloadT"+s(1624)]?this[s(415)][s(1009)+s(1624)][s(1631)](/\s/g,"")[s(850)+"ase"]():""},g=h["payloadT"+s(1624)]?h[s(1009)+"ype"][s(1631)](/\s/g,"")[s(850)+s(1774)]():"",L=S[s(831)]?S[s(1097)]:g||S.type,O=m.force?m[s(806)]:y||m[s(806)],B=[e.IINBX,e[s(570)],s(776)+s(825)+s(856)+s(1472),e[s(1533)]],F=[s(784)+"e",e[s(1014)]];this[s(415)][s(1470)+s(707)+s(1156)+"ad"]&&B.includes(L)&&(!O||F.includes(O))?h.textPayload=e[s(1292)](Jl,h[s(1177)],0,h.payload[s(1826)+"th"]):h["textPayl"+s(789)]=""}else h[s(1234)+s(789)]=""}catch(m){h[s(1234)+s(789)]="",console.log(m)}c[s(1500)]=h,e.tSYcb(r)}else{let h=0,m=[];for(;h<_0x332b8c[s(1826)+"th"];){let{offset:y}=l.Ydrnp(_0x5f5929,_0x4b0e86,h);h=y;let S={cursor_name:"",cursor:0,service:0},{value:g,offset:L}=l.Ydrnp(_0x3d69c5,_0x572638,h);S[s(1566)]=g,h=L;let{value:O,offset:B}=_0x283911(_0x182db4,h);h=B,S[s(1195)+s(887)]=l[s(1136)](_0x5848d1,_0x313fc1,h,l[s(1501)](h,O)),h+=O;let{value:F,offset:$}=l[s(1301)](_0x67eb11,_0x114f5c,h);S.cursor=F[s(1691)](),h=$,m[s(567)](S)}return m}}function lm(c,r,s){let l=t,h=e[l(889)](s,8192),m=h>>>1,y=null,S=h;return function(g){let L=l;if(e[L(900)](g,1)||e[L(1020)](g,m))return e[L(1428)](c,g);e[L(1779)](S,g)>h&&(y=c(h),S=0);let O=r.call(y,S,S+=g);return 7&S&&(S=e[L(1528)](7,S)+1),O}}let fm=4294967295;function um(c,r,s){let l=t;return e[l(1674)](RangeError,e[l(1403)](e[l(1705)](e[l(769)](e.LMZwy(e.LkhjI,c),e[l(1806)]),r||1)+e[l(862)],s))}function hm(c,r,s){let l=t;if(e[l(1493)](s,fm))throw new Error(e[l(972)]);let h=3;for(;e[l(1616)](h,0);){let m=e[l(1415)](255,s);Za(m,c,e.LMZwy(r,h)),s>>>=8,h--}return e[l(1779)](r,4)}function xm(c,r){let s=t;if(e[s(546)]!=="JbPKx")this[s(1022)]?.[s(714)](_0x33538c[s(1256)+"id"]);else{let l=0,h=r,m=r+4;for(;e[s(1198)](h,m);){let{value:y,offset:S}=e[s(1553)](Ja,c,h);h=S,l=e[s(319)](e[s(733)](l,8),0),l+=y}return{value:l,offset:m}}}function pm(c,r,s){let l=t;if(e[l(1728)](e[l(353)],e[l(353)]))return _0x54d960 instanceof _0x4dad0e&&(rxVpOu[l(1221)](_0x4923c0,rxVpOu[l(908)])||rxVpOu[l(596)](_0x41545d,rxVpOu[l(1293)]))?!0:rxVpOu.QztgY(_0x290eee,_0x428517);{let h=e[l(739)][l(1622)]("|"),m=0;for(;;){switch(h[m++]){case"0":if(!c)return s;continue;case"1":if(r[l(326)+"e"])return e[l(1297)](r[l(326)+"e"](c,s),s);continue;case"2":return e.ILrrY(e[l(612)](Ka,c,r,s),s);case"3":if(c.length<40)return e.hIiDm(Ka(c,r,s),s);continue;case"4":if(r[l(1684)])return r[l(1684)](c,s)+s;continue}break}}}function gm(c,r){let s=t,l=new ce(e[s(1314)](e[s(1279)](e[s(804)](c[e[s(743)](r,4)],24),e.HEuSu(c[e[s(961)](r,5)],16))|c[r+6]<<8,c[e.Ecwql(r,7)]),e[s(1560)](e.QeBbx(e.mkzVT(e[s(1316)](c[e[s(1602)](r,0)],24),e[s(1316)](c[e[s(1045)](r,1)],16)),e[s(1477)](c[e[s(1681)](r,2)],8)),c[r+3]),!0);return r+=8,{value:l,offset:e.gFMeO(r,8)}}function mm(c,r,s){let l=t,h=c[l(1272)],m=c.high;return r[s]=m>>>24,r[e[l(1779)](s,1)]=e[l(706)](m>>>16,255),r[e.eKtDn(s,2)]=e[l(1228)](e[l(374)](m,8),255),r[e[l(1212)](s,3)]=e[l(846)](255,m),r[e[l(1602)](s,4)]=e.BDmaw(h,24),r[e[l(1705)](s,5)]=e[l(1638)](h,16)&255,r[e[l(1163)](s,6)]=e[l(962)](e[l(1211)](h,8),255),r[s+7]=e.yTcwZ(255,h),s+=8,s}function Ja(c,r){let s=t;return c[s(1162)+"8"]?{value:c.readUInt8(r),offset:e[s(1761)](r,1)}:{value:e.tCpuN(255,c[r]),offset:e[s(1164)](r,1)}}function Za(c,r,s){let l=t;return r[l(1111)+"t8"]?r[l(1111)+"t8"](c,s):r[s]=e.UNifh(255,c),s+1}let wm=function(c){return new Uint8Array(c)},_m=e[t(1733)]!=typeof Buffer?Buffer["allocUns"+t(407)]:lm(wm,Uint8Array[t(501)+"e"][t(1104)]),ym=16,Xa=32;function Em(c){let r=t,s=0,l={};for(let h=0;e[r(1417)](h,c[r(1511)]);h++)l[c[h][r(1195)+r(887)]]=Vl(c[h][r(1195)+"ame"]),s+=e[r(552)](14,l[c[h][r(1195)+r(887)]]);return[s,l]}function Ql(c,r,s){let l=t,h={HRsQI:e[l(427)],PAtfQ:e[l(1554)],pSQeG:function(m,y,S,g){return m(y,S,g)},neBaR:e[l(437)],voCKf:l(913),GvkqQ:e.lNlby,ZKqtc:e.TSHAC};if(e[l(894)]===e.lrWPe){let m=this[l(1022)][l(1299)+l(1006)+"nc"](this[l(1142)]),y=_0x5ac3e1.parse(e.VvGXy(m,"{}"));return _0x2872c2.values(y)}else{let[m,y]=Em(c),S=e[l(842)](_m,m),g=0;return c[l(1588)](L=>{let O=l,B=h[O(893)][O(1622)]("|"),F=0;for(;;){switch(B[F++]){case"0":console.log(h[O(1274)],L,L.service);continue;case"1":g=h.pSQeG(Za,y[L[O(1195)+O(887)]],S,g);continue;case"2":console.log(h[O(462)],g);continue;case"3":g=h[O(772)](mm,ce[O(686)+"er"](L[O(658)]||r),S,g);continue;case"4":console.log(h.voCKf,g);continue;case"5":console[O(1492)](h[O(1357)],g);continue;case"6":g=h[O(772)](hm,S,g,L.service||0);continue;case"7":g=pm(L["cursor_n"+O(887)],S,g);continue;case"8":console.log(h[O(362)],g);continue;case"9":g=h[O(772)](Za,0,S,g);continue;case"10":console[O(1492)](O(1566),g);continue}break}}),{frameType:Xa,headers:[{key:e[l(1430)],value:s}],payload:S}}}function bm(c){let r=t,s=0,l=[];for(;e[r(1417)](s,c[r(1826)+"th"]);)if(e[r(1813)]!==e[r(1772)]){let{offset:h}=e[r(1810)](Ja,c,s);s=h;let m={cursor_name:"",cursor:0,service:0},{value:y,offset:S}=xm(c,s);m[r(1566)]=y,s=S;let{value:g,offset:L}=e.luFvg(Ja,c,s);s=L,m["cursor_n"+r(887)]=e.EKTmn(Jl,c,s,e[r(1028)](s,g)),s+=g;let{value:O,offset:B}=e[r(805)](gm,c,s);m.cursor=O[r(1691)](),s=B,l.push(m)}else return _0x2bcd06&&(_0x570b26=(0,_0x39cf7e[rxVpOu[r(1141)](_0x3cf1ac,_0x8e5d16)[0]])(_0x388e2a=0)),_0x479401;return l}function vm(){let c=t;return{frameType:Xa,headers:[{key:c(540)+c(323),value:e.mOdIZ}],payload:void 0}}class Sm{constructor(r,s,l){let h=t;this[h(1037)+h(1236)]=r,this[h(1536)+h(1169)]=s,this[h(602)+h(1209)]=l,this._qosDB=Xl(this["_cursorN"+h(1236)],e[h(663)])}async[t(876)](){await this._qosDB.openDB()}async[t(830)+"rs"](){let r=t;if(!this[r(1022)][r(1599)])return;let s=this[r(602)+r(1209)],l=await this[r(1022)].getAll();switch(console.log(e.GDHuG,l),s){case e[r(788)]:return l&&l[r(1511)]?e[r(576)](Ql,l,0,this[r(1536)+r(1169)]):void 0;case e[r(614)]:return;case e[r(1715)]:return l&&l[r(1511)]?e[r(1401)](Ql,l,0,this["_cursorF"+r(1169)]):e[r(1505)](vm)}}async[t(1753)](r,s,l){let h=t,m={inMYO:function(y,S){return e[V(1007)](y,S)},YLxef:e[h(1497)]};if(e[h(421)]!==h(1587))return console[h(1492)](h(1586),r,s,l),this._qosDB[h(1753)]({cursor_name:r,cursor:s,service:l});_0x11fd62[h(757)+h(1712)]=void 0,qbmKIG[h(474)](_0x2dd225,qbmKIG[h(1127)])}async[t(1029)+"rs"](r){let s=t,l=bm(r);for(let h of l)console[s(1492)](s(1738)+"r",l),await this[s(1022)][s(1753)](h)}async[t(1326)](r){let s=t;if(e[s(1010)](s(799),e[s(1830)]))return(await this._qosDB[s(1326)](r))?.cursor;{let l=255&_0x4122bb;e[s(612)](_0x2f88ea,l,_0x533e99,e.mBORv(_0x459da2,_0x32304b)),_0xd41034>>>=8,_0x3eca66--}}async closeDB(){await this[t(1022)].closeDB()}["updateCu"+t(1085)+"Name"](r){let s=t,l={jtJns:function(h,m){return e.KvTlD(h,m)},qERGt:function(h,m){return h+m},mQCrd:s(1282)+"d error."};if(e[s(1238)]===e.KNIvX)this["_cursorF"+s(1169)]=r;else{let h=this[s(833)+"rs"][_0x102b8d];if(h)h.slice()[s(1588)](m=>m.fn[s(939)](m[s(1362)],_0x222127));else if(JcFKTi[s(1694)](s(1746),_0xbfe14b)&&!this.onerror){let m=_0x175b4c.length&&_0x5962c0[0];if(m instanceof _0xd0d47a)throw m;let y=new _0x1d3def(JcFKTi[s(1385)](JcFKTi[s(1441)],m?JcFKTi[s(1385)](" ("+m[s(1500)],")"):""));throw y[s(1190)]=m,m}return this}}get[t(1599)](){let r=t;return this._qosDB[r(1599)]}}let Im=e.hjJcw;async function ef(c){let r=t;if(!this._options[r(396)+"S"])return null;let{aID:s,fpID:l,messageStrategy:h}=this[r(415)],m=e[r(584)](c,Im);try{return this[r(1329)+r(665)]?c&&this[r(1329)+r(665)][r(865)+r(1085)+"Name"](c):this[r(1329)+r(665)]=new Sm(l+"_"+s+"_"+m,m,h),this[r(1329)+r(665)].isReady||await this._cursorManager[r(876)](),this[r(1329)+r(665)]}catch{if(e[r(1460)](r(1026),e[r(968)]))return null;_0x17f593[r(1492)](_0x423e32)}}async function Am(c,r){let s=t,l=e.VKzqk(_n,c[s(1500)].headers,e[s(1242)],"-1"),h=e[s(1204)](_n,c[s(1500)].headers,e.FWGWC,"1"),m=e[s(1239)](Er,c.message[s(497)],e.yaLav),y=e.fiTkl(Number,e[s(1226)](Er,c[s(1500)].headers,e[s(839)]))||0,S=Va[s(1603)](this,c),g=e[s(576)](_n,c[s(1500)][s(497)],e[s(1225)],"2"),L=e[s(1358)](Er,c[s(1500)].headers,e.tOhov),O=e.ZdFoq(Number,e[s(801)](Er,c[s(1500)][s(497)],"x-msg-cu"+s(364)+"ue"));if(S.isQoSAck)return e.tSYcb(r);let B=S[s(1173)+s(500)]?await Yl.call(this):null;if(c[s(1500)].service>0&&h&&!l||e[s(1380)](c[s(1500)][s(1566)],0))if(e[s(1575)](e.clZiP,s(1276))){let F=_0x38a62c[s(1603)](rxVpOu[s(974)](_0x551ee3,this),_0xa72b2b,..._0x2aa8d1);return _0x3ab1ce.set(F,_0x584c71[s(1645)]?_0x5947f8.sort():[_0x4ff645]),rxVpOu.PDhRO(_0x3c1725,F)}else{if(m&&S[s(1173)+s(500)]&&B)return!!!await B[s(1326)](m)&&(this[s(1775)+"hMessage"+s(1474)](c),await B[s(1753)](m,Date.now()+y)),r();if(g){let F=await ef[s(1603)](this);if(!F)return this[s(1775)+s(738)+s(1474)](c),e[s(1505)](r);let $=await F[s(1326)](L)??-1;if($<O)this[s(1775)+"hMessageEvent"](c),F[s(1753)](L,O,c[s(1500)][s(1566)]);else throw new Error(s(496)+s(1360)+s(1532)+O+(" larger "+s(1752)+"al cursor ")+$);return e[s(1407)](r)}return this["_dispatc"+s(738)+s(1474)](c),e.GeOuU(r)}}async function km(c,r){let s=t,l=Va[s(1603)](this,c);if(!l[s(1173)+"sage"])return r();let h=await Yl[s(1603)](this);if(l[s(1665)+s(871)+"age"]&&l[s(405)+"s"][s(1511)])for(let m of l[s(405)+"s"])await h.del(m);e[s(1148)](r)}async function Tm(c,r){let s=t,l=e.zqbvw(c[s(1500)][s(1205)+"e"],ym),h=e[s(488)](c[s(1500)].frameType,Xa);if(e[s(981)](!l,!h))return e.fQUyr(r);let m=e[s(1382)](Er,c[s(1500)][s(497)],e.nDDfB);if(!m)return e[s(1370)](r);let y=await ef[s(1603)](this,m);if(!y)return r();if(l)if(e[s(384)](e[s(1431)],s(1534))){let S=_0x131700.split(":");_0x13e149&&(_0x309d25=S.length),_0x47c3bd+=S[s(1511)];for(let g=0;g<S[s(1511)];g++)if(S[g][s(1511)]!==4){let L=_0x2357da[s(994)+"g"](0,4-S[g].length),O=L[s(1408)](S[g]);_0x3c3209[s(567)](O)}else _0xe6bc5a[s(567)](S[g]);_0x1aafb0=!1}else{let S=await y[s(830)+"rs"](),g={frameType:S?.[s(1205)+"e"],SeqID:ce[s(686)+"er"](this._seqId++),LogID:ce[s(686)+"er"](this[s(415)][s(1745)+s(1339)]()),service:9e3,method:5,headers:S?.headers,payload:S?.payload},L=e[s(1007)](b,g);this._ws&&this[s(1545)][s(1558)+"te"]&&this[s(1545)][s(933)](L)}if(h){let S=c[s(1500)][s(1177)];S&&y[s(1029)+"rs"](S)}}let Cm=async function(c,r){let s=t;this[s(1776)]=!1,e.IFczQ(clearTimeout,this[s(1378)+s(1251)+"utId"]),r()},Rm=async function(c,r){let s=t;if(!this[s(1545)]||this._ws[s(1558)+"te"]!==this[s(1547)])return e[s(1615)](r);let{pingInterval:l}=this[s(415)];this[s(1402)+s(1361)]?.[s(1248)+s(902)+s(1822)]();for(let m=0;m<this[s(602)+s(1797)][s(1511)];m++){let y=this[s(602)+s(1797)][m];if(this._ws.readyState===this[s(1547)]&&e[s(1719)](null,y))this[s(1545)]&&this._ws[s(933)](y),this[s(602)+s(1797)][m]=null;else break}this["_message"+s(1797)]=this["_message"+s(1797)][s(653)](m=>!!m),this["_pingPon"+s(1576)+"Id"]=e[s(522)](setTimeout,()=>this._ping(),l),this[s(1775)+"hOpenEvent"](c),this[s(357)+"er"]&&this[s(1545)]&&(this[s(1545)][s(572)+"pe"]=this[s(1379)+s(1624)]);let h=this["_endpoin"+s(1361)]?.["getCurre"+s(1025)+"nt"]();this[s(1270)](s(694)+h+s(1267)),r()},Pm=async function(c,r){let s=t,l=this["_endpoin"+s(1361)]?.[s(478)+s(1025)+"nt"]();this._debug(s(694)+l),r()};class Dm extends Wa{constructor(r){let s=t,l={DvyhC:function(S,g){return e[V(1542)](S,g)},SIcNm:function(S,g){return e[V(1050)](S,g)},bYQkp:function(S,g){return e[V(535)](S,g)},Clqju:e[s(955)],alzEW:e[s(1044)],VjlHJ:function(S,g,L){return e[s(1553)](S,g,L)},FfHZX:function(S,g){return S===g},YNrqn:s(1707),KrgtT:function(S,g,L,O){return e[s(1292)](S,g,L,O)},BoKMf:e[s(360)],DNwNq:function(S,g){return e[s(1342)](S,g)},qImZA:e.nxLRQ,JuRUP:"Module",pbYKF:function(S,g){return e[s(1090)](S,g)},zFJlY:e[s(369)],LsAcR:function(S,g,L){return e[s(768)](S,g,L)},axiva:function(S,g,L){return e[s(1764)](S,g,L)}};super(),this[s(566)+s(1777)+s(1769)]=!0,this[s(357)+"er"]=yr,this._isNode=Vg,this[s(1077)+"T"]=Gn,this[s(1030)+"X"]=wi,this[s(493)+"r"]=_i,this._messageQueue=[],this[s(1402)+s(1361)]=null,this[s(402)+s(554)]=!1,this[s(1379)+s(1624)]=e[s(1709)],this[s(1378)+s(1013)]=!1,this[s(1378)+s(1251)+s(1051)]=null,this[s(1183)+s(625)+s(1614)]=null,this[s(435)+s(1576)+"Id"]=null,this[s(636)]=0,this._isInit=!1,this._url="",this[s(1793)+s(1128)]=null,this[s(1329)+s(665)]=null,this[s(1252)+s(815)]=null,this[s(504)+"ls"]=e.ZjLQp,this[s(575)]=3,this.CONNECTING=0,this[s(1547)]=1,this[s(1773)]=2,this[s(802)]=S=>{let g=s,L={kommx:function(O,B,F){return e.eJBZN(O,B,F)},rhmHT:function(O,B,F){return e.qRysC(O,B,F)},gypmO:function(O){return e[V(1627)](O)}};if(e.XTtTI(e.WlEHi,e[g(816)]))try{e[g(745)]!=="WMqLC"?(FDyNCs[g(517)](_0x21609a,_0x39b879,8),FDyNCs.rhmHT(_0x2436e3,_0x304b19,_0x2c6c0c)):e[g(576)]($l,this,S,[Cm,Rm,Pm])}catch(O){let B=e[g(1461)](wt,g(1746),{message:O.message,code:wn[g(1157)+"OR"],error:O});this[g(1775)+g(863)+g(927)](B)}else FDyNCs.gypmO(_0x22a729),FDyNCs[g(1771)](_0x5235b5)},this._onMessage=async S=>{let g=s,{pingInterval:L,pingFrequency:O}=this._options;if((l.SIcNm("hi",S[g(960)])&&l[g(1429)](l[g(1012)],O)||l[g(763)]===O)&&(this[g(1400)+g(490)](),this[g(910)]("ping_onc"+g(1150)+"s","success"),this[g(435)+g(1576)+"Id"]=l[g(1109)](setTimeout,this[g(669)][g(1305)](this),L)),!l[g(574)]("hi",S[g(960)]))try{if(l[g(341)](l.YNrqn,l[g(1304)]))l.KrgtT($l,this,S,[dm,am,km,Tm,Am,cm]);else return XTMlim[g(574)](-1,this[g(1272)])&&XTMlim[g(1429)](-1,this[g(837)])?_0x11c304[g(1015)](0,0,this[g(340)]):XTMlim[g(1429)](-1,this[g(1272)])?_0xa1ab43.fromBits(0,XTMlim[g(1394)](this[g(837)],1),this[g(340)]):_0x224a70[g(1015)](this[g(1272)]+1,this[g(837)],this[g(340)])}catch(B){let F=l[g(1109)](wt,l[g(724)],{message:B[g(1500)],code:wn[g(1643)+g(327)],error:B});this[g(1775)+g(863)+g(927)](F)}},this[s(1261)]=S=>{let g=s,L={bCMNS:function(F,$){return l[V(1027)](F,$)},odvJD:l.qImZA,bjnVJ:l[g(1340)],KLzMP:g(377)+"le"},O=this[g(1402)+"tManager"]?.[g(882)+"chMaxTries"](),B=this[g(1402)+g(1361)]?.[g(478)+"ntEndpoint"]();if(O&&!S[g(1500)])if(l.pbYKF(l.zFJlY,l[g(1425)]))GvRlep[g(1052)](GvRlep[g(492)],typeof _0x5cd908)&&_0x4675ce[g(1518)+g(800)]&&_0x735295.defineProperty(_0x1e6744,_0x314e5a[g(1518)+g(800)],{value:GvRlep[g(1818)]}),_0x1160bd[g(824)+g(1266)](_0x5f0f12,GvRlep.KLzMP,{value:!0});else{let F="connect "+B+(g(1763)+g(1513)+g(533)+"ed");this[g(1775)+g(863)+g(927)](l.LsAcR(wt,l[g(724)],{message:F,code:wn["MAX_RETR"+g(943)+"R"],error:S}));return}this._ws&&l[g(1429)](this._ws[g(1558)+"te"],this[g(1547)])&&this[g(593)+g(1255)](),this._dispatchErrorEvent(l[g(1510)](wt,l[g(724)],{message:S.message,code:wn[g(1601)+g(1336)],error:S}))},this._onClose=async S=>{let g=s,L={wWOsD:function(B){return e[V(977)](B)},baekM:g(1699),dRIED:g(1746),ZeXeV:e[g(754)]};this[g(1800)+"mer"](),this["_clearPi"+g(490)](),this[g(773)+g(1730)+"rs"](),this[g(1545)]=null,this[g(1378)+g(1013)]=!1;let O=this[g(1402)+g(1361)]?.[g(882)+"chMaxTries"]();if(!O&&this["_navigat"+g(325)]()&&!this[g(402)+g(554)]){let B=this[g(1402)+g(1361)]?.["getCurre"+g(1025)+"nt"](),F=this[g(415)][g(528)+g(555)+g(1504)](S.code,S.reason);this[g(1775)+g(1613)+"ent"](e[g(564)](kt,g(1175),{code:1006,reason:S[g(828)]||g(1579)+"ng faile"+g(673)+g(1418)+g(684)+"ame: "+B,willReconnect:F})),F&&this[g(1378)]();return}if(S[g(1373)]!==1e3&&this["_readyCl"+g(554)]){this[g(1775)+g(1613)+g(927)](e[g(514)](kt,e[g(1455)],{code:1e3,reason:g(678)})),this["_endpoin"+g(1361)]?.["resetEnd"+g(902)+g(1822)](),this["_pingLos"+g(815)]?.["resetCou"+g(585)]();return}if(e.IrlNJ(1e3,S[g(1373)])&&O)if(e[g(1069)]===g(793)){let B={RVgvC:g(1746),wBkyX:function(de){return oniLHY.wWOsD(de)},NqlDC:"AbortError",GNMCW:function(de){return de()}},F=()=>{let de=g;_0x347619[de(963)+de(1331)+de(441)](de(1699),$),_0x1d093a[de(963)+de(1331)+de(441)](B.RVgvC,pe),_0x21de08[de(963)+"entListener"](de(1479),pe)},$=()=>{B[g(711)](_0x4752e3),B.wBkyX(F)},pe=()=>{let de=g;_0x2d82b8(_0x19f776[de(1746)]||new _0x4133dd(B.NqlDC,de(1108)+"or")),B[de(1307)](F)};_0x4e2b17[g(1107)+g(984)](oniLHY.baekM,$),_0x2d249f[g(1107)+"Listener"](oniLHY[g(472)],pe),_0x4b6678["addEvent"+g(984)](oniLHY.ZeXeV,pe)}else{let B=this._endpointManager?.[g(478)+"ntEndpoint"](),F=S[g(828)];F||(F=await e[g(842)](tm,this[g(654)])),F=g(1579)+g(1642)+"d, "+F+(g(1259)+g(705))+B+(g(1597)+g(1399)+g(455)),this[g(1775)+g(1613)+g(927)](e[g(541)](kt,e[g(1455)],{code:S[g(1373)],reason:F}));let $=g(1079)+B+(g(1763)+"ax retri"+g(533)+"ed");this[g(1775)+g(863)+g(927)](e[g(1833)](wt,e[g(360)],{message:$,code:wn[g(618)+g(943)+"R"]})),this[g(1402)+g(1361)]?.["resetEnd"+g(902)+g(1822)](),this._pingLossCounter?.[g(553)+"nter"]();return}if(e[g(624)](1e3,S[g(1373)])&&!S.reason){let B=this[g(1402)+g(1361)]?.[g(478)+g(1025)+"nt"]();this[g(1775)+g(1613)+g(927)](kt(e.DeTlc,{code:S.code,reason:g(1579)+g(1642)+g(673)+g(1418)+"n, hostn"+g(1033)+B})),this._endpointManager?.["resetEnd"+g(902)+"fig"](),this[g(1252)+g(815)]?.[g(553)+"nter"]();return}this._dispatchCloseEvent(S),this[g(1402)+g(1361)]?.[g(1248)+"pointConfig"](),this["_pingLos"+g(815)]?.[g(553)+g(585)]()},this[s(1338)]=null,this.onerror=null,this[s(1036)+"e"]=null,this[s(1419)]=null,this[s(1652)+s(1260)]=null,this[s(1716)+s(1827)]=null,this[s(1424)+s(1657)+"yReconnect"]=null,this[s(1582)+"nLine"]=this[s(1582)+"nLine"].bind(this),this[s(1582)+s(919)]=this[s(1582)+s(919)][s(1305)](this),this[s(1519)+"ageHide"]=this[s(1519)+s(1074)][s(1305)](this),this[s(1519)+s(918)]=this[s(1519)+s(918)][s(1305)](this),this[s(415)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e.FxbwE,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(1715)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:m}=r,y=Array[s(577)](h)?h:e.QcgRi(s(1397),typeof h)?[h]:[];if(!y||e[s(857)](0,y.length))throw new Error(e[s(1345)]);if(!e[s(1661)](Xg,m))throw new Error(e[s(1478)]);Object.assign(this[s(415)],r),this[s(1402)+"tManager"]=new Kl(y,this._options[s(1634)+"es"]),this[s(1252)+s(815)]=new em(this._options["pingLoss"+s(695)]),this[s(415)]["automati"+s(1440)]&&(this[s(1776)]=!0,this[s(1378)]()),this[s(415)][s(543)+s(414)+s(376)]&&(this[s(1077)+"T"]||this[s(1030)+"X"]?this[s(620)+s(1454)+s(560)]():this[s(357)+"er"]&&this[s(832)+s(1008)+s(984)]())}_handleOnLine(){let r=t;this._options[r(767)+"utoReconnect"]||this[r(402)+r(554)]||this[r(1207)+r(1260)]()}[t(1582)+t(919)](){let r=t;this[r(1188)+r(483)+"t"]();let s=e.JiDue(ja,e[r(1516)],{message:e[r(1700)]});this[r(1424)+r(1657)+r(1350)+"ct"]&&this[r(1424)+r(1657)+"yReconnect"](s)}[t(832)+t(1008)+t(984)](){let r=t;this[r(357)+"er"]&&window[r(1107)+r(984)](e.ftcVx,this[r(1582)+r(870)]),this[r(357)+"er"]&&window[r(1107)+"Listener"](e[r(1317)],this[r(1582)+"ffLine"]),this[r(357)+"er"]&&window["addEvent"+r(984)](e[r(880)],this[r(1519)+r(1074)]),this[r(357)+"er"]&&window["addEvent"+r(984)](e[r(1750)],this["_handleP"+r(918)])}[t(530)+t(1008)+t(984)](){let r=t;this._isBrowser&&window[r(963)+r(1331)+r(441)]("online",this[r(1582)+r(870)]),this[r(357)+"er"]&&window["removeEv"+r(1331)+r(441)](e[r(1317)],this._handleOffLine),this[r(357)+"er"]&&window["removeEventListe"+r(441)](e[r(880)],this[r(1519)+r(1074)]),this[r(357)+"er"]&&window[r(963)+r(1331)+r(441)](r(1206),this[r(1519)+r(918)])}[t(1519)+t(1074)](r){let s=t;!r.persisted&&(this._isBrowser&&window[s(963)+s(1331)+s(441)](e.GhpYy,this[s(1519)+s(1074)]),this._isBrowser&&window[s(963)+s(1331)+"ner"](e.zJaqZ,this._handlePageShow),this[s(1175)]()),this[s(357)+"er"]&&window[s(963)+s(1331)+"ner"](e[s(1829)],this[s(1582)+s(870)]),this[s(357)+"er"]&&window[s(963)+s(1331)+s(441)](e.ZaINm,this["_handleO"+s(919)])}[t(1519)+"ageShow"](r){let s=t,l={tllur:function(h,m,y){return e.eUZAL(h,m,y)}};r.persisted&&(e[s(513)]!==e[s(513)]?this[s(910)](s(1746),DXVMIl[s(949)](_0x9dfaee,s(1746),{..._0x4f427f,message:_0x3423ce[s(843)]||""})):(this[s(592)+s(325)]()&&(!this[s(1545)]||e.XeLaC(this[s(1545)].readyState,this[s(1547)])||e[s(1540)](this[s(1545)][s(1558)+"te"],this[s(1135)+"NG"]))&&this["_handleO"+s(870)](),this[s(357)+"er"]&&window[s(1107)+s(984)](e.ftcVx,this[s(1582)+"nLine"]),this._isBrowser&&window[s(1107)+s(984)](e.ZaINm,this[s(1582)+s(919)])))}async[t(1309)+t(1294)](r){let s=t,l={fNORl:function(h,m,y,S){return e.PBygh(h,m,y,S)},WClJH:e[s(1427)],ecUlZ:"x_fronti"+s(774)+"ck",BeiDa:s(395)+s(453)+"k",xDfJd:function(h,m,y){return e[s(564)](h,m,y)},XGeRl:e.WUTJW,XRSGR:function(h,m){return h(m)},aHBfF:e[s(1551)]};if(e.WRxwo!==e[s(1756)]){let h=!!this[s(415)][s(396)+"S"];if(!h)return{enabled:h,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let m=SRLljZ[s(1790)](_0x81db6f,_0x52c841[s(1500)].headers,SRLljZ[s(359)],"2"),y=m&&SRLljZ[s(1790)](_0xca4eaa,_0x2de7a8[s(1500)].headers,SRLljZ[s(464)],"1"),S=m&&_0x23bb66(_0xef0b05[s(1500)][s(497)],SRLljZ[s(1499)],"1"),g=S?SRLljZ[s(844)](_0x1c1a94,_0xe17211[s(1500)][s(497)],SRLljZ[s(626)])?.[s(1622)](",")[s(653)](_0x1a42b5)||[]:[];return{enabled:h,isQoSMessage:m,isQoSAck:y,isAckCleanupMessage:S,ackMsgIds:g}}else{let{fpID:h,deviceID:m,bddID:y,ttwID:S,accessKey:g,aID:L,customParams:O={},enableAutoAck:B,enableQoS:F,QoSLevel:$,env:pe}=this[s(415)],de,be,Ae;if(this[s(357)+"er"]||this[s(1030)+"X"]||this[s(1077)+"T"])de=location&&e[s(676)](e[s(531)],location.protocol)?e[s(976)]:s(878),be=r.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),Ae=/^wss(.*:\/\/)/[s(945)](r)?r:""+de+be;else if(e[s(1333)](e.sXDQp,e[s(1457)])){let yi={CAHRT:function(En,bn){let Lm=s;return SRLljZ[Lm(386)](En,bn)}};_0x608bf9[s(1107)+s(984)](SRLljZ.aHBfF,En=>{let bn=s;_0x2a428f(yi[bn(1351)](_0x5cf4d3,_0x94b2dc[bn(836)]),En[bn(1610)+"on"],En[bn(1420)+"on"],_0x2658d7(_0x5c848c[bn(1567)+bn(817)]))})}else de="wss://",be=r.replace(/(^http)((?:[s]*:\/\/))/,""),Ae=/(^ws)((?:[s]*:\/\/))/[s(945)](be)?be:""+de+be;let yn=y?e[s(1481)]:S?e[s(1390)]:s(446)+"d",Tt=y||S||m;if(e.AnzQz(!Tt,!yn))throw new Error(e.xfvFF);let br=e[s(916)](e.UGXQj,typeof O)?await O():O,Ya=pe?e[s(322)](Qg,pe.xUseEnv,pe[s(1095)]):{},Qa=Object[s(924)]({device_platform:e[s(649)],version_code:e[s(1406)],access_key:g,fpid:h,aid:L,[yn]:Tt,xsack:B?1:0,xaack:B?1:0,xsqos:F?1:0,qos_level:F?$:void 0,qos_sdk_version:2,...Ya},br),Om=Object[s(440)](Qa)[s(1295)]((yi,En)=>Qa[En]!==void 0?""+yi+(yi?"&":"?")+En+"="+Qa[En]:yi,"");return Ae+s(1514)+Om}}async _connect(){let r=t,s={VxeEw:e[r(1829)],jDPXO:e[r(1317)],JrRhy:e[r(1750)]};if(!(this[r(1378)+r(1013)]||this[r(402)+"osed"])){this[r(1378)+r(1013)]=!0;try{if(e[r(1300)](e[r(1368)],e.RNVgr)){let h=""+_0x4f7c98.now(),m=_0x2403be||(_0x590c8c=e[r(795)](_0x545a6e,_0x1ced8b)),y=_0x2e3af5.random()[r(1518)](16)[r(899)](-6);return e[r(1164)](e[r(1223)]("02",h),m)+y}else{let l=this[r(1402)+r(1361)]?.[r(1594)+r(750)+r(401)+r(1550)+r(1664)](),{timeoutInterval:h}=this[r(415)];if(l){let y=this[r(1402)+"tManager"]?.["getCurre"+r(1025)+"nt"](),S=this["_endpoin"+r(1361)]?.[r(641)+r(1607)+r(1780)+"UpdateCount"](),g=this["_endpoin"+r(1361)]?.[r(478)+r(1025)+r(1134)+r(883)]();if(S)if(e.eUPLx("eXMIZ",e.mNOFk)){let L=r(1079)+y+(r(1059)+r(1597)+"tries re"+r(982)+r(947)+r(1651)+r(1724))+S+(r(1817)+"y"),O=e[r(1035)](wt,e[r(360)],{message:L,code:wn[r(618)+r(943)+"R"]});this[r(1270)](L),this["_dispatc"+r(863)+"ent"](O),this[r(654)]=await this[r(1309)+"eUrl"](S),this[r(1270)]("connect "+S+" "+g+r(337)),this[r(773)+r(1730)+"rs"]()}else this[r(357)+"er"]&&_0x22f3d2[r(1107)+r(984)](rYxiZb[r(1825)],this[r(1582)+r(870)]),this[r(357)+"er"]&&_0x2c30b1["addEvent"+r(984)](rYxiZb.jDPXO,this[r(1582)+"ffLine"]),this[r(357)+"er"]&&_0x3fc535[r(1107)+"Listener"]("pagehide",this[r(1519)+"ageHide"]),this[r(357)+"er"]&&_0x6be7f4[r(1107)+r(984)](rYxiZb[r(847)],this[r(1519)+r(918)]);else{let L=r(1079)+y+(" timeout"+r(1597)+r(1399)+r(455));this[r(1270)](L),this[r(1775)+r(863)+r(927)](e[r(970)](wt,r(1746),{message:L,code:wn[r(618)+r(943)+"R"]}));return}}else if(e.gMuio(e[r(539)],e[r(539)])){if(e[r(1654)](4,_0x19d02e[r(1511)])){let y=_0x4377f2[r(994)+"g"](0,e[r(1392)](4,_0x5ea55[r(1511)])),S=y.concat(_0x225a16);_0x2af80a[r(567)](S)}else _0x4f054e[r(567)](_0x198e3b);_0x305e77&&(_0x2f42c8+=1),_0x1162c6+=1,_0x28a349=!1}else{let y=this._endpointManager?.[r(478)+r(1025)+r(1697)+r(1729)](),S=this[r(1402)+"tManager"]?.[r(478)+"ntEndpoi"+r(1134)+"ount"]();this[r(654)]=await this["_generat"+r(1294)](e[r(727)](y,"")),this[r(1270)](r(1079)+y+" "+S+r(337)),this[r(773)+r(1730)+"rs"]()}if(this[r(1776)])this[r(1776)]=!1;else{let y=e.AZVUy(ja,e[r(1516)],{message:r(1196)});this[r(1652)+r(1260)]&&this[r(1652)+"econnect"](y)}let m=this["_endpoin"+r(1361)]?.[r(478)+r(1025)+r(1134)+r(883)]()||0;m>1&&await this[r(1630)](m-1),this[r(1270)]("connecti"+r(971)+this._url+(r(451)+"ls: ")+this[r(504)+"ls"]),this[r(1545)]=e[r(355)](Zg,{url:this[r(654)],protocols:[this[r(504)+"ls"]],headers:this._options[r(1520)+"ramParams"][r(898)+r(1437)]},this[r(415)].ws),(this[r(357)+"er"]||this[r(493)+"r"])&&this._ws&&(this[r(1545)][r(572)+"pe"]=this[r(1379)+r(1624)]),this[r(1781)+r(956)](),this[r(1378)+r(1251)+r(1051)]=e[r(1515)](setTimeout,this._onTimeout.bind(this),h)}}catch(l){throw this._connectLock=!1,l}}}["_clearTi"+t(1113)](){let r=t;e.StfKX(clearTimeout,this[r(1378)+r(1251)+r(1051)]),this[r(1378)+r(1251)+r(1051)]=null}[t(1400)+t(490)](){let r=t;e[r(704)](clearTimeout,this[r(435)+"gTimeoutId"]),e[r(795)](clearTimeout,this["_reconnectTimeou"+r(1614)]),this[r(435)+"gTimeoutId"]=null,this["_reconnectTimeou"+r(1614)]=null}[t(1270)](...r){let s=t;this._options[s(1448)]&&console[s(1492)][s(939)](console,[e[s(992)],...r])}[t(1064)+"rvalValue"](r){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:m}=this[s(415)],y=e.KGxEv(l,Math[s(1525)](m,r-1));return e[s(1751)](y,h)?h:y}[t(669)](){let r=t;if(this[r(1545)]&&this[r(1545)][r(1558)+"te"]===this.CONNECTING){this._clearPingTimer(),this[r(435)+r(1576)+"Id"]=e[r(1459)](setTimeout,this[r(669)][r(1305)](this),this[r(415)][r(1106)+"rval"]);return}if(!this._ws||e[r(398)](this._ws[r(1558)+"te"],this[r(1547)]))return void this[r(1207)+r(1260)]();this[r(1545)]&&this[r(1545)][r(933)]("hi"),this["_reconne"+r(625)+r(1614)]=e[r(674)](setTimeout,this["_handleR"+r(1260)+r(896)][r(1305)](this),this._options[r(598)+r(1168)+r(646)])}[t(1207)+t(1260)+t(896)](){let r=t;this[r(1252)+"sCounter"]?.addCount(),this.emit(e[r(390)],e[r(1355)]),this[r(1252)+r(815)]?.[r(882)+r(328)+"nt"]()?this[r(1207)+"econnect"]():this[r(669)]()}[t(592)+t(325)](){let r=t;return this[r(1077)+"T"]||this._isMiniWX?this["_miniNav"+r(1777)+r(1769)]:(this[r(357)+"er"]||this[r(493)+"r"])&&this[r(415)][r(543)+"tworkCha"+r(376)]?navigator.onLine:!0}["_handleR"+t(1260)](){let r=t;!this["_navigat"+r(325)]()||this[r(402)+r(554)]||(this[r(1402)+r(1361)]?.[r(1248)+r(902)+"fig"](),this[r(1252)+r(815)]?.[r(553)+r(585)](),this[r(1545)]?this[r(593)+r(1255)](1001,e[r(1102)],!0):this[r(1378)]())}[t(620)+t(1454)+"ange"](){let r=t,s={sHlcB:function(l,h,m){return e[V(447)](l,h,m)},ViyOz:function(l,h){return l!==h},avpaz:e[r(1680)],MdYZC:e[r(1312)]};this[r(1077)+"T"]?tt["onNetworkStatusC"+r(1824)](({isConnected:l})=>{let h=r,m={ixVoo:function(y,S,g){return s.sHlcB(y,S,g)}};s[h(715)](s[h(1741)],s[h(1121)])?(this["_miniNav"+h(1777)+"line"]=l,l?this[h(1582)+h(870)]():this[h(1582)+h(919)]()):(_0x3938c4(_0x4310f4,74),XwpckS[h(664)](_0x4432f2,_0x246235,_0x4533a7))}):this[r(1030)+"X"]&&wx[r(548)+r(819)+"hange"](({isConnected:l})=>{let h=r;this[h(566)+h(1777)+"line"]=l,l?this[h(1582)+"nLine"]():this["_handleO"+h(919)]()})}_wait(r){let s=t,l={BzvNF:function(h,m){return e[V(790)](h,m)},YSSYQ:function(h,m,y){return e[V(1358)](h,m,y)}};if(e[s(1389)](e.RXiyq,e[s(867)]))_0x502eb5+=thGSnL[s(1332)](_0x252f94,_0x525e6c),_0x172726++;else return new Promise(h=>{let m=s;l[m(1480)](setTimeout,h,this["_getInte"+m(1245)+"e"](r))})}["_disconn"+t(1255)](r=1e3,s="",l=!1){this[t(1545)]&&this._destroyWebSocket(r,s,l)}[t(821)+"ut"](){let r=t,s=this["_endpoin"+r(1361)]?.[r(478)+r(1025)+"nt"]();this[r(1270)](r(1079)+s+r(1059)),this[r(593)+r(1255)](1001,e[r(1668)],!0)}[t(1220)](r){let s=t,l=Qt(r);this._ws&&this._ws[s(1558)+"te"]===this[s(1547)]&&(this._ws&&this._ws[s(933)](l),this[s(1270)](e[s(1318)],r))}[t(773)+t(1730)+"rs"](){let r=t,s=e.gPLnk[r(1622)]("|"),l=0;for(;;){switch(s[l++]){case"0":if(!this[r(1545)])return;continue;case"1":this[r(1545)][r(963)+r(1331)+"ner"](r(1746),this[r(1261)]);continue;case"2":this[r(1545)][r(963)+"entListe"+r(441)](e[r(408)],this[r(802)]);continue;case"3":this[r(1545)]["removeEv"+r(1331)+r(441)]("message",this._onMessage);continue;case"4":this[r(1545)][r(963)+r(1331)+"ner"](e[r(1455)],this[r(465)]);continue}break}}[t(1781)+t(956)](){let r=t,s=e[r(1081)][r(1622)]("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(1545)]["addEvent"+r(984)](e.PLgri,this._onOpen);continue;case"1":if(!this[r(1545)])return;continue;case"2":this[r(1545)][r(1107)+r(984)](r(1746),this[r(1261)]);continue;case"3":this[r(1545)][r(1107)+r(984)](e[r(1539)],this[r(1002)+"ge"]);continue;case"4":this[r(1545)][r(1107)+r(984)](e[r(1455)],this._onClose);continue}break}}["_wsInsta"+t(911)](r=1e3,s=""){let l=t;try{this[l(1545)]&&this[l(1545)][l(1175)](r,s)}catch{}}[t(1188)+t(483)+"t"](r=1e3,s="",l=!1){let h=t;if(this[h(1400)+h(490)](),this[h(1800)+"mer"](),this[h(773)+h(1730)+"rs"](),this[h(662)+h(911)](1e3,s),this[h(1378)+h(1013)]=!1,l&&this[h(592)+"orOnline"]()&&!this["_readyCl"+h(554)]){if(this[h(1402)+h(1361)]?.[h(882)+h(342)+"es"]()){let y=this[h(1402)+"tManager"]?.[h(478)+h(1025)+"nt"]();this["_dispatc"+h(1613)+h(927)](kt(e[h(1455)],{code:1006,reason:h(1079)+y+(" timeout"+h(1597)+h(1399)+h(455)),wasClean:!0}))}else{let y=this[h(415)]["reconnec"+h(555)+h(1504)](r,s);this[h(1775)+h(1613)+h(927)](e[h(967)](kt,e[h(1455)],{code:r,reason:s,wasClean:!0,willReconnect:y})),y&&this[h(1378)]()}return}this._navigatorOnline()||this[h(402)+h(554)]?this[h(1775)+h(1613)+"ent"](kt(e[h(1455)],{code:r,reason:e.wMPJr})):this[h(1775)+"hCloseEv"+h(927)](e[h(1226)](kt,e[h(1455)],{code:1006,reason:h(907)+h(827)+h(484)+"ine"})),this._ws=null,this[h(1402)+"tManager"]?.[h(1248)+h(902)+h(1822)](),this[h(1252)+"sCounter"]?.[h(553)+h(585)]()}[t(1775)+t(1496)+"nt"](r){let s=t;this.emit(e[s(408)],r),this[s(1419)]&&this[s(1419)](r)}[t(1775)+t(738)+t(1474)](r){let s=t;if(e[s(473)]("sQkhm",e[s(1466)]))this[s(910)](e[s(1539)],r),this[s(1036)+"e"]&&this[s(1036)+"e"](r);else return _0x44c0df.log(e[s(1130)],_0xaec748,_0x124bea,_0x10dbb9),this._qosDB[s(1753)]({cursor_name:_0x3cc0e1,cursor:_0x10ea7d,service:_0x1111e4})}[t(1775)+t(382)+"ageEvent"](r){let s=t;this[s(910)](e[s(835)],r),this[s(1716)+s(1827)]&&this[s(1716)+s(1827)](r)}[t(1775)+t(863)+t(927)](r){let s=t;this[s(910)](s(1746),r),this[s(1577)]&&this[s(1577)](r)}[t(1775)+t(1613)+t(927)](r){let s=t;this[s(910)](e.DeTlc,r),this[s(1338)]&&this[s(1338)](r)}get binaryType(){let r=t;return e.vwwCX===e[r(1689)]?new _0x9c93b0(_0x5b6e8f,{message:_0x1d2fb5,code:_0x3a8731,error:_0x54b4d4}):this._ws?this[r(1545)][r(572)+"pe"]:this["_binaryT"+r(1624)]}set[t(572)+"pe"](r){let s=t;this[s(1379)+s(1624)]=r,this[s(1545)]&&(this._ws[s(572)+"pe"]=r)}get[t(324)+"nt"](){let r=t;return this[r(1402)+"tManager"]?.[r(478)+"ntEndpoi"+r(1134)+r(883)]()||0}get[t(1648)+"Amount"](){let r=t;return this[r(602)+"Queue"].reduce((l,h)=>(l+=h&&h[r(1826)+"th"]||0,l),0)+(this._ws?this[r(1545)]["buffered"+r(736)]:0)}get[t(521)+"ns"](){let r=t;return this._ws?this._ws[r(521)+"ns"]:""}get[t(1449)](){let r=t;return this[r(1545)]?this[r(1545)][r(1449)]:""}get[t(1558)+"te"](){let r=t;return this[r(1545)]?this[r(1545)][r(1558)+"te"]:this[r(415)][r(691)+r(1440)]?this.CONNECTING:this[r(575)]}get[t(397)](){let r=t;return this._ws?this[r(1545)][r(397)]:this[r(654)]}close(r=1e3,s){let l=t,h=e[l(1087)].split("|"),m=0;for(;;){switch(h[m++]){case"0":this[l(1400)+"ngTimer"]();continue;case"1":if(this[l(1545)][l(1558)+"te"]===this[l(575)]||e.vcIsH(this._ws[l(1558)+"te"],this.CLOSING))return void this._debug(e[l(1549)]);continue;case"2":this[l(1800)+l(1113)]();continue;case"3":this[l(402)+l(554)]=!0;continue;case"4":this[l(530)+l(1008)+l(984)]();continue;case"5":this["_QoSMana"+l(1128)]?.[l(796)]();continue;case"6":this["_destroy"+l(483)+"t"](r,s);continue;case"7":if(!this._ws)return void this[l(1270)]("close, ws instan"+l(1323)+l(1453)+"ed");continue}break}}async[t(933)](r,s){let l=t;if(e.QTJgX(null,r))throw new Error(e.cURCE);e.bLRCO(e[l(561)],typeof r)&&(r=JSON[l(1353)+"y"](r)),e[l(1708)](e.ASApT,typeof r)&&!e[l(703)](r,ArrayBuffer)&&!(r[l(476)]&&e[l(834)](r.buffer,ArrayBuffer))&&(r=JSON[l(1353)+"y"](r));let h=await e.idfbv(Zl,r),m=Yg(r),{method:y=0,service:S=this[l(415)][l(1566)],logID:g=this[l(415)][l(1745)+l(1339)](),headers:L=this[l(415)][l(497)],payloadEncoding:O=this[l(415)][l(391)+l(1143)],payloadType:B=this[l(415)][l(1009)+l(1624)],logIDNew:F=this[l(415)][l(411)+l(1321)][l(952)+l(954)+l(1596)+"ew"]?e[l(542)](i,this[l(415)].logIDNewConfig[l(685)]):""}=e[l(1154)](s,{});if(!S)throw new Error(e.hftLs);let $={SeqID:ce[l(686)+"er"](this._seqId++),LogID:ce[l(686)+"er"](g),service:S,method:y,headers:L,payloadEncoding:e[l(1065)](O,Object)?O.encoding?O[l(806)]:"":O,payloadType:e.QWrVf(B,Object)?B[l(1097)]?B[l(1097)]:m:B||m,payload:h,LogIDNew:F},pe=e[l(1172)](Qt,$);return this._ws&&this._ws[l(1558)+"te"]===this[l(1547)]?(this[l(1545)]&&this[l(1545)][l(933)](pe),this._debug(e[l(519)],$)):this[l(602)+l(1797)][l(1511)]<this[l(415)][l(450)+l(1552)+"ength"]?(this[l(602)+l(1797)][l(567)](pe),this._debug(e[l(1617)],$)):(this["_message"+l(1797)].shift(),this._messageQueue[l(567)](pe)),{seqID:this[l(636)],logID:g,logIDNew:F}}async[t(528)+"t"](r){let s=t,l={mmJjr:function(y,S){return e[V(1616)](y,S)}},{url:h}=e[s(1201)](r,{}),m=Array[s(577)](h)?h:e.BszbC(e[s(1533)],typeof h)?[h]:[];if(r&&Object[s(924)](this[s(415)],r),m&&m[s(1511)]?this[s(1402)+s(1361)]=new Kl(m,this[s(415)][s(1634)+"es"]):this[s(1402)+s(1361)]?.["resetEnd"+s(902)+"fig"](),this[s(1252)+"sCounter"]?.[s(553)+s(585)](this[s(415)][s(1224)+s(695)]),this[s(402)+s(554)]=!1,this[s(1545)]&&e[s(1090)](this._ws[s(1558)+"te"],this[s(575)]))this[s(593)+s(1255)](1e3,e[s(1600)],!0);else if(e[s(1458)](e[s(931)],e[s(931)]))this._isInit=!0,this._connect();else if(Bziorf.mmJjr(_0x527a56,_0x27cfa5))return _0xf787d0}async[t(1442)](){let r=t;if(!this[r(1378)+r(1013)]){let s=(r(1041)+"3").split("|"),l=0;for(;;){switch(s[l++]){case"0":this[r(402)+"osed"]=!1;continue;case"1":this[r(1252)+r(815)]?.["resetCou"+r(585)]();continue;case"2":this[r(1402)+r(1361)]?.[r(1248)+r(902)+r(1822)]();continue;case"3":this[r(1378)]();continue;case"4":this[r(1776)]=!0;continue}break}}}["addEvent"+t(984)](r,s){this.on(r,s)}[t(442)+"Event"](r){let s=t,{type:l}=r;this[s(910)](l,r)}[t(963)+t(1331)+t(441)](r,s){this.off(r,s)}pingOnce(){let r=t,s={Fknum:function(l,h){return e[V(897)](l,h)},zAXtZ:"success",VINkn:e[r(1375)],LmPAN:r(1369)+r(590)+"t",TggNy:function(l,h,m){return e[r(322)](l,h,m)}};return new Promise((l,h)=>{let m=r,y={CNRXg:function(L,O){return s[V(1047)](L,O)},qXMCZ:s[m(1244)],sMpvk:m(1369)+m(590)+"t"};this[m(1400)+m(490)](),this[m(435)+m(1576)+"Id"]=s[m(687)](setTimeout,this[m(669)][m(1305)](this),this[m(415)][m(1106)+"rval"]);let S=()=>{let L=m;s.Fknum(l,s[L(1649)]),this[L(670)](s[L(1244)],S),this.off(s[L(1216)],g)},g=()=>{let L=m;y[L(469)](h,L(1118)),this[L(670)](y[L(545)],S),this[L(670)](y[L(333)],g)};this.on(m(1369)+m(1150)+"s",S),this.on(s.LmPAN,g),this[m(669)]()})}}})(),He[M(721)+M(826)]=Me[M(721)+M(826)],He[M(1120)+M(980)]=Me[M(1120)+M(980)],He[M(964)+"e"]=Me[M(964)+"e"],He[M(1474)]=Me[M(1474)],He.FWS=Me[M(1381)],He["Frontier"+M(352)+M(431)]=Me[M(1423)+M(352)+"vent"],He[M(352)+M(431)]=Me["MessageE"+M(431)],He[M(491)+"t"]=Me[M(491)+"t"],He["Reconnec"+M(1795)]=Me[M(766)+M(1795)],He["createCl"+M(826)]=Me["createCl"+M(826)],He["createEr"+M(980)]=Me["createEr"+M(980)],He[M(917)+M(853)+"nt"]=Me[M(917)+M(853)+"nt"],He[M(849)+M(381)]=Me[M(849)+M(381)],He["createRe"+M(1765)+M(431)]=Me["createRe"+M(1765)+M(431)],He[M(1732)+M(999)]=Me[M(1732)+M(999)],He[M(498)+"ame"]=Me[M(498)+M(887)];for(Ea in Me)[M(721)+M(826),M(1120)+"rorEvent",M(964)+"e",M(1474),M(1381),"Frontier"+M(352)+M(431),M(352)+"vent",M(491)+"t",M(766)+M(1795),M(940)+M(826),M(393)+M(980),M(917)+"ssageEvent","createOp"+M(381),M(392)+M(1765)+M(431),M(1732)+M(999),M(498)+M(887)][M(1611)](Ea)===-1&&(He[Ea]=Me[Ea]);function ka(){let t=["y1nnuuS","zMzLCG","CgjduhC","zKfstwy","ywjVCNq","wvntwve","zvrxyKq","D2fVu0G","x2zVCM1HDeu","sNnHDxe","CwLHDKC","qNHduNa","quzlrM0","ywjfwwC","uKzcCfu","y2XoC0u","sufIuKW","Bg9N","zg1MCKC","wvzoDMe","CwvJvKu","Ae9Wzw5fDMu","yMrpuw4","vxPPAgy","qMvPrge","BwvZC2fNzq","vvfWrfC","EujxCui","ywXSzwqGBxu","ChrVCG","yvfKA0G","B2nRzxrtDwm","tgLQCvm","u2HtzeK","sg9QAwK","yxHPDMe","BgvUz3rO","nxW0FdD8mhW","yxGGCMv0CMK","l3DZl3yY","wgf6ywu","s0fLr0m","tg50DMS","Dg9tDhjPBMC","x2HHBMrSzva","BwLUAvbYB2C","ENLezNy","y3vhAKi","Cg9W","rgneCxO","Cg93","BMCGB3iGyw4","Bvj2q1q","vvrkCvu","CuDdAu0","zxjFywnRx20","ve1cEvm","ign1CNnVCIa","qvnbCfq","BhPXsKC","y2HHCKnVzgu","x2n1CNnVCKy","Au1kzgi","BerOsxe","EwzeALy","sgDJvwq","ruvVDem","suDiq2S","CLzHBhvLCW","wKPkD0G","x3DZ","vLDgCe0","t1bftG","A0LfvKm","vhv4Dwm","AgvKtwf4uMu","B0DUB28","z2vrDwv1zuW","Dxnyr00","ExfXy0K","Aw1LCYbPBIa","CMTLCKDSB2i","yxLIrxy","CMvHzhLtDge","D0nQwva","DwLouKm","A1jMCgm","qvbtEeG","EgrmEfK","nhWYFdf8m3W","tgjSzM8","C2vYDMLJzq","DhjHBNnHy3q","CgzPsui","wuXIs3i","ywDLrxzLBNq","yvnrEfC","tg9Nsuq","qLHSz0i","vNvUy1e","B2LRtgS","z1rPBwvVDxq","B25LCNjVCG","wgz0EwK","y29UBMvJDgK","B2jlvfq","B0vvAve","x2HHBMrSzu8","Dw5KzwzPBMu","B25fCNjVCG","nZCYnJC3rMXoELfK","C2v0zgi","zNfgvhi","zM9YrwfJAa","BhHKt2G","BMXWrwC","u2vYDMLJzvC","DwvRu2q","rfrrsMC","y2HLy2TdDxi","DMfSDwu","DgvmB2Djre4","lcbTyxGGCMu","z2v0sxrLBq","AxnszwfKEq","Be1pz0W","tKfusvzfx0u","ALnpEwK","y2fSBa","rLDlzMS","v2zywKq","sg1JC0O","ywnRDxbfBMq","BMnqug8","turdrMy","B2XKvMvYC2K","Aw5KzxHpzG","ALPkweu","AenSB3nLrxy","DeLK","Ae5RtKK","C2nOtxi","BNfjrhy","BgvY","mhWZFdf8nhW","CKjnrfi","qvb3vLO","C3bSAxq","DLfpqKS","ExbL","C3bSAwnL","y1n0B3i","rMvPywq","Dg9Y","vLLOzem","x3DHAxq","CMvWBgfJzq","rxDxrui","BKrQv2q","Bwf4uMv0CMK","u1j3D2W","ihrYEsbYzwm","wxH2Deu","zKfrsfe","DMvYC2LVBMm","suvhCMK","BxnN","BMCGzMfPBgu","tuvtu0fhrv8","ufjcAgW","C29YDa","EKjtC2C","z0DfuKq","yNvMzMvYzwq","EKfyDfO","vMnNANq","yMfJA3vWigu","B25tDgfYDfi","zwDHzgW","EwjtAMq","zxf1ywXZ","CMznrxa","BwvKAwf0zwW","CMvHzhDYAxq","CuHAue8","yM9KEq","A3riv0e","BM1pwNe","vK1IDxi","DhjPzxm","Axnby2TdBgu","DMLJzuLeig8","x2rItMfTzq","vefJDeW","EK1StKy","Ae9Hthy","ywrKt25L","D2fgy2K","AKzpEwC","vhvyz04","y0TOyw0","yxPZD1y","CYbHBhjLywq","y29UDgLUDwu","BuPADNu","uNzWvLi","u1jPsgu","DMvY","A2v5","D3jPDgu","rKrJug0","ywrK","vvDir1u","x2LUAxrqCM8","z05gs1e","u0XsuuW","Dg9oDw1Izxi","AxnAzxjV","wK1Otui","ANrkBNm","BMDcEKm","zwTcBxy","BNrbBMrvCgq","mxWZFdb8nxW","y29TCgXLDgu","thvyExm","DuPkqK8","rMLMtKm","BhrPCgXLihq","tKvhreG","t3PgzLy","B2nRzxrgywK","vLbLwMy","uKDwBhC","AM5Az0u","A1j4twm","sKfbq0O","sLnptLa","tg5vzwm","z2vtEw5J","EgL0suW","B25szwnLAxy","DePVuKK","mxWWFdr8m3W","sxjStKO","wvj1CxO","x2nYzwf0zvm","vvHpwMe","u3Lns2y","BMrWB2LUDca","q3DICxy","ChD4Dui","mZG1mta0nMTUsKDVrq","q1nrBfK","yxrLq291BNq","C0XPC3rLBMu","DgLUzYbZzxi","zgvJB2rLzey","BNHmuLe","wMDAwuu","Aw5PDcbrB1m","y3vYCMvUDeK","rNblDxa","C2v0y3vYC28","tuvPqKG","swXQwg8","yxzWyxO","u3nTEMW","s2fjvw4","rwLuqLC","Bg9Nsurhzw4","zxjYB3i","rMzvrhy","yNL0zu9MzNm","ywr2yw5Jzq","EKPHCvO","thrwB3e","DgHHBIbSB2m","C2v0","yMXVy2TLza","BM5Ly3q","v1j4D28","sLHKvLa","vw5YBfy","wMLWBvi","C3vWyve","Bgf4sNy","v01Qt0O","igzHAwWSig0","qLj0Aue","y29UBMvJDeu","tMvyquu","Ee9ctee","AgvHzgvY","BgLUzq","AM9PBG","z3LWBu8","s25oA1i","q0Xpu0LorW","yxnL","x2rPC3bHDgm","x2LZsw5PDa","AwDHDg9Yt24","vMPQC2S","EevlAxa","Cg9PBNrbBMq","x2fKzfDZtgK","rwHWCKW","B2zMBgLUzq","CwXkuvm","BK5Xy0C","CMvXDwLYzwq","qNjPzgDL","v050wgm","D0jcBxe","zK5puMW","CgjICdi","z3jPt3e","x1fVu01HBMe","ywXPzcb1CMW","Dev2zw50","C3HNyuO","uxvLDwu","quXTzLi","z0DTCfy","x2nSzwfYvgK","CNjVCK1LC3m","CM92AwrLigi","Bwv0Ag9K","tKDFrvjst1i","uvnYsLq","y1DRwve","D2vI","C3Pvq0e","AxnFywnR","wLDAs0q","EsbJBg9Zzwq","CwzqDue","uuTssw0","CLvfvgu","wevkt0e","BND4v1G","ihrVihjLDhi","yMPUvKO","vKrfqKG","u25hwu8","wgnAtMe","zMLN","CuDNv24","AgfUz2u","vNHLrxC","yNL0zuXLBMC","zufJAW","Ahr0Chm6","zNrJvNG","qLzNAey","uvvwBeG","CgfKuLC","AhrRzeu","Bgr1u1K","zgrjrcWGzgu","AhzoA3u","v2LUzg93","vxbKyxrLq28","wM9xs2q","zLvKyxy","AhzpDKG","C3rVCMu","swjez1K","u29ls0O","AwXLx25HBwu","CMv0CNLdB3u","B3jpBMXPBMu","DxrMofDYAxq","rvjst1i","y2HnyxHdB3u","B3jLtMfTzxm","sKLdr3u","z0LYEw8","AuTcD1e","C01WDMS","yMLNAfG","ueLnBeO","AuzJuwy","ihrPBwvZ","y3vYC29YlNm","zNjVBunOyxi","Dw5ZAwDUzwq","rMziwLG","y2HnyxHuCMK","tMTMCge","yuDRvgi","nhWY","ANDvuwO","tfb2q28","Cw9Z","DKT0sue","thzcufq","zgDVs2K","twvZC2fNzuu","BLnLDLq","rK9cuui","tK1utvy","ysbTDxn0igi","x2LZqNjVD3m","B2nRzxq","v0nSsKG","Cgf6s0y","v1HmDha","wKTXDgm","EvHVt04","CNnVCL92ywW","ww1AzMi","vhjjANC","sezOs1a","uhjPBwfYEuS","BwvvCuO","AfrpvuC","zwrPyxrLBhK","vufAqKC","t2LRBNm","qNLSuue","D2fZq2XLyw4","BMDLza","x19LC01Vzhu","BMvJDa","zNvUy3rPB24","mZyXnJmWD2n0A0vl","zw5fDMvUDa","AefJA01LC3m","DejAChm","zezbuKy","wgfMyum","wfjtr1i","v2vPEgLUsLm","q2jjB2K","x0vysvnu","C3HzBKq","Cgf5Bg9Hzeu","y3jLyxrLuMu","y3jLyxrLrxi","sxjWwg4","Ef9MCM9UDgK","zw5HyMXLuw8","DxjS","v0LKEvK","uuTLs1O","D2XNwgm","B2LUDfjLywm","x3jLywr5q2W","CM92AwrLige","wvDHDwS","ywnRtxnNswq","AeLPrg0","ywzL","ueXNCMK","suzJELe","zNbuDvi","Bg9NsurozxC","DuvSvu0","AxnmB25N","DhDVCMTdAge","x29WDgLVBNm","DeT1BuO","B2zMC2v0","tLz4wgW","uhrPqLm","uhzPDLm","y1rjCwC","yMfSu2nVCgu","ruHUtgG","BwfW","yMrFzgLK","u3LUAhq","D2j0A2y","vNzhwhK","r2vuENe","u2TPCcbWyxm","DMvUDa","igzPzwXKoIa","BwLUzW","Ee9nq3u","x3bPBMDqB24","ywvws2q","rKHsDeS","mhW5FdH8nNW","B0vmuMO","A2v5CW","BMvY","zgLZCgf0y2G","BurAsNO","wvzmsLC","r2LxBu4","zgv2AwnLx2K","rgTMyKm","rfDUr0q","yND6vve","Bwf4twvZC2e","ihbYB3rVy28","AhbxvKi","zxjFAxnFywm","wxPXD0e","ywnOzwq","yxH3AwG","yMTrq0S","A3HOEKi","vhvOuKK","yKHzELq","wKvyy2e","BMvcyvi","wLjVBxa","zwnvBfO","x29Uq2XVC2u","vK9Qwvy","CfHMs1C","C3vJy2vZCW","q05swgC","y2niDey","z2rHqxi","zfjjruq","DNbNB1e","Aw5nwu8","zLHRBMq","yNvMzMvY","mZu2ntq1CuDzDKDu","z2v0q3vYCMu","EfPSufm","Dg9iyxnO","v3PADKW","zw5XDwv1zq","v2vIu29JA2u","B3jRig9MzMW","uNbytvG","BMv4DcGPigm","zwvKzwq","s3zuBeq","qLHRBge","BMDuAw1LCG","t3bLBKv2zw4","B2r2sKq","x2LZv29YA2u","vgHJyKC","EvbVCMe","CMvJzxzPzwq","AgvHzgvYCW","zw5JB2rLrNi","ywXS","C2fNzq","ChjVDg90Exa","Dw50","y253uMG","x3bYB3rVy28","C2P4Dvq","ywvqvum","uKTVyKC","wKnTtfK","D2DpC2W","zNDZxZeUmc4","EwHkree","EvDNCLe","DvbNs1a","AKPjy1e","Fdr8m3W1","u2nXvxK","A29TBxG","DhDRt0G","CLz6Awe","qxPnDgi","zxH0zw5ZAw8","B09Vy3C","ohDRsNPLCG","r3Lfwge","vfnTuwC","zMLUza","zuT3t2C","CMvJB25Uzwm","qMzdwNq","x2rYB3bhBg8","vfr6z0y","vwrwswW","zxmGCMvHy2G","x2LUAxq","A2LZquW","EwDRBuq","EM5PrLi","B3jL","sxPdsxq","y3vYC29Yx2y","sMLeDwu","zK9bDNK","BgLZDgvUtMu","CMjlEgm","CvHnq1O","y2vfAeu","wKftrwW","B25ozxr3B3i","CKHOwhq","CuLZBLi","DgLLCKPtt04","zK55y2K","CMvZzxrdB3u","B3nLza","DeLUDgvYy2u","rxfzuKO","z0X1v1y","z0j1y0q","BM93","yw5Nzq","yNfQtw0","wM1Vz3G","C0zYBhy","s1HMrwG","AMvJDfn0B3i","x21PBMLoyxy","ChvZAa","ywDL","AgHJteC","qxPTuLu","EKvMsxu","yMLUyxj5vhK","x194x21Zz18","rhz5Aem","q0Xpu0ve","u21VvhO","AxnbCNjHEq","BwvZC2fNztO","zg9Uzq","ENLhtuO","y2XVC2uSihC","yMfoDNi","AwrI","B2zcvha","BNrLCG","mxWYFdn8mhW","y2vZC0HHBMq","vxvxCLm","wffQshC","zv90Aw1LB3u","ChfjyKK","x25HDMLNyxq","x2rPC2nVBM4","z1Hereu","AvfksNu","vMfxDem","vw5PBxbSzw0","CgLUz1rPBwu","svfIChm","uu12rxG","Aw50zwDLCIa","x21LC3nHz2u","ywXSq3vYC28","yNL0zxm","tw9KDwXL","zMvY","vwrnrhK","Dhr3Awq","sg1dB0e","CMLLC0nVDw4","svzVwwq","rKn3Cey","Ec1TC2CTy3u","BKTdzNG","Aw5KzxGGB3u","x2LUDgvYDMe","rK90C3u","tufyx1jfvfi","Aw5Lza","x29UugfNzu4","m3WYFdb8nhW","CK5Ls0m","zgfsy2q","Du10yMG","y3ruAw1LB3u","weDLuMW","teniENq","DgfIyxnL","Cgu6ia","vuPODuG","vLb0A1q","Aw5JBhvKzxm","z2TszKy","D3PoufC","u2z3r3i","x3nLCuLK","y29UBMvJDfm","Bg9IywXty28","wwz3D2S","AxDlqNa","CMvWBgfJzui","zeXKzLm","tgfhCMC","ignVzgu6ia","DuLMuKq","DMfS","DNPczeC","D3nZoI8V","A1bADxO","s1LjEM4","txnmqwe","r1fbww0","zMLSDgvY","x3vYBa","tg1RB3C","EgHytMK","wKPltgi","y3vYC29Y","vuDwwxG","tLb2Ahy","A1jpB3u","x3DZsw5ZDge","qunqBxK","AxHwB28","yw5Hz2vY","zwnMENO","qKrTyxC","DLzVDM8","x3bPBMC","B2zM","q3HMwve","y1Pcuxy","zcWGDw5RBM8","zgDPB2q","Awr0D20","z25zrw4","rujHAhG","yNLL","rKLRzKu","DgjetgG","vxvpz0y","v01Xtem","wgjRz0S","BIWGAg9ZDg4","DxnLCKLW","zNjVBu51Bwi","vgDNtNK","Aw47y2HHCNm","uhDKAM0","AfjYrwS","yxv0B21HDgK","swDxDNe","z2v0qwXSs2u","B3bLBIa","q291BNq","zLbuA3O","vMHREgO","tLnOCfy","rKHWCuW","BfrPBwvVDxq","BxnNsuq","rNnnA3O","r1H3sgu","qK5fA2e","Bwu6ia","zuzmt1u","yw5ZzM9YBvq","Auvyu0e","ELbXrwS","q29Kzq","D0jREvG","ExvHDeO","ru1LBvq","zgvS","vML5t3O","D0Pfz3K","CMvJzwL2zwq","u2v0Auy","rKLmrv9ot1q","Dg9VigXHCMC","q3vZDg9Tq2W","yMn0sxm","DcbSAw1PDa","qM9ltwy","yu5WAeO","BKvHqMq","uwL3B0C","zwDoDg4","yxbWzw5Kq2G","swfxEuy","uMPvqMG","zxj2AwnL","sejMwLC","AxnrB1nby2S","qwfrsNC","qw1VDw50","rhjTtgu","Ae1LC3nHz2u","ELDYwg8","y2TzqvG","Ec1TC2CTCw8","qvnuCfa","AwTOrhy","B25dBg9Zzq","BK50see","t2TwCMi","vNPSD2S","vhv1vgG","Dhj1y3rVCIa","CMvUDevUzha","CMfNzvn5BMm","u0r1uLa","rfvrt28","whLSDxC","rLDhv0m","AxbnvxO","zNjVBNrPzxi","BMrWB2LUDfq","sgXqywu","ANfAEwK","CM92AwrLihC","icSG","ywX6rvC","mJG3mtG2thDhCxrw","y2f0y2G","uMvJB25Uzwm","zgLZywjSzue","DePNzfu","CLrxzfu","v2T1twS","suvHDLO","CfnrzuC","x3jLBw92zvC","zxjFCw9Zx2e","vfjYv3O","yxbWBgLJyxq","rwPZD0G","BKLurLC","qu5PzxK","zfjNwvi","vgXTtgq","AMTPwgq","De9rtMi","BM9Uzv9UB24","Bxriqui","se1szhC","A2r3wKi","y3brC2G","B2fK","quPwDK4","C2DPza","mtb8mtf8oxW","q1bPAwK","Aw5KzxG","AxLXsgC","y2XVC2veqG","BgrjDu8","Chrsu2u","ANnsBwW","vgfN","CuzlsfC","x29Ut3bLBG","yKnXz2K","q2LODNm","Cvj5C0m","zw5JB2rPBMC","D2rxshO","zgvSzxrLrge","wMfpuw0","yvfkvuO","sNjszwi","u2vXsuq","CgzdEKq","Efziz3C","C0nVDw50zxi","v2XfsgK","Aw9U","B1nWqKK","A1n0yxr1C0m","uLLftfe","x29UvgLTzw8","zwfXEe8","wfblvu4","zgvMAw5Luhi","Aw9Ul2PZB24","B3nLrxzLBNq","yxKSig5LDhC","CMvHC29U","zMLSzw5HBwu","z2v0q3vYC28","zM9Yy2u","x2LUAxrhBg8","x2XPC3rLBMu","t1HlwwO","ugnoqNi","CMvZDwX0","AgLNAa","svzwCMq","yKrivLa","EwXyweq","B3bLBG","EMj2BeC","zxjYtxnN","EerMsMq","x0rctMfTzq","rxnWvhm","sNjsAhK","rhL4ufO","y3jLyxrLt3a","Dg9mB3DLCKm","DNbNCNO","EfnkB2C","C3nHz2vfDMu","vwjTuxe","tMfcz2W","o2nOyxjZzxq","u21kuwS","q0H6B2W","CNzHBa","zNjVBuHHC2G","uLPXuui","vKfeqLG","AevYCM9Yrxy","EfzKBw8","DxbKyxrLq3u","Afz5Aum","uLHPExe","wgvmyum","CMvQzwn0","BKXPBMu","yw51Ce1LC3m","yvnXruW","ywnRx2nVzgu","q2P2quK","mxW4Fdz8m3W","B3bLBKrc","CLvkCfe","D3m6lY8","AKzJuwW","r2HWwxK","seTbzuS","y2HLy2Tszwe","B3vUDa","x3bHDgHlzxK","qxjRtum","EfD2Beu","yw1L","B3zuAuC","Devxy2C","Ew5fBhC","B2jQzwn0u3q","BNvotgW","sfjZuuK","A3POu3K","senwB2K","vgLTzw91Da","A1rotum","y3vZDg9Tshq","C2XPy2u","r3r4seK","BMrLEa","Cg9PBNrdB24","rw5AvKu","twvUAfO","ChjVy2vZCW","DhjPBq","z29PBMCGyxC","AMTvrhK","C0Xf","zw1PDa","BMnLq2XVC2u","C1HWCNC","BMfTzq","uezQCui","z2v0s2v5","DuTjr2e","y3jLyxrLtwu","ywDLu2HVDW","zMzmAw5L","ELzfrMm","r05jyM0","z3bisLu","DvzArMW","yxnZAwDU","zwDIAK0","q2vnrKK","zw50","Dxb1yM4","zMD6BLO","t3DozM4","wg5RCge","s3vtELC","C2vUza","qMDUwK4","y2XLyxjtDg8","t1b3vuC","z2v0t3DUuhi","CNnVCL9Uyw0","yxbWBhK","y3jLyxrLq2W","Bwf4tg9ZC0m","qvroywW","suvtx0vsuK8","svPSruy","DgvZDa","B25nzxnZywC","AwXSihvZzsa","D01qsNi","DgXSDxi","z09iAha","zufrrM8","zw5HyMXLqxu","D0vnEfq","Dg9hzw5LCMe","B0flC2K","C3rLBMvYCW","vKT6CwS","C3rVCcbPBw0","qNrnANC","zgf0yq","BgDKDey","Au9iDwq","CMvTB3zLrxy","rxjYB3jdB2q","BgLUzw5V","CMvTB3zLq2G","vwzjwwq","tKz1quy","ENHlEM4","CMvtCge","BMCGDxjSoIa","turqyxO","x2TLEvbHDgG","uLPywgm","BgLTAxq","z2TvsKy","vhbAAg8","DNHkuxi","y2z5ELq","CM9YrxzLBNq","q1zwrvm","ywnOzwqSihC","AMLfC08","tgLZDgvUzxi","sLfTB2i","EhjpyvK","zxjFCw9Z","y29SBM8","rKHJExK","CvPNz2G","BwLZzq","BwvVCuC","yxnJCMLWDa","C3vIC3rYAw4","svDbyw4","ru5WCwK","wNzjBwy","mdaWma","CMfTzq","CMfUzg9T","suzQueC","x29UtwvZC2e","t1L1t3y","twTLCei","r0HHC1y","z2vjBMzVu3K","tgLmEK0","yMfSrxzLBNq","Cgf5Bg9Hzfq","zvvqthG","A2vRsvi","q2XXANu","tg9JAW","AeXJzhi","zNjVBujPDhm","Dufnrvi","yxrHlcbKyxq","s0LQzwu","Dxj4A3a","DwLAugW","yxKSihrYEsa","x3fVC0rc","zu9TDei","zfDVCMTLCKC","BNrfBMrWB2K","CK1lEe8","re53tNe","reD2Awy","C2v0q3vYC28","x2LZtwLUAvC","C2HPzNq","tMPUCem","yw1LoIa","te1Xr1K","z2L4DMC","B25TzxnZywC","x2n1CNnVCK4","BwPfzuW","q1H2tMG","qvrMEwO","mNWXFdb8nhW","tvbOuw8","u2HHCMvKv28","rNHID0u","tvfkrhC","C2Ttr08","rMTUDw0","q1bjy0K","ufbjEe4","twv5ALy","Dxrjza","yKnntLm","Eg9tBKm","refmBg8","DgfYz2v0","Cg5PtK0","C2v0sxrLBq","swffuNe","ihrPBwvVDxq","zxrgCKK","D2LSBfjLy28","AgfZt3DUuhi","vxfrthu","x2DLDeLUDgu","vM1sCvC","B3bsvgu","y3jLyxrLrwW","DufvvKG","ChriCKW","zLPZD0q","Bg5pzva","y2ndAKS","z1jItuC","ywDLsgLKzq","vMjMCKi","vMLlEey","x2LZtwLUAvq","CMvZB2X2zq","y29UBMvJDca","DurgsvC","D3vHy0S","ru5HEfi","v3HyEKq","BKLptwK","CNnVCKzPBgu","qNndqxq","y1DgCKO","uwDAD2i","odCXodi0yurPCuzX","uMvutgO","C2vUDa","EwfOA2u","zsbHihn0CMK","DgHLBG","Efrurw52","uuTjtfa","DhLWzq","ngv6B29jAG","B21iCge","qKjgy08","ihzHBgLKihm","qxbJBwe","ywDku2S","C3vIyxjYyxK","sertqNO","CgLUz0LUDgu","ywrKrxzLBNq","qwjVCNrfCNi","vMPSseO","BwvZ","D3jPDgvvAw4","y3jLyxrLt2i","BwvY","lcbxzwjtB2m","BezSDxnO","quzqDu0","CgXLyxnLiha","DgLTzw91Da","rxvduuK","q3vZDg9Trxi","twrzwKm","C0jf","y3btrMG","veThwey","uu1JtxO","yK5Zue8","wuX4zwy","z2vY","yxDnzxu","zMrUuuq","AMrpDvq","vvLyAhy","wefmt2e","BNruCMLLC0m","q09otKvdveK","EgPWsw4","igfYCMf5yNu","zNjVBuj5Dgu","EeXkvhe","Dgv4Dc9Qyxy","BLjWtMS","x3bYzwzPEa","BMnVzgLUzW","B3rivM4","tLvoEwO","rMDHs0G","rePfwhq","Dfnzy2i","BuXbBK4","zv9ZDwnJzxm","aaaaaaaaaaa","u3Lzrwi","C3jJ","z2ftvhe","zw5KCg9PBNq","zxH0ugf5Bg8","t1bftL9fuLi","ue9urNC","vxzwqMm","Cgrdseq","BLvhv2i","CMvHzfvjBNq","z0znzu8","wxLbAvi","BeHHBMrSzxi","v2nYDei","y3vYCMvUDeu","B3v0sw50zxi","AwXLtMfTzq","C0voBLe","tgrWDgu","ve5KCK8","AxnrB1nnzxm","D1vYvLK","y2XVC2u","D3fzt0W","Cgf5Bg9Hza","D09HsvO","twLZC2LUzYa","tLbyzNC","C29Tzq","zwrtyNy","x3jLy29UBMu","yMLUyxj5","AuPUtLe","te1jzwq","sfz5whi","x2rLC3rYB3K","t2jQzwn0","y29UDgv4Da","wvjqswy","EfvLBgC","uwvcyNG","rMrfv0W","y3vYC29Yx24","C3rHCNq","AgfZ","rgH6A2m","Bxb2yvG","q09oveLovuu","vMLTswO","swLuBwK","yvbHAgS","zgjHvw8","zNjHBwvuExa","CgfNzxnOB3C","x2HHBMrSzvi","qKDss04","u3rYyxrLz3K","zK1Vz08","CLzvzfq","v3DluNe","ywTLDgC","CfrbAMW","y291BNq","tg1qqu4","sLvMCum","vxvlywq","q0HVDKK","x3nLBMrby2S","rgHqruq","v0XKzwm","zuXmtey","CgLUz0XVC3m","D2PmD3u","AerfD2y","x3nVy2TLDa","EuDnu2u","CvnAtxa","C2v0u3rVCMe","re1drLK","zw50zwqGDhK","zxjYtM8","Dgv4DfbHEwW","q0r5Efe","yw1Lu3bHy2u","u1fowgK","s05jDLG","tKHsq2i","r3DVzNe","y0rby0u","yuPnswK","rgvKAwnHDgu","vKLoA24","CNzHBfzHBhu","s0fnzvy","uNHVwuq","CMvZzxrfBMq","zwr6wwO","sKrnBMe","Aw9UvgLTzw8","x3bPBMDmB3m","z1bPDLa","DgLTzw91DcW","zwn0","BwvZC2fNzv8","z3nWrvq","zgvSzxrL","lcbOB3n0BMe","zwnVBM5Ly3q","x29UrxjYB3i","uLLmrue","t0rHuMG","CuXbBKe","sefjzMS","B3bLCNr5","ihn1y2nLC3m","CIb0DhDjra","A0LUEMm","x2rLyNvN","Ahr0Ca","Bg93","EgnkzM8","uef0zLe","rgz3CKC","y3r5uMK","Dw5RBM93BIa","qwHNqxq","DwXzDLe","zMXVB3i","ugf1rNy","vw5Oyw5KBgu","zMX1C2HfEha","Cerwt2O","ueLHruq","zMLYweG","Aw5N","teP4ve0","mJeYmda5AM5tuwHp","DMfSDwvZ","suLoqLG","zMXTv28","C0XcwK8","zvvYBa","CMvKDwnL","Dgv4Dc9WBge","EhfVtNq","D2nNAg0","z2v0u3rVCMe","z2HjExq","ANzPEem","z2v0qwXS","EK1jCxe","wu5YCw4","yMLUza","Ec11C2uT","r05nq1C","z3rHqKO","x2DLBMvYyxq","BhrTAeq","uuHitKu","u2PwC2y","rg5bzxe","BwT6vLq","DcbVzIbYyw4","Bu94uva","wMfjtM0","txjuy2u","Exbezu0","Dg9cExrLC0i","q29UzMLN","AvnIBM8","y2uGBM90igK","zeToq0e","tg9NsurozxC","z2v0","C1P3twK","CxHNt08","x2n1CNnVCK0","DujtBgq","zw50tgLZDgu","qNP2tKy","CePdrMG","Cw9Zx18","ChDIEhq","uLjpuG","vMrKsxm","B25JBg9Zzq","zxjHDg9Y","sNvsvva","C2vYDMLJzs0","v1rjBwC","BNvTyMvY","z2fytfq","ufjhvvi","ALnczLC","yxjYyxLIDwy","BerVuLq","Cgvtv0e","EvjLy29UBMu","q0fiuLq","rMvRELa","C3rYAw5NAwy","yK1eBKK","wvzqCK0","z0niyve","r3zRCve","BvPis1e","ENfIDNC","ig1LC3nHz2u","De1HBMfNzxi","y3r4","ywfjAMu","rwv2DLy","DK5RvNq","ywXty29Wzq","BvfAvg0","yur3zNu","CgLUz19VBMm","A21Mug0","Ewvstu0","wNv4vhK","y29Kzq","reiGzMfPBgu","Ew5gsNO","txnUB0W","wM1Jwg4","x2nVBM5Ly3q","x2jPBMfYEvq","Chvgrhu","rLDt","CKvHBMe","v3rTrMC","B3HoCha","Cuvsr3q","Dg9cExrLCW","AxjLza","id4G","shPgEu0","tgXju0q","uKj5zKG","CgDZyxK","q0HRq00","yLLrA3a","ihzHBgLKigq","t3zfww4","C3rYAw5N","u3HnvKW","DhjPzxmGCMu","x2nSzwfYugK","CLHmC1C","x2vUzhbVAw4","rK1xr2q","yNzlrwC","yxv0BW","DxvKqwq","zLfvExi","y29Uy2f0","Eg55y1q","C2vYDMvYvgK","Aevbvfi","t3vWuuG","DNfcwuS","reTIsuy","BerAuNu","ru5MrwW","uuHLs1e","D24GCMvHC28","B25VCgvU","BMv3vMvYC2K","B3rvq2y","ueXstgu","rNjVBNrPzxi","B25tDg9Wsw0","EKzkBfK","DgrJru8","q29MufO","twzHq3C","u0LJtM0","BKrezKi","ELHeDfK","mdaWmdaWmda","y2XLyxi","Chv0","sgfrr0G","CMvHzg9UBhK","DhbizwfKzxi","B3jRzxjhBg8","ChbL","y09Wzw4","BvfdCMq","y29UBMvJDa","sgHQBNC","vKLkC1q","qunmuve","CLDmvg0","y29UC3rYDwm","zgvIDwC","ChjVDg9JB2W","BwfUDwfSihi","Ag9cBg4","A0fIuMm","BML0AwfSAxO","zxrxB3jRq2G","rgvuBgm","uvzyyMe","C1Heuxa","y2nNs0W","rNHOC2K","rKDAtMu","AK9wC3i","qwTWEhG","AezLwKm","DfvXAhK","DMvYC2LVBG","qM1Sy2e","s2nmB3C","zxHWB3j0CW","nxW3Fdf8nG","zw5HyMXLvhi","CgfYC2u","pxv0zI04","BeDwyNC","rxzLBNq"];return ka=function(){return t},ka()}var Ea;Object[M(824)+M(1266)](He,M(377)+"le",{value:!0})});import{existsSync as NI,openSync as FI}from"node:fs";import{mkdir as BI}from"node:fs/promises";import{dirname as zI}from"node:path";import{fileURLToPath as UI}from"node:url";function qI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Il(t=Z()){return NI(t.libEntry)?t.libEntry:UI(new URL("../index.ts",import.meta.url))}async function sg(t={}){let e=t.paths??Z(),n=t.entryOverride??Il(e),i=qI(e,process.env.COZE_BRIDGE_LOG_MODE);await BI(zI(i),{recursive:!0});let o=FI(i,"a"),d=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],f=dt(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[As]:"1"}});if(f.unref(),typeof f.pid!="number")throw new Error("failed to spawn daemon (no pid)");return HI.info("daemon spawned",{pid:f.pid,entry:n}),{pid:f.pid,entry:n}}var HI,As,Da=ot(()=>{"use strict";Wt();ne();Pe();HI=q("spawn-daemon"),As="COZE_BRIDGE_DAEMON"});import{spawn as zA}from"node:child_process";import{mkdir as UA,unlink as HA,writeFile as qA}from"node:fs/promises";import{dirname as GA,join as jA}from"node:path";function gi(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function WA(t){if(!t)return"";let e=Object.entries(t).map(([n,i])=>` <key>${gi(n)}</key>
21
+ <string>${gi(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function K2(t,e){return new Promise((n,i)=>{let s=z2(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var ui,Ss,Ra,Tl,Sg=ot(()=>{"use strict";ne();ui=G("supervisor.launchd"),Ss="ai.coze.bridge",Ra=K2,Tl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function KA(t,e){return new Promise((n,i)=>{let o=zA(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 pi,Cs,Ba,Ll,Tg=ot(()=>{"use strict";ne();pi=q("supervisor.launchd"),Cs="ai.coze.bridge",Ba=KA,Ll={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
29
29
  <dict>
30
30
  <key>Label</key>
31
- <string>${Ss}</string>
31
+ <string>${Cs}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${fi(t.nodeBin)}</string>
35
- <string>${fi(t.entry)}</string>
34
+ <string>${gi(t.nodeBin)}</string>
35
+ <string>${gi(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>${fi(t.logFile)}</string>
45
+ <string>${gi(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${fi(t.logFile)}</string>${W2(t.env)}
47
+ <string>${gi(t.logFile)}</string>${WA(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return j2(t.homeDir,"Library","LaunchAgents",`${Ss}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await U2(q2(i),{recursive:!0}),await G2(i,this.renderConfig(t),"utf8"),ui.info("plist written",{plistPath:i,activate:n}),!n)return;await Ra("launchctl",["unload","-w",i]).catch(a=>ui.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Ra("launchctl",["load","-w",i]),ui.info("launchd job loaded",{label:Ss});let s=process.getuid?.()??0;await Ra("launchctl",["kickstart","-k",`gui/${s}/${Ss}`]),ui.info("launchd job kickstarted",{label:Ss,uid:s})},async uninstall(t){let e=this.configPath(t);await Ra("launchctl",["unload","-w",e]).catch(n=>ui.warn("launchctl unload failed (ignored)",{err:String(n)})),await H2(e).catch(n=>{if(n.code!=="ENOENT")throw n}),ui.info("launchd job removed",{plistPath:e})}}});import{spawn as $2}from"node:child_process";import{mkdir as V2,unlink as J2,writeFile as Z2}from"node:fs/promises";import{dirname as Y2,join as Ig}from"node:path";function La(t,e){return t.isRoot?e:["--user",...e]}function Q2(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function Ma(t,e){return new Promise((n,i)=>{let s=$2(t,e,{stdio:["ignore","pipe","pipe"]}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Oa,hi,X2,Pl,Ag=ot(()=>{"use strict";ne();Oa=G("supervisor.systemd"),hi="coze-bridge.service",X2="/etc/systemd/system";Pl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return jA(t.homeDir,"Library","LaunchAgents",`${Cs}.plist`)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t);if(await UA(GA(i),{recursive:!0}),await qA(i,this.renderConfig(t),"utf8"),pi.info("plist written",{plistPath:i,activate:n}),!n)return;await Ba("launchctl",["unload","-w",i]).catch(a=>pi.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(a)})),await Ba("launchctl",["load","-w",i]),pi.info("launchd job loaded",{label:Cs});let o=process.getuid?.()??0;await Ba("launchctl",["kickstart","-k",`gui/${o}/${Cs}`]),pi.info("launchd job kickstarted",{label:Cs,uid:o})},async uninstall(t){let e=this.configPath(t);await Ba("launchctl",["unload","-w",e]).catch(n=>pi.warn("launchctl unload failed (ignored)",{err:String(n)})),await HA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),pi.info("launchd job removed",{plistPath:e})}}});import{spawn as $A}from"node:child_process";import{mkdir as VA,unlink as JA,writeFile as ZA}from"node:fs/promises";import{dirname as XA,join as Cg}from"node:path";function Ua(t,e){return t.isRoot?e:["--user",...e]}function QA(t){return t?Object.entries(t).map(([e,n])=>{let i=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function Ha(t,e){return new Promise((n,i)=>{let o=$A(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 za,mi,YA,Ml,Rg=ot(()=>{"use strict";ne();za=q("supervisor.systemd"),mi="coze-bridge.service",YA="/etc/systemd/system";Ml={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
- ${Q2(t.env)}
62
+ ${QA(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Ig(X2,hi):Ig(t.homeDir,".config","systemd","user",hi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),s=t.isRoot?"system":"user";await V2(Y2(i),{recursive:!0}),await Z2(i,this.renderConfig(t),"utf8"),Oa.info("systemd unit written",{unitPath:i,mode:s,activate:n}),await Ma("systemctl",La(t,["daemon-reload"])),await Ma("systemctl",La(t,n?["enable","--now",hi]:["enable",hi])),Oa.info("systemd unit enabled",{unitName:hi,mode:s,activate:n})},async uninstall(t){let e=this.configPath(t);await Ma("systemctl",La(t,["disable","--now",hi])).catch(n=>Oa.warn("systemctl disable failed (ignored)",{err:String(n)})),await J2(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Ma("systemctl",La(t,["daemon-reload"])).catch(()=>{}),Oa.info("systemd unit removed",{unitPath:e})}}});import{spawn as e1}from"node:child_process";import{join as t1}from"node:path";function kg(t,e){return new Promise((n,i)=>{let s=e1(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),a="";s.stderr?.on("data",d=>{a+=d.toString("utf8")}),s.on("error",i),s.on("close",d=>{d===0?n():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${a.trim()}`))})})}var Dl,Na,Rl,Cg=ot(()=>{"use strict";ne();Dl=G("supervisor.taskscheduler"),Na="CozeBridge",Rl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?Cg(YA,mi):Cg(t.homeDir,".config","systemd","user",mi)},async install(t,e){let n=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await VA(XA(i),{recursive:!0}),await ZA(i,this.renderConfig(t),"utf8"),za.info("systemd unit written",{unitPath:i,mode:o,activate:n}),await Ha("systemctl",Ua(t,["daemon-reload"])),await Ha("systemctl",Ua(t,n?["enable","--now",mi]:["enable",mi])),za.info("systemd unit enabled",{unitName:mi,mode:o,activate:n})},async uninstall(t){let e=this.configPath(t);await Ha("systemctl",Ua(t,["disable","--now",mi])).catch(n=>za.warn("systemctl disable failed (ignored)",{err:String(n)})),await JA(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Ha("systemctl",Ua(t,["daemon-reload"])).catch(()=>{}),za.info("systemd unit removed",{unitPath:e})}}});import{spawn as ek}from"node:child_process";import{join as tk}from"node:path";function Pg(t,e){return new Promise((n,i)=>{let o=ek(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 Nl,qa,Fl,Dg=ot(()=>{"use strict";ne();Nl=q("supervisor.taskscheduler"),qa="CozeBridge",Fl={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,64 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return t1(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await kg("schtasks",["/Create","/SC","ONLOGON","/TN",Na,"/TR",n,"/RU",t.userName,"/F"]),Dl.info("task scheduler entry created",{task:Na,logFile:t.logFile})},async uninstall(t){await kg("schtasks",["/Delete","/TN",Na,"/F"]).catch(e=>Dl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Dl.info("task scheduler entry removed",{task:Na})}}});var Tg={};Za(Tg,{buildContext:()=>a1,getSupervisor:()=>i1,launchdSupervisor:()=>Tl,systemdSupervisor:()=>Pl,taskSchedulerSupervisor:()=>Rl});import{homedir as n1,userInfo as r1}from"node:os";function i1(t=process.platform){switch(t){case"darwin":return Tl;case"linux":return Pl;case"win32":return Rl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function o1(){let t={};for(let e of s1){let n=process.env[e];n&&(t[e]=n)}return t}function a1(){let t=Z();return{nodeBin:process.execPath,entry:yl(t),logFile:t.logFile,homeDir:n1(),userName:r1().username,isRoot:process.getuid?.()===0,env:o1()}}var s1,Pg=ot(()=>{"use strict";Ce();Aa();Sg();Ag();Cg();s1=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();yn();var au=G("acp-installer-warmup"),iw=["claude-code","codex"];async function cu(t={}){let e=t.ensure??Er,i=(await Promise.allSettled(iw.map(async s=>{let a=await e(s);au.info("acp wrapper warmup ok",{framework:s,path:a})}))).filter(s=>s.status==="rejected");i.length>0&&au.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(s=>s.reason instanceof Error?s.reason.message:String(s.reason))})}Qt();ne();import{readdir as yw}from"node:fs/promises";import{mkdir as fu,readFile as ww,writeFile as hu}from"node:fs/promises";import{join as rc}from"node:path";var _w={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function Sr(t,e,n){await fu(t,{recursive:!0});let i=_w[e],s=rc(t,i);return await hu(s,n??"","utf8"),s}async function ic(t,e,n){let i=rc(t,".claude");await fu(i,{recursive:!0});let s=rc(i,"settings.local.json"),a={};try{let u=await ww(s,"utf8"),h=JSON.parse(u);typeof h=="object"&&h!==null&&!Array.isArray(h)&&(a=h)}catch{}let d=typeof a.permissions=="object"&&a.permissions!==null&&!Array.isArray(a.permissions)?a.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",a.autoCompactWindow=15e4;else{if(!n)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=n)}return a.permissions=d,await hu(s,JSON.stringify(a,null,2),"utf8"),s}var Qe=G("agent-detail-sync"),bw=6e4,vw=5*6e4,Ns=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await yw(n)}catch(s){Qe.info("agents dir not found, skip detail sync",{root:n,err:String(s)});return}Qe.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async s=>{let a=await ge(s,this.opts.paths).catch(()=>null);if(a){if(a.disconnectedAt){Qe.debug("detail sync: skip disconnected agent",{agentId:s});return}try{await this.syncOne(s,a)}catch(d){Qe.warn("detail sync failed for agent, skipping",{agentId:s,err:String(d)})}}})),Qe.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[i,s]of this.retryQueue)e>=s.dueAt&&n.push(i);if(n.length!==0){Qe.info("retrying pending detail syncs",{count:n.length});for(let i of n)try{await this.syncOne(i)}catch(s){Qe.debug("detail sync retry still failing, will try again",{agentId:i,err:String(s)})}}}async syncOne(e,n){let i=n??await ge(e,this.opts.paths);if(!i){Qe.info("detail sync: agent config missing, skip",{agentId:e});return}let s;try{s=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(h){Qe.warn("detail RPC failed, using local data",{agentId:e,err:String(h)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,vw):bw;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(s.agentId&&s.agentId!==e){Qe.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:s.agentId});return}let a=!1,d=!1;s.agentName&&s.agentName!==i.agentName&&(i.agentName=s.agentName,a=!0),s.description!==void 0&&s.description!==i.description&&(i.description=s.description,a=!0),s.cozeIdentity&&s.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=s.cozeIdentity,a=!0,d=!0);let u=!1;if(s.deployType==="cloud"&&i.deployType!=="cloud"?(Qe.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",a=!0,u=!0):s.deployType&&Qe.info("detail.deployType",{agentId:e,deployType:s.deployType}),!a){Qe.debug("detail sync: no diff",{agentId:e});return}await Re(i,this.opts.paths),Qe.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Qe.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await Sr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Ld=Xt(Ku(),1);import{createHash as Ib}from"node:crypto";import{lstat as Ad,mkdir as kd,readFile as Ro,readdir as Q0,rm as Cd,stat as Rd,writeFile as Td}from"node:fs/promises";import{homedir as Ab}from"node:os";import{basename as Z0,dirname as kb,join as he,normalize as Cb,relative as Od,resolve as Pd,sep as eh}from"node:path";import{Readable as th}from"node:stream";import{pipeline as nh}from"node:stream/promises";import jw from"events";import ct from"fs";import{EventEmitter as id}from"node:events";import Tf from"node:stream";import{StringDecoder as Ww}from"node:string_decoder";import Rf from"node:path";import Nr from"node:fs";import{dirname as i_,parse as s_}from"path";import{EventEmitter as h_}from"events";import zc from"assert";import{Buffer as Xn}from"buffer";import*as Yu from"zlib";import x_ from"zlib";import{posix as Tr}from"node:path";import{basename as G_}from"node:path";import po from"fs";import Ht from"fs";import of from"path";import{win32 as ty}from"node:path";import hf from"path";import $f from"node:fs";import wy from"node:assert";import{randomBytes as Vf}from"node:crypto";import se from"node:fs";import Fe from"node:path";import Jf from"fs";import So from"node:fs";import Ui from"node:path";import pt from"node:fs";import Iy from"node:fs/promises";import wo from"node:path";import{join as o0}from"node:path";import xt from"node:fs";import d0 from"node:path";var Gw=Object.defineProperty,qw=(t,e)=>{for(var n in e)Gw(t,n,{get:e[n],enumerable:!0})},$u=typeof process=="object"&&process?process:{stdout:null,stderr:null},Kw=t=>!!t&&typeof t=="object"&&(t instanceof tr||t instanceof Tf||$w(t)||Vw(t)),$w=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.pipe=="function"&&t.pipe!==Tf.Writable.prototype.pipe,Vw=t=>!!t&&typeof t=="object"&&t instanceof id&&typeof t.write=="function"&&typeof t.end=="function",en=Symbol("EOF"),tn=Symbol("maybeEmitEnd"),vn=Symbol("emittedEnd"),Hs=Symbol("emittingEnd"),vi=Symbol("emittedError"),Gs=Symbol("closed"),Vu=Symbol("read"),qs=Symbol("flush"),Ju=Symbol("flushChunk"),Tt=Symbol("encoding"),Cr=Symbol("decoder"),Ue=Symbol("flowing"),Ei=Symbol("paused"),Or=Symbol("resume"),He=Symbol("buffer"),et=Symbol("pipes"),Ge=Symbol("bufferLength"),lc=Symbol("bufferPush"),js=Symbol("bufferShift"),Ye=Symbol("objectMode"),Te=Symbol("destroyed"),uc=Symbol("error"),fc=Symbol("emitData"),Zu=Symbol("emitEnd"),hc=Symbol("emitEnd2"),Bt=Symbol("async"),xc=Symbol("abort"),Ws=Symbol("aborted"),Si=Symbol("signal"),qn=Symbol("dataListeners"),ht=Symbol("discarded"),Ii=t=>Promise.resolve().then(t),Jw=t=>t(),Zw=t=>t==="end"||t==="finish"||t==="prefinish",Yw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Xw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Pf=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Or](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Qw=class extends Pf{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,n){super(t,e,n),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},e_=t=>!!t.objectMode,t_=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",tr=class extends id{[Ue]=!1;[Ei]=!1;[et]=[];[He]=[];[Ye];[Tt];[Bt];[Cr];[en]=!1;[vn]=!1;[Hs]=!1;[Gs]=!1;[vi]=null;[Ge]=0;[Te]=!1;[Si];[Ws]=!1;[qn]=0;[ht]=!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");e_(e)?(this[Ye]=!0,this[Tt]=null):t_(e)?(this[Tt]=e.encoding,this[Ye]=!1):(this[Ye]=!1,this[Tt]=null),this[Bt]=!!e.async,this[Cr]=this[Tt]?new Ww(this[Tt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[He]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:n}=e;n&&(this[Si]=n,n.aborted?this[xc]():n.addEventListener("abort",()=>this[xc]()))}get bufferLength(){return this[Ge]}get encoding(){return this[Tt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Bt]}set async(t){this[Bt]=this[Bt]||!!t}[xc](){this[Ws]=!0,this.emit("abort",this[Si]?.reason),this.destroy(this[Si]?.reason)}get aborted(){return this[Ws]}set aborted(t){}write(t,e,n){if(this[Ws])return!1;if(this[en])throw new Error("write after end");if(this[Te])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let i=this[Bt]?Ii:Jw;if(!this[Ye]&&!Buffer.isBuffer(t)){if(Xw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Yw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ye]?(this[Ue]&&this[Ge]!==0&&this[qs](!0),this[Ue]?this.emit("data",t):this[lc](t),this[Ge]!==0&&this.emit("readable"),n&&i(n),this[Ue]):t.length?(typeof t=="string"&&!(e===this[Tt]&&!this[Cr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Tt]&&(t=this[Cr].write(t)),this[Ue]&&this[Ge]!==0&&this[qs](!0),this[Ue]?this.emit("data",t):this[lc](t),this[Ge]!==0&&this.emit("readable"),n&&i(n),this[Ue]):(this[Ge]!==0&&this.emit("readable"),n&&i(n),this[Ue])}read(t){if(this[Te])return null;if(this[ht]=!1,this[Ge]===0||t===0||t&&t>this[Ge])return this[tn](),null;this[Ye]&&(t=null),this[He].length>1&&!this[Ye]&&(this[He]=[this[Tt]?this[He].join(""):Buffer.concat(this[He],this[Ge])]);let e=this[Vu](t||null,this[He][0]);return this[tn](),e}[Vu](t,e){if(this[Ye])this[js]();else{let n=e;t===n.length||t===null?this[js]():typeof n=="string"?(this[He][0]=n.slice(t),e=n.slice(0,t),this[Ge]-=t):(this[He][0]=n.subarray(t),e=n.subarray(0,t),this[Ge]-=t)}return this.emit("data",e),!this[He].length&&!this[en]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[en]=!0,this.writable=!1,(this[Ue]||!this[Ei])&&this[tn](),this}[Or](){this[Te]||(!this[qn]&&!this[et].length&&(this[ht]=!0),this[Ei]=!1,this[Ue]=!0,this.emit("resume"),this[He].length?this[qs]():this[en]?this[tn]():this.emit("drain"))}resume(){return this[Or]()}pause(){this[Ue]=!1,this[Ei]=!0,this[ht]=!1}get destroyed(){return this[Te]}get flowing(){return this[Ue]}get paused(){return this[Ei]}[lc](t){this[Ye]?this[Ge]+=1:this[Ge]+=t.length,this[He].push(t)}[js](){return this[Ye]?this[Ge]-=1:this[Ge]-=this[He][0].length,this[He].shift()}[qs](t=!1){do;while(this[Ju](this[js]())&&this[He].length);!t&&!this[He].length&&!this[en]&&this.emit("drain")}[Ju](t){return this.emit("data",t),this[Ue]}pipe(t,e){if(this[Te])return t;this[ht]=!1;let n=this[vn];return e=e||{},t===$u.stdout||t===$u.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[et].push(e.proxyErrors?new Qw(this,t,e):new Pf(this,t,e)),this[Bt]?Ii(()=>this[Or]()):this[Or]()),t}unpipe(t){let e=this[et].find(n=>n.dest===t);e&&(this[et].length===1?(this[Ue]&&this[qn]===0&&(this[Ue]=!1),this[et]=[]):this[et].splice(this[et].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[ht]=!1,this[qn]++,!this[et].length&&!this[Ue]&&this[Or]();else if(t==="readable"&&this[Ge]!==0)super.emit("readable");else if(Zw(t)&&this[vn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[vi]){let i=e;this[Bt]?Ii(()=>i.call(this,this[vi])):i.call(this,this[vi])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[qn]=this.listeners("data").length,this[qn]===0&&!this[ht]&&!this[et].length&&(this[Ue]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[qn]=0,!this[ht]&&!this[et].length&&(this[Ue]=!1)),e}get emittedEnd(){return this[vn]}[tn](){!this[Hs]&&!this[vn]&&!this[Te]&&this[He].length===0&&this[en]&&(this[Hs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Gs]&&this.emit("close"),this[Hs]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Te&&this[Te])return!1;if(t==="data")return!this[Ye]&&!n?!1:this[Bt]?(Ii(()=>this[fc](n)),!0):this[fc](n);if(t==="end")return this[Zu]();if(t==="close"){if(this[Gs]=!0,!this[vn]&&!this[Te])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(t==="error"){this[vi]=n,super.emit(uc,n);let s=!this[Si]||this.listeners("error").length?super.emit("error",n):!1;return this[tn](),s}else if(t==="resume"){let s=super.emit("resume");return this[tn](),s}else if(t==="finish"||t==="prefinish"){let s=super.emit(t);return this.removeAllListeners(t),s}let i=super.emit(t,...e);return this[tn](),i}[fc](t){for(let n of this[et])n.dest.write(t)===!1&&this.pause();let e=this[ht]?!1:super.emit("data",t);return this[tn](),e}[Zu](){return this[vn]?!1:(this[vn]=!0,this.readable=!1,this[Bt]?(Ii(()=>this[hc]()),!0):this[hc]())}[hc](){if(this[Cr]){let e=this[Cr].end();if(e){for(let n of this[et])n.dest.write(e);this[ht]||super.emit("data",e)}}for(let e of this[et])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ye]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Ye]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Tt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Te,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ht]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[en])return e();let i,s,a=x=>{this.off("data",d),this.off("end",u),this.off(Te,h),e(),s(x)},d=x=>{this.off("error",a),this.off("end",u),this.off(Te,h),this.pause(),i({value:x,done:!!this[en]})},u=()=>{this.off("error",a),this.off("data",d),this.off(Te,h),e(),i({done:!0,value:void 0})},h=()=>a(new Error("stream destroyed"));return new Promise((x,p)=>{s=p,i=x,this.once(Te,h),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[ht]=!1;let t=!1,e=()=>(this.pause(),this.off(uc,e),this.off(Te,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(uc,e),this.once(Te,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Te])return t?this.emit("error",t):this.emit(Te),this;this[Te]=!0,this[ht]=!0,this[He].length=0,this[Ge]=0;let e=this;return typeof e.close=="function"&&!this[Gs]&&e.close(),t?this.emit("error",t):this.emit(Te),this}static get isStream(){return Kw}},n_=ct.writev,Dn=Symbol("_autoClose"),Ot=Symbol("_close"),Ai=Symbol("_ended"),fe=Symbol("_fd"),pc=Symbol("_finished"),on=Symbol("_flags"),gc=Symbol("_flush"),Bc=Symbol("_handleChunk"),Fc=Symbol("_makeBuf"),Fi=Symbol("_mode"),Ks=Symbol("_needDrain"),Fr=Symbol("_onerror"),zr=Symbol("_onopen"),mc=Symbol("_onread"),Lr=Symbol("_onwrite"),Rn=Symbol("_open"),Rt=Symbol("_path"),An=Symbol("_pos"),Ft=Symbol("_queue"),Mr=Symbol("_read"),wc=Symbol("_readSize"),sn=Symbol("_reading"),ki=Symbol("_remain"),_c=Symbol("_size"),no=Symbol("_write"),jn=Symbol("_writing"),ro=Symbol("_defaultFlag"),Yn=Symbol("_errored"),sd=class extends tr{[Yn]=!1;[fe];[Rt];[wc];[sn]=!1;[_c];[ki];[Dn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Yn]=!1,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[Rt]=t,this[wc]=e.readSize||16*1024*1024,this[sn]=!1,this[_c]=typeof e.size=="number"?e.size:1/0,this[ki]=this[_c],this[Dn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[fe]=="number"?this[Mr]():this[Rn]()}get fd(){return this[fe]}get path(){return this[Rt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Rn](){ct.open(this[Rt],"r",(t,e)=>this[zr](t,e))}[zr](t,e){t?this[Fr](t):(this[fe]=e,this.emit("open",e),this[Mr]())}[Fc](){return Buffer.allocUnsafe(Math.min(this[wc],this[ki]))}[Mr](){if(!this[sn]){this[sn]=!0;let t=this[Fc]();if(t.length===0)return process.nextTick(()=>this[mc](null,0,t));ct.read(this[fe],t,0,t.length,null,(e,n,i)=>this[mc](e,n,i))}}[mc](t,e,n){this[sn]=!1,t?this[Fr](t):this[Bc](e,n)&&this[Mr]()}[Ot](){if(this[Dn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Fr](t){this[sn]=!0,this[Ot](),this.emit("error",t)}[Bc](t,e){let n=!1;return this[ki]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[ki]<=0)&&(n=!1,this[Ot](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[fe]=="number"&&this[Mr](),!1;case"error":return this[Yn]?!1:(this[Yn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},r_=class extends sd{[Rn](){let t=!0;try{this[zr](null,ct.openSync(this[Rt],"r")),t=!1}finally{t&&this[Ot]()}}[Mr](){let t=!0;try{if(!this[sn]){this[sn]=!0;do{let e=this[Fc](),n=e.length===0?0:ct.readSync(this[fe],e,0,e.length,null);if(!this[Bc](n,e))break}while(!0);this[sn]=!1}t=!1}finally{t&&this[Ot]()}}[Ot](){if(this[Dn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.closeSync(t),this.emit("close")}}},_o=class extends jw{readable=!1;writable=!0;[Yn]=!1;[jn]=!1;[Ai]=!1;[Ft]=[];[Ks]=!1;[Rt];[Fi];[Dn];[fe];[ro];[on];[pc]=!1;[An];constructor(t,e){e=e||{},super(e),this[Rt]=t,this[fe]=typeof e.fd=="number"?e.fd:void 0,this[Fi]=e.mode===void 0?438:e.mode,this[An]=typeof e.start=="number"?e.start:void 0,this[Dn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[An]!==void 0?"r+":"w";this[ro]=e.flags===void 0,this[on]=e.flags===void 0?n:e.flags,this[fe]===void 0&&this[Rn]()}emit(t,...e){if(t==="error"){if(this[Yn])return!1;this[Yn]=!0}return super.emit(t,...e)}get fd(){return this[fe]}get path(){return this[Rt]}[Fr](t){this[Ot](),this[jn]=!0,this.emit("error",t)}[Rn](){ct.open(this[Rt],this[on],this[Fi],(t,e)=>this[zr](t,e))}[zr](t,e){this[ro]&&this[on]==="r+"&&t&&t.code==="ENOENT"?(this[on]="w",this[Rn]()):t?this[Fr](t):(this[fe]=e,this.emit("open",e),this[jn]||this[gc]())}end(t,e){return t&&this.write(t,e),this[Ai]=!0,!this[jn]&&!this[Ft].length&&typeof this[fe]=="number"&&this[Lr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Ai]?(this.emit("error",new Error("write() after end()")),!1):this[fe]===void 0||this[jn]||this[Ft].length?(this[Ft].push(t),this[Ks]=!0,!1):(this[jn]=!0,this[no](t),!0)}[no](t){ct.write(this[fe],t,0,t.length,this[An],(e,n)=>this[Lr](e,n))}[Lr](t,e){t?this[Fr](t):(this[An]!==void 0&&typeof e=="number"&&(this[An]+=e),this[Ft].length?this[gc]():(this[jn]=!1,this[Ai]&&!this[pc]?(this[pc]=!0,this[Ot](),this.emit("finish")):this[Ks]&&(this[Ks]=!1,this.emit("drain"))))}[gc](){if(this[Ft].length===0)this[Ai]&&this[Lr](null,0);else if(this[Ft].length===1)this[no](this[Ft].pop());else{let t=this[Ft];this[Ft]=[],n_(this[fe],t,this[An],(e,n)=>this[Lr](e,n))}}[Ot](){if(this[Dn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Df=class extends _o{[Rn](){let t;if(this[ro]&&this[on]==="r+")try{t=ct.openSync(this[Rt],this[on],this[Fi])}catch(e){if(e?.code==="ENOENT")return this[on]="w",this[Rn]();throw e}else t=ct.openSync(this[Rt],this[on],this[Fi]);this[zr](null,t)}[Ot](){if(this[Dn]&&typeof this[fe]=="number"){let t=this[fe];this[fe]=void 0,ct.closeSync(t),this.emit("close")}}[no](t){let e=!0;try{this[Lr](null,ct.writeSync(this[fe],t,0,t.length,this[An])),e=!1}finally{if(e)try{this[Ot]()}catch{}}}},o_=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"]]),a_=t=>!!t.sync&&!!t.file,c_=t=>!t.sync&&!!t.file,d_=t=>!!t.sync&&!t.file,l_=t=>!t.sync&&!t.file,u_=t=>!!t.file,f_=t=>o_.get(t)||t,od=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let s=f_(n);e[s]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},$i=(t,e,n,i,s)=>Object.assign((a=[],d,u)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let h=od(a);if(s?.(h,d),a_(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(h,d)}else if(c_(h)){let x=e(h,d);return u?x.then(()=>u(),u):x}else if(d_(h)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return n(h,d)}else if(l_(h)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(h,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:s}),p_=x_.constants||{ZLIB_VERNUM:4736},qt=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},p_)),g_=Xn.concat,Xu=Object.getOwnPropertyDescriptor(Xn,"concat"),m_=t=>t,yc=Xu?.writable===!0||Xu?.set!==void 0?t=>{Xn.concat=t?m_:g_}:t=>{},Qn=Symbol("_superWrite"),$s=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},bc=Symbol("flushFlag"),ad=class extends tr{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Yu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Yu[e](t)}catch(n){throw new $s(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 $s(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return zc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Xn.alloc(0),{[bc]:t})))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(n)}get ended(){return this.#n}[Qn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=Xn.from(t,e)),this.#e)return;zc(this.#t,"zlib binding closed");let i=this.#t._handle,s=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},yc(!0);let d;try{let h=typeof t[bc]=="number"?t[bc]:this.#r;d=this.#t._processChunk(t,h),yc(!1)}catch(h){yc(!1),this.#o(new $s(h,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=s,this.#t.close=a,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",h=>this.#o(new $s(h,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let h=d[0];u=this[Qn](Xn.from(h));for(let x=1;x<d.length;x++)u=this[Qn](d[x])}else u=this[Qn](Xn.from(d));return n&&n(),u}},Of=class extends ad{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||qt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||qt.Z_FINISH,t.fullFlushFlag=qt.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(qt.Z_SYNC_FLUSH),zc(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(i,s)=>{typeof i=="function"&&(s=i,i=this.flushFlag),this.flush(i),s?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},w_=class extends Of{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Qn](t){return this.#e?(this.#e=!1,t[9]=255,super[Qn](t)):super[Qn](t)}},__=class extends Of{constructor(t){super(t,"Unzip")}},Lf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||qt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||qt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=qt.BROTLI_OPERATION_FLUSH,super(t,e)}},y_=class extends Lf{constructor(t){super(t,"BrotliCompress")}},b_=class extends Lf{constructor(t){super(t,"BrotliDecompress")}},Mf=class extends ad{constructor(t,e){t=t||{},t.flush=t.flush||qt.ZSTD_e_continue,t.finishFlush=t.finishFlush||qt.ZSTD_e_end,t.fullFlushFlag=qt.ZSTD_e_flush,super(t,e)}},v_=class extends Mf{constructor(t){super(t,"ZstdCompress")}},E_=class extends Mf{constructor(t){super(t,"ZstdDecompress")}},S_=(t,e)=>{if(Number.isSafeInteger(t))t<0?A_(t,e):I_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},I_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},A_=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var i=e.length;i>1;i--){var s=t&255;t=Math.floor(t/256),n?e[i-1]=Nf(s):s===0?e[i-1]=0:(n=!0,e[i-1]=Bf(s))}},k_=t=>{let e=t[0],n=e===128?T_(t.subarray(1,t.length)):e===255?C_(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},C_=t=>{for(var e=t.length,n=0,i=!1,s=e-1;s>-1;s--){var a=Number(t[s]),d;i?d=Nf(a):a===0?d=a:(i=!0,d=Bf(a)),d!==0&&(n-=d*Math.pow(256,e-s-1))}return n},T_=t=>{for(var e=t.length,n=0,i=e-1;i>-1;i--){var s=Number(t[i]);s!==0&&(n+=s*Math.pow(256,e-i-1))}return n},Nf=t=>(255^t)&255,Bf=t=>(255^t)+1&255,P_={};qw(P_,{code:()=>cd,isCode:()=>io,isName:()=>D_,name:()=>yo,normalFsTypes:()=>Ff});var io=t=>yo.has(t),D_=t=>cd.has(t),Ff=new Set(["0","","1","2","3","4","5","6","7","D"]),yo=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),cd=new Map(Array.from(yo).map(t=>[t[1],t[0]])),R_=t=>t===void 0||t<0?void 0:t,er=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,i){Buffer.isBuffer(t)?this.decode(t,e||0,n,i):t&&this.#n(t)}decode(t,e,n,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let s=Wn(t,e+156,1),a=Ff.has(s),d=a?n:void 0,u=a?i:void 0;if(this.path=d?.path??Wn(t,e,100),this.mode=d?.mode??u?.mode??kn(t,e+100,8),this.uid=d?.uid??u?.uid??kn(t,e+108,8),this.gid=d?.gid??u?.gid??kn(t,e+116,8),this.size=R_(d?.size??u?.size??kn(t,e+124,12)),this.mtime=d?.mtime??u?.mtime??vc(t,e+136,12),this.cksum=kn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),io(s)&&(this.#e=s||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Wn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Wn(t,e+265,32),this.gname=d?.gname??u?.gname??Wn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??kn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??kn(t,e+337,8)??0,t[e+475]!==0){let x=Wn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Wn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??vc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??vc(t,e+488,12)}let h=256;for(let x=e;x<e+148;x++)h+=t[x];for(let x=e+156;x<e+512;x++)h+=t[x];this.cksumValid=h===this.cksum,this.cksum===void 0&&h===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([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=O_(this.path||"",n),s=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Kn(t,e,100,s)||this.needPax,this.needPax=Cn(t,e+100,8,this.mode)||this.needPax,this.needPax=Cn(t,e+108,8,this.uid)||this.needPax,this.needPax=Cn(t,e+116,8,this.gid)||this.needPax,this.needPax=Cn(t,e+124,12,this.size)||this.needPax,this.needPax=Ec(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Kn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Kn(t,e+265,32,this.uname)||this.needPax,this.needPax=Kn(t,e+297,32,this.gname)||this.needPax,this.needPax=Cn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Cn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Kn(t,e+345,n,a)||this.needPax,t[e+475]!==0?this.needPax=Kn(t,e+345,155,a)||this.needPax:(this.needPax=Kn(t,e+345,130,a)||this.needPax,this.needPax=Ec(t,e+476,12,this.atime)||this.needPax,this.needPax=Ec(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,Cn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:yo.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(cd.get(t));if(io(e)||e==="Unsupported")this.#e=e;else if(io(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},O_=(t,e)=>{let n=t,i="",s,a=Tr.parse(t).root||".";if(Buffer.byteLength(n)<100)s=[n,i,!1];else{i=Tr.dirname(n),n=Tr.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=e?s=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=e?s=[n.slice(0,99),i,!0]:(n=Tr.join(Tr.basename(i),n),i=Tr.dirname(i));while(i!==a&&s===void 0);s||(s=[t.slice(0,99),"",!0])}return s},Wn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),vc=(t,e,n)=>L_(kn(t,e,n)),L_=t=>t===void 0?void 0:new Date(t*1e3),kn=(t,e,n)=>Number(t[e])&128?k_(t.subarray(e,e+n)):N_(t,e,n),M_=t=>isNaN(t)?void 0:t,N_=(t,e,n)=>M_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),B_={12:8589934591,8:2097151},Cn=(t,e,n,i)=>i===void 0?!1:i>B_[n]||i<0?(S_(i,t.subarray(e,e+n)),!0):(F_(t,e,n,i),!1),F_=(t,e,n,i)=>t.write(z_(i,n),e,n,"ascii"),z_=(t,e)=>U_(Math.floor(t).toString(8),e),U_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Ec=(t,e,n,i)=>i===void 0?!1:Cn(t,e,n,i.getTime()/1e3),H_=new Array(156).join("\0"),Kn=(t,e,n,i)=>i===void 0?!1:(t.write(i+H_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),xo=class zf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),i=512*Math.ceil(1+n/512),s=Buffer.allocUnsafe(i);for(let a=0;a<512;a++)s[a]=0;new er({path:("PaxHeader/"+G_(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(s),s.write(e,512,n,"utf8");for(let a=n+512;a<s.length;a++)s[a]=0;return s}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let n=this[e],i=n instanceof Date?n.getTime()/1e3:n,s=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,a=Buffer.byteLength(s),d=Math.floor(Math.log(a)/Math.log(10))+1;return a+d>=Math.pow(10,d)&&(d+=1),d+a+s}static parse(e,n,i=!1){return new zf(q_(j_(e),n),i)}},q_=(t,e)=>e?Object.assign({},e,t):t,j_=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(W_,Object.create(null)),W_=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let i=e.split("="),s=i.shift();if(!s)return t;let a=s.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=").replace(/\0.*/,"");switch(a){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":t[a]=d;break;case"ctime":case"atime":case"mtime":t[a]=new Date(Number(d)*1e3);break;case"size":let u=+d;u>=0&&(t[a]=u);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},K_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,te=K_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),$_=class extends tr{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=te(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?te(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=te(t.path)),t.linkpath&&(t.linkpath=te(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},bo=(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,Uc=Buffer.from([31,139]),Hc=Buffer.from([40,181,47,253]),J_=Math.max(Uc.length,Hc.length),yt=Symbol("state"),$n=Symbol("writeEntry"),nn=Symbol("readEntry"),Sc=Symbol("nextEntry"),Qu=Symbol("processEntry"),zt=Symbol("extendedHeader"),Ci=Symbol("globalExtendedHeader"),En=Symbol("meta"),ef=Symbol("emitMeta"),we=Symbol("buffer"),rn=Symbol("queue"),Sn=Symbol("ended"),Ic=Symbol("emittedEnd"),Vn=Symbol("emit"),Ae=Symbol("unzip"),Vs=Symbol("consumeChunk"),Js=Symbol("consumeChunkSub"),Ac=Symbol("consumeBody"),tf=Symbol("consumeMeta"),nf=Symbol("consumeHeader"),Ti=Symbol("consuming"),kc=Symbol("bufferConcat"),Zs=Symbol("maybeEnd"),Pr=Symbol("writing"),Ut=Symbol("aborted"),Ys=Symbol("onDone"),Jn=Symbol("sawValidEntry"),Xs=Symbol("sawNullBlock"),Qs=Symbol("sawEOF"),rf=Symbol("closeStream"),Z_=1e3,Pi=Symbol("compressedBytesRead"),Cc=Symbol("decompressedBytesRead"),sf=Symbol("checkDecompressionRatio"),Y_=()=>!0,Ki=class extends h_{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[rn]=[];[we];[nn];[$n];[yt]="begin";[En]="";[zt];[Ci];[Sn]=!1;[Ae];[Ut]=!1;[Jn];[Xs]=!1;[Qs]=!1;[Pr]=!1;[Ti]=!1;[Ic]=!1;[Pi]=0;[Cc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Ys,()=>{(this[yt]==="begin"||this[Jn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ys,t.ondone):this.on(Ys,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Z_,this.maxMetaEntrySize=t.maxMetaEntrySize||V_,this.filter=typeof t.filter=="function"?t.filter:Y_;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[rf]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){bo(this,t,e,n)}[nf](t,e){this[Jn]===void 0&&(this[Jn]=!1);let n;try{n=new er(t,e,this[zt],this[Ci])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[Xs]?(this[Qs]=!0,this[yt]==="begin"&&(this[yt]="header"),this[Vn]("eof")):(this[Xs]=!0,this[Vn]("nullBlock"));else if(this[Xs]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let i=n.type;if(/^(Symbolic)?Link$/.test(i)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let s=this[$n]=new $_(n,this[zt],this[Ci]);if(!this[Jn])if(s.remain){let a=()=>{s.invalid||(this[Jn]=!0)};s.on("end",a)}else this[Jn]=!0;s.meta?s.size>this.maxMetaEntrySize?(s.ignore=!0,this[Vn]("ignoredEntry",s),this[yt]="ignore",s.resume()):s.size>0&&(this[En]="",s.on("data",a=>this[En]+=a),this[yt]="meta"):(this[zt]=void 0,s.ignore=s.ignore||!this.filter(s.path,s),s.ignore?(this[Vn]("ignoredEntry",s),this[yt]=s.remain?"ignore":"header",s.resume()):(s.remain?this[yt]="body":(this[yt]="header",s.end()),this[nn]?this[rn].push(s):(this[rn].push(s),this[Sc]())))}}}[rf](){queueMicrotask(()=>this.emit("close"))}[Qu](t){let e=!0;if(!t)this[nn]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[nn]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Sc]()),e=!1);return e}[Sc](){do;while(this[Qu](this[rn].shift()));if(this[rn].length===0){let t=this[nn];!t||t.flowing||t.size===t.remain?this[Pr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ac](t,e){let n=this[$n];if(!n)throw new Error("attempt to consume body without entry??");let i=n.blockRemain??0,s=i>=t.length&&e===0?t:t.subarray(e,e+i);return n.write(s),n.blockRemain||(this[yt]="header",this[$n]=void 0,n.end()),s.length}[tf](t,e){let n=this[$n],i=this[Ac](t,e);return!this[$n]&&n&&this[ef](n),i}[Vn](t,e,n){this[rn].length===0&&!this[nn]?this.emit(t,e,n):this[rn].push([t,e,n])}[ef](t){switch(this[Vn]("meta",this[En]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[zt]=xo.parse(this[En],this[zt],!1);break;case"GlobalExtendedHeader":this[Ci]=xo.parse(this[En],this[Ci],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[zt]??Object.create(null);this[zt]=e,e.path=this[En].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[zt]||Object.create(null);this[zt]=e,e.linkpath=this[En].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ut]){if(this[Ae]){let e=this[Ae];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ut]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[sf](t){this[Cc]+=t.length;let e=this[Cc]/this[Pi];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[Ut])return n?.(),!1;if((this[Ae]===void 0||this.brotli===void 0&&this[Ae]===!1)&&t){if(this[we]&&(t=Buffer.concat([this[we],t]),this[we]=void 0),t.length<J_)return this[we]=t,n?.(),!0;for(let d=0;this[Ae]===void 0&&d<Uc.length;d++)t[d]!==Uc[d]&&(this[Ae]=!1);let s=!1;if(this[Ae]===!1&&this.zstd!==!1){s=!0;for(let d=0;d<Hc.length;d++)if(t[d]!==Hc[d]){s=!1;break}}let a=this.brotli===void 0&&!s;if(this[Ae]===!1&&a)if(t.length<512)if(this[Sn])this.brotli=!0;else return this[we]=t,n?.(),!0;else try{new er(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ae]===void 0||this[Ae]===!1&&(this.brotli||s)){let d=this[Sn];this[Sn]=!1,this[Ae]=this[Ae]===void 0?new __({}):s?new E_({}):new b_({}),this[Ae].on("data",h=>{this[sf](h)&&this[Vs](h)}),this[Ae].on("error",h=>{this[Ut]||this.abort(h)}),this[Ae].on("end",()=>{this[Sn]=!0,this[Vs]()}),this[Pr]=!0,this[Pi]+=t.length;let u=!!this[Ae][d?"end":"write"](t);return this[Pr]=!1,n?.(),u}}this[Pr]=!0,this[Ae]?(this[Pi]+=t.length,this[Ae].write(t)):this[Vs](t),this[Pr]=!1;let i=this[rn].length>0?!1:this[nn]?this[nn].flowing:!0;return!i&&this[rn].length===0&&this[nn]?.once("drain",()=>this.emit("drain")),n?.(),i}[kc](t){t&&!this[Ut]&&(this[we]=this[we]?Buffer.concat([this[we],t]):t)}[Zs](){if(this[Sn]&&!this[Ic]&&!this[Ut]&&!this[Ti]){this[Ic]=!0;let t=this[$n];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[Vn](Ys)}}[Vs](t){if(this[Ti]&&t)this[kc](t);else if(!t&&!this[we])this[Zs]();else if(t){if(this[Ti]=!0,this[we]){this[kc](t);let e=this[we];this[we]=void 0,this[Js](e)}else this[Js](t);for(;this[we]&&this[we]?.length>=512&&!this[Ut]&&!this[Qs];){let e=this[we];this[we]=void 0,this[Js](e)}this[Ti]=!1}(!this[we]||this[Sn])&&this[Zs]()}[Js](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ut]&&!this[Qs];)switch(this[yt]){case"begin":case"header":this[nf](t,e),e+=512;break;case"ignore":case"body":e+=this[Ac](t,e);break;case"meta":e+=this[tf](t,e);break;default:throw new Error("invalid state: "+this[yt])}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[Ut]||(this[Ae]?(t&&(this[Pi]+=t.length,this[Ae].write(t)),this[Ae].end()):(this[Sn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Zs]())),this}},zi=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)},X_=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Uf=(t,e)=>{let n=new Map(e.map(a=>[zi(a),!0])),i=t.filter,s=(a,d="")=>{let u=d||s_(a).root||".",h;if(a===u)h=!1;else{let x=n.get(a);h=x!==void 0?x:s(i_(a),u)}return n.set(a,h),h};t.filter=i?(a,d)=>i(a,d)&&s(zi(a)):a=>s(zi(a))},Q_=t=>{let e=new Ki(t),n=t.file,i;try{i=Nr.openSync(n,"r");let s=Nr.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(s.size<a){let d=Buffer.allocUnsafe(s.size),u=Nr.readSync(i,d,0,s.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(a);for(;d<s.size;){let h=Nr.readSync(i,u,0,a,d);if(h===0)break;d+=h,e.write(u.subarray(0,h))}e.end()}}finally{if(typeof i=="number")try{Nr.closeSync(i)}catch{}}},ey=(t,e)=>{let n=new Ki(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Nr.stat(s,(u,h)=>{if(u)d(u);else{let x=new sd(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},Ur=$i(Q_,ey,t=>new Ki(t),t=>new Ki(t),(t,e)=>{e?.length&&Uf(t,e),t.noResume||X_(t)}),Hf=(t,e,n)=>(t&=4095,n&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:ny,parse:af}=ty,dd=t=>{let e="",n=af(t);for(;ny(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=af(t)}return[e,t]},vo=["|","<",">","?",":"],ld=vo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),ry=new Map(vo.map((t,e)=>[t,ld[e]])),iy=new Map(ld.map((t,e)=>[t,vo[e]])),cf=t=>vo.reduce((e,n)=>e.split(n).join(ry.get(n)),t),sy=t=>ld.reduce((e,n)=>e.split(n).join(iy.get(n)),t),Gf=(t,e)=>e?(t=te(t).replace(/^\.(\/|$)/,""),zi(e)+"/"+t):te(t),oy=16*1024*1024,df=Symbol("process"),lf=Symbol("file"),uf=Symbol("directory"),Gc=Symbol("symlink"),ff=Symbol("hardlink"),Di=Symbol("header"),so=Symbol("read"),qc=Symbol("lstat"),oo=Symbol("onlstat"),jc=Symbol("onread"),Wc=Symbol("onreadlink"),Kc=Symbol("openfile"),$c=Symbol("onopenfile"),Tn=Symbol("close"),go=Symbol("mode"),Vc=Symbol("awaitDrain"),Tc=Symbol("ondrain"),Gt=Symbol("prefix"),qf=class extends tr{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let n=od(e);super(),this.path=te(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||oy,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=te(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?te(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[a,d]=dd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=sy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=te(n.absolute||of.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let s=this.statCache.get(this.absolute);s?this[oo](s):this[qc]()}warn(t,e,n={}){return bo(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[qc](){Ht.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[oo](e)})}[oo](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=dy(t),this.emit("stat",t),this[df]()}[df](){switch(this.type){case"File":return this[lf]();case"Directory":return this[uf]();case"SymbolicLink":return this[Gc]();default:return this.end()}}[go](t){return Hf(t,this.type==="Directory",this.portable)}[Gt](t){return Gf(t,this.prefix)}[Di](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new er({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,mode:this[go](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 xo({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[uf](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Di](),this.end()}[Gc](){Ht.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Wc](e)})}[Wc](t){this.linkpath=te(t),this[Di](),this.end()}[ff](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=te(of.relative(this.cwd,t)),this.stat.size=0,this[Di](),this.end()}[lf](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[ff](e);this.linkCache.set(t,this.absolute)}if(this[Di](),this.stat.size===0)return this.end();this[Kc]()}[Kc](){Ht.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[$c](e)})}[$c](t){if(this.fd=t,this.#e)return this[Tn]();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[so]()}[so](){let{fd:t,buf:e,offset:n,length:i,pos:s}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Ht.read(t,e,n,i,s,(a,d)=>{if(a)return this[Tn](()=>this.emit("error",a));this[jc](d)})}[Tn](t=()=>{}){this.fd!==void 0&&Ht.close(this.fd,t)}[jc](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Tn](()=>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[Tn](()=>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[Tc]():this[Vc](()=>this[Tc]())}[Vc](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[Tc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Tn](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[so]()}},ay=class extends qf{sync=!0;[qc](){this[oo](Ht.lstatSync(this.absolute))}[Gc](){this[Wc](Ht.readlinkSync(this.absolute))}[Kc](){this[$c](Ht.openSync(this.absolute,"r"))}[so](){let t=!0;try{let{fd:e,buf:n,offset:i,length:s,pos:a}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let d=Ht.readSync(e,n,i,s,a);this[jc](d),t=!1}finally{if(t)try{this[Tn](()=>{})}catch{}}}[Vc](t){t()}[Tn](t=()=>{}){this.fd!==void 0&&Ht.closeSync(this.fd),t()}},cy=class extends tr{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return bo(this,t,e,n)}constructor(t,e={}){let n=od(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=te(t.path),this.mode=t.mode!==void 0?this[go](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?te(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let s=!1;if(!this.preservePaths){let[d,u]=dd(this.path);d&&typeof u=="string"&&(this.path=u,s=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new er({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),s&&this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute path`,{entry:this,path:s+this.path}),this.header.encode()&&!this.noPax&&super.write(new xo({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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)}[Gt](t){return Gf(t,this.prefix)}[go](t){return Hf(t,this.type==="Directory",this.portable)}write(t,e,n){typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,n)}end(t,e,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),n&&this.once("finish",n),t?super.end(t,n):super.end(n),this}},dy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",ly=class Br{tail;head;length=0;static create(e=[]){return new Br(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++)fy(this,e[n]);return this.length}unshift(...e){for(var n=0,i=e.length;n<i;n++)hy(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let i=this.head,s=0;i;s++)e.call(n,i.value,s,this),i=i.next}forEachReverse(e,n){n=n||this;for(let i=this.tail,s=this.length-1;i;s--)e.call(n,i.value,s,this),i=i.prev}get(e){let n=0,i=this.head;for(;i&&n<e;n++)i=i.next;if(n===e&&i)return i.value}getReverse(e){let n=0,i=this.tail;for(;i&&n<e;n++)i=i.prev;if(n===e&&i)return i.value}map(e,n){n=n||this;let i=new Br;for(let s=this.head;s;)i.push(e.call(n,s.value,this)),s=s.next;return i}mapReverse(e,n){n=n||this;var i=new Br;for(let s=this.tail;s;)i.push(e.call(n,s.value,this)),s=s.prev;return i}reduce(e,n){let i,s=this.head;if(arguments.length>1)i=n;else if(this.head)s=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var a=0;s;a++)i=e(i,s.value,a),s=s.next;return i}reduceReverse(e,n){let i,s=this.tail;if(arguments.length>1)i=n;else if(this.tail)s=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let a=this.length-1;s;a--)i=e(i,s.value,a),s=s.prev;return i}toArray(){let e=new Array(this.length);for(let n=0,i=this.head;i;n++)e[n]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,i=this.tail;i;n++)e[n]=i.value,i=i.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Br;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.head,a=0;for(a=0;s&&a<e;a++)s=s.next;for(;s&&a<n;a++,s=s.next)i.push(s.value);return i}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let i=new Br;if(n<e||n<0)return i;e<0&&(e=0),n>this.length&&(n=this.length);let s=this.length,a=this.tail;for(;a&&s>n;s--)a=a.prev;for(;a&&s>e;s--,a=a.prev)i.push(a.value);return i}splice(e,n=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let s=this.head;for(let d=0;s&&d<e;d++)s=s.next;let a=[];for(let d=0;s&&d<n;d++)a.push(s.value),s=this.removeNode(s);s?s!==this.tail&&(s=s.prev):s=this.tail;for(let d of i)s=uy(this,s,d);return a}reverse(){let e=this.head,n=this.tail;for(let i=e;i;i=i.prev){let s=i.prev;i.prev=i.next,i.next=s}return this.head=n,this.tail=e,this}};function uy(t,e,n){let i=e,s=e?e.next:t.head,a=new ud(n,i,s,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function fy(t,e){t.tail=new ud(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function hy(t,e){t.head=new ud(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var ud=class{list;next;prev;value;constructor(t,e,n,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},xf=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},pf=Buffer.alloc(1024),ao=Symbol("onStat"),Ri=Symbol("ended"),Pt=Symbol("queue"),Oi=Symbol("pendingLinks"),In=Symbol("current"),Zn=Symbol("process"),Li=Symbol("processing"),eo=Symbol("processJob"),Dt=Symbol("jobs"),Pc=Symbol("jobDone"),co=Symbol("addFSEntry"),gf=Symbol("addTarEntry"),Jc=Symbol("stat"),Zc=Symbol("readdir"),lo=Symbol("onreaddir"),uo=Symbol("pipe"),mf=Symbol("entry"),Dc=Symbol("entryOpt"),fo=Symbol("writeEntryClass"),jf=Symbol("write"),Rc=Symbol("ondrain"),Eo=class extends tr{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[fo];onWriteEntry;[Pt];[Oi]=new Map;[Dt]=0;[Li]=!1;[Ri]=!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=te(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[fo]=qf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new w_(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new y_(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new v_(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[Rc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Rc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[Pt]=new ly,this[Dt]=0,this.jobs=Number(t.jobs)||4,this[Li]=!1,this[Ri]=!1}[jf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&this.add(t),this[Ri]=!0,this[Zn](),n&&n(),this}write(t){if(this[Ri])throw new Error("write after end");return typeof t=="string"?this[co](t):this[gf](t),this.flowing}[gf](t){let e=te(hf.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new xf(t.path,e);n.entry=new cy(t,this[Dc](n)),n.entry.on("end",()=>this[Pc](n)),this[Dt]+=1,this[Pt].push(n)}this[Zn]()}[co](t){let e=te(hf.resolve(this.cwd,t));this[Pt].push(new xf(t,e)),this[Zn]()}[Jc](t){t.pending=!0,this[Dt]+=1;let e=this.follow?"stat":"lstat";po[e](t.absolute,(n,i)=>{t.pending=!1,this[Dt]-=1,n?this.emit("error",n):this[ao](t,i)})}[ao](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[In])this[eo](t);else{let n=`${e.dev}:${e.ino}`,i=this[Oi].get(n);i?i.push(t):this[Oi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Zn]()}[Zc](t){t.pending=!0,this[Dt]+=1,po.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Dt]-=1,e)return this.emit("error",e);this[lo](t,n)})}[lo](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Zn]()}[Zn](){if(!this[Li]){this[Li]=!0;for(let t=this[Pt].head;t&&this[Dt]<this.jobs;t=t.next)if(this[eo](t.value),t.value.ignore){let e=t.next;this[Pt].removeNode(t),t.next=e}this[Li]=!1,this[Ri]&&this[Pt].length===0&&this[Dt]===0&&(this.zip?this.zip.end(pf):(super.write(pf),super.end()))}}get[In](){return this[Pt]&&this[Pt].head&&this[Pt].head.value}[Pc](t){this[Pt].shift(),this[Dt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Oi].get(n);if(i){this[Oi].delete(n);for(let s of i)s.pending=!1,this[eo](s)}}this[Zn]()}[eo](t){if(t.pending&&t.pendingLink&&t===this[In]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[In]&&!t.piped&&this[uo](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[ao](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[lo](t,e):this[Zc](t),!t.readdir)return}if(t.entry=this[mf](t),!t.entry){t.ignore=!0;return}t===this[In]&&!t.piped&&this[uo](t)}}}[Dc](t){return{onwarn:(e,n,i)=>this.warn(e,n,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[mf](t){this[Dt]+=1;try{return new this[fo](t.path,this[Dc](t)).on("end",()=>this[Pc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Rc](){this[In]&&this[In].entry&&this[In].entry.resume()}[uo](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[co](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={}){bo(this,t,e,n)}},fd=class extends Eo{sync=!0;constructor(t){super(t),this[fo]=ay}pause(){}resume(){}[Jc](t){let e=this.follow?"statSync":"lstatSync";this[ao](t,po[e](t.absolute))}[Zc](t){this[lo](t,po.readdirSync(t.absolute))}[uo](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let s=t.path,a=s==="./"?"":s.replace(/\/*$/,"/");this[co](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[jf](i)})}},xy=(t,e)=>{let n=new fd(t),i=new Df(t.file,{mode:t.mode||438});n.pipe(i),Wf(n,e)},py=(t,e)=>{let n=new Eo(t),i=new _o(t.file,{mode:t.mode||438});n.pipe(i);let s=new Promise((a,d)=>{i.on("error",d),i.on("close",a),n.on("error",d)});return Kf(n,e).catch(a=>n.emit("error",a)),s},Wf=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Ur({file:Rf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Kf=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Ur({file:Rf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},gy=(t,e)=>{let n=new fd(t);return Wf(n,e),n},my=(t,e)=>{let n=new Eo(t);return Kf(n,e).catch(i=>n.emit("error",i)),n},qk=$i(xy,py,gy,my,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),_y=process.env.__FAKE_PLATFORM__||process.platform,Zf=_y==="win32",{O_CREAT:Yf,O_NOFOLLOW:wf,O_TRUNC:Xf,O_WRONLY:Qf}=Jf.constants,e0=Number(process.env.__FAKE_FS_O_FILENAME__)||Jf.constants.UV_FS_O_FILEMAP||0,yy=Zf&&!!e0,by=512*1024,vy=e0|Xf|Yf|Qf,_f=!Zf&&typeof wf=="number"?wf|Xf|Yf|Qf:null,t0=_f!==null?()=>_f:yy?t=>t<by?vy:"w":()=>"w",Yc=(t,e,n)=>{try{return So.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},mo=(t,e,n,i)=>{So.lchown(t,e,n,s=>{i(s&&s?.code!=="ENOENT"?s:null)})},Ey=(t,e,n,i,s)=>{if(e.isDirectory())n0(Ui.resolve(t,e.name),n,i,a=>{if(a)return s(a);let d=Ui.resolve(t,e.name);mo(d,n,i,s)});else{let a=Ui.resolve(t,e.name);mo(a,n,i,s)}},n0=(t,e,n,i)=>{So.readdir(t,{withFileTypes:!0},(s,a)=>{if(s){if(s.code==="ENOENT")return i();if(s.code!=="ENOTDIR"&&s.code!=="ENOTSUP")return i(s)}if(s||!a.length)return mo(t,e,n,i);let d=a.length,u=null,h=x=>{if(!u){if(x)return i(u=x);if(--d===0)return mo(t,e,n,i)}};for(let x of a)Ey(t,x,e,n,h)})},Sy=(t,e,n,i)=>{e.isDirectory()&&r0(Ui.resolve(t,e.name),n,i),Yc(Ui.resolve(t,e.name),n,i)},r0=(t,e,n)=>{let i;try{i=So.readdirSync(t,{withFileTypes:!0})}catch(s){let a=s;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return Yc(t,e,n);throw a}for(let s of i)Sy(t,s,e,n);return Yc(t,e,n)},i0=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},Io=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"}},Ay=(t,e)=>{pt.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new i0(t,n?.code||"ENOTDIR")),e(n)})},ky=(t,e,n)=>{t=te(t);let i=e.umask??18,s=e.mode|448,a=(s&i)!==0,d=e.uid,u=e.gid,h=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,w=te(e.cwd),b=(v,I)=>{v?n(v):I&&h?n0(I,d,u,A=>b(A)):a?pt.chmod(t,s,n):n()};if(t===w)return Ay(t,b);if(x)return Iy.mkdir(t,{mode:s,recursive:!0}).then(v=>b(null,v??void 0),b);let y=te(wo.relative(w,t)).split("/");Xc(w,y,s,p,w,void 0,b)},Xc=(t,e,n,i,s,a,d)=>{if(e.length===0)return d(null,a);let u=e.shift(),h=te(wo.resolve(t+"/"+u));pt.mkdir(h,n,s0(h,e,n,i,s,a,d))},s0=(t,e,n,i,s,a,d)=>u=>{u?pt.lstat(t,(h,x)=>{if(h)h.path=h.path&&te(h.path),d(h);else if(x.isDirectory())Xc(t,e,n,i,s,a,d);else if(i)pt.unlink(t,p=>{if(p)return d(p);pt.mkdir(t,n,s0(t,e,n,i,s,a,d))});else{if(x.isSymbolicLink())return d(new Io(t,t+"/"+e.join("/")));d(u)}}):(a=a||t,Xc(t,e,n,i,s,a,d))},Cy=t=>{let e=!1,n;try{e=pt.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new i0(t,n??"ENOTDIR")}},Ty=(t,e)=>{t=te(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,a=e.uid,d=e.gid,u=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),h=e.preserve,x=e.unlink,p=te(e.cwd),w=v=>{v&&u&&r0(v,a,d),s&&pt.chmodSync(t,i)};if(t===p)return Cy(p),w();if(h)return w(pt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let b=te(wo.relative(p,t)).split("/"),y;for(let v=b.shift(),I=p;v&&(I+="/"+v);v=b.shift()){I=te(wo.resolve(I));try{pt.mkdirSync(I,i),y=y||I}catch{let A=pt.lstatSync(I);if(A.isDirectory())continue;if(x){pt.unlinkSync(I),pt.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new Io(I,I+"/"+b.join("/"))}}return w(y)},Oc=Object.create(null),yf=1e4,Dr=new Set,Py=t=>{Dr.has(t)?Dr.delete(t):Oc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Dr.add(t);let e=Oc[t],n=Dr.size-yf;if(n>yf/10){for(let i of Dr)if(Dr.delete(i),delete Oc[i],--n<=0)break}return e},Dy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ry=Dy==="win32",Oy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=o0(i,n)),e.push(n||"/"),e},[]),Ly=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=Ry?["win32 parallelization disabled"]:t.map(i=>zi(o0(Py(i))));let n=new Set(t.map(i=>Oy(i)).reduce((i,s)=>i.concat(s)));this.#n.set(e,{dirs:n,paths:t});for(let i of t){let s=this.#e.get(i);s?s.push(e):this.#e.set(i,[e])}for(let i of n){let s=this.#e.get(i);if(!s)this.#e.set(i,[new Set([e])]);else{let a=s.at(-1);a instanceof Set?a.add(e):s.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(i=>i&&i[0]===t)&&n.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:i}=e,s=new Set;for(let a of n){let d=this.#e.get(a);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(a);continue}if(d.shift(),typeof u=="function")s.add(u);else for(let h of u)s.add(h)}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 h=d[0];typeof h=="function"&&s.add(h)}else u.delete(t)}return this.#r.delete(t),s.forEach(a=>this.#i(a)),!0}},My=()=>process.umask(),bf=Symbol("onEntry"),Qc=Symbol("checkFs"),vf=Symbol("checkFs2"),ed=Symbol("isReusable"),bt=Symbol("makeFs"),td=Symbol("file"),nd=Symbol("directory"),ho=Symbol("link"),Ef=Symbol("symlink"),Sf=Symbol("hardlink"),Bi=Symbol("ensureNoSymlink"),If=Symbol("unsupported"),Af=Symbol("checkPath"),Lc=Symbol("stripAbsolutePath"),Pn=Symbol("mkdir"),qe=Symbol("onError"),to=Symbol("pending"),kf=Symbol("pend"),Rr=Symbol("unpend"),Mc=Symbol("ended"),Nc=Symbol("maybeClose"),rd=Symbol("skip"),Hi=Symbol("doChown"),Gi=Symbol("uid"),qi=Symbol("gid"),ji=Symbol("checkedCwd"),Ny=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Wi=Ny==="win32",By=1024,Fy=(t,e)=>{if(!Wi)return se.unlink(t,e);let n=t+".DELETE."+Vf(16).toString("hex");se.rename(t,n,i=>{if(i)return e(i);se.unlink(n,e)})},zy=t=>{if(!Wi)return se.unlinkSync(t);let e=t+".DELETE."+Vf(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},Cf=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,hd=class extends Ki{[Mc]=!1;[ji]=!1;[to]=0;reservations=new Ly;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[Mc]=!0,this[Nc]()},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:By,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Wi,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=te(Fe.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:My():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[bf](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Nc](){this[Mc]&&this[to]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Lc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[s,a]=dd(n),d=a.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Wi&&/^[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=Fe.posix.dirname(t.path),h=Fe.posix.normalize(Fe.posix.join(u,d.join("/")));if(h.startsWith("../")||h==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return s&&(t[e]=String(a),this.warn("TAR_ENTRY_INFO",`stripping ${s} from absolute ${e}`,{entry:t,[e]:n})),!0}[Af](t){let e=te(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=te(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[Lc](t,"path")||!this[Lc](t,"linkpath"))return!1;if(t.absolute=Fe.isAbsolute(t.path)?te(Fe.resolve(t.path)):te(Fe.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:te(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}=Fe.win32.parse(String(t.absolute));t.absolute=i+cf(String(t.absolute).slice(i.length));let{root:s}=Fe.win32.parse(t.path);t.path=s+cf(t.path.slice(s.length))}return!0}[bf](t){if(!this[Af](t))return t.resume();switch(wy.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Qc](t);default:return this[If](t)}}[qe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Rr](),e.resume())}[Pn](t,e,n){ky(te(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)}[Hi](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}[Gi](t){return Cf(this.uid,t.uid,this.processUid)}[qi](t){return Cf(this.gid,t.gid,this.processGid)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new _o(String(t.absolute),{flags:t0(t.size),mode:n,autoClose:!1});i.on("error",u=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[qe](u,t),e()});let s=1,a=u=>{if(u){i.fd&&se.close(i.fd,()=>{}),this[qe](u,t),e();return}--s===0&&i.fd!==void 0&&se.close(i.fd,h=>{h?this[qe](h,t):this[Rr](),e()})};i.on("finish",()=>{let u=String(t.absolute),h=i.fd;if(typeof h=="number"&&t.mtime&&!this.noMtime){s++;let x=t.atime||new Date,p=t.mtime;se.futimes(h,x,p,w=>w?se.utimes(u,x,p,b=>a(b&&w)):a())}if(typeof h=="number"&&this[Hi](t)){s++;let x=this[Gi](t),p=this[qi](t);typeof x=="number"&&typeof p=="number"&&se.fchown(h,x,p,w=>w?se.chown(u,x,p,b=>a(b&&w)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[qe](u,t),e()}),t.pipe(d)),d.pipe(i)}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Pn](String(t.absolute),n,i=>{if(i){this[qe](i,t),e();return}let s=1,a=()=>{--s===0&&(e(),this[Rr](),t.resume())};t.mtime&&!this.noMtime&&(s++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Hi](t)&&(s++,se.chown(String(t.absolute),Number(this[Gi](t)),Number(this[qi](t)),a)),a()})}[If](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ef](t,e){let n=te(Fe.relative(this.cwd,Fe.resolve(Fe.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Bi](t,this.cwd,n,()=>this[ho](t,String(t.linkpath),"symlink",e),i=>{this[qe](i,t),e()})}[Sf](t,e){let n=te(Fe.resolve(this.cwd,String(t.linkpath))),i=te(String(t.linkpath)).split("/");this[Bi](t,this.cwd,i,()=>this[ho](t,n,"link",e),s=>{this[qe](s,t),e()})}[Bi](t,e,n,i,s){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Fe.resolve(e,a);se.lstat(d,(u,h)=>{if(u)return i();if(h?.isSymbolicLink())return s(new Io(d,Fe.resolve(d,n.join("/"))));this[Bi](t,d,n,i,s)})}[kf](){this[to]++}[Rr](){this[to]--,this[Nc]()}[rd](t){this[Rr](),t.resume()}[ed](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Wi}[Qc](t){this[kf]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[vf](t,n))}[vf](t,e){let n=d=>{e(d)},i=()=>{this[Pn](this.cwd,this.dmode,d=>{if(d){this[qe](d,t),n();return}this[ji]=!0,s()})},s=()=>{if(t.absolute!==this.cwd){let d=te(Fe.dirname(String(t.absolute)));if(d!==this.cwd)return this[Pn](d,this.dmode,u=>{if(u){this[qe](u,t),n();return}a()})}a()},a=()=>{se.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[rd](t),n();return}if(d||this[ed](t,u))return this[bt](null,t,n);if(u.isDirectory()){if(t.type==="Directory"){let h=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[bt](p??null,t,n);return h?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),h=>this[bt](h??null,t,n))}if(t.absolute===this.cwd)return this[bt](null,t,n);Fy(String(t.absolute),h=>this[bt](h??null,t,n))})};this[ji]?s():i()}[bt](t,e,n){if(t){this[qe](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[td](e,n);case"Link":return this[Sf](e,n);case"SymbolicLink":return this[Ef](e,n);case"Directory":case"GNUDumpDir":return this[nd](e,n)}}[ho](t,e,n,i){se[n](e,String(t.absolute),s=>{s?this[qe](s,t):(this[Rr](),t.resume()),i()})}},Mi=t=>{try{return[null,t()]}catch(e){return[e,null]}},a0=class extends hd{sync=!0;[bt](t,e){return super[bt](t,e,()=>{})}[Qc](t){if(!this[ji]){let s=this[Pn](this.cwd,this.dmode);if(s)return this[qe](s,t);this[ji]=!0}if(t.absolute!==this.cwd){let s=te(Fe.dirname(String(t.absolute)));if(s!==this.cwd){let a=this[Pn](s,this.dmode);if(a)return this[qe](a,t)}}let[e,n]=Mi(()=>se.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[rd](t);if(e||this[ed](t,n))return this[bt](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Mi(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[bt](d,t)}let[s]=Mi(()=>se.rmdirSync(String(t.absolute)));this[bt](s,t)}let[i]=t.absolute===this.cwd?[]:Mi(()=>zy(String(t.absolute)));this[bt](i,t)}[td](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{se.closeSync(s)}catch(h){u=h}(d||u)&&this[qe](d||u,t),e()},s;try{s=se.openSync(String(t.absolute),t0(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[qe](d,t)),t.pipe(a)),a.on("data",d=>{try{se.writeSync(s,d,0,d.length)}catch(u){i(u)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,h=t.mtime;try{se.futimesSync(s,u,h)}catch(x){try{se.utimesSync(String(t.absolute),u,h)}catch{d=x}}}if(this[Hi](t)){let u=this[Gi](t),h=this[qi](t);try{se.fchownSync(s,Number(u),Number(h))}catch(x){try{se.chownSync(String(t.absolute),Number(u),Number(h))}catch{d=d||x}}}i(d)})}[nd](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[Pn](String(t.absolute),n);if(i){this[qe](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Hi](t))try{se.chownSync(String(t.absolute),Number(this[Gi](t)),Number(this[qi](t)))}catch{}e(),t.resume()}[Pn](t,e){try{return Ty(te(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}}[Bi](t,e,n,i,s){if(this.preservePaths||n.length===0)return i();let a=e;for(let d of n){a=Fe.resolve(a,d);let[u,h]=Mi(()=>se.lstatSync(a));if(u)return i();if(h.isSymbolicLink())return s(new Io(a,Fe.resolve(e,n.join("/"))))}i()}[ho](t,e,n,i){let s=`${n}Sync`;try{se[s](e,String(t.absolute)),i(),t.resume()}catch(a){return this[qe](a,t)}}},Uy=t=>{let e=new a0(t),n=t.file,i=$f.statSync(n),s=t.maxReadSize||16*1024*1024;new r_(n,{readSize:s,size:i.size}).pipe(e)},Hy=(t,e)=>{let n=new hd(t),i=t.maxReadSize||16*1024*1024,s=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),$f.stat(s,(u,h)=>{if(u)d(u);else{let x=new sd(s,{readSize:i,size:h.size});x.on("error",d),x.pipe(n)}})})},c0=$i(Uy,Hy,t=>new a0(t),t=>new hd(t),(t,e)=>{e?.length&&Uf(t,e)}),Gy=(t,e)=>{let n=new fd(t),i=!0,s,a;try{try{s=xt.openSync(t.file,"r+")}catch(h){if(h?.code==="ENOENT")s=xt.openSync(t.file,"w+");else throw h}let d=xt.fstatSync(s),u=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,w=0;p<512;p+=w){if(w=xt.readSync(s,u,p,u.length-p,a+p),a===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let h=new er(u);if(!h.cksumValid)break;let x=512*Math.ceil((h.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime)}i=!1,qy(t,n,a,s,e)}finally{if(i)try{xt.closeSync(s)}catch{}}},qy=(t,e,n,i,s)=>{let a=new Df(t.file,{fd:i,start:n});e.pipe(a),Wy(e,s)},jy=(t,e)=>{e=Array.from(e);let n=new Eo(t),i=(s,a,d)=>{let u=(b,y)=>{b?xt.close(s,v=>d(b)):d(null,y)},h=0;if(a===0)return u(null,0);let x=0,p=Buffer.alloc(512),w=(b,y)=>{if(b||y===void 0)return u(b);if(x+=y,x<512&&y)return xt.read(s,p,x,p.length-x,h+x,w);if(h===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,h);let v=new er(p);if(!v.cksumValid)return u(null,h);let I=512*Math.ceil((v.size??0)/512);if(h+I+512>a||(h+=I+512,h>=a))return u(null,h);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,xt.read(s,p,0,512,h,w)};xt.read(s,p,0,512,h,w)};return new Promise((s,a)=>{n.on("error",a);let d="r+",u=(h,x)=>{if(h&&h.code==="ENOENT"&&d==="r+")return d="w+",xt.open(t.file,d,u);if(h||!x)return a(h);xt.fstat(x,(p,w)=>{if(p)return xt.close(x,()=>a(p));i(x,w.size,(b,y)=>{if(b)return a(b);let v=new _o(t.file,{fd:x,start:y});n.pipe(v),v.on("error",a),v.on("close",s),Ky(n,e)})})};xt.open(t.file,d,u)})},Wy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Ur({file:d0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Ky=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Ur({file:d0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Ni=$i(Gy,jy,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!u_(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")}),iC=$i(Ni.syncFile,Ni.asyncFile,Ni.syncNoFile,Ni.asyncNoFile,(t,e=[])=>{Ni.validate?.(t,e),$y(t)}),$y=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(n,i)=>e(n,i)&&!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0)):(n,i)=>!((t.mtimeCache?.get(n)??i.mtime??0)>(i.mtime??0))};Qt();var nt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill",SET_CONFIG_OPTION:"_agent/setConfigOption",LIST_AVAILABLE_MODELS:"_agent/listAvailableModels"};function nr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function l0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Ao(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function u0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function f0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function h0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function rr(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Ct();import{homedir as Jy}from"node:os";import x0 from"node:path";var p0=".claude",g0="settings.json",ko=new Map;function m0(t){return x0.join(t,p0,g0)}async function w0(t,e){let n=m0(t),s=(ko.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=await Ze(n)??{};a.effortLevel=e,await ft(n,a)});ko.set(n,s);try{await s}finally{ko.get(n)===s&&ko.delete(n)}}async function _0(t){let n=(await Ze(m0(t)))?.effortLevel;return typeof n=="string"?n:void 0}async function y0(){let t=x0.join(Jy(),p0,g0),n=(await Ze(t))?.effortLevel;return typeof n=="string"?n:void 0}an();Ve();ne();Ce();Ve();function Vi(t,e){if(nr(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function xd(t,e){if(nr(t)==="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_CLOUD",`${e} is not allowed for cloud agent`)}function Ji(t){return t.startsWith("http://")||t.startsWith("https://")}function Hr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as QC}from"node:fs";import{dirname as tT,join as nT}from"node:path";import{fileURLToPath as iT}from"node:url";var jt="0.3.2-alpha.105";var pd={"claude-code":{effort:["default","low","medium","high","xhigh","max"],fastMode:null},codex:{effort:["low","medium","high","xhigh"],fastMode:["off","on"]},hermes:{effort:null,fastMode:null},openclaw:{effort:null,fastMode:null}};function S0(t,e){return pd[t][e]}import{mkdir as ub,rm as z0}from"node:fs/promises";import{join as Qi}from"node:path";Ct();import{readFileSync as nb}from"node:fs";var rb=384;async function gd(t,e=process.env){let n={};for(let[i,s]of Object.entries(e))typeof s=="string"&&(n[i]=s);await ft(t.agentEnvFile,n,{mode:rb})}function ir(t){try{let e=JSON.parse(nb(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Co(t,e,n={},i=s=>s){return{...i({...t,...ir(e)}),...n}}Ct();function Zi(t){let e=[],n=Object.keys(t).sort();for(let i of n){let s=t[i];s!==void 0&&(ib(s)||e.push(`${i}=${s}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return tk(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 Pg("schtasks",["/Create","/SC","ONLOGON","/TN",qa,"/TR",n,"/RU",t.userName,"/F"]),Nl.info("task scheduler entry created",{task:qa,logFile:t.logFile})},async uninstall(t){await Pg("schtasks",["/Delete","/TN",qa,"/F"]).catch(e=>Nl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Nl.info("task scheduler entry removed",{task:qa})}}});var Og={};tc(Og,{buildContext:()=>ak,getSupervisor:()=>ik,launchdSupervisor:()=>Ll,systemdSupervisor:()=>Ml,taskSchedulerSupervisor:()=>Fl});import{homedir as nk,userInfo as rk}from"node:os";function ik(t=process.platform){switch(t){case"darwin":return Ll;case"linux":return Ml;case"win32":return Fl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function ok(){let t={};for(let e of sk){let n=process.env[e];n&&(t[e]=n)}return t}function ak(){let t=Z();return{nodeBin:process.execPath,entry:Il(t),logFile:t.logFile,homeDir:nk(),userName:rk().username,isRoot:process.getuid?.()===0,env:ok()}}var sk,Lg=ot(()=>{"use strict";Pe();Da();Tg();Rg();Dg();sk=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();vn();var hf=q("acp-installer-warmup"),aw=["claude-code","codex"];async function xf(t={}){let e=t.ensure??kr,i=(await Promise.allSettled(aw.map(async o=>{let a=await e(o);hf.info("acp wrapper warmup ok",{framework:o,path:a})}))).filter(o=>o.status==="rejected");i.length>0&&hf.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))})}tn();ne();import{readdir as vw}from"node:fs/promises";import{mkdir as wf,readFile as Ew,writeFile as _f}from"node:fs/promises";import{join as cc}from"node:path";var bw={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md",hermes:"AGENTS.md"};async function Tr(t,e,n){await wf(t,{recursive:!0});let i=bw[e],o=cc(t,i);return await _f(o,n??"","utf8"),o}async function dc(t,e,n){let i=cc(t,".claude");await wf(i,{recursive:!0});let o=cc(i,"settings.local.json"),a={};try{let f=await Ew(o,"utf8"),u=JSON.parse(f);typeof u=="object"&&u!==null&&!Array.isArray(u)&&(a=u)}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 _f(o,JSON.stringify(a,null,2),"utf8"),o}var et=q("agent-detail-sync"),Sw=6e4,Iw=5*6e4,Hs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,i;try{i=await vw(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 we(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 we(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(u){et.warn("detail RPC failed, using local data",{agentId:e,err:String(u)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,Iw):Sw;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 f=!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,f=!0):o.deployType&&et.info("detail.deployType",{agentId:e,deployType:o.deployType}),!a){et.debug("detail sync: no diff",{agentId:e});return}await Le(i,this.opts.paths),et.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),f?(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 Tr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var zd=en(Yf(),1);import{createHash as IE}from"node:crypto";import{lstat as Pd,mkdir as Dd,readFile as Bo,readdir as rh,rm as Od,stat as Fd,writeFile as Ld}from"node:fs/promises";import{homedir as AE}from"node:os";import{basename as eh,dirname as kE,join as xe,normalize as TE,relative as Bd,resolve as Md,sep as ih}from"node:path";import{Readable as sh}from"node:stream";import{pipeline as oh}from"node:stream/promises";import $w from"events";import ct from"fs";import{EventEmitter as dd}from"node:events";import Lu from"node:stream";import{StringDecoder as Vw}from"node:string_decoder";import Fu from"node:path";import Ur from"node:fs";import{dirname as a_,parse as c_}from"path";import{EventEmitter as g_}from"events";import jc from"assert";import{Buffer as tr}from"buffer";import*as ru from"zlib";import m_ from"zlib";import{posix as Or}from"node:path";import{basename as W_}from"node:path";import yo from"fs";import qt from"fs";import fu from"path";import{win32 as iy}from"node:path";import wu from"path";import Yu from"node:fs";import Ey from"node:assert";import{randomBytes as Qu}from"node:crypto";import se from"node:fs";import Ue from"node:path";import e0 from"fs";import Co from"node:fs";import Wi from"node:path";import pt from"node:fs";import Ty from"node:fs/promises";import vo from"node:path";import{join as f0}from"node:path";import xt from"node:fs";import x0 from"node:path";var Ww=Object.defineProperty,Kw=(t,e)=>{for(var n in e)Ww(t,n,{get:e[n],enumerable:!0})},Qf=typeof process=="object"&&process?process:{stdout:null,stderr:null},Jw=t=>!!t&&typeof t=="object"&&(t instanceof ir||t instanceof Lu||Zw(t)||Xw(t)),Zw=t=>!!t&&typeof t=="object"&&t instanceof dd&&typeof t.pipe=="function"&&t.pipe!==Lu.Writable.prototype.pipe,Xw=t=>!!t&&typeof t=="object"&&t instanceof dd&&typeof t.write=="function"&&typeof t.end=="function",nn=Symbol("EOF"),rn=Symbol("maybeEmitEnd"),In=Symbol("emittedEnd"),Ks=Symbol("emittingEnd"),ki=Symbol("emittedError"),$s=Symbol("closed"),eu=Symbol("read"),Vs=Symbol("flush"),tu=Symbol("flushChunk"),Rt=Symbol("encoding"),Dr=Symbol("decoder"),Ge=Symbol("flowing"),Ti=Symbol("paused"),Fr=Symbol("resume"),je=Symbol("buffer"),nt=Symbol("pipes"),We=Symbol("bufferLength"),pc=Symbol("bufferPush"),Js=Symbol("bufferShift"),Qe=Symbol("objectMode"),De=Symbol("destroyed"),gc=Symbol("error"),mc=Symbol("emitData"),nu=Symbol("emitEnd"),wc=Symbol("emitEnd2"),Bt=Symbol("async"),_c=Symbol("abort"),Zs=Symbol("aborted"),Ci=Symbol("signal"),Kn=Symbol("dataListeners"),ht=Symbol("discarded"),Ri=t=>Promise.resolve().then(t),Yw=t=>t(),Qw=t=>t==="end"||t==="finish"||t==="prefinish",e_=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,t_=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Mu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[Fr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},n_=class extends Mu{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)}},r_=t=>!!t.objectMode,i_=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",ir=class extends dd{[Ge]=!1;[Ti]=!1;[nt]=[];[je]=[];[Qe];[Rt];[Bt];[Dr];[nn]=!1;[In]=!1;[Ks]=!1;[$s]=!1;[ki]=null;[We]=0;[De]=!1;[Ci];[Zs]=!1;[Kn]=0;[ht]=!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");r_(e)?(this[Qe]=!0,this[Rt]=null):i_(e)?(this[Rt]=e.encoding,this[Qe]=!1):(this[Qe]=!1,this[Rt]=null),this[Bt]=!!e.async,this[Dr]=this[Rt]?new Vw(this[Rt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[je]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[nt]});let{signal:n}=e;n&&(this[Ci]=n,n.aborted?this[_c]():n.addEventListener("abort",()=>this[_c]()))}get bufferLength(){return this[We]}get encoding(){return this[Rt]}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[Bt]}set async(t){this[Bt]=this[Bt]||!!t}[_c](){this[Zs]=!0,this.emit("abort",this[Ci]?.reason),this.destroy(this[Ci]?.reason)}get aborted(){return this[Zs]}set aborted(t){}write(t,e,n){if(this[Zs])return!1;if(this[nn])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[Bt]?Ri:Yw;if(!this[Qe]&&!Buffer.isBuffer(t)){if(t_(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(e_(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[Ge]&&this[We]!==0&&this[Vs](!0),this[Ge]?this.emit("data",t):this[pc](t),this[We]!==0&&this.emit("readable"),n&&i(n),this[Ge]):t.length?(typeof t=="string"&&!(e===this[Rt]&&!this[Dr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Rt]&&(t=this[Dr].write(t)),this[Ge]&&this[We]!==0&&this[Vs](!0),this[Ge]?this.emit("data",t):this[pc](t),this[We]!==0&&this.emit("readable"),n&&i(n),this[Ge]):(this[We]!==0&&this.emit("readable"),n&&i(n),this[Ge])}read(t){if(this[De])return null;if(this[ht]=!1,this[We]===0||t===0||t&&t>this[We])return this[rn](),null;this[Qe]&&(t=null),this[je].length>1&&!this[Qe]&&(this[je]=[this[Rt]?this[je].join(""):Buffer.concat(this[je],this[We])]);let e=this[eu](t||null,this[je][0]);return this[rn](),e}[eu](t,e){if(this[Qe])this[Js]();else{let n=e;t===n.length||t===null?this[Js]():typeof n=="string"?(this[je][0]=n.slice(t),e=n.slice(0,t),this[We]-=t):(this[je][0]=n.subarray(t),e=n.subarray(0,t),this[We]-=t)}return this.emit("data",e),!this[je].length&&!this[nn]&&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[nn]=!0,this.writable=!1,(this[Ge]||!this[Ti])&&this[rn](),this}[Fr](){this[De]||(!this[Kn]&&!this[nt].length&&(this[ht]=!0),this[Ti]=!1,this[Ge]=!0,this.emit("resume"),this[je].length?this[Vs]():this[nn]?this[rn]():this.emit("drain"))}resume(){return this[Fr]()}pause(){this[Ge]=!1,this[Ti]=!0,this[ht]=!1}get destroyed(){return this[De]}get flowing(){return this[Ge]}get paused(){return this[Ti]}[pc](t){this[Qe]?this[We]+=1:this[We]+=t.length,this[je].push(t)}[Js](){return this[Qe]?this[We]-=1:this[We]-=this[je][0].length,this[je].shift()}[Vs](t=!1){do;while(this[tu](this[Js]())&&this[je].length);!t&&!this[je].length&&!this[nn]&&this.emit("drain")}[tu](t){return this.emit("data",t),this[Ge]}pipe(t,e){if(this[De])return t;this[ht]=!1;let n=this[In];return e=e||{},t===Qf.stdout||t===Qf.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[nt].push(e.proxyErrors?new n_(this,t,e):new Mu(this,t,e)),this[Bt]?Ri(()=>this[Fr]()):this[Fr]()),t}unpipe(t){let e=this[nt].find(n=>n.dest===t);e&&(this[nt].length===1?(this[Ge]&&this[Kn]===0&&(this[Ge]=!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[ht]=!1,this[Kn]++,!this[nt].length&&!this[Ge]&&this[Fr]();else if(t==="readable"&&this[We]!==0)super.emit("readable");else if(Qw(t)&&this[In])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ki]){let i=e;this[Bt]?Ri(()=>i.call(this,this[ki])):i.call(this,this[ki])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Kn]=this.listeners("data").length,this[Kn]===0&&!this[ht]&&!this[nt].length&&(this[Ge]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Kn]=0,!this[ht]&&!this[nt].length&&(this[Ge]=!1)),e}get emittedEnd(){return this[In]}[rn](){!this[Ks]&&!this[In]&&!this[De]&&this[je].length===0&&this[nn]&&(this[Ks]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[$s]&&this.emit("close"),this[Ks]=!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[Bt]?(Ri(()=>this[mc](n)),!0):this[mc](n);if(t==="end")return this[nu]();if(t==="close"){if(this[$s]=!0,!this[In]&&!this[De])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ki]=n,super.emit(gc,n);let o=!this[Ci]||this.listeners("error").length?super.emit("error",n):!1;return this[rn](),o}else if(t==="resume"){let o=super.emit("resume");return this[rn](),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[rn](),i}[mc](t){for(let n of this[nt])n.dest.write(t)===!1&&this.pause();let e=this[ht]?!1:super.emit("data",t);return this[rn](),e}[nu](){return this[In]?!1:(this[In]=!0,this.readable=!1,this[Bt]?(Ri(()=>this[wc]()),!0):this[wc]())}[wc](){if(this[Dr]){let e=this[Dr].end();if(e){for(let n of this[nt])n.dest.write(e);this[ht]||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[Rt]?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[ht]=!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[nn])return e();let i,o,a=x=>{this.off("data",d),this.off("end",f),this.off(De,u),e(),o(x)},d=x=>{this.off("error",a),this.off("end",f),this.off(De,u),this.pause(),i({value:x,done:!!this[nn]})},f=()=>{this.off("error",a),this.off("data",d),this.off(De,u),e(),i({done:!0,value:void 0})},u=()=>a(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(De,u),this.once("error",a),this.once("end",f),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ht]=!1;let t=!1,e=()=>(this.pause(),this.off(gc,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(gc,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[ht]=!0,this[je].length=0,this[We]=0;let e=this;return typeof e.close=="function"&&!this[$s]&&e.close(),t?this.emit("error",t):this.emit(De),this}static get isStream(){return Jw}},s_=ct.writev,Ln=Symbol("_autoClose"),Lt=Symbol("_close"),Pi=Symbol("_ended"),he=Symbol("_fd"),yc=Symbol("_finished"),cn=Symbol("_flags"),Ec=Symbol("_flush"),qc=Symbol("_handleChunk"),Gc=Symbol("_makeBuf"),Gi=Symbol("_mode"),Xs=Symbol("_needDrain"),qr=Symbol("_onerror"),Gr=Symbol("_onopen"),bc=Symbol("_onread"),Br=Symbol("_onwrite"),Mn=Symbol("_open"),Ot=Symbol("_path"),Cn=Symbol("_pos"),zt=Symbol("_queue"),zr=Symbol("_read"),vc=Symbol("_readSize"),an=Symbol("_reading"),Di=Symbol("_remain"),Sc=Symbol("_size"),ao=Symbol("_write"),$n=Symbol("_writing"),co=Symbol("_defaultFlag"),er=Symbol("_errored"),ld=class extends ir{[er]=!1;[he];[Ot];[vc];[an]=!1;[Sc];[Di];[Ln];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[er]=!1,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Ot]=t,this[vc]=e.readSize||16*1024*1024,this[an]=!1,this[Sc]=typeof e.size=="number"?e.size:1/0,this[Di]=this[Sc],this[Ln]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[he]=="number"?this[zr]():this[Mn]()}get fd(){return this[he]}get path(){return this[Ot]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Mn](){ct.open(this[Ot],"r",(t,e)=>this[Gr](t,e))}[Gr](t,e){t?this[qr](t):(this[he]=e,this.emit("open",e),this[zr]())}[Gc](){return Buffer.allocUnsafe(Math.min(this[vc],this[Di]))}[zr](){if(!this[an]){this[an]=!0;let t=this[Gc]();if(t.length===0)return process.nextTick(()=>this[bc](null,0,t));ct.read(this[he],t,0,t.length,null,(e,n,i)=>this[bc](e,n,i))}}[bc](t,e,n){this[an]=!1,t?this[qr](t):this[qc](e,n)&&this[zr]()}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[qr](t){this[an]=!0,this[Lt](),this.emit("error",t)}[qc](t,e){let n=!1;return this[Di]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[Di]<=0)&&(n=!1,this[Lt](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[he]=="number"&&this[zr](),!1;case"error":return this[er]?!1:(this[er]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},o_=class extends ld{[Mn](){let t=!0;try{this[Gr](null,ct.openSync(this[Ot],"r")),t=!1}finally{t&&this[Lt]()}}[zr](){let t=!0;try{if(!this[an]){this[an]=!0;do{let e=this[Gc](),n=e.length===0?0:ct.readSync(this[he],e,0,e.length,null);if(!this[qc](n,e))break}while(!0);this[an]=!1}t=!1}finally{t&&this[Lt]()}}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.closeSync(t),this.emit("close")}}},So=class extends $w{readable=!1;writable=!0;[er]=!1;[$n]=!1;[Pi]=!1;[zt]=[];[Xs]=!1;[Ot];[Gi];[Ln];[he];[co];[cn];[yc]=!1;[Cn];constructor(t,e){e=e||{},super(e),this[Ot]=t,this[he]=typeof e.fd=="number"?e.fd:void 0,this[Gi]=e.mode===void 0?438:e.mode,this[Cn]=typeof e.start=="number"?e.start:void 0,this[Ln]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Cn]!==void 0?"r+":"w";this[co]=e.flags===void 0,this[cn]=e.flags===void 0?n:e.flags,this[he]===void 0&&this[Mn]()}emit(t,...e){if(t==="error"){if(this[er])return!1;this[er]=!0}return super.emit(t,...e)}get fd(){return this[he]}get path(){return this[Ot]}[qr](t){this[Lt](),this[$n]=!0,this.emit("error",t)}[Mn](){ct.open(this[Ot],this[cn],this[Gi],(t,e)=>this[Gr](t,e))}[Gr](t,e){this[co]&&this[cn]==="r+"&&t&&t.code==="ENOENT"?(this[cn]="w",this[Mn]()):t?this[qr](t):(this[he]=e,this.emit("open",e),this[$n]||this[Ec]())}end(t,e){return t&&this.write(t,e),this[Pi]=!0,!this[$n]&&!this[zt].length&&typeof this[he]=="number"&&this[Br](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Pi]?(this.emit("error",new Error("write() after end()")),!1):this[he]===void 0||this[$n]||this[zt].length?(this[zt].push(t),this[Xs]=!0,!1):(this[$n]=!0,this[ao](t),!0)}[ao](t){ct.write(this[he],t,0,t.length,this[Cn],(e,n)=>this[Br](e,n))}[Br](t,e){t?this[qr](t):(this[Cn]!==void 0&&typeof e=="number"&&(this[Cn]+=e),this[zt].length?this[Ec]():(this[$n]=!1,this[Pi]&&!this[yc]?(this[yc]=!0,this[Lt](),this.emit("finish")):this[Xs]&&(this[Xs]=!1,this.emit("drain"))))}[Ec](){if(this[zt].length===0)this[Pi]&&this[Br](null,0);else if(this[zt].length===1)this[ao](this[zt].pop());else{let t=this[zt];this[zt]=[],s_(this[he],t,this[Cn],(e,n)=>this[Br](e,n))}}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Nu=class extends So{[Mn](){let t;if(this[co]&&this[cn]==="r+")try{t=ct.openSync(this[Ot],this[cn],this[Gi])}catch(e){if(e?.code==="ENOENT")return this[cn]="w",this[Mn]();throw e}else t=ct.openSync(this[Ot],this[cn],this[Gi]);this[Gr](null,t)}[Lt](){if(this[Ln]&&typeof this[he]=="number"){let t=this[he];this[he]=void 0,ct.closeSync(t),this.emit("close")}}[ao](t){let e=!0;try{this[Br](null,ct.writeSync(this[he],t,0,t.length,this[Cn])),e=!1}finally{if(e)try{this[Lt]()}catch{}}}},d_=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"]]),l_=t=>!!t.sync&&!!t.file,f_=t=>!t.sync&&!!t.file,u_=t=>!!t.sync&&!t.file,h_=t=>!t.sync&&!t.file,x_=t=>!!t.file,p_=t=>d_.get(t)||t,fd=(t={})=>{if(!t)return{};let e={};for(let[n,i]of Object.entries(t)){let o=p_(n);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Yi=(t,e,n,i,o)=>Object.assign((a=[],d,f)=>{Array.isArray(a)&&(d=a,a={}),typeof d=="function"&&(f=d,d=void 0),d=d?Array.from(d):[];let u=fd(a);if(o?.(u,d),l_(u)){if(typeof f=="function")throw new TypeError("callback not supported for sync tar functions");return t(u,d)}else if(f_(u)){let x=e(u,d);return f?x.then(()=>f(),f):x}else if(u_(u)){if(typeof f=="function")throw new TypeError("callback not supported for sync tar functions");return n(u,d)}else if(h_(u)){if(typeof f=="function")throw new TypeError("callback only supported with file option");return i(u,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:i,validate:o}),w_=m_.constants||{ZLIB_VERNUM:4736},jt=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},w_)),__=tr.concat,iu=Object.getOwnPropertyDescriptor(tr,"concat"),y_=t=>t,Ic=iu?.writable===!0||iu?.set!==void 0?t=>{tr.concat=t?y_:__}:t=>{},nr=Symbol("_superWrite"),Ys=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Ac=Symbol("flushFlag"),ud=class extends ir{#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 ru[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new ru[e](t)}catch(n){throw new Ys(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 Ys(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return jc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(tr.alloc(0),{[Ac]: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}[nr](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=tr.from(t,e)),this.#e)return;jc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let a=this.#t.close;this.#t.close=()=>{},Ic(!0);let d;try{let u=typeof t[Ac]=="number"?t[Ac]:this.#r;d=this.#t._processChunk(t,u),Ic(!1)}catch(u){Ic(!1),this.#o(new Ys(u,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",u=>this.#o(new Ys(u,this.write)));let f;if(d)if(Array.isArray(d)&&d.length>0){let u=d[0];f=this[nr](tr.from(u));for(let x=1;x<d.length;x++)f=this[nr](d[x])}else f=this[nr](tr.from(d));return n&&n(),f}},Bu=class extends ud{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||jt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||jt.Z_FINISH,t.fullFlushFlag=jt.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(jt.Z_SYNC_FLUSH),jc(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)}}}},E_=class extends Bu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[nr](t){return this.#e?(this.#e=!1,t[9]=255,super[nr](t)):super[nr](t)}},b_=class extends Bu{constructor(t){super(t,"Unzip")}},zu=class extends ud{constructor(t,e){t=t||{},t.flush=t.flush||jt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||jt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=jt.BROTLI_OPERATION_FLUSH,super(t,e)}},v_=class extends zu{constructor(t){super(t,"BrotliCompress")}},S_=class extends zu{constructor(t){super(t,"BrotliDecompress")}},Uu=class extends ud{constructor(t,e){t=t||{},t.flush=t.flush||jt.ZSTD_e_continue,t.finishFlush=t.finishFlush||jt.ZSTD_e_end,t.fullFlushFlag=jt.ZSTD_e_flush,super(t,e)}},I_=class extends Uu{constructor(t){super(t,"ZstdCompress")}},A_=class extends Uu{constructor(t){super(t,"ZstdDecompress")}},k_=(t,e)=>{if(Number.isSafeInteger(t))t<0?C_(t,e):T_(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},T_=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},C_=(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]=Hu(o):o===0?e[i-1]=0:(n=!0,e[i-1]=qu(o))}},R_=t=>{let e=t[0],n=e===128?D_(t.subarray(1,t.length)):e===255?P_(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},P_=t=>{for(var e=t.length,n=0,i=!1,o=e-1;o>-1;o--){var a=Number(t[o]),d;i?d=Hu(a):a===0?d=a:(i=!0,d=qu(a)),d!==0&&(n-=d*Math.pow(256,e-o-1))}return n},D_=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},Hu=t=>(255^t)&255,qu=t=>(255^t)+1&255,O_={};Kw(O_,{code:()=>hd,isCode:()=>lo,isName:()=>L_,name:()=>Io,normalFsTypes:()=>Gu});var lo=t=>Io.has(t),L_=t=>hd.has(t),Gu=new Set(["0","","1","2","3","4","5","6","7","D"]),Io=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),hd=new Map(Array.from(Io).map(t=>[t[1],t[0]])),M_=t=>t===void 0||t<0?void 0:t,rr=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=Vn(t,e+156,1),a=Gu.has(o),d=a?n:void 0,f=a?i:void 0;if(this.path=d?.path??Vn(t,e,100),this.mode=d?.mode??f?.mode??Rn(t,e+100,8),this.uid=d?.uid??f?.uid??Rn(t,e+108,8),this.gid=d?.gid??f?.gid??Rn(t,e+116,8),this.size=M_(d?.size??f?.size??Rn(t,e+124,12)),this.mtime=d?.mtime??f?.mtime??kc(t,e+136,12),this.cksum=Rn(t,e+148,12),f&&this.#n(f,!0),d&&this.#n(d),lo(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Vn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??f?.uname??Vn(t,e+265,32),this.gname=d?.gname??f?.gname??Vn(t,e+297,32),this.devmaj=d?.devmaj??f?.devmaj??Rn(t,e+329,8)??0,this.devmin=d?.devmin??f?.devmin??Rn(t,e+337,8)??0,t[e+475]!==0){let x=Vn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Vn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=n?.atime??i?.atime??kc(t,e+476,12),this.ctime=n?.ctime??i?.ctime??kc(t,e+488,12)}let u=256;for(let x=e;x<e+148;x++)u+=t[x];for(let x=e+156;x<e+512;x++)u+=t[x];this.cksumValid=u===this.cksum,this.cksum===void 0&&u===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=N_(this.path||"",n),o=i[0],a=i[1];this.needPax=!!i[2],this.needPax=Jn(t,e,100,o)||this.needPax,this.needPax=Pn(t,e+100,8,this.mode)||this.needPax,this.needPax=Pn(t,e+108,8,this.uid)||this.needPax,this.needPax=Pn(t,e+116,8,this.gid)||this.needPax,this.needPax=Pn(t,e+124,12,this.size)||this.needPax,this.needPax=Tc(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=Pn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Pn(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=Tc(t,e+476,12,this.atime)||this.needPax,this.needPax=Tc(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let f=e;f<e+148;f++)d+=t[f];for(let f=e+156;f<e+512;f++)d+=t[f];return this.cksum=d,Pn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Io.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(hd.get(t));if(lo(e)||e==="Unsupported")this.#e=e;else if(lo(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},N_=(t,e)=>{let n=t,i="",o,a=Or.parse(t).root||".";if(Buffer.byteLength(n)<100)o=[n,i,!1];else{i=Or.dirname(n),n=Or.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=Or.join(Or.basename(i),n),i=Or.dirname(i));while(i!==a&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Vn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),kc=(t,e,n)=>F_(Rn(t,e,n)),F_=t=>t===void 0?void 0:new Date(t*1e3),Rn=(t,e,n)=>Number(t[e])&128?R_(t.subarray(e,e+n)):z_(t,e,n),B_=t=>isNaN(t)?void 0:t,z_=(t,e,n)=>B_(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),U_={12:8589934591,8:2097151},Pn=(t,e,n,i)=>i===void 0?!1:i>U_[n]||i<0?(k_(i,t.subarray(e,e+n)),!0):(H_(t,e,n,i),!1),H_=(t,e,n,i)=>t.write(q_(i,n),e,n,"ascii"),q_=(t,e)=>G_(Math.floor(t).toString(8),e),G_=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Tc=(t,e,n,i)=>i===void 0?!1:Pn(t,e,n,i.getTime()/1e3),j_=new Array(156).join("\0"),Jn=(t,e,n,i)=>i===void 0?!1:(t.write(i+j_,e,n,"utf8"),i.length!==Buffer.byteLength(i)||i.length>n),_o=class ju{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 rr({path:("PaxHeader/"+W_(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 ju(K_($_(e),n),i)}},K_=(t,e)=>e?Object.assign({},e,t):t,$_=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(V_,Object.create(null)),V_=(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 f=+d;f>=0&&(t[a]=f);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":t[a]=+d;break}return t},J_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,te=J_!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),Z_=class extends ir{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=te(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?te(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=te(t.path)),t.linkpath&&(t.linkpath=te(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,i])=>!(i==null||n==="path"&&e))))}},Ao=(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))},X_=1024*1024,Wc=Buffer.from([31,139]),Kc=Buffer.from([40,181,47,253]),Y_=Math.max(Wc.length,Kc.length),yt=Symbol("state"),Zn=Symbol("writeEntry"),sn=Symbol("readEntry"),Cc=Symbol("nextEntry"),su=Symbol("processEntry"),Ut=Symbol("extendedHeader"),Oi=Symbol("globalExtendedHeader"),An=Symbol("meta"),ou=Symbol("emitMeta"),_e=Symbol("buffer"),on=Symbol("queue"),kn=Symbol("ended"),Rc=Symbol("emittedEnd"),Xn=Symbol("emit"),Ce=Symbol("unzip"),Qs=Symbol("consumeChunk"),eo=Symbol("consumeChunkSub"),Pc=Symbol("consumeBody"),au=Symbol("consumeMeta"),cu=Symbol("consumeHeader"),Li=Symbol("consuming"),Dc=Symbol("bufferConcat"),to=Symbol("maybeEnd"),Lr=Symbol("writing"),Ht=Symbol("aborted"),no=Symbol("onDone"),Yn=Symbol("sawValidEntry"),ro=Symbol("sawNullBlock"),io=Symbol("sawEOF"),du=Symbol("closeStream"),Q_=1e3,Mi=Symbol("compressedBytesRead"),Oc=Symbol("decompressedBytesRead"),lu=Symbol("checkDecompressionRatio"),ey=()=>!0,Xi=class extends g_{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[on]=[];[_e];[sn];[Zn];[yt]="begin";[An]="";[Ut];[Oi];[kn]=!1;[Ce];[Ht]=!1;[Yn];[ro]=!1;[io]=!1;[Lr]=!1;[Li]=!1;[Rc]=!1;[Mi]=0;[Oc]=0;constructor(t={}){super(),this.file=t.file||"",this.on(no,()=>{(this[yt]==="begin"||this[Yn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(no,t.ondone):this.on(no,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:Q_,this.maxMetaEntrySize=t.maxMetaEntrySize||X_,this.filter=typeof t.filter=="function"?t.filter:ey;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[du]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){Ao(this,t,e,n)}[cu](t,e){this[Yn]===void 0&&(this[Yn]=!1);let n;try{n=new rr(t,e,this[Ut],this[Oi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(n.nullBlock)this[ro]?(this[io]=!0,this[yt]==="begin"&&(this[yt]="header"),this[Xn]("eof")):(this[ro]=!0,this[Xn]("nullBlock"));else if(this[ro]=!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[Zn]=new Z_(n,this[Ut],this[Oi]);if(!this[Yn])if(o.remain){let a=()=>{o.invalid||(this[Yn]=!0)};o.on("end",a)}else this[Yn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Xn]("ignoredEntry",o),this[yt]="ignore",o.resume()):o.size>0&&(this[An]="",o.on("data",a=>this[An]+=a),this[yt]="meta"):(this[Ut]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Xn]("ignoredEntry",o),this[yt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[yt]="body":(this[yt]="header",o.end()),this[sn]?this[on].push(o):(this[on].push(o),this[Cc]())))}}}[du](){queueMicrotask(()=>this.emit("close"))}[su](t){let e=!0;if(!t)this[sn]=void 0,e=!1;else if(Array.isArray(t)){let[n,...i]=t;this.emit(n,...i)}else this[sn]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Cc]()),e=!1);return e}[Cc](){do;while(this[su](this[on].shift()));if(this[on].length===0){let t=this[sn];!t||t.flowing||t.size===t.remain?this[Lr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Pc](t,e){let n=this[Zn];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[yt]="header",this[Zn]=void 0,n.end()),o.length}[au](t,e){let n=this[Zn],i=this[Pc](t,e);return!this[Zn]&&n&&this[ou](n),i}[Xn](t,e,n){this[on].length===0&&!this[sn]?this.emit(t,e,n):this[on].push([t,e,n])}[ou](t){switch(this[Xn]("meta",this[An]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ut]=_o.parse(this[An],this[Ut],!1);break;case"GlobalExtendedHeader":this[Oi]=_o.parse(this[An],this[Oi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ut]??Object.create(null);this[Ut]=e,e.path=this[An].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ut]||Object.create(null);this[Ut]=e,e.linkpath=this[An].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[Ht]){if(this[Ce]){let e=this[Ce];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[Ht]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[lu](t){this[Oc]+=t.length;let e=this[Oc]/this[Mi];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[Ht])return n?.(),!1;if((this[Ce]===void 0||this.brotli===void 0&&this[Ce]===!1)&&t){if(this[_e]&&(t=Buffer.concat([this[_e],t]),this[_e]=void 0),t.length<Y_)return this[_e]=t,n?.(),!0;for(let d=0;this[Ce]===void 0&&d<Wc.length;d++)t[d]!==Wc[d]&&(this[Ce]=!1);let o=!1;if(this[Ce]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<Kc.length;d++)if(t[d]!==Kc[d]){o=!1;break}}let a=this.brotli===void 0&&!o;if(this[Ce]===!1&&a)if(t.length<512)if(this[kn])this.brotli=!0;else return this[_e]=t,n?.(),!0;else try{new rr(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Ce]===void 0||this[Ce]===!1&&(this.brotli||o)){let d=this[kn];this[kn]=!1,this[Ce]=this[Ce]===void 0?new b_({}):o?new A_({}):new S_({}),this[Ce].on("data",u=>{this[lu](u)&&this[Qs](u)}),this[Ce].on("error",u=>{this[Ht]||this.abort(u)}),this[Ce].on("end",()=>{this[kn]=!0,this[Qs]()}),this[Lr]=!0,this[Mi]+=t.length;let f=!!this[Ce][d?"end":"write"](t);return this[Lr]=!1,n?.(),f}}this[Lr]=!0,this[Ce]?(this[Mi]+=t.length,this[Ce].write(t)):this[Qs](t),this[Lr]=!1;let i=this[on].length>0?!1:this[sn]?this[sn].flowing:!0;return!i&&this[on].length===0&&this[sn]?.once("drain",()=>this.emit("drain")),n?.(),i}[Dc](t){t&&!this[Ht]&&(this[_e]=this[_e]?Buffer.concat([this[_e],t]):t)}[to](){if(this[kn]&&!this[Rc]&&!this[Ht]&&!this[Li]){this[Rc]=!0;let t=this[Zn];if(t?.blockRemain){let e=this[_e]?this[_e].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[_e]&&t.write(this[_e]),t.end()}this[Xn](no)}}[Qs](t){if(this[Li]&&t)this[Dc](t);else if(!t&&!this[_e])this[to]();else if(t){if(this[Li]=!0,this[_e]){this[Dc](t);let e=this[_e];this[_e]=void 0,this[eo](e)}else this[eo](t);for(;this[_e]&&this[_e]?.length>=512&&!this[Ht]&&!this[io];){let e=this[_e];this[_e]=void 0,this[eo](e)}this[Li]=!1}(!this[_e]||this[kn])&&this[to]()}[eo](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ht]&&!this[io];)switch(this[yt]){case"begin":case"header":this[cu](t,e),e+=512;break;case"ignore":case"body":e+=this[Pc](t,e);break;case"meta":e+=this[au](t,e);break;default:throw new Error("invalid state: "+this[yt])}e<n&&(this[_e]=this[_e]?Buffer.concat([t.subarray(e),this[_e]]):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[Ht]||(this[Ce]?(t&&(this[Mi]+=t.length,this[Ce].write(t)),this[Ce].end()):(this[kn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[to]())),this}},ji=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)},ty=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Wu=(t,e)=>{let n=new Map(e.map(a=>[ji(a),!0])),i=t.filter,o=(a,d="")=>{let f=d||c_(a).root||".",u;if(a===f)u=!1;else{let x=n.get(a);u=x!==void 0?x:o(a_(a),f)}return n.set(a,u),u};t.filter=i?(a,d)=>i(a,d)&&o(ji(a)):a=>o(ji(a))},ny=t=>{let e=new Xi(t),n=t.file,i;try{i=Ur.openSync(n,"r");let o=Ur.fstatSync(i),a=t.maxReadSize||16*1024*1024;if(o.size<a){let d=Buffer.allocUnsafe(o.size),f=Ur.readSync(i,d,0,o.size,0);e.end(f===d.byteLength?d:d.subarray(0,f))}else{let d=0,f=Buffer.allocUnsafe(a);for(;d<o.size;){let u=Ur.readSync(i,f,0,a,d);if(u===0)break;d+=u,e.write(f.subarray(0,u))}e.end()}}finally{if(typeof i=="number")try{Ur.closeSync(i)}catch{}}},ry=(t,e)=>{let n=new Xi(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("end",a),Ur.stat(o,(f,u)=>{if(f)d(f);else{let x=new ld(o,{readSize:i,size:u.size});x.on("error",d),x.pipe(n)}})})},jr=Yi(ny,ry,t=>new Xi(t),t=>new Xi(t),(t,e)=>{e?.length&&Wu(t,e),t.noResume||ty(t)}),Ku=(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:sy,parse:uu}=iy,xd=t=>{let e="",n=uu(t);for(;sy(t)||n.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(i.length),e+=i,n=uu(t)}return[e,t]},ko=["|","<",">","?",":"],pd=ko.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),oy=new Map(ko.map((t,e)=>[t,pd[e]])),ay=new Map(pd.map((t,e)=>[t,ko[e]])),hu=t=>ko.reduce((e,n)=>e.split(n).join(oy.get(n)),t),cy=t=>pd.reduce((e,n)=>e.split(n).join(ay.get(n)),t),$u=(t,e)=>e?(t=te(t).replace(/^\.(\/|$)/,""),ji(e)+"/"+t):te(t),dy=16*1024*1024,xu=Symbol("process"),pu=Symbol("file"),gu=Symbol("directory"),$c=Symbol("symlink"),mu=Symbol("hardlink"),Ni=Symbol("header"),fo=Symbol("read"),Vc=Symbol("lstat"),uo=Symbol("onlstat"),Jc=Symbol("onread"),Zc=Symbol("onreadlink"),Xc=Symbol("openfile"),Yc=Symbol("onopenfile"),Dn=Symbol("close"),Eo=Symbol("mode"),Qc=Symbol("awaitDrain"),Lc=Symbol("ondrain"),Gt=Symbol("prefix"),Vu=class extends ir{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=fd(e);super(),this.path=te(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||dy,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=te(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?te(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]=xd(this.path);a&&typeof d=="string"&&(this.path=d,i=a)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=cy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=te(n.absolute||fu.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[uo](o):this[Vc]()}warn(t,e,n={}){return Ao(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Vc](){qt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[uo](e)})}[uo](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=uy(t),this.emit("stat",t),this[xu]()}[xu](){switch(this.type){case"File":return this[pu]();case"Directory":return this[gu]();case"SymbolicLink":return this[$c]();default:return this.end()}}[Eo](t){return Ku(t,this.type==="Directory",this.portable)}[Gt](t){return $u(t,this.prefix)}[Ni](){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 rr({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,mode:this[Eo](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new _o({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[gu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ni](),this.end()}[$c](){qt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Zc](e)})}[Zc](t){this.linkpath=te(t),this[Ni](),this.end()}[mu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=te(fu.relative(this.cwd,t)),this.stat.size=0,this[Ni](),this.end()}[pu](){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[mu](e);this.linkCache.set(t,this.absolute)}if(this[Ni](),this.stat.size===0)return this.end();this[Xc]()}[Xc](){qt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Yc](e)})}[Yc](t){if(this.fd=t,this.#e)return this[Dn]();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[fo]()}[fo](){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");qt.read(t,e,n,i,o,(a,d)=>{if(a)return this[Dn](()=>this.emit("error",a));this[Jc](d)})}[Dn](t=()=>{}){this.fd!==void 0&&qt.close(this.fd,t)}[Jc](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Dn](()=>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[Dn](()=>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[Lc]():this[Qc](()=>this[Lc]())}[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)}[Lc](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Dn](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[fo]()}},ly=class extends Vu{sync=!0;[Vc](){this[uo](qt.lstatSync(this.absolute))}[$c](){this[Zc](qt.readlinkSync(this.absolute))}[Xc](){this[Yc](qt.openSync(this.absolute,"r"))}[fo](){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=qt.readSync(e,n,i,o,a);this[Jc](d),t=!1}finally{if(t)try{this[Dn](()=>{})}catch{}}}[Qc](t){t()}[Dn](t=()=>{}){this.fd!==void 0&&qt.closeSync(this.fd),t()}},fy=class extends ir{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 Ao(this,t,e,n)}constructor(t,e={}){let n=fd(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=te(t.path),this.mode=t.mode!==void 0?this[Eo](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0: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?te(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let o=!1;if(!this.preservePaths){let[d,f]=xd(this.path);d&&typeof f=="string"&&(this.path=f,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new rr({path:this[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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 _o({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[Gt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Gt](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)}[Gt](t){return $u(t,this.prefix)}[Eo](t){return Ku(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}},uy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",hy=class Hr{tail;head;length=0;static create(e=[]){return new Hr(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++)py(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 Hr;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 Hr;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 Hr;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 Hr;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=xy(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 xy(t,e,n){let i=e,o=e?e.next:t.head,a=new gd(n,i,o,t);return a.next===void 0&&(t.tail=a),a.prev===void 0&&(t.head=a),t.length++,a}function py(t,e){t.tail=new gd(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function gy(t,e){t.head=new gd(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var gd=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}},_u=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},yu=Buffer.alloc(1024),ho=Symbol("onStat"),Fi=Symbol("ended"),Pt=Symbol("queue"),Bi=Symbol("pendingLinks"),Tn=Symbol("current"),Qn=Symbol("process"),zi=Symbol("processing"),so=Symbol("processJob"),Dt=Symbol("jobs"),Mc=Symbol("jobDone"),xo=Symbol("addFSEntry"),Eu=Symbol("addTarEntry"),ed=Symbol("stat"),td=Symbol("readdir"),po=Symbol("onreaddir"),go=Symbol("pipe"),bu=Symbol("entry"),Nc=Symbol("entryOpt"),mo=Symbol("writeEntryClass"),Ju=Symbol("write"),Fc=Symbol("ondrain"),To=class extends ir{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[mo];onWriteEntry;[Pt];[Bi]=new Map;[Dt]=0;[zi]=!1;[Fi]=!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=te(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[mo]=Vu,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 E_(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new v_(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new I_(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[Fc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Fc]);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[Pt]=new hy,this[Dt]=0,this.jobs=Number(t.jobs)||4,this[zi]=!1,this[Fi]=!1}[Ju](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[Fi]=!0,this[Qn](),n&&n(),this}write(t){if(this[Fi])throw new Error("write after end");return typeof t=="string"?this[xo](t):this[Eu](t),this.flowing}[Eu](t){let e=te(wu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new _u(t.path,e);n.entry=new fy(t,this[Nc](n)),n.entry.on("end",()=>this[Mc](n)),this[Dt]+=1,this[Pt].push(n)}this[Qn]()}[xo](t){let e=te(wu.resolve(this.cwd,t));this[Pt].push(new _u(t,e)),this[Qn]()}[ed](t){t.pending=!0,this[Dt]+=1;let e=this.follow?"stat":"lstat";yo[e](t.absolute,(n,i)=>{t.pending=!1,this[Dt]-=1,n?this.emit("error",n):this[ho](t,i)})}[ho](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[Tn])this[so](t);else{let n=`${e.dev}:${e.ino}`,i=this[Bi].get(n);i?i.push(t):this[Bi].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[Qn]()}[td](t){t.pending=!0,this[Dt]+=1,yo.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[Dt]-=1,e)return this.emit("error",e);this[po](t,n)})}[po](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Qn]()}[Qn](){if(!this[zi]){this[zi]=!0;for(let t=this[Pt].head;t&&this[Dt]<this.jobs;t=t.next)if(this[so](t.value),t.value.ignore){let e=t.next;this[Pt].removeNode(t),t.next=e}this[zi]=!1,this[Fi]&&this[Pt].length===0&&this[Dt]===0&&(this.zip?this.zip.end(yu):(super.write(yu),super.end()))}}get[Tn](){return this[Pt]&&this[Pt].head&&this[Pt].head.value}[Mc](t){this[Pt].shift(),this[Dt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,i=this[Bi].get(n);if(i){this[Bi].delete(n);for(let o of i)o.pending=!1,this[so](o)}}this[Qn]()}[so](t){if(t.pending&&t.pendingLink&&t===this[Tn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Tn]&&!t.piped&&this[go](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[ho](t,e):this[ed](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[po](t,e):this[td](t),!t.readdir)return}if(t.entry=this[bu](t),!t.entry){t.ignore=!0;return}t===this[Tn]&&!t.piped&&this[go](t)}}}[Nc](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}}[bu](t){this[Dt]+=1;try{return new this[mo](t.path,this[Nc](t)).on("end",()=>this[Mc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Fc](){this[Tn]&&this[Tn].entry&&this[Tn].entry.resume()}[go](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[xo](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={}){Ao(this,t,e,n)}},md=class extends To{sync=!0;constructor(t){super(t),this[mo]=ly}pause(){}resume(){}[ed](t){let e=this.follow?"statSync":"lstatSync";this[ho](t,yo[e](t.absolute))}[td](t){this[po](t,yo.readdirSync(t.absolute))}[go](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,a=o==="./"?"":o.replace(/\/*$/,"/");this[xo](a+i)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",i=>{n.write(i)}):e.on("data",i=>{super[Ju](i)})}},my=(t,e)=>{let n=new md(t),i=new Nu(t.file,{mode:t.mode||438});n.pipe(i),Zu(n,e)},wy=(t,e)=>{let n=new To(t),i=new So(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 Xu(n,e).catch(a=>n.emit("error",a)),o},Zu=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?jr({file:Fu.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Xu=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await jr({file:Fu.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(n);t.end()},_y=(t,e)=>{let n=new md(t);return Zu(n,e),n},yy=(t,e)=>{let n=new To(t);return Xu(n,e).catch(i=>n.emit("error",i)),n},GT=Yi(my,wy,_y,yy,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),by=process.env.__FAKE_PLATFORM__||process.platform,t0=by==="win32",{O_CREAT:n0,O_NOFOLLOW:vu,O_TRUNC:r0,O_WRONLY:i0}=e0.constants,s0=Number(process.env.__FAKE_FS_O_FILENAME__)||e0.constants.UV_FS_O_FILEMAP||0,vy=t0&&!!s0,Sy=512*1024,Iy=s0|r0|n0|i0,Su=!t0&&typeof vu=="number"?vu|r0|n0|i0:null,o0=Su!==null?()=>Su:vy?t=>t<Sy?Iy:"w":()=>"w",nd=(t,e,n)=>{try{return Co.lchownSync(t,e,n)}catch(i){if(i?.code!=="ENOENT")throw i}},bo=(t,e,n,i)=>{Co.lchown(t,e,n,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},Ay=(t,e,n,i,o)=>{if(e.isDirectory())a0(Wi.resolve(t,e.name),n,i,a=>{if(a)return o(a);let d=Wi.resolve(t,e.name);bo(d,n,i,o)});else{let a=Wi.resolve(t,e.name);bo(a,n,i,o)}},a0=(t,e,n,i)=>{Co.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 bo(t,e,n,i);let d=a.length,f=null,u=x=>{if(!f){if(x)return i(f=x);if(--d===0)return bo(t,e,n,i)}};for(let x of a)Ay(t,x,e,n,u)})},ky=(t,e,n,i)=>{e.isDirectory()&&c0(Wi.resolve(t,e.name),n,i),nd(Wi.resolve(t,e.name),n,i)},c0=(t,e,n)=>{let i;try{i=Co.readdirSync(t,{withFileTypes:!0})}catch(o){let a=o;if(a?.code==="ENOENT")return;if(a?.code==="ENOTDIR"||a?.code==="ENOTSUP")return nd(t,e,n);throw a}for(let o of i)ky(t,o,e,n);return nd(t,e,n)},d0=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},Ro=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},Cy=(t,e)=>{pt.stat(t,(n,i)=>{(n||!i.isDirectory())&&(n=new d0(t,n?.code||"ENOTDIR")),e(n)})},Ry=(t,e,n)=>{t=te(t);let i=e.umask??18,o=e.mode|448,a=(o&i)!==0,d=e.uid,f=e.gid,u=typeof d=="number"&&typeof f=="number"&&(d!==e.processUid||f!==e.processGid),x=e.preserve,p=e.unlink,w=te(e.cwd),b=(v,I)=>{v?n(v):I&&u?a0(I,d,f,A=>b(A)):a?pt.chmod(t,o,n):n()};if(t===w)return Cy(t,b);if(x)return Ty.mkdir(t,{mode:o,recursive:!0}).then(v=>b(null,v??void 0),b);let _=te(vo.relative(w,t)).split("/");rd(w,_,o,p,w,void 0,b)},rd=(t,e,n,i,o,a,d)=>{if(e.length===0)return d(null,a);let f=e.shift(),u=te(vo.resolve(t+"/"+f));pt.mkdir(u,n,l0(u,e,n,i,o,a,d))},l0=(t,e,n,i,o,a,d)=>f=>{f?pt.lstat(t,(u,x)=>{if(u)u.path=u.path&&te(u.path),d(u);else if(x.isDirectory())rd(t,e,n,i,o,a,d);else if(i)pt.unlink(t,p=>{if(p)return d(p);pt.mkdir(t,n,l0(t,e,n,i,o,a,d))});else{if(x.isSymbolicLink())return d(new Ro(t,t+"/"+e.join("/")));d(f)}}):(a=a||t,rd(t,e,n,i,o,a,d))},Py=t=>{let e=!1,n;try{e=pt.statSync(t).isDirectory()}catch(i){n=i?.code}finally{if(!e)throw new d0(t,n??"ENOTDIR")}},Dy=(t,e)=>{t=te(t);let n=e.umask??18,i=e.mode|448,o=(i&n)!==0,a=e.uid,d=e.gid,f=typeof a=="number"&&typeof d=="number"&&(a!==e.processUid||d!==e.processGid),u=e.preserve,x=e.unlink,p=te(e.cwd),w=v=>{v&&f&&c0(v,a,d),o&&pt.chmodSync(t,i)};if(t===p)return Py(p),w();if(u)return w(pt.mkdirSync(t,{mode:i,recursive:!0})??void 0);let b=te(vo.relative(p,t)).split("/"),_;for(let v=b.shift(),I=p;v&&(I+="/"+v);v=b.shift()){I=te(vo.resolve(I));try{pt.mkdirSync(I,i),_=_||I}catch{let A=pt.lstatSync(I);if(A.isDirectory())continue;if(x){pt.unlinkSync(I),pt.mkdirSync(I,i),_=_||I;continue}else if(A.isSymbolicLink())return new Ro(I,I+"/"+b.join("/"))}}return w(_)},Bc=Object.create(null),Iu=1e4,Mr=new Set,Oy=t=>{Mr.has(t)?Mr.delete(t):Bc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Mr.add(t);let e=Bc[t],n=Mr.size-Iu;if(n>Iu/10){for(let i of Mr)if(Mr.delete(i),delete Bc[i],--n<=0)break}return e},Ly=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,My=Ly==="win32",Ny=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let i=e.at(-1);return i!==void 0&&(n=f0(i,n)),e.push(n||"/"),e},[]),Fy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=My?["win32 parallelization disabled"]:t.map(i=>ji(f0(Oy(i))));let n=new Set(t.map(i=>Ny(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 f=d[1];if(!f){this.#e.delete(a);continue}if(d.shift(),typeof f=="function")o.add(f);else for(let u of f)o.add(u)}for(let a of i){let d=this.#e.get(a),f=d?.[0];if(!(!d||!(f instanceof Set)))if(f.size===1&&d.length===1){this.#e.delete(a);continue}else if(f.size===1){d.shift();let u=d[0];typeof u=="function"&&o.add(u)}else f.delete(t)}return this.#r.delete(t),o.forEach(a=>this.#i(a)),!0}},By=()=>process.umask(),Au=Symbol("onEntry"),id=Symbol("checkFs"),ku=Symbol("checkFs2"),sd=Symbol("isReusable"),Et=Symbol("makeFs"),od=Symbol("file"),ad=Symbol("directory"),wo=Symbol("link"),Tu=Symbol("symlink"),Cu=Symbol("hardlink"),qi=Symbol("ensureNoSymlink"),Ru=Symbol("unsupported"),Pu=Symbol("checkPath"),zc=Symbol("stripAbsolutePath"),On=Symbol("mkdir"),Ke=Symbol("onError"),oo=Symbol("pending"),Du=Symbol("pend"),Nr=Symbol("unpend"),Uc=Symbol("ended"),Hc=Symbol("maybeClose"),cd=Symbol("skip"),Ki=Symbol("doChown"),$i=Symbol("uid"),Vi=Symbol("gid"),Ji=Symbol("checkedCwd"),zy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Zi=zy==="win32",Uy=1024,Hy=(t,e)=>{if(!Zi)return se.unlink(t,e);let n=t+".DELETE."+Qu(16).toString("hex");se.rename(t,n,i=>{if(i)return e(i);se.unlink(n,e)})},qy=t=>{if(!Zi)return se.unlinkSync(t);let e=t+".DELETE."+Qu(16).toString("hex");se.renameSync(t,e),se.unlinkSync(e)},Ou=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,wd=class extends Xi{[Uc]=!1;[Ji]=!1;[oo]=0;reservations=new Fy;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[Uc]=!0,this[Hc]()},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:Uy,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=te(Ue.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:By():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[Au](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[Hc](){this[Uc]&&this[oo]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[zc](t,e){let n=t[e],{type:i}=t;if(!n||this.preservePaths)return!0;let[o,a]=xd(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 f=Ue.posix.dirname(t.path),u=Ue.posix.normalize(Ue.posix.join(f,d.join("/")));if(u.startsWith("../")||u==="..")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}[Pu](t){let e=te(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let i=te(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[zc](t,"path")||!this[zc](t,"linkpath"))return!1;if(t.absolute=Ue.isAbsolute(t.path)?te(Ue.resolve(t.path)):te(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:te(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+hu(String(t.absolute).slice(i.length));let{root:o}=Ue.win32.parse(t.path);t.path=o+hu(t.path.slice(o.length))}return!0}[Au](t){if(!this[Pu](t))return t.resume();switch(Ey.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[id](t);default:return this[Ru](t)}}[Ke](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Nr](),e.resume())}[On](t,e,n){Ry(te(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)}[Ki](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}[$i](t){return Ou(this.uid,t.uid,this.processUid)}[Vi](t){return Ou(this.gid,t.gid,this.processGid)}[od](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new So(String(t.absolute),{flags:o0(t.size),mode:n,autoClose:!1});i.on("error",f=>{i.fd&&se.close(i.fd,()=>{}),i.write=()=>!0,this[Ke](f,t),e()});let o=1,a=f=>{if(f){i.fd&&se.close(i.fd,()=>{}),this[Ke](f,t),e();return}--o===0&&i.fd!==void 0&&se.close(i.fd,u=>{u?this[Ke](u,t):this[Nr](),e()})};i.on("finish",()=>{let f=String(t.absolute),u=i.fd;if(typeof u=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;se.futimes(u,x,p,w=>w?se.utimes(f,x,p,b=>a(b&&w)):a())}if(typeof u=="number"&&this[Ki](t)){o++;let x=this[$i](t),p=this[Vi](t);typeof x=="number"&&typeof p=="number"&&se.fchown(u,x,p,w=>w?se.chown(f,x,p,b=>a(b&&w)):a())}a()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",f=>{this[Ke](f,t),e()}),t.pipe(d)),d.pipe(i)}[ad](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[On](String(t.absolute),n,i=>{if(i){this[Ke](i,t),e();return}let o=1,a=()=>{--o===0&&(e(),this[Nr](),t.resume())};t.mtime&&!this.noMtime&&(o++,se.utimes(String(t.absolute),t.atime||new Date,t.mtime,a)),this[Ki](t)&&(o++,se.chown(String(t.absolute),Number(this[$i](t)),Number(this[Vi](t)),a)),a()})}[Ru](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Tu](t,e){let n=te(Ue.relative(this.cwd,Ue.resolve(Ue.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[qi](t,this.cwd,n,()=>this[wo](t,String(t.linkpath),"symlink",e),i=>{this[Ke](i,t),e()})}[Cu](t,e){let n=te(Ue.resolve(this.cwd,String(t.linkpath))),i=te(String(t.linkpath)).split("/");this[qi](t,this.cwd,i,()=>this[wo](t,n,"link",e),o=>{this[Ke](o,t),e()})}[qi](t,e,n,i,o){let a=n.shift();if(this.preservePaths||a===void 0)return i();let d=Ue.resolve(e,a);se.lstat(d,(f,u)=>{if(f)return i();if(u?.isSymbolicLink())return o(new Ro(d,Ue.resolve(d,n.join("/"))));this[qi](t,d,n,i,o)})}[Du](){this[oo]++}[Nr](){this[oo]--,this[Hc]()}[cd](t){this[Nr](),t.resume()}[sd](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Zi}[id](t){this[Du]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[ku](t,n))}[ku](t,e){let n=d=>{e(d)},i=()=>{this[On](this.cwd,this.dmode,d=>{if(d){this[Ke](d,t),n();return}this[Ji]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=te(Ue.dirname(String(t.absolute)));if(d!==this.cwd)return this[On](d,this.dmode,f=>{if(f){this[Ke](f,t),n();return}a()})}a()},a=()=>{se.lstat(String(t.absolute),(d,f)=>{if(f&&(this.keep||this.newer&&f.mtime>(t.mtime??f.mtime))){this[cd](t),n();return}if(d||this[sd](t,f))return this[Et](null,t,n);if(f.isDirectory()){if(t.type==="Directory"){let u=this.chmod&&t.mode&&(f.mode&4095)!==t.mode,x=p=>this[Et](p??null,t,n);return u?se.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return se.rmdir(String(t.absolute),u=>this[Et](u??null,t,n))}if(t.absolute===this.cwd)return this[Et](null,t,n);Hy(String(t.absolute),u=>this[Et](u??null,t,n))})};this[Ji]?o():i()}[Et](t,e,n){if(t){this[Ke](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[od](e,n);case"Link":return this[Cu](e,n);case"SymbolicLink":return this[Tu](e,n);case"Directory":case"GNUDumpDir":return this[ad](e,n)}}[wo](t,e,n,i){se[n](e,String(t.absolute),o=>{o?this[Ke](o,t):(this[Nr](),t.resume()),i()})}},Ui=t=>{try{return[null,t()]}catch(e){return[e,null]}},u0=class extends wd{sync=!0;[Et](t,e){return super[Et](t,e,()=>{})}[id](t){if(!this[Ji]){let o=this[On](this.cwd,this.dmode);if(o)return this[Ke](o,t);this[Ji]=!0}if(t.absolute!==this.cwd){let o=te(Ue.dirname(String(t.absolute)));if(o!==this.cwd){let a=this[On](o,this.dmode);if(a)return this[Ke](a,t)}}let[e,n]=Ui(()=>se.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[cd](t);if(e||this[sd](t,n))return this[Et](null,t);if(n.isDirectory()){if(t.type==="Directory"){let a=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[d]=a?Ui(()=>{se.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[Et](d,t)}let[o]=Ui(()=>se.rmdirSync(String(t.absolute)));this[Et](o,t)}let[i]=t.absolute===this.cwd?[]:Ui(()=>qy(String(t.absolute)));this[Et](i,t)}[od](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let f;try{se.closeSync(o)}catch(u){f=u}(d||f)&&this[Ke](d||f,t),e()},o;try{o=se.openSync(String(t.absolute),o0(t.size),n)}catch(d){return i(d)}let a=this.transform&&this.transform(t)||t;a!==t&&(a.on("error",d=>this[Ke](d,t)),t.pipe(a)),a.on("data",d=>{try{se.writeSync(o,d,0,d.length)}catch(f){i(f)}}),a.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let f=t.atime||new Date,u=t.mtime;try{se.futimesSync(o,f,u)}catch(x){try{se.utimesSync(String(t.absolute),f,u)}catch{d=x}}}if(this[Ki](t)){let f=this[$i](t),u=this[Vi](t);try{se.fchownSync(o,Number(f),Number(u))}catch(x){try{se.chownSync(String(t.absolute),Number(f),Number(u))}catch{d=d||x}}}i(d)})}[ad](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[On](String(t.absolute),n);if(i){this[Ke](i,t),e();return}if(t.mtime&&!this.noMtime)try{se.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ki](t))try{se.chownSync(String(t.absolute),Number(this[$i](t)),Number(this[Vi](t)))}catch{}e(),t.resume()}[On](t,e){try{return Dy(te(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}}[qi](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[f,u]=Ui(()=>se.lstatSync(a));if(f)return i();if(u.isSymbolicLink())return o(new Ro(a,Ue.resolve(e,n.join("/"))))}i()}[wo](t,e,n,i){let o=`${n}Sync`;try{se[o](e,String(t.absolute)),i(),t.resume()}catch(a){return this[Ke](a,t)}}},Gy=t=>{let e=new u0(t),n=t.file,i=Yu.statSync(n),o=t.maxReadSize||16*1024*1024;new o_(n,{readSize:o,size:i.size}).pipe(e)},jy=(t,e)=>{let n=new wd(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((a,d)=>{n.on("error",d),n.on("close",a),Yu.stat(o,(f,u)=>{if(f)d(f);else{let x=new ld(o,{readSize:i,size:u.size});x.on("error",d),x.pipe(n)}})})},h0=Yi(Gy,jy,t=>new u0(t),t=>new wd(t),(t,e)=>{e?.length&&Wu(t,e)}),Wy=(t,e)=>{let n=new md(t),i=!0,o,a;try{try{o=xt.openSync(t.file,"r+")}catch(u){if(u?.code==="ENOENT")o=xt.openSync(t.file,"w+");else throw u}let d=xt.fstatSync(o),f=Buffer.alloc(512);e:for(a=0;a<d.size;a+=512){for(let p=0,w=0;p<512;p+=w){if(w=xt.readSync(o,f,p,f.length-p,a+p),a===0&&f[0]===31&&f[1]===139)throw new Error("cannot append to compressed archives");if(!w)break e}let u=new rr(f);if(!u.cksumValid)break;let x=512*Math.ceil((u.size||0)/512);if(a+x+512>d.size)break;a+=x,t.mtimeCache&&u.mtime&&t.mtimeCache.set(String(u.path),u.mtime)}i=!1,Ky(t,n,a,o,e)}finally{if(i)try{xt.closeSync(o)}catch{}}},Ky=(t,e,n,i,o)=>{let a=new Nu(t.file,{fd:i,start:n});e.pipe(a),Vy(e,o)},$y=(t,e)=>{e=Array.from(e);let n=new To(t),i=(o,a,d)=>{let f=(b,_)=>{b?xt.close(o,v=>d(b)):d(null,_)},u=0;if(a===0)return f(null,0);let x=0,p=Buffer.alloc(512),w=(b,_)=>{if(b||_===void 0)return f(b);if(x+=_,x<512&&_)return xt.read(o,p,x,p.length-x,u+x,w);if(u===0&&p[0]===31&&p[1]===139)return f(new Error("cannot append to compressed archives"));if(x<512)return f(null,u);let v=new rr(p);if(!v.cksumValid)return f(null,u);let I=512*Math.ceil((v.size??0)/512);if(u+I+512>a||(u+=I+512,u>=a))return f(null,u);t.mtimeCache&&v.mtime&&t.mtimeCache.set(String(v.path),v.mtime),x=0,xt.read(o,p,0,512,u,w)};xt.read(o,p,0,512,u,w)};return new Promise((o,a)=>{n.on("error",a);let d="r+",f=(u,x)=>{if(u&&u.code==="ENOENT"&&d==="r+")return d="w+",xt.open(t.file,d,f);if(u||!x)return a(u);xt.fstat(x,(p,w)=>{if(p)return xt.close(x,()=>a(p));i(x,w.size,(b,_)=>{if(b)return a(b);let v=new So(t.file,{fd:x,start:_});n.pipe(v),v.on("error",a),v.on("close",o),Jy(n,e)})})};xt.open(t.file,d,f)})},Vy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?jr({file:x0.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n)}),t.end()},Jy=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await jr({file:x0.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(n);t.end()},Hi=Yi(Wy,$y,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!x_(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")}),iC=Yi(Hi.syncFile,Hi.asyncFile,Hi.syncNoFile,Hi.asyncNoFile,(t,e=[])=>{Hi.validate?.(t,e),Zy(t)}),Zy=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))};tn();var rt={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill",SET_CONFIG_OPTION:"_agent/setConfigOption",LIST_AVAILABLE_MODELS:"_agent/listAvailableModels"};function sr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function p0(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Po(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function g0(t){let e=t?.requestScene?.trim();if(!(!e||e.length>64||!/^[A-Za-z0-9_.-]+$/.test(e)))return e}function m0(t){let e=t?.permissionMode;if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}function w0(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function or(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Ct();import{homedir as Yy}from"node:os";import _0 from"node:path";var y0=".claude",E0="settings.json",Do=new Map;function b0(t){return _0.join(t,y0,E0)}async function v0(t,e){let n=b0(t),o=(Do.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=await Ye(n)??{};a.effortLevel=e,await ut(n,a)});Do.set(n,o);try{await o}finally{Do.get(n)===o&&Do.delete(n)}}async function S0(t){let n=(await Ye(b0(t)))?.effortLevel;return typeof n=="string"?n:void 0}async function I0(){let t=_0.join(Yy(),y0,E0),n=(await Ye(t))?.effortLevel;return typeof n=="string"?n:void 0}Wt();Ze();ne();Pe();Ze();function Qi(t,e){if(sr(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function _d(t,e){if(sr(t)==="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_CLOUD",`${e} is not allowed for cloud agent`)}function es(t){return t.startsWith("http://")||t.startsWith("https://")}function Wr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as QC}from"node:fs";import{dirname as t2,join as n2}from"node:path";import{fileURLToPath as i2}from"node:url";var Kt="0.3.2-alpha.106";var yd={"claude-code":{effort:["default","low","medium","high","xhigh","max"],fastMode:null},codex:{effort:["low","medium","high","xhigh"],fastMode:["off","on"]},hermes:{effort:null,fastMode:null},openclaw:{effort:null,fastMode:null}};function T0(t,e){return yd[t][e]}import{mkdir as xE,rm as G0}from"node:fs/promises";import{join as is}from"node:path";Ct();import{readFileSync as sE}from"node:fs";var oE=384;async function Ed(t,e=process.env){let n={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(n[i]=o);await ut(t.agentEnvFile,n,{mode:oE})}function ar(t){try{let e=JSON.parse(sE(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Lo(t,e,n={},i=o=>o){return{...i({...t,...ar(e)}),...n}}Ct();function ts(t){let e=[],n=Object.keys(t).sort();for(let i of n){let o=t[i];o!==void 0&&(aE(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
92
92
  `)}
93
- `}function ib(t){if(t.includes(`
94
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ne();Ce();import{homedir as ab}from"node:os";import{join as cb}from"node:path";Ve();ne();var To="1008033",I0="1289";var A0="pbbp2",k0="https://www.coze.cn",C0="/api/coze_claw/resource/get_frontier_key",sb="https://www.coze.cn",ob="wss://frontier.coze.cn";function Gr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??sb}function T0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??ob}function On(t){let e={},n=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return n&&(e["x-tt-env"]=n),i&&(e["x-use-ppe"]=i),e}function Xi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Yi=G("handshake");async function md(t){let e=Gr(t.endpoint),n=t.timeoutMs??1e4,i=`${Hr(e)}${C0}?aid=${encodeURIComponent(To)}`,s={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...On(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);Yi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:s,signal:a.signal}),h=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let v=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${h}: ${v.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${h}`);let w=p.data??{},b=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,y=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!b||!y){let v=JSON.stringify(p).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${h}: ${v}`)}return Yi.info("handshake ok",{remoteDeviceId:y,logid:h,traceId:x}),{accessKey:b,deviceId:y}}catch(u){if(u instanceof k)throw Yi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Yi.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:u});let h=u.cause;throw Yi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:h?.code,syscall:h?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Po=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Lt="auto",_d="default",wd=19e4,P0=32e3;function R0(t){if(!(vt(t.model)&&!t.effort&&!t.fastMode))return{model:t.model,...t.effort?{effort:t.effort}:{},...t.fastMode?{fastMode:t.fastMode}:{}}}function O0(t){return{model:yd(t.model)??Lt,...t.modelToken?{modelToken:t.modelToken}:{}}}function vt(t){return!t||t===Lt}var db=new Set(["auto","\u81EA\u52A8"]);function yd(t){let e=t?.trim();if(e)return db.has(e.toLowerCase())?Lt:e}function L0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Po,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Lt;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!vt(t.model)&&t.model!==_d&&(e.ANTHROPIC_MODEL=t.model);return e}function M0(t,e,n,i){let s={};if(t.modelToken?s.model=t.model||Lt:vt(t.model)||(s.model=t.model),t.effort&&(s.model_reasoning_effort=t.effort),t.modelToken){let a={name:"coze",base_url:`${Po}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Do(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),s.model_providers={coze:a},s.model_context_window=t.modelInfo?.contextWindow??wd}return Object.keys(s).length===0?{}:{CODEX_CONFIG:JSON.stringify(s),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function N0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Do(t,e,n){let{ttEnv:i,usePpe:s}=Xi(t),a={};return i&&(a["x-tt-env"]=i),s&&(a["x-use-ppe"]=s),e&&(a["x-mock-scenario"]=e),n&&(a["x-coze-request-scene"]=n),a}function B0(t,e,n,i){if(!t.modelToken)return{};let s=Do(e,n,i);return Object.keys(s).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(s).map(([d,u])=>`${d}:${u}`).join(`
95
- `)}}function bd(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function vd(t){return t.model||Lt}function D0(t,e,n,i){return{id:t,name:t,reasoning:!1,input:e,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:n,maxTokens:i,api:"openai-completions"}}function F0(t,e,n,i,s){if(!t.modelToken)return null;let a=vd(t),d=Do(e,n,s),u=["text"];t.modelInfo?.capabilities?.image===!0&&u.push("image");let h=[D0(a,u,t.modelInfo?.contextWindow??wd,t.modelInfo?.maxOutput??P0)],x=new Set([a]);for(let w of i??[])!w||x.has(w)||(x.add(w),h.push(D0(w,["text"],wd,P0)));let p={baseUrl:`${Po}/v1`,api:"openai-completions",apiKey:t.modelToken,models:h};return Object.keys(d).length>0&&(p.headers=d),p}function lb(t){if(t!==void 0)return t?"auto":"text"}function Ed(t,e,n){let i=Do(e,n),s=t.model||Lt,a=["model:"," provider: custom",` default: ${JSON.stringify(s)}`,` base_url: ${Po}/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,h]of Object.entries(i))a.push(` ${u}: ${JSON.stringify(h)}`)}a.push("compression:"),a.push(" threshold: 0.8"),a.push("approvals:"),a.push(` mode: ${JSON.stringify("off")}`),a.push(` cron_mode: ${JSON.stringify("approve")}`);let d=lb(t.modelInfo?.capabilities?.image);return d&&(a.push("agent:"),a.push(` image_input_mode: ${JSON.stringify(d)}`)),a.push("skills:"),a.push(" external_dirs:"),a.push(` - ${cb(ab(),".hermes","skills")}`),`${a.join(`
93
+ `}function aE(t){if(t.includes(`
94
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}ne();Pe();import{homedir as lE}from"node:os";import{join as fE}from"node:path";Ze();ne();var Mo="1008033",C0="1289";var R0="pbbp2",P0="https://www.coze.cn",D0="/api/coze_claw/resource/get_frontier_key",cE="https://www.coze.cn",dE="wss://frontier.coze.cn";function Kr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??cE}function O0(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??dE}function Nn(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 rs(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var ns=q("handshake");async function bd(t){let e=Kr(t.endpoint),n=t.timeoutMs??1e4,i=`${Wr(e)}${D0}?aid=${encodeURIComponent(Mo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Nn(t.ppeOverride)},a=new AbortController,d=setTimeout(()=>a.abort(),n);ns.info("frontier key handshake",{base:e});try{let f=await fetch(i,{method:"GET",headers:o,signal:a.signal}),u=f.headers.get("x-tt-logid")??"",x=f.headers.get("x-tt-trace-id")??"";if(!f.ok){let v=await f.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${f.status} logid=${u}: ${v.slice(0,200)}`)}let p=await f.json();if(p.code!==void 0&&p.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${u}`);let w=p.data??{},b=typeof w.access_key=="string"&&w.access_key||typeof w.accessKey=="string"&&w.accessKey||void 0,_=typeof w.device_id=="string"&&w.device_id||typeof w.deviceId=="string"&&w.deviceId||void 0;if(!b||!_){let v=JSON.stringify(p).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${u}: ${v}`)}return ns.info("handshake ok",{remoteDeviceId:_,logid:u,traceId:x}),{accessKey:b,deviceId:_}}catch(f){if(f instanceof k)throw ns.error("handshake failed (bridge error)",{base:e,message:f.message,code:f.code}),f;if(f.name==="AbortError")throw ns.warn("handshake timeout",{base:e,timeoutMs:n}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:f});let u=f.cause;throw ns.error("handshake error",{base:e,message:f instanceof Error?f.message:String(f),errno:u?.code,syscall:u?.syscall,cause:String(f).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(f),{cause:f})}finally{clearTimeout(d)}}var No=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Mt="auto",Sd="default",vd=19e4,L0=32e3;function N0(t){if(!(bt(t.model)&&!t.effort&&!t.fastMode))return{model:t.model,...t.effort?{effort:t.effort}:{},...t.fastMode?{fastMode:t.fastMode}:{}}}function F0(t){return{model:Id(t.model)??Mt,...t.modelToken?{modelToken:t.modelToken}:{}}}function bt(t){return!t||t===Mt}var uE=new Set(["auto","\u81EA\u52A8"]);function Id(t){let e=t?.trim();if(e)return uE.has(e.toLowerCase())?Mt:e}function B0(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=No,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Mt;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!bt(t.model)&&t.model!==Sd&&(e.ANTHROPIC_MODEL=t.model);return e}function z0(t,e,n,i){let o={};if(t.modelToken?o.model=t.model||Mt:bt(t.model)||(o.model=t.model),t.effort&&(o.model_reasoning_effort=t.effort),t.modelToken){let a={name:"coze",base_url:`${No}/v1`,env_key:"CODEX_API_KEY",wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},d=Fo(e,n,i);Object.keys(d).length>0&&(a.http_headers=d),o.model_providers={coze:a},o.model_context_window=t.modelInfo?.contextWindow??vd}return Object.keys(o).length===0?{}:{CODEX_CONFIG:JSON.stringify(o),...t.modelToken?{MODEL_PROVIDER:"coze"}:{}}}function U0(t){return t.modelToken?{CODEX_API_KEY:t.modelToken,OPENAI_API_KEY:t.modelToken}:{}}function Fo(t,e,n){let{ttEnv:i,usePpe:o}=rs(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 H0(t,e,n,i){if(!t.modelToken)return{};let o=Fo(e,n,i);return Object.keys(o).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(o).map(([d,f])=>`${d}:${f}`).join(`
95
+ `)}}function Ad(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function kd(t){return t.model||Mt}function M0(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 q0(t,e,n,i,o){if(!t.modelToken)return null;let a=kd(t),d=Fo(e,n,o),f=["text"];t.modelInfo?.capabilities?.image===!0&&f.push("image");let u=[M0(a,f,t.modelInfo?.contextWindow??vd,t.modelInfo?.maxOutput??L0)],x=new Set([a]);for(let w of i??[])!w||x.has(w)||(x.add(w),u.push(M0(w,["text"],vd,L0)));let p={baseUrl:`${No}/v1`,api:"openai-completions",apiKey:t.modelToken,models:u};return Object.keys(d).length>0&&(p.headers=d),p}function hE(t){if(t!==void 0)return t?"auto":"text"}function Td(t,e,n){let i=Fo(e,n),o=t.model||Mt,a=["model:"," provider: custom",` default: ${JSON.stringify(o)}`,` base_url: ${No}/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[f,u]of Object.entries(i))a.push(` ${f}: ${JSON.stringify(u)}`)}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=hE(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(` - ${fE(lE(),".hermes","skills")}`),`${a.join(`
96
96
  `)}
97
- `}var sr=G("hermes-config"),U0="dont_ask",H0="default";function or(t,e){return Qi(De(t,e).root,"hermes-home")}async function fb(t){let e=or(t.agentId,t.paths);await ub(e,{recursive:!0,mode:448});let n=Zi({...process.env,...ir(t.paths.agentEnvFile)});await _t(Qi(e,".env"),n,{mode:384});let i=Ed(t.modelConfig,t.cozeEnv,t.mockScenario);await _t(Qi(e,"config.yaml"),i,{mode:384}),sr.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function G0(t){let e=or(t.agentId,t.paths),n=Qi(e,"state.db"),i=Qi(e,"config.yaml");sr.warn("[AUDIT] ABOUT TO RM hermes state.db (resetHermesHome)",{src:"hermes-config.resetHermesHome",agentId:t.agentId,home:e,stateDb:n,callerStack:new Error("resetHermesHome-caller").stack?.split(`
98
- `).slice(1,6).join(" | ")}),await z0(n,{force:!0}).catch(a=>sr.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let s=Ed({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await _t(i,s,{mode:384}).catch(a=>sr.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),sr.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function Id(t,e){let n=or(t,e);sr.warn("[AUDIT] ABOUT TO RM hermes-home (cleanupHermesHome)",{src:"hermes-config.cleanupHermesHome",agentId:t,home:n,callerStack:new Error("cleanupHermesHome-caller").stack?.split(`
99
- `).slice(1,6).join(" | ")}),await z0(n,{recursive:!0,force:!0}).catch(i=>sr.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var Sd=new Map;function q0(t){let e=Sd.get(t.agentId);if(e)return e;let n=fb(t).finally(()=>Sd.delete(t.agentId));return Sd.set(t.agentId,n),n}import{execFile as hb}from"node:child_process";import{createHash as j0}from"node:crypto";import{readFile as xb}from"node:fs/promises";import{homedir as pb}from"node:os";import gb from"node:path";import{promisify as mb}from"node:util";var wb=mb(hb),_b=3e4;function cn(t){return typeof t=="object"&&t!==null?t:null}function qr(t){return Array.isArray(t)?t:[]}function Et(t){return typeof t=="string"?t:void 0}function W0(t,e){return t.map(n=>cn(n)).filter(n=>n!==null).map(n=>{let i={id:Et(n[e])??""},s=Et(n.name),a=Et(n.description);return s&&(i.name=s),a&&(i.description=a),i}).filter(n=>n.id!=="")}function yb(t){let e=qr(t.configOptions);if(e.length===0)return null;let n=null,i,s,a,d,u;for(let x of e){let p=cn(x);if(!p)continue;let w=Et(p.id);if(!w)continue;let b=qr(p.options);w==="model"?(n=W0(b,"value"),i=Et(p.currentValue)):w==="effort"||w==="reasoning_effort"?(s=Et(p.currentValue),d=b.map(y=>Et(cn(y)?.value)).filter(y=>y!==void 0)):w==="fast-mode"&&(a=Et(p.currentValue),u=b.map(y=>Et(cn(y)?.value)).filter(y=>y!==void 0))}return n!==null||i!==void 0||s!==void 0||a!==void 0||d!==void 0||u!==void 0?{models:n??[],...i?{currentModelId:i}:{},...s?{currentEffort:s}:{},...a?{currentFastMode:a}:{},...d?{effortLevels:d}:{},...u?{fastModes:u}:{}}:null}function bb(t){let e=cn(t.models);if(!e)return null;let n=qr(e.availableModels);if(n.length===0)return null;let i=W0(n,"modelId");if(i.length===0)return null;let s=Et(e.currentModelId);return{models:i,...s?{currentModelId:s}:{}}}function K0(t,e){let n=cn(e);if(!n)return null;let i=cn(n.result)??n;return t==="hermes"?bb(i):yb(i)}function vb(t){let e=[],n=t.split(/\r?\n/),i=!1,s=-1,a=null,d=-1,u=!1,h=-1,x=p=>p.length-p.trimStart().length;for(let p of n){let w=p.replace(/#.*$/,"").trimEnd();if(w.trim()==="")continue;let b=x(w),y=w.trim();if(!i){y==="providers:"&&(i=!0,s=b);continue}if(b<=s&&!y.startsWith("-"))break;if((a===null||b<=d)&&y.endsWith(":")&&!y.startsWith("-")){a=y.slice(0,-1).trim(),d=b,u=!1;continue}if(a!==null){if(!u){y==="models:"&&(u=!0,h=b);continue}if(y.startsWith("-")&&b>h){let v=y.slice(1).trim(),I,A=v.match(/^(?:model|id)\s*:\s*(.+)$/);if(A?.[1]?I=A[1].trim():v&&!v.includes(":")&&(I=v),I){let C=I.replace(/^["']|["']$/g,"");e.push({id:`${a}:${C}`,providerId:a})}continue}b<=h&&(u=!1,b<=d&&y.endsWith(":")&&(a=y.slice(0,-1).trim(),d=b))}}return e}async function $0(t){let e=t??pb(),n=gb.join(e,".hermes","config.yaml"),i;try{i=await xb(n,"utf8")}catch{return null}let s=vb(i);return s.length===0?null:{models:s}}async function V0(t){let e;try{({stdout:e}=await wb(t,["models","list","--json","--log-level","silent"],{timeout:_b,maxBuffer:4*1024*1024}))}catch{return null}return Eb(e)}function Eb(t){let e;try{e=JSON.parse(t)}catch{return null}let n=qr(cn(e)?.models);if(n.length===0)return null;let i=n.map(h=>cn(h)).filter(h=>h!==null&&h.available!==!1),s=i.filter(h=>qr(h.tags).some(x=>x==="configured")),a=s.length>0?s:i,d=[],u;for(let h of a){let x=Et(h.key);if(!x)continue;let p={id:x},w=Et(h.name);w&&(p.name=w);let b=x.indexOf("/");b>0&&(p.providerId=x.slice(0,b)),d.push(p),!u&&qr(h.tags).some(y=>y==="default")&&(u=x)}return d.length===0?null:{models:d,...u?{defaultModelId:u}:{}}}function Sb(t){let e=[...t].sort((n,i)=>n.id.localeCompare(i.id));return j0("sha1").update(JSON.stringify(e)).digest("hex")}function J0(t){return j0("sha1").update(Sb(t.models)).update(JSON.stringify(t.effortLevels??null)).update(JSON.stringify(t.fastModes??null)).digest("hex")}var Y=G("agent-handlers"),Y0=5*1024*1024,Tb=1,Pb=6,Db=new Set(["node_modules",".git",".coze","dist","build",".next"]),Rb=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Ob=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,Lb=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Mb(t){let e=t?.trim();return e?Lb.test(e)||Ob.test(e)?e:(Y.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function Nb(t){return new Promise((e,n)=>{let i=dt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),s=!1,a=d=>{s||(s=!0,d?n(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),a()}),i.once("error",d=>a(d))})}function Bb(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var Oo=class t{constructor(e){this.opts=e}opts;static OPENCLAW_MODEL_CACHE_TTL_MS=18e4;openclawRefreshInFlight=!1;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let n=rr(e._meta),i=await this.loadAgentCfg(n),s=i?.workspace??De(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:u}=Wr(a,n,s,this.paths),h=[],x=new Set;for(let w of d){let b=he(u,w.relPath,"SKILL.md");await Rd(b).then(v=>v.isFile()).catch(()=>!1)&&(h.push(Gb(w)),x.add(w.relPath))}if(e.scanLocal){let w=await ch(n,s,a,this.paths),b=await dh(n,a);for(let y of[...w,...b])x.has(y.relPath)||(x.add(y.relPath),h.push(y.skill))}return{skills:a==="hermes"?h.filter(w=>w.skillName!=="yuanbao"):h}}async addSkills(e){e._meta;let n=rr(e._meta),i=await this.requireAgentCfg(n),s=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((h,x)=>[h.skillId,x])),u=[];for(let h of s){let x=await Lo({agentId:n,workspace:i.workspace,framework:i.framework,skill:h,paths:this.paths});Mo(a,d,x),u.push(h)}return await yi(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let n=rr(e._meta),i=await this.requireAgentCfg(n),s=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:u}=Wr(i.framework,n,i.workspace,this.paths);for(let h of a){if(!s.has(h.skillId)){d.push(h);continue}let x=he(u,h.relPath);Y.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:h.skillId,relPath:h.relPath,skillBase:u,absDir:x}),await Cd(x,{recursive:!0,force:!0}),Y.info("skill removed",{agentId:n,skillId:h.skillId,relPath:h.relPath})}return await yi(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=rr(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");Y.info("_agent/publishSkill start",{agentId:n,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(n),s=i?.workspace??De(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,u=await zb(n,s,a,e.skillName,d,this.paths);if(!u){let P=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${P}: ${e.skillName}`)}let{absDir:h,relPath:x,dirName:p}=u,w=he(h,"SKILL.md"),b=new Ld.default;b.addLocalFolder(h,p);let y=b.toBuffer();if(y.length>X0)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${y.length} bytes exceeds limit ${X0}`);let v=await Ro(w,{encoding:"utf8"}).then(P=>oh(P).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:y,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):Y.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",C=I.skillId??e.skillId??sh(n,x);if(i&&!d){let P=i.skills??[],E=P.find(D=>D.relPath===x);E?(E.version=A,E.skillId=C):P.push({skillId:C,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await yi(n,P)}return Y.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:y.length,skillId:C,version:A}),{ok:!0,skillId:C,version:A}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let i=this.opts.agents.get(e);if(i)for(let[s,a]of i.sessions){if(!a.downstream)continue;let d=a.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(a)){a.reloadAfterTurn=!0,Y.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d});continue}let h=a.downstream;a.downstream=void 0,Y.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:s,acpId:d}),h.stop(n).catch(x=>Y.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:s,err:String(x)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return Y.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await ge(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return Y.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Sr(i.workspace,i.framework,e.cozeIdentity)}catch(s){throw Y.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:i.framework,workspace:i.workspace,err:String(s)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(s)}`,{cause:s})}return i.cozeIdentity=e.cozeIdentity,await Re(i),Y.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:i.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async upgradeBridge(e){let n=e.agentId||e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await ge(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=["-y"];e.registry&&Ji(e.registry)&&s.push(`--registry=${e.registry}`);let a=Mb(e.targetVersion);s.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&Rb.test(d)&&s.push("--env",d);let u=await Nb(s);return Y.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:u,targetVersion:a,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await ge(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Re(i),Y.info("agent disconnected",{agentId:n,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(n,e.reason??"disconnect"),{ok:!0}):(Y.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async deleteAgent(e){let n=e.agentId;if(!n)throw new k("IPC_BAD_REQUEST",`${nt.DELETE}: missing agentId`);Y.warn("[AUDIT] deleteAgent handler entry",{agentId:n,reason:e.reason??"",forceParamDeployType:e.deployType,metaDeployType:e._meta?.cozeDeployType,callerStack:new Error("deleteAgent-caller").stack?.split(`
100
- `).slice(1,6).join(" | ")});let i=await ge(n),s=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,a=e.deployType??s??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(n,e.reason??"delete");let d=De(n);return a==="cloud"?(Y.warn("[AUDIT] ABOUT TO RM agent dir (deleteAgent cloud path)",{src:"agent-handlers.deleteAgent",agentId:n,path:d.root,deployType:a,reason:e.reason??""}),await Cd(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Re(i)),Y.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=yd(e.model)??Lt;if(nr(e._meta)!=="cloud")return this.switchModelLocal(e,n);let i=await ge(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 Re(i),Y.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return Y.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};let a=s.model,d=s.modelInfo;s.model=n,e.modelInfo&&s.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(s,a).catch(x=>Y.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=s.framework==="hermes"&&Bb(d,s.modelInfo);if(s.framework==="hermes"&&!u){let x=[];for(let[p,w]of s.allSessionQueues())x.push(w.enqueue(async()=>{let b=s.sessions.get(p);if(!(!b?.downstream||!b.acpSessionId))try{await b.downstream.setSessionModel?.({sessionId:b.acpSessionId,modelId:n})}catch(y){Y.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:b.acpSessionId,err:String(y)})}}));return await Promise.all(x),Y.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let h=[];for(let[x,p]of s.allSessionQueues())h.push(p.enqueue(async()=>{let w=s.sessions.get(x);w?.downstream&&(await w.downstream.stop(`switchModel: ${n}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(h),Y.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:h.length}),{ok:!0}}async switchModelLocal(e,n){let i=await ge(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,await Re(i),Y.info("_agent/switchModel(local): model persisted",{agentId:e.agentId,model:n});let s=this.opts.agents.get(e.agentId);if(!s)return Y.info("_agent/switchModel(local): agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};if(s.model=n,vt(n))return Y.info("_agent/switchModel(local): auto sentinel, skip runtime fan-out",{agentId:e.agentId}),{ok:!0};let a=await this.fanOutConfigAxis(s,e.agentId,"model",n,"_agent/switchModel(local)");return Y.info("_agent/switchModel(local): sessions updated via set_config_option",{agentId:e.agentId,model:n,cloudSessions:a}),{ok:!0}}async fanOutConfigAxis(e,n,i,s,a){let d=[];for(let[u,h]of e.allSessionQueues())d.push(h.enqueue(async()=>{let x=e.sessions.get(u);!x?.downstream||!x.acpSessionId||await x.downstream.setConfigOption(x.acpSessionId,i,s).catch(p=>Y.warn(`${a}: set_config_option failed (ignored)`,{agentId:n,cloudId:u,err:String(p)}))}));return await Promise.all(d),d.length}async setConfigOption(e){if(xd(e._meta,nt.SET_CONFIG_OPTION),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/setConfigOption: missing agentId");let n=await ge(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=S0(n.framework,e.configType);if(!i)throw new k("CAPABILITY_UNSUPPORTED",`${n.framework} does not support config '${e.configType}'`);let s=this.opts.modelListCache?.get(n.framework);if(!((e.configType==="effort"?s?.effortLevels:s?.fastModes)??i).includes(e.value))throw new k("IPC_BAD_REQUEST",`invalid ${e.configType} value '${e.value}' for ${n.framework}`);let d=e.value;n.framework==="claude-code"&&e.configType==="effort"&&e.value==="default"&&(d=await this.resolveEffortDefault(n.workspace));let u=n[e.configType];n[e.configType]=d,await Re(n),Y.info("_agent/setConfigOption: persisted",{agentId:e.agentId,configType:e.configType,value:d}),n.framework==="claude-code"&&e.configType==="effort"&&await w0(n.workspace,d).catch(x=>Y.warn("_agent/setConfigOption: writeCcWorkspaceEffort failed (ignored)",{agentId:e.agentId,err:String(x)}));let h=this.opts.agents.get(e.agentId);return h&&(e.configType==="effort"?h.setEffort(d):h.setFastMode(d),await this.fanOutConfigAxis(h,e.agentId,e.configType,d,"_agent/setConfigOption")),{ok:!0,previousValue:u,currentValue:d}}async resolveEffortDefault(e){let n=await _0(e).catch(()=>{});if(n)return n;let i=await y0().catch(()=>{});return i||"default"}async listAvailableModels(e){if(xd(e._meta,nt.LIST_AVAILABLE_MODELS),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/listAvailableModels: missing agentId");let n=await ge(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=n.framework,s=this.opts.modelListCache,a=[],d,u="fallback",h=s?.get(i);if(h&&h.models.length>0)a=h.models,d=h.defaultModelId,u="cache",i==="openclaw"&&this.maybeRefreshOpenclawModels(h.cachedAt);else if(i==="hermes"){let C=await $0().catch(()=>null);C&&C.models.length>0&&(a=C.models,d=C.defaultModelId,u="disk")}else if(i==="openclaw"){let C=await this.opts.openclawModelLister?.().catch(()=>null);C&&C.models.length>0&&(a=C.models,d=C.defaultModelId,u="disk",s?.update("openclaw",C).catch(()=>{}))}let x=s?.getRuntimeCurrent(e.agentId),p;n.model&&!vt(n.model)?p=n.model:p=x?.model??d;let w=n.effort??x?.effort,b=n.fastMode??x?.fastMode,y=pd[i],v=h?.effortLevels??y.effort,I=h?.fastModes??y.fastMode,A={switchModel:!0,switchEffort:y.effort!==null,switchFastMode:y.fastMode!==null,...v?{supportedEffortLevels:[...v]}:{},...I?{supportedFastModes:[...I]}:{}};return{framework:i,models:a,...d?{defaultModelId:d}:{},...p?{currentModelId:p}:{},...A.switchEffort&&w?{currentEffort:w}:{},...A.switchFastMode&&b?{currentFastMode:b}:{},source:u,capabilities:A}}maybeRefreshOpenclawModels(e){let n=this.opts.openclawModelLister,i=this.opts.modelListCache;!n||!i||this.openclawRefreshInFlight||Date.now()-e<t.OPENCLAW_MODEL_CACHE_TTL_MS||(this.openclawRefreshInFlight=!0,(async()=>{try{let s=await n();s&&s.models.length>0&&await i.update("openclaw",s)}catch{}finally{this.openclawRefreshInFlight=!1}})())}async detail(e){let n=e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST",`${nt.DETAIL}: missing cozeAgentId`);let i=await ge(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=this.opts.modelListCache?.getRuntimeCurrent(n),a=i.effort??s?.effort,d=i.fastMode??s?.fastMode;return{agentId:n,agentName:i.agentName??"",cozeIdentity:i.cozeIdentity??"",framework:i.framework,...i.description!==void 0?{description:i.description}:{},...i.model?{model:i.model}:{},...a?{effort:a}:{},...d?{fastMode:d}:{}}}async resetAgent(e){if(Vi(e._meta,nt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${nt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,nt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>Y.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,nt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),Y.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(n);for(let a of i.sessions.values())a.acpSessionId=void 0,a.replySeq=0,a.loadingSession=!1,a.spawnFailCount=void 0,a.spawnFailedAt=void 0;let s=new Map;for(let[a,d]of i.sessions)s.set(a,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt,permissionMode:d.permissionMode,cozeGroupId:d.cozeGroupId});await _i(e,s)}async clearPersistedAcpSessionIds(e){let n=await ge(e).catch(()=>null);if(!n?.sessions)return;let i=!1;for(let s of Object.values(n.sessions))s.acpSessionId&&(s.acpSessionId=void 0,i=!0);i&&await Re(n)}async repairAgent(e){if(Vi(e._meta,nt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${nt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${nt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){Y.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,nt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){Y.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){Y.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(s)})}}async getFileTree(e){Vi(e._meta,"_agent/getFileTree");let n=e._meta,i=rr(n),s=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(s,a),u=await Ad(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 wi(d,s))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let h=ev(e.depth);return u.isDirectory()?{tree:await Qb(s,d,a,h)}:{tree:[{name:tv(a),path:fh(a||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){Vi(e._meta,"_agent/getFileContent");let n=rr(e._meta),i=await this.resolveWorkspace(n);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(i,e.filePath),a=await Ad(s).catch(()=>null);if(!a||!a.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(a.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await wi(s,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>Y0)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${Y0})`);let d=await Ro(s);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:a.size}:{content:d.toString("utf8"),encoding:"utf-8",size:a.size}}async resolveWorkspace(e){let n=this.opts.agents.get(e);return n?n.workspace:(await ge(e).catch(()=>null))?.workspace??De(e).workspace}safeJoin(e,n){let i=Pd(e,n||"."),s=Od(e,i);if(s.startsWith("..")||s===".."||s.startsWith(`..${eh}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return ge(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function rh(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new k("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new k("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Wr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:he(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:he(".agents","skills")};case"hermes":return{base:or(e,i??Z()),subdir:"skills"}}}function ih(t){let e=Ab();if(t==="claude-code")return[he(e,".claude","skills")];if(t==="codex")return[he(e,".agents","skills"),he(e,".codex","skills")];if(t==="openclaw")return[he(e,".agents","skills"),he(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||he(e,"AppData","Local");return[he(n,"hermes","skills"),he(e,".hermes","skills")]}return[he(e,".hermes","skills")]}return[]}async function Fb(t,e,n,i,s,a){let d=async u=>Rd(he(u,"SKILL.md")).then(h=>h.isFile()).catch(()=>!1);if(!s){let{base:u,subdir:h}=Wr(n,t,e,a),x=he(h,i),p=he(u,x);return await d(p)?{absDir:p,relPath:x}:null}for(let u of ih(n)){let h=he(u,i);if(await d(h))return{absDir:h,relPath:h}}return null}async function zb(t,e,n,i,s,a){let d=rh(i),u=await Fb(t,e,n,d,s,a);if(u)return{...u,dirName:d};let x=(s?await dh(t,n):await ch(t,e,n,a)).filter(b=>b.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${s?"global":"workspace"}: ${x.map(b=>Z0(b.relPath)).join(", ")} \u2014 rename or remove duplicates`);let p=x[0];return p?{absDir:s?p.relPath:he(e,p.relPath),relPath:p.relPath,dirName:Z0(p.relPath)}:null}function sh(t,e){return(Ib("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function oh(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
- ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let s of n.split(`
102
- `)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(s);if(!a||!a[2])continue;let d=a[1],u=a[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function ah(t,e,n,i){let s=await Q0(e,{withFileTypes:!0}).catch(()=>null);if(!s)return[];let a=[];for(let d of s){let u=d.isDirectory();if(!u&&d.isSymbolicLink()&&(u=!!(await Rd(he(e,d.name)).catch(()=>null))?.isDirectory()),!u)continue;let h=d.name,x=he(n,h),p=he(e,h,"SKILL.md"),w=await Ro(p,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let b=oh(w);a.push({relPath:x,skill:{skillId:sh(t,x),skillName:b.name||h,...b.description?{description:b.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function ch(t,e,n,i){let{base:s,subdir:a}=Wr(n,t,e,i);return ah(t,he(s,a),a,!1)}async function dh(t,e){let n=[],i=new Set;for(let s of ih(e)){let a=await ah(t,s,s,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var Ub=3e4,Hb=50*1024*1024,X0=10*1024*1024,jr=3e4;async function Lo(t){let{agentId:e,workspace:n,framework:i,skill:s,paths:a}=t;if(!s.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let d=typeof s.content=="string"&&s.content.length>0,u=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!d&&!u)throw new k("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let h=rh(s.skillName),{base:x,subdir:p}=Wr(i,e,n,a),w=he(p,h),b=he(x,w);if(await kd(b,{recursive:!0}),d){let v=Buffer.from(s.content,"utf8");es(v.length),await Td(he(b,"SKILL.md"),v,"utf8")}else{let v=await jb(s.downloadUrl);Kb(v)?await Zb(v,b):$b(v)?await Vb(v,b):await Td(he(b,"SKILL.md"),v.toString("utf8"),"utf8")}let y={skillId:s.skillId,skillName:s.skillName,relPath:w,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return Y.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:w,source:d?"content":"downloadUrl"}),y}function Mo(t,e,n){let i=e.get(n.skillId);if(i!==void 0){t[i]=n;return}e.set(n.skillId,t.length),t.push(n)}function Gb(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}function qb(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function lh(t,e){let n=await ge(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=jt,s=n.skillsRefreshedForVersion;if(s===i)return{status:"noop",count:0};if(!s)return n.skillsRefreshedForVersion=i,await Re(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((w,b)=>[w.skillId,b])),u=a.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(u.length===0)return n.skillsRefreshedForVersion=i,await Re(n,e),{status:"noop",count:0};let h=0,x=0,{base:p}=Wr(n.framework,t,n.workspace,e);Y.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:s,current:i,skillBase:p,builtinCount:u.length,builtinRelPaths:u.map(w=>w.relPath)});for(let w of u)try{let b=he(p,w.relPath);Y.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:b}),await Cd(b,{recursive:!0,force:!0});let y=await Lo({agentId:t,workspace:n.workspace,framework:n.framework,skill:qb(w),...e?{paths:e}:{}});Mo(a,d,y),h+=1}catch(b){x+=1,Y.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(b)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await Re(n,e),Y.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:s,to:i,ok:h,failed:x}),{status:"refreshed",count:h}}async function jb(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);es(e);let n=Wb(t);return es(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Ro(e);return es(n.length),n}if(Ji(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),Ub);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let s=await i.arrayBuffer();return es(s.byteLength),Buffer.from(s)}finally{clearTimeout(n)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function es(t){if(t>Hb)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Wb(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 Kb(t){return t.length>=2&&t[0]===31&&t[1]===139}function $b(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],n=t[3];return e===3&&n===4||e===5&&n===6}function Dd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Vb(t,e){let n,i;try{n=new Ld.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||Dd(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let h=d.header.attr>>>16&61440;if(h!==0&&h!==32768&&h!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${h.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let s=Jb(i),a=Pd(e);for(let d of i){if(Dd(d.entryName))continue;let u=d.entryName;if(s&&u.startsWith(s)&&(u=u.slice(s.length)),!u)continue;let h=Pd(e,u),x=Od(a,h);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await kd(h,{recursive:!0});continue}await kd(kb(h),{recursive:!0});let p;try{p=d.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await Td(h,p)}}function Jb(t){let e;for(let n of t){let i=n.entryName;if(!i||Dd(i))continue;let s=i.indexOf("/");if(s<=0)return;let a=i.slice(0,s+1);if(e===void 0)e=a;else if(e!==a)return}return e}async function Zb(t,e){await Yb(t);let n=c0({cwd:e,strip:1}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${jr}ms)`))},jr);try{await nh(th.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${jr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}}async function Yb(t){let e=[],n=Ur({onReadEntry:a=>{let d=a.path,u=a.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,s=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${jr}ms)`))},jr);try{await nh(th.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${jr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(s)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Xb=5e3;async function Qb(t,e,n,i){return uh(t,e,n,i,{count:0})}async function uh(t,e,n,i,s){if(i<=0)return[];let a;try{a=await Q0(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of a){if(Db.has(u.name)||u.isSymbolicLink())continue;if(s.count>=Xb){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let h=he(e,u.name),x=Cb(he(n,u.name)),p=null;try{p=await Ad(h)}catch{continue}if(p.isSymbolicLink())continue;s.count++;let w={name:u.name,path:fh(Od(t,h)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(w.children=await uh(t,h,x,i-1,s)),d.push(w)}return d.sort((u,h)=>u.isDir!==h.isDir?u.isDir?-1:1:u.name.localeCompare(h.name)),d}function ev(t){return!t||t<=0?Tb:Math.min(t,Pb)}function tv(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function fh(t){return t.split(eh).join("/")}ne();var Ln=G("agent-health-reporter"),nv=1e4,rv=3,ts=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??nv,this.livenessFailureThreshold=e.livenessFailureThreshold??rv}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Ln.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Ln.info("heartbeat stopped"))}async tick(){if(this.inFlight){Ln.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Ln.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let d of this.opts.core.agents.values()){let u=iv(d);if(!u)continue;let h={agentId:d.agentId,status:u};d.patToken&&(h.patToken=d.patToken),d.accountId&&(h.accountId=d.accountId),n.push(h)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:jt,_meta:{cozeDeviceId:e}},s;try{s=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Ln.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=s?.authFailures;if(a&&a.length>0&&(Ln.warn("heartbeat received authFailures from cloud",{count:a.length,agentIds:a.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(a)}catch(d){Ln.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Ln.warn("onTickEnd hook failed",{err:String(n)})}}};function iv(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Qt();import{copyFile as bE,cp as vE,mkdir as $o,readFile as EE,rm as SE,stat as Gd,writeFile as IE}from"node:fs/promises";import{homedir as Yh}from"node:os";import{basename as AE,join as ln}from"node:path";yn();import{existsSync as pv}from"node:fs";import{release as gv}from"node:os";import{basename as mv,isAbsolute as wv}from"node:path";function ns(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Kr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function $r(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Mn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ve();var No=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)}},Q={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function hh(t){return"method"in t&&"id"in t&&t.id!==void 0}function xh(t){return"method"in t&&!("id"in t)}function Bo(t){return!("method"in t)&&"id"in t}var sv={AGENT_NOT_FOUND:Q.AGENT_NOT_FOUND,AGENT_BUSY:Q.AGENT_BUSY,AGENT_DISCONNECTED:Q.AGENT_DISCONNECTED,AGENT_TIMEOUT:Q.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Q.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Q.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Q.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Q.INTERNAL_ERROR,BRIDGE_INTERNAL:Q.INTERNAL_ERROR,IPC_AUTH_FAILED:Q.INTERNAL_ERROR,IPC_BAD_REQUEST:Q.INVALID_REQUEST,METHOD_NOT_FOUND:Q.METHOD_NOT_FOUND,CAPABILITY_UNSUPPORTED:Q.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Q.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Q.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Q.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Q.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Q.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Q.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Q.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Q.FILE_TOO_LARGE,UNSUPPORTED_MIME:Q.UNSUPPORTED_MIME,UPLOAD_FAILED:Q.UPLOAD_FAILED,UPSTREAM_NOT_READY:Q.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Q.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Q.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Q.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Q.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Q.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Q.SKILL_ZIP_TOO_LARGE};function ov(t){if(t!=null)return t instanceof Error?{name:t.name,message:rs(t.message)}:typeof t=="string"?rs(t):typeof t=="object"?cv(t):t}var av=[[/\/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 rs(t){let e=t;for(let[n,i]of av)e=e.replace(n,i);return e}function cv(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=rs(i):e[n]=i;return e}function is(t){if(t instanceof k){let e=ov(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:sv[t.code]??Q.INTERNAL_ERROR,message:rs(t.message),data:n}}return{code:Q.INTERNAL_ERROR,message:rs(t instanceof Error?t.message:String(t))}}function ph(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,s=i?e?.message:t.message,a=t.data;if(i&&e){let{message:d,...u}=e;a=u}return new k(n,s,{retriable:e?.retriable??!1,cause:a})}function mh(t){return`${JSON.stringify(t)}
103
- `}var gh=10*1024*1024,Fo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>gh){let s=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${s} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${gh} bytes`)}),[]}let n=this.buffer.split(`
104
- `);this.buffer=n.pop()??"";let i=[];for(let s of n){let a=s.replace(/\r$/,"").trim();if(a)try{i.push(JSON.parse(a))}catch(d){this.onError?.({line:a,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var _h={"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"},gP=Object.fromEntries(Object.entries(_h).map(([t,e])=>[e,t])),dv={"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:[]},Vr=class{seq=0;next(e,n){this.seq+=1;let i=_h[e]??lv(e),s=dv[i]??[],a=[i,String(this.seq)];if(s.length>0){let d=s.map(h=>wh(n?.[h]??"")),u=uv(d).join(":");u&&a.push(u)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>wh(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function lv(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function wh(t){return t.replace(/[:_\s]+/g,"-")}function uv(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}an();_r();Ve();ne();Ce();import{execFileSync as fv,spawnSync as hv}from"node:child_process";function ss(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function os(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),hv("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Md=new Set;function yh(t){typeof t=="number"&&t>0&&Md.add(t)}function bh(t){typeof t=="number"&&Md.delete(t)}function vh(){for(let t of Md)os(t,"SIGKILL")}var Jr="coze-bridge-daemon";function Eh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let s=process.getuid?.()??0;return fv("pgrep",["-U",String(s),"-f",Jr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),n;try{n=e()}catch{return[]}let i=process.pid;return n.split(`
105
- `).map(s=>Number.parseInt(s.trim(),10)).filter(s=>Number.isFinite(s)&&s>0&&s!==i)}async function Sh(t,e){if(t.length===0)return;let n=e?.killFn??os,i=e?.isAliveFn??ss,s=e?.sleepFn??(u=>new Promise(h=>setTimeout(h,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(h=>i(h));u+=d)await s(Math.min(d,a-u));for(let u of t)i(u)&&n(u,"SIGKILL")}var xv=[{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 xv)if(!(n.frameworks&&!n.frameworks.includes(t))&&n.match.test(e))return{bridgeCode:n.bridgeCode,reason:n.reason,message:n.message};return null}function Ah(t,e){return Ih(t,e)}function kh(t,e){return Ih(t,e)}function Zr(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 Ch(t,e,n){let s=n-t.armedAt-t.expectedIntervalMs;if(s>e.suspendThresholdMs){let x=t.suspendedMs+s,p=n-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:s,rearmMs:Zr(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:Zr(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Zr(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Zr(a,!1,e)}}var Th=$e("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",6e4),_v=200,yv=40,bv=$e("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),vv=$e("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Ev=$e("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Sv=$e("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Iv=$e("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Av=$e("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ph=500,kv=process.env.COZE_BRIDGE_TRACE_RPC==="1",Dh=$e("COZE_BRIDGE_TRACE_RPC_MAX",2e3);function Cv(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ph?t:`${e.slice(0,Ph)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Tv(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 Rh(t){try{return pv(t)}catch{return}}function Pv(t,e){return{platform:process.platform,osRelease:gv(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:wv(e.command)?Rh(e.command):void 0,cwd:e.cwd,cwdExists:Rh(e.cwd),envKeys:e.envKeys}}function Dv(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${mv(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var St=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Fo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Vr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",n=Co(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,s=>this.sanitizeEnv(s)),i=dt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,yh(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",s=>{try{for(let a of this.decoder.push(s))this.dispatch(a)}catch(a){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(a)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",s=>{let a=s.trimEnd();this.stderrRing.push(a),this.stderrRing.length>_v&&this.stderrRing.shift(),this.log.debug("stderr",{text:a})}),i.stdin?.on("error",s=>{this.log.warn("child stdin error",{err:String(s)})}),i.stdout?.on("error",s=>{this.log.warn("child stdout error",{err:String(s)})}),i.stderr?.on("error",s=>{this.log.warn("child stderr error",{err:String(s)})}),i.on("exit",(s,a)=>{this.stopped=!0,bh(i.pid),(s!==0||a!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:s,signal:a,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(s,a));for(let u of this.exitHandlers)u(s,a)}),i.on("error",s=>{let a=s,d=Pv(a,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(n).length});this.log.error("child error",{err:String(s),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",Dv(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()));os(n.pid,"SIGTERM");let s=setTimeout(()=>{n.killed||os(n.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,n){let i={firstUpdateMs:Iv,phase2GateMs:bv,livenessWindowMs:vv,absoluteMaxMs:Ev,approvalMaxMs:Av,suspendThresholdMs:Sv,...n};return this.call("session/prompt",e,Th,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Kr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}setSessionModel(e){return this.call("session/set_model",e)}configIdFor(e){return e==="model"?"model":null}sendSetConfigOption(e,n,i){return this.call("session/set_config_option",{sessionId:e,configId:n,value:i}).then(()=>{})}setConfigOption(e,n,i){let s=this.configIdFor(n);return s===null?Promise.reject(new k("CAPABILITY_UNSUPPORTED",`${this.framework} does not support axis '${n}'`)):this.sendSetConfigOption(e,s,i)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame($r(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(Mn(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=Th,s){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=ns(a,e,n),u=(()=>{if(typeof n!="object"||n===null)return;let h=n.sessionId;return typeof h=="string"?h:void 0})();return new Promise((h,x)=>{let p={resolve:h,reject:x,timer:null,method:e,promptTimeout:null};if(s){let w=this.now(),b={cfg:s,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:Zr(0,!1,s),sessionId:u};p.promptTimeout=b;let y=()=>{let v={startedAt:b.startedAt,lastActivityAt:b.lastActivityAt,firstFrameSeen:b.firstFrameSeen,hasActiveTool:b.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:b.suspendedMs,armedAt:b.armedAt,expectedIntervalMs:b.expectedIntervalMs},I=this.now(),A=Ch(v,b.cfg,I),C=P=>{b.armedAt=I,b.expectedIntervalMs=P,p.timer=setTimeout(y,P)};if(A.action==="suspend"){b.suspendedMs+=A.suspendedDeltaMs,b.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:b.suspendedMs,...b.sessionId?{sessionId:b.sessionId}:{}}),C(A.rearmMs);return}if(A.action==="continue"){C(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...b.sessionId?{sessionId:b.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${b.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${b.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...b.sessionId?{sessionId:b.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${b.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(y,b.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,p);try{this.writeFrame(d)}catch(w){p.timer&&clearTimeout(p.timer),this.pending.delete(a),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.traceFrame("->",e),this.child.stdin.write(mh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}traceFrame(e,n){if(!kv)return;let i=n,s;try{let a=JSON.stringify(n);s=a===void 0||a.length<=Dh?n:`${a.slice(0,Dh)}...<truncated, total ${a.length} chars>`}catch{s="<unserializable>"}this.log.info(`rpc ${e}`,{dir:e,method:i.method,id:i.id,frame:s})}dispatch(e){if(this.traceFrame("<-",e),Bo(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:Cv(e.result)}),n.resolve(e.result));return}if(xh(e)){if(e.method==="session/update"){let n=e.params;for(let i of this.pending.values()){let s=i.promptTimeout;s&&(s.firstFrameSeen=!0,s.lastActivityAt=this.now(),this.trackToolCall(s,n))}for(let i of this.updateHandlers)try{Promise.resolve(i(n)).catch(s=>this.log.warn("update handler failed (async)",{err:String(s)}))}catch(s){this.log.warn("update handler threw sync, swallowed",{err:String(s)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(hh(e)){let n=e;try{this.handleAgentRequest(n).catch(i=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(i)})}}}trackToolCall(e,n){let i=n.update,s=i?.sessionUpdate;if(s!=="tool_call"&&s!=="tool_call_update")return;let a=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!a)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";s==="tool_call"&&!u?e.activeToolCalls.add(a):u&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Mn(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(Mn(e.id,is(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=ph(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=kh(this.framework,Tv(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(yv).join(`
106
- `),s=Ah(this.framework,i);return s?new k(s.bridgeCode,s.message,{cause:{reason:s.reason,code:e,signal:n,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${n})`,{cause:{code:e,signal:n,stderrTail:i}})}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Rv(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 zo=class extends St{framework="claude-code";constructor(e){let{command:n,args:i}=mi("claude-code",e.command,e.args??[]),s={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return Rv(e)}configIdFor(e){return e==="model"?"model":e==="effort"?"effort":null}};yn();import{spawn as Ov}from"node:child_process";import{closeSync as Lv,existsSync as Fd,mkdirSync as Mv,mkdtempSync as Nv,openSync as Bv,readFileSync as zh,readSync as Fv,readdirSync as zv,rmSync as Uv,statSync as Hv}from"node:fs";import{homedir as Gv,tmpdir as qv}from"node:os";import{join as Yr}from"node:path";var Oh=["default","acceptEdits","plan","auto","bypassPermissions"],Lh=["read-only","auto","full-access"];var Mh=["default","accept_edits","dont_ask"];function Wt(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Oh.includes(e);case"codex":return Lh.includes(e);case"hermes":return Mh.includes(e);case"openclaw":return!1}}function Uo(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Nh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Nd(t){switch(t){case"claude-code":return Oh.join("/");case"codex":return Lh.join("/");case"hermes":return Mh.join("/");case"openclaw":return""}}Ce();var zd=9e4,jv=64*1024,Wv=100;function Kv(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?zd:Math.max(1,Math.floor(e*1e3))}function $v(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?zd:Math.max(1,Math.floor(e))}function Vv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return Object.keys(e).length>0?e:void 0}function Bh(t){if(typeof t=="string"&&t.trim())return{command:t,timeoutMs:zd};if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.type&&e.type!=="command")return;let n=typeof e.command=="string"?e.command.trim():"";if(!n)return;let i=typeof e.working_directory=="string"&&e.working_directory.trim()?e.working_directory.trim():typeof e.cwd=="string"&&e.cwd.trim()?e.cwd.trim():void 0,s=Vv(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?Kv(e.timeout):$v(e.timeout_ms),...i?{cwd:i}:{},...s?{env:s}:{}}}function Bd(t){if(Array.isArray(t))return t.flatMap(i=>Bd(i));if(!t||typeof t!="object"){let i=Bh(t);return i?[i]:[]}let e=t;if(e.hooks)return Bd(e.hooks);let n=Bh(e);return n?[n]:[]}function Jv(t){let e=Yr(t,"hooks.json");if(!Fd(e))return[];let n=JSON.parse(zh(e,"utf8")),s=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return Bd(s.Stop??s.stop)}function Zv(t,e){let n=Yr(t,"sessions");if(!Fd(n))return;let i=[],s=a=>{let d;try{d=zv(a,{withFileTypes:!0})}catch{return}for(let u of d){let h=Yr(a,u.name);if(u.isDirectory())s(h);else if(u.isFile()&&u.name.endsWith(".jsonl"))try{i.push({path:h,mtimeMs:Hv(h).mtimeMs})}catch{}}};s(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,Wv))if(Yv(a.path,e))return a.path}function Yv(t,e){let n;try{n=Bv(t,"r");let i=Buffer.alloc(jv),s=Fv(n,i,0,i.length,0),a=i.subarray(0,s).toString("utf8");return a.includes(JSON.stringify(e))||a.includes(e)}catch{return!1}finally{if(n!==void 0)try{Lv(n)}catch{}}}function Xv(t){return ir(t??Z().agentEnvFile)}function Qv(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 eE(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let s=i.startsWith("export ")?i.slice(7).trimStart():i,a=s.indexOf("=");if(a<=0)continue;let d=s.slice(0,a).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&(e[d]=Qv(s.slice(a+1)))}return e}function tE(t){let e=Yr(t,"cozeloop.env");return Fd(e)?eE(zh(e,"utf8")):{}}function Fh(t){let e=t?.trim();return e||void 0}function nE(t){let e=Xv(t.agentEnvFile),n=Fh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=Fh(t.env?.HOME??e.HOME??process.env.HOME)??Gv();return Yr(i,".codex")}var Ho=class extends St{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;fastMode;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:s,args:a}=mi("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Nv(Yr(qv(),"coze-bridge-codex-home-")):nE(e),u=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!u&&Mv(d,{recursive:!0});let h=e.isolateCodexHome&&d?{...e.env??{},CODEX_HOME:d}:e.env,x={command:s,args:a,cwd:e.cwd,agentId:e.agentId,...e.agentEnvFile?{agentEnvFile:e.agentEnvFile}:{},...h?{env:h}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=u,this.fastMode=e.fastMode}configIdFor(e){return e==="model"?"model":e==="effort"?"reasoning_effort":e==="fastMode"?"fast-mode":null}async afterSessionEstablished(e){if(this.fastMode)try{await this.setConfigOption(e,"fastMode",this.fastMode)}catch(n){this.log.warn("codex fast-mode post-establish failed (ignored)",{sessionId:e,err:String(n)})}}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=Wt("codex",e.modeId)?Uo(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(rE(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=Jv(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let s=Zv(n,e),a=JSON.stringify({hook_event_name:"Stop",session_id:e,...s?{transcript_path:s}:{},trigger:"coze-bridge"});await Promise.all(i.map(async d=>{try{await this.runHookCommand(d,a)}catch(u){this.log.warn("codex stop hook failed",{codexHomeDir:n,command:d.command.slice(0,200),err:String(u)})}}))}runHookCommand(e,n){return new Promise((i,s)=>{let a=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=a?tE(a):{},u=Co(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&u.COZE_API_TOKEN&&(u.COZELOOP_API_TOKEN=u.COZE_API_TOKEN);let h=Ov(e.command,{cwd:e.cwd??this.opts.cwd,env:u,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",p=setTimeout(()=>{h.kill("SIGTERM"),s(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);h.stderr?.setEncoding("utf8"),h.stderr?.on("data",w=>{x+=w,x.length>4e3&&(x=x.slice(-4e3))}),h.on("error",w=>{clearTimeout(p),s(w)}),h.on("close",(w,b)=>{if(clearTimeout(p),w===0){i();return}s(new Error(`hook exited code=${w} signal=${b} stderr=${x.slice(-1e3)}`))}),h.stdin.end(`${n}
108
- `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{Uv(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function rE(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=Nh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var iE=G("hermes-downstream"),Go=class extends St{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setConfigOption(e,"model",this.modelId)}catch(n){iE.warn("hermes model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}setConfigOption(e,n,i){return n==="model"?this.setSessionModel({sessionId:e,modelId:i}).then(()=>{}):super.setConfigOption(e,n,i)}};Ve();var Uh=3e4,Xr=class extends St{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let s={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Uh))}get acpSessionName(){return this.sessionName}async setConfigOption(e,n,i){if(n!=="model")throw new k("CAPABILITY_UNSUPPORTED",`openclaw does not support axis '${n}'`);await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${i}`}]},Uh)}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Ct();Ve();ne();Ce();function Ud(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}yn();var Kt=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 qo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;effort;fastMode;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo),e.effort&&(this.effort=e.effort),e.fastMode&&(this.fastMode=e.fastMode)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}setEffort(e){this.effort=e}setFastMode(e){this.fastMode=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Kt,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)Qr(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 Qr(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function dn(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}an();ne();import{constants as Hh}from"node:fs";import{access as sE,readFile as oE}from"node:fs/promises";import{delimiter as aE,dirname as cE,join as Gh}from"node:path";var rt=G("framework-detector"),qh={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},dE=[".exe",".cmd",".bat",".ps1"],ar=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??dt,access:e.access??sE,readFile:e.readFile??oE}}async detect(e){let n=qh[e],i=await this.which(n);if(!i&&e==="hermes"&&(i=await this.resolveHermesAcpViaHermesShim()),!i)return rt.debug("framework binary not found",{framework:e,bin:n}),null;let s=e==="openclaw"?["--log-level","silent"]:[],[a,d]=await Promise.all([this.probeVersion(i,s),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:a};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(qh).map(async i=>[i,await this.detect(i)])),n={};for(let[i,s]of e)s&&(n[i]=s);return n}async which(e){let n=this.env.pathEnv.split(aE).filter(Boolean),i=this.env.platform==="win32"?["",...dE]:[""];for(let s of n)for(let a of i){let d=Gh(s,e+a);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Hh.F_OK:Hh.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async resolveHermesAcpViaHermesShim(){if(this.env.platform==="win32")return null;let e=await this.which("hermes");if(!e)return null;let n;try{n=await this.env.readFile(e,"utf8")}catch(d){return rt.debug("hermes shim fallback: readFile failed",{hermesPath:e,err:String(d)}),null}let s=n.match(/exec\s+["']?(\/[^\s"']+\/bin\/hermes)["']?/)?.[1];if(!s)return rt.debug("hermes shim fallback: no exec line matched",{hermesPath:e}),null;let a=Gh(cE(s),"hermes-acp");return await this.isExecutable(a)?(rt.info("hermes-acp resolved via hermes shim fallback",{hermesPath:e,candidate:a}),a):(rt.debug("hermes shim fallback: hermes-acp not executable at inferred path",{hermesPath:e,candidate:a}),null)}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return rt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return rt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let i=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return rt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let s=JSON.parse(i[0]);if(!Array.isArray(s))return rt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let a=s.find(d=>d?.isDefault===!0);return a?!a.id||!a.workspace?(rt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!a.id,hasWorkspace:!!a.workspace}),null):{id:a.id,workspace:a.workspace}:(rt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:s.length}),null)}catch(s){return rt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(s),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let n=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!n)return rt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=n.code===0;i||rt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)});let s={reachable:i},a=n.stdout.match(/\{[\s\S]*\}/);if(a)try{let d=JSON.parse(a[0]);typeof d.gateway?.port=="number"&&(s.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(s.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(s.detail=d.rpc.error)}catch(d){rt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return s}async probeVersion(e,n=[]){let i=await this.runProbe(e,[...n,"--version"]);return i&&(uE(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let s="",a=!1,d,u=h=>{a||(a=!0,d&&clearTimeout(d),i(h))};try{let h=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{h.kill("SIGKILL"),u(null)},15e3),h.stdout?.on("data",x=>{s+=x.toString("utf8")}),h.on("error",()=>u(null)),h.on("close",x=>u({code:x,stdout:s}))}catch{u(null)}})}},lE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function uE(t){return t.replace(lE,"")}import{homedir as Wh}from"node:os";import{join as Wo}from"node:path";Ct();an();_r();Ve();ne();async function Kh(){let t=Wo(Wh(),".openclaw/openclaw.json");return Ze(t)}async function $h(){return(await Kh())?.gateway?.auth?.token??""}var cr=G("openclaw.config"),fE=[0,5e3,5e3],hE=$e("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),jh="models.providers.",jo="agents.defaults.models",xE=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function ei(t,e){let n=Array.isArray(t)?[...t]:[],i=new Set(n);for(let s of e)i.has(s)||(i.add(s),n.push(s));return n}var Ko=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Kt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??fE,this.cliTimeoutMs=e.cliTimeoutMs??hE,this.openclawDir=e.openclawDir??Wo(Wh(),".openclaw")}async withRetry(e,n){let i;for(let s=0;s<this.retryDelaysMs.length;s++){let a=this.retryDelaysMs[s]??0;a>0&&await new Promise(d=>setTimeout(d,a));try{return await n()}catch(d){i=d,cr.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((n,i)=>{let s=dt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,u=x=>{d||(d=!0,clearTimeout(h),x())};s.stderr?.on("data",x=>{a+=x.toString("utf8")});let h=setTimeout(()=>{u(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);h.unref(),s.on("error",x=>u(()=>i(x))),s.on("close",x=>u(()=>{x===0?n():i(new Error(`exit ${x}: ${a.trim().slice(0,500)}`))}))})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(i){let s=String(i);if(n.some(a=>s.includes(a)))return;throw i}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCliTolerant(["config","unset",n],["Config path not found","Nothing was changed"])))}catch(i){cr.warn(`${e} failed (best-effort)`,{configPath:n,err:String(i)})}}ensureProvider(e,n){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${jh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${jh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${jo}[${e}]`,()=>this.runCli(["config","set",jo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${jo}[${e}]`,`${jo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await Kh())?.agents?.defaults?.models;if(!i||typeof i!="object")return[];let s=`${e}/`,a=[];for(let d of Object.keys(i))d.startsWith(s)&&a.push(d.slice(s.length));return a}ensureAgent(e,n,i){let s=["agents","add",e,"--workspace",n,"--non-interactive"];return i&&s.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}ensureAcpDeviceScopes(){return this.queue.enqueue(()=>this.ensureAcpDeviceScopesUnlocked())}async ensureAcpDeviceScopesUnlocked(){try{let e=Wo(this.openclawDir,"identity","device.json"),i=(await Ze(e))?.deviceId?.trim();if(!i)return cr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let s=Wo(this.openclawDir,"devices","paired.json"),a=await Ze(s),d=a?.[i];if(!a||!d)return cr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let u=d.tokens?.operator,h=ei(ei(d.scopes,d.approvedScopes??[]),u?.scopes??[]).filter(v=>v.startsWith("operator.")),x=ei([...xE],h),p=ei(d.scopes,x),w=ei(d.approvedScopes,x),b=u?ei(u.scopes,x):void 0;return p.length!==(d.scopes?.length??0)||w.length!==(d.approvedScopes?.length??0)||u!==void 0&&b?.length!==(u.scopes?.length??0)?(d.scopes=p,d.approvedScopes=w,u&&b&&(u.scopes=b),await ft(s,a,{mode:384}),cr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(cr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return cr.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as pE,writeFile as gE}from"node:fs/promises";import{join as mE}from"node:path";var wE=["```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
- `),_E=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
110
- `);function yE(t){return t.length===0?t:`${(t.endsWith(`
97
+ `}var cr=q("hermes-config"),j0="dont_ask",W0="default";function dr(t,e){return is(Oe(t,e).root,"hermes-home")}async function pE(t){let e=dr(t.agentId,t.paths);await xE(e,{recursive:!0,mode:448});let n=ts({...process.env,...ar(t.paths.agentEnvFile)});await _t(is(e,".env"),n,{mode:384});let i=Td(t.modelConfig,t.cozeEnv,t.mockScenario);await _t(is(e,"config.yaml"),i,{mode:384}),cr.info("hermes home bootstrapped",{agentId:t.agentId,home:e,envBytes:n.length,yamlBytes:i.length})}async function K0(t){let e=dr(t.agentId,t.paths),n=is(e,"state.db"),i=is(e,"config.yaml");cr.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 G0(n,{force:!0}).catch(a=>cr.warn("hermes reset: rm state.db failed (ignored)",{agentId:t.agentId,err:String(a)}));let o=Td({model:t.model,modelInfo:t.modelInfo},t.cozeEnv,t.mockScenario);await _t(i,o,{mode:384}).catch(a=>cr.warn("hermes reset: write config.yaml failed (ignored)",{agentId:t.agentId,err:String(a)})),cr.info("hermes reset complete",{agentId:t.agentId,removed:["state.db"],rewrote:["config.yaml"]})}async function Rd(t,e){let n=dr(t,e);cr.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 G0(n,{recursive:!0,force:!0}).catch(i=>cr.warn("hermes-home cleanup failed (ignored)",{agentId:t,err:String(i)}))}var Cd=new Map;function $0(t){let e=Cd.get(t.agentId);if(e)return e;let n=pE(t).finally(()=>Cd.delete(t.agentId));return Cd.set(t.agentId,n),n}Wt();import{createHash as V0}from"node:crypto";import{readFile as gE}from"node:fs/promises";import{homedir as mE}from"node:os";import wE from"node:path";var _E=3e4;function dn(t){return typeof t=="object"&&t!==null?t:null}function $r(t){return Array.isArray(t)?t:[]}function vt(t){return typeof t=="string"?t:void 0}function J0(t,e){return t.map(n=>dn(n)).filter(n=>n!==null).map(n=>{let i={id:vt(n[e])??""},o=vt(n.name),a=vt(n.description);return o&&(i.name=o),a&&(i.description=a),i}).filter(n=>n.id!=="")}function yE(t){let e=$r(t.configOptions);if(e.length===0)return null;let n=null,i,o,a,d,f;for(let x of e){let p=dn(x);if(!p)continue;let w=vt(p.id);if(!w)continue;let b=$r(p.options);w==="model"?(n=J0(b,"value"),i=vt(p.currentValue)):w==="effort"||w==="reasoning_effort"?(o=vt(p.currentValue),d=b.map(_=>vt(dn(_)?.value)).filter(_=>_!==void 0)):w==="fast-mode"&&(a=vt(p.currentValue),f=b.map(_=>vt(dn(_)?.value)).filter(_=>_!==void 0))}return n!==null||i!==void 0||o!==void 0||a!==void 0||d!==void 0||f!==void 0?{models:n??[],...i?{currentModelId:i}:{},...o?{currentEffort:o}:{},...a?{currentFastMode:a}:{},...d?{effortLevels:d}:{},...f?{fastModes:f}:{}}:null}function EE(t){let e=dn(t.models);if(!e)return null;let n=$r(e.availableModels);if(n.length===0)return null;let i=J0(n,"modelId");if(i.length===0)return null;let o=vt(e.currentModelId);return{models:i,...o?{currentModelId:o}:{}}}function Z0(t,e){let n=dn(e);if(!n)return null;let i=dn(n.result)??n;return t==="hermes"?EE(i):yE(i)}function bE(t){let e=[],n=t.split(/\r?\n/),i=!1,o=-1,a=null,d=-1,f=!1,u=-1,x=p=>p.length-p.trimStart().length;for(let p of n){let w=p.replace(/#.*$/,"").trimEnd();if(w.trim()==="")continue;let b=x(w),_=w.trim();if(!i){_==="providers:"&&(i=!0,o=b);continue}if(b<=o&&!_.startsWith("-"))break;if((a===null||b<=d)&&_.endsWith(":")&&!_.startsWith("-")){a=_.slice(0,-1).trim(),d=b,f=!1;continue}if(a!==null){if(!f){_==="models:"&&(f=!0,u=b);continue}if(_.startsWith("-")&&b>u){let v=_.slice(1).trim(),I,A=v.match(/^(?:model|id)\s*:\s*(.+)$/);if(A?.[1]?I=A[1].trim():v&&!v.includes(":")&&(I=v),I){let T=I.replace(/^["']|["']$/g,"");e.push({id:`${a}:${T}`,providerId:a})}continue}b<=u&&(f=!1,b<=d&&_.endsWith(":")&&(a=_.slice(0,-1).trim(),d=b))}}return e}async function X0(t){let e=t??mE(),n=wE.join(e,".hermes","config.yaml"),i;try{i=await gE(n,"utf8")}catch{return null}let o=bE(i);return o.length===0?null:{models:o}}async function Y0(t){let e;try{({stdout:e}=await Oo(t,["models","list","--json","--log-level","silent"],{timeout:_E,maxBuffer:4*1024*1024}))}catch{return null}return vE(e)}function vE(t){let e;try{e=JSON.parse(t)}catch{return null}let n=$r(dn(e)?.models);if(n.length===0)return null;let i=n.map(u=>dn(u)).filter(u=>u!==null&&u.available!==!1),o=i.filter(u=>$r(u.tags).some(x=>x==="configured")),a=o.length>0?o:i,d=[],f;for(let u of a){let x=vt(u.key);if(!x)continue;let p={id:x},w=vt(u.name);w&&(p.name=w);let b=x.indexOf("/");b>0&&(p.providerId=x.slice(0,b)),d.push(p),!f&&$r(u.tags).some(_=>_==="default")&&(f=x)}return d.length===0?null:{models:d,...f?{defaultModelId:f}:{}}}function SE(t){let e=[...t].sort((n,i)=>n.id.localeCompare(i.id));return V0("sha1").update(JSON.stringify(e)).digest("hex")}function Q0(t){return V0("sha1").update(SE(t.models)).update(JSON.stringify(t.effortLevels??null)).update(JSON.stringify(t.fastModes??null)).digest("hex")}var X=q("agent-handlers"),th=5*1024*1024,CE=1,RE=6,PE=new Set(["node_modules",".git",".coze","dist","build",".next"]),DE=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,OE=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,LE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function ME(t){let e=t?.trim();return e?LE.test(e)||OE.test(e)?e:(X.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function NE(t){return new Promise((e,n)=>{let i=dt("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 FE(t,e){return t?.contextWindow!==e?.contextWindow||t?.maxOutput!==e?.maxOutput||t?.capabilities?.image!==e?.capabilities?.image}var zo=class t{constructor(e){this.opts=e}opts;static OPENCLAW_MODEL_CACHE_TTL_MS=18e4;openclawRefreshInFlight=!1;get paths(){return this.opts.paths??Z()}async listSkills(e){e._meta;let n=or(e._meta),i=await this.loadAgentCfg(n),o=i?.workspace??Oe(n,this.paths).workspace,a=i?.framework??"claude-code",d=i?.skills??[],{base:f}=Jr(a,n,o,this.paths),u=[],x=new Set;for(let w of d){let b=xe(f,w.relPath,"SKILL.md");await Fd(b).then(v=>v.isFile()).catch(()=>!1)&&(u.push(qE(w)),x.add(w.relPath))}if(e.scanLocal){let w=await uh(n,o,a,this.paths),b=await hh(n,a);for(let _ of[...w,...b])x.has(_.relPath)||(x.add(_.relPath),u.push(_.skill))}return{skills:a==="hermes"?u.filter(w=>w.skillName!=="yuanbao"):u}}async addSkills(e){e._meta;let n=or(e._meta),i=await this.requireAgentCfg(n),o=e.skills??[],a=[...i.skills??[]],d=new Map(a.map((u,x)=>[u.skillId,x])),f=[];for(let u of o){let x=await Uo({agentId:n,workspace:i.workspace,framework:i.framework,skill:u,paths:this.paths});Ho(a,d,x),f.push(u)}return await Ii(n,a),this.reloadAgentSessions(n,"skills-added"),{installedSkills:f}}async removeSkills(e){e._meta;let n=or(e._meta),i=await this.requireAgentCfg(n),o=new Set(e.skillIds??[]),a=i.skills??[],d=[],{base:f}=Jr(i.framework,n,i.workspace,this.paths);for(let u of a){if(!o.has(u.skillId)){d.push(u);continue}let x=xe(f,u.relPath);X.warn("[AUDIT] ABOUT TO RM skill dir (removeSkills)",{src:"agent-handlers.removeSkills",agentId:n,skillId:u.skillId,relPath:u.relPath,skillBase:f,absDir:x}),await Od(x,{recursive:!0,force:!0}),X.info("skill removed",{agentId:n,skillId:u.skillId,relPath:u.relPath})}return await Ii(n,d),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let n=or(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");X.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??Oe(n,this.paths).workspace,a=i?.framework??"claude-code",d=e.isGlobal??!1,f=await zE(n,o,a,e.skillName,d,this.paths);if(!f){let R=d?"global":"workspace";throw new k("SKILL_NOT_FOUND",`skill not found in ${R}: ${e.skillName}`)}let{absDir:u,relPath:x,dirName:p}=f,w=xe(u,"SKILL.md"),b=new zd.default;b.addLocalFolder(u,p);let _=b.toBuffer();if(_.length>nh)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${_.length} bytes exceeds limit ${nh}`);let v=await Bo(w,{encoding:"utf8"}).then(R=>lh(R).description).catch(()=>{}),I={};this.opts.publishSkillToMarketplace?I=await this.opts.publishSkillToMarketplace({zip:_,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...v?{description:v}:{},agentId:n,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):X.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:n,skillName:e.skillName});let A=I.version??"v1.0",T=I.skillId??e.skillId??dh(n,x);if(i&&!d){let R=i.skills??[],E=R.find(P=>P.relPath===x);E?(E.version=A,E.skillId=T):R.push({skillId:T,skillName:e.skillName,relPath:x,version:A,installedAt:Date.now(),...v?{description:v}:{}}),await Ii(n,R)}return X.info("skill published",{agentId:n,skillName:e.skillName,relPath:x,zipBytes:_.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,X.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let u=a.downstream;a.downstream=void 0,X.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:i.framework,cloudId:o,acpId:d}),u.stop(n).catch(x=>X.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 X.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,i=await we(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);if(i.cozeIdentity===e.cozeIdentity)return X.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Tr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw X.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 Le(i),X.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 we(n))throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=["-y"];e.registry&&es(e.registry)&&o.push(`--registry=${e.registry}`);let a=ME(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${a}`,"connect");let d=e._meta?.cozeEnv;d&&DE.test(d)&&o.push("--env",d);let f=await NE(o);return X.info("_agent/upgrade: spawned bridge upgrade process",{agentId:n,pid:f,targetVersion:a,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:f,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 we(n);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Le(i),X.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}):(X.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",`${rt.DELETE}: missing agentId`);X.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 we(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=Oe(n);return a==="cloud"?(X.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 Od(d.root,{recursive:!0,force:!0})):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Le(i)),X.info("agent deleted",{agentId:n,reason:e.reason??"",deployType:a,configFound:!!i}),{ok:!0}}async switchModel(e){if(!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Id(e.model)??Mt;if(sr(e._meta)!=="cloud")return this.switchModelLocal(e,n);let i=await we(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 Le(i),X.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return X.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=>X.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(x)}));let f=o.framework==="hermes"&&FE(d,o.modelInfo);if(o.framework==="hermes"&&!f){let x=[];for(let[p,w]of o.allSessionQueues())x.push(w.enqueue(async()=>{let b=o.sessions.get(p);if(!(!b?.downstream||!b.acpSessionId))try{await b.downstream.setSessionModel?.({sessionId:b.acpSessionId,modelId:n})}catch(_){X.warn("_agent/switchModel: hermes session/set_model failed (ignored)",{agentId:e.agentId,cloudId:p,acpId:b.acpSessionId,err:String(_)})}}));return await Promise.all(x),X.info("_agent/switchModel: hermes sessions updated via session/set_model",{agentId:e.agentId,model:n,cloudSessions:x.length}),{ok:!0}}let u=[];for(let[x,p]of o.allSessionQueues())u.push(p.enqueue(async()=>{let w=o.sessions.get(x);w?.downstream&&(await w.downstream.stop(`switchModel: ${n}`).catch(()=>{}),w.downstream=void 0)}));return await Promise.all(u),X.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:n,cloudSessions:u.length}),{ok:!0}}async switchModelLocal(e,n){let i=await we(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=n,await Le(i),X.info("_agent/switchModel(local): model persisted",{agentId:e.agentId,model:n});let o=this.opts.agents.get(e.agentId);if(!o)return X.info("_agent/switchModel(local): agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};if(o.model=n,bt(n))return X.info("_agent/switchModel(local): auto sentinel, skip runtime fan-out",{agentId:e.agentId}),{ok:!0};let a=await this.fanOutConfigAxis(o,e.agentId,"model",n,"_agent/switchModel(local)");return X.info("_agent/switchModel(local): sessions updated via set_config_option",{agentId:e.agentId,model:n,cloudSessions:a}),{ok:!0}}async fanOutConfigAxis(e,n,i,o,a){let d=[];for(let[f,u]of e.allSessionQueues())d.push(u.enqueue(async()=>{let x=e.sessions.get(f);!x?.downstream||!x.acpSessionId||await x.downstream.setConfigOption(x.acpSessionId,i,o).catch(p=>X.warn(`${a}: set_config_option failed (ignored)`,{agentId:n,cloudId:f,err:String(p)}))}));return await Promise.all(d),d.length}async setConfigOption(e){if(_d(e._meta,rt.SET_CONFIG_OPTION),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/setConfigOption: missing agentId");let n=await we(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=T0(n.framework,e.configType);if(!i)throw new k("CAPABILITY_UNSUPPORTED",`${n.framework} does not support config '${e.configType}'`);let o=this.opts.modelListCache?.get(n.framework);if(!((e.configType==="effort"?o?.effortLevels:o?.fastModes)??i).includes(e.value))throw new k("IPC_BAD_REQUEST",`invalid ${e.configType} value '${e.value}' for ${n.framework}`);let d=e.value;n.framework==="claude-code"&&e.configType==="effort"&&e.value==="default"&&(d=await this.resolveEffortDefault(n.workspace));let f=n[e.configType];n[e.configType]=d,await Le(n),X.info("_agent/setConfigOption: persisted",{agentId:e.agentId,configType:e.configType,value:d}),n.framework==="claude-code"&&e.configType==="effort"&&await v0(n.workspace,d).catch(x=>X.warn("_agent/setConfigOption: writeCcWorkspaceEffort failed (ignored)",{agentId:e.agentId,err:String(x)}));let u=this.opts.agents.get(e.agentId);return u&&(e.configType==="effort"?u.setEffort(d):u.setFastMode(d),await this.fanOutConfigAxis(u,e.agentId,e.configType,d,"_agent/setConfigOption")),{ok:!0,previousValue:f,currentValue:d}}async resolveEffortDefault(e){let n=await S0(e).catch(()=>{});if(n)return n;let i=await I0().catch(()=>{});return i||"default"}async listAvailableModels(e){if(_d(e._meta,rt.LIST_AVAILABLE_MODELS),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/listAvailableModels: missing agentId");let n=await we(e.agentId);if(!n)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);let i=n.framework,o=this.opts.modelListCache,a=[],d,f="fallback",u=o?.get(i);if(u&&u.models.length>0)a=u.models,d=u.defaultModelId,f="cache",i==="openclaw"&&this.maybeRefreshOpenclawModels(u.cachedAt);else if(i==="hermes"){let T=await X0().catch(()=>null);T&&T.models.length>0&&(a=T.models,d=T.defaultModelId,f="disk")}else if(i==="openclaw"){let T=await this.opts.openclawModelLister?.().catch(()=>null);T&&T.models.length>0&&(a=T.models,d=T.defaultModelId,f="disk",o?.update("openclaw",T).catch(()=>{}))}let x=o?.getRuntimeCurrent(e.agentId),p;n.model&&!bt(n.model)?p=n.model:p=x?.model??d;let w=n.effort??x?.effort,b=n.fastMode??x?.fastMode,_=yd[i],v=u?.effortLevels??_.effort,I=u?.fastModes??_.fastMode,A={switchModel:!0,switchEffort:_.effort!==null,switchFastMode:_.fastMode!==null,...v?{supportedEffortLevels:[...v]}:{},...I?{supportedFastModes:[...I]}:{}};return{framework:i,models:a,...d?{defaultModelId:d}:{},...p?{currentModelId:p}:{},...A.switchEffort&&w?{currentEffort:w}:{},...A.switchFastMode&&b?{currentFastMode:b}:{},source:f,capabilities:A}}maybeRefreshOpenclawModels(e){let n=this.opts.openclawModelLister,i=this.opts.modelListCache;!n||!i||this.openclawRefreshInFlight||Date.now()-e<t.OPENCLAW_MODEL_CACHE_TTL_MS||(this.openclawRefreshInFlight=!0,(async()=>{try{let o=await n();o&&o.models.length>0&&await i.update("openclaw",o)}catch{}finally{this.openclawRefreshInFlight=!1}})())}async detail(e){let n=e._meta?.cozeAgentId;if(!n)throw new k("IPC_BAD_REQUEST",`${rt.DETAIL}: missing cozeAgentId`);let i=await we(n);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${n}`);let o=this.opts.modelListCache?.getRuntimeCurrent(n),a=i.effort??o?.effort,d=i.fastMode??o?.fastMode;return{agentId:n,agentName:i.agentName??"",cozeIdentity:i.cozeIdentity??"",framework:i.framework,...i.description!==void 0?{description:i.description}:{},...i.model?{model:i.model}:{},...a?{effort:a}:{},...d?{fastMode:d}:{}}}async resetAgent(e){if(Qi(e._meta,rt.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${rt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,rt.RESET),this.opts.hermesReset&&await this.opts.hermesReset(e.agentId,e._meta?.cozeEnv).catch(n=>X.warn("hermes reset hook failed (ignored)",{agentId:e.agentId,err:String(n)})),await this.runDetailSync(e.agentId,rt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),X.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 Si(e,o)}async clearPersistedAcpSessionIds(e){let n=await we(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 Le(n)}async repairAgent(e){if(Qi(e._meta,rt.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${rt.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${rt.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(i){X.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,rt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,i){if(!this.opts.detailSyncer){X.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){X.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){Qi(e._meta,"_agent/getFileTree");let n=e._meta,i=or(n),o=await this.resolveWorkspace(i),a=e.filePath??"",d=this.safeJoin(o,a),f=await Pd(d).catch(()=>null);if(!f)throw new k("IPC_BAD_REQUEST",`path not found: ${a}`);if(f.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${a}`);if(!await vi(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${a}`);let u=eb(e.depth);return f.isDirectory()?{tree:await QE(o,d,a,u)}:{tree:[{name:tb(a),path:gh(a||"."),isDir:!1,size:f.size,modifiedAt:Math.floor(f.mtimeMs)}]}}async getFileContent(e){Qi(e._meta,"_agent/getFileContent");let n=or(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 Pd(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 vi(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(a.size>th)throw new k("IPC_BAD_REQUEST",`file too large: ${a.size} bytes (max ${th})`);let d=await Bo(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 we(e).catch(()=>null))?.workspace??Oe(e).workspace}safeJoin(e,n){let i=Md(e,n||"."),o=Bd(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${ih}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return i}loadAgentCfg(e){return we(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 ah(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 Jr(t,e,n,i){switch(t){case"claude-code":return{base:n,subdir:xe(".claude","skills")};case"codex":case"openclaw":return{base:n,subdir:xe(".agents","skills")};case"hermes":return{base:dr(e,i??Z()),subdir:"skills"}}}function ch(t){let e=AE();if(t==="claude-code")return[xe(e,".claude","skills")];if(t==="codex")return[xe(e,".agents","skills"),xe(e,".codex","skills")];if(t==="openclaw")return[xe(e,".agents","skills"),xe(e,".openclaw","skills")];if(t==="hermes"){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA||xe(e,"AppData","Local");return[xe(n,"hermes","skills"),xe(e,".hermes","skills")]}return[xe(e,".hermes","skills")]}return[]}async function BE(t,e,n,i,o,a){let d=async f=>Fd(xe(f,"SKILL.md")).then(u=>u.isFile()).catch(()=>!1);if(!o){let{base:f,subdir:u}=Jr(n,t,e,a),x=xe(u,i),p=xe(f,x);return await d(p)?{absDir:p,relPath:x}:null}for(let f of ch(n)){let u=xe(f,i);if(await d(u))return{absDir:u,relPath:u}}return null}async function zE(t,e,n,i,o,a){let d=ah(i),f=await BE(t,e,n,d,o,a);if(f)return{...f,dirName:d};let x=(o?await hh(t,n):await uh(t,e,n,a)).filter(b=>b.skill.skillName===i);if(x.length>1)throw new k("SKILL_NOT_FOUND",`multiple skills named "${i}" in ${o?"global":"workspace"}: ${x.map(b=>eh(b.relPath)).join(", ")} \u2014 rename or remove duplicates`);let p=x[0];return p?{absDir:o?p.relPath:xe(e,p.relPath),relPath:p.relPath,dirName:eh(p.relPath)}:null}function dh(t,e){return(IE("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function lh(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
101
+ ---`,3);if(e<0)return{};let n=t.slice(3,e),i={};for(let o of n.split(`
102
+ `)){let a=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!a||!a[2])continue;let d=a[1],f=a[2].trim();(f.startsWith('"')&&f.endsWith('"')||f.startsWith("'")&&f.endsWith("'"))&&(f=f.slice(1,-1)),f&&(i[d]=f)}return i}async function fh(t,e,n,i){let o=await rh(e,{withFileTypes:!0}).catch(()=>null);if(!o)return[];let a=[];for(let d of o){let f=d.isDirectory();if(!f&&d.isSymbolicLink()&&(f=!!(await Fd(xe(e,d.name)).catch(()=>null))?.isDirectory()),!f)continue;let u=d.name,x=xe(n,u),p=xe(e,u,"SKILL.md"),w=await Bo(p,{encoding:"utf8"}).catch(()=>null);if(w===null)continue;let b=lh(w);a.push({relPath:x,skill:{skillId:dh(t,x),skillName:b.name||u,...b.description?{description:b.description}:{},...i?{isGlobal:!0}:{}}})}return a}async function uh(t,e,n,i){let{base:o,subdir:a}=Jr(n,t,e,i);return fh(t,xe(o,a),a,!1)}async function hh(t,e){let n=[],i=new Set;for(let o of ch(e)){let a=await fh(t,o,o,!0);for(let d of a)i.has(d.relPath)||(i.add(d.relPath),n.push(d))}return n}var UE=3e4,HE=50*1024*1024,nh=10*1024*1024,Vr=3e4;async function Uo(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,f=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!d&&!f)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=ah(o.skillName),{base:x,subdir:p}=Jr(i,e,n,a),w=xe(p,u),b=xe(x,w);if(await Dd(b,{recursive:!0}),d){let v=Buffer.from(o.content,"utf8");ss(v.length),await Ld(xe(b,"SKILL.md"),v,"utf8")}else{let v=await jE(o.downloadUrl);KE(v)?await ZE(v,b):$E(v)?await VE(v,b):await Ld(xe(b,"SKILL.md"),v.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:w,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return X.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:w,source:d?"content":"downloadUrl"}),_}function Ho(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 qE(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 GE(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 xh(t,e){let n=await we(t,e);if(!n)return{status:"skipped",count:0};if(n.disconnectedAt)return{status:"skipped",count:0};let i=Kt,o=n.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return n.skillsRefreshedForVersion=i,await Le(n,e),{status:"seeded",count:0};let a=[...n.skills??[]],d=new Map(a.map((w,b)=>[w.skillId,b])),f=a.filter(w=>w.builtin===!0&&!!w.downloadUrl);if(f.length===0)return n.skillsRefreshedForVersion=i,await Le(n,e),{status:"noop",count:0};let u=0,x=0,{base:p}=Jr(n.framework,t,n.workspace,e);X.warn("[AUDIT] refreshBuiltinSkills triggered (version bump)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,framework:n.framework,prev:o,current:i,skillBase:p,builtinCount:f.length,builtinRelPaths:f.map(w=>w.relPath)});for(let w of f)try{let b=xe(p,w.relPath);X.warn("[AUDIT] ABOUT TO RM builtin skill dir (refreshBuiltinSkills)",{src:"agent-handlers.refreshAgentBuiltinSkillsOnUpgrade",agentId:t,skillId:w.skillId,relPath:w.relPath,rmTarget:b}),await Od(b,{recursive:!0,force:!0});let _=await Uo({agentId:t,workspace:n.workspace,framework:n.framework,skill:GE(w),...e?{paths:e}:{}});Ho(a,d,_),u+=1}catch(b){x+=1,X.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:w.skillId,skillName:w.skillName,err:String(b)})}return n.skills=a,x===0&&(n.skillsRefreshedForVersion=i),await Le(n,e),X.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:u,failed:x}),{status:"refreshed",count:u}}async function jE(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);ss(e);let n=WE(t);return ss(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Bo(e);return ss(n.length),n}if(es(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),UE);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 ss(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 ss(t){if(t>HE)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function WE(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 KE(t){return t.length>=2&&t[0]===31&&t[1]===139}function $E(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 Nd(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function VE(t,e){let n,i;try{n=new zd.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 f=d.entryName;if(!f||Nd(f))continue;if(f.startsWith("/")||/^[A-Za-z]:[\\/]/.test(f))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${f}`);if(f.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${f}`);let u=d.header.attr>>>16&61440;if(u!==0&&u!==32768&&u!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${u.toString(16)} not allowed (symlink/hardlink/special): ${f}`)}let o=JE(i),a=Md(e);for(let d of i){if(Nd(d.entryName))continue;let f=d.entryName;if(o&&f.startsWith(o)&&(f=f.slice(o.length)),!f)continue;let u=Md(e,f),x=Bd(a,u);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${f}`);if(d.isDirectory){await Dd(u,{recursive:!0});continue}await Dd(kE(u),{recursive:!0});let p;try{p=d.getData()}catch(w){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${w.message}`,{cause:w})}await Ld(u,p)}}function JE(t){let e;for(let n of t){let i=n.entryName;if(!i||Nd(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 ZE(t,e){await XE(t);let n=h0({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,n.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Vr}ms)`))},Vr);try{await oh(sh.from(t),n)}catch(a){throw a instanceof k?a:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Vr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${a.message??String(a)}`,{cause:a})}finally{clearTimeout(o)}}async function XE(t){let e=[],n=jr({onReadEntry:a=>{let d=a.path,f=a.type;if(f!=="File"&&f!=="Directory"){e.push(`tar entry kind '${f}' 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 k("IPC_BAD_REQUEST",`tar list timeout (${Vr}ms)`))},Vr);try{await oh(sh.from(t),n)}catch(a){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Vr}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 YE=5e3;async function QE(t,e,n,i){return ph(t,e,n,i,{count:0})}async function ph(t,e,n,i,o){if(i<=0)return[];let a;try{a=await rh(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let f of a){if(PE.has(f.name)||f.isSymbolicLink())continue;if(o.count>=YE){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let u=xe(e,f.name),x=TE(xe(n,f.name)),p=null;try{p=await Pd(u)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let w={name:f.name,path:gh(Bd(t,u)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(w.children=await ph(t,u,x,i-1,o)),d.push(w)}return d.sort((f,u)=>f.isDir!==u.isDir?f.isDir?-1:1:f.name.localeCompare(u.name)),d}function eb(t){return!t||t<=0?CE:Math.min(t,RE)}function tb(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function gh(t){return t.split(ih).join("/")}ne();var Fn=q("agent-health-reporter"),nb=1e4,rb=3,os=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??nb,this.livenessFailureThreshold=e.livenessFailureThreshold??rb}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()}),Fn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Fn.info("heartbeat stopped"))}async tick(){if(this.inFlight){Fn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,Fn.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 f=ib(d);if(!f)continue;let u={agentId:d.agentId,status:f};d.patToken&&(u.patToken=d.patToken),d.accountId&&(u.accountId=d.accountId),n.push(u)}if(n.length===0){this.consecutiveFailures=0;return}let i={agents:n,bridgeVersion:Kt,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,Fn.warn("heartbeat batch send failed",{count:n.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let a=o?.authFailures;if(a&&a.length>0&&(Fn.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){Fn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Fn.warn("onTickEnd hook failed",{err:String(n)})}}};function ib(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}tn();import{copyFile as Ev,cp as bv,mkdir as Qo,readFile as vv,rm as Sv,stat as $d,writeFile as Iv}from"node:fs/promises";import{homedir as tx}from"node:os";import{basename as Av,join as fn}from"node:path";vn();import{existsSync as pb}from"node:fs";import{release as gb}from"node:os";import{basename as mb,isAbsolute as wb}from"node:path";function as(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 Xr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Bn(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ze();var qo=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)}},Q={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 mh(t){return"method"in t&&"id"in t&&t.id!==void 0}function wh(t){return"method"in t&&!("id"in t)}function Go(t){return!("method"in t)&&"id"in t}var sb={AGENT_NOT_FOUND:Q.AGENT_NOT_FOUND,AGENT_BUSY:Q.AGENT_BUSY,AGENT_DISCONNECTED:Q.AGENT_DISCONNECTED,AGENT_TIMEOUT:Q.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:Q.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:Q.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:Q.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:Q.INTERNAL_ERROR,BRIDGE_INTERNAL:Q.INTERNAL_ERROR,IPC_AUTH_FAILED:Q.INTERNAL_ERROR,IPC_BAD_REQUEST:Q.INVALID_REQUEST,METHOD_NOT_FOUND:Q.METHOD_NOT_FOUND,CAPABILITY_UNSUPPORTED:Q.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:Q.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:Q.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:Q.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:Q.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:Q.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:Q.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:Q.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:Q.FILE_TOO_LARGE,UNSUPPORTED_MIME:Q.UNSUPPORTED_MIME,UPLOAD_FAILED:Q.UPLOAD_FAILED,UPSTREAM_NOT_READY:Q.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:Q.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:Q.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:Q.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:Q.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:Q.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:Q.SKILL_ZIP_TOO_LARGE};function ob(t){if(t!=null)return t instanceof Error?{name:t.name,message:cs(t.message)}:typeof t=="string"?cs(t):typeof t=="object"?cb(t):t}var ab=[[/\/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 cs(t){let e=t;for(let[n,i]of ab)e=e.replace(n,i);return e}function cb(t){let e={};for(let[n,i]of Object.entries(t))typeof i=="string"?e[n]=cs(i):e[n]=i;return e}function ds(t){if(t instanceof k){let e=ob(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:sb[t.code]??Q.INTERNAL_ERROR,message:cs(t.message),data:n}}return{code:Q.INTERNAL_ERROR,message:cs(t instanceof Error?t.message:String(t))}}function _h(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,...f}=e;a=f}return new k(n,o,{retriable:e?.retriable??!1,cause:a})}function Eh(t){return`${JSON.stringify(t)}
103
+ `}var yh=10*1024*1024,jo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>yh){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${yh} 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 vh={"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"},pR=Object.fromEntries(Object.entries(vh).map(([t,e])=>[e,t])),db={"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:[]},Yr=class{seq=0;next(e,n){this.seq+=1;let i=vh[e]??lb(e),o=db[i]??[],a=[i,String(this.seq)];if(o.length>0){let d=o.map(u=>bh(n?.[u]??"")),f=fb(d).join(":");f&&a.push(f)}else n&&Object.values(n).some(d=>d)&&a.push(Object.values(n).filter(Boolean).map(d=>bh(String(d))).join(":"));return a.join("_")}reset(){this.seq=0}};function lb(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function bh(t){return t.replace(/[:_\s]+/g,"-")}function fb(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Wt();vr();Ze();ne();Pe();import{execFileSync as ub,spawnSync as hb}from"node:child_process";function ls(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function fs(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),hb("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Ud=new Set;function Sh(t){typeof t=="number"&&t>0&&Ud.add(t)}function Ih(t){typeof t=="number"&&Ud.delete(t)}function Ah(){for(let t of Ud)fs(t,"SIGKILL")}var Qr="coze-bridge-daemon";function kh(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return ub("pgrep",["-U",String(o),"-f",Qr],{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??fs,i=e?.isAliveFn??ls,o=e?.sleepFn??(f=>new Promise(u=>setTimeout(u,f))),a=e?.graceMs??3e3,d=e?.pollMs??100;for(let f of t)n(f,"SIGTERM");for(let f=0;f<a&&t.some(u=>i(u));f+=d)await o(Math.min(d,a-f));for(let f of t)i(f)&&n(f,"SIGKILL")}var xb=[{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 Ch(t,e){if(!e)return null;for(let n of xb)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 Ch(t,e)}function Ph(t,e){return Ch(t,e)}function ei(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 Dh(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:ei(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:ei(a,!0,e)}:n-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:ei(a,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&a>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:ei(a,!1,e)}}var Oh=Je("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",6e4),_b=200,yb=40,Eb=Je("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),bb=Je("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),vb=Je("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Sb=Je("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Ib=Je("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Ab=Je("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Lh=500,kb=process.env.COZE_BRIDGE_TRACE_RPC==="1",Mh=Je("COZE_BRIDGE_TRACE_RPC_MAX",2e3);function Tb(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Lh?t:`${e.slice(0,Lh)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Cb(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 Nh(t){try{return pb(t)}catch{return}}function Rb(t,e){return{platform:process.platform,osRelease:gb(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:wb(e.command)?Nh(e.command):void 0,cwd:e.cwd,cwdExists:Nh(e.cwd),envKeys:e.envKeys}}function Pb(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${mb(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var St=class{constructor(e){this.opts=e;this.log=q(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new jo({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Yr;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=Lo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=dt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,Sh(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>_b&&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,Ih(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 f of this.decoder.flush())this.dispatch(f)}catch(f){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(f)})}this.failAllPending(this.buildExitError(o,a));for(let f of this.exitHandlers)f(o,a)}),i.on("error",o=>{let a=o,d=Rb(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",Pb(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()));fs(n.pid,"SIGTERM");let o=setTimeout(()=>{n.killed||fs(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:Ib,phase2GateMs:Eb,livenessWindowMs:bb,absoluteMaxMs:vb,approvalMaxMs:Ab,suspendThresholdMs:Sb,...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)}configIdFor(e){return e==="model"?"model":null}sendSetConfigOption(e,n,i){return this.call("session/set_config_option",{sessionId:e,configId:n,value:i}).then(()=>{})}setConfigOption(e,n,i){let o=this.configIdFor(n);return o===null?Promise.reject(new k("CAPABILITY_UNSUPPORTED",`${this.framework} does not support axis '${n}'`)):this.sendSetConfigOption(e,o,i)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Xr(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(Bn(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 k("AGENT_PROTOCOL_ERROR","downstream not started"));let a=this.idAllocator.next(e),d=as(a,e,n),f=(()=>{if(typeof n!="object"||n===null)return;let u=n.sessionId;return typeof u=="string"?u:void 0})();return new Promise((u,x)=>{let p={resolve:u,reject:x,timer:null,method:e,promptTimeout:null};if(o){let w=this.now(),b={cfg:o,startedAt:w,lastActivityAt:w,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:w,expectedIntervalMs:ei(0,!1,o),sessionId:f};p.promptTimeout=b;let _=()=>{let v={startedAt:b.startedAt,lastActivityAt:b.lastActivityAt,firstFrameSeen:b.firstFrameSeen,hasActiveTool:b.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:b.suspendedMs,armedAt:b.armedAt,expectedIntervalMs:b.expectedIntervalMs},I=this.now(),A=Dh(v,b.cfg,I),T=R=>{b.armedAt=I,b.expectedIntervalMs=R,p.timer=setTimeout(_,R)};if(A.action==="suspend"){b.suspendedMs+=A.suspendedDeltaMs,b.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:a,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:b.suspendedMs,...b.sessionId?{sessionId:b.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(a),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:a,method:e,awaitingApproval:A.awaitingApproval,...b.sessionId?{sessionId:b.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${b.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${b.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:a,method:e,...b.sessionId?{sessionId:b.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${b.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(_,b.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(a),this.log.warn("downstream call timeout",{id:a,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(a,p);try{this.writeFrame(d)}catch(w){p.timer&&clearTimeout(p.timer),this.pending.delete(a),x(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.traceFrame("->",e),this.child.stdin.write(Eh(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}traceFrame(e,n){if(!kb)return;let i=n,o;try{let a=JSON.stringify(n);o=a===void 0||a.length<=Mh?n:`${a.slice(0,Mh)}...<truncated, total ${a.length} chars>`}catch{o="<unserializable>"}this.log.info(`rpc ${e}`,{dir:e,method:i.method,id:i.id,frame:o})}dispatch(e){if(this.traceFrame("<-",e),Go(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:Tb(e.result)}),n.resolve(e.result));return}if(wh(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(mh(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,f=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!f?e.activeToolCalls.add(a):f&&e.activeToolCalls.delete(a)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Bn(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(Bn(e.id,ds(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let n=_h(e);if(n.code!=="AGENT_PROTOCOL_ERROR")return n;let i=Ph(this.framework,Cb(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(yb).join(`
106
+ `),o=Rh(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 Db(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 Wo=class extends St{framework="claude-code";constructor(e){let{command:n,args:i}=bi("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 Db(e)}configIdFor(e){return e==="model"?"model":e==="effort"?"effort":null}};vn();import{spawn as Ob}from"node:child_process";import{closeSync as Lb,existsSync as Gd,mkdirSync as Mb,mkdtempSync as Nb,openSync as Fb,readFileSync as Gh,readSync as Bb,readdirSync as zb,rmSync as Ub,statSync as Hb}from"node:fs";import{homedir as qb,tmpdir as Gb}from"node:os";import{join as ti}from"node:path";var Fh=["default","acceptEdits","plan","auto","bypassPermissions"],Bh=["read-only","auto","full-access"];var zh=["default","accept_edits","dont_ask"];function $t(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return Fh.includes(e);case"codex":return Bh.includes(e);case"hermes":return zh.includes(e);case"openclaw":return!1}}function Ko(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}function Uh(t){switch(t){case"read-only":return"read-only";case"agent":return"auto";case"agent-full-access":return"full-access";default:return}}function Hd(t){switch(t){case"claude-code":return Fh.join("/");case"codex":return Bh.join("/");case"hermes":return zh.join("/");case"openclaw":return""}}Pe();var jd=9e4,jb=64*1024,Wb=100;function Kb(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?jd:Math.max(1,Math.floor(e*1e3))}function $b(t){let e=typeof t=="number"?t:typeof t=="string"?Number.parseFloat(t):Number.NaN;return!Number.isFinite(e)||e<=0?jd:Math.max(1,Math.floor(e))}function Vb(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:jd};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=Vb(e.env);return{command:n,timeoutMs:e.timeout_ms===void 0?Kb(e.timeout):$b(e.timeout_ms),...i?{cwd:i}:{},...o?{env:o}:{}}}function qd(t){if(Array.isArray(t))return t.flatMap(i=>qd(i));if(!t||typeof t!="object"){let i=Hh(t);return i?[i]:[]}let e=t;if(e.hooks)return qd(e.hooks);let n=Hh(e);return n?[n]:[]}function Jb(t){let e=ti(t,"hooks.json");if(!Gd(e))return[];let n=JSON.parse(Gh(e,"utf8")),o=n.hooks&&typeof n.hooks=="object"?n.hooks:n;return qd(o.Stop??o.stop)}function Zb(t,e){let n=ti(t,"sessions");if(!Gd(n))return;let i=[],o=a=>{let d;try{d=zb(a,{withFileTypes:!0})}catch{return}for(let f of d){let u=ti(a,f.name);if(f.isDirectory())o(u);else if(f.isFile()&&f.name.endsWith(".jsonl"))try{i.push({path:u,mtimeMs:Hb(u).mtimeMs})}catch{}}};o(n),i.sort((a,d)=>d.mtimeMs-a.mtimeMs);for(let a of i.slice(0,Wb))if(Xb(a.path,e))return a.path}function Xb(t,e){let n;try{n=Fb(t,"r");let i=Buffer.alloc(jb),o=Bb(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{Lb(n)}catch{}}}function Yb(t){return ar(t??Z().agentEnvFile)}function Qb(t){let e=t.trim();if(e.length>=2){let n=e[0];if((n==='"'||n==="'")&&e.endsWith(n)){let i=e.slice(1,-1);return n==='"'?i.replace(/\\n/g,`
107
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i.replace(/\\'/g,"'")}}return e.replace(/\s+#.*$/,"")}function ev(t){let e={};for(let n of t.split(/\r?\n/)){let i=n.trim();if(!i||i.startsWith("#"))continue;let 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]=Qb(o.slice(a+1)))}return e}function tv(t){let e=ti(t,"cozeloop.env");return Gd(e)?ev(Gh(e,"utf8")):{}}function qh(t){let e=t?.trim();return e||void 0}function nv(t){let e=Yb(t.agentEnvFile),n=qh(t.env?.CODEX_HOME??e.CODEX_HOME??process.env.CODEX_HOME);if(n)return n;let i=qh(t.env?.HOME??e.HOME??process.env.HOME)??qb();return ti(i,".codex")}var $o=class extends St{framework="codex";authMethodId;codexHomeDir;cleanupCodexHomeDir;fastMode;constructor(e){let n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,{command:o,args:a}=bi("codex",e.command,i),d=e.isolateCodexHome?e.codexHomeDir??e.env?.CODEX_HOME??Nb(ti(Gb(),"coze-bridge-codex-home-")):nv(e),f=!!e.isolateCodexHome&&!!d&&!e.codexHomeDir&&e.env?.CODEX_HOME!==d;e.isolateCodexHome&&d&&!f&&Mb(d,{recursive:!0});let u=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}:{},...u?{env:u}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=d,this.cleanupCodexHomeDir=f,this.fastMode=e.fastMode}configIdFor(e){return e==="model"?"model":e==="effort"?"reasoning_effort":e==="fastMode"?"fast-mode":null}async afterSessionEstablished(e){if(this.fastMode)try{await this.setConfigOption(e,"fastMode",this.fastMode)}catch(n){this.log.warn("codex fast-mode post-establish failed (ignored)",{sessionId:e,err:String(n)})}}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async sessionPrompt(e){let n=await super.sessionPrompt(e);return this.runStopHooksBestEffort(e.sessionId).catch(i=>{this.log.warn("codex stop hook unexpected failure",{err:String(i)})}),n}setSessionMode(e){let n=$t("codex",e.modeId)?Ko(e.modeId):e.modeId;return super.setSessionMode({...e,modeId:n})}onUpdate(e){super.onUpdate(n=>e(rv(n)))}async runStopHooksBestEffort(e){let n=this.codexHomeDir??this.opts.env?.CODEX_HOME;if(!n)return;let i;try{i=Jb(n)}catch(d){this.log.warn("codex stop hook load failed",{codexHomeDir:n,err:String(d)});return}if(i.length===0)return;let o=Zb(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(f){this.log.warn("codex stop hook failed",{codexHomeDir:n,command:d.command.slice(0,200),err:String(f)})}}))}runHookCommand(e,n){return new Promise((i,o)=>{let a=this.codexHomeDir??this.opts.env?.CODEX_HOME,d=a?tv(a):{},f=Lo(process.env,this.opts.agentEnvFile??Z().agentEnvFile,{...this.opts.env??{},...d,...e.env??{}});this.opts.env?.COZELAB_ONBOARD_CLOUD==="true"&&f.COZE_API_TOKEN&&(f.COZELOOP_API_TOKEN=f.COZE_API_TOKEN);let u=Ob(e.command,{cwd:e.cwd??this.opts.cwd,env:f,shell:!0,stdio:["pipe","ignore","pipe"]}),x="",p=setTimeout(()=>{u.kill("SIGTERM"),o(new Error(`hook timed out after ${e.timeoutMs}ms`))},e.timeoutMs);u.stderr?.setEncoding("utf8"),u.stderr?.on("data",w=>{x+=w,x.length>4e3&&(x=x.slice(-4e3))}),u.on("error",w=>{clearTimeout(p),o(w)}),u.on("close",(w,b)=>{if(clearTimeout(p),w===0){i();return}o(new Error(`hook exited code=${w} signal=${b} stderr=${x.slice(-1e3)}`))}),u.stdin.end(`${n}
108
+ `)})}async stop(e){if(await super.stop(e),this.codexHomeDir&&this.cleanupCodexHomeDir)try{Ub(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};function rv(t){let e=t.update;if(e.sessionUpdate!=="current_mode_update"||typeof e.currentModeId!="string")return t;let n=Uh(e.currentModeId);return!n||n===e.currentModeId?t:{...t,update:{...t.update,currentModeId:n}}}ne();var iv=q("hermes-downstream"),Vo=class extends St{framework="hermes";modelId;constructor(e){let n={command:e.command,args:[],cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(n),e.modelId&&(this.modelId=e.modelId)}async afterSessionEstablished(e){if(this.modelId)try{await this.setConfigOption(e,"model",this.modelId)}catch(n){iv.warn("hermes model post-establish failed (ignored)",{sessionId:e,modelId:this.modelId,err:String(n)})}}setConfigOption(e,n,i){return n==="model"?this.setSessionModel({sessionId:e,modelId:i}).then(()=>{}):super.setConfigOption(e,n,i)}};Ze();var jh=3e4,ni=class extends St{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}`}]},jh))}get acpSessionName(){return this.sessionName}async setConfigOption(e,n,i){if(n!=="model")throw new k("CAPABILITY_UNSUPPORTED",`openclaw does not support axis '${n}'`);await this.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${i}`}]},jh)}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};Ct();Ze();ne();Pe();function Wd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}vn();var Vt=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((n,i)=>{this.slots.push({task:e,resolve:n,reject:i}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let n=await e.task();e.resolve(n)}catch(n){e.reject(n)}}}finally{this.running=!1}}}};var Jo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;effort;fastMode;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo),e.effort&&(this.effort=e.effort),e.fastMode&&(this.fastMode=e.fastMode)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}setEffort(e){this.effort=e}setFastMode(e){this.fastMode=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new Vt,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)ri(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 ri(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function ln(t){return t.framework==="hermes"?!0:t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Wt();ne();import{constants as Wh}from"node:fs";import{access as sv,readFile as ov}from"node:fs/promises";import{delimiter as av,dirname as cv,join as Kh}from"node:path";var it=q("framework-detector"),$h={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes-acp"},dv=[".exe",".cmd",".bat",".ps1"],lr=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??dt,access:e.access??sv,readFile:e.readFile??ov}}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)]),f={path:i,version:a};return d&&(f.defaultAgent=d),f}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(av).filter(Boolean),i=this.env.platform==="win32"?["",...dv]:[""];for(let o of n)for(let a of i){let d=Kh(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=Kh(cv(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&&(fv(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(i=>{let o="",a=!1,d,f=u=>{a||(a=!0,d&&clearTimeout(d),i(u))};try{let u=this.env.spawn(e,n,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{u.kill("SIGKILL"),f(null)},15e3),u.stdout?.on("data",x=>{o+=x.toString("utf8")}),u.on("error",()=>f(null)),u.on("close",x=>f({code:x,stdout:o}))}catch{f(null)}})}},lv=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function fv(t){return t.replace(lv,"")}import{homedir as Jh}from"node:os";import{join as Xo}from"node:path";Ct();Wt();vr();Ze();ne();async function Zh(){let t=Xo(Jh(),".openclaw/openclaw.json");return Ye(t)}async function Xh(){return(await Zh())?.gateway?.auth?.token??""}var fr=q("openclaw.config"),uv=[0,5e3,5e3],hv=Je("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),Vh="models.providers.",Zo="agents.defaults.models",xv=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];function ii(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 Yo=class{command;env;retryDelaysMs;cliTimeoutMs;openclawDir;queue=new Vt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??uv,this.cliTimeoutMs=e.cliTimeoutMs??hv,this.openclawDir=e.openclawDir??Xo(Jh(),".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,fr.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=dt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),a="",d=!1,f=x=>{d||(d=!0,clearTimeout(u),x())};o.stderr?.on("data",x=>{a+=x.toString("utf8")});let u=setTimeout(()=>{f(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);u.unref(),o.on("error",x=>f(()=>i(x))),o.on("close",x=>f(()=>{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){fr.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",`${Vh}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Vh}${e}`)}addModelToAllowlist(e,n){let i={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Zo}[${e}]`,()=>this.runCli(["config","set",Zo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Zo}[${e}]`,`${Zo}.${e}`)}async getAllowlistModelsForProvider(e){let i=(await Zh())?.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=Xo(this.openclawDir,"identity","device.json"),i=(await Ye(e))?.deviceId?.trim();if(!i)return fr.debug("openclaw device identity absent, skip acp scope ensure",{identityPath:e}),!1;let o=Xo(this.openclawDir,"devices","paired.json"),a=await Ye(o),d=a?.[i];if(!a||!d)return fr.debug("acp device not yet paired, skip scope ensure",{deviceId:i}),!1;let f=d.tokens?.operator,u=ii(ii(d.scopes,d.approvedScopes??[]),f?.scopes??[]).filter(v=>v.startsWith("operator.")),x=ii([...xv],u),p=ii(d.scopes,x),w=ii(d.approvedScopes,x),b=f?ii(f.scopes,x):void 0;return p.length!==(d.scopes?.length??0)||w.length!==(d.approvedScopes?.length??0)||f!==void 0&&b?.length!==(f.scopes?.length??0)?(d.scopes=p,d.approvedScopes=w,f&&b&&(f.scopes=b),await ut(o,a,{mode:384}),fr.info("acp device scopes upgraded to full operator set (bypass manual approval)",{deviceId:i,scopes:x}),!0):(fr.debug("acp device already has full operator scopes",{deviceId:i}),!1)}catch(e){return fr.warn("ensureAcpDeviceScopes failed (ignored, best-effort)",{err:String(e)}),!1}}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}};import{readFile as pv,writeFile as gv}from"node:fs/promises";import{join as mv}from"node:path";var wv=["```markdown","# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.","```","","## Related","","- [Heartbeat config](/gateway/config-agents)",""].join(`
109
+ `),_v=["# Keep this file empty (or with only comments) to skip heartbeat API calls.","","# Add tasks below when you want the agent to check something periodically.",""].join(`
110
+ `);function yv(t){return t.length===0?t:`${(t.endsWith(`
111
111
  `)?t.slice(0,-1):t).split(`
112
- `).map(s=>s.endsWith("\r")?s.slice(0,-1):s).join(`
112
+ `).map(o=>o.endsWith("\r")?o.slice(0,-1):o).join(`
113
113
  `)}
114
- `}async function Vh(t){let e=mE(t,"HEARTBEAT.md"),n=await pE(e,"utf8");return yE(n)!==wE?!1:(await gE(e,_E),!0)}var re=G("agent-manager"),kE=["hooks.json","cozeloop.env"],CE=["hooks"];async function TE(t,e){let n=ln(De(t,e).root,"codex-home"),i=ln(Yh(),".codex");if(n!==i){await $o(n,{recursive:!0});for(let s of CE){let a=ln(i,s),d=ln(n,s);try{await Gd(d);continue}catch{}try{await vE(a,d,{recursive:!0,errorOnExist:!0,filter:u=>{let h=AE(u);return!h.endsWith(".log")&&!h.includes(".bak")}}),re.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}for(let s of kE){let a=ln(i,s),d=ln(n,s);try{await Gd(d);continue}catch{}try{if(s==="cozeloop.env"){let h=(await EE(a,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
115
- `);await IE(d,h,{mode:384})}else await bE(a,d);re.info("migrated legacy Codex state",{agentId:t,name:s})}catch(u){u.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:s,err:String(u)})}}}}var qd="acceptEdits",Xh="full-access",Qh="read-only";function PE(t){return{INITIAL_AGENT_MODE:Uo(t)}}var DE=(t,e,n,i,s,a,d,u,h,x,p,w)=>{switch(t){case"claude-code":{let b={...s?{...L0(s),...B0(s,d,u,w)}:{},...h??{},IS_SANDBOX:"1"};return new zo({cwd:n,env:b,agentId:i})}case"codex":{let b=Xh;x!==void 0&&(Wt("codex",x)?b=x:re.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let y=!!s?.modelToken,v={...s?{...N0(s),...M0(s,d,u,w)}:{},...PE(b),...y?{NO_BROWSER:"1"}:{},...h??{},...y?{COZELAB_ONBOARD_CLOUD:"true"}:{}};return new Ho({cwd:n,agentId:i,...Object.keys(v).length>0?{env:v}:{},...s?.fastMode?{fastMode:s.fastMode}:{},...y?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new Xr({command:e,cwd:n,agentId:i,...a?{sessionName:Ud(a)}:{}});case"hermes":return new Go({command:e,cwd:n,agentId:i,...h&&Object.keys(h).length>0?{env:{...h}}:{},...s?.model&&!vt(s.model)?{modelId:s.model}:{}})}};function Hd(t){return t==="claude-code"||t==="codex"}var RE={path:"",version:"cloud-deployed"},Jh="openclaw_gateway_unavailable",OE="openclaw_default_agent_missing";function Zh(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 LE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},ME=6e4,Vo=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??DE,this.createTimeoutMs=e.createTimeoutMs??ME,this.detectorFactory=e.detectorFactory??(()=>new ar),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Ko({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??ln(Yh(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{re.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=ln(e,".env");if(await Gd(n).then(a=>a.isFile()).catch(()=>!1)){re.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let s=Zi({...process.env,...ir(this.paths.agentEnvFile)});await _t(n,s,{mode:384}),re.info("openclaw .env bootstrapped",{envFile:n,bytes:s.length}),await this.getOpenclawConfig().restartGateway(),re.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 ge(e.agentId,this.paths).catch(()=>null),s=nr(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")re.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(C=>re.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else if(s&&a.deployType!=="cloud")re.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(C=>re.warn("dispose drifted agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){re.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let C=await ge(e.agentId,this.paths).catch(()=>null);C&&(C.patToken=e.patToken,await Re(C,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){re.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let C=await ge(e.agentId,this.paths).catch(()=>null);C&&(C.modelInfo=e.modelInfo,await Re(C,this.paths))}return re.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}}if(!s&&!this.config.frameworksCache?.[e.framework]){let 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=De(e.agentId,this.paths),h=s?"cloud":"local",x=e.framework==="openclaw"&&h==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),b=e.workspace??w??u.workspace,y=new AbortController,v=setTimeout(()=>y.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{s&&Hd(e.framework)&&await Er(e.framework,y.signal);let C=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await $o(u.root,{recursive:!0}),await $o(b,{recursive:!0}),await $o(u.logs,{recursive:!0}),C(),x||await Sr(b,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(h==="cloud"?await ic(b,"cloud"):await ic(b,"local",qd)),C();let P=i,E=O0({model:e.model??P?.model}),D=l0(e._meta)??P?.accountId,O=e.patToken??P?.patToken,U=h==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new qo({agentId:e.agentId,framework:e.framework,workspace:b,model:E.model??Lt,deployType:h,...D?{accountId:D}:{},...O?{patToken:O}:{},...U?{modelInfo:U}:{}}),I.status="ok",P?.sessions){let V=e.framework==="hermes"||h==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[X,oe]of Object.entries(P.sessions)){let de={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?oe.permissionMode===void 0?(de.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",re.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:X,framework:e.framework,fallback:de.permissionMode})):Wt(e.framework,oe.permissionMode)?de.permissionMode=oe.permissionMode:re.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:X,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&re.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:X,framework:e.framework,deployType:h}),oe.cozeGroupId&&(de.cozeGroupId=oe.cozeGroupId),oe.tokenGroupId&&(de.tokenGroupId=oe.tokenGroupId),oe.requestScene&&(de.requestScene=oe.requestScene),I.sessions.set(X,de)}let ie=Object.keys(P.sessions).length;ie>0&&re.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(I),A=!0,n?.revive||this.registry.warmupModelList?.(I);let M={agentId:e.agentId,framework:e.framework,workspace:b,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:E.model};if(h==="cloud"&&(M.deployType="cloud"),D&&(M.accountId=D),O&&(M.patToken=O),U&&(M.modelInfo=U),P?.skills&&(M.skills=P.skills),P?.agentName&&(M.agentName=P.agentName),P?.description&&(M.description=P.description),M.skillsRefreshedForVersion=P?.skillsRefreshedForVersion??jt,e.framework==="openclaw"&&h==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,b)):re.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Vh(b)&&re.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:b})}catch(V){re.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:b,err:String(V)})}}let K=e.initialSkills??[];if(K.length>0){let V=[...M.skills??[]],ie=new Map(V.map((de,ye)=>[de.skillId,ye])),X=await Promise.allSettled(K.map(de=>Lo({agentId:e.agentId,workspace:b,framework:e.framework,skill:de,paths:this.paths}))),oe=0;for(let[de,ye]of X.entries()){let ze=K[de];ze&&(ye.status==="fulfilled"?(Mo(V,ie,ye.value),oe++):re.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:ze.skillId,skillName:ze.skillName,err:String(ye.reason)}))}oe>0&&(M.skills=V,re.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:K.length}))}return await Re(M,this.paths),re.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:b,framework:e.framework}}catch(C){throw re.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),re.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:C instanceof Error?C.stack:String(C)}),await SE(u.root,{recursive:!0,force:!0}).catch(P=>re.warn("rm agent dir failed (ignored)",{err:String(P)})),C instanceof k?C:new k("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,s,a,d){let h=this.config.frameworksCache?.[e.framework];if(!h)if(e.deployType==="cloud"&&Hd(e.framework))h=RE;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`);Hd(e.framework)&&!Rs(e.framework)&&(re.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await Er(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:R0({model:e.model,effort:e.effort,fastMode:e.fastMode}),p;if(e.framework==="openclaw")p=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:s,mockScenario:a,requestScene:d,command:h.path});else if(e.framework==="hermes"){let w={...this.buildBinShimPathEnv()};x?.modelToken&&(await q0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:s,mockScenario:a}),w.HERMES_HOME=or(e.agentId,this.paths)),p=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,s,a,w)}else{let w=e.sessions.get(i),b=dn(e)?w?.permissionMode??Xh:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await TE(e.agentId,this.paths),p=this.factory(e.framework,h.path,e.workspace,e.agentId,x,i,s,a,this.buildBinShimPathEnv(),b,e.framework==="codex"&&e.deployType==="cloud"?ln(De(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await p.start(),await p.initialize(LE),p}catch(w){let b=p instanceof St?p.getStderrTail():[];throw b.length>0&&re.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof k?w.code:"unknown",recentStderr:b}),await p.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,h.path,w)}}async resolveSpawnFailure(e,n,i){if(e.framework==="openclaw"&&e.deployType==="local"&&n)try{let s=await this.detectorFactory().probeOpenclawGateway(n);if(!s.reachable)return new k("AGENT_ENV_NOT_READY",Zh(s),{cause:{reason:Jh}})}catch(s){re.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(s)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};re.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 re.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:OE}})}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",Zh(n),{cause:{reason:Jh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:s,cozeEnv:a,mockScenario:d,requestScene:u,command:h}=e,x=Ud(s);if(n.deployType==="local"){let b=await this.ensureOpenclawDefaultAgent(),y=i&&!vt(i.model)?i.model:void 0;return new Xr({command:h,cwd:b.workspace,agentId:b.id,sessionName:x,...y?{slashModelOnStart:y}:{}})}let p=await $h();try{let b=this.getOpenclawConfig();await b.ensureAcpDeviceScopes()&&await b.restartGateway()}catch(b){re.warn("acp device scope ensure failed (ignored)",{err:String(b)})}let w;if(i?.modelToken){let b=bd(s),y=vd(i),v=`${b}/${y}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:u});if(this.ensuredProviders.get(v)!==I){let A=this.getOpenclawConfig(),C=await A.getAllowlistModelsForProvider(b),P=F0(i,a,d,C,u);P&&(await A.ensureProvider(b,P),await A.addModelToAllowlist(v),this.ensuredProviders.set(v,I))}w=v}else i&&!vt(i.model)&&(w=i.model);return new Xr({command:h,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...w?{slashModelOnStart:w}:{}})}async openclawRepair(e,n){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e,n){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache,s=n??e.model;for(let a of e.sessions.keys()){let d=bd(a),u=`${d}/${s}`,h=!0;try{await i.removeProvider(d)}catch(x){h=!1,re.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(u)}catch(x){h=!1,re.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:u,err:String(x)})}h&&this.ensuredProviders.delete(u)}}};import{randomUUID as ix}from"node:crypto";import{promises as GE}from"node:fs";import{basename as sx}from"node:path";Ve();ne();import{promises as NE}from"node:fs";import{basename as BE}from"node:path";var ex=G("file-upload"),FE="/api/coze_claw/file/agent_upload",zE=6e4;async function tx(t,e={}){let i=`${Hr(Gr(e.handshakeBase))}${FE}`,s=e.timeoutMs??zE,a=await NE.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([a],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...On(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},h=new AbortController,x=setTimeout(()=>h.abort(),s);ex.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:h.signal}),w=p.headers.get("x-tt-logid")??"";if(!p.ok){let v=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${w}: ${v.slice(0,200)}`)}let b=await p.json();if(b.code!==void 0&&b.code!==0)throw new k("UPLOAD_FAILED",`upload code=${b.code} msg=${b.msg??"-"} logid=${w}`);let y=b.data?.file?.file_url;if(!y)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(b).slice(0,200)}`);return ex.info("file upload ok",{uri:y,logid:w}),{uri:y}}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${s}ms) for ${BE(t.path)}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Ve();ne();import{extname as UE}from"node:path";var HE={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function nx(t){let e=UE(t).toLowerCase();return HE[e]??"application/octet-stream"}Ce();var Jo=G("agent-send"),rx=50*1024*1024;function ox(t,e,n){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let s=i.sessions.get(n);if(!s)throw new k("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:i,runtime:s}}async function ax(t,e,n,i,s,a){let u;for(let h=0;h<=2;h++)try{await t.core.sendAgentFileUpdate(e,n,i,s);return}catch(x){u=x,h<2&&(Jo.warn("sendAgentFileUpdate failed, retrying",{attempt:h+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(u)}`,{cause:u})}async function cx(t,e){let{session:n,runtime:i}=ox(e.core,t.agentId,t.sessionId);if(!await wi(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let s=await GE.stat(t.path).catch(()=>null);if(!s||!s.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(s.size>rx)throw new k("FILE_TOO_LARGE",`${s.size} bytes > limit ${rx}`);let a=await nx(t.path);if(t.kind==="image"&&!a.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${a}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??sx(t.path),u;try{u=await tx({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:a,name:d,sizeBytes:s.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw Jo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:s.size,mime:a,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let h={sessionUpdate:"agent_file",messageId:ix(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:a,name:d,sizeBytes:s.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await ax(e,n,i,t.sessionId,h,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Jo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:s.size,mime:a,uri:u.uri}),{ok:!0,uri:u.uri,bytes:s.size,mimeType:a,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function dx(t,e){let{session:n,runtime:i}=ox(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let s=t.name??sx(t.path),a={sessionUpdate:"group_file",messageId:ix(),content:{uri:t.path,name:s,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await ax(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),Jo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:s,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function lx(t,e){let n=t.split(".").map(Number),i=e.split(".").map(Number),s=Math.max(n.length,i.length);for(let a=0;a<s;a++){let d=n[a]??0,u=i[a]??0;if(d<u)return!0;if(d>u)return!1}return!1}an();ne();yn();var $t=G("coze-cli-installer"),ux="@coze/cli@latest",qE="coze",fx="0.1.8",jE=5e3,WE=5e3,KE=9e4,hx=1e4,as=null,Zo=!1;async function Wd(t,e={}){if(Zo)return;if(as)return as;let n=e.exec??E0;return as=(async()=>{try{let i=await $E(qE,n),s=!1;if(i){let d=await VE(n);if(d===void 0)$t.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(lx(d,fx))$t.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:fx}),s=!0;else{$t.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Zo=!0;return}}let a=s?"upgrade-only":"full";$t.info("coze-cli install start",{package:ux,mode:a});try{await n("npm",["i","-g","--prefer-online",ux],{timeout:KE,maxBuffer:10*1024*1024}),$t.info("coze-cli install ok")}catch(d){$t.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(s){Zo=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:hx}),$t.info("coze config set xTTEnv ok",{env:t.env})}catch(d){$t.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:hx}),$t.info("coze auth login ok")}catch(d){$t.warn("coze auth login failed",{err:String(d)});return}Zo=!0}finally{as=null}})(),as}async function $E(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:jE});return nc(i)}catch{return}}async function VE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:WE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Ct();var Yo=class{cacheFilePath;memory=new Map;runtimeCurrent=new Map;writeQueue=new Kt;constructor(e){this.cacheFilePath=e}async loadFromDisk(){if(!this.cacheFilePath)return;let e=await Ze(this.cacheFilePath);if(e)for(let[n,i]of Object.entries(e))i&&this.memory.set(n,i)}get(e){return this.memory.get(e)}update(e,n){return this.writeQueue.enqueue(async()=>{let i=J0(n),s=this.memory.get(e);if(s&&s.hash===i){if(s.cachedAt=Date.now(),n.defaultModelId&&s.defaultModelId!==n.defaultModelId){if(s.defaultModelId=n.defaultModelId,this.cacheFilePath){let u=await Ze(this.cacheFilePath)??{};u[e]=s,await ft(this.cacheFilePath,u)}return!0}return!1}let a={cachedAt:Date.now(),hash:i,models:n.models,...n.defaultModelId?{defaultModelId:n.defaultModelId}:{},...n.effortLevels?{effortLevels:n.effortLevels}:{},...n.fastModes?{fastModes:n.fastModes}:{}};if(this.memory.set(e,a),!this.cacheFilePath)return!0;let d=await Ze(this.cacheFilePath)??{};return d[e]=a,await ft(this.cacheFilePath,d),!0})}setRuntimeCurrent(e,n){let i=this.runtimeCurrent.get(e)??{};this.runtimeCurrent.set(e,{...i,...n.model!==void 0?{model:n.model}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.fastMode!==void 0?{fastMode:n.fastMode}:{}})}getRuntimeCurrent(e){return this.runtimeCurrent.get(e)}};Qt();Ct();Ce();var JE=10*6e4;function xx(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?JE:e}function Xo(t){return Ze(t??Z().configFile)}function cs(t,e){return ft(e??Z().configFile,t)}import{randomBytes as pS}from"node:crypto";_r();Ve();ne();import{createReadStream as ZE}from"node:fs";import{mkdir as YE,readFile as XE,realpath as QE,stat as eS,writeFile as tS}from"node:fs/promises";import{basename as nS,dirname as Kd,isAbsolute as rS,join as iS,relative as sS,resolve as px,sep as oS}from"node:path";import{createInterface as aS}from"node:readline";var mx=G("fs-rpc"),ds=$e("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function _x(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>ds)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${ds} bytes`);let i=await bx(t.path,e);return await YE(Kd(i),{recursive:!0}),await tS(i,t.content,"utf8"),mx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function yx(t,e){let n=await bx(t.path,e),i=await eS(n),s=typeof t.line=="number"||typeof t.limit=="number";if(i.size>ds&&!s)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${ds} bytes`);let a;if(s&&i.size>ds)a=await cS(n,t.line??1,t.limit);else{let d=await XE(n,"utf8");if(s){let u=d.split(`
116
- `),h=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?h+t.limit:void 0;a=u.slice(h,x).join(`
117
- `)}else a=d}return mx.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function cS(t,e,n){let i=aS({input:ZE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),s=Math.max(0,e-1),a=typeof n=="number"?s+n:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let h of i)if(u>=s&&u<a&&d.push(h),u++,u>=a)break}finally{i.close()}return d.join(`
118
- `)}async function bx(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[n,i]=await Promise.all([gx(px(e)),gx(px(t))]),s=sS(n,i);if(dS(s,oS,rS(s)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function dS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function gx(t){let e=[],n=t;for(;n!==Kd(n);)try{let i=await QE(n);return e.length?iS(i,...e.reverse()):i}catch{e.push(nS(n)),n=Kd(n)}return t}ne();var vx=G("prompt-multimodal"),Ex=10*1024*1024,lS=15e3,uS=6;async function Sx(t){let e=new Array(t.length),n=0;async function i(){for(;n<t.length;){let a=n++,d=t[a];d!==void 0&&(e[a]=await fS(d))}}let s=Array.from({length:Math.min(uS,t.length)},()=>i());return await Promise.all(s),e}function Ix(t){return t.some(e=>e.type==="image")}async function fS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ji(e.uri))return t;try{let{buf:n,contentType:i}=await xS(e.uri),s=e.mimeType||hS(i)||"application/octet-stream";return vx.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:s}),{type:"image",data:n.toString("base64"),mimeType:s}}catch(n){return vx.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function hS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function xS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),lS);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let s=await i.arrayBuffer();if(s.byteLength>Ex)throw new Error(`image too large: ${s.byteLength} bytes (max ${Ex})`);return{buf:Buffer.from(s),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Qt();Ve();ne();var W=G("core"),gS=3e4,mS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,wS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",_S="\u5BA1\u6279\u5DF2\u8D85\u65F6",yS=3e4,bS="__model_warmup__",Qo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Vr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;modelListCache;openclawModelLister;modelListWarmupInFlight=new Set;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=xx(e.bridgeConfig),this.modelListCache=e.modelListCache,this.openclawModelLister=e.openclawModelLister}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(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(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),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,i){let s=i.downstream;s&&(s.onUpdate(a=>{i.loadingSession||this.forwardUpdate(e,a)}),s.onAgentRequest(a=>{this.handleAgentRequest(e,s,a)}),s.onExit((a,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),Qr(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(s,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let i=[];for(let[s,a]of this.pendingUpstream)a.downstream===e&&i.push(s);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:i.length});for(let s of i){let a=this.pendingUpstream.get(s);if(a){this.pendingUpstream.delete(s),this.upstream.send(Mn(s,{code:Q.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:Q.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Q.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(Bo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&mS.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let s=e.params,a=u0(s?._meta),d=s?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let u=this.requestSceneBySession.get(d);a&&u!==a?(this.requestSceneBySession.set(d,a),W.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&u!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let u=this.extensions[e.method];if(!u){n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let h=await u(e,this);n!==null&&await this.upstream.send($r(n,h));return}if(e.method.startsWith("session/")){let u=await this.routeSessionMethod(e);n!==null&&await this.upstream.send($r(n,u));return}if(e.method==="initialize"){n!==null&&await this.upstream.send($r(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(u){W.error("handleFrame failed",{method:e.method,err:String(u)}),n!==null&&await this.upstream.send(Mn(n,is(u)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,i=n._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(i);if(!s)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let a=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!a)return this.dispatchSessionCall(s,e.method,n);if(e.method==="session/prompt"){let h=s.sessions.get(a);if(h?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,p=Ao(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:s.agentId,cloudSessionId:a}),this.synthesizePromptReply(s,h,a,wS,x,p)}}let d=Date.now(),u=!1;try{let h=await s.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(s,e.method,n));return u=!0,h}finally{W.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:s}=h0(i);switch(n){case"session/new":{let a=vS();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=s;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:a.sessionId}),{}}case"session/prompt":{let a=s,d=a.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=dn(e)?f0(i._meta):void 0;if(u!==void 0&&!Wt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Nd(e.framework)}`);let h=Ao(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,h,x);if(u!==void 0&&p.permissionMode===void 0&&(p.permissionMode=u,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==u){let y=p.permissionMode;p.permissionMode=u,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:u})}catch(v){throw p.permissionMode=y,await this.persistSessionMapping(e).catch(()=>{}),v}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(p.acpSessionId,w):e.activeTriggers.delete(p.acpSessionId),h?e.activeGroupIds.set(p.acpSessionId,h):e.activeGroupIds.delete(p.acpSessionId),h&&p.cozeGroupId!==h&&(p.cozeGroupId=h,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Ix(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let b=await Sx(a.prompt);try{let y=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:b});return p.lastActiveAt=Date.now(),y}catch(y){if(y instanceof k&&y.code==="AGENT_APPROVAL_TIMEOUT"){let v=p.pendingPermission;v&&(v.downstream.respondAgentRequest(v.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(v.upstreamId),p.pendingPermission=void 0);let I=p.acpSessionId,A=I?e.activeTriggers.get(I):void 0,C=I?e.activeGroupIds.get(I):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,p,d,_S,A,C)}throw y}finally{if(e.activeTriggers.delete(p.acpSessionId),e.activeGroupIds.delete(p.acpSessionId),p.pendingPermission=void 0,p.reloadAfterTurn){p.reloadAfterTurn=!1;let y=p.downstream;y&&(p.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),y.stop("reload-after-turn").catch(v=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(v)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=s.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let h=e.getSessionQueue(d);h.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:h.size}),h.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=s,d=a.sessionId,u=a.modeId,h=Ao(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!dn(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Wt(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Nd(e.framework)}`);if(h)return await this.handleGroupSetMode(e,h,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let 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(w){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),w}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let s=[];for(let[d,u]of e.sessions)u.cozeGroupId===n&&u.permissionMode!==i&&s.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(s.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i,targets:s.length});for(let d of s)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let a=[];for(let d of s){let u=d.runtime.downstream,h=d.runtime.acpSessionId;u?.isAlive()&&h&&a.push({downstream:u,acpSessionId:h,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 h of s)h.runtime.permissionMode=h.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,n,i,s){let a=e.sessions.get(n);if(a){let h=a.cozeGroupId!==i,x=e.deployType==="cloud"&&a.tokenGroupId!==i,p=a.requestScene!==s;if(x&&(a.modelToken=await this.requestSessionToken(e.agentId,n,i),a.tokenGeneratedAt=Date.now(),a.tokenGroupId=i),x||p){Qr(a);let w=a.downstream;a.downstream=void 0,w&&await w.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=s,(h||x||p)&&await this.persistSessionMapping(e),a}let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0,...i?{cozeGroupId:i}:{},...i?{tokenGroupId:i}:{},...s?{requestScene:s}:{}};return dn(e)&&(e.framework==="hermes"?u.permissionMode=e.deployType==="cloud"?U0:H0:u.permissionMode=e.framework==="claude-code"?qd:Qh),e.sessions.set(n,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,n,i){let s={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(nt.GEN_MODEL_TOKEN,s,yS);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(Qr(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=3,a=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=s&&Date.now()-u<a)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((a-(Date.now()-u))/1e3)}s`);let h;try{let x=this.requestSceneBySession.get(n);x&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),h=await this.sessionSpawner(e,i.modelToken,n,this.currentCozeEnv,this.currentMockScenario,x)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=s&&i.acpSessionId&&(W.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=h,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{let x=await h.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace});W.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId}),this.piggybackModelList(e,x)}catch(x){W.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 h.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,this.piggybackModelList(e,p),await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await h.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,this.piggybackModelList(e,x),await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await h.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(h.afterSessionEstablished&&i.acpSessionId&&await h.afterSessionEstablished(i.acpSessionId),dn(e)&&i.acpSessionId&&i.permissionMode)try{await h.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(Qr(i),this.isRuntimeBusy(e,i)){W.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)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let s=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),s&&s.stop("idle timeout").catch(a=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(a)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let i=n.downstream;if(!i)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,n,i,s){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let d=e.activeTriggers.get(n.acpSessionId);d&&(a.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(n.acpSessionId);u&&(a.cozeGroupId=u)}await this.upstream.send(Kr("session/update",{sessionId:i,update:s,_meta:a}))}async synthesizePromptReply(e,n,i,s,a,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(u.cozeTriggerMsgId=a),d&&(u.cozeGroupId=d),await this.upstream.send(Kr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}},_meta:u})).catch(h=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(h)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,s=this.reverseSessionId(e,i);if(!s){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(s);if(!a){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(IS(n)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=n.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&dn(e)){let p=d.currentModeId;Wt(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(w=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof p=="string"&&!Wt(e.framework,p)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}if(d&&typeof d=="object"&&d.sessionUpdate==="config_option_update"){let p=d.configOptions;Array.isArray(p)&&this.piggybackModelList(e,{configOptions:p})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},h=e.activeTriggers.get(i);h&&(u.cozeTriggerMsgId=h);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Kr("session/update",{...n,sessionId:s,_meta:u})).catch(p=>W.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}piggybackModelList(e,n){let i=this.modelListCache;if(i)try{let s=K0(e.framework,n);if(!s)return;(vt(e.model)||e.model===_d)&&s.currentModelId&&!s.defaultModelId&&(s.defaultModelId=s.currentModelId),s.models.length>0&&i.update(e.framework,s).catch(d=>W.warn("piggyback model-list update failed (ignored)",{agentId:e.agentId,err:String(d)})),(s.currentModelId||s.currentEffort||s.currentFastMode)&&i.setRuntimeCurrent(e.agentId,{...s.currentModelId?{model:s.currentModelId}:{},...s.currentEffort?{effort:s.currentEffort}:{},...s.currentFastMode?{fastMode:s.currentFastMode}:{}})}catch(s){W.warn("piggyback model-list parse failed (ignored)",{agentId:e.agentId,err:String(s)})}}warmupModelList(e){let n=this.modelListCache;if(!n||e.deployType!=="local")return;let i=e.framework,s=i==="claude-code"||i==="codex"||i==="hermes",a=i==="openclaw";if(!s&&!a||s&&!this.sessionSpawner||a&&!this.openclawModelLister||n.get(i)||this.modelListWarmupInFlight.has(i))return;this.modelListWarmupInFlight.add(i),(a?this.runOpenclawModelWarmup(i):this.runModelListWarmup(e,i)).finally(()=>this.modelListWarmupInFlight.delete(i))}async runOpenclawModelWarmup(e){if(this.openclawModelLister)try{let n=await this.openclawModelLister();n&&n.models.length>0?(await this.modelListCache?.update("openclaw",n),W.info("openclaw model-list warm-up done",{framework:e,count:n.models.length})):W.warn("openclaw model-list warm-up: empty CLI result (ignored)",{framework:e})}catch(n){W.warn("openclaw model-list warm-up failed (ignored)",{framework:e,err:String(n)})}}async runModelListWarmup(e,n){if(!this.sessionSpawner)return;let i;try{i=await this.sessionSpawner(e,"",bS,this.currentCozeEnv,this.currentMockScenario,void 0);let s=await i.sessionNew({cwd:e.workspace});this.piggybackModelList(e,s),W.info("model-list warm-up done",{agentId:e.agentId,framework:n})}catch(s){W.warn("model-list warm-up failed (ignored)",{agentId:e.agentId,framework:n,err:String(s)})}finally{await i?.stop("model-list warm-up done").catch(()=>{})}}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}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:Q.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,n,i){try{let s=e.workspace;if(i.method==="fs/write_text_file"){let a=i.params??{},d=await _x(a,s);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await yx(a,s);n.respondAgentRequest(i.id,d)}}catch(s){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(s)}),n.respondAgentRequestError(i.id,is(s))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,i){let s=this.upstreamIds.next("session/request_permission"),a=i.params??{},u=a.sessionId,h=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};h&&(x.cozeTriggerMsgId=h);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let w=u?this.reverseSessionId(e,u):void 0,b=w?e.sessions.get(w):void 0;b&&(b.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:s});let y={...a,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(s,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:u,cloudSessionId:w,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(ns(s,"session/request_permission",y)).catch(v=>{this.pendingUpstream.delete(s),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:Q.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let s=n.value;this.clearPendingPermissionFor(s),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:s.agentId,upstreamId:e.id,method:s.method,error:e.error}),s.downstream.respondAgentRequestError(s.agentRequestId,e.error)):(s.method==="session/request_permission"&&ES(e.result,s),W.info("upstream \u2192 permission response (result)",{agentId:s.agentId,upstreamId:e.id,method:s.method,result:e.result}),s.downstream.respondAgentRequest(s.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new No(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,i){let s=e.get(n);if(s)return{value:s,key:n};if(typeof n=="number"){let a=String(n),d=e.get(a);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=gS){let s=this.upstreamIds.next(e);return new Promise((a,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(s),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(s,{method:e,resolve:a,reject:d,timer:u}),this.upstream.send(ns(s,e,n)).catch(h=>{let x=this.pendingBridge.get(s);x&&(clearTimeout(x.timer),this.pendingBridge.delete(s)),d(h)})})}async persistSessionMapping(e){if(this.paths)try{let n=new Map;for(let[i,s]of e.sessions){let a={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(a.acpSessionId=s.acpSessionId),s.permissionMode&&dn(e)&&(a.permissionMode=s.permissionMode),s.cozeGroupId&&(a.cozeGroupId=s.cozeGroupId),s.tokenGroupId&&(a.tokenGroupId=s.tokenGroupId),s.requestScene&&(a.requestScene=s.requestScene),n.set(i,a)}await _i(e.agentId,n,this.paths)}catch(n){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[i,s]of e.sessions.entries())if(s.acpSessionId===n)return i}sendError(e,n,i){return this.upstream.send(Mn(e,{code:n,message:i,data:{bridgeVersion:jt}}))}};function vS(){return pS(16).toString("hex")}function ES(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){W.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"){W.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")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var SS=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."],Ax="Warning: ";function IS(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let i=n;if(i.type!=="text"||typeof i.text!="string")return!1;let s=i.text.startsWith(Ax)?i.text.slice(Ax.length):i.text;return SS.some(a=>s.startsWith(a))}Ct();ne();Ce();import{randomBytes as AS}from"node:crypto";import{createServer as kS}from"node:http";var CS=1e6,kx=G("ipc"),ea=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(n=>[`${n.method} ${n.path}`,n])),this.paths=e.paths??Z()}async start(){this.token=AS(32).toString("hex");let e=kS((i,s)=>{this.dispatch(i,s)});this.server=e,await new Promise((i,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>i())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),kx.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,i)=>{e.close(s=>s?i(s):n())}),this.server=null)}async persistAuthFiles(){await _t(this.paths.portFile,String(this.port)),await _t(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ls(n,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(s);if(!a){ls(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await TS(e)}catch(u){ls(n,400,{error:"invalid json",detail:String(u)});return}try{let u=await a.handler(d,e);ls(n,200,u??{ok:!0})}catch(u){kx.error("IPC handler failed",{key:s,err:String(u)}),ls(n,500,{error:u instanceof Error?u.message:String(u)})}}};function ls(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function TS(t){let e=[],n=0;for await(let s of t){let a=s;if(n+=a.length,n>CS)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 JI=Xt(vp(),1),ZI=Xt(da(),1),YI=Xt(ri(),1),XI=Xt(rl(),1),QI=Xt(ol(),1),eA=Xt(fl(),1),Dp=Xt(ha(),1),tA=Xt(Pp(),1);var Rp=Dp.default;Ve();ne();var{FWS:mA}=qp(),Le=G("upstream.frontier"),Wp="application/json",Kp="none",wA=15e3;function _A(t){class e extends Rp{constructor(i){super(i,A0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Le.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,s){this.guardTeardown(),super.close(i,s)}terminate(){this.guardTeardown(),super.terminate()}send(i,...s){if(eu("debug"))try{let a;typeof i=="string"?a=Buffer.from(i,"utf8"):i instanceof Buffer?a=i:i instanceof ArrayBuffer?a=new Uint8Array(i):ArrayBuffer.isView(i)?a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):a=new Uint8Array(0);let d=Buffer.from(a.slice(0,128)).toString("hex");Le.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Le.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...s)}}return e}var _s=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Le.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:k0,...On(this.opts.ppeOverride)},n=_A(e),i=T0(this.opts.urlOverride),s={url:i,ws:n,fpID:I0,aID:To,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Wp,force:!0},payloadEncoding:{encoding:Kp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new mA(s),d=!1,u=null,h,x,p=new Promise((y,v)=>{h=y,x=v}),w=y=>{d||(d=!0,u&&(clearTimeout(u),u=null),y?x(y):h())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Le.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&w();for(let v of this.connectHandlers)Promise.resolve(v({initial:y})).catch(I=>Le.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=y=>{this.opened=!1,Le.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},a.onerror=y=>{Le.warn("frontier error",{code:y.code,msg:y.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},a.onmessage=y=>this.handleMessage(y),this.fws=a;let b=this.opts.openTimeoutMs??wA;u=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${b}ms (handshake or upgrade slow)`))},b),await a.connect();try{await p}catch(y){try{a.close(1e3,"open failed")}catch(v){Le.warn("fws close during start failure threw (ignored)",{err:String(v)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(i){Le.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Le.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?(Le.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let s=JSON.stringify(e),a=e;$p(a)||Le.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:s.length});try{await n.send(s,{service:33555712,method:1,payloadType:Wp,payloadEncoding:Kp})}catch(u){throw Le.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let n=this.opts.getPatTokenForAgent;if(!n)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let s=n(i.cozeAgentId);s&&(i.cozePatToken=s)}handleMessage(e){let n=e.message?.service;if(n!==33555712){Le.debug("drop non-adapter frontier frame",{service:n});return}let i=vA(e);if(!i){Le.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Le.debug("frame received but no onFrame handler",{size:i.length});return}let s;try{s=JSON.parse(i)}catch(d){Le.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=s;$p(a)||Le.info("frontier frame in",{logid:bA(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:yA(i)}),Promise.resolve(this.handler(s)).catch(d=>Le.warn("frontier frame handler threw",{err:String(d)}))}};function $p(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Vp=2e3;function yA(t){return t.length<=Vp?t:`${t.slice(0,Vp)}...<truncated, total ${t.length} chars>`}function bA(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function vA(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}}Ve();ne();var gl=G("skill-publish"),EA="/api/marketplace/product/skill/publish_with_assets",SA=15e4;async function Jp(t,e={}){let i=`${Hr(Gr(e.handshakeBase))}${EA}`,s=e.timeoutMs??SA,a=new FormData;a.append("skill_id",t.skillId??""),a.append("skill_name",t.skillName),a.append("skill_description",t.description??""),a.append("agent_id",t.agentId),a.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...On(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,h=setTimeout(()=>u.abort(),s);gl.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:a,signal:u.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let y=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${y.slice(0,200)}`)}let w=await x.json();if(gl.info("skill publish response",{logid:p,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${p}`);let b={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(b.skillId=String(w.data.skill_id)),w.data?.version&&(b.version=w.data.version),gl.info("skill publish ok",{logid:p,skillId:b.skillId??"",version:b.version??""}),b}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${s}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(h)}}ne();var ml=G("upstream.switchable"),va=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;ml.info("swap upstream",{reason:n});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let s of this.connectHandlers)e.onConnect(s);try{await e.start()}catch(s){throw ml.error("swap target start failed, reverting",{err:String(s)}),this.inner=i,s}await i.stop(n??"swapped").catch(s=>ml.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var wl=G("upstream"),di=class{handler=null;async start(){wl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){wl.info("NoopUpstream stopped",{reason:e})}async send(e){wl.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)}};Ve();ne();Ct();ne();Ce();import{promises as IA}from"node:fs";var Zp=G("pat-token-store");async function Ea(t=Z()){try{let n=(await IA.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(Zp.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"&&Zp.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function ys(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await _t(e.patTokenFile,t,{mode:384})}Ce();Ce();import{promises as Sa}from"node:fs";import{join as AA}from"node:path";function kA(t,e){return`#!/bin/sh
114
+ `}async function Yh(t){let e=mv(t,"HEARTBEAT.md"),n=await pv(e,"utf8");return yv(n)!==wv?!1:(await gv(e,_v),!0)}var re=q("agent-manager"),kv=["hooks.json","cozeloop.env"],Tv=["hooks"];async function Cv(t,e){let n=fn(Oe(t,e).root,"codex-home"),i=fn(tx(),".codex");if(n!==i){await Qo(n,{recursive:!0});for(let o of Tv){let a=fn(i,o),d=fn(n,o);try{await $d(d);continue}catch{}try{await bv(a,d,{recursive:!0,errorOnExist:!0,filter:f=>{let u=Av(f);return!u.endsWith(".log")&&!u.includes(".bak")}}),re.info("migrated legacy Codex state",{agentId:t,name:o})}catch(f){f.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(f)})}}for(let o of kv){let a=fn(i,o),d=fn(n,o);try{await $d(d);continue}catch{}try{if(o==="cozeloop.env"){let u=(await vv(a,"utf8")).split(/\r?\n/).filter(x=>!/^\s*(?:export\s+)?CODEX_HOME\s*=/.test(x)).join(`
115
+ `);await Iv(d,u,{mode:384})}else await Ev(a,d);re.info("migrated legacy Codex state",{agentId:t,name:o})}catch(f){f.code!=="ENOENT"&&re.warn("legacy Codex state migration skipped",{agentId:t,name:o,err:String(f)})}}}}var Vd="acceptEdits",nx="full-access",rx="read-only";function Rv(t){return{INITIAL_AGENT_MODE:Ko(t)}}var Pv=(t,e,n,i,o,a,d,f,u,x,p,w)=>{switch(t){case"claude-code":{let b={...o?{...B0(o),...H0(o,d,f,w)}:{},...u??{},IS_SANDBOX:"1"};return new Wo({cwd:n,env:b,agentId:i})}case"codex":{let b=nx;x!==void 0&&($t("codex",x)?b=x:re.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _=!!o?.modelToken,v={...o?{...U0(o),...z0(o,d,f,w)}:{},...Rv(b),..._?{NO_BROWSER:"1"}:{},...u??{},..._?{COZELAB_ONBOARD_CLOUD:"true"}:{}};return new $o({cwd:n,agentId:i,...Object.keys(v).length>0?{env:v}:{},...o?.fastMode?{fastMode:o.fastMode}:{},..._?{authMethodId:"api-key",isolateCodexHome:!0,...p?{codexHomeDir:p}:{}}:{}})}case"openclaw":return new ni({command:e,cwd:n,agentId:i,...a?{sessionName:Wd(a)}:{}});case"hermes":return new Vo({command:e,cwd:n,agentId:i,...u&&Object.keys(u).length>0?{env:{...u}}:{},...o?.model&&!bt(o.model)?{modelId:o.model}:{}})}};function Kd(t){return t==="claude-code"||t==="codex"}var Dv={path:"",version:"cloud-deployed"},Qh="openclaw_gateway_unavailable",Ov="openclaw_default_agent_missing";function ex(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var Lv={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Mv=6e4,ea=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??Pv,this.createTimeoutMs=e.createTimeoutMs??Mv,this.detectorFactory=e.detectorFactory??(()=>new lr),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Yo({command:n,openclawDir:this.openclawConfigDir})),this.openclawConfigDir=e.openclawConfigDir??fn(tx(),".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=>{re.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=fn(e,".env");if(await $d(n).then(a=>a.isFile()).catch(()=>!1)){re.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}let o=ts({...process.env,...ar(this.paths.agentEnvFile)});await _t(n,o,{mode:384}),re.info("openclaw .env bootstrapped",{envFile:n,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),re.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 we(e.agentId,this.paths).catch(()=>null),o=sr(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")re.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(T=>re.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&a.deployType!=="cloud")re.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await a.dispose("rebuild after deployType drift").catch(T=>re.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==a.patToken){re.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),a.setPatToken(e.patToken);let T=await we(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Le(T,this.paths))}if(a.deployType==="cloud"&&e.modelInfo){re.info("updating agent modelInfo on re-create",{agentId:e.agentId}),a.setModelInfo(e.modelInfo);let T=await we(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Le(T,this.paths))}return re.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 k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine${R}`)}let f=Oe(e.agentId,this.paths),u=o?"cloud":"local",x=e.framework==="openclaw"&&u==="local",p;x&&!n?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let w=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),b=e.workspace??w??f.workspace,_=new AbortController,v=setTimeout(()=>_.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&Kd(e.framework)&&await kr(e.framework,_.signal);let T=()=>{if(_.signal.aborted)throw _.signal.reason instanceof Error?_.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await Qo(f.root,{recursive:!0}),await Qo(b,{recursive:!0}),await Qo(f.logs,{recursive:!0}),T(),x||await Tr(b,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(u==="cloud"?await dc(b,"cloud"):await dc(b,"local",Vd)),T();let R=i,E=F0({model:e.model??R?.model}),P=p0(e._meta)??R?.accountId,D=e.patToken??R?.patToken,U=u==="cloud"?e.modelInfo??R?.modelInfo:void 0;if(I=new Jo({agentId:e.agentId,framework:e.framework,workspace:b,model:E.model??Mt,deployType:u,...P?{accountId:P}:{},...D?{patToken:D}:{},...U?{modelInfo:U}:{}}),I.status="ok",R?.sessions){let J=e.framework==="hermes"||u==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,oe]of Object.entries(R.sessions)){let le={acpSessionId:oe.acpSessionId,modelToken:oe.modelToken,tokenGeneratedAt:oe.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};J?oe.permissionMode===void 0?(le.permissionMode=e.framework==="claude-code"?"bypassPermissions":e.framework==="codex"?"full-access":"default",re.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Y,framework:e.framework,fallback:le.permissionMode})):$t(e.framework,oe.permissionMode)?le.permissionMode=oe.permissionMode:re.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:oe.permissionMode}):oe.permissionMode!==void 0&&re.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:u}),oe.cozeGroupId&&(le.cozeGroupId=oe.cozeGroupId),oe.tokenGroupId&&(le.tokenGroupId=oe.tokenGroupId),oe.requestScene&&(le.requestScene=oe.requestScene),I.sessions.set(Y,le)}let ie=Object.keys(R.sessions).length;ie>0&&re.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ie})}this.registry.register(I),A=!0,n?.revive||this.registry.warmupModelList?.(I);let N={agentId:e.agentId,framework:e.framework,workspace:b,cozeIdentity:e.cozeIdentity,createdAt:R?.createdAt??Date.now(),sessions:R?.sessions??{},model:E.model};if(u==="cloud"&&(N.deployType="cloud"),P&&(N.accountId=P),D&&(N.patToken=D),U&&(N.modelInfo=U),R?.skills&&(N.skills=R.skills),R?.agentName&&(N.agentName=R.agentName),R?.description&&(N.description=R.description),N.skillsRefreshedForVersion=R?.skillsRefreshedForVersion??Kt,e.framework==="openclaw"&&u==="cloud"){this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,b)):re.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId});try{await Yh(b)&&re.info("legacy openclaw HEARTBEAT template fixed",{agentId:e.agentId,workspace:b})}catch(J){re.warn("failed to fix legacy openclaw HEARTBEAT template (ignored)",{agentId:e.agentId,workspace:b,err:String(J)})}}let K=e.initialSkills??[];if(K.length>0){let J=[...N.skills??[]],ie=new Map(J.map((le,Ee)=>[le.skillId,Ee])),Y=await Promise.allSettled(K.map(le=>Uo({agentId:e.agentId,workspace:b,framework:e.framework,skill:le,paths:this.paths}))),oe=0;for(let[le,Ee]of Y.entries()){let qe=K[le];qe&&(Ee.status==="fulfilled"?(Ho(J,ie,Ee.value),oe++):re.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:qe.skillId,skillName:qe.skillName,err:String(Ee.reason)}))}oe>0&&(N.skills=J,re.info("initialSkills installed",{agentId:e.agentId,installed:oe,requested:K.length}))}return await Le(N,this.paths),re.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:u}),{ok:!0,agentId:e.agentId,workspace:b,framework:e.framework}}catch(T){throw re.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),re.error("[AUDIT] ROLLBACK: about to rm dirs.root",{src:"agent-manager.createAgent.catch",agentId:e.agentId,path:f.root,revive:n?.revive===!0,framework:e.framework,errStack:T instanceof Error?T.stack:String(T)}),await Sv(f.root,{recursive:!0,force:!0}).catch(R=>re.warn("rm agent dir failed (ignored)",{err:String(R)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(v)}}async spawnSessionDownstream(e,n,i,o,a,d){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&Kd(e.framework))u=Dv;else throw e.framework==="hermes"?new k("AGENT_SPAWN_FAILED","hermes-acp not detected on this machine; install with `pipx install hermes-agent` and rerun daemon to refresh frameworks_cache"):new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);Kd(e.framework)&&!Fs(e.framework)&&(re.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await kr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:N0({model:e.model,effort:e.effort,fastMode:e.fastMode}),p;if(e.framework==="openclaw")p=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:a,requestScene:d,command:u.path});else if(e.framework==="hermes"){let w={...this.buildBinShimPathEnv()};x?.modelToken&&(await $0({paths:this.paths,agentId:e.agentId,modelConfig:x,cozeEnv:o,mockScenario:a}),w.HERMES_HOME=dr(e.agentId,this.paths)),p=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,a,w)}else{let w=e.sessions.get(i),b=ln(e)?w?.permissionMode??nx:"full-access";e.framework==="codex"&&e.deployType==="cloud"&&await Cv(e.agentId,this.paths),p=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,a,this.buildBinShimPathEnv(),b,e.framework==="codex"&&e.deployType==="cloud"?fn(Oe(e.agentId,this.paths).root,"codex-home"):void 0,d)}try{return await p.start(),await p.initialize(Lv),p}catch(w){let b=p instanceof St?p.getStderrTail():[];throw b.length>0&&re.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof k?w.code:"unknown",recentStderr:b}),await p.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,w)}}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",ex(o),{cause:{reason:Qh}})}catch(o){re.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};re.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 re.info("openclaw lazy re-detect success",{agentId:n.defaultAgent.id,workspace:n.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=n,{id:n.defaultAgent.id,workspace:n.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:Ov}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let n=await this.detectorFactory().probeOpenclawGateway(e);if(!n.reachable)throw new k("AGENT_ENV_NOT_READY",ex(n),{cause:{reason:Qh}})}async buildOpenclawDownstream(e){let{session:n,modelConfig:i,cloudSessionId:o,cozeEnv:a,mockScenario:d,requestScene:f,command:u}=e,x=Wd(o);if(n.deployType==="local"){let b=await this.ensureOpenclawDefaultAgent(),_=i&&!bt(i.model)?i.model:void 0;return new ni({command:u,cwd:b.workspace,agentId:b.id,sessionName:x,..._?{slashModelOnStart:_}:{}})}let p=await Xh();try{let b=this.getOpenclawConfig();await b.ensureAcpDeviceScopes()&&await b.restartGateway()}catch(b){re.warn("acp device scope ensure failed (ignored)",{err:String(b)})}let w;if(i?.modelToken){let b=Ad(o),_=kd(i),v=`${b}/${_}`,I=JSON.stringify({modelConfig:i,cozeEnv:a,mockScenario:d,requestScene:f});if(this.ensuredProviders.get(v)!==I){let A=this.getOpenclawConfig(),T=await A.getAllowlistModelsForProvider(b),R=q0(i,a,d,T,f);R&&(await A.ensureProvider(b,R),await A.addModelToAllowlist(v),this.ensuredProviders.set(v,I))}w=v}else i&&!bt(i.model)&&(w=i.model);return new ni({command:u,cwd:n.workspace,agentId:n.agentId,sessionName:x,...p?{gatewayToken:p}:{},...w?{slashModelOnStart:w}:{}})}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=Ad(a),f=`${d}/${o}`,u=!0;try{await i.removeProvider(d)}catch(x){u=!1,re.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:d,err:String(x)})}try{await i.removeModelFromAllowlist(f)}catch(x){u=!1,re.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:f,err:String(x)})}u&&this.ensuredProviders.delete(f)}}};import{randomUUID as cx}from"node:crypto";import{promises as qv}from"node:fs";import{basename as dx}from"node:path";Ze();ne();import{promises as Nv}from"node:fs";import{basename as Fv}from"node:path";var ix=q("file-upload"),Bv="/api/coze_claw/file/agent_upload",zv=6e4;async function sx(t,e={}){let i=`${Wr(Kr(e.handshakeBase))}${Bv}`,o=e.timeoutMs??zv,a=await Nv.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 f={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Nn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},u=new AbortController,x=setTimeout(()=>u.abort(),o);ix.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:f,body:d,signal:u.signal}),w=p.headers.get("x-tt-logid")??"";if(!p.ok){let v=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${w}: ${v.slice(0,200)}`)}let b=await p.json();if(b.code!==void 0&&b.code!==0)throw new k("UPLOAD_FAILED",`upload code=${b.code} msg=${b.msg??"-"} logid=${w}`);let _=b.data?.file?.file_url;if(!_)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${w}: ${JSON.stringify(b).slice(0,200)}`);return ix.info("file upload ok",{uri:_,logid:w}),{uri:_}}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Fv(t.path)}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}Ze();ne();import{extname as Uv}from"node:path";var Hv={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function ox(t){let e=Uv(t).toLowerCase();return Hv[e]??"application/octet-stream"}Pe();var ta=q("agent-send"),ax=50*1024*1024;function lx(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 fx(t,e,n,i,o,a){let f;for(let u=0;u<=2;u++)try{await t.core.sendAgentFileUpdate(e,n,i,o);return}catch(x){f=x,u<2&&(ta.warn("sendAgentFileUpdate failed, retrying",{attempt:u+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new k("UPSTREAM_NOT_READY",`${a} after 3 attempts: ${String(f)}`,{cause:f})}async function ux(t,e){let{session:n,runtime:i}=lx(e.core,t.agentId,t.sessionId);if(!await vi(t.path,n.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let o=await qv.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>ax)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${ax}`);let a=await ox(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??dx(t.path),f;try{f=await sx({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 ta.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:a,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let u={sessionUpdate:"agent_file",messageId:cx(),content:{type:t.kind==="image"?"image":"resource",uri:f.uri,mimeType:a,name:d,sizeBytes:o.size,...f.fileId!==void 0?{fileId:f.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await fx(e,n,i,t.sessionId,u,"agent file uploaded to cloud but sendAgentFileUpdate failed"),ta.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:a,uri:f.uri}),{ok:!0,uri:f.uri,bytes:o.size,mimeType:a,...f.fileId!==void 0?{fileId:f.fileId}:{}}}async function hx(t,e){let{session:n,runtime:i}=lx(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??dx(t.path),a={sessionUpdate:"group_file",messageId:cx(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await fx(e,n,i,t.sessionId,a,"agent group file sendAgentFileUpdate failed"),ta.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 xx(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,f=i[a]??0;if(d<f)return!0;if(d>f)return!1}return!1}Wt();ne();vn();var Jt=q("coze-cli-installer"),px="@coze/cli@latest",Gv="coze",gx="0.1.8",jv=5e3,Wv=5e3,Kv=9e4,mx=1e4,us=null,na=!1;async function Zd(t,e={}){if(na)return;if(us)return us;let n=e.exec??Oo;return us=(async()=>{try{let i=await $v(Gv,n),o=!1;if(i){let d=await Vv(n);if(d===void 0)Jt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(xx(d,gx))Jt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:gx}),o=!0;else{Jt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),na=!0;return}}let a=o?"upgrade-only":"full";Jt.info("coze-cli install start",{package:px,mode:a});try{await n("npm",["i","-g","--prefer-online",px],{timeout:Kv,maxBuffer:10*1024*1024}),Jt.info("coze-cli install ok")}catch(d){Jt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){na=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:mx}),Jt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Jt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:mx}),Jt.info("coze auth login ok")}catch(d){Jt.warn("coze auth login failed",{err:String(d)});return}na=!0}finally{us=null}})(),us}async function $v(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(n,[t],{timeout:jv});return ac(i)}catch{return}}async function Vv(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:Wv});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Ct();var ra=class{cacheFilePath;memory=new Map;runtimeCurrent=new Map;writeQueue=new Vt;constructor(e){this.cacheFilePath=e}async loadFromDisk(){if(!this.cacheFilePath)return;let e=await Ye(this.cacheFilePath);if(e)for(let[n,i]of Object.entries(e))i&&this.memory.set(n,i)}get(e){return this.memory.get(e)}update(e,n){return this.writeQueue.enqueue(async()=>{let i=Q0(n),o=this.memory.get(e);if(o&&o.hash===i){if(o.cachedAt=Date.now(),n.defaultModelId&&o.defaultModelId!==n.defaultModelId){if(o.defaultModelId=n.defaultModelId,this.cacheFilePath){let f=await Ye(this.cacheFilePath)??{};f[e]=o,await ut(this.cacheFilePath,f)}return!0}return!1}let a={cachedAt:Date.now(),hash:i,models:n.models,...n.defaultModelId?{defaultModelId:n.defaultModelId}:{},...n.effortLevels?{effortLevels:n.effortLevels}:{},...n.fastModes?{fastModes:n.fastModes}:{}};if(this.memory.set(e,a),!this.cacheFilePath)return!0;let d=await Ye(this.cacheFilePath)??{};return d[e]=a,await ut(this.cacheFilePath,d),!0})}setRuntimeCurrent(e,n){let i=this.runtimeCurrent.get(e)??{};this.runtimeCurrent.set(e,{...i,...n.model!==void 0?{model:n.model}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.fastMode!==void 0?{fastMode:n.fastMode}:{}})}getRuntimeCurrent(e){return this.runtimeCurrent.get(e)}};tn();Ct();Pe();var Jv=10*6e4;function _x(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Jv:e}function ia(t){return Ye(t??Z().configFile)}function hs(t,e){return ut(e??Z().configFile,t)}import{randomBytes as pS}from"node:crypto";vr();Ze();ne();import{createReadStream as Zv}from"node:fs";import{mkdir as Xv,readFile as Yv,realpath as Qv,stat as eS,writeFile as tS}from"node:fs/promises";import{basename as nS,dirname as Xd,isAbsolute as rS,join as iS,relative as sS,resolve as yx,sep as oS}from"node:path";import{createInterface as aS}from"node:readline";var bx=q("fs-rpc"),xs=Je("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function vx(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>xs)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${xs} bytes`);let i=await Ix(t.path,e);return await Xv(Xd(i),{recursive:!0}),await tS(i,t.content,"utf8"),bx.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function Sx(t,e){let n=await Ix(t.path,e),i=await eS(n),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>xs&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${xs} bytes`);let a;if(o&&i.size>xs)a=await cS(n,t.line??1,t.limit);else{let d=await Yv(n,"utf8");if(o){let f=d.split(`
116
+ `),u=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?u+t.limit:void 0;a=f.slice(u,x).join(`
117
+ `)}else a=d}return bx.info("fs/read_text_file ok",{path:n,size:a.length}),{content:a}}async function cS(t,e,n){let i=aS({input:Zv(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),a=typeof n=="number"?o+n:Number.POSITIVE_INFINITY,d=[],f=0;try{for await(let u of i)if(f>=o&&f<a&&d.push(u),f++,f>=a)break}finally{i.close()}return d.join(`
118
+ `)}async function Ix(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([Ex(yx(e)),Ex(yx(t))]),o=sS(n,i);if(dS(o,oS,rS(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function dS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Ex(t){let e=[],n=t;for(;n!==Xd(n);)try{let i=await Qv(n);return e.length?iS(i,...e.reverse()):i}catch{e.push(nS(n)),n=Xd(n)}return t}ne();var Ax=q("prompt-multimodal"),kx=10*1024*1024,lS=15e3,fS=6;async function Tx(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 uS(d))}}let o=Array.from({length:Math.min(fS,t.length)},()=>i());return await Promise.all(o),e}function Cx(t){return t.some(e=>e.type==="image")}async function uS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!es(e.uri))return t;try{let{buf:n,contentType:i}=await xS(e.uri),o=e.mimeType||hS(i)||"application/octet-stream";return Ax.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 Ax.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function hS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function xS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),lS);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>kx)throw new Error(`image too large: ${o.byteLength} bytes (max ${kx})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}tn();Ze();ne();var W=q("core"),gS=3e4,mS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,wS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",_S="\u5BA1\u6279\u5DF2\u8D85\u65F6",yS=3e4,ES="__model_warmup__",sa=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Yr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;requestSceneBySession=new Map;modelListCache;openclawModelLister;modelListWarmupInFlight=new Set;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=_x(e.bridgeConfig),this.modelListCache=e.modelListCache,this.openclawModelLister=e.openclawModelLister}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(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(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),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,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)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:a,signal:d}),ri(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){W.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(Bn(o,{code:Q.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{a.downstream.respondAgentRequestError(a.agentRequestId,{code:Q.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:Q.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(Go(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&mS.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});let o=e.params,a=g0(o?._meta),d=o?.sessionId;if(e.method==="session/prompt"&&typeof d=="string"){let f=this.requestSceneBySession.get(d);a&&f!==a?(this.requestSceneBySession.set(d,a),W.info("cached request_scene for session",{sessionId:d,requestScene:a})):!a&&f!==void 0&&(this.requestSceneBySession.delete(d),W.info("cleared request_scene for session",{sessionId:d}))}try{if(e.method.startsWith("_agent/")){let f=this.extensions[e.method];if(!f){n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let u=await f(e,this);n!==null&&await this.upstream.send(Xr(n,u));return}if(e.method.startsWith("session/")){let f=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Xr(n,f));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Xr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,Q.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(f){W.error("handleFrame failed",{method:e.method,err:String(f)}),n!==null&&await this.upstream.send(Bn(n,ds(f)))}}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 u=o.sessions.get(a);if(u?.pendingPermission){let x=n._meta?.cozeTriggerMsgId,p=Po(n._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:a}),this.synthesizePromptReply(o,u,a,wS,x,p)}}let d=Date.now(),f=!1;try{let u=await o.getSessionQueue(a).enqueue(()=>this.dispatchSessionCall(o,e.method,n));return f=!0,u}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:f})}}async dispatchSessionCall(e,n,i){e.lastActiveAt=Date.now();let{stripped:o}=w0(i);switch(n){case"session/new":{let a=bS();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:a}),{sessionId:a}}case"session/load":{let a=o;return W.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 f=ln(e)?m0(i._meta):void 0;if(f!==void 0&&!$t(e.framework,f))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${f}; allowed: ${Hd(e.framework)}`);let u=Po(i._meta),x=this.requestSceneBySession.get(d),p=await this.ensureRuntime(e,d,u,x);if(f!==void 0&&p.permissionMode===void 0&&(p.permissionMode=f,await this.persistSessionMapping(e)),p.replySeq=0,await this.ensureDownstream(e,d,p),!p.downstream||!p.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(f!==void 0&&p.permissionMode!==void 0&&p.permissionMode!==f){let _=p.permissionMode;p.permissionMode=f,await this.persistSessionMapping(e);try{await p.downstream.setSessionMode({sessionId:p.acpSessionId,modeId:f})}catch(v){throw p.permissionMode=_,await this.persistSessionMapping(e).catch(()=>{}),v}}let w=i._meta?.cozeTriggerMsgId;if(w?e.activeTriggers.set(p.acpSessionId,w):e.activeTriggers.delete(p.acpSessionId),u?e.activeGroupIds.set(p.acpSessionId,u):e.activeGroupIds.delete(p.acpSessionId),u&&p.cozeGroupId!==u&&(p.cozeGroupId=u,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Cx(a.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let b=await Tx(a.prompt);try{let _=await p.downstream.sessionPrompt({...a,sessionId:p.acpSessionId,prompt:b});return p.lastActiveAt=Date.now(),_}catch(_){if(_ instanceof k&&_.code==="AGENT_APPROVAL_TIMEOUT"){let v=p.pendingPermission;v&&(v.downstream.respondAgentRequest(v.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(v.upstreamId),p.pendingPermission=void 0);let I=p.acpSessionId,A=I?e.activeTriggers.get(I):void 0,T=I?e.activeGroupIds.get(I):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,p,d,_S,A,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,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:p.acpSessionId}),_.stop("reload-after-turn").catch(v=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(v)})))}else p.downstream?.isAlive()&&this.armIdleTimer(e,d,p)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let f=e.sessions.get(d);if(e.hasSessionQueue(d)){let u=e.getSessionQueue(d);u.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:u.size}),u.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return f?.downstream?.isAlive()&&f.acpSessionId&&await f.downstream.sessionCancel({sessionId:f.acpSessionId}),{ok:!0}}case"session/set_mode":{let a=o,d=a.sessionId,f=a.modeId,u=Po(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!ln(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(!$t(e.framework,f))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(f)}; allowed: ${Hd(e.framework)}`);if(u)return await this.handleGroupSetMode(e,u,f);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===f)return{};let p=x.permissionMode;if(x.permissionMode=f,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:f})}catch(w){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),w}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:f});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${n}`)}}async handleGroupSetMode(e,n,i){let o=[];for(let[d,f]of e.sessions)f.cozeGroupId===n&&f.permissionMode!==i&&o.push({cloudId:d,runtime:f,oldMode:f.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:n,modeId:i}),{};W.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 f=d.runtime.downstream,u=d.runtime.acpSessionId;f?.isAlive()&&u&&a.push({downstream:f,acpSessionId:u,oldMode:d.oldMode,runtime:d.runtime})}for(let d of a)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(f){for(let u of o)u.runtime.permissionMode=u.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),f}return{}}async ensureRuntime(e,n,i,o){let a=e.sessions.get(n);if(a){let u=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){ri(a);let w=a.downstream;a.downstream=void 0,w&&await w.stop("request-context-changed")}return a.cozeGroupId=i,a.requestScene=o,(u||x||p)&&await this.persistSessionMapping(e),a}let f={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 ln(e)&&(e.framework==="hermes"?f.permissionMode=e.deployType==="cloud"?j0:W0:f.permissionMode=e.framework==="claude-code"?Vd:rx),e.sessions.set(n,f),await this.persistSessionMapping(e),f}async requestSessionToken(e,n,i){let o={sessionId:n,_meta:{cozeAgentId:e,...i?{cozeGroupId:i}:{}}};try{let a=await this.sendRequest(rt.GEN_MODEL_TOKEN,o,yS);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(ri(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,f=i.spawnFailedAt??0;if(d>=o&&Date.now()-f<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()-f))/1e3)}s`);let u;try{let x=this.requestSceneBySession.get(n);x&&W.info("spawn: injecting request_scene gateway header",{agentId:e.agentId,cloudId:n,requestScene:x}),u=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&&(W.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=u,this.attachRuntimeHooks(e,n,i);try{if(i.acpSessionId){i.loadingSession=!0;try{let x=await u.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace});W.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId}),this.piggybackModelList(e,x)}catch(x){W.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 u.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,this.piggybackModelList(e,p),await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await u.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,this.piggybackModelList(e,x),await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:n,acpId:i.acpSessionId,err:String(x)}),await u.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(u.afterSessionEstablished&&i.acpSessionId&&await u.afterSessionEstablished(i.acpSessionId),ln(e)&&i.acpSessionId&&i.permissionMode)try{await u.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:n,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,n,i){if(ri(i),this.isRuntimeBusy(e,i)){W.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)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,i);return}W.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=>W.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 f=e.activeGroupIds.get(n.acpSessionId);f&&(a.cozeGroupId=f)}await this.upstream.send(Zr("session/update",{sessionId:i,update:o,_meta:a}))}async synthesizePromptReply(e,n,i,o,a,d){let f={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return a&&(f.cozeTriggerMsgId=a),d&&(f.cozeGroupId=d),await this.upstream.send(Zr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:f})).catch(u=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(u)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let i=n.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let a=e.sessions.get(o);if(!a){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(IS(n)){W.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"&&ln(e)){let p=d.currentModeId;$t(e.framework,p)&&a.permissionMode!==p?(a.permissionMode=p,this.persistSessionMapping(e).catch(w=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(w)}))):typeof p=="string"&&!$t(e.framework,p)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}if(d&&typeof d=="object"&&d.sessionUpdate==="config_option_update"){let p=d.configOptions;Array.isArray(p)&&this.piggybackModelList(e,{configOptions:p})}let f={cozeAgentId:e.agentId,cozeReplySeqID:++a.replySeq},u=e.activeTriggers.get(i);u&&(f.cozeTriggerMsgId=u);let x=e.activeGroupIds.get(i);x&&(f.cozeGroupId=x),this.upstream.send(Zr("session/update",{...n,sessionId:o,_meta:f})).catch(p=>W.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}piggybackModelList(e,n){let i=this.modelListCache;if(i)try{let o=Z0(e.framework,n);if(!o)return;(bt(e.model)||e.model===Sd)&&o.currentModelId&&!o.defaultModelId&&(o.defaultModelId=o.currentModelId),o.models.length>0&&i.update(e.framework,o).catch(d=>W.warn("piggyback model-list update failed (ignored)",{agentId:e.agentId,err:String(d)})),(o.currentModelId||o.currentEffort||o.currentFastMode)&&i.setRuntimeCurrent(e.agentId,{...o.currentModelId?{model:o.currentModelId}:{},...o.currentEffort?{effort:o.currentEffort}:{},...o.currentFastMode?{fastMode:o.currentFastMode}:{}})}catch(o){W.warn("piggyback model-list parse failed (ignored)",{agentId:e.agentId,err:String(o)})}}warmupModelList(e){let n=this.modelListCache;if(!n||e.deployType!=="local")return;let i=e.framework,o=i==="claude-code"||i==="codex"||i==="hermes",a=i==="openclaw";if(!o&&!a||o&&!this.sessionSpawner||a&&!this.openclawModelLister||n.get(i)||this.modelListWarmupInFlight.has(i))return;this.modelListWarmupInFlight.add(i),(a?this.runOpenclawModelWarmup(i):this.runModelListWarmup(e,i)).finally(()=>this.modelListWarmupInFlight.delete(i))}async runOpenclawModelWarmup(e){if(this.openclawModelLister)try{let n=await this.openclawModelLister();n&&n.models.length>0?(await this.modelListCache?.update("openclaw",n),W.info("openclaw model-list warm-up done",{framework:e,count:n.models.length})):W.warn("openclaw model-list warm-up: empty CLI result (ignored)",{framework:e})}catch(n){W.warn("openclaw model-list warm-up failed (ignored)",{framework:e,err:String(n)})}}async runModelListWarmup(e,n){if(!this.sessionSpawner)return;let i;try{i=await this.sessionSpawner(e,"",ES,this.currentCozeEnv,this.currentMockScenario,void 0);let o=await i.sessionNew({cwd:e.workspace});this.piggybackModelList(e,o),W.info("model-list warm-up done",{agentId:e.agentId,framework:n})}catch(o){W.warn("model-list warm-up failed (ignored)",{agentId:e.agentId,framework:n,err:String(o)})}finally{await i?.stop("model-list warm-up done").catch(()=>{})}}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}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),n.respondAgentRequestError(i.id,{code:Q.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 vx(a,o);n.respondAgentRequest(i.id,d)}else{let a=i.params??{},d=await Sx(a,o);n.respondAgentRequest(i.id,d)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),n.respondAgentRequestError(i.id,ds(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??{},f=a.sessionId,u=f?e.activeTriggers.get(f):void 0,x={cozeAgentId:e.agentId};u&&(x.cozeTriggerMsgId=u);let p=f?e.activeGroupIds.get(f):void 0;p&&(x.cozeGroupId=p);let w=f?this.reverseSessionId(e,f):void 0,b=w?e.sessions.get(w):void 0;b&&(b.pendingPermission={downstream:n,agentRequestId:i.id,upstreamId:o});let _={...a,...w?{sessionId:w}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:n,method:i.method,cloudSessionId:w}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:f,cloudSessionId:w,toolCallId:a.toolCall?.toolCallId,options:a.options?.map(v=>({optionId:v.optionId,kind:v.kind,name:v.name}))}),this.upstream.send(as(o,"session/request_permission",_)).catch(v=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(v)}),n.respondAgentRequestError(i.id,{code:Q.INTERNAL_ERROR,message:`upstream send failed: ${String(v)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let o=n.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&vS(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new qo(e.error)):i.value.resolve(e.result);return}W.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 W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:a}),{value:d,key:a}}}sendRequest(e,n,i=gS){let o=this.upstreamIds.next(e);return new Promise((a,d)=>{let f=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:f}),this.upstream.send(as(o,e,n)).catch(u=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(u)})})}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&&ln(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 Si(e.agentId,n,this.paths)}catch(n){W.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(Bn(e,{code:n,message:i,data:{bridgeVersion:Kt}}))}};function bS(){return pS(16).toString("hex")}function vS(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){W.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"){W.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")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:a,result:t})}var SS=["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."],Rx="Warning: ";function IS(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(Rx)?i.text.slice(Rx.length):i.text;return SS.some(a=>o.startsWith(a))}Ct();ne();Pe();import{randomBytes as AS}from"node:crypto";import{createServer as kS}from"node:http";var TS=1e6,Px=q("ipc"),oa=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=AS(32).toString("hex");let e=kS((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(),Px.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 _t(this.paths.portFile,String(this.port)),await _t(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ps(n,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,a=this.routes.get(o);if(!a){ps(n,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await CS(e)}catch(f){ps(n,400,{error:"invalid json",detail:String(f)});return}try{let f=await a.handler(d,e);ps(n,200,f??{ok:!0})}catch(f){Px.error("IPC handler failed",{key:o,err:String(f)}),ps(n,500,{error:f instanceof Error?f.message:String(f)})}}};function ps(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function CS(t){let e=[],n=0;for await(let o of t){let a=o;if(n+=a.length,n>TS)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 J1=en(Ap(),1),Z1=en(pa(),1),X1=en(ai(),1),Y1=en(cl(),1),Q1=en(fl(),1),eI=en(ml(),1),Mp=en(_a(),1),tI=en(Lp(),1);var Np=Mp.default;Ze();ne();var{FWS:mI}=$p(),Ne=q("upstream.frontier"),Jp="application/json",Zp="none",wI=15e3;function _I(t){class e extends Np{constructor(i){super(i,R0,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Ne.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(of("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");Ne.debug("WS raw frame out",{bytes:a.byteLength,headHex:d})}catch(a){Ne.warn("WS raw frame dump failed",{err:String(a)})}super.send(i,...o)}}return e}var Ss=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){Ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:P0,...Nn(this.opts.ppeOverride)},n=_I(e),i=O0(this.opts.urlOverride),o={url:i,ws:n,fpID:C0,aID:Mo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Jp,force:!0},payloadEncoding:{encoding:Zp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},a=new mI(o),d=!1,f=null,u,x,p=new Promise((_,v)=>{u=_,x=v}),w=_=>{d||(d=!0,f&&(clearTimeout(f),f=null),_?x(_):u())};a.onopen=()=>{this.opened=!0,this.openCount+=1;let _=this.openCount===1;Ne.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:_,openCount:this.openCount}),_&&w();for(let v of this.connectHandlers)Promise.resolve(v({initial:_})).catch(I=>Ne.warn("onConnect handler threw (ignored)",{err:String(I)}))},a.onclose=_=>{this.opened=!1,Ne.info("frontier closed",{code:_.code,reason:_.reason,willReconnect:_.willReconnect})},a.onerror=_=>{Ne.warn("frontier error",{code:_.code,msg:_.message}),w(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${_.code} msg=${_.message??""}`))},a.onmessage=_=>this.handleMessage(_),this.fws=a;let b=this.opts.openTimeoutMs??wI;f=setTimeout(()=>{w(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${b}ms (handshake or upgrade slow)`))},b),await a.connect();try{await p}catch(_){try{a.close(1e3,"open failed")}catch(v){Ne.warn("fws close during start failure threw (ignored)",{err:String(v)})}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){Ne.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let n=this.fws,i=e.method;if(!n)throw Ne.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let f=Date.now();throw f-this.lastSendRefusedLogAt>1e3?(Ne.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:n.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=f,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;Xp(a)||Ne.info("frontier frame out",{method:a.method,jsonrpcId:a.id,size:o.length});try{await n.send(o,{service:33555712,method:1,payloadType:Jp,payloadEncoding:Zp})}catch(f){throw Ne.warn("frontier frame send failed",{method:a.method,jsonrpcId:a.id,err:String(f)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(f)}`,{cause:f})}}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){Ne.debug("drop non-adapter frontier frame",{service:n});return}let i=bI(e);if(!i){Ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Ne.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Ne.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let a=o;Xp(a)||Ne.info("frontier frame in",{logid:EI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:a.id,method:a.method,body:yI(i)}),Promise.resolve(this.handler(o)).catch(d=>Ne.warn("frontier frame handler threw",{err:String(d)}))}};function Xp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Yp=2e3;function yI(t){return t.length<=Yp?t:`${t.slice(0,Yp)}...<truncated, total ${t.length} chars>`}function EI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function bI(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}Ze();ne();var El=q("skill-publish"),vI="/api/marketplace/product/skill/publish_with_assets",SI=15e4;async function Qp(t,e={}){let i=`${Wr(Kr(e.handshakeBase))}${vI}`,o=e.timeoutMs??SI,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",...Nn(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},f=new AbortController,u=setTimeout(()=>f.abort(),o);El.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:f.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let _=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${_.slice(0,200)}`)}let w=await x.json();if(El.info("skill publish response",{logid:p,httpStatus:x.status,code:w.code,msg:w.msg,dataSkillId:w.data?.skill_id??"",dataVersion:w.data?.version??""}),w.code!==void 0&&w.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${w.code} msg=${w.msg??"-"} logid=${p}`);let b={};return w.data?.skill_id!==void 0&&w.data.skill_id!==""&&(b.skillId=String(w.data.skill_id)),w.data?.version&&(b.version=w.data.version),El.info("skill publish ok",{logid:p,skillId:b.skillId??"",version:b.version??""}),b}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(u)}}ne();var bl=q("upstream.switchable"),Ta=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;bl.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 bl.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(n??"swapped").catch(o=>bl.warn("previous upstream stop threw (ignored)",{err:String(o)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var vl=q("upstream"),hi=class{handler=null;async start(){vl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){vl.info("NoopUpstream stopped",{reason:e})}async send(e){vl.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)}};Ze();ne();Ct();ne();Pe();import{promises as II}from"node:fs";var eg=q("pat-token-store");async function Ca(t=Z()){try{let n=(await II.readFile(t.patTokenFile,"utf8")).trim();return n.length===0?(eg.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"&&eg.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function Is(t,e=Z()){if(!t)throw new Error("writePatToken: empty patToken");await _t(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as Ra}from"node:fs";import{join as AI}from"node:path";function kI(t,e){return`#!/bin/sh
119
119
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
120
- `}function CA(t,e){return`@echo off\r
120
+ `}function TI(t,e){return`@echo off\r
121
121
  "${e}" "${t}" %*\r
122
- `}async function Yp(t,e=Z()){let n=e.binDir;await Sa.mkdir(n,{recursive:!0});let i=AA(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),s=process.execPath,a=process.platform==="win32"?CA(t,s):kA(t,s);return await Sa.readFile(i,"utf8").catch(()=>null)===a||(await Sa.writeFile(i,a,"utf8"),process.platform!=="win32"&&await Sa.chmod(i,493)),n}ne();Ce();import{execSync as Xp}from"node:child_process";import{readFileSync as Qp,unlinkSync as TA}from"node:fs";import{mkdir as PA,open as DA,readFile as eg,unlink as _l,writeFile as RA}from"node:fs/promises";import{dirname as OA}from"node:path";var LA=G("single-instance"),MA=t=>new Promise(e=>setTimeout(e,t)),Ia=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Z().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:n=>ss(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&&LA.warn("removing stale pid file",{stalePid:i}),await RA(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return n.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),n}async release(){if(this.acquired){try{(await eg(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await _l(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let n=await eg(e,"utf8"),i=Number.parseInt(n.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(n){if(n.code==="ENOENT")return null;throw n}}async withClaimLock(e){let n=`${this.pidFile}.lock`;await PA(OA(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let s;try{s=await DA(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 MA(this.claimLockIntervalMs);continue}await _l(n).catch(()=>{});continue}try{return await s.writeFile(String(this.selfPid)),await e()}finally{await s.close().catch(()=>{}),await _l(n).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${n} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=Qp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Jr)||n.includes("lib/index.js"))}catch{}try{let n=Xp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Jr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Xp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let s=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return s.includes("node")||s.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Qp(this.pidFile,"utf8").trim()===String(this.selfPid)&&TA(this.pidFile)}catch{}})}};Aa();ne();var xr=G("daemon.upstream-watchdog"),qA=12e4,jA=9e5,WA=3e4;function bl(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var ka=class{constructor(e){this.opts=e;this.softMs=e.softMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",qA),this.hardMs=e.hardMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",jA),this.intervalMs=e.intervalMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",WA),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?.(),xr.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&&xr.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&&xr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,xr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){xr.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,xr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>xr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var q=G("daemon");async function rg(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){Xl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:T=>De(T,t).logs,listAgentIds:()=>Os(t)});try{let{writeFileSync:T}=await import("node:fs");T(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
122
+ `}async function tg(t,e=Z()){let n=e.binDir;await Ra.mkdir(n,{recursive:!0});let i=AI(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,a=process.platform==="win32"?TI(t,o):kI(t,o);return await Ra.readFile(i,"utf8").catch(()=>null)===a||(await Ra.writeFile(i,a,"utf8"),process.platform!=="win32"&&await Ra.chmod(i,493)),n}ne();Pe();import{execSync as ng}from"node:child_process";import{readFileSync as rg,unlinkSync as CI}from"node:fs";import{mkdir as RI,open as PI,readFile as ig,unlink as Sl,writeFile as DI}from"node:fs/promises";import{dirname as OI}from"node:path";var LI=q("single-instance"),MI=t=>new Promise(e=>setTimeout(e,t)),Pa=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=>ls(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&&LI.warn("removing stale pid file",{stalePid:i}),await DI(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 ig(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Sl(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 ig(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 RI(OI(n),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await PI(n,"wx")}catch(a){if(a.code!=="EEXIST")throw a;let d=await this.readPidFrom(n);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await MI(this.claimLockIntervalMs);continue}await Sl(n).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Sl(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=rg(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes(Qr)||n.includes("lib/index.js"))}catch{}try{let n=ng(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes(Qr)||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=ng(`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{rg(this.pidFile,"utf8").trim()===String(this.selfPid)&&CI(this.pidFile)}catch{}})}};Da();ne();var mr=q("daemon.upstream-watchdog"),GI=12e4,jI=9e5,WI=3e4;function Al(t,e){let n=process.env[t];if(!n)return e;let i=Number(n);return Number.isFinite(i)&&i>0?i:e}var Oa=class{constructor(e){this.opts=e;this.softMs=e.softMs??Al("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",GI),this.hardMs=e.hardMs??Al("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",jI),this.intervalMs=e.intervalMs??Al("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",WI),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?.(),mr.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&&mr.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&&mr.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,mr.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){mr.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,mr.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>mr.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var G=q("daemon");async function ag(){let t=Z();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){rf({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:C=>Oe(C,t).logs,listAgentIds:()=>Bs(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
123
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
124
124
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
125
- `)}catch{}}let e=new Ia({processTitle:Jr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await Xo(),s=i??{};Ts({pid:process.pid}),q.info(i?"loaded bridge config":"initialized bridge config");let a=new va(new di),d=new Yo(t.modelCacheFile);await d.loadFromDisk().catch(T=>q.warn("modelListCache.loadFromDisk failed (ignored)",{err:String(T)}));let u=null,h=async()=>{let T=s.frameworksCache?.openclaw?.path;return T?V0(T):null},x=new Qo({upstream:a,paths:t,bridgeConfig:s,modelListCache:d,openclawModelLister:h,sessionSpawner:async(T,H,j,ee,ae,it)=>{if(!u)throw new Error("agentManager not ready");return u.spawnSessionDownstream(T,H,j,ee,ae,it)}}),p=new Vo({paths:t,config:s,registry:x});u=p;let w,b,y=null,v={},I,A=null,C=null,P=null,E=new Kt;function D(T,H){return E.enqueue(()=>U(T,H))}function O(){C||(C=new ka({isConnected:()=>a.isConnected()&&!(A?.isLivenessLost()??!1),forceReconnect:()=>P?D(P,{force:!0}):void 0,onFatal:T=>{if(process.env[bs]==="1"){q.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:T});return}q.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:T}),process.exit(1)}})),C.start()}async function U(T,H){let j=T,ee=j?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let ae=Xi(j.env),it=j.handshake_url,lt=j.frontier_url,Nt=ng(j.env,it,lt);if(P=j,!H?.force&&w===ee&&b===Nt){let Ne=await KA(t);return x.agents.size===0&&Ne?(q.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ta(t,p).catch(pe=>q.warn("connect-noop auto-revive error (ignored)",{err:String(pe)}))):q.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Yt=!!w&&w!==ee,gn=b!==void 0&&b!==Nt,zn=Yt||gn,mt=await md({privatecode:ee,...it?{endpoint:it}:{},ppeOverride:ae});if(zn){q.warn("connect config switched, resetting agents",{pcChanged:Yt,envChanged:gn,previousPc:w?Ca(w):"",nextPc:Ca(ee)});for(let Ne of[...x.agents.values()])await Ne.dispose("connect config switch").catch(()=>{}),x.agents.delete(Ne.agentId);x.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on connect config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new di,"connect switch").catch(()=>{})}y=mt.deviceId,Ts({deviceId:y,pid:process.pid}),Wd({patToken:ee,env:j.env}).catch(Ne=>q.warn("coze-cli setup error (ignored)",{err:String(Ne)}));let pr=new _s({handshake:mt,privatecode:ee,...lt?{urlOverride:lt}:{},ppeOverride:ae,getPatTokenForAgent:Ne=>x.agents.get(Ne)?.patToken});return await a.swap(pr,"connect"),w=ee,b=Nt,v=ae,I=it,j.mock_scenario!==void 0&&(x.setMockScenario(j.mock_scenario),q.info("mock scenario set",{scenario:j.mock_scenario})),A||(A=new ts({core:x,getDeviceId:()=>y??"",onTickEnd:()=>V.retryPending().catch(Ne=>q.warn("detailSync.retryPending failed (ignored)",{err:String(Ne)})),onAuthFailures:ie})),A.start(),O(),zn&&Ta(t,p).catch(Ne=>q.warn("post-connect-switch auto-revive error (ignored)",{err:String(Ne)})),ys(ee,t).catch(Ne=>q.warn("writePatToken after /connect failed (ignored)",{err:String(Ne)})),q.info("/connect: WS established",{deviceId:y}),{ok:!0,note:"connected"}}x.registerExtension("_agent/create",async T=>p.createAgent(T.params)),x.registerExtension("_agent/health",async()=>({ok:!0}));let M={},K=new Oo({agents:x.agents,modelListCache:d,openclawModelLister:h,paths:t,publishSkillToMarketplace:async T=>{let H=x.agents.get(T.agentId)?.patToken??w;if(!H)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Jp({patToken:H,zip:T.zip,...T.skillId?{skillId:T.skillId}:{},skillName:T.skillName,...T.description?{description:T.description}:{},agentId:T.agentId,...T.accountId?{accountId:T.accountId}:{}},{handshakeBase:I,ppeOverride:v})},disposeAndMarkDisconnected:async(T,H)=>{let j=x.agents.get(T);if(j){await p.cleanupOpenclawSessionProviders(j).catch(ae=>q.warn("cleanup openclaw providers failed (ignored)",{agentId:T,err:String(ae)})),j.framework==="hermes"&&j.deployType==="cloud"&&await Id(T,t).catch(ae=>q.warn("cleanup hermes-home failed (ignored)",{agentId:T,err:String(ae)}));let ee=!0;try{await j.dispose(`disconnect: ${H}`)}catch(ae){ee=!1,q.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:T,err:String(ae)}),j.status="error"}ee&&(j.status="disconnected",x.unregister(T),x.disconnectedAgents.add(T))}else x.disconnectedAgents.add(T)},disposeForDelete:async(T,H)=>{let j=x.agents.get(T);j&&(await p.cleanupOpenclawSessionProviders(j).catch(ee=>q.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:T,err:String(ee)})),j.framework==="hermes"&&j.deployType==="cloud"&&await Id(T,t).catch(ee=>q.warn("cleanup hermes-home during delete failed (ignored)",{agentId:T,err:String(ee)})),await j.dispose(`delete: ${H}`).catch(ee=>q.warn("dispose during delete failed (ignored)",{agentId:T,err:String(ee)})),x.unregister(T)),x.disconnectedAgents.delete(T)},detailSyncer:async T=>{if(!M.ref)throw new Error("agent-detail-sync not initialized yet");await M.ref.syncOne(T)},cleanupOpenclawProviders:async(T,H)=>{await p.cleanupOpenclawSessionProviders(T,H)},openclawRepair:async(T,H)=>{await p.openclawRepair(T,H)},hermesReset:async(T,H)=>{let j=await ge(T).catch(()=>null);!j||j.framework!=="hermes"||j.deployType!=="cloud"||await G0({paths:t,agentId:T,model:j.model,modelInfo:j.modelInfo,cozeEnv:H,mockScenario:x.getMockScenario()})},isRuntimePendingPermission:T=>x.hasPendingPermissionFor(T)});x.registerExtension("_agent/listSkills",T=>K.listSkills(T.params)),x.registerExtension("_agent/addSkills",T=>K.addSkills(T.params)),x.registerExtension("_agent/removeSkills",T=>K.removeSkills(T.params)),x.registerExtension("_agent/publishSkill",T=>K.publishSkill(T.params)),x.registerExtension("_agent/getFileTree",T=>K.getFileTree(T.params)),x.registerExtension("_agent/getFileContent",T=>K.getFileContent(T.params)),x.registerExtension("_agent/update",T=>K.updateAgent(T.params)),x.registerExtension("_agent/disconnect",T=>K.disconnectAgent(T.params)),x.registerExtension("_agent/switchModel",T=>K.switchModel(T.params)),x.registerExtension("_agent/setConfigOption",T=>K.setConfigOption(T.params)),x.registerExtension("_agent/listAvailableModels",T=>K.listAvailableModels(T.params)),x.registerExtension("_agent/detail",T=>K.detail(T.params)),x.registerExtension("_agent/reset",T=>K.resetAgent(T.params)),x.registerExtension("_agent/repair",T=>K.repairAgent(T.params)),x.registerExtension("_agent/delete",T=>K.deleteAgent(T.params)),x.registerExtension("_agent/upgrade",T=>K.upgradeBridge(T.params));let V=new Ns({paths:t,handlers:K,agentManager:p,sendDetail:T=>x.sendRequest("_agent/detail",T)});M.ref=V;let ie=async T=>{await Promise.allSettled(T.map(async H=>{try{await K.disconnectAgent({agentId:H.agentId,reason:`auth_failure: code=${H.code} ${H.message}`}),q.info("agent disconnected due to auth failure from heartbeat response",{agentId:H.agentId,code:H.code,message:H.message})}catch(j){q.warn("disconnect during authFailure handling failed (ignored)",{agentId:H.agentId,err:String(j)})}}))};a.onConnect(({initial:T})=>{q.info("frontier upstream connected, triggering detail sync",{initial:T}),V.syncAll(T?"initial-connect":"reconnect").catch(H=>q.warn("detail sync top-level error (ignored)",{err:String(H)}))});let X=new ea({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let T=x.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[bs]==="1"?"manual":"supervisor",agents:[...x.agents.keys()],deviceId:y??"",frameworksCache:s.frameworksCache??{},...T?{mockScenario:T}:{}}}},{method:"POST",path:"/pair",handler:async T=>{let H=T,j=H?.privatecode,ee=H?.pairing_code;if(!j||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ae=Xi(H.env),it=H.handshake_url,lt=H.frontier_url,Nt=ng(H.env,it,lt),Yt=!!w&&w!==j,gn=b!==void 0&&b!==Nt,zn=Yt||gn,mt=await md({privatecode:j,...it?{endpoint:it}:{},ppeOverride:ae});if(zn){q.warn("pair config switched, resetting agents",{pcChanged:Yt,envChanged:gn,previousPc:w?Ca(w):"",nextPc:Ca(j),previousEnvKey:b??"",nextEnvKey:Nt});for(let pe of[...x.agents.values()])await pe.dispose("pair config switch").catch(()=>{}),x.agents.delete(pe.agentId);x.disconnectedAgents.size>0&&(q.info("clearing disconnectedAgents set on pair config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new di,"pair switch").catch(()=>{})}y=mt.deviceId,Ts({deviceId:y,pid:process.pid}),Wd({patToken:j,env:H.env}).catch(pe=>q.warn("coze-cli setup error (ignored)",{err:String(pe)}));let pr=new _s({handshake:mt,privatecode:j,...lt?{urlOverride:lt}:{},ppeOverride:ae,getPatTokenForAgent:pe=>x.agents.get(pe)?.patToken});await a.swap(pr,"pair");try{let pe=new ar;s.frameworksCache=await pe.detectAll(),await cs(s),q.info("frameworks_cache refreshed before pair",{detected:Object.keys(s.frameworksCache)})}catch(pe){q.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(pe)})}let Ne=Object.keys(s.frameworksCache??{});try{let pe=await x.sendRequest("_agent/pair",{pairCode:ee,patToken:j,frameworks:Ne,_meta:{cozeDeviceId:y}});q.info("_agent/pair ok",{pairResult:pe}),w=j,b=Nt,v=ae,I=it,H.mock_scenario!==void 0&&(x.setMockScenario(H.mock_scenario),q.info("mock scenario set",{scenario:H.mock_scenario})),ys(j,t).catch(ut=>q.warn("writePatToken after /pair failed (ignored)",{err:String(ut)})),A||(A=new ts({core:x,getDeviceId:()=>y??"",onTickEnd:()=>V.retryPending().catch(ut=>q.warn("detailSync.retryPending failed (ignored)",{err:String(ut)})),onAuthFailures:ie})),A.start(),O(),zn&&Ta(t,p).catch(ut=>q.warn("post-pair-switch auto-revive error (ignored)",{err:String(ut)}));let ce;return H.agent_id&&(ce=await VA(H.agent_id,t,p,ut=>x.sendRequest("_agent/detail",ut),j).catch(ut=>(q.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(ut)}),{ok:!1,agentId:H.agent_id??"",note:String(ut)}))),{ok:!0,note:"paired with cloud",...ce?{agent:ce}:{}}}catch(pe){return q.error("_agent/pair failed",{err:String(pe)}),{ok:!1,note:`pair failed: ${String(pe)}`}}}},{method:"POST",path:"/connect",handler:T=>D(T)},{method:"POST",path:"/_agent/create",handler:async T=>{let H=T;return{ok:!0,result:await p.createAgent(H)}}},{method:"POST",path:"/agent/send",handler:async T=>{let H=T;if(!H?.agentId||!H?.sessionId||!H?.kind||!H?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!w)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=H;return await(j.groupFile?dx:cx)(j,{core:x,patToken:w,handshakeBase:I,ppeOverride:v})}catch(j){if(j instanceof k)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async T=>{let H=T?.agent_id,j=await x.reloadAgents(H);return q.info("IPC /reload: recycled agent subprocesses",{agentId:H??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(q.info("IPC /shutdown received"),setImmediate(()=>{ze.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:oe,token:de}=await X.start();try{await Yp(t.libEntry,t)}catch(T){q.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(T)})}await x.start(),JA({paths:t,core:x,agentManager:p,detectAll:async()=>(s.frameworksCache=await new ar().detectAll(),await cs(s),s.frameworksCache)}).catch(T=>q.warn("startup warmup error (ignored)",{err:String(T)})),cu().then(async()=>{let{probeAcpVersion:T}=await Promise.resolve().then(()=>(yn(),ou));for(let H of["claude-code","codex"]){let j=await T(H);j&&q.info("acp wrapper version",{framework:H,version:j})}}).catch(T=>q.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(T)}));let ye=null,ze={port:oe,token:de,core:x,ipc:X,shutdown(T){return ye||(q.info("daemon shutdown",{reason:T}),ye=(async()=>{A?.stop(),C?.stop(),await x.stop(T),await X.stop(),await e.release()})(),ye)}};for(let T of["SIGTERM","SIGINT"])process.on(T,()=>{ze.shutdown(T).then(()=>process.exit(0))});return process.on("exit",()=>vh()),process.on("unhandledRejection",T=>{q.error("unhandledRejection",{reason:T instanceof Error?T.message:String(T),stack:T instanceof Error?T.stack:void 0})}),process.on("uncaughtException",T=>{q.error("uncaughtException (will exit, supervisor will restart)",{message:T.message,stack:T.stack,name:T.name});try{process.stderr.write(`FATAL uncaughtException: ${T.stack??T.message}
126
- `)}catch{}process.exit(1)}),q.info("daemon ready",{port:oe,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(s.frameworksCache??{}),libVersion:s.libVersion??"dev"}),YA({cliSpawned:process.env[bs]==="1",readPatToken:()=>Ea(t),connect:D}).catch(T=>q.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(T)})),ze}async function KA(t){return Os(t).length>0}function Ca(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function ng(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function $A(t,e){let n=Os(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(Qt(),Ms));for(let a of n){await s(a,t).catch(d=>q.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),q.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),q.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){q.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function VA(t,e,n,i,s){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(Qt(),Ms)),d=await a(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);q.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=ig(d),w={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...s?{patToken:s}:{},...p?{_meta:p}:{}};return await n.createAgent(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}q.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new 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 h={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...s?{patToken:s}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await n.createAgent(h);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function JA(t){let e=t.logger??q;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 $A(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Ta(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await ZA(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Ta(t,e){let{readdir:n}=await import("node:fs/promises"),i;try{i=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(Qt(),Ms));q.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=0;for(let u of i){let h;try{h=await s(u,t)}catch(x){q.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!h){d+=1;continue}if(h.deletedAt){q.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:h.deletedAt}),d+=1;continue}if(h.disconnectedAt){q.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:h.disconnectedAt}),d+=1;continue}try{q.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:h.framework});let x=ig(h);await e.createAgent({agentId:h.agentId,framework:h.framework,...h.cozeIdentity?{cozeIdentity:h.cozeIdentity}:{},...h.model?{model:h.model}:{},...x?{_meta:x}:{}},{revive:!0}),a+=1}catch(x){q.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:h.framework,err:String(x)}),d+=1}}return q.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function ZA(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let s of n)try{(await lh(s,t)).status==="refreshed"&&(i+=1)}catch(a){q.warn("refresh builtin skills failed (skipping agent)",{agentId:s,err:String(a)})}return i>0&&q.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function YA(t){let e=t.logger??q;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function ig(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Aa();Ce();import{readFile as sg}from"node:fs/promises";var pn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let n=await Pa(this.paths);if(!n)return{kind:"not-running"};try{let i=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...n,body:i.body}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:QA(i)}}}async request(e){let n=await Pa(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let i=n.body!==void 0,s={Authorization:`Bearer ${e.token}`};i&&(s["content-type"]="application/json");let a=new AbortController,d=setTimeout(()=>a.abort(),n.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:s,body:i?JSON.stringify(n.body):void 0,signal:a.signal}),h=await u.text();return{status:u.status,body:XA(h)}}finally{clearTimeout(d)}}};async function Pa(t){try{let[e,n]=await Promise.all([sg(t.portFile,"utf8"),sg(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),s=n.trim();return!Number.isFinite(i)||i<=0||!s?null:{port:i,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}function XA(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function QA(t){return t instanceof Error?t.message:String(t)}an();ne();_r();import{spawn as e2}from"node:child_process";import{userInfo as ag}from"node:os";var vl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",t2=new Set(["bash","zsh","sh","dash","ksh"]),og=$e("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),n2=2e3;function r2(t,e=vl){let n=t.indexOf(e);if(n===-1)return null;let i=t.indexOf(e,n+e.length);if(i===-1)return null;let s=t.slice(n+e.length,i),a={};for(let d of s.split(`
127
- `)){let u=d.indexOf("=");u<=0||(a[d.slice(0,u)]=d.slice(u+1))}return a}function i2(){let t=(process.env.SHELL??"").trim()||(ag().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return t2.has(e)?t:null}function s2(t){return new Promise(e=>{let n=`printf '%s' '${vl}'; env; printf '%s' '${vl}'`,i;try{i=e2(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??ag().homedir}})}catch{e(null);return}let s="",a=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{a||(a=!0,clearTimeout(h),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{s+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(s.length>0?s:null));let h=setTimeout(()=>d("SIGTERM"),og),x=setTimeout(()=>{d("SIGKILL"),u(s.length>0?s:null)},og+n2)})}async function El(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=i2();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??s2)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let s=r2(i);return s==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:s}}Ce();function Fn(t,...e){let n=[],i;for(let s=0;s<t.length;s++){let a=t[s],d=!1;for(let u of e){if(a===u){i=t[s+1],s+=1,d=!0;break}if(a.startsWith(`${u}=`)){i=a.slice(u.length+1),d=!0;break}}d||n.push(a)}return{value:i,rest:n}}yn();import{chmod as o2,copyFile as cg,mkdir as lg,readFile as Es,rename as dg,rm as Al,stat as ug,writeFile as a2}from"node:fs/promises";import{homedir as p3}from"node:os";import{dirname as c2,join as Me,resolve as kl,sep as vs}from"node:path";import{fileURLToPath as d2}from"node:url";an();ne();Ce();function li(t,e,n,i){at(t.bridgeLogsDir,e,"dist-install",n,i)}function fg(){return{darwin:{arm64:"@openai/codex-darwin-arm64",x64:"@openai/codex-darwin-x64"},linux:{arm64:"@openai/codex-linux-arm64",x64:"@openai/codex-linux-x64"},win32:{arm64:"@openai/codex-win32-arm64",x64:"@openai/codex-win32-x64"}}[process.platform]?.[process.arch]}function l2(){return{darwin:{arm64:Me("vendor","aarch64-apple-darwin","bin","codex"),x64:Me("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Me("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Me("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Me("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Me("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function u2(t){let e=d2(t),n=c2(e),i=`${vs}src${vs}`;if(n.includes(i)||n.endsWith(`${vs}src${vs}cli`))return null;let s=kl(n,"index.js"),a=kl(n,"..","package.json");return{dist:s,pkgJson:a}}async function Cl(t={}){let e=t.paths??Z(),n=u2(import.meta.url),i=t.sourceDist??n?.dist,s=t.sourcePackageJson??n?.pkgJson;if(!i||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let a,d;try{let v=JSON.parse(await Es(s,"utf8"));a=v.version??"unknown",d=v.dependencies??{}}catch(v){throw li(e,"error","cannot read source package.json",{err:String(v)}),new Error(`cannot read source package.json: ${String(v)}`,{cause:v})}let u=Ds.map(v=>({name:v,spec:d[v]??"latest"})),h=u.map(({name:v,spec:I})=>`${v}@${I}`),x=await Xo(e.configFile)??{},p=x.libVersion,w=await Es(e.libEntry).then(()=>!0).catch(()=>!1),b=p===a,y=await hg(e,u);if(b&&w&&y)return{kind:"already-current",libVersion:a};if(!b||!w){await lg(e.libDir,{recursive:!0}),await cg(i,e.libEntry),await cg(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=kl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
128
- `;await Es(v,"utf8").catch(()=>null)!==I&&await a2(v,I)}return y||(t.installWrappers?await t.installWrappers(e,h):await x2(e,h,u)),x.libVersion=a,await cs(x,e.configFile),li(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:a}),b&&w?{kind:"already-current",libVersion:a}:p?{kind:"version-changed",fromVersion:p,toVersion:a,libEntry:e.libEntry}:{kind:"first-install",libVersion:a,libEntry:e.libEntry}}async function hg(t,e){for(let n of e){let i=Me(t.libDir,"node_modules",...n.name.split("/"),"package.json"),s;try{s=JSON.parse(await Es(i,"utf8"))}catch(d){return li(t,"debug","wrapper not ready: package.json read failed",{package:n.name,expected:n.spec,pkgJson:i,err:String(d)}),!1}let a=s.version;if(!a)return li(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!f2(a,n.spec))return li(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await xg(Me(t.libDir,"node_modules"))}function f2(t,e){let n=Sl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=Sl(i.slice(1));if(!a)return!0;if(Il(n,a)<0)return!1;let d=h2(a);return Il(n,d)<0}let s=Sl(i);return s?Il(n,s)===0:!0}function h2(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function Sl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Il(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 x2(t,e,n){await m2(t.installLock,async()=>{if(await hg(t,n))return;let i=Math.random().toString(36).slice(2,10),s=`${t.libDir}${vs}.staging-${process.pid}-${i}`,a=Me(s,"node_modules"),d=Me(t.libDir,"node_modules");try{await lg(s,{recursive:!0}),await p2(e,s),await g2(a);let u=`${d}.trash-${i}`;await dg(d,u).catch(()=>{}),await dg(a,d),await Al(u,{recursive:!0,force:!0}).catch(()=>{}),li(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Al(s,{recursive:!0,force:!0}).catch(()=>{})}})}function p2(t,e){let n=["install",...t,"--prefix",e,"--omit=dev","--include=optional","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,s)=>{let a=dt("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",h=>{d.length<8192&&(d+=h.toString("utf8"))});let u=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",h=>{clearTimeout(u),s(new Error(`spawn npm failed: ${String(h)}`))}),a.once("close",h=>{clearTimeout(u),h===0?i():s(new Error(`npm install \u9000\u51FA\u7801 ${h}: ${d.trim().slice(0,2e3)}`))})})}async function g2(t){for(let e of Ds){let n=Me(t,...e.split("/")),i=JSON.parse(await Es(Me(n,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let s=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!s)throw new Error(`${e}: package.json \u7F3A bin`);let a=Me(t,".bin",s),d=await ug(a);process.platform!=="win32"&&!(d.mode&73)&&await o2(a,d.mode|73).catch(()=>{})}if(!await xg(t)){let e=fg()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function xg(t){let e=fg(),n=l2();if(!e||!n)return!0;let i=Me(t,"@openai","codex"),s=Me(t,...e.split("/")),a=[Me(i,"package.json"),Me(i,"bin","codex.js"),Me(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Me(s,"package.json"),Me(s,n)];return(await Promise.all(a.map(u=>ug(u).then(h=>h.isFile()).catch(()=>!1)))).every(Boolean)}async function m2(t,e){let{open:n}=await import("node:fs/promises"),i=!1;for(let s=0;s<60&&!i;s++)try{await(await n(t,"wx")).close(),i=!0}catch{await new Promise(a=>setTimeout(a,500))}try{return await e()}finally{i&&await Al(t,{force:!0}).catch(()=>{})}}Xa();ne();Ce();import{closeSync as gg,fstatSync as mg,openSync as wg,readFileSync as w2,readSync as _2,readdirSync as y2,statSync as b2}from"node:fs";import{join as Da}from"node:path";var v2=new Set(["debug","info","warn","error"]);function _g(t){let e=t,n=Fn(e,"--agent-id");e=n.rest;let i=Fn(e,"--date");e=i.rest;let s=Fn(e,"-n","--lines");e=s.rest;let a=Fn(e,"--level");e=a.rest;let d=Fn(e,"--grep");e=d.rest;let u=s.value===void 0?200:Number(s.value),h=Number.isInteger(u)&&u>=0?u:200,x=a.value&&v2.has(a.value)?a.value:void 0,p={lines:h,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 E2(t,e){return t.agentId?Da(De(t.agentId,e).logs,yr("agent",t.date)):Da(e.bridgeLogsDir,yr("bridge",t.date))}function S2(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function I2(t,e){let n;try{n=y2(t)}catch{return[]}let i=[];for(let s of n){let a=Ya(s,e);if(!a)continue;let d=0;try{d=b2(Da(t,s)).size}catch{}i.push({file:Da(t,s),date:a,size:d})}return i.sort((s,a)=>a.date.localeCompare(s.date)),i}function yg(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let n;try{n=JSON.parse(t).level}catch{return!0}if(typeof n=="string"&&!tu(n,e.level))return!1}return!0}var pg={debug:"90",info:"36",warn:"33",error:"31"},A2=new Set(["ts","level","module","msg"]);function k2(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function bg(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=k2(n.ts),s=typeof n.level=="string"?n.level:"",a=s.toUpperCase().padEnd(5);e.color&&pg[s]&&(a=`\x1B[${pg[s]}m${a}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",u=typeof n.msg=="string"?n.msg:"",h=Object.entries(n).filter(([x])=>!A2.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${a} ${d} ${u}${h}`}function C2(t,e,n){let a=w2(t,"utf8").split(`
129
- `).filter(d=>d.length>0).filter(d=>yg(d,{level:e.level,grep:e.grep}));for(let d of S2(a,e.lines))process.stdout.write(`${bg(d,{raw:e.raw,color:n})}
130
- `)}async function vg(t,e){let n=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?De(t.agentId,n).logs:n.bridgeLogsDir,u=t.agentId?"agent":"bridge",h=I2(d,u);if(h.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
131
- `),1;for(let x of h)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
132
- `);return 0}let s=t.date??Hn(new Date),a=E2({agentId:t.agentId,date:s},n);try{C2(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
125
+ `)}catch{}}let e=new Pa({processTitle:Qr}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let i=await ia(),o=i??{};Ls({pid:process.pid}),G.info(i?"loaded bridge config":"initialized bridge config");let a=new Ta(new hi),d=new ra(t.modelCacheFile);await d.loadFromDisk().catch(C=>G.warn("modelListCache.loadFromDisk failed (ignored)",{err:String(C)}));let f=null,u=async()=>{let C=o.frameworksCache?.openclaw?.path;return C?Y0(C):null},x=new sa({upstream:a,paths:t,bridgeConfig:o,modelListCache:d,openclawModelLister:u,sessionSpawner:async(C,H,j,ee,ae,st)=>{if(!f)throw new Error("agentManager not ready");return f.spawnSessionDownstream(C,H,j,ee,ae,st)}}),p=new ea({paths:t,config:o,registry:x});f=p;let w,b,_=null,v={},I,A=null,T=null,R=null,E=new Vt;function P(C,H){return E.enqueue(()=>U(C,H))}function D(){T||(T=new Oa({isConnected:()=>a.isConnected()&&!(A?.isLivenessLost()??!1),forceReconnect:()=>R?P(R,{force:!0}):void 0,onFatal:C=>{if(process.env[As]==="1"){G.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:C});return}G.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:C}),process.exit(1)}})),T.start()}async function U(C,H){let j=C,ee=j?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let ae=rs(j.env),st=j.handshake_url,lt=j.frontier_url,Ft=og(j.env,st,lt);if(R=j,!H?.force&&w===ee&&b===Ft){let Be=await KI(t);return x.agents.size===0&&Be?(G.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Ma(t,p).catch(me=>G.warn("connect-noop auto-revive error (ignored)",{err:String(me)}))):G.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Qt=!!w&&w!==ee,mn=b!==void 0&&b!==Ft,qn=Qt||mn,mt=await bd({privatecode:ee,...st?{endpoint:st}:{},ppeOverride:ae});if(qn){G.warn("connect config switched, resetting agents",{pcChanged:Qt,envChanged:mn,previousPc:w?La(w):"",nextPc:La(ee)});for(let Be of[...x.agents.values()])await Be.dispose("connect config switch").catch(()=>{}),x.agents.delete(Be.agentId);x.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on connect config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new hi,"connect switch").catch(()=>{})}_=mt.deviceId,Ls({deviceId:_,pid:process.pid}),Zd({patToken:ee,env:j.env}).catch(Be=>G.warn("coze-cli setup error (ignored)",{err:String(Be)}));let wr=new Ss({handshake:mt,privatecode:ee,...lt?{urlOverride:lt}:{},ppeOverride:ae,getPatTokenForAgent:Be=>x.agents.get(Be)?.patToken});return await a.swap(wr,"connect"),w=ee,b=Ft,v=ae,I=st,j.mock_scenario!==void 0&&(x.setMockScenario(j.mock_scenario),G.info("mock scenario set",{scenario:j.mock_scenario})),A||(A=new os({core:x,getDeviceId:()=>_??"",onTickEnd:()=>J.retryPending().catch(Be=>G.warn("detailSync.retryPending failed (ignored)",{err:String(Be)})),onAuthFailures:ie})),A.start(),D(),qn&&Ma(t,p).catch(Be=>G.warn("post-connect-switch auto-revive error (ignored)",{err:String(Be)})),Is(ee,t).catch(Be=>G.warn("writePatToken after /connect failed (ignored)",{err:String(Be)})),G.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}x.registerExtension("_agent/create",async C=>p.createAgent(C.params)),x.registerExtension("_agent/health",async()=>({ok:!0}));let N={},K=new zo({agents:x.agents,modelListCache:d,openclawModelLister:u,paths:t,publishSkillToMarketplace:async C=>{let H=x.agents.get(C.agentId)?.patToken??w;if(!H)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Qp({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:I,ppeOverride:v})},disposeAndMarkDisconnected:async(C,H)=>{let j=x.agents.get(C);if(j){await p.cleanupOpenclawSessionProviders(j).catch(ae=>G.warn("cleanup openclaw providers failed (ignored)",{agentId:C,err:String(ae)})),j.framework==="hermes"&&j.deployType==="cloud"&&await Rd(C,t).catch(ae=>G.warn("cleanup hermes-home failed (ignored)",{agentId:C,err:String(ae)}));let ee=!0;try{await j.dispose(`disconnect: ${H}`)}catch(ae){ee=!1,G.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:C,err:String(ae)}),j.status="error"}ee&&(j.status="disconnected",x.unregister(C),x.disconnectedAgents.add(C))}else x.disconnectedAgents.add(C)},disposeForDelete:async(C,H)=>{let j=x.agents.get(C);j&&(await p.cleanupOpenclawSessionProviders(j).catch(ee=>G.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:C,err:String(ee)})),j.framework==="hermes"&&j.deployType==="cloud"&&await Rd(C,t).catch(ee=>G.warn("cleanup hermes-home during delete failed (ignored)",{agentId:C,err:String(ee)})),await j.dispose(`delete: ${H}`).catch(ee=>G.warn("dispose during delete failed (ignored)",{agentId:C,err:String(ee)})),x.unregister(C)),x.disconnectedAgents.delete(C)},detailSyncer:async C=>{if(!N.ref)throw new Error("agent-detail-sync not initialized yet");await N.ref.syncOne(C)},cleanupOpenclawProviders:async(C,H)=>{await p.cleanupOpenclawSessionProviders(C,H)},openclawRepair:async(C,H)=>{await p.openclawRepair(C,H)},hermesReset:async(C,H)=>{let j=await we(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:x.getMockScenario()})},isRuntimePendingPermission:C=>x.hasPendingPermissionFor(C)});x.registerExtension("_agent/listSkills",C=>K.listSkills(C.params)),x.registerExtension("_agent/addSkills",C=>K.addSkills(C.params)),x.registerExtension("_agent/removeSkills",C=>K.removeSkills(C.params)),x.registerExtension("_agent/publishSkill",C=>K.publishSkill(C.params)),x.registerExtension("_agent/getFileTree",C=>K.getFileTree(C.params)),x.registerExtension("_agent/getFileContent",C=>K.getFileContent(C.params)),x.registerExtension("_agent/update",C=>K.updateAgent(C.params)),x.registerExtension("_agent/disconnect",C=>K.disconnectAgent(C.params)),x.registerExtension("_agent/switchModel",C=>K.switchModel(C.params)),x.registerExtension("_agent/setConfigOption",C=>K.setConfigOption(C.params)),x.registerExtension("_agent/listAvailableModels",C=>K.listAvailableModels(C.params)),x.registerExtension("_agent/detail",C=>K.detail(C.params)),x.registerExtension("_agent/reset",C=>K.resetAgent(C.params)),x.registerExtension("_agent/repair",C=>K.repairAgent(C.params)),x.registerExtension("_agent/delete",C=>K.deleteAgent(C.params)),x.registerExtension("_agent/upgrade",C=>K.upgradeBridge(C.params));let J=new Hs({paths:t,handlers:K,agentManager:p,sendDetail:C=>x.sendRequest("_agent/detail",C)});N.ref=J;let ie=async C=>{await Promise.allSettled(C.map(async H=>{try{await K.disconnectAgent({agentId:H.agentId,reason:`auth_failure: code=${H.code} ${H.message}`}),G.info("agent disconnected due to auth failure from heartbeat response",{agentId:H.agentId,code:H.code,message:H.message})}catch(j){G.warn("disconnect during authFailure handling failed (ignored)",{agentId:H.agentId,err:String(j)})}}))};a.onConnect(({initial:C})=>{G.info("frontier upstream connected, triggering detail sync",{initial:C}),J.syncAll(C?"initial-connect":"reconnect").catch(H=>G.warn("detail sync top-level error (ignored)",{err:String(H)}))});let Y=new oa({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let C=x.getMockScenario();return{running:!0,pid:process.pid,nodeExecPath:process.execPath,nodeVersion:process.version,nodeArch:process.arch,spawnedBy:process.env[As]==="1"?"manual":"supervisor",agents:[...x.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...C?{mockScenario:C}:{}}}},{method:"POST",path:"/pair",handler:async C=>{let H=C,j=H?.privatecode,ee=H?.pairing_code;if(!j||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ae=rs(H.env),st=H.handshake_url,lt=H.frontier_url,Ft=og(H.env,st,lt),Qt=!!w&&w!==j,mn=b!==void 0&&b!==Ft,qn=Qt||mn,mt=await bd({privatecode:j,...st?{endpoint:st}:{},ppeOverride:ae});if(qn){G.warn("pair config switched, resetting agents",{pcChanged:Qt,envChanged:mn,previousPc:w?La(w):"",nextPc:La(j),previousEnvKey:b??"",nextEnvKey:Ft});for(let me of[...x.agents.values()])await me.dispose("pair config switch").catch(()=>{}),x.agents.delete(me.agentId);x.disconnectedAgents.size>0&&(G.info("clearing disconnectedAgents set on pair config switch",{count:x.disconnectedAgents.size}),x.disconnectedAgents.clear()),await a.swap(new hi,"pair switch").catch(()=>{})}_=mt.deviceId,Ls({deviceId:_,pid:process.pid}),Zd({patToken:j,env:H.env}).catch(me=>G.warn("coze-cli setup error (ignored)",{err:String(me)}));let wr=new Ss({handshake:mt,privatecode:j,...lt?{urlOverride:lt}:{},ppeOverride:ae,getPatTokenForAgent:me=>x.agents.get(me)?.patToken});await a.swap(wr,"pair");try{let me=new lr;o.frameworksCache=await me.detectAll(),await hs(o),G.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(me){G.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(me)})}let Be=Object.keys(o.frameworksCache??{});try{let me=await x.sendRequest("_agent/pair",{pairCode:ee,patToken:j,frameworks:Be,_meta:{cozeDeviceId:_}});G.info("_agent/pair ok",{pairResult:me}),w=j,b=Ft,v=ae,I=st,H.mock_scenario!==void 0&&(x.setMockScenario(H.mock_scenario),G.info("mock scenario set",{scenario:H.mock_scenario})),Is(j,t).catch(ft=>G.warn("writePatToken after /pair failed (ignored)",{err:String(ft)})),A||(A=new os({core:x,getDeviceId:()=>_??"",onTickEnd:()=>J.retryPending().catch(ft=>G.warn("detailSync.retryPending failed (ignored)",{err:String(ft)})),onAuthFailures:ie})),A.start(),D(),qn&&Ma(t,p).catch(ft=>G.warn("post-pair-switch auto-revive error (ignored)",{err:String(ft)}));let ce;return H.agent_id&&(ce=await VI(H.agent_id,t,p,ft=>x.sendRequest("_agent/detail",ft),j).catch(ft=>(G.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(ft)}),{ok:!1,agentId:H.agent_id??"",note:String(ft)}))),{ok:!0,note:"paired with cloud",...ce?{agent:ce}:{}}}catch(me){return G.error("_agent/pair failed",{err:String(me)}),{ok:!1,note:`pair failed: ${String(me)}`}}}},{method:"POST",path:"/connect",handler:C=>P(C)},{method:"POST",path:"/_agent/create",handler:async C=>{let H=C;return{ok:!0,result:await p.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(!w)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=H;return await(j.groupFile?hx:ux)(j,{core:x,patToken:w,handshakeBase:I,ppeOverride:v})}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 x.reloadAgents(H);return G.info("IPC /reload: recycled agent subprocesses",{agentId:H??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(G.info("IPC /shutdown received"),setImmediate(()=>{qe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:oe,token:le}=await Y.start();try{await tg(t.libEntry,t)}catch(C){G.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(C)})}await x.start(),JI({paths:t,core:x,agentManager:p,detectAll:async()=>(o.frameworksCache=await new lr().detectAll(),await hs(o),o.frameworksCache)}).catch(C=>G.warn("startup warmup error (ignored)",{err:String(C)})),xf().then(async()=>{let{probeAcpVersion:C}=await Promise.resolve().then(()=>(vn(),uf));for(let H of["claude-code","codex"]){let j=await C(H);j&&G.info("acp wrapper version",{framework:H,version:j})}}).catch(C=>G.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(C)}));let Ee=null,qe={port:oe,token:le,core:x,ipc:Y,shutdown(C){return Ee||(G.info("daemon shutdown",{reason:C}),Ee=(async()=>{A?.stop(),T?.stop(),await x.stop(C),await Y.stop(),await e.release()})(),Ee)}};for(let C of["SIGTERM","SIGINT"])process.on(C,()=>{qe.shutdown(C).then(()=>process.exit(0))});return process.on("exit",()=>Ah()),process.on("unhandledRejection",C=>{G.error("unhandledRejection",{reason:C instanceof Error?C.message:String(C),stack:C instanceof Error?C.stack:void 0})}),process.on("uncaughtException",C=>{G.error("uncaughtException (will exit, supervisor will restart)",{message:C.message,stack:C.stack,name:C.name});try{process.stderr.write(`FATAL uncaughtException: ${C.stack??C.message}
126
+ `)}catch{}process.exit(1)}),G.info("daemon ready",{port:oe,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),XI({cliSpawned:process.env[As]==="1",readPatToken:()=>Ca(t),connect:P}).catch(C=>G.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(C)})),qe}async function KI(t){return Bs(t).length>0}function La(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function og(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function $I(t,e){let n=Bs(t);if(n.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(tn(),Us));for(let a of n){await o(a,t).catch(d=>G.warn("enforceAgentConfigMode failed (ignored)",{agentId:a,err:String(d)}));try{let d=await i(a,t);d?.deletedAt?(e.disconnectedAgents.add(a),G.info("agent marked deleted on startup",{agentId:a,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(a),G.info("agent marked disconnected on startup",{agentId:a,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){G.warn("failed to load agent config on startup, skipping",{agentId:a,err:String(d)})}}}async function VI(t,e,n,i,o){let{loadAgentConfig:a}=await Promise.resolve().then(()=>(tn(),Us)),d=await a(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);G.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=cg(d),w={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(w),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}G.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let f=await i({_meta:{cozeAgentId:t}});if(!f.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 u={agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...o?{patToken:o}:{},...f.deployType?{_meta:{cozeDeployType:f.deployType}}:{}};await n.createAgent(u);let x=f.deployType==="cloud"&&f.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function JI(t){let e=t.logger??G;try{let n=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(n??{})})}catch(n){e.warn("framework detection failed (using cached)",{err:String(n)})}await $I(t.paths,t.core).catch(n=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(n)})),await Ma(t.paths,t.agentManager).catch(n=>e.warn("auto-revive top-level error (ignored)",{err:String(n)})),await ZI(t.paths).catch(n=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(n)}))}async function Ma(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(()=>(tn(),Us));G.info("auto-revive: scanning local agents on startup",{count:i.length});let a=0,d=0;for(let f of i){let u;try{u=await o(f,t)}catch(x){G.warn("auto-revive: load config failed (skipping)",{agentId:f,err:String(x)}),d+=1;continue}if(!u){d+=1;continue}if(u.deletedAt){G.info("auto-revive: skip deleted agent",{agentId:f,deletedAt:u.deletedAt}),d+=1;continue}if(u.disconnectedAt){G.info("auto-revive: skip disconnected agent",{agentId:f,disconnectedAt:u.disconnectedAt}),d+=1;continue}try{G.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:f,framework:u.framework});let x=cg(u);await e.createAgent({agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...x?{_meta:x}:{}},{revive:!0}),a+=1}catch(x){G.warn("auto-revive: createAgent failed (skipping)",{agentId:f,framework:u.framework,err:String(x)}),d+=1}}return G.info("auto-revive: done",{revived:a,skipped:d,total:i.length}),{revived:a,skipped:d,total:i.length}}async function ZI(t){let{readdir:e}=await import("node:fs/promises"),n;try{n=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(n.length===0)return{refreshed:0,total:0};let i=0;for(let o of n)try{(await xh(o,t)).status==="refreshed"&&(i+=1)}catch(a){G.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(a)})}return i>0&&G.info("builtin skills refresh on startup done",{refreshed:i,total:n.length}),{refreshed:i,total:n.length}}async function XI(t){let e=t.logger??G;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function cg(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Da();Pe();import{readFile as dg}from"node:fs/promises";var gn=class{paths;constructor(e){this.paths=e??Z()}async probe(e=1e3){let n=await Na(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:QI(i)}}}async request(e){let n=await Na(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 f=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}),u=await f.text();return{status:f.status,body:YI(u)}}finally{clearTimeout(d)}}};async function Na(t){try{let[e,n]=await Promise.all([dg(t.portFile,"utf8"),dg(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 YI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function QI(t){return t instanceof Error?t.message:String(t)}Wt();ne();vr();import{spawn as eA}from"node:child_process";import{userInfo as fg}from"node:os";var kl="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",tA=new Set(["bash","zsh","sh","dash","ksh"]),lg=Je("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),nA=2e3;function rA(t,e=kl){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 f=d.indexOf("=");f<=0||(a[d.slice(0,f)]=d.slice(f+1))}return a}function iA(){let t=(process.env.SHELL??"").trim()||(fg().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return tA.has(e)?t:null}function sA(t){return new Promise(e=>{let n=`printf '%s' '${kl}'; env; printf '%s' '${kl}'`,i;try{i=eA(t,["-ilc",n],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??fg().homedir}})}catch{e(null);return}let o="",a=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},f=p=>{a||(a=!0,clearTimeout(u),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{o+=p.toString("utf8")}),i.on("error",()=>f(null)),i.on("close",()=>f(o.length>0?o:null));let u=setTimeout(()=>d("SIGTERM"),lg),x=setTimeout(()=>{d("SIGKILL"),f(o.length>0?o:null)},lg+nA)})}async function Tl(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let n=iA();if(!n)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??sA)(n);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=rA(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Pe();function Hn(t,...e){let n=[],i;for(let o=0;o<t.length;o++){let a=t[o],d=!1;for(let f of e){if(a===f){i=t[o+1],o+=1,d=!0;break}if(a.startsWith(`${f}=`)){i=a.slice(f.length+1),d=!0;break}}d||n.push(a)}return{value:i,rest:n}}vn();import{chmod as oA,copyFile as ug,mkdir as xg,readFile as Ts,rename as hg,rm as Pl,stat as pg,writeFile as aA}from"node:fs/promises";import{homedir as x3}from"node:os";import{dirname as cA,join as Fe,resolve as Dl,sep as ks}from"node:path";import{fileURLToPath as dA}from"node:url";Wt();ne();Pe();function xi(t,e,n,i){at(t.bridgeLogsDir,e,"dist-install",n,i)}function gg(){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 lA(){return{darwin:{arm64:Fe("vendor","aarch64-apple-darwin","bin","codex"),x64:Fe("vendor","x86_64-apple-darwin","bin","codex")},linux:{arm64:Fe("vendor","aarch64-unknown-linux-musl","bin","codex"),x64:Fe("vendor","x86_64-unknown-linux-musl","bin","codex")},win32:{arm64:Fe("vendor","aarch64-pc-windows-msvc","bin","codex.exe"),x64:Fe("vendor","x86_64-pc-windows-msvc","bin","codex.exe")}}[process.platform]?.[process.arch]}function fA(t){let e=dA(t),n=cA(e),i=`${ks}src${ks}`;if(n.includes(i)||n.endsWith(`${ks}src${ks}cli`))return null;let o=Dl(n,"index.js"),a=Dl(n,"..","package.json");return{dist:o,pkgJson:a}}async function Ol(t={}){let e=t.paths??Z(),n=fA(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 v=JSON.parse(await Ts(o,"utf8"));a=v.version??"unknown",d=v.dependencies??{}}catch(v){throw xi(e,"error","cannot read source package.json",{err:String(v)}),new Error(`cannot read source package.json: ${String(v)}`,{cause:v})}let f=Ns.map(v=>({name:v,spec:d[v]??"latest"})),u=f.map(({name:v,spec:I})=>`${v}@${I}`),x=await ia(e.configFile)??{},p=x.libVersion,w=await Ts(e.libEntry).then(()=>!0).catch(()=>!1),b=p===a,_=await mg(e,f);if(b&&w&&_)return{kind:"already-current",libVersion:a};if(!b||!w){await xg(e.libDir,{recursive:!0}),await ug(i,e.libEntry),await ug(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Dl(e.libDir,"package.json"),I=`${JSON.stringify({type:"module"},null,2)}
128
+ `;await Ts(v,"utf8").catch(()=>null)!==I&&await aA(v,I)}return _||(t.installWrappers?await t.installWrappers(e,u):await xA(e,u,f)),x.libVersion=a,await hs(x,e.configFile),xi(e,"info","dist installed",{libEntry:e.libEntry,fromVersion:p,toVersion:a}),b&&w?{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 mg(t,e){for(let n of e){let i=Fe(t.libDir,"node_modules",...n.name.split("/"),"package.json"),o;try{o=JSON.parse(await Ts(i,"utf8"))}catch(d){return xi(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 xi(t,"debug","wrapper not ready: package.json \u7F3A version",{package:n.name,expected:n.spec,pkgJson:i}),!1;if(!uA(a,n.spec))return xi(t,"debug","wrapper not ready: installed version does not satisfy expected range",{package:n.name,installed:a,expected:n.spec}),!1}return!!await wg(Fe(t.libDir,"node_modules"))}function uA(t,e){let n=Cl(t);if(!n)return!0;let i=e.trim();if(!i||i==="*"||i==="latest")return!0;if(i.startsWith("^")){let a=Cl(i.slice(1));if(!a)return!0;if(Rl(n,a)<0)return!1;let d=hA(a);return Rl(n,d)<0}let o=Cl(i);return o?Rl(n,o)===0:!0}function hA(t){return t[0]>0?[t[0]+1,0,0]:t[1]>0?[0,t[1]+1,0]:[0,0,t[2]+1]}function Cl(t){let e=t.match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);return e?[Number(e[1]),Number(e[2]??0),Number(e[3]??0)]:null}function Rl(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 xA(t,e,n){await mA(t.installLock,async()=>{if(await mg(t,n))return;let i=Math.random().toString(36).slice(2,10),o=`${t.libDir}${ks}.staging-${process.pid}-${i}`,a=Fe(o,"node_modules"),d=Fe(t.libDir,"node_modules");try{await xg(o,{recursive:!0}),await pA(e,o),await gA(a);let f=`${d}.trash-${i}`;await hg(d,f).catch(()=>{}),await hg(a,d),await Pl(f,{recursive:!0,force:!0}).catch(()=>{}),xi(t,"info","wrapper closure installed",{liveNm:d,specs:e})}finally{await Pl(o,{recursive:!0,force:!0}).catch(()=>{})}})}function pA(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=dt("npm",n,{stdio:["ignore","pipe","pipe"]}),d="";a.stderr?.on("data",u=>{d.length<8192&&(d+=u.toString("utf8"))});let f=setTimeout(()=>a.kill("SIGKILL"),18e4);a.once("error",u=>{clearTimeout(f),o(new Error(`spawn npm failed: ${String(u)}`))}),a.once("close",u=>{clearTimeout(f),u===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${u}: ${d.trim().slice(0,2e3)}`))})})}async function gA(t){for(let e of Ns){let n=Fe(t,...e.split("/")),i=JSON.parse(await Ts(Fe(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=Fe(t,".bin",o),d=await pg(a);process.platform!=="win32"&&!(d.mode&73)&&await oA(a,d.mode|73).catch(()=>{})}if(!await wg(t)){let e=gg()??"<unsupported-platform>";throw new Error(`${e}: \u5F53\u524D\u5E73\u53F0 codex binary \u7F3A\u5931`)}}async function wg(t){let e=gg(),n=lA();if(!e||!n)return!0;let i=Fe(t,"@openai","codex"),o=Fe(t,...e.split("/")),a=[Fe(i,"package.json"),Fe(i,"bin","codex.js"),Fe(t,".bin",process.platform==="win32"?"codex.cmd":"codex"),Fe(o,"package.json"),Fe(o,n)];return(await Promise.all(a.map(f=>pg(f).then(u=>u.isFile()).catch(()=>!1)))).every(Boolean)}async function mA(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 Pl(t,{force:!0}).catch(()=>{})}}rc();ne();Pe();import{closeSync as yg,fstatSync as Eg,openSync as bg,readFileSync as wA,readSync as _A,readdirSync as yA,statSync as EA}from"node:fs";import{join as Fa}from"node:path";var bA=new Set(["debug","info","warn","error"]);function vg(t){let e=t,n=Hn(e,"--agent-id");e=n.rest;let i=Hn(e,"--date");e=i.rest;let o=Hn(e,"-n","--lines");e=o.rest;let a=Hn(e,"--level");e=a.rest;let d=Hn(e,"--grep");e=d.rest;let f=o.value===void 0?200:Number(o.value),u=Number.isInteger(f)&&f>=0?f:200,x=a.value&&bA.has(a.value)?a.value:void 0,p={lines:u,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 vA(t,e){return t.agentId?Fa(Oe(t.agentId,e).logs,Sr("agent",t.date)):Fa(e.bridgeLogsDir,Sr("bridge",t.date))}function SA(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function IA(t,e){let n;try{n=yA(t)}catch{return[]}let i=[];for(let o of n){let a=nc(o,e);if(!a)continue;let d=0;try{d=EA(Fa(t,o)).size}catch{}i.push({file:Fa(t,o),date:a,size:d})}return i.sort((o,a)=>a.date.localeCompare(o.date)),i}function Sg(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"&&!af(n,e.level))return!1}return!0}var _g={debug:"90",info:"36",warn:"33",error:"31"},AA=new Set(["ts","level","module","msg"]);function kA(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Ig(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let i=kA(n.ts),o=typeof n.level=="string"?n.level:"",a=o.toUpperCase().padEnd(5);e.color&&_g[o]&&(a=`\x1B[${_g[o]}m${a}\x1B[0m`);let d=typeof n.module=="string"?n.module:"",f=typeof n.msg=="string"?n.msg:"",u=Object.entries(n).filter(([x])=>!AA.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${a} ${d} ${f}${u}`}function TA(t,e,n){let a=wA(t,"utf8").split(`
129
+ `).filter(d=>d.length>0).filter(d=>Sg(d,{level:e.level,grep:e.grep}));for(let d of SA(a,e.lines))process.stdout.write(`${Ig(d,{raw:e.raw,color:n})}
130
+ `)}async function Ag(t,e){let n=e.paths??Z(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Oe(t.agentId,n).logs:n.bridgeLogsDir,f=t.agentId?"agent":"bridge",u=IA(d,f);if(u.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
131
+ `),1;for(let x of u)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
132
+ `);return 0}let o=t.date??jn(new Date),a=vA({agentId:t.agentId,date:o},n);try{TA(a,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${a}
133
133
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
134
134
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
135
- `),1}return t.follow&&await D2(a,t,i),0}var T2=500;function P2(t){try{let e=wg(t,"r");try{return mg(e).size}finally{gg(e)}}catch{return 0}}async function D2(t,e,n){let i=P2(t),s="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let u="";try{let h=wg(t,"r");try{let x=mg(h).size;if(x>i){let p=Buffer.allocUnsafe(x-i),w=_2(h,p,0,p.length,i);u=p.subarray(0,w).toString("utf8"),i+=w}}finally{gg(h)}}catch{}if(u){let h=(s+u).split(`
136
- `);s=h.pop()??"";for(let x of h)x.length>0&&yg(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${bg(x,{raw:e.raw,color:n})}
137
- `)}await new Promise(h=>setTimeout(h,T2))}}finally{process.off("SIGINT",d)}}import{basename as R2,resolve as O2}from"node:path";Ce();var L2=9e4,M2={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,CAPABILITY_UNSUPPORTED:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1,SKILL_NOT_FOUND:1,SKILL_ZIP_TOO_LARGE:1};function N2(t){return M2[t]??1}async function Eg(t,e={}){let n=e.paths??Z();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
135
+ `),1}return t.follow&&await PA(a,t,i),0}var CA=500;function RA(t){try{let e=bg(t,"r");try{return Eg(e).size}finally{yg(e)}}catch{return 0}}async function PA(t,e,n){let i=RA(t),o="",a=!1,d=()=>{a=!0};process.on("SIGINT",d);try{for(;!a;){let f="";try{let u=bg(t,"r");try{let x=Eg(u).size;if(x>i){let p=Buffer.allocUnsafe(x-i),w=_A(u,p,0,p.length,i);f=p.subarray(0,w).toString("utf8"),i+=w}}finally{yg(u)}}catch{}if(f){let u=(o+f).split(`
136
+ `);o=u.pop()??"";for(let x of u)x.length>0&&Sg(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${Ig(x,{raw:e.raw,color:n})}
137
+ `)}await new Promise(u=>setTimeout(u,CA))}}finally{process.off("SIGINT",d)}}import{basename as DA,resolve as OA}from"node:path";Pe();var LA=9e4,MA={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,CAPABILITY_UNSUPPORTED:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1,SKILL_NOT_FOUND:1,SKILL_ZIP_TOO_LARGE:1};function NA(t){return MA[t]??1}async function kg(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
138
  `),4;if(t.groupFile&&!t.mimeType)return process.stderr.write(`Error: --group-file requires --mime <mimeType> (e.g. application/pdf, image/png). No local file is read in group-file mode, mime cannot be auto-detected.
139
- `),3;let i=await Pa(n).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${n.portFile} / ${n.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
140
- `),4;let s={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:O2(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 B2(i,"/agent/send",s,L2)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
139
+ `),3;let i=await Na(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:OA(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 FA(i,"/agent/send",o,LA)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
141
141
  `),4}if(!a.ok)return process.stderr.write(`Error: ${a.code}: ${a.message}
142
- `),N2(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
143
- `);else{let d=t.name??R2(s.path);if(t.groupFile){let u=a.uri.length>60?`${a.uri.slice(0,57)}...`:a.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
144
- `)}else process.stdout.write(`Sent ${t.kind} ${d} (${F2(a.bytes)})
145
- `)}return 0}async function B2(t,e,n,i){let s=new AbortController,a=setTimeout(()=>s.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(n),signal:s.signal}),u=await d.text(),h=u?JSON.parse(u):null;return h&&typeof h=="object"&&"ok"in h?h:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(a)}}function F2(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Og=G("cli");function We(t,e){let{value:n,rest:i}=Fn(t,e);return{value:n,rest:i}}function Ba(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
146
- `)}function c1(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}=We(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 d1(e.slice(1));if(e[0]==="log")return{mode:"log",..._g(e.slice(1))};if(e[0]==="connect")return l1(e.slice(1));if(e.includes("--status"))return Ba("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ba("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ba("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ba("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:i,rest:s}=We(n,"--pat-token");n=s;let{value:a,rest:d}=We(n,"--pair-code");n=d;let{value:u,rest:h}=We(n,"--env");n=h;let{value:x,rest:p}=We(n,"--handshake-url");n=p;let{value:w,rest:b}=We(n,"--frontier-url");n=b;let{value:y,rest:v}=We(n,"--mock-scenario");n=v;let{value:I}=We(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let C={mode:"pair",privatecode:i,pairingCode:a};return u&&(C.env=u),x&&(C.handshakeUrl=x),w&&(C.frontierUrl=w),y&&(C.mockScenario=y),I&&(C.agentId=I),A&&(C.skipRebuildEnv=!0),C}function d1(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:s,rest:a}=We(i,"--caption");i=a;let{value:d,rest:u}=We(i,"--name");i=u;let{value:h,rest:x}=We(i,"--agent-id");i=x;let{value:p,rest:w}=We(i,"--session-id");i=w;let{value:b,rest:y}=We(i,"--mime");i=y;let v=i.includes("--group-file");i=i.filter(C=>C!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return s&&(A.caption=s),d&&(A.name=d),h&&(A.agentId=h),p&&(A.sessionId=p),v&&(A.groupFile=!0),b&&(A.mimeType=b),A}function l1(t){let e=t,{value:n,rest:i}=We(e,"--pat-token");e=i;let{value:s,rest:a}=We(e,"--env");e=a;let{value:d,rest:u}=We(e,"--handshake-url");e=u;let{value:h,rest:x}=We(e,"--frontier-url");e=x;let{value:p,rest:w}=We(e,"--mock-scenario");e=w;let b=e.includes("--skip-rebuild-env"),y={mode:"connect"};return n&&(y.privatecode=n),s&&(y.env=s),d&&(y.handshakeUrl=d),h&&(y.frontierUrl=h),p&&(y.mockScenario=p),b&&(y.skipRebuildEnv=!0),y}var u1=`
142
+ `),NA(a.code);if(t.json)process.stdout.write(`${JSON.stringify(a)}
143
+ `);else{let d=t.name??DA(o.path);if(t.groupFile){let f=a.uri.length>60?`${a.uri.slice(0,57)}...`:a.uri;process.stdout.write(`Sent group file ${d} (uri=${f})
144
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${BA(a.bytes)})
145
+ `)}return 0}async function FA(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}),f=await d.text(),u=f?JSON.parse(f):null;return u&&typeof u=="object"&&"ok"in u?u:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${f.slice(0,200)}`}}finally{clearTimeout(a)}}function BA(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Fg=q("cli");function Ve(t,e){let{value:n,rest:i}=Hn(t,e);return{value:n,rest:i}}function Ga(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
146
+ `)}function ck(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:R}=Ve(e.slice(1),"--agent-id");return R?{mode:"reload",agentId:R}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return dk(e.slice(1));if(e[0]==="log")return{mode:"log",...vg(e.slice(1))};if(e[0]==="connect")return lk(e.slice(1));if(e.includes("--status"))return Ga("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Ga("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return Ga("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Ga("--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}=Ve(n,"--pat-token");n=o;let{value:a,rest:d}=Ve(n,"--pair-code");n=d;let{value:f,rest:u}=Ve(n,"--env");n=u;let{value:x,rest:p}=Ve(n,"--handshake-url");n=p;let{value:w,rest:b}=Ve(n,"--frontier-url");n=b;let{value:_,rest:v}=Ve(n,"--mock-scenario");n=v;let{value:I}=Ve(n,"--agent-id"),A=n.includes("--skip-rebuild-env");if(!i||!a)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:a};return f&&(T.env=f),x&&(T.handshakeUrl=x),w&&(T.frontierUrl=w),_&&(T.mockScenario=_),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function dk(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}=Ve(i,"--caption");i=a;let{value:d,rest:f}=Ve(i,"--name");i=f;let{value:u,rest:x}=Ve(i,"--agent-id");i=x;let{value:p,rest:w}=Ve(i,"--session-id");i=w;let{value:b,rest:_}=Ve(i,"--mime");i=_;let v=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:n,json:I};return o&&(A.caption=o),d&&(A.name=d),u&&(A.agentId=u),p&&(A.sessionId=p),v&&(A.groupFile=!0),b&&(A.mimeType=b),A}function lk(t){let e=t,{value:n,rest:i}=Ve(e,"--pat-token");e=i;let{value:o,rest:a}=Ve(e,"--env");e=a;let{value:d,rest:f}=Ve(e,"--handshake-url");e=f;let{value:u,rest:x}=Ve(e,"--frontier-url");e=x;let{value:p,rest:w}=Ve(e,"--mock-scenario");e=w;let b=e.includes("--skip-rebuild-env"),_={mode:"connect"};return n&&(_.privatecode=n),o&&(_.env=o),d&&(_.handshakeUrl=d),u&&(_.frontierUrl=u),p&&(_.mockScenario=p),b&&(_.skipRebuildEnv=!0),_}var fk=`
147
147
  coze-bridge - local bridge daemon for cloud Agent Service
148
148
 
149
149
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -224,52 +224,52 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
224
224
 
225
225
  Internal:
226
226
  <node> <entry> --daemon daemon mode (OS supervisor only)
227
- `.trimStart();async function Lg(t=process.argv,e={}){let n=c1(t);switch(n.mode){case"help":return process.stdout.write(u1),0;case"version":return process.stdout.write(`${jt}
228
- `),0;case"daemon":{try{await rg()}catch(i){return Og.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return f1(e);case"stop":return Ng(e);case"reload":return p1(n.agentId,e);case"log":return vg(n,e);case"update":return h1(e);case"purge":return m1(e);case"service-install":return w1(e);case"service-uninstall":return _1(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),y1(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),b1(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 Mg(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 f1(t){let e=t.paths??Z(),n=new pn(e),i=await n.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
229
- `),1;if(i.kind==="stale")return await Mg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
230
- `),1;let s=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
231
- ${JSON.stringify(s.body,null,2)}
232
- `),0}async function Ng(t){let e=t.paths??Z(),n=new pn(e),i=t.daemonSweep??(async()=>{let h=Eh();return await Sh(h),h}),s=async()=>{t.skipProcessKill||await i(e)},a=await Is(t),d=!1;if(a)try{await a.uninstall(),d=!0}catch(h){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(h)}
233
- `)}let u=await n.probe();if(u.kind==="not-running")return await s(),process.stdout.write(d?`coze-bridge: stopped
227
+ `.trimStart();async function Bg(t=process.argv,e={}){let n=ck(t);switch(n.mode){case"help":return process.stdout.write(fk),0;case"version":return process.stdout.write(`${Kt}
228
+ `),0;case"daemon":{try{await ag()}catch(i){return Fg.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return uk(e);case"stop":return Ug(e);case"reload":return pk(n.agentId,e);case"log":return Ag(n,e);case"update":return hk(e);case"purge":return mk(e);case"service-install":return wk(e);case"service-uninstall":return _k(e);case"pair":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),yk(n.privatecode,n.pairingCode,e,i,n.agentId,n.skipRebuildEnv)}case"connect":{let i={};return n.env&&(i.env=n.env),n.handshakeUrl&&(i.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(i.frontierUrl=n.frontierUrl),n.mockScenario&&(i.mockScenario=n.mockScenario),Ek(n.privatecode,e,i,n.skipRebuildEnv)}case"send":return kg({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 zg(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function uk(t){let e=t.paths??Z(),n=new gn(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 zg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
230
+ `),1;let o=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
231
+ ${JSON.stringify(o.body,null,2)}
232
+ `),0}async function Ug(t){let e=t.paths??Z(),n=new gn(e),i=t.daemonSweep??(async()=>{let u=kh();return await Th(u),u}),o=async()=>{t.skipProcessKill||await i(e)},a=await Rs(t),d=!1;if(a)try{await a.uninstall(),d=!0}catch(u){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(u)}
233
+ `)}let f=await n.probe();if(f.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
234
234
  `:`coze-bridge: not running
235
- `),0;if(u.kind==="stale")return await Mg(e),await s(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
236
- `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await s(),process.stdout.write(`coze-bridge: stopped
237
- `),0}catch(h){return(await n.probe()).kind!=="connected"?(await s(),process.stdout.write(`coze-bridge: stopped
238
- `),0):(await s(),process.stdout.write(`coze-bridge: stop failed: ${String(h)}
239
- `),1)}}async function h1(t){return await Ng(t),(t.spawnNpx??x1)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function x1(t){return new Promise(e=>{let n=dt("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 p1(t,e){let n=new pn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
241
- `),1;try{let s=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(s.status===200&&s.body?.ok){let a=s.body.recycled??[];return t&&a.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
235
+ `),0;if(f.kind==="stale")return await zg(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
236
+ `),0;try{return await n.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
237
+ `),0}catch(u){return(await n.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
238
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(u)}
239
+ `),1)}}async function hk(t){return await Ug(t),(t.spawnNpx??xk)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function xk(t){return new Promise(e=>{let n=dt("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 pk(t,e){let n=new gn(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
241
+ `),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
242
  `):process.stdout.write(`coze-bridge: reloaded ${a.length} agent(s): ${a.join(", ")||"(none)"}
243
- `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(s.body)}
244
- `),1}catch(s){return process.stderr.write(`coze-bridge: reload failed: ${String(s)}
245
- `),1}}async function Is(t){if(t.supervisor){let a=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:a.platform,install:u=>a.install(d,u),uninstall:()=>a.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Pg(),Tg)),i=e(),s=n();return{platform:i.platform,install:a=>i.install(s,a),uninstall:()=>i.uninstall(s)}}async function Bg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,s=t.sleep??v1,a=t.paths??Z();if(n.kind==="connected"){if(!g1(n.body))return n;at(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(h=>at(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(h)})),await Rg(a.pidFile,s)}let d=t.spawnDaemon??tg,u=await Is(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let h=await Dg(e,i,s);if(h.kind==="connected")return h;at(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(h){at(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(h)})}at(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 Rg(a.pidFile,s)}else u&&await u.install({activate:!1}).catch(h=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(h)}
243
+ `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
244
+ `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
245
+ `),1}}async function Rs(t){if(t.supervisor){let a=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:a.platform,install:f=>a.install(d,f),uninstall:()=>a.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Lg(),Og)),i=e(),o=n();return{platform:i.platform,install:a=>i.install(o,a),uninstall:()=>i.uninstall(o)}}async function Hg(t,e){let n=await e.probe(),i=t.waitTimeoutMs??15e3,o=t.sleep??bk,a=t.paths??Z();if(n.kind==="connected"){if(!gk(n.body))return n;at(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(u=>at(a.bridgeLogsDir,"warn","cli","restart for Node drift: shutdown failed",{err:String(u)})),await Ng(a.pidFile,o)}let d=t.spawnDaemon??sg,f=await Rs(t);if(f&&(f.platform==="darwin"||f.platform==="linux")){try{await f.install({activate:!0});let u=await Mg(e,i,o);if(u.kind==="connected")return u;at(a.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(u){at(a.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(u)})}at(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:f.platform}),await f.uninstall().catch(()=>{}),await Ng(a.pidFile,o)}else f&&await f.install({activate:!1}).catch(u=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(u)}
246
246
  `));return process.stdout.write(`coze-bridge: starting daemon...
247
- `),await d({paths:t.paths}),Dg(e,i,s)}function g1(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 m1(t){let e=new pn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
247
+ `),await d({paths:t.paths}),Mg(e,i,o)}function gk(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 mk(t){let e=new gn(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
248
248
  `);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 Is(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
249
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await Rs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
250
250
  `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
251
- `)}let s=t.paths??Z(),{rm:a}=await import("node:fs/promises");try{await a(s.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${s.bridgeRoot}
251
+ `)}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
252
  `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
253
253
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
254
- `),0}async function w1(t){let e=await Is(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
254
+ `),0}async function wk(t){let e=await Rs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
255
255
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
256
256
  `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
257
- `),1}}async function _1(t){let e=await Is(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
257
+ `),1}}async function _k(t){let e=await Rs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
258
258
  `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
259
- `),1}}async function Fg(t,e,n){if(e)return at(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(at(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(at(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
260
- `),at(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function y1(t,e,n,i={},s,a){let d=new pn(n.paths),u=n.paths??Z(),h=await Fg(u,a,n.reconstructEnv??El);if(await gd(u,h).catch(w=>at(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!n.skipDistInstall){let w=await Cl({paths:n.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
261
- `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
262
- `)}let x=await Bg(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
263
- `),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),s&&(p.agent_id=s);try{let w=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let b=w.body.agent;return b&&!b.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${b.agentId}): ${b.note}
259
+ `),1}}async function qg(t,e,n){if(e)return at(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await n();return i.kind==="ok"?(at(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(at(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
260
+ `),at(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function yk(t,e,n,i={},o,a){let d=new gn(n.paths),f=n.paths??Z(),u=await qg(f,a,n.reconstructEnv??Tl);if(await Ed(f,u).catch(w=>at(f.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!n.skipDistInstall){let w=await Ol({paths:n.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
261
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
262
+ `)}let x=await Hg(n,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
263
+ `),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let w=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(w.status===200&&w.body?.ok){let b=w.body.agent;return b&&!b.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${b.agentId}): ${b.note}
264
264
  `),1):(process.stdout.write(`\u5DF2\u914D\u5BF9\u8FDE\u63A5\u5B8C\u6210\uFF0C\u8BF7\u8FD4\u56DE\u5230 coze \u5E73\u53F0\u4E0A\u70B9\u51FB "\u6211\u5DF2\u6267\u884C"
265
265
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
266
266
  `),1}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
267
- `),1}}async function b1(t,e,n={},i){let s=e.paths??Z(),a=t??await Ea(s);if(!a)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new pn(e.paths),u=await Fg(s,i,e.reconstructEnv??El);if(await gd(s,u).catch(p=>at(s.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await Cl({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
267
+ `),1}}async function Ek(t,e,n={},i){let o=e.paths??Z(),a=t??await Ca(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 gn(e.paths),f=await qg(o,i,e.reconstructEnv??Tl);if(await Ed(o,f).catch(p=>at(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await Ol({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
268
268
  `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(b=>setTimeout(b,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
269
- `)}let h=await Bg(e,d);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
269
+ `)}let u=await Hg(e,d);if(u.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${u.kind}
270
270
  `),1;let x={privatecode:a};n.env&&(x.env=n.env),n.handshakeUrl&&(x.handshake_url=n.handshakeUrl),n.frontierUrl&&(x.frontier_url=n.frontierUrl),n.mockScenario&&(x.mock_scenario=n.mockScenario);try{let p=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return p.status===200&&p.body?.ok?(process.stdout.write(`coze-bridge: connected (${p.body.note??"ok"})
271
- `),t!==void 0&&await ys(a,s).catch(w=>Og.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
271
+ `),t!==void 0&&await Is(a,o).catch(w=>Fg.warn("writePatToken after connect failed (ignored)",{err:String(w)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
272
272
  `),1)}catch(p){return process.stderr.write(`coze-bridge: connect failed: ${String(p)}
273
- `),1}}async function Dg(t,e,n){let i=Date.now()+e;for(;Date.now()<i;){let s=await t.probe(500);if(s.kind==="connected")return s;await n(200)}return t.probe(500)}async function Rg(t,e,n=60,i=200){let{readFile:s}=await import("node:fs/promises");for(let a=0;a<n;a++){let d;try{d=await s(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!ss(u))return;await e(i)}}function v1(t){return new Promise(e=>setTimeout(e,t))}ne();function E1(t){let e=/^v?(\d+)/.exec(t.trim());return e&&Number(e[1])<22?"fatal":"ok"}function zg(t=process.versions.node,e=i=>{process.stderr.write(i)},n=i=>process.exit(i)){if(E1(t)==="ok")return;let s=t.replace(/^v/,"");e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${s} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v22.0.0)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
274
- `),n(1)}zg();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Ql("warn");Lg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
273
+ `),1}}async function Mg(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 Ng(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 f=Number.parseInt(d.trim(),10);if(!Number.isFinite(f)||f<=0||!ls(f))return;await e(i)}}function bk(t){return new Promise(e=>setTimeout(e,t))}ne();function vk(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(vk(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&&sf("warn");Bg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
275
275
  `),process.exit(1)});